File size: 4,662 Bytes
08ad0fa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | import json
import random
import shutil
from pathlib import Path
import sys
from datetime import datetime
import pytz
def sample_data_and_images():
"""
從一個JSONL數據集中隨機抽取指定數量的樣本,
並將樣本數據和對應的圖片保存到新的位置。
"""
# --- 配置區 ---
# 1. 指定您的輸入JSONL文件名
INPUT_JSONL_FILE = "/home/wangxingjian/data/V-FLUTE/vflute_parallel_dataset.jsonl" # ⚠️ 請修改為您的JSONL文件名
# 2. 存放所有原始圖片的源文件夾
SOURCE_IMAGE_DIR = Path("/home/wangxingjian/data/V-FLUTE/images")
# 3. 您想要抽取的樣本數量
SAMPLE_SIZE = 300
# 4. 指定抽樣後的新JSONL文件名
OUTPUT_JSONL_FILE = f"/home/wangxingjian/data/V-FLUTE/sampled_{SAMPLE_SIZE}_records.jsonl"
# 5. 指定存放抽樣後圖片的新文件夾
OUTPUT_IMAGE_DIR = Path(f"/home/wangxingjian/data/V-FLUTE/sampled_{SAMPLE_SIZE}_images")
# --- 腳本主體 ---
# 獲取當前台灣時間
tz = pytz.timezone('Asia/Taipei')
current_time = datetime.now(tz).strftime('%Y年%m月%d日 傍晚%H:%M')
print(f"--- 數據集隨機抽樣腳本 ---")
print(f"現在是台灣時間: {current_time}")
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
# --- 1. 將所有記錄讀取到內存 ---
print(f"\n🚀 正在從 '{input_jsonl_path}' 讀取所有記錄...")
all_records = []
try:
with open(input_jsonl_path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip(): # 確保不是空行
all_records.append(json.loads(line))
except Exception as e:
print(f"❌ 讀取文件時發生錯誤: {e}")
return
total_records = len(all_records)
print(f"✅ 讀取完成,共找到 {total_records} 條記錄。")
# --- 2. 執行隨機抽樣 ---
actual_sample_size = min(SAMPLE_SIZE, total_records)
if actual_sample_size == 0:
print("⚠️ 警告: 文件中沒有記錄可供抽樣。")
return
print(f"🔬 正在從 {total_records} 條記錄中隨機抽取 {actual_sample_size} 條...")
# random.sample 確保抽樣的唯一性
sampled_records = random.sample(all_records, actual_sample_size)
print("✅ 抽樣完成。")
# --- 3. 保存抽樣結果 ---
# 創建輸出文件夾
OUTPUT_IMAGE_DIR.mkdir(parents=True, exist_ok=True)
copied_count = 0
not_found_count = 0
print(f"📝 正在將抽樣記錄寫入 '{OUTPUT_JSONL_FILE}'...")
print(f"🖼️ 正在將對應圖片複製到 '{OUTPUT_IMAGE_DIR}'...")
with open(OUTPUT_JSONL_FILE, 'w', encoding='utf-8') as outfile:
for record in sampled_records:
# 寫入新的 .jsonl 文件
outfile.write(json.dumps(record, ensure_ascii=False) + '\n')
# 複製對應的圖片
image_filename = record.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}',無法複製。")
not_found_count += 1
else:
print(f" - ⚠️ 警告: 記錄 '{record.get('extra_info', {}).get('index', '')}' 缺少 'image.path' 信息。")
# --- 4. 打印最終總結 ---
print("\n--- ✨ 抽樣完成 ✨ ---")
print(f"總記錄數: {total_records}")
print(f"請求抽樣數: {SAMPLE_SIZE}")
print(f"實際抽樣數: {actual_sample_size}")
print("--------------------------")
print(f"📄 新的數據文件已保存至: '{OUTPUT_JSONL_FILE}'")
print(f"🖼️ 複製的圖片數量: {copied_count}")
if not_found_count > 0:
print(f"❗ 未找到對應圖片: {not_found_count} 次")
print(f"所有抽樣圖片都保存在 '{OUTPUT_IMAGE_DIR}' 文件夾中。")
print("--------------------------")
if __name__ == '__main__':
# 在運行前,請先確保已安裝 pytz 库:pip install pytz
sample_data_and_images() |