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 # ===================== 配置区域 (请在此处修改) ===================== # 1. JSONL 文件的根目录 QUESTION_ROOT = 'data/questions/task3_metadata_v3' # 2. JSONL 数据中写的图片路径前缀 (目标前缀) TARGET_PREFIX = 'data/raw_images_v3' # 3. 图片实际存在的源目录 (源前缀) SOURCE_ROOT = '/run/determined/NAS1/public/lixinyuan/interleaved-co3d/data/original' # 4. 多线程并发数量 MAX_WORKERS = 16 # 5. 错误日志保存路径 ERROR_LOG_FILE = 'copy_errors.log' # ================================================================= def is_image_valid(file_path): """ 检查图片是否有效 1. 检查文件大小是否 > 0 2. 使用 PIL 检查文件头和结构是否完整 """ # 1. 基础检查:文件是否存在且大小不为0 if not os.path.exists(file_path) or os.path.getsize(file_path) == 0: return False # 2. 深度检查:使用 PIL 验证 (如果安装了的话) 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) # 1. 计算相对路径 try: relative_path = target_full_path.relative_to(tgt_prefix_path) except ValueError: return 'fail', f"路径格式不匹配 (不包含 {tgt_prefix_path})" # 2. 构造真实的源文件路径 source_full_path = src_root_path / relative_path # 3. 检查源文件是否存在 (如果源文件都不在,那就没法复制/修复了) if not source_full_path.exists(): return 'fail', f"源文件缺失: {source_full_path}" # 4. 检查目标文件逻辑 (核心修改部分) if target_full_path.exists(): # 检查目标文件是否完好 if is_image_valid(target_full_path): return 'skip', None else: # 文件存在但损坏,准备覆盖 # print(f"发现损坏文件,准备修复: {target_full_path}") # 调试用,多线程下不建议打印 pass # 继续向下执行复制逻辑,shutil.copy2 会自动覆盖 # 5. 创建目标文件夹 target_full_path.parent.mkdir(parents=True, exist_ok=True) # 6. 复制文件 (如果目标存在,copy2 会直接覆盖) shutil.copy2(source_full_path, target_full_path) # 如果之前文件存在(代码走到这里说明之前不存在 或者 之前存在但损坏了) # 为了统计准确,我们可以再次判断一下之前是否存在,但为了性能, # 这里简单地将所有执行了 copy 的操作视为 success 或 fixed。 # 我们可以通过判断 "是否是覆盖操作" 来区分,但 copy2 不返回这个信息。 # 简单起见:只要执行了 copy,如果之前文件存在且损坏,那就是 fixed。 # 但由于并发,这里很难精确判断 "之前是否存在", # 所以我们统一逻辑:只要执行了 copy,就是 'success' (包含修复)。 # 如果你想精确区分 'fixed',需要在 copy 前记录一下状态。 # 稍微精确一点的返回逻辑: # 如果刚才 is_image_valid 返回 False 且 exists 为 True,那就是 fixed。 # 但为了代码简洁,我们在上面没有保留这个状态。 # 让我们稍微调整一下逻辑结构以便区分。 return 'success', None except Exception as e: return 'fail', f"系统异常: {e}" # 为了支持 'fixed' 统计,重写一下 process_single_image 的内部逻辑结构 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)