feat: add integrity check to copy script, and add .gitignore
Browse files- .gitignore +3 -1
- scripts/copy_image.py +163 -66
.gitignore
CHANGED
|
@@ -1,2 +1,4 @@
|
|
| 1 |
__pycache__/
|
| 2 |
-
*.egg-info/
|
|
|
|
|
|
|
|
|
| 1 |
__pycache__/
|
| 2 |
+
*.egg-info/
|
| 3 |
+
raw_images/
|
| 4 |
+
*_test/
|
scripts/copy_image.py
CHANGED
|
@@ -2,15 +2,10 @@ import os
|
|
| 2 |
import json
|
| 3 |
import shutil
|
| 4 |
from pathlib import Path
|
|
|
|
| 5 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
try:
|
| 9 |
-
from tqdm import tqdm
|
| 10 |
-
except ImportError:
|
| 11 |
-
# 如果没装 tqdm,提供一个简单的替代,防止报错
|
| 12 |
-
def tqdm(iterable, **kwargs):
|
| 13 |
-
return iterable
|
| 14 |
|
| 15 |
# ===================== 配置区域 (请在此处修改) =====================
|
| 16 |
|
|
@@ -23,23 +18,48 @@ TARGET_PREFIX = 'data/raw_images'
|
|
| 23 |
# 3. 图片实际存在的源目录 (源前缀)
|
| 24 |
SOURCE_ROOT = '/run/determined/NAS1/public/lixinyuan/interleaved-co3d/data/original'
|
| 25 |
|
| 26 |
-
# 4.
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
# =================================================================
|
| 31 |
|
| 32 |
|
| 33 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
"""
|
| 35 |
-
遍历 question_root 下的所有 jsonl 文件,
|
| 36 |
"""
|
| 37 |
unique_paths = set()
|
|
|
|
| 38 |
jsonl_files = []
|
| 39 |
|
| 40 |
if not os.path.exists(question_root):
|
| 41 |
print(f"[Error] 找不到目录: {question_root}")
|
| 42 |
-
return set()
|
| 43 |
|
| 44 |
print(f"[*] 正在扫描 {question_root} 下的 jsonl 文件...")
|
| 45 |
for root, dirs, files in os.walk(question_root):
|
|
@@ -47,30 +67,37 @@ def collect_image_paths(question_root):
|
|
| 47 |
if file.endswith('.jsonl'):
|
| 48 |
jsonl_files.append(os.path.join(root, file))
|
| 49 |
|
| 50 |
-
print(f"[*] 找到 {len(jsonl_files)} 个 jsonl 文件,开始解析
|
| 51 |
|
| 52 |
for file_path in tqdm(jsonl_files, desc="解析 JSONL"):
|
|
|
|
| 53 |
with open(file_path, 'r', encoding='utf-8') as f:
|
| 54 |
-
for line in f:
|
| 55 |
line = line.strip()
|
| 56 |
if not line:
|
| 57 |
continue
|
| 58 |
try:
|
| 59 |
data = json.loads(line)
|
|
|
|
|
|
|
|
|
|
| 60 |
if 'images' in data and isinstance(data['images'], dict):
|
| 61 |
for img_path in data['images'].values():
|
| 62 |
unique_paths.add(img_path)
|
|
|
|
|
|
|
| 63 |
except json.JSONDecodeError:
|
| 64 |
continue
|
| 65 |
|
| 66 |
-
print(f"[*] 总共找到 {len(unique_paths)} 张唯一的图片需要
|
| 67 |
-
return unique_paths
|
| 68 |
|
| 69 |
|
| 70 |
def process_single_image(target_path_str, src_root_path, tgt_prefix_path):
|
| 71 |
"""
|
| 72 |
-
单个图片处理逻辑
|
| 73 |
-
返回
|
|
|
|
| 74 |
"""
|
| 75 |
try:
|
| 76 |
target_full_path = Path(target_path_str)
|
|
@@ -79,84 +106,154 @@ def process_single_image(target_path_str, src_root_path, tgt_prefix_path):
|
|
| 79 |
try:
|
| 80 |
relative_path = target_full_path.relative_to(tgt_prefix_path)
|
| 81 |
except ValueError:
|
| 82 |
-
return 'fail', f"路径格式不匹配
|
| 83 |
|
| 84 |
# 2. 构造真实的源文件路径
|
| 85 |
source_full_path = src_root_path / relative_path
|
| 86 |
|
| 87 |
-
# 3. 检查源文件是否存在
|
| 88 |
if not source_full_path.exists():
|
| 89 |
-
return 'fail',
|
| 90 |
|
| 91 |
-
# 4. 检查目标文件
|
| 92 |
if target_full_path.exists():
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
# 5. 创建目标文件夹
|
| 96 |
target_full_path.parent.mkdir(parents=True, exist_ok=True)
|
| 97 |
|
| 98 |
-
# 6. 复制文件
|
| 99 |
shutil.copy2(source_full_path, target_full_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
return 'success', None
|
| 101 |
|
| 102 |
except Exception as e:
|
| 103 |
-
return 'fail', f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
-
def copy_images_multithread(unique_paths, source_root, target_prefix, max_workers):
|
| 107 |
"""
|
| 108 |
多线程执行复制操作
|
| 109 |
"""
|
| 110 |
-
success_count = 0
|
| 111 |
-
skip_count = 0
|
| 112 |
-
|
|
|
|
| 113 |
|
| 114 |
src_root_path = Path(source_root)
|
| 115 |
tgt_prefix_path = Path(target_prefix)
|
| 116 |
|
| 117 |
-
print(f"[*] 开始多线程复制
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
print("\n" + "="*30)
|
| 147 |
print(f"任务完成 Summary:")
|
| 148 |
-
print(f"
|
| 149 |
-
print(f"跳过 (
|
|
|
|
| 150 |
print(f"失败 (源缺失/错误): {fail_count}")
|
|
|
|
| 151 |
print("="*30)
|
| 152 |
|
| 153 |
|
| 154 |
if __name__ == "__main__":
|
| 155 |
-
|
| 156 |
-
paths = collect_image_paths(QUESTION_ROOT)
|
| 157 |
|
| 158 |
if not paths:
|
| 159 |
print("[*] 没有找到需要复制的图片,或者目录为空,程序退出。")
|
| 160 |
else:
|
| 161 |
-
|
| 162 |
-
copy_images_multithread(paths, SOURCE_ROOT, TARGET_PREFIX, MAX_WORKERS)
|
|
|
|
| 2 |
import json
|
| 3 |
import shutil
|
| 4 |
from pathlib import Path
|
| 5 |
+
from collections import defaultdict
|
| 6 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 7 |
+
from PIL import Image, UnidentifiedImageError
|
| 8 |
+
from tqdm import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# ===================== 配置区域 (请在此处修改) =====================
|
| 11 |
|
|
|
|
| 18 |
# 3. 图片实际存在的源目录 (源前缀)
|
| 19 |
SOURCE_ROOT = '/run/determined/NAS1/public/lixinyuan/interleaved-co3d/data/original'
|
| 20 |
|
| 21 |
+
# 4. 多线程并发数量
|
| 22 |
+
MAX_WORKERS = 16
|
| 23 |
+
|
| 24 |
+
# 5. 错误日志保存路径
|
| 25 |
+
ERROR_LOG_FILE = 'copy_errors.log'
|
| 26 |
|
| 27 |
# =================================================================
|
| 28 |
|
| 29 |
|
| 30 |
+
def is_image_valid(file_path):
|
| 31 |
+
"""
|
| 32 |
+
检查图片是否有效
|
| 33 |
+
1. 检查文件大小是否 > 0
|
| 34 |
+
2. 使用 PIL 检查文件头和结构是否完整
|
| 35 |
+
"""
|
| 36 |
+
# 1. 基础检查:文件是否存在且大小不为0
|
| 37 |
+
if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
# 2. 深度检查:使用 PIL 验证 (如果安装了的话)
|
| 41 |
+
if PIL_AVAILABLE:
|
| 42 |
+
try:
|
| 43 |
+
with Image.open(file_path) as img:
|
| 44 |
+
img.verify() # 验证文件完整性,不会加载整个图像,速度较快
|
| 45 |
+
return True
|
| 46 |
+
except (IOError, SyntaxError, UnidentifiedImageError):
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
return True
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def collect_image_paths_and_refs(question_root):
|
| 53 |
"""
|
| 54 |
+
遍历 question_root 下的所有 jsonl 文件,建立索引
|
| 55 |
"""
|
| 56 |
unique_paths = set()
|
| 57 |
+
image_ref_map = defaultdict(list)
|
| 58 |
jsonl_files = []
|
| 59 |
|
| 60 |
if not os.path.exists(question_root):
|
| 61 |
print(f"[Error] 找不到目录: {question_root}")
|
| 62 |
+
return set(), {}
|
| 63 |
|
| 64 |
print(f"[*] 正在扫描 {question_root} 下的 jsonl 文件...")
|
| 65 |
for root, dirs, files in os.walk(question_root):
|
|
|
|
| 67 |
if file.endswith('.jsonl'):
|
| 68 |
jsonl_files.append(os.path.join(root, file))
|
| 69 |
|
| 70 |
+
print(f"[*] 找到 {len(jsonl_files)} 个 jsonl 文件,开始解析...")
|
| 71 |
|
| 72 |
for file_path in tqdm(jsonl_files, desc="解析 JSONL"):
|
| 73 |
+
file_name = os.path.basename(file_path)
|
| 74 |
with open(file_path, 'r', encoding='utf-8') as f:
|
| 75 |
+
for line_num, line in enumerate(f):
|
| 76 |
line = line.strip()
|
| 77 |
if not line:
|
| 78 |
continue
|
| 79 |
try:
|
| 80 |
data = json.loads(line)
|
| 81 |
+
q_id = data.get('id', f"line_{line_num}")
|
| 82 |
+
ref_info = f"{file_name} -> ID:{q_id}"
|
| 83 |
+
|
| 84 |
if 'images' in data and isinstance(data['images'], dict):
|
| 85 |
for img_path in data['images'].values():
|
| 86 |
unique_paths.add(img_path)
|
| 87 |
+
image_ref_map[img_path].append(ref_info)
|
| 88 |
+
|
| 89 |
except json.JSONDecodeError:
|
| 90 |
continue
|
| 91 |
|
| 92 |
+
print(f"[*] 总共找到 {len(unique_paths)} 张唯一的图片需要处理。")
|
| 93 |
+
return unique_paths, image_ref_map
|
| 94 |
|
| 95 |
|
| 96 |
def process_single_image(target_path_str, src_root_path, tgt_prefix_path):
|
| 97 |
"""
|
| 98 |
+
单个图片处理逻辑
|
| 99 |
+
返回: (status, message)
|
| 100 |
+
status: 'success' (新复制), 'skip' (已存在且完好), 'fixed' (已存在但损坏,已覆盖), 'fail' (出错)
|
| 101 |
"""
|
| 102 |
try:
|
| 103 |
target_full_path = Path(target_path_str)
|
|
|
|
| 106 |
try:
|
| 107 |
relative_path = target_full_path.relative_to(tgt_prefix_path)
|
| 108 |
except ValueError:
|
| 109 |
+
return 'fail', f"路径格式不匹配 (不包含 {tgt_prefix_path})"
|
| 110 |
|
| 111 |
# 2. 构造真实的源文件路径
|
| 112 |
source_full_path = src_root_path / relative_path
|
| 113 |
|
| 114 |
+
# 3. 检查源文件是否存在 (如果源文件都不在,那就没法复制/修复了)
|
| 115 |
if not source_full_path.exists():
|
| 116 |
+
return 'fail', f"源文件缺失: {source_full_path}"
|
| 117 |
|
| 118 |
+
# 4. 检查目标文件逻辑 (核心修改部分)
|
| 119 |
if target_full_path.exists():
|
| 120 |
+
# 检查目标文件是否完好
|
| 121 |
+
if is_image_valid(target_full_path):
|
| 122 |
+
return 'skip', None
|
| 123 |
+
else:
|
| 124 |
+
# 文件存在但损坏,准备覆盖
|
| 125 |
+
# print(f"发现损坏文件,准备修复: {target_full_path}") # 调试用,多线程下不建议打印
|
| 126 |
+
pass # 继续向下执行复制逻辑,shutil.copy2 会自动覆盖
|
| 127 |
|
| 128 |
+
# 5. 创建目标文件夹
|
| 129 |
target_full_path.parent.mkdir(parents=True, exist_ok=True)
|
| 130 |
|
| 131 |
+
# 6. 复制文件 (如果目标存在,copy2 会直接覆盖)
|
| 132 |
shutil.copy2(source_full_path, target_full_path)
|
| 133 |
+
|
| 134 |
+
# 如果之前文件存在(代码走到这里说明之前不存在 或者 之前存在但损坏了)
|
| 135 |
+
# 为了统计准确,我们可以再次判断一下之前是否存在,但为了性能,
|
| 136 |
+
# 这里简单地将所有执行了 copy 的操作视为 success 或 fixed。
|
| 137 |
+
# 我们可以通过判断 "是否是覆盖操作" 来区分,但 copy2 不返回这个信息。
|
| 138 |
+
# 简单起见:只要执行了 copy,如果之前文件存在且损坏,那就是 fixed。
|
| 139 |
+
# 但由于并发,这里很难精确判断 "之前是否存在",
|
| 140 |
+
# 所以我们统一逻辑:只要执行了 copy,就是 'success' (包含修复)。
|
| 141 |
+
# 如果你想精确区分 'fixed',需要在 copy 前记录一下状态。
|
| 142 |
+
|
| 143 |
+
# 稍微精确一点的返回逻辑:
|
| 144 |
+
# 如果刚才 is_image_valid 返回 False 且 exists 为 True,那就是 fixed。
|
| 145 |
+
# 但为了代码简洁,我们在上面没有保留这个状态。
|
| 146 |
+
# 让我们稍微调整一下逻辑结构以便区分。
|
| 147 |
return 'success', None
|
| 148 |
|
| 149 |
except Exception as e:
|
| 150 |
+
return 'fail', f"系统异常: {e}"
|
| 151 |
+
|
| 152 |
+
# 为了支持 'fixed' 统计,重写一下 process_single_image 的内部逻辑结构
|
| 153 |
+
def process_single_image_refined(target_path_str, src_root_path, tgt_prefix_path):
|
| 154 |
+
try:
|
| 155 |
+
target_full_path = Path(target_path_str)
|
| 156 |
+
|
| 157 |
+
try:
|
| 158 |
+
relative_path = target_full_path.relative_to(tgt_prefix_path)
|
| 159 |
+
except ValueError:
|
| 160 |
+
return 'fail', f"路径格式不匹配 (不包含 {tgt_prefix_path})"
|
| 161 |
+
|
| 162 |
+
source_full_path = src_root_path / relative_path
|
| 163 |
+
|
| 164 |
+
if not source_full_path.exists():
|
| 165 |
+
return 'fail', f"源文件缺失: {source_full_path}"
|
| 166 |
+
|
| 167 |
+
# === 检查目标文件 ===
|
| 168 |
+
is_repair = False
|
| 169 |
+
if target_full_path.exists():
|
| 170 |
+
if is_image_valid(target_full_path):
|
| 171 |
+
return 'skip', None
|
| 172 |
+
else:
|
| 173 |
+
# 存在但损坏,标记为修复模式
|
| 174 |
+
is_repair = True
|
| 175 |
+
|
| 176 |
+
# === 执行复制 ===
|
| 177 |
+
target_full_path.parent.mkdir(parents=True, exist_ok=True)
|
| 178 |
+
shutil.copy2(source_full_path, target_full_path)
|
| 179 |
+
|
| 180 |
+
return 'fixed' if is_repair else 'success', None
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
return 'fail', f"系统异常: {e}"
|
| 184 |
|
| 185 |
|
| 186 |
+
def copy_images_multithread(unique_paths, image_ref_map, source_root, target_prefix, max_workers, log_file_path):
|
| 187 |
"""
|
| 188 |
多线程执行复制操作
|
| 189 |
"""
|
| 190 |
+
success_count = 0 # 新复制
|
| 191 |
+
skip_count = 0 # 已存在且完好
|
| 192 |
+
fixed_count = 0 # 已存在但损坏,已修复
|
| 193 |
+
fail_count = 0 # 失败
|
| 194 |
|
| 195 |
src_root_path = Path(source_root)
|
| 196 |
tgt_prefix_path = Path(target_prefix)
|
| 197 |
|
| 198 |
+
print(f"[*] 开始多线程复制与校验 (线程数: {max_workers})...")
|
| 199 |
+
|
| 200 |
+
with open(log_file_path, 'w', encoding='utf-8') as log_f:
|
| 201 |
+
log_f.write(f"=== 图片复制错误日志 ===\n")
|
| 202 |
+
log_f.write(f"源目录: {source_root}\n")
|
| 203 |
+
log_f.write(f"目标前缀: {target_prefix}\n")
|
| 204 |
+
log_f.write("="*50 + "\n\n")
|
| 205 |
+
|
| 206 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 207 |
+
futures = {
|
| 208 |
+
executor.submit(process_single_image_refined, path, src_root_path, tgt_prefix_path): path
|
| 209 |
+
for path in unique_paths
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
for future in tqdm(as_completed(futures), total=len(unique_paths), desc="处理进度"):
|
| 213 |
+
path = futures[future]
|
| 214 |
+
try:
|
| 215 |
+
status, msg = future.result()
|
| 216 |
+
except Exception as e:
|
| 217 |
+
status = 'fail'
|
| 218 |
+
msg = f"线程崩溃: {e}"
|
| 219 |
+
|
| 220 |
+
if status == 'success':
|
| 221 |
+
success_count += 1
|
| 222 |
+
elif status == 'skip':
|
| 223 |
+
skip_count += 1
|
| 224 |
+
elif status == 'fixed':
|
| 225 |
+
fixed_count += 1
|
| 226 |
+
elif status == 'fail':
|
| 227 |
+
fail_count += 1
|
| 228 |
+
|
| 229 |
+
refs = image_ref_map.get(path, ["Unknown Reference"])
|
| 230 |
+
ref_str = "\n\t".join(refs[:5])
|
| 231 |
+
if len(refs) > 5:
|
| 232 |
+
ref_str += f"\n\t... (还有 {len(refs)-5} 个引用)"
|
| 233 |
+
|
| 234 |
+
log_entry = (
|
| 235 |
+
f"--------------------------------------------------\n"
|
| 236 |
+
f"[FAIL] 图片路径: {path}\n"
|
| 237 |
+
f"[原因] {msg}\n"
|
| 238 |
+
f"[影响的问题]:\n\t{ref_str}\n"
|
| 239 |
+
)
|
| 240 |
+
log_f.write(log_entry)
|
| 241 |
+
log_f.flush()
|
| 242 |
|
| 243 |
print("\n" + "="*30)
|
| 244 |
print(f"任务完成 Summary:")
|
| 245 |
+
print(f"新增复制: {success_count}")
|
| 246 |
+
print(f"跳过 (完好): {skip_count}")
|
| 247 |
+
print(f"修复 (损坏并覆盖): {fixed_count}")
|
| 248 |
print(f"失败 (源缺失/错误): {fail_count}")
|
| 249 |
+
print(f"详细错误日志已保存至: {log_file_path}")
|
| 250 |
print("="*30)
|
| 251 |
|
| 252 |
|
| 253 |
if __name__ == "__main__":
|
| 254 |
+
paths, ref_map = collect_image_paths_and_refs(QUESTION_ROOT)
|
|
|
|
| 255 |
|
| 256 |
if not paths:
|
| 257 |
print("[*] 没有找到需要复制的图片,或者目录为空,程序退出。")
|
| 258 |
else:
|
| 259 |
+
copy_images_multithread(paths, ref_map, SOURCE_ROOT, TARGET_PREFIX, MAX_WORKERS, ERROR_LOG_FILE)
|
|
|