{"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# --- 1. CẤU HÌNH ĐỢT CHẠY ---\nBATCH_SIZE = 2000  # Mỗi lần xử lý 2000 file\nBATCH_NUMBER =  4  # <--- THAY ĐỔI SỐ NÀY (0, 1, 2, 3, 4, 5) ĐỂ CHẠY CÁC ĐỢT TIẾP THEO\n\narchive_path = '/kaggle/input/competitions/malware-classification/test.7z'\noutput_dir = f'/kaggle/working/train_images_gray_batch_{BATCH_NUMBER}'\ntemp_dir = f'/kaggle/working/temp_asm_{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# --- 2. HÀM TẠO ẢNH BASELINE (GRAYSCALE) ---\ndef create_baseline_image(file_path, size=(128, 128)):\n    try:\n        with open(file_path, 'rb') as f:\n            data = np.frombuffer(f.read(), dtype=np.uint8)\n        \n        if len(data) == 0: return None\n        \n        # Tạo ma trận vuông từ dữ liệu gốc\n        side = int(len(data)**0.5)\n        img_array = data[:side*side].reshape((side, side))\n        \n        # Chuyển thành ảnh và resize về chuẩn\n        img = Image.fromarray(img_array)\n        return img.resize(size, Image.BILINEAR)\n    except Exception as e:\n        return None\n\n# --- 3. QUY TRÌNH CHIA ĐỢT ---\nprint(\"Đang quét danh sách file .asm trong tệp nén...\")\nlist_cmd = f'7z l {archive_path}'\nresult = subprocess.run(list_cmd.split(), capture_output=True, text=True)\n\n# Sắp xếp để đảm bảo thứ tự file luôn giống nhau giữa các 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)\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\n# --- 4. XỬ LÝ CHÍNH ---\nif len(current_batch) == 0:\n    print(\"Hết file rồi ông ơi, kiểm tra lại BATCH_NUMBER nhe!\")\nelse:\n    for i, fname in enumerate(current_batch):\n        try:\n            # Giải nén từng file ra temp\n            extract_cmd = f'7z e {archive_path} -o{temp_dir} {fname} -y'\n            subprocess.run(extract_cmd.split(), capture_output=True)\n            \n            base_name = os.path.basename(fname)\n            full_temp_path = os.path.join(temp_dir, base_name)\n            \n            if os.path.exists(full_temp_path):\n                # Tạo ảnh Baseline (Grayscale)\n                gray_img = create_baseline_image(full_temp_path)\n                \n                if gray_img:\n                    save_path = os.path.join(output_dir, base_name.replace('.asm', '.png'))\n                    gray_img.save(save_path)\n                \n                # Xóa file .asm ngay lập tức để tiết kiệm bộ nhớ\n                os.remove(full_temp_path)\n                \n            if (i+1) % 100 == 0:\n                print(f\"Tiến độ Batch {BATCH_NUMBER}: {i+1}/{len(current_batch)} file.\")\n                \n        except Exception as e:\n            print(f\"Lỗi tại {fname}: {e}\")\n\n    # --- 5. ĐÓNG GÓI ---\n    zip_name = f'/kaggle/working/malware_gray_batch_{BATCH_NUMBER}'\n    print(f\"Đang nén Batch {BATCH_NUMBER} thành file ZIP...\")\n    shutil.make_archive(zip_name, 'zip', output_dir)\n    \n    # Dọn dẹp folder sau khi nén\n    shutil.rmtree(output_dir)\n    shutil.rmtree(temp_dir)\n    \n    print(f\"--- XONG BATCH {BATCH_NUMBER}! ---\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-04-12T03:46:35.902383Z","iopub.execute_input":"2026-04-12T03:46:35.902706Z","iopub.status.idle":"2026-04-12T05:44:19.191272Z","shell.execute_reply.started":"2026-04-12T03:46:35.902668Z","shell.execute_reply":"2026-04-12T05:44:19.190410Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}