Sakigo's picture
Add files using upload-large-folder tool
08ad0fa verified
Raw
History Blame Contribute Delete
4.33 kB
import json
import shutil
from pathlib import Path
import sys
def filter_jsonl_and_extract_images():
"""
讀取一個JSONL文件,篩選出 'optimal_path' 不為空的記錄,
保存為新JSONL文件,並將對應的圖片複製到新文件夾。
"""
# --- 配置區 ---
# 1. 指定您的輸入JSONL文件名
INPUT_JSONL_FILE = "/home/wangxingjian/data/metaphor/hummus/hummus_to_del.jsonl" # ⚠️ 請修改為您的JSONL文件名
# 2. 指定存放所有原始圖片的源文件夾
SOURCE_IMAGE_DIR = Path("/home/wangxingjian/data/metaphor/hummus/images")
# 3. 指定篩選後的新JSONL文件名
OUTPUT_JSONL_FILE = "/home/wangxingjian/data/metaphor/hummus/hummus_dataset.jsonl"
# 4. 指定存放篩選後圖片的新文件夾
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 是否存在且不為空字符串
optimal_path_value = data.get("extra_info", {}).get("optimal_path")
if optimal_path_value: # 在Python中,非空字符串被視為 True
# 1. 將該行寫入新文件
outfile.write(line)
kept_count += 1
# 2. 複製對應的圖片
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:
# 如果 optimal_path 為空或不存在,則跳過
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()