{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceType":"competition","sourceId":4117,"databundleVersionId":46665}],"dockerImageVersionId":31328,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport subprocess\nimport numpy as np\nfrom PIL import Image\nimport shutil\n\n# --- CẤU HÌNH ĐỢT CHẠY ---\nBATCH_SIZE = 2000\nBATCH_NUMBER = 4# <--- CHỈ CẦN THAY ĐỔI SỐ NÀY MỖI LẦN CHẠY TIẾP THEO\n\narchive_path = '/kaggle/input/competitions/malware-classification/test.7z'\noutput_dir = f'/kaggle/working/train_rgb_batch_{BATCH_NUMBER}'\ntemp_dir = f'/kaggle/working/temp_rgb_{BATCH_NUMBER}'\n\nif not os.path.exists(output_dir): os.makedirs(output_dir)\nif not os.path.exists(temp_dir): os.makedirs(temp_dir)\n\n# --- HÀM TẠO ẢNH RGB (GIỮ NGUYÊN LOGIC ĐỀ XUẤT 1) ---\ndef create_rgb_opcode_image(file_path, size=(128, 128)):\n    red_ops = {'mov', 'push', 'pop', 'lea'}\n    green_ops = {'add', 'sub', 'mul', 'div', 'xor', 'and', 'or'}\n    blue_ops = {'call', 'jmp', 'ret', 'int', 'jnz', 'jz', 'cmp'}\n    pixels = []\n    try:\n        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:\n            for line in f:\n                if len(pixels) >= size[0] * size[1]: break\n                line_lower = line.lower()\n                r, g, b = 0, 0, 0\n                if any(op in line_lower for op in red_ops): r = 255\n                if any(op in line_lower for op in green_ops): g = 255\n                if any(op in line_lower for op in blue_ops): b = 255\n                if r == 0 and g == 0 and b == 0:\n                    first_byte = ord(line[0]) if len(line) > 0 else 0\n                    r = g = b = first_byte % 64\n                pixels.append([r, g, b])\n        while len(pixels) < size[0] * size[1]: pixels.append([0, 0, 0])\n        img_array = np.array(pixels[:size[0]*size[1]], dtype=np.uint8).reshape((size[1], size[0], 3))\n        return Image.fromarray(img_array)\n    except: return None\n\n# --- QUY TRÌNH CHIA ĐỢT CHÍNH XÁC ---\nprint(\"Đang quét toàn bộ danh sách file từ tệp nén...\")\nlist_cmd = f'7z l {archive_path}'\nresult = subprocess.run(list_cmd.split(), capture_output=True, text=True)\n# Sắp xếp danh sách file để đảm bảo thứ tự luôn cố định qua mỗi lần chạy\nasm_files = sorted([line.split()[-1] for line in result.stdout.splitlines() if '.asm' in line])\n\ntotal_files = len(asm_files)\nstart_idx = BATCH_NUMBER * BATCH_SIZE\nend_idx = min(start_idx + BATCH_SIZE, total_files)\n\ncurrent_batch = asm_files[start_idx : end_idx]\n\nprint(f\"--- THÔNG TIN ĐỢT CHẠY ---\")\nprint(f\"Tổng số file trong dataset: {total_files}\")\nprint(f\"Đang xử lý BATCH số: {BATCH_NUMBER}\")\nprint(f\"Phạm vi: File thứ {start_idx} đến file thứ {end_idx - 1}\")\nprint(f\"Số lượng file thực tế đợt này: {len(current_batch)}\")\nprint(f\"---------------------------\")\n\nif len(current_batch) == 0:\n    print(\"Ủa ông ơi, Batch này không có file nào hết. Chắc ông chạy hết dataset rồi!\")\nelse:\n    for i, fname in enumerate(current_batch):\n        try:\n            extract_cmd = f'7z e {archive_path} -o{temp_dir} {fname} -y'\n            subprocess.run(extract_cmd.split(), capture_output=True)\n            \n            full_path = os.path.join(temp_dir, os.path.basename(fname))\n            if os.path.exists(full_path):\n                img = create_rgb_opcode_image(full_path)\n                if img:\n                    img.save(os.path.join(output_dir, os.path.basename(fname).replace('.asm', '.png')))\n                os.remove(full_path)\n            \n            if (i+1) % 100 == 0:\n                print(f\"Tiến độ Batch {BATCH_NUMBER}: {i+1}/{len(current_batch)}\")\n        except Exception as e:\n            print(f\"Lỗi tại {fname}: {e}\")\n\n    # Nén ZIP\n    zip_path = f'/kaggle/working/malware_rgb_batch_{BATCH_NUMBER}'\n    shutil.make_archive(zip_path, 'zip', output_dir)\n    shutil.rmtree(output_dir)\n    shutil.rmtree(temp_dir)\n    print(f\"\\n--- XONG BATCH {BATCH_NUMBER}! Tải file .zip về máy đi ông! ---\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-04-08T06:30:51.744906Z","iopub.execute_input":"2026-04-08T06:30:51.745356Z","iopub.status.idle":"2026-04-08T08:44:19.141302Z","shell.execute_reply.started":"2026-04-08T06:30:51.745322Z","shell.execute_reply":"2026-04-08T08:44:19.140452Z"}},"outputs":[],"execution_count":null}]}