| import json |
| import shutil |
| from pathlib import Path |
| import sys |
|
|
| def filter_jsonl_and_extract_images(): |
| """ |
| 讀取一個JSONL文件,篩選出 'optimal_path' 不為空的記錄, |
| 保存為新JSONL文件,並將對應的圖片複製到新文件夾。 |
| """ |
| |
| |
| INPUT_JSONL_FILE = "/home/wangxingjian/data/metaphor/hummus/hummus_to_del.jsonl" |
|
|
| |
| SOURCE_IMAGE_DIR = Path("/home/wangxingjian/data/metaphor/hummus/images") |
|
|
| |
| OUTPUT_JSONL_FILE = "/home/wangxingjian/data/metaphor/hummus/hummus_dataset.jsonl" |
|
|
| |
| OUTPUT_IMAGE_DIR = Path("/home/wangxingjian/data/metaphor/hummus/filtered_images") |
| |
| |
|
|
| |
| input_jsonl_path = Path(INPUT_JSONL_FILE) |
| if not input_jsonl_path.exists(): |
| print(f"❌ 錯誤: 找不到輸入文件 '{INPUT_JSONL_FILE}'。") |
| return |
| if not SOURCE_IMAGE_DIR.is_dir(): |
| print(f"❌ 錯誤: 找不到源圖片文件夾 '{SOURCE_IMAGE_DIR}'。") |
| return |
|
|
| |
| OUTPUT_IMAGE_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| kept_count = 0 |
| deleted_count = 0 |
| copied_count = 0 |
| error_count = 0 |
| line_count = 0 |
|
|
| print(f"🚀 開始處理文件 '{input_jsonl_path}'...") |
| print(f"源圖片位於: '{SOURCE_IMAGE_DIR}'") |
| |
| try: |
| with open(input_jsonl_path, 'r', encoding='utf-8') as infile, \ |
| open(OUTPUT_JSONL_FILE, 'w', encoding='utf-8') as outfile: |
| |
| for line in infile: |
| line_count += 1 |
| try: |
| data = json.loads(line) |
| |
| |
| optimal_path_value = data.get("extra_info", {}).get("optimal_path") |
|
|
| if optimal_path_value: |
| |
| outfile.write(line) |
| kept_count += 1 |
|
|
| |
| image_filename = data.get("image", {}).get("path") |
| if image_filename: |
| source_image_path = SOURCE_IMAGE_DIR / image_filename |
| dest_image_path = OUTPUT_IMAGE_DIR / image_filename |
| |
| if source_image_path.exists(): |
| shutil.copy2(source_image_path, dest_image_path) |
| copied_count += 1 |
| else: |
| print(f"⚠️ 警告: 找不到源圖片 '{source_image_path}',無法複製。") |
| error_count += 1 |
| else: |
| print(f"⚠️ 警告: 第 {line_count} 行記錄缺少 'image.path' 信息,無法複製圖片。") |
| error_count += 1 |
| else: |
| |
| deleted_count += 1 |
| |
| except json.JSONDecodeError: |
| print(f"⚠️ 警告: 第 {line_count} 行不是有效的JSON格式,已跳過。") |
| deleted_count += 1 |
|
|
| print("\n--- ✨ 處理完成 ✨ ---") |
| print(f"總共處理了 {line_count} 行數據。") |
| print(f"✅ 保留的記錄: {kept_count} 行 (已保存至 '{OUTPUT_JSONL_FILE}')") |
| print(f"🗑️ 刪除的記錄 (路徑為空): {deleted_count} 行") |
| print(f"🖼️ 成功複製的圖片: {copied_count} 張 (已保存至 '{OUTPUT_IMAGE_DIR}')") |
| if error_count > 0: |
| print(f"❗ 處理期間出現錯誤/警告: {error_count} 次 (詳見上方日誌)") |
| print("--------------------------") |
|
|
| except Exception as e: |
| print(f"❌ 處理過程中發生未知錯誤: {e}") |
|
|
| if __name__ == '__main__': |
| filter_jsonl_and_extract_images() |