-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.py
More file actions
694 lines (552 loc) · 27.9 KB
/
Copy pathprocess.py
File metadata and controls
694 lines (552 loc) · 27.9 KB
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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import argparse
import json
import os
import re
import shutil
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple
SCRIPT_DIR = Path(__file__).resolve().parent
try:
from input_discovery import (
discover_sequences as discover_input_sequences,
filter_names as filter_input_names,
find_buffer as find_input_buffer,
group_files_by_frame as group_input_files_by_frame,
select_group_file as select_input_group_file,
sort_frame_ids as sort_input_frame_ids,
)
except ModuleNotFoundError:
from process_exr.input_discovery import (
discover_sequences as discover_input_sequences,
filter_names as filter_input_names,
find_buffer as find_input_buffer,
group_files_by_frame as group_input_files_by_frame,
select_group_file as select_input_group_file,
sort_frame_ids as sort_input_frame_ids,
)
os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"
import cv2
from tqdm import tqdm
def group_buffers_by_name(file_list: List[str]) -> Dict[str, List[str]]:
return group_input_files_by_frame(file_list)
def sort_frame_ids(frame_ids: List[str]) -> List[str]:
return sort_input_frame_ids(frame_ids)
def select_group_file(files: List[str], keyword: Optional[str], input_sequence_name: str = "") -> Optional[str]:
return select_input_group_file(files, keyword, input_sequence_name)
def find_buffer(files: List[str], keyword: str, input_sequence_name: str = "") -> Optional[str]:
return find_input_buffer(files, keyword, input_sequence_name)
def load_buffer(input_dir: str, file_name: Optional[str]):
if not file_name:
return None
file_path = os.path.join(input_dir, file_name)
if not os.path.exists(file_path):
return None
return cv2.imread(file_path, cv2.IMREAD_UNCHANGED)
def fast_copy(input_dir: str, output_dir: str, src_file: Optional[str], dst_file: str) -> None:
if not src_file:
return
src_path = os.path.join(input_dir, src_file)
if not os.path.exists(src_path):
return
shutil.copyfile(src_path, os.path.join(output_dir, dst_file))
def combine_d(buffers):
if len(buffers) != 4 or any(b is None for b in buffers):
return None
try:
b1, g1, r1, d1 = cv2.split(buffers[0])
b2, g2, r2, d2 = cv2.split(buffers[1])
b3, g3, r3, d3 = cv2.split(buffers[2])
b4, g4, r4, d4 = cv2.split(buffers[3])
combined = cv2.merge([b1, g2, r3, g4])
return cv2.cvtColor(combined, cv2.COLOR_BGRA2RGBA)
except Exception:
return None
def combine_e(buffers):
if len(buffers) != 2 or any(b is None for b in buffers):
return None
try:
b1, g1, r1, d1 = cv2.split(buffers[0])
b2, g2, r2, d2 = cv2.split(buffers[1])
combined = cv2.merge([b1, g1, r1, b2])
return cv2.cvtColor(combined, cv2.COLOR_BGRA2RGBA)
except Exception:
return None
COMBINE_HANDLERS = {
"combineD": combine_d,
"combineE": combine_e,
}
@dataclass(frozen=True)
class MergeBufferMapping:
target_keyword: str
output_suffix: str
overlay_keyword: Optional[str] = None
@dataclass(frozen=True)
class MergeSequenceConfig:
target_sequence: str
overlay_sequence: str
output_sequence_name: str
buffer_mappings: Tuple[MergeBufferMapping, ...]
target_start_frame: int
overlay_start_frame: int
target_frame_step: int
overlay_frame_step: int
missing_behavior: str
frame_limit: Optional[int]
def process_group(task: Tuple[str, List[str], str, str, str, str, List[str], List[dict]]) -> str:
group_id, files, input_dir, output_dir, stage_name, input_sequence_name, copy_buffers, combinations = task
for keyword in copy_buffers:
src_file = find_buffer(files, keyword, input_sequence_name)
fast_copy(input_dir, output_dir, src_file, f"{stage_name}{keyword}.{group_id}.exr")
for combo in combinations:
mode = combo["mode"]
inputs = combo["inputs"]
output_suffix = combo["output_suffix"]
buffers = [
load_buffer(input_dir, find_buffer(files, keyword, input_sequence_name))
for keyword in inputs
]
result = COMBINE_HANDLERS[mode](buffers)
if result is not None:
out_file = f"{stage_name}{output_suffix}.{group_id}.exr"
cv2.imwrite(os.path.join(output_dir, out_file), result)
return group_id
def extract_stage_name(sequence_name: str, sequence_input_dir: str) -> str:
source_name = sequence_name.strip() if sequence_name else os.path.basename(os.path.normpath(sequence_input_dir))
if not source_name:
return "Sequence"
stage_name = source_name.split("_", 1)[0]
return stage_name or source_name
def extract_output_subdirs(sequence_name: str, sequence_input_dir: str) -> Tuple[str, str]:
source_name = sequence_name.strip() if sequence_name else os.path.basename(os.path.normpath(sequence_input_dir))
if not source_name:
return "Sequence", "default"
if "_" in source_name:
level1, level2 = source_name.split("_", 1)
return (level1 or "Sequence"), (level2 or "default")
return source_name, "default"
def load_config(config_path: str) -> dict:
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
required = ["input_root", "output_root"]
missing = [k for k in required if k not in config]
if missing:
raise ValueError(f"配置缺少必填项: {missing}")
if "copy_buffers" not in config:
config["copy_buffers"] = []
if "combinations" not in config:
config["combinations"] = []
for combo in config["combinations"]:
for key in ["mode", "inputs", "output_suffix"]:
if key not in combo:
raise ValueError(f"组合配置缺少字段 '{key}': {combo}")
if combo["mode"] not in COMBINE_HANDLERS:
raise ValueError(f"不支持的组合模式: {combo['mode']}")
workers = config.get("workers", 0)
if not isinstance(workers, int) or workers < 0:
raise ValueError("workers 必须是 >= 0 的整数")
suffixes = config.get("subfolder_suffixes")
if suffixes is not None:
if not isinstance(suffixes, list) or not all(isinstance(s, str) for s in suffixes):
raise ValueError("subfolder_suffixes 必须是字符串数组,例如 [\"_30\", \"_60\"]")
sequences = config.get("sequences")
if sequences is None:
config["sequences"] = []
elif not isinstance(sequences, list):
raise ValueError("sequences 必须是数组,可由输入节点 sequence_discovery 生成")
if "relocate_input_before_run" in config and not isinstance(config["relocate_input_before_run"], bool):
raise ValueError("relocate_input_before_run 必须是布尔值")
if "input_staging_dir" in config:
if not isinstance(config["input_staging_dir"], str) or not config["input_staging_dir"].strip():
raise ValueError("input_staging_dir 必须是非空字符串")
merge_sequences = config.get("merge_sequences")
if merge_sequences is None:
config["merge_sequences"] = []
elif not isinstance(merge_sequences, list):
raise ValueError("merge_sequences 必须是数组")
for merge in config["merge_sequences"]:
for key in [
"target_sequence",
"overlay_sequence",
"buffer_mappings",
]:
if key not in merge:
raise ValueError(f"merge_sequences 配置缺少字段 '{key}': {merge}")
if not isinstance(merge["target_sequence"], str) or not merge["target_sequence"].strip():
raise ValueError("merge_sequences.target_sequence 必须是非空字符串")
if not isinstance(merge["overlay_sequence"], str) or not merge["overlay_sequence"].strip():
raise ValueError("merge_sequences.overlay_sequence 必须是非空字符串")
output_sequence_name = merge.get("output_sequence_name", merge["target_sequence"])
if not isinstance(output_sequence_name, str) or not output_sequence_name.strip():
raise ValueError("merge_sequences.output_sequence_name 必须是非空字符串")
merge["output_sequence_name"] = output_sequence_name.strip()
buffer_mappings = merge["buffer_mappings"]
if not isinstance(buffer_mappings, list) or not buffer_mappings:
raise ValueError("merge_sequences.buffer_mappings 必须是非空数组")
for mapping in buffer_mappings:
if not isinstance(mapping, dict):
raise ValueError(f"buffer_mappings 项必须是对象: {mapping}")
if "output_suffix" not in mapping:
raise ValueError(f"buffer_mappings 缺少字段 'output_suffix': {mapping}")
if not isinstance(mapping["output_suffix"], str) or not mapping["output_suffix"].strip():
raise ValueError("buffer_mappings.output_suffix 必须是非空字符串")
target_keyword = mapping.get("target_keyword", "")
overlay_keyword = mapping.get("overlay_keyword", target_keyword)
if not isinstance(target_keyword, str):
raise ValueError("buffer_mappings.target_keyword 必须是字符串")
if overlay_keyword is not None and not isinstance(overlay_keyword, str):
raise ValueError("buffer_mappings.overlay_keyword 必须是字符串或 null")
mapping["target_keyword"] = target_keyword.strip()
mapping["overlay_keyword"] = overlay_keyword.strip() if isinstance(overlay_keyword, str) else None
mapping["output_suffix"] = mapping["output_suffix"].strip()
for key in ["target_start_frame", "overlay_start_frame"]:
value = merge.get(key, 0)
if not isinstance(value, int) or value < 0:
raise ValueError(f"merge_sequences.{key} 必须是 >= 0 的整数")
merge[key] = value
for key in ["target_frame_step", "overlay_frame_step"]:
value = merge.get(key, 1)
if not isinstance(value, int) or value <= 0:
raise ValueError(f"merge_sequences.{key} 必须是 > 0 的整数")
merge[key] = value
frame_limit = merge.get("frame_limit")
if frame_limit is not None:
if not isinstance(frame_limit, int) or frame_limit <= 0:
raise ValueError("merge_sequences.frame_limit 必须是 > 0 的整数或 null")
missing_behavior = merge.get("missing_behavior", "skip")
if missing_behavior not in {"skip", "fail"}:
raise ValueError("merge_sequences.missing_behavior 仅支持 'skip' 或 'fail'")
merge["missing_behavior"] = missing_behavior
return config
def compile_merge_config(raw_merge: dict) -> MergeSequenceConfig:
return MergeSequenceConfig(
target_sequence=raw_merge["target_sequence"].strip(),
overlay_sequence=raw_merge["overlay_sequence"].strip(),
output_sequence_name=raw_merge["output_sequence_name"].strip(),
buffer_mappings=tuple(
MergeBufferMapping(
target_keyword=mapping["target_keyword"],
overlay_keyword=mapping.get("overlay_keyword"),
output_suffix=mapping["output_suffix"],
)
for mapping in raw_merge["buffer_mappings"]
),
target_start_frame=raw_merge.get("target_start_frame", 0),
overlay_start_frame=raw_merge.get("overlay_start_frame", 0),
target_frame_step=raw_merge.get("target_frame_step", 1),
overlay_frame_step=raw_merge.get("overlay_frame_step", 1),
missing_behavior=raw_merge.get("missing_behavior", "skip"),
frame_limit=raw_merge.get("frame_limit"),
)
def resolve_runtime_path(raw_path: str) -> str:
candidate = Path(raw_path)
if not candidate.is_absolute():
candidate = SCRIPT_DIR / candidate
return os.path.normpath(str(candidate))
def resolve_cli_path(raw_path: str) -> str:
candidate = Path(raw_path)
if not candidate.is_absolute():
candidate = SCRIPT_DIR / candidate
return os.path.normpath(str(candidate))
def resolve_config_path(config_dir: str, config: Optional[str], config_name: Optional[str], default_config_name: Optional[str]) -> str:
if config:
return config
selected = config_name or default_config_name
if not selected:
raise ValueError("请通过 --config 或 --config-name 指定配置")
if not selected.endswith(".json"):
selected = f"{selected}.json"
return os.path.join(config_dir, selected)
def list_configs(config_dir: str) -> List[str]:
if not os.path.isdir(config_dir):
return []
return sorted([f for f in os.listdir(config_dir) if f.endswith(".json")])
def filter_subdirs_by_suffix(names: List[str], suffixes: Optional[List[str]]) -> List[str]:
"""仅保留名称以任一后缀结尾的子文件夹名;suffixes 为 None 或空列表时不筛选。"""
return filter_input_names(names, suffixes=suffixes)
def resolve_input_staging_dir(config: dict) -> str:
"""staging 目录:相对路径相对于本脚本所在目录(与在 PY_Script 下运行时的 ./input 一致)。"""
raw = (config.get("input_staging_dir") or "input").strip()
if os.path.isabs(raw):
return os.path.normpath(raw)
return os.path.normpath(str(SCRIPT_DIR / raw))
def relocate_input_to_staging(
input_root: str,
staging_dir: str,
subfolder_suffixes: Optional[List[str]],
) -> Tuple[str, bool]:
"""将待处理序列从 input_root 剪切到 staging_dir,返回新的 input_root 及是否为单序列模式。
与 discover_sequences 一致:有子文件夹时只剪切名称符合 subfolder_suffixes 的(若配置了筛选);
无子文件夹时视为单序列,将整个 input_root 文件夹剪切到 staging_dir/basename(input_root)。
"""
input_root = os.path.abspath(input_root)
staging_dir = os.path.abspath(staging_dir)
in_root = os.path.normcase(input_root)
st_root = os.path.normcase(staging_dir)
if in_root == st_root or st_root.startswith(in_root + os.sep):
raise ValueError("input_staging_dir 不能与 input_root 相同或位于 input_root 内部")
os.makedirs(staging_dir, exist_ok=True)
all_children = sorted(
[d for d in os.listdir(input_root) if os.path.isdir(os.path.join(input_root, d))]
)
if not all_children:
base = os.path.basename(os.path.normpath(input_root))
dest = os.path.join(staging_dir, base)
if os.path.exists(dest):
raise FileExistsError(f"staging 目标已存在,请先清空或重命名: {dest}")
shutil.move(input_root, dest)
print(f"[staging] 单序列目录已剪切至: {dest}")
return staging_dir, True
to_move = filter_subdirs_by_suffix(all_children, subfolder_suffixes)
if subfolder_suffixes and not to_move:
raise RuntimeError(
"staging: input_root 下有子文件夹,但 subfolder_suffixes 筛选后无匹配,未剪切任何目录。"
)
if not subfolder_suffixes:
to_move = all_children
for name in to_move:
src = os.path.join(input_root, name)
dst = os.path.join(staging_dir, name)
if os.path.exists(dst):
raise FileExistsError(f"staging 目标已存在,请先清空或重命名: {dst}")
shutil.move(src, dst)
print(f"[staging] 剪切: {src} -> {dst}")
print(f"[staging] 处理将使用 input_root: {staging_dir}(staging 内将继续按后缀筛选)")
return staging_dir, False
def discover_sequences(input_root: str, subfolder_suffixes: Optional[List[str]] = None) -> List[Tuple[str, str]]:
sequences = discover_input_sequences(input_root, suffixes=subfolder_suffixes)
return [(sequence.name, sequence.path) for sequence in sequences]
def normalize_config_sequences(raw_sequences: List[object]) -> List[Tuple[str, str]]:
sequences: List[Tuple[str, str]] = []
for item in raw_sequences:
if isinstance(item, dict):
name = str(item.get("name", "")).strip()
raw_path = str(item.get("path", "")).strip()
elif isinstance(item, (list, tuple)) and len(item) >= 2:
name = str(item[0]).strip()
raw_path = str(item[1]).strip()
else:
raise ValueError(f"sequences 项必须是对象或 [name, path]: {item}")
if not raw_path:
raise ValueError(f"sequences 缺少 path: {item}")
sequences.append((name, resolve_runtime_path(raw_path)))
return sequences
def process_sequence(sequence_name: str, sequence_input_dir: str, output_root: str, config: dict) -> None:
input_sequence_name = sequence_name if sequence_name else os.path.basename(os.path.normpath(sequence_input_dir))
stage_name = extract_stage_name(sequence_name, sequence_input_dir)
level1_dir, level2_dir = extract_output_subdirs(sequence_name, sequence_input_dir)
copy_buffers = config["copy_buffers"]
combinations = config["combinations"]
workers = config.get("workers", 0)
sequence_output_dir = os.path.join(output_root, level1_dir, level2_dir)
os.makedirs(sequence_output_dir, exist_ok=True)
file_list = [f for f in os.listdir(sequence_input_dir) if f.lower().endswith(".exr")]
grouped_files = group_buffers_by_name(file_list)
if not grouped_files:
print(f"[跳过] 序列 {sequence_name or '<root>'} 未找到可处理帧")
return
print(
f"处理序列: {sequence_name or '<root>'},stage_name: {stage_name},"
f"输出目录: {level1_dir}/{level2_dir},帧数: {len(grouped_files)}"
)
tasks = [
(
group_id,
files,
sequence_input_dir,
sequence_output_dir,
stage_name,
input_sequence_name,
copy_buffers,
combinations,
)
for group_id, files in grouped_files.items()
]
max_workers = None if workers == 0 else workers
with ProcessPoolExecutor(max_workers=max_workers) as executor:
list(tqdm(executor.map(process_group, tasks), total=len(tasks), desc=sequence_name or "root"))
def build_sequence_lookup(sequences: List[Tuple[str, str]]) -> Dict[str, str]:
return {name: path for name, path in sequences if name}
def build_merge_frame_map(
target_frame_ids: List[str],
overlay_frame_ids: List[str],
merge_config: MergeSequenceConfig,
) -> Dict[str, str]:
eligible_target = [
frame_id for frame_id in sort_frame_ids(target_frame_ids) if int(frame_id) >= merge_config.target_start_frame
]
eligible_overlay = [
frame_id for frame_id in sort_frame_ids(overlay_frame_ids) if int(frame_id) >= merge_config.overlay_start_frame
]
frame_map: Dict[str, str] = {}
target_index = 0
overlay_index = 0
while target_index < len(eligible_target) and overlay_index < len(eligible_overlay):
target_frame_id = eligible_target[target_index]
overlay_frame_id = eligible_overlay[overlay_index]
frame_map[target_frame_id] = overlay_frame_id
if merge_config.frame_limit is not None and len(frame_map) >= merge_config.frame_limit:
break
target_index += merge_config.target_frame_step
overlay_index += merge_config.overlay_frame_step
return frame_map
def handle_missing_merge_file(merge_config: MergeSequenceConfig, message: str) -> bool:
if merge_config.missing_behavior == "fail":
raise ValueError(message)
print(f"[merge][skip] {message}")
return False
def merge_single_sequence_pair(
input_root: str,
output_root: str,
sequence_lookup: Dict[str, str],
raw_merge: dict,
) -> None:
merge_config = compile_merge_config(raw_merge)
target_dir = sequence_lookup.get(merge_config.target_sequence)
overlay_dir = sequence_lookup.get(merge_config.overlay_sequence)
if not target_dir:
raise ValueError(f"merge_sequences 找不到 target_sequence: {merge_config.target_sequence}")
if not overlay_dir:
raise ValueError(f"merge_sequences 找不到 overlay_sequence: {merge_config.overlay_sequence}")
output_level1, output_level2 = extract_output_subdirs(merge_config.output_sequence_name, target_dir)
stage_name = extract_stage_name(merge_config.output_sequence_name, target_dir)
sequence_output_dir = os.path.join(output_root, output_level1, output_level2)
os.makedirs(sequence_output_dir, exist_ok=True)
target_files = [f for f in os.listdir(target_dir) if f.lower().endswith(".exr")]
overlay_files = [f for f in os.listdir(overlay_dir) if f.lower().endswith(".exr")]
target_groups = group_buffers_by_name(target_files)
overlay_groups = group_buffers_by_name(overlay_files)
if not target_groups:
raise ValueError(f"merge_sequences: target_sequence 未找到可处理帧: {merge_config.target_sequence}")
if not overlay_groups:
raise ValueError(f"merge_sequences: overlay_sequence 未找到可处理帧: {merge_config.overlay_sequence}")
frame_map = build_merge_frame_map(list(target_groups.keys()), list(overlay_groups.keys()), merge_config)
print(
f"[merge] {merge_config.target_sequence} <- {merge_config.overlay_sequence},"
f"映射帧数: {len(frame_map)},输出目录: {output_level1}/{output_level2}"
)
written_files = 0
replaced_files = 0
for target_frame_id in sort_frame_ids(list(target_groups.keys())):
target_group_files = target_groups[target_frame_id]
overlay_frame_id = frame_map.get(target_frame_id)
overlay_group_files = overlay_groups.get(overlay_frame_id, []) if overlay_frame_id else []
for mapping in merge_config.buffer_mappings:
source_dir = target_dir
source_sequence_name = merge_config.target_sequence
source_group_files = target_group_files
source_keyword = mapping.target_keyword
if overlay_frame_id and mapping.overlay_keyword is not None:
overlay_source = select_group_file(
overlay_group_files,
mapping.overlay_keyword,
merge_config.overlay_sequence,
)
if overlay_source:
source_dir = overlay_dir
source_sequence_name = merge_config.overlay_sequence
source_group_files = overlay_group_files
source_keyword = mapping.overlay_keyword
replaced_files += 1
else:
should_continue = handle_missing_merge_file(
merge_config,
(
f"overlay 帧缺少匹配文件: sequence={merge_config.overlay_sequence}, "
f"frame={overlay_frame_id}, keyword={mapping.overlay_keyword or '<single-file>'}"
),
)
if not should_continue:
overlay_frame_id = None
selected_file = select_group_file(source_group_files, source_keyword, source_sequence_name)
if not selected_file:
should_continue = handle_missing_merge_file(
merge_config,
(
f"target 帧缺少匹配文件: sequence={merge_config.target_sequence}, "
f"frame={target_frame_id}, keyword={mapping.target_keyword or '<single-file>'}"
),
)
if not should_continue:
continue
src_path = os.path.join(source_dir, selected_file)
dst_path = os.path.join(sequence_output_dir, f"{stage_name}{mapping.output_suffix}.{target_frame_id}.exr")
shutil.copyfile(src_path, dst_path)
written_files += 1
print(
f"[merge] 完成: output_sequence={merge_config.output_sequence_name}, "
f"written_files={written_files}, replaced_files={replaced_files}"
)
def run_merge_sequences(input_root: str, output_root: str, sequences: List[Tuple[str, str]], config: dict) -> None:
merge_sequences = config.get("merge_sequences", [])
if not merge_sequences:
return
sequence_lookup = build_sequence_lookup(sequences)
for raw_merge in merge_sequences:
merge_single_sequence_pair(input_root, output_root, sequence_lookup, raw_merge)
def run(config_path: str) -> None:
config = load_config(config_path)
input_root = resolve_runtime_path(config["input_root"])
output_root = resolve_runtime_path(config["output_root"])
os.makedirs(output_root, exist_ok=True)
suffixes = config.get("subfolder_suffixes")
if isinstance(suffixes, list) and len(suffixes) == 0:
suffixes = None
print(f"配置: {config_path}")
if suffixes:
print(f"子文件夹后缀筛选: {suffixes}")
configured_sequences = config.get("sequences") or []
if configured_sequences:
sequences = normalize_config_sequences(configured_sequences)
print(f"使用配置传入序列数: {len(sequences)}")
elif config.get("relocate_input_before_run"):
staging_dir = resolve_input_staging_dir(config)
print(f"[staging] 剪切目标目录: {staging_dir}")
input_root, is_single_sequence = relocate_input_to_staging(input_root, staging_dir, suffixes)
config["input_root"] = input_root
if is_single_sequence:
sequences = discover_sequences(input_root, subfolder_suffixes=None)
else:
sequences = discover_sequences(input_root, subfolder_suffixes=suffixes)
else:
sequences = discover_sequences(input_root, subfolder_suffixes=suffixes)
print(f"找到序列数: {len(sequences)}")
if not sequences:
print(
"[提示] 无待处理序列:请检查 input_root 下是否有子文件夹,"
"或 subfolder_suffixes 是否过严导致无匹配。"
)
return
if config["copy_buffers"] or config["combinations"]:
for sequence_name, sequence_input_dir in sequences:
process_sequence(sequence_name, sequence_input_dir, output_root, config)
run_merge_sequences(input_root, output_root, sequences, config)
print("全部处理完成")
def run_from_cli(default_config_name: Optional[str] = None) -> None:
parser = argparse.ArgumentParser(description="EXR 序列处理工具(配置驱动)")
parser.add_argument("--config", help="配置文件路径(json)")
parser.add_argument("--config-name", help="配置名(不带后缀),从 config-dir 中查找")
parser.add_argument("--config-dir", default=str(SCRIPT_DIR / "configs"), help="配置目录,默认: process_exr/configs")
parser.add_argument("--list-configs", action="store_true", help="列出可用配置并退出")
args = parser.parse_args()
config_dir = resolve_cli_path(args.config_dir)
config_path_arg = resolve_cli_path(args.config) if args.config else None
if args.list_configs:
names = list_configs(config_dir)
if not names:
print("未找到配置文件")
return
print("可用配置:")
for name in names:
print(f"- {name}")
return
config_path = resolve_config_path(
config_dir=config_dir,
config=config_path_arg,
config_name=args.config_name,
default_config_name=default_config_name,
)
run(config_path)
if __name__ == "__main__":
run_from_cli()