-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetaFiller.py
More file actions
2642 lines (2211 loc) · 97.5 KB
/
Copy pathMetaFiller.py
File metadata and controls
2642 lines (2211 loc) · 97.5 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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# MetaFiller.py
# DaVinci Resolve script
# Purpose: Read continuity CSV/XLSX and write clip metadata into Resolve Media Pool clips.
import os
import sys
# Redirect stdout/stderr safely for debugging Resolve crashes
try:
log_file = open(r"d:/04_ACTIVE_WORKBENCH/MetaFiller/metafiller_debug.log", "w", encoding="utf-8", buffering=1)
sys.stdout = log_file
sys.stderr = log_file
except Exception:
pass
import csv
import re
import glob
import datetime
import traceback
import json
import threading
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
def _load_resolve_module():
"""
Import DaVinciResolveScript robustly.
"""
try:
import DaVinciResolveScript as dvr_script # noqa
return dvr_script
except ImportError:
pass
module_path = os.environ.get("RESOLVE_SCRIPT_API")
candidate_dirs = []
if module_path:
candidate_dirs.append(os.path.join(module_path, "Modules"))
if sys.platform.startswith("win"):
program_data = os.environ.get("PROGRAMDATA", r"C:\ProgramData")
candidate_dirs.append(
os.path.join(
program_data,
"Blackmagic Design",
"DaVinci Resolve",
"Support", "Developer", "Scripting", "Modules",
)
)
elif sys.platform == "darwin":
candidate_dirs.append(
"/Library/Application Support/Blackmagic Design/"
"DaVinci Resolve/Developer/Scripting/Modules"
)
else: # Linux
candidate_dirs.append(
"/opt/resolve/Developer/Scripting/Modules"
)
candidate_dirs.append(
"/home/resolve/Developer/Scripting/Modules"
)
for d in candidate_dirs:
if d and os.path.isdir(d) and d not in sys.path:
sys.path.append(d)
try:
import DaVinciResolveScript as dvr_script # noqa
return dvr_script
except ImportError as e:
raise ImportError(
f"Could not import DaVinciResolveScript. Original error: {e}"
)
dvr_script = _load_resolve_module()
# =========================
# SETTINGS MANAGEMENT
# =========================
SETTINGS_PATH = r"d:\04_ACTIVE_WORKBENCH\MetaFiller\metafiller_settings.json"
def load_settings():
default_dir = r"D:\04_ACTIVE_WORKBENCH\PSA_Kolektif\02_Project_Files\Continuity_Logs"
if not os.path.exists(default_dir):
default_dir = r"d:\04_ACTIVE_WORKBENCH\MetaFiller"
defaults = {
"last_csv_path": "",
"last_dir": default_dir,
"scan_scope": "SELECTED_BIN_WITH_SUBFOLDERS",
"bin_filter_string": "Raw_Camera",
"overwrite": False,
"apply_audio": True,
"timeline_group_by": "Scene",
"timeline_include": "Good Takes Only",
"timeline_order": "Scene > Shot > Take > Camera",
"timeline_bin_mode": "Current Bin",
"timeline_custom_bin_path": "Master/05_Timeline_Comp",
}
if os.path.exists(SETTINGS_PATH):
try:
with open(SETTINGS_PATH, "r") as f:
data = json.load(f)
defaults.update(data)
except Exception:
pass
return defaults
def save_settings(settings):
try:
os.makedirs(os.path.dirname(SETTINGS_PATH), exist_ok=True)
with open(SETTINGS_PATH, "w") as f:
json.dump(settings, f, indent=4)
except Exception:
pass
# =========================
# CONSTANTS & HEADERS
# =========================
# Resolve metadata field mapping.
METADATA_MAP = {
"SCENE": "Scene",
"TAKE": "Take",
"SHOT": "Shot",
"CAMERA": "Camera #",
"NOTES": "Comments",
"SHOT_SIZE": "Shot Type",
}
# Clip color mapping based on GOOD_NG value.
# Resolve supports: Orange, Apricot, Yellow, Lime, Olive, Green,
# Teal, Navy, Blue, Purple, Violet, Pink, Tan, Beige, Brown, Chocolate
CLIP_COLOR_MAP = {
"G": "Green",
"GOOD": "Green",
"NG": "Red", # Red is not in official list; we use Pink as closest
"NF": "Yellow", # Not Focused / technical fail
}
# Resolve does not have a "Red" clip color. Use these fallbacks:
CLIP_COLOR_FALLBACK = {
"Red": "Pink",
}
# Flag color mapping for GOOD/NG markers.
# Resolve flag colors: Blue, Cyan, Green, Yellow, Red, Pink, Purple, Fuchsia, Rose, Lavender, Sky, Mint, Lemon, Sand, Cocoa, Cream
FLAG_COLOR_MAP = {
"G": "Green",
"GOOD": "Green",
"NG": "Red",
"NF": "Yellow",
}
# Deterministic scene colors: cycle through these for scene-based coloring.
SCENE_COLOR_PALETTE = [
"Orange", "Apricot", "Yellow", "Lime", "Olive", "Green",
"Teal", "Navy", "Blue", "Purple", "Violet", "Pink",
"Tan", "Beige", "Brown", "Chocolate",
]
EXTRA_FIELDS_FOR_KEYWORDS = [
"GOOD_NG",
"SHOT_SIZE",
"LENS",
"FSTOP",
"AUDIO_GNG",
"AUDIO_NAME",
]
REQUIRED_COLUMNS = [
"SCENE",
"TAKE",
"SHOT",
"CLIP_NAME",
"CAMERA",
"GOOD_NG",
"SHOT_SIZE",
"LENS",
"FSTOP",
"AUDIO_GNG",
"AUDIO_NAME",
"NOTES",
]
_MIN_HEADER_MATCHES = 3
HEADER_ALIASES = {
"SCENE": "SCENE",
"SCENENO": "SCENE",
"TAKE": "TAKE",
"TAKENO": "TAKE",
"SHOT": "SHOT",
"SHOTNO": "SHOT",
"CLIPNAME": "CLIP_NAME",
"CLIP": "CLIP_NAME",
"FILENAME": "CLIP_NAME",
"CLIPNAMEFIXED": "CLIP_NAME_FIXED",
"CLIPNAMEFIX": "CLIP_NAME_FIXED",
"CLIPFIXED": "CLIP_NAME_FIXED",
"CLIPFIX": "CLIP_NAME_FIXED",
"CAMERA": "CAMERA",
"CAM": "CAMERA",
"GOODNG": "GOOD_NG",
"GOODBNG": "GOOD_NG",
"SHOTSIZE": "SHOT_SIZE",
"SIZE": "SHOT_SIZE",
"LENS": "LENS",
"FSTOP": "FSTOP",
"TSTOP": "FSTOP",
"APERTURE": "FSTOP",
"AUDIOGNG": "AUDIO_GNG",
"AUDIOGOODNG": "AUDIO_GNG",
"AUDIONAME": "AUDIO_NAME",
"AUDIOFILE": "AUDIO_NAME",
"CATATAN": "NOTES",
"NOTES": "NOTES",
"NOTE": "NOTES",
"KETERANGAN": "NOTES",
"SHOOTDAY": "SHOOT_DAY",
"SHOOT_DAY": "SHOOT_DAY",
"DAY": "SHOOT_DAY",
"PRODUCTIONDAY": "SHOOT_DAY",
}
# =========================
# HELPERS
# =========================
def normalize_clip_name(name):
if not name:
return ""
# Strip spaces from inside the name so typos like "C1632 . MP 4" become "C1632.MP4"
return re.sub(r"\s+", "", os.path.basename(str(name))).upper()
def natural_sort_key(s):
if not s:
return []
return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', str(s))]
def sanitize_group_name(name):
if not name:
return "Unknown"
if str(name).isdigit():
return f"{int(name):02d}"
return re.sub(r"[^A-Za-z0-9_\-]", "_", str(name)).strip("_")
def get_group_key_and_name(row, group_by):
if group_by == "Entire CSV":
return "All", "Comp_All"
elif group_by == "Scene":
val = row.get("SCENE", "").strip()
name_part = sanitize_group_name(val)
return val, f"Comp_Scene_{name_part}"
elif group_by == "Shoot Day":
val = row.get("SHOOT_DAY", "").strip()
name_part = sanitize_group_name(val)
return val, f"Comp_Day_{name_part}"
elif group_by == "Camera":
val = row.get("CAMERA", "").strip()
name_part = sanitize_group_name(val)
return val, f"Comp_Cam_{name_part}"
return "All", "Comp_All"
def get_unique_timeline_name(project, base_name):
existing_names = set()
get_count = getattr(project, "GetTimelineCount", None)
get_by_idx = getattr(project, "GetTimelineByIndex", None)
if get_count and callable(get_count) and get_by_idx and callable(get_by_idx):
try:
timeline_count = get_count()
for i in range(1, timeline_count + 1):
t = get_by_idx(i)
if t:
existing_names.add(t.GetName().upper())
except Exception:
pass
if base_name.upper() not in existing_names:
return base_name
ts = timestamp()
candidate = f"{base_name}_{ts}"
if candidate.upper() not in existing_names:
return candidate
idx = 1
while f"{base_name}_{ts}_{idx}".upper() in existing_names:
idx += 1
return f"{base_name}_{ts}_{idx}"
def parse_audio_names(raw_name):
"""
Parses audio names from CSV (e.g. REC1/REC2/S24/SH4/TK1)
Returns a list of expected base names (e.g. ['REC1S24SH4TK1', 'REC2S24SH4TK1'])
"""
raw_name = clean_value(raw_name).upper()
if not raw_name or raw_name == "MOS":
return []
# Split by slash and remove empty parts
parts = [p.strip() for p in raw_name.split("/") if p.strip()]
if not parts:
return []
mics = []
suffix_parts = []
for part in parts:
# Check if part is a mic identifier (e.g. REC1, REC 2, CAMA)
# It's a mic if it starts with REC or CAM, or if we already have some mics and haven't hit scene yet.
# But simply looking for "REC" or just collecting early parts until we hit "S" or "SH" is safer.
if part.startswith("REC") or part.startswith("CAM"):
mics.append(part.replace(" ", ""))
elif part.startswith("S") or part.startswith("SH") or part.startswith("TK") or part.startswith("PA"):
suffix_parts.append(part.replace(" ", ""))
else:
# If we don't recognize it, just assume it's part of the suffix if mics already exist
if not mics:
mics.append(part.replace(" ", ""))
else:
suffix_parts.append(part.replace(" ", ""))
if not mics:
return ["".join(parts).replace(" ", "")]
suffix_str = "".join(suffix_parts)
return [f"{mic}{suffix_str}" for mic in mics]
def get_audio_track_idx(base, expected_bases):
if not base:
return 3
match = re.search(r"REC\s*(\d+)", base, re.IGNORECASE)
if match:
mic_num = int(match.group(1))
return 3 + (mic_num - 1)
try:
idx = expected_bases.index(base)
return 3 + idx
except ValueError:
return 3
def parse_scene_shot_take_from_audio_name(audio_name_raw):
raw_name = clean_value(audio_name_raw).upper()
if not raw_name:
return "", "", ""
parts = [p.strip() for p in raw_name.split("/") if p.strip()]
sc = ""
sh = ""
tk = ""
for p in parts:
if p.startswith("S") and not p.startswith("SH"):
sc = p[1:]
elif p.startswith("SH"):
sh = p[2:]
elif p.startswith("TK"):
tk = p[2:]
return sc, sh, tk
def determine_audio_category(path_str, fallback="Dialogue"):
if not path_str:
return fallback
path_lower = str(path_str).lower()
if any(k in path_lower for k in ["sfx", "sound effect", "effect", "fx"]):
return "Effect"
elif any(k in path_lower for k in ["music", "bgm", "ost"]):
return "Music"
elif any(k in path_lower for k in ["silence", "mos"]):
return "Silence"
elif any(k in path_lower for k in ["dialogue", "dialog", "voiceover", "vo"]):
return "Dialogue"
return fallback
def timecode_to_frames(tc_str, fps):
if not tc_str:
return 0
parts = tc_str.strip().split(":")
if len(parts) != 4:
return 0
try:
h, m, s, f = int(parts[0]), int(parts[1]), int(parts[2]), int(parts[3])
total_frames = int(((h * 3600) + (m * 60) + s) * fps + f)
return total_frames
except Exception:
return 0
def get_clip_duration_frames(clip, fps):
try:
val = clip.GetClipProperty("Frames")
if val and str(val).isdigit():
return int(val)
except Exception:
pass
try:
val_dur = clip.GetClipProperty("Duration")
if val_dur:
return timecode_to_frames(val_dur, fps)
except Exception:
pass
return 0
def clean_value(value):
if value is None:
return ""
return str(value).strip()
def timestamp():
return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
def detect_day_number(path):
name = os.path.basename(str(path))
match = re.search(r"day\s*0*(\d+)", name, re.IGNORECASE)
if match:
return int(match.group(1))
return None
def get_resolve():
injected = globals().get("resolve")
if injected is not None:
return injected
injected_fusion = globals().get("fusion")
if injected_fusion is not None:
try:
resolve = injected_fusion.GetResolve()
if resolve is not None:
return resolve
except Exception:
pass
try:
import builtins
if getattr(builtins, "resolve", None) is not None:
return builtins.resolve
except Exception:
pass
try:
import builtins
if getattr(builtins, "fusion", None) is not None:
resolve = builtins.fusion.GetResolve()
if resolve is not None:
return resolve
except Exception:
pass
resolve = dvr_script.scriptapp("Resolve")
if resolve is not None:
return resolve
raise RuntimeError(
"Could not connect to DaVinci Resolve.\n"
"Ensure Resolve is running and scripting is enabled."
)
def find_or_create_folder(media_pool, path_str):
root = media_pool.GetRootFolder()
parts = [p.strip() for p in path_str.replace("\\", "/").split("/") if p.strip()]
if not parts:
return root
if parts[0].lower() in ("master", "root"):
current_folder = root
parts = parts[1:]
else:
current_folder = root
for part in parts:
found = None
for sub in current_folder.GetSubFolderList():
if sub.GetName() == part:
found = sub
break
if found:
current_folder = found
else:
new_folder = media_pool.AddSubFolder(current_folder, part)
if not new_folder:
return current_folder
current_folder = new_folder
return current_folder
def get_all_folder_paths():
try:
resolve = get_resolve()
if not resolve:
return ["Master"]
project = resolve.GetProjectManager().GetCurrentProject()
if not project:
return ["Master"]
media_pool = project.GetMediaPool()
root = media_pool.GetRootFolder()
paths = []
def walk(folder, current_path):
paths.append(current_path)
for sub in folder.GetSubFolderList():
walk(sub, current_path + "/" + sub.GetName())
walk(root, "Master")
return paths
except Exception:
return ["Master"]
def collect_clips_with_paths(media_pool, scan_scope, filter_str=None):
if not media_pool:
return {}, {}, {}
try:
root_folder = media_pool.GetRootFolder()
if not root_folder:
return {}, {}, {}
except Exception:
return {}, {}, {}
try:
current_folder = media_pool.GetCurrentFolder()
if not current_folder:
current_folder = root_folder
except Exception:
current_folder = root_folder
current_folder_path = []
def find_path(curr, target, current_accum):
if curr.GetUniqueId() == target.GetUniqueId():
return current_accum
for sub in curr.GetSubFolderList():
res = find_path(sub, target, current_accum + [sub.GetName()])
if res is not None:
return res
return None
if scan_scope in ("CURRENT_SELECTED_BIN", "SELECTED_BIN_WITH_SUBFOLDERS"):
if current_folder.GetUniqueId() == root_folder.GetUniqueId():
current_folder_path = ["Master"]
else:
path_tail = find_path(root_folder, current_folder, [])
if path_tail is not None:
current_folder_path = ["Master"] + path_tail
else:
current_folder_path = [current_folder.GetName()]
all_clips = {}
def walk_folder(folder, path_list, recursive):
path_str = "/".join(path_list)
for clip in folder.GetClipList():
try:
if clip.GetClipProperty("Type") == "Timeline":
continue
except Exception:
pass
clip_name = normalize_clip_name(clip.GetName())
if not clip_name:
continue
all_clips.setdefault(clip_name, []).append((clip, path_str))
if recursive:
for sub in folder.GetSubFolderList():
walk_folder(sub, path_list + [sub.GetName()], recursive)
if scan_scope == "ENTIRE_MEDIA_POOL":
walk_folder(root_folder, ["Master"], recursive=True)
elif scan_scope == "CURRENT_SELECTED_BIN":
walk_folder(current_folder, current_folder_path, recursive=False)
elif scan_scope == "SELECTED_BIN_WITH_SUBFOLDERS":
walk_folder(current_folder, current_folder_path, recursive=True)
elif scan_scope == "BIN_PATH_CONTAINS_FILTER":
walk_folder(root_folder, ["Master"], recursive=True)
filtered_clips = {}
filter_upper = filter_str.upper() if filter_str else ""
for name, clip_list in all_clips.items():
matching_items = []
for clip, path_str in clip_list:
if filter_upper in path_str.upper():
matching_items.append((clip, path_str))
if matching_items:
filtered_clips[name] = matching_items
all_clips = filtered_clips
clips_by_name = {}
duplicates = {}
clip_paths = {}
for name, items in all_clips.items():
if len(items) == 1:
clip, path_str = items[0]
clips_by_name[name] = clip
clip_paths[clip.GetUniqueId()] = path_str
else:
duplicates[name] = items
for clip, path_str in items:
clip_paths[clip.GetUniqueId()] = path_str
return clips_by_name, duplicates, clip_paths
def validate_day_camera(row, day_number, bin_path, camera_value):
warnings = []
row_day = row.get("SHOOT_DAY")
target_day = None
if row_day:
match = re.search(r"\d+", str(row_day))
if match:
target_day = int(match.group(0))
elif day_number is not None:
target_day = day_number
if target_day is not None:
day_patterns = [
rf"\bDAY\s*0*{target_day}\b",
rf"\bDAY_0*{target_day}\b",
rf"\bDAY0*{target_day}\b",
]
matched_day = False
for pat in day_patterns:
if re.search(pat, bin_path, re.IGNORECASE):
matched_day = True
break
if not matched_day:
warnings.append(f"Day mismatch: expected Day {target_day} in bin path")
if camera_value:
cam_clean = str(camera_value).strip().upper()
cam_patterns = [
rf"\bCAM\s*[-_]*{re.escape(cam_clean)}\b",
rf"\b{re.escape(cam_clean)}\b",
]
matched_cam = False
for pat in cam_patterns:
if re.search(pat, bin_path, re.IGNORECASE):
matched_cam = True
break
if not matched_cam:
warnings.append(f"Camera mismatch: expected Camera {cam_clean} in bin path")
return warnings
def _normalize_header(value):
if value is None:
return ""
return re.sub(r"[^A-Za-z0-9]", "", str(value)).upper()
def _map_header_row(cells):
mapping = {}
for col_index, cell in enumerate(cells):
norm = _normalize_header(cell)
if not norm:
continue
canonical = HEADER_ALIASES.get(norm)
if canonical and canonical not in mapping.values():
mapping[col_index] = canonical
return mapping
def _find_header_mapping(grid, source_name):
best_index = None
best_mapping = {}
for index, cells in enumerate(grid):
mapping = _map_header_row(cells)
if "CLIP_NAME" not in mapping.values() and "CLIP_NAME_FIXED" not in mapping.values():
continue
if len(mapping) > len(best_mapping):
best_mapping = mapping
best_index = index
if best_index is None or len(best_mapping) < _MIN_HEADER_MATCHES:
raise ValueError(
f"Could not find a header row in {source_name}.\n"
"Expected a row containing columns like CLIP NAME, SCENE, TAKE, SHOT, CAMERA, etc."
)
found = set(best_mapping.values())
required_cols_to_check = [c for c in REQUIRED_COLUMNS if c != "CLIP_NAME"]
missing = [c for c in required_cols_to_check if c not in found]
if "CLIP_NAME" not in found and "CLIP_NAME_FIXED" not in found:
missing.append("CLIP_NAME")
if missing:
raise ValueError(
f"{source_name} header row was found but is missing column(s): "
+ ", ".join(missing)
)
return best_index, best_mapping
def _rows_from_grid(grid, source_name):
header_index, mapping = _find_header_mapping(grid, source_name)
rows = []
for offset, cells in enumerate(grid[header_index + 1:], start=1):
if not cells or all(
c is None or str(c).strip() == "" for c in cells
):
continue
row = {}
for col_index, canonical in mapping.items():
value = cells[col_index] if col_index < len(cells) else ""
row[canonical] = clean_value(value)
row["_CSV_ROW_NUMBER"] = header_index + 1 + offset
rows.append(row)
return rows
def _grid_from_csv(path):
last_error = None
for encoding in ("utf-8-sig", "cp1252", "latin-1"):
try:
with open(path, "r", encoding=encoding, newline="") as f:
return [row for row in csv.reader(f)]
except UnicodeDecodeError as e:
last_error = e
continue
raise RuntimeError(
f"Could not decode CSV: {path}. Error: {last_error}"
)
def _grid_from_xlsx(path):
try:
import openpyxl
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
sheet = wb.active
grid = []
for row in sheet.iter_rows(values_only=True):
grid.append([str(val) if val is not None else "" for val in row])
wb.close()
return grid
except Exception as e:
raise RuntimeError(f"Could not read Excel file {path}. Error: {e}")
def get_sheet_names(path):
"""Return list of sheet names from an XLSX file, or ['CSV'] for CSV files."""
_, ext = os.path.splitext(path)
if ext.lower() == ".xlsx":
import openpyxl
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
names = list(wb.sheetnames)
wb.close()
return names
return ["CSV"]
def read_log_rows(path, selected_sheets=None):
if not os.path.exists(path):
raise FileNotFoundError(f"Log file not found: {path}")
_, ext = os.path.splitext(path)
if ext.lower() == ".xlsx":
import openpyxl
try:
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
all_rows = []
global_row_counter = 1
for sheet_name in wb.sheetnames:
if selected_sheets is not None and sheet_name not in selected_sheets:
continue
sheet = wb[sheet_name]
grid = []
for row in sheet.iter_rows(values_only=True):
grid.append([str(val) if val is not None else "" for val in row])
try:
sheet_rows = _rows_from_grid(grid, f"XLSX Sheet '{sheet_name}'")
for r in sheet_rows:
r["_SHEET_NAME"] = sheet_name
r["_GLOBAL_ROW_NUMBER"] = global_row_counter
global_row_counter += 1
all_rows.extend(sheet_rows)
except ValueError:
# Skip sheets that don't match our headers
pass
wb.close()
if not all_rows:
raise ValueError("Could not find a valid header row in any of the Excel sheets.")
return all_rows
except Exception as e:
raise RuntimeError(f"Could not read Excel file {path}. Error: {e}")
else:
grid = _grid_from_csv(path)
rows = _rows_from_grid(grid, "CSV")
for idx, r in enumerate(rows, start=1):
r["_SHEET_NAME"] = "CSV"
r["_GLOBAL_ROW_NUMBER"] = idx
return rows
def build_keywords(row):
parts = []
for field in EXTRA_FIELDS_FOR_KEYWORDS:
value = clean_value(row.get(field))
if value:
parts.append(f"{field}={value}")
return ", ".join(parts)
def build_metadata_payload(row):
metadata = {}
for csv_field, resolve_field in METADATA_MAP.items():
if resolve_field == "Comments":
continue
value = clean_value(row.get(csv_field))
if value:
metadata[resolve_field] = value
# Map Good/NG directly to Description
good_ng = clean_value(row.get("GOOD_NG")).upper()
if good_ng in ("G", "GOOD"):
metadata["Description"] = "GOOD"
elif good_ng in ("NG", "REJECTED"):
metadata["Description"] = "NG"
else:
metadata["Description"] = ""
# Keywords should always be empty
metadata["Keywords"] = ""
# Comments should ONLY contain CATATAN (NOTES) value
original_notes = clean_value(row.get("NOTES"))
metadata["Comments"] = original_notes
return metadata
def apply_clip_color(clip, good_ng_value):
"""
Set clip color based on GOOD_NG value.
Returns: (success_bool, color_applied_or_error_str)
"""
val = str(good_ng_value).strip().upper()
color = CLIP_COLOR_MAP.get(val)
if not color:
return True, "NO_MAPPING"
# Resolve might not have exact color; apply fallback
color = CLIP_COLOR_FALLBACK.get(color, color)
try:
ok = clip.SetClipColor(color)
return bool(ok), color
except Exception as e:
return False, f"ERROR: {e}"
def apply_clip_flag(clip, good_ng_value):
"""
Add a colored flag to clip based on GOOD_NG value.
Returns: (success_bool, flag_color_or_error_str)
"""
val = str(good_ng_value).strip().upper()
flag_color = FLAG_COLOR_MAP.get(val)
if not flag_color:
return True, "NO_MAPPING"
try:
ok = clip.AddFlag(flag_color)
return bool(ok), flag_color
except Exception as e:
return False, f"ERROR: {e}"
def set_metadata_safely(clip, metadata):
results = {}
for key, value in metadata.items():
try:
ok = clip.SetMetadata(key, value)
results[key] = bool(ok)
except Exception as e:
results[key] = f"ERROR: {e}"
return results
def write_report(report_path, report_rows):
import openpyxl
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "MetaFiller Report"
headers = [
"status",
"sheet_name",
"csv_row",
"clip_name",
"message",
"metadata_attempted",
"field_results",
]
# Colors
header_fill = PatternFill(start_color="5B9BD5", end_color="5B9BD5", fill_type="solid") # Soft blue
header_font = Font(name="Plus Jakarta Sans", size=11, bold=True, color="FFFFFF")
missing_fill = PatternFill(start_color="F2C4A2", end_color="F2C4A2", fill_type="solid") # Orange/light peach
missing_font = Font(name="Plus Jakarta Sans", size=10, color="000000")
normal_font = Font(name="Plus Jakarta Sans", size=10)
thin_border = Border(
left=Side(style='thin', color='D9D9D9'),
right=Side(style='thin', color='D9D9D9'),
top=Side(style='thin', color='D9D9D9'),
bottom=Side(style='thin', color='D9D9D9')
)
# Write Headers
for col_idx, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col_idx, value=header)
cell.fill = header_fill
cell.font = header_font
cell.alignment = Alignment(horizontal="center", vertical="center")
cell.border = thin_border
# Write Rows
for row_idx, row in enumerate(report_rows, 2):
is_missing = False
# Check if the row contains missing keywords
status_val = str(row.get("status", "")).upper()
msg_val = str(row.get("message", "")).lower()
meta_val = str(row.get("metadata_attempted", "")).lower()
if "MISSING" in status_val or "FAILED" in status_val or "missing" in msg_val or "missing" in meta_val or "not found" in msg_val or "not found" in meta_val:
is_missing = True
for col_idx, header in enumerate(headers, 1):
val = row.get(header, "")
# Convert dictionary/list to string for metadata_attempted and field_results
if isinstance(val, (dict, list)):
val = str(val)
cell = ws.cell(row=row_idx, column=col_idx, value=val)
cell.border = thin_border
if is_missing:
cell.fill = missing_fill
cell.font = missing_font
else:
cell.font = normal_font
if header in ("csv_row", "status"):
cell.alignment = Alignment(horizontal="center")
# Add spacing
start_summary_row = len(report_rows) + 4
# Summary Header
summary_title_fill = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid") # Dark Blue
summary_title_font = Font(name="Plus Jakarta Sans", size=11, bold=True, color="FFFFFF")
ws.merge_cells(start_row=start_summary_row, start_column=1, end_row=start_summary_row, end_column=3)
title_cell = ws.cell(row=start_summary_row, column=1, value="SUMMARY METRICS")
title_cell.fill = summary_title_fill
title_cell.font = summary_title_font