| import os |
| import json |
| import shutil |
| from pathlib import Path |
| from collections import defaultdict |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from PIL import Image, UnidentifiedImageError |
| from tqdm import tqdm |
|
|
| |
|
|
| |
| QUESTION_ROOT = 'data/questions/task3_metadata_v3' |
|
|
| |
| TARGET_PREFIX = 'data/raw_images_v3' |
|
|
| |
| SOURCE_ROOT = '/run/determined/NAS1/public/lixinyuan/interleaved-co3d/data/original' |
|
|
| |
| MAX_WORKERS = 16 |
|
|
| |
| ERROR_LOG_FILE = 'copy_errors.log' |
|
|
| |
|
|
|
|
| def is_image_valid(file_path): |
| """ |
| 检查图片是否有效 |
| 1. 检查文件大小是否 > 0 |
| 2. 使用 PIL 检查文件头和结构是否完整 |
| """ |
| |
| if not os.path.exists(file_path) or os.path.getsize(file_path) == 0: |
| return False |
|
|
| |
| try: |
| with Image.open(file_path) as img: |
| img.verify() |
| return True |
| except (IOError, SyntaxError, UnidentifiedImageError): |
| return False |
|
|
| def collect_image_paths_and_refs(question_root): |
| """ |
| 遍历 question_root 下的所有 jsonl 文件,建立索引 |
| """ |
| unique_paths = set() |
| image_ref_map = defaultdict(list) |
| jsonl_files = [] |
|
|
| if not os.path.exists(question_root): |
| print(f"[Error] 找不到目录: {question_root}") |
| return set(), {} |
|
|
| print(f"[*] 正在扫描 {question_root} 下的 jsonl 文件...") |
| for root, dirs, files in os.walk(question_root): |
| for file in files: |
| if file.endswith('.jsonl'): |
| jsonl_files.append(os.path.join(root, file)) |
|
|
| print(f"[*] 找到 {len(jsonl_files)} 个 jsonl 文件,开始解析...") |
| |
| for file_path in tqdm(jsonl_files, desc="解析 JSONL"): |
| file_name = os.path.basename(file_path) |
| with open(file_path, 'r', encoding='utf-8') as f: |
| for line_num, line in enumerate(f): |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| data = json.loads(line) |
| q_id = data.get('id', f"line_{line_num}") |
| ref_info = f"{file_name} -> ID:{q_id}" |
|
|
| if 'images' in data and isinstance(data['images'], dict): |
| for img_path in data['images'].values(): |
| unique_paths.add(img_path) |
| image_ref_map[img_path].append(ref_info) |
| |
| except json.JSONDecodeError: |
| continue |
|
|
| print(f"[*] 总共找到 {len(unique_paths)} 张唯一的图片需要处理。") |
| return unique_paths, image_ref_map |
|
|
|
|
| def process_single_image(target_path_str, src_root_path, tgt_prefix_path): |
| """ |
| 单个图片处理逻辑 |
| 返回: (status, message) |
| status: 'success' (新复制), 'skip' (已存在且完好), 'fixed' (已存在但损坏,已覆盖), 'fail' (出错) |
| """ |
| try: |
| target_full_path = Path(target_path_str) |
|
|
| |
| try: |
| relative_path = target_full_path.relative_to(tgt_prefix_path) |
| except ValueError: |
| return 'fail', f"路径格式不匹配 (不包含 {tgt_prefix_path})" |
|
|
| |
| source_full_path = src_root_path / relative_path |
|
|
| |
| if not source_full_path.exists(): |
| return 'fail', f"源文件缺失: {source_full_path}" |
|
|
| |
| if target_full_path.exists(): |
| |
| if is_image_valid(target_full_path): |
| return 'skip', None |
| else: |
| |
| |
| pass |
|
|
| |
| target_full_path.parent.mkdir(parents=True, exist_ok=True) |
|
|
| |
| shutil.copy2(source_full_path, target_full_path) |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| return 'success', None |
|
|
| except Exception as e: |
| return 'fail', f"系统异常: {e}" |
|
|
| |
| def process_single_image_refined(target_path_str, src_root_path, tgt_prefix_path): |
| try: |
| target_full_path = Path(target_path_str) |
|
|
| try: |
| relative_path = target_full_path.relative_to(tgt_prefix_path) |
| except ValueError: |
| return 'fail', f"路径格式不匹配 (不包含 {tgt_prefix_path})" |
|
|
| source_full_path = src_root_path / relative_path |
|
|
| if not source_full_path.exists(): |
| return 'fail', f"源文件缺失: {source_full_path}" |
|
|
| |
| is_repair = False |
| if target_full_path.exists(): |
| if is_image_valid(target_full_path): |
| return 'skip', None |
| else: |
| |
| is_repair = True |
| |
| |
| target_full_path.parent.mkdir(parents=True, exist_ok=True) |
| shutil.copy2(source_full_path, target_full_path) |
| |
| return 'fixed' if is_repair else 'success', None |
|
|
| except Exception as e: |
| return 'fail', f"系统异常: {e}" |
|
|
|
|
| def copy_images_multithread(unique_paths, image_ref_map, source_root, target_prefix, max_workers, log_file_path): |
| """ |
| 多线程执行复制操作 |
| """ |
| success_count = 0 |
| skip_count = 0 |
| fixed_count = 0 |
| fail_count = 0 |
|
|
| src_root_path = Path(source_root) |
| tgt_prefix_path = Path(target_prefix) |
|
|
| print(f"[*] 开始多线程复制与校验 (线程数: {max_workers})...") |
| |
| with open(log_file_path, 'w', encoding='utf-8') as log_f: |
| log_f.write(f"=== 图片复制错误日志 ===\n") |
| log_f.write(f"源目录: {source_root}\n") |
| log_f.write(f"目标前缀: {target_prefix}\n") |
| log_f.write("="*50 + "\n\n") |
|
|
| with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| futures = { |
| executor.submit(process_single_image_refined, path, src_root_path, tgt_prefix_path): path |
| for path in unique_paths |
| } |
|
|
| for future in tqdm(as_completed(futures), total=len(unique_paths), desc="处理进度"): |
| path = futures[future] |
| try: |
| status, msg = future.result() |
| except Exception as e: |
| status = 'fail' |
| msg = f"线程崩溃: {e}" |
|
|
| if status == 'success': |
| success_count += 1 |
| elif status == 'skip': |
| skip_count += 1 |
| elif status == 'fixed': |
| fixed_count += 1 |
| elif status == 'fail': |
| fail_count += 1 |
| |
| refs = image_ref_map.get(path, ["Unknown Reference"]) |
| ref_str = "\n\t".join(refs[:5]) |
| if len(refs) > 5: |
| ref_str += f"\n\t... (还有 {len(refs)-5} 个引用)" |
| |
| log_entry = ( |
| f"--------------------------------------------------\n" |
| f"[FAIL] 图片路径: {path}\n" |
| f"[原因] {msg}\n" |
| f"[影响的问题]:\n\t{ref_str}\n" |
| ) |
| log_f.write(log_entry) |
| log_f.flush() |
|
|
| print("\n" + "="*30) |
| print(f"任务完成 Summary:") |
| print(f"新增复制: {success_count}") |
| print(f"跳过 (完好): {skip_count}") |
| print(f"修复 (损坏并覆盖): {fixed_count}") |
| print(f"失败 (源缺失/错误): {fail_count}") |
| print(f"详细错误日志已保存至: {log_file_path}") |
| print("="*30) |
|
|
|
|
| if __name__ == "__main__": |
| paths, ref_map = collect_image_paths_and_refs(QUESTION_ROOT) |
| |
| if not paths: |
| print("[*] 没有找到需要复制的图片,或者目录为空,程序退出。") |
| else: |
| copy_images_multithread(paths, ref_map, SOURCE_ROOT, TARGET_PREFIX, MAX_WORKERS, ERROR_LOG_FILE) |
|
|