File size: 49,149 Bytes
b620472
175adcc
b620472
f15162e
04065a9
175adcc
b620472
 
9007b40
 
 
490d656
 
89b565b
05104b9
fce9bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b94fac
fce9bf7
f15162e
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fce9bf7
fe751ad
 
 
 
 
 
503d4ac
 
 
fe751ad
 
 
503d4ac
fe751ad
 
 
 
503d4ac
fe751ad
 
 
 
 
503d4ac
 
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175adcc
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175adcc
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54639e8
fe751ad
54639e8
 
 
 
 
fe751ad
e9330fa
 
228e117
 
e9330fa
 
228e117
 
 
 
 
e7fbeb6
 
228e117
e9330fa
 
 
 
9007b40
 
 
 
bb7f4db
 
 
 
 
9007b40
 
 
fe751ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490d656
 
89b565b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2426a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490d656
 
 
b2426a5
490d656
 
 
 
89b565b
 
b2426a5
89b565b
b2426a5
 
 
 
 
503d4ac
b2426a5
89b565b
 
 
503d4ac
b2426a5
 
89b565b
 
490d656
 
 
782b3ed
 
 
490d656
782b3ed
 
 
490d656
b2426a5
490d656
 
 
 
 
 
 
782b3ed
 
490d656
 
 
 
 
 
 
 
 
86b188e
490d656
 
 
 
 
 
 
86b188e
 
490d656
 
86b188e
490d656
bab9fee
 
490d656
 
 
 
 
 
 
 
 
 
 
 
503d4ac
86b188e
490d656
 
 
86b188e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
86b188e
 
503d4ac
86b188e
 
 
 
 
 
503d4ac
490d656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5f0585
6eec0dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
6eec0dc
 
 
503d4ac
6eec0dc
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
6eec0dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
6eec0dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5f0585
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
ce1df2f
 
 
 
 
503d4ac
ce1df2f
503d4ac
ce1df2f
 
 
 
 
 
de452b1
ce1df2f
 
 
 
 
503d4ac
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
 
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
ce1df2f
 
 
 
 
 
 
 
 
 
 
 
503d4ac
ce1df2f
89b565b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
89b565b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503d4ac
89b565b
 
 
 
503d4ac
89b565b
 
 
 
 
e7fbeb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
"""
Utility functions
"""
from __future__ import annotations

from src.logger_config import logger, setup_logger
import sys
from pathlib import Path
import subprocess
import os
import uuid
import re
import shutil
import tempfile
from src.config import get_config_value
import json
import traceback
import cv2
import numpy as np
import imagehash
from PIL import Image
from moviepy.editor import VideoFileClip
import tempfile
import librosa

def get_temp_dir(prefix: str = "tmp_") -> Path:
    """
    Creates a temp directory.
    Uses fixed path during test automation if configured.
    """
    if get_config_value("test_automation"):
        base_dir = get_config_value("test_data_directory")
        if not base_dir:
            raise RuntimeError("TEST_DATA_DIRECTORY must be set when TEST_AUTOMATION=true")

        # Ensure base dir exists
        Path(base_dir).mkdir(parents=True, exist_ok=True)

        sub_dir = "output"
        if "download" in prefix:
            sub_dir = "downloads"
            
        path = Path(base_dir) / sub_dir
        path.mkdir(parents=True, exist_ok=True)
        return path

    return Path(tempfile.mkdtemp(prefix=prefix))

def get_video_duration(path: str) -> float:
    """
    Returns the duration of a video file in seconds as a float.
    Uses ffprobe (very fast and accurate).
    """
    cmd = [
        "ffprobe", "-v", "error",
        "-select_streams", "v:0",
        "-show_entries", "format=duration",
        "-of", "json",
        path
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    info = json.loads(result.stdout)
    return float(info["format"]["duration"])

def calculate_video_durations(selected_videos, all_tts_script_segment, word_level_segment, total_duration: float) -> None:
    """
    Calculate and update duration for each video based on word-level segments.
    Uses three approaches in order of preference:
    1. Simple word count matching (if counts align exactly)
    2. Text matching with cleaning (if counts differ slightly)
    3. Fuzzy matching (if words are missing or mismatched)
    """
    try:
        # Get word counts
        all_script_words = all_tts_script_segment.split()

        def clean_word(word: str) -> str:
            return re.sub(r'[^a-zA-Z]', '', word).lower()
        
        cleaned_script_words = [clean_word(w) for w in all_script_words if clean_word(w)]
        cleaned_segment_words = [clean_word(seg.get("word", "")) for seg in word_level_segment if clean_word(seg.get("word", ""))]
        
        logger.debug(f"📊 Original: Script={len(all_script_words)} words, Segments={len(word_level_segment)} words")
        logger.debug(f"📊 Cleaned: Script={len(cleaned_script_words)} words, Segments={len(cleaned_segment_words)} words")
        logger.debug(f"⏱️ Total audio duration: {total_duration}s (starting from 0)")
        
        # APPROACH 1: Exact match (original word counts)
        if len(all_script_words) == len(word_level_segment):
            logger.debug("✅ Using APPROACH 1: Simple word count matching")
            calculate_durations_simple(selected_videos, word_level_segment, total_duration)
        
        # APPROACH 2: Cleaned match (cleaned word counts)
        elif len(cleaned_script_words) == len(cleaned_segment_words):
            logger.debug("✅ Using APPROACH 2: Text matching with cleaning")
            calculate_durations_with_text_matching(selected_videos, word_level_segment, total_duration)
        
        # APPROACH 3: Fuzzy match
        else:
            diff = abs(len(cleaned_script_words) - len(cleaned_segment_words))
            logger.debug(f"⚠️ Word count mismatch after cleaning (diff: {diff})")
            logger.debug("🔍 Using APPROACH 3: Fuzzy matching")
            calculate_durations_with_fuzzy_matching(selected_videos, word_level_segment, total_duration)
            
    except Exception as e:
        logger.error(f"❌ Failed to calculate video durations: {e}")
        traceback.print_exc()
        # Fallback: set equal durations
        equal_duration = total_duration / len(selected_videos)
        for video in selected_videos:
            video["duration"] = round(equal_duration, 2)


def calculate_durations_simple(selected_videos, word_level_segment, total_duration: float) -> None:
    """
    APPROACH 1: Simple sequential matching when word counts align exactly.
    First video always starts at 0, last video always ends at total_duration.
    """
    current_word_index = 0
    
    for i, video in enumerate(selected_videos):
        tts_text = video.get("tts_script_segment", "").strip()
        
        if not tts_text:
            video["duration"] = 0
            continue
            
        word_count = len(tts_text.split())
        
        # Get start time for this segment
        if i == 0:
            start_time = 0.0
        else:
            start_time = word_level_segment[current_word_index]["start_time"]
        
        # Calculate next word index
        next_word_index = current_word_index + word_count
        
        # Get end time
        if i + 1 == len(selected_videos):
            end_time = total_duration
        else:
            if next_word_index < len(word_level_segment):
                end_time = word_level_segment[next_word_index]["start_time"]
            else:
                end_time = total_duration
        
        # Calculate duration
        video["duration"] = round(end_time - start_time, 2)
        logger.debug(f"  Video {i}: [{start_time:.2f}s - {end_time:.2f}s] = {video['duration']}s | '{tts_text[:40]}...'")
        
        # Move to next segment
        current_word_index = next_word_index
    
    # Verify total
    total_calculated = sum(v.get("duration", 0) for v in selected_videos)
    logger.debug(f"✅ Total calculated duration: {total_calculated:.2f}s (expected: {total_duration:.2f}s)")


def calculate_durations_with_text_matching(selected_videos, word_level_segment, total_duration: float) -> None:
    """
    APPROACH 2: Text matching with cleaned/normalized text.
    Handles cases where word counts don't align due to numbers, punctuation, etc.
    First video always starts at 0, last video always ends at total_duration.
    """
    def clean_word(word: str) -> str:
        """Clean a single word - remove numbers, special chars, keep only alpha"""
        return re.sub(r'[^a-zA-Z]', '', word).lower()
    
    # Build cleaned word list from word_level_segment
    cleaned_word_segments = []
    for seg in word_level_segment:
        word = seg.get("word", "")
        cleaned = clean_word(word)
        if cleaned:
            cleaned_word_segments.append({
                "cleaned": cleaned,
                "original": word,
                "start_time": seg.get("start_time", 0),
                "end_time": seg.get("end_time", 0)
            })
    
    logger.debug(f"📝 Cleaned word segments: {len(cleaned_word_segments)} words")
    
    # Track current position in cleaned_word_segments
    current_word_index = 0
    
    for i, video in enumerate(selected_videos):
        tts_text = video.get("tts_script_segment", "").strip()
        
        if not tts_text:
            video["duration"] = 0
            continue
        
        # Clean the video's script segment
        video_words = tts_text.split()
        cleaned_video_words = [clean_word(w) for w in video_words if clean_word(w)]
        
        if not cleaned_video_words:
            video["duration"] = 0
            continue
        
        word_count = len(cleaned_video_words)
        logger.debug(f"  Video {i}: Looking for {word_count} cleaned words starting at index {current_word_index}")
        
        # Get start time
        if i == 0:
            start_time = 0.0
        elif current_word_index < len(cleaned_word_segments):
            start_time = cleaned_word_segments[current_word_index]["start_time"]
        else:
            logger.warning(f"    ⚠️ Out of word segments, using remaining time")
            remaining_videos = len(selected_videos) - i
            remaining_time = total_duration - (cleaned_word_segments[-1]["end_time"] if cleaned_word_segments else 0)
            video["duration"] = round(remaining_time / remaining_videos, 2)
            continue
        
        # Calculate next word index
        next_word_index = current_word_index + word_count
        
        # Get end time
        if i + 1 == len(selected_videos):
            end_time = total_duration
        else:
            if next_word_index < len(cleaned_word_segments):
                end_time = cleaned_word_segments[next_word_index]["start_time"]
            else:
                end_time = total_duration
        
        # Calculate duration
        video["duration"] = round(end_time - start_time, 2)
        logger.debug(f"    ✅ [{start_time:.2f}s - {end_time:.2f}s] = {video['duration']}s | {word_count} words")
        
        # Move to next segment
        current_word_index = next_word_index
    
    # Verify total
    total_calculated = sum(v.get("duration", 0) for v in selected_videos)
    logger.debug(f"✅ Total calculated duration: {total_calculated:.2f}s (expected: {total_duration:.2f}s)")


def calculate_durations_with_fuzzy_matching(selected_videos, word_level_segment, total_duration: float) -> None:
    """
    APPROACH 3: Fuzzy matching with flexible word alignment.
    Handles cases where words are missing, misspelled, or slightly different.
    First video always starts at 0, last video always ends at total_duration.
    """
    from difflib import SequenceMatcher
    
    def clean_word(word: str) -> str:
        """Clean a single word - remove numbers, special chars, keep only alpha"""
        return re.sub(r'[^a-zA-Z]', '', word).lower()
    
    def similarity_ratio(word1: str, word2: str) -> float:
        """Calculate similarity between two words (0.0 to 1.0)"""
        if not word1 or not word2:
            return 0.0
        return SequenceMatcher(None, word1, word2).ratio()
    
    # Build cleaned word list from word_level_segment
    cleaned_word_segments = []
    for seg in word_level_segment:
        word = seg.get("word", "")
        cleaned = clean_word(word)
        if cleaned:
            cleaned_word_segments.append({
                "cleaned": cleaned,
                "original": word,
                "start_time": seg.get("start_time", 0),
                "end_time": seg.get("end_time", 0)
            })
    
    logger.debug(f"📝 Cleaned word segments: {len(cleaned_word_segments)} words")
    
    # Track current position in cleaned_word_segments
    current_word_index = 0
    
    for i, video in enumerate(selected_videos):
        tts_text = video.get("tts_script_segment", "").strip()
        
        if not tts_text:
            video["duration"] = 0
            continue
        
        # Clean the video's script segment
        video_words = tts_text.split()
        cleaned_video_words = [clean_word(w) for w in video_words if clean_word(w)]
        
        if not cleaned_video_words:
            video["duration"] = 0
            continue
        
        word_count = len(cleaned_video_words)
        logger.debug(f"  Video {i}: Fuzzy matching {word_count} words starting at index {current_word_index}")
        
        # Get start time
        if i == 0:
            start_time = 0.0
        elif current_word_index < len(cleaned_word_segments):
            start_time = cleaned_word_segments[current_word_index]["start_time"]
        else:
            logger.warning(f"    ⚠️ Out of word segments")
            remaining_videos = len(selected_videos) - i
            remaining_time = total_duration - (cleaned_word_segments[-1]["end_time"] if cleaned_word_segments else 0)
            video["duration"] = round(remaining_time / remaining_videos, 2)
            continue
        
        # FUZZY MATCHING: Match words with flexibility
        matched_count = 0
        search_index = current_word_index
        last_matched_index = current_word_index - 1
        
        for video_word in cleaned_video_words:
            found = False
            
            # Search within a window (next 5 words to avoid jumping too far)
            search_end = min(search_index + 5, len(cleaned_word_segments))
            
            for j in range(search_index, search_end):
                segment_word = cleaned_word_segments[j]["cleaned"]
                
                # Exact match
                if video_word == segment_word:
                    matched_count += 1
                    last_matched_index = j
                    search_index = j + 1
                    found = True
                    break
                
                # Substring match
                if video_word in segment_word or segment_word in video_word:
                    matched_count += 1
                    last_matched_index = j
                    search_index = j + 1
                    found = True
                    logger.debug(f"    Substring match: '{video_word}' ≈ '{segment_word}'")
                    break
                
                # Fuzzy similarity match
                similarity = similarity_ratio(video_word, segment_word)
                if similarity >= 0.75:  # 75% similarity threshold
                    matched_count += 1
                    last_matched_index = j
                    search_index = j + 1
                    found = True
                    logger.debug(f"    Fuzzy match: '{video_word}' ≈ '{segment_word}' (sim: {similarity:.2f})")
                    break
            
            if not found:
                logger.debug(f"    No match for '{video_word}'")
        
        # Determine end index
        if matched_count > 0:
            next_word_index = last_matched_index + 1
            logger.debug(f"    ✓ Matched {matched_count}/{word_count} words")
        else:
            logger.warning(f"    ⚠️ No matches, estimating position")
            next_word_index = min(current_word_index + word_count, len(cleaned_word_segments))
        
        # Get end time
        if i + 1 == len(selected_videos):
            end_time = total_duration
        else:
            if next_word_index < len(cleaned_word_segments):
                end_time = cleaned_word_segments[next_word_index]["start_time"]
            else:
                end_time = total_duration
        
        # Calculate duration
        video["duration"] = round(end_time - start_time, 2)
        logger.debug(f"    ✅ [{start_time:.2f}s - {end_time:.2f}s] = {video['duration']}s")
        
        # Move to next segment
        current_word_index = next_word_index
    
    # Verify total
    total_calculated = sum(v.get("duration", 0) for v in selected_videos)
    logger.debug(f"✅ Total calculated duration: {total_calculated:.2f}s (expected: {total_duration:.2f}s)")

def is_video_loopable(video_path, frame_check_window=10, threshold=15.0):
    if not video_path:
        return False
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"Cannot open video: {video_path}")

    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if frame_count <= frame_check_window * 2:
        cap.release()
        return False  # Too short to judge loopability

    frame_indices = list(range(frame_check_window)) + \
                    list(range(frame_count - frame_check_window, frame_count))

    frames = []
    for idx in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
        ret, frame = cap.read()
        if not ret or frame is None:
            continue
        frame = cv2.resize(frame, (128, 128))
        frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))

    cap.release()

    if len(frames) < 2 * frame_check_window:
        return False

    start_frames = np.array(frames[:frame_check_window])
    end_frames = np.array(frames[-frame_check_window:])

    diff = np.mean(np.abs(start_frames.astype(np.float32) - end_frames.astype(np.float32)))
    logger.debug(f"🔍 Mean frame difference: {diff:.2f}")

    return diff < threshold


def is_loopable_phash(video_path, hash_diff_threshold=8):
    if not video_path:
        return False
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"Cannot open video: {video_path}")

    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if frame_count < 2:
        cap.release()
        return False

    # Read first frame
    cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
    ret, start = cap.read()
    if not ret or start is None:
        cap.release()
        return False

    # Try to read last valid frame (with fallback)
    last_frame_index = frame_count - 1
    ret, end = False, None
    while not ret and last_frame_index > frame_count - 10:
        cap.set(cv2.CAP_PROP_POS_FRAMES, last_frame_index)
        ret, end = cap.read()
        last_frame_index -= 1

    cap.release()

    if end is None or not ret:
        return False

    start_hash = imagehash.phash(Image.fromarray(cv2.cvtColor(start, cv2.COLOR_BGR2RGB)))
    end_hash = imagehash.phash(Image.fromarray(cv2.cvtColor(end, cv2.COLOR_BGR2RGB)))

    diff = abs(start_hash - end_hash)
    logger.debug(f"🧩 pHash difference: {diff}")

    return diff < hash_diff_threshold

def is_video_zoomable_tail(video_path, tail_seconds=1, sample_frames=15, motion_threshold=1.5):
    """
    Checks only the *last few seconds* of the video to see if it's already zooming.
    Returns True if mostly static (safe to add zoom), False if motion already exists.
    """
    return False
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"Cannot open video: {video_path}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = total_frames / fps if fps > 0 else 0

    # Only analyze the last N seconds
    start_frame = max(total_frames - int(tail_seconds * fps), 0)
    cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)

    frames = []
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))
    cap.release()

    if len(frames) < 2:
        return True  # too few frames → assume static

    # Sample frames evenly
    step = max(len(frames) // sample_frames, 1)
    total_motion = 0
    motion_samples = 0

    for i in range(0, len(frames) - step, step):
        prev_gray = frames[i]
        gray = frames[i + step]
        flow = cv2.calcOpticalFlowFarneback(
            prev_gray, gray, None,
            pyr_scale=0.5, levels=3, winsize=15,
            iterations=3, poly_n=5, poly_sigma=1.2, flags=0
        )
        mag, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
        total_motion += np.mean(mag)
        motion_samples += 1

    avg_motion = total_motion / motion_samples if motion_samples else 0
    logger.debug(f"🎥 Tail motion magnitude: {avg_motion:.3f}")

    # If low optical flow in tail section → it's safe to add zoom
    return avg_motion < motion_threshold

def selective_update_with_keymaps(source: dict, modified: dict, source_keys: list, modified_keys: list) -> dict:
    """
    Update 'source' dict by copying values from 'modified' dict.
    Each pair (source_key, modified_key) defines a mapping.

    Example:
      source_keys = ["url", "description"]
      modified_keys = ["video_url", "desc_text"]
    """
    updated = source.copy()

    for s_key, m_key in zip(source_keys, modified_keys):
        if m_key in modified:
            updated[s_key] = modified[m_key]

    return updated

def clean_tts_script(tts_script: str) -> str:
    """Split and clean TTS script joined by '-'."""
    if tts_script:
        # Split by hyphen and strip spaces
        parts = [part.strip() for part in tts_script.split('-') if part.strip()]
        return " ".join(parts).rstrip(".")
    return ""

def reverse_clip(path_or_clip) -> str:
    input_path = ""
    # ✅ Handle any MoviePy clip (VideoFileClip, CompositeVideoClip, etc.)
    if hasattr(path_or_clip, "write_videofile"):
        with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_input:
            input_path = temp_input.name
        path_or_clip.write_videofile(
            input_path,
            codec="libx264",
            audio_codec="aac",
            verbose=False,
            logger=None,
            fps=25
        )

    elif isinstance(path_or_clip, str):
        input_path = path_or_clip

    """Reverse both video and audio using ffmpeg."""
    out_path = os.path.join(tempfile.gettempdir(), f"{uuid.uuid4().hex[:8]}_reversed.mp4")
    
    subprocess.run([
        "ffmpeg", "-hide_banner", "-loglevel", "error",
        "-y", "-i", input_path,
        "-vf", "reverse",
        "-af", "areverse",
        out_path
    ], check=True)
    
    return out_path

def interpolate_video(input_path: str, target_duration: float = 4.0, fps: int = 60) -> str:
    """
    Smoothly extend a short video using motion interpolation.
    Works entirely on CPU (no GPU required).

    Args:
        input_path: path to input video
        target_duration: desired output length (seconds)
        fps: target output framerate (default 60)
    """
    return None
    # Get actual duration
    cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
           "-of", "default=noprint_wrappers=1:nokey=1", input_path]
    duration_str = subprocess.check_output(cmd).decode().strip()
    duration = float(duration_str)

    # Calculate how much we need to stretch
    stretch_factor = target_duration / duration

    # Output file
    base = os.path.splitext(os.path.basename(input_path))[0]
    output_path = f"/tmp/{base}_interp.mp4"

    # FFmpeg motion interpolation command
    cmd = [
        "ffmpeg",
        "-i", input_path,
        "-filter_complex",
        f"[0:v]setpts={stretch_factor}*PTS,"
        f"minterpolate='mi_mode=mci:mc_mode=aobmc:vsbmc=1:fps={fps}'[v]",
        "-map", "[v]",
        "-an",  # remove audio
        "-c:v", "libx264",
        "-preset", "fast",
        "-crf", "18",
        "-y", output_path
    ]

    subprocess.run(cmd, check=True)
    return output_path

def _get_video_resolution(path: str) -> tuple[int, int]:
    cmd = [
        "ffprobe",
        "-v", "error",
        "-select_streams", "v:0",
        "-show_entries", "stream=width,height",
        "-of", "json",
        path,
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise RuntimeError(f"ffprobe failed:\n{result.stderr.decode()}")

    info = json.loads(result.stdout)
    stream = info["streams"][0]
    return stream["width"], stream["height"]

def _get_pixel_format(path: str) -> str:
    cmd = [
        "ffprobe",
        "-v", "error",
        "-select_streams", "v:0",
        "-show_entries", "stream=pix_fmt",
        "-of", "json",
        path,
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        return ""

    info = json.loads(result.stdout)
    return info["streams"][0].get("pix_fmt", "")

def resize_video(input_path: str, target_width: int = 1080, target_height: int = 1920, overwrite: bool = False, force: bool = False) -> str:
    """
    Resize a video to the given resolution (default 1080x1920) using FFmpeg.
    If overwrite=True, replaces the original file safely after successful conversion.
    If force=True, re-encodes even if the resolution already matches.
    """
    if not os.path.exists(input_path):
        raise FileNotFoundError(f"Input video not found: {input_path}")

    # 🔍 Probe resolution
    width, height = _get_video_resolution(input_path)
    pix_fmt = _get_pixel_format(input_path)

    # Check if we can skip:
    # 1. Force is False
    # 2. Dimensions match
    # 3. Pixel format is yuv420p (required for broad compatibility)
    if not force and width == target_width and height == target_height and pix_fmt == "yuv420p":
        logger.debug(
            f"Skipping resize (already {width}x{height}, {pix_fmt}): {os.path.basename(input_path)}"
        )
        return input_path

    logger.debug(
        f"Resizing/Re-encoding {os.path.basename(input_path)} "
        f"({width}x{height}, {pix_fmt}) → ({target_width}x{target_height}, yuv420p)"
    )

    temp_output = os.path.join("/tmp", f"{uuid.uuid4().hex}.mp4")

    # FFmpeg resize command (output goes to /tmp first)
    # FFmpeg command for Crop-to-Fill (Strict 9:16 enforcement)
    # scale=1080:1920:force_original_aspect_ratio=increase ensures min dim fits
    # crop=1080:1920 crops the excess
    cmd = [
        "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
        "-i", input_path,
        "-vf", f"scale={target_width}:{target_height}:force_original_aspect_ratio=increase,crop={target_width}:{target_height},setsar=1",
        "-c:v", "libx264", "-crf", "18", "-preset", "slow",
        "-pix_fmt", "yuv420p",
        "-c:a", "copy",
        temp_output
    ]

    # Run FFmpeg process
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        if os.path.exists(temp_output):
            os.remove(temp_output)
        raise RuntimeError(f"FFmpeg failed:\n{result.stderr.decode('utf-8', errors='ignore')}")

    # Overwrite original safely if requested
    if overwrite:
        shutil.move(temp_output, input_path)
        return input_path

    return temp_output

def remove_black_padding(input_path: str, overwrite: bool = False, threshold_pct: float = 0.1) -> str:
    """
    Automatically detect and remove black padding (crop only) using FFmpeg.
    Saves to /tmp with a unique UUID filename unless overwrite=True.

    Args:
        input_path (str): Path to the input video.
        overwrite (bool): If True, safely replace the original file.
        threshold_pct (float): Only crop if black padding > threshold_pct (0.0 to 1.0).
                              0.0 = always crop if any padding detected.

    Returns:
        str: Path to the cropped video (or original if no crop needed).
    """
    if get_config_value("test_automation"):
        return input_path
    if not os.path.exists(input_path):
        raise FileNotFoundError(f"Input video not found: {input_path}")

    # Step 1: Detect crop parameters using cropdetect
    detect_cmd = [
        "ffmpeg", "-i", input_path, "-vf", "cropdetect=24:16:0",
        "-frames:v", "500", "-f", "null", "-"
    ]
    result = subprocess.run(detect_cmd, stderr=subprocess.PIPE, text=True)
    matches = re.findall(r"crop=\S+", result.stderr)

    if not matches:
        logger.debug("No black padding detected.")
        return input_path

    # Get most frequent crop value
    crop_value = max(set(matches), key=matches.count)
    
    # Parse crop string: crop=w:h:x:y
    # Example: crop=1080:1520:0:200
    try:
        match = re.search(r"crop=(\d+):(\d+):(\d+):(\d+)", crop_value)
        if match:
            c_w, c_h, _, _ = map(int, match.groups())
            
            # Get original resolution
            orig_w, orig_h = _get_video_resolution(input_path)
            
            orig_area = orig_w * orig_h
            crop_area = c_w * c_h
            padding_area = orig_area - crop_area
            padding_pct = padding_area / orig_area if orig_area > 0 else 0
            
            if padding_pct < threshold_pct:
                logger.debug(f"Skipping crop: Padding {padding_pct:.1%} < Threshold {threshold_pct:.1%}")
                return input_path
            
            logger.debug(f"Detected crop: {crop_value} (Padding: {padding_pct:.1%})")
            
    except Exception as e:
        logger.warning(f"Could not parse crop value '{crop_value}' for threshold check: {e}")
        # Proceed with cropping if parsing fails, or return? 
        # Safest is to proceed as before or log and continue. 
        # Let's proceed to maintain existing behavior on failure unless explicitly stopped.
        logger.debug(f"Proceeding with crop: {crop_value}")

    # Step 2: Create temp output file
    tmp_output = os.path.join("/tmp", f"{uuid.uuid4().hex}_cropped.mp4")

    # Step 3: Run FFmpeg crop command
    crop_cmd = ["ffmpeg", "-y", "-i", input_path, "-vf", crop_value, "-c:a", "copy", tmp_output]
    crop_proc = subprocess.run(crop_cmd, stderr=subprocess.PIPE, text=True)

    if crop_proc.returncode != 0:
        raise RuntimeError(f"FFmpeg crop failed:\n{crop_proc.stderr}")

    # Step 4: Handle overwrite safely
    if overwrite:
        shutil.move(tmp_output, input_path)
        return input_path

    return tmp_output

def trim_black_frames(
    input_path: str, 
    overwrite: bool = False, 
    black_threshold: int = 20,
    min_frames_to_trim: int = 1,
    max_frames_to_trim: int = 30
) -> str:
    """
    Detect and remove solid black frames from the start and end of a video.
    
    Uses FFmpeg showinfo filter to analyze frame luminance (Y channel mean).
    A frame is considered black if its Y mean is <= black_threshold.
    
    Args:
        input_path: Path to the input video
        overwrite: If True, replace the original file
        black_threshold: Maximum Y luminance value to consider a frame as black (0-255)
                        Default 20 catches pure black (16) with some tolerance
        min_frames_to_trim: Minimum black frames at start/end to trigger trimming
        max_frames_to_trim: Maximum frames to check at start/end
        
    Returns:
        Path to the trimmed video, or original path if no trimming needed
    """
    if not os.path.exists(input_path):
        raise FileNotFoundError(f"Input video not found: {input_path}")
    
    # Get video info
    probe_cmd = [
        "ffprobe", "-v", "error",
        "-select_streams", "v:0",
        "-show_entries", "stream=nb_frames,r_frame_rate,duration",
        "-show_entries", "format=duration",
        "-of", "json", input_path
    ]
    probe_result = subprocess.run(probe_cmd, capture_output=True, text=True)
    
    if probe_result.returncode != 0:
        logger.warning(f"Failed to probe video: {input_path}")
        return input_path
    
    probe_data = json.loads(probe_result.stdout)
    
    # Get FPS
    fps_str = probe_data.get("streams", [{}])[0].get("r_frame_rate", "25/1")
    fps_parts = fps_str.split("/")
    fps = float(fps_parts[0]) / float(fps_parts[1]) if len(fps_parts) == 2 else float(fps_parts[0])
    
    # Get total duration
    duration = float(probe_data.get("format", {}).get("duration", 0))
    if duration == 0:
        duration = float(probe_data.get("streams", [{}])[0].get("duration", 0))
    
    if duration <= 0:
        logger.warning(f"Could not determine video duration: {input_path}")
        return input_path
    
    # Analyze first N frames for black frames at start
    start_black_frames = _count_black_frames_at_position(
        input_path, "start", max_frames_to_trim, black_threshold, fps
    )
    
    # Analyze last N frames for black frames at end  
    end_black_frames = _count_black_frames_at_position(
        input_path, "end", max_frames_to_trim, black_threshold, fps, duration
    )
    
    logger.debug(f"🎬 Black frame analysis: start={start_black_frames}, end={end_black_frames}")
    
    # Check if trimming is needed
    if start_black_frames < min_frames_to_trim and end_black_frames < min_frames_to_trim:
        logger.debug(f"✅ No black frames to trim in: {os.path.basename(input_path)}")
        return input_path
    
    # Calculate trim times
    start_trim_time = start_black_frames / fps if start_black_frames >= min_frames_to_trim else 0
    end_trim_time = end_black_frames / fps if end_black_frames >= min_frames_to_trim else 0
    
    # New duration after trimming
    new_duration = duration - start_trim_time - end_trim_time
    
    if new_duration <= 0.1:
        logger.warning(f"⚠️ Trimming would remove entire video, skipping: {input_path}")
        return input_path
    
    logger.debug(
        f"✂️ Trimming black frames: {os.path.basename(input_path)} "
        f"(start: {start_trim_time:.3f}s, end: {end_trim_time:.3f}s)"
    )
    
    # Generate output path
    temp_output = os.path.join("/tmp", f"{uuid.uuid4().hex}_trimmed.mp4")
    
    # Build FFmpeg command
    cmd = [
        "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
        "-ss", str(start_trim_time),
        "-i", input_path,
        "-t", str(new_duration),
        "-c:v", "libx264", "-preset", "fast", "-crf", "18",
        "-pix_fmt", "yuv420p",
        "-c:a", "copy",
        temp_output
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode != 0:
        logger.error(f"FFmpeg trim failed: {result.stderr}")
        return input_path
    
    logger.debug(f"✅ Trimmed video saved: {temp_output}")
    
    # Handle overwrite
    if overwrite:
        shutil.move(temp_output, input_path)
        return input_path
    
    return temp_output


def _count_black_frames_at_position(
    video_path: str,
    position: str,  # "start" or "end"
    max_frames: int,
    black_threshold: int,
    fps: float,
    duration: float = 0
) -> int:
    """
    Count consecutive black frames at the start or end of a video.
    
    Args:
        video_path: Path to video file
        position: "start" or "end"
        max_frames: Maximum frames to analyze
        black_threshold: Y luminance threshold for black detection
        fps: Video frame rate
        duration: Video duration (required for "end" position)
        
    Returns:
        Number of consecutive black frames at the specified position
    """
    # For start: analyze first max_frames frames
    # For end: seek to near end and analyze last max_frames frames
    if position == "end" and duration > 0:
        seek_time = max(0, duration - (max_frames / fps) - 0.5)
        ss_arg = ["-ss", str(seek_time)]
    else:
        ss_arg = []
    
    # Use showinfo filter to get frame luminance
    cmd = [
        "ffmpeg", "-hide_banner",
        *ss_arg,
        "-i", video_path,
        "-vf", f"select='lte(n,{max_frames})',showinfo",
        "-frames:v", str(max_frames + 5),
        "-f", "null", "-"
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
    
    if result.returncode != 0:
        return 0
    
    # Parse showinfo output for mean values
    # Format: mean:[Y U V] where Y is luminance
    # A pure black frame has Y=16 in YUV (limited range)
    frame_means = []
    for line in result.stderr.split('\n'):
        match = re.search(r'mean:\[(\d+)\s+\d+\s+\d+\]', line)
        if match:
            y_mean = int(match.group(1))
            frame_means.append(y_mean)
    
    if not frame_means:
        return 0
    
    # Count consecutive black frames
    if position == "start":
        # Count from beginning
        black_count = 0
        for y_mean in frame_means:
            if y_mean <= black_threshold:
                black_count += 1
            else:
                break
        return black_count
    else:
        # Count from end (reverse)
        black_count = 0
        for y_mean in reversed(frame_means):
            if y_mean <= black_threshold:
                black_count += 1
            else:
                break
        return black_count


def ratio_1x1_to9x16(video_path, overwrite=False):
    """
    Convert a 1:1 video to 9:16 by adding blurred padding using FFmpeg.
    Saves to /tmp with a unique UUID filename unless overwrite=True.

    Args:
        video_path (str): Path to the input video.
        overwrite (bool): If True, safely replace the original file.

    Returns:
        str: Path to the converted video.
    """
    if not os.path.exists(video_path):
        raise FileNotFoundError(f"Input video not found: {video_path}")

    tmp_output = os.path.join("/tmp", f"{uuid.uuid4().hex}_9x16.mp4")

    cmd = [
        "ffmpeg",
        "-i", video_path,
        "-vf", "crop=min(iw\\,ih):min(iw\\,ih),scale=1080:1080,pad=1080:1920:0:(1920-1080)/2:black",
        "-c:a", "copy",
        "-y",
        tmp_output
    ]

    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise RuntimeError(f"FFmpeg failed:\n{result.stderr.decode('utf-8', errors='ignore')}")

    if overwrite:
        shutil.move(tmp_output, video_path)
        return video_path

    return tmp_output

def get_best_beat_method(audio_path: str, min_interval: float = 1.0, target_beats: int = 10) -> tuple[np.ndarray, str]:
    """
    Try all beat detection methods and return the one with closest to target number of beats.
    
    Args:
        audio_path: Path to audio file
        min_interval: Minimum time between beats in seconds
        target_beats: Desired number of beats (default 10 for 10-15 sec videos)
    
    Returns:
        Tuple of (beat_times, method_name)
    """
    methods = ["kick", "snare", "downbeat", "general"]
    results = {}
    
    logger.debug(f"Testing all beat detection methods (target: ~{target_beats} beats)...")
    
    for method in methods:
        try:
            beat_times = get_beat_times(audio_path, beat_type=method, min_interval=min_interval)
            results[method] = beat_times
            logger.debug(f"{method:12s}: {len(beat_times):2d} beats detected")
        except Exception as e:
            logger.debug(f"{method:12s}: ERROR - {e}")
            results[method] = np.array([])
    
    # Filter out empty results
    valid_results = {k: v for k, v in results.items() if len(v) > 0}
    
    if not valid_results:
        return None, None
    
    # Find the method closest to target
    best_method = min(valid_results.keys(), key=lambda k: abs(len(valid_results[k]) - target_beats))
    best_beats = valid_results[best_method]
    
    logger.debug(f"Selected: {best_method} with {len(best_beats)} beats (closest to target)")
    
    return best_beats, best_method


def get_kick_times(audio_path: str, min_interval: float = 1.0) -> np.ndarray:
    """
    Detect kick drum hits (low frequency emphasis).
    Kicks are the "boom" - usually the strongest low-end hits.
    
    Args:
        audio_path: Path to audio file
        min_interval: Minimum time between kicks in seconds
    
    Returns:
        Array of kick drum timestamps in seconds
    """
    y, sr = librosa.load(audio_path)
    
    # Use percussive component separation
    y_harmonic, y_percussive = librosa.effects.hpss(y, margin=2.0)
    
    # Apply low-pass filter to focus on bass frequencies
    y_bass = librosa.effects.percussive(y_percussive, margin=4.0)
    
    # Get onset strength emphasizing low frequencies
    onset_env = librosa.onset.onset_strength(
        y=y_bass, 
        sr=sr,
        aggregate=np.median,
        fmax=200,  # Focus on frequencies below 200Hz
        n_mels=128
    )
    
    # Detect onsets with lower threshold for kicks
    onset_frames = librosa.onset.onset_detect(
        onset_envelope=onset_env,
        sr=sr,
        backtrack=False,
        pre_max=3,
        post_max=3,
        pre_avg=3,
        post_avg=5,
        delta=0.15,  # Very low threshold to catch more kicks
        wait=8
    )
    
    kick_times = librosa.frames_to_time(onset_frames, sr=sr)
    
    logger.debug(f"Raw kick detections: {len(kick_times)}")
    
    # Filter to minimum interval
    return _filter_by_min_interval(kick_times, min_interval)


def get_snare_times(audio_path: str, min_interval: float = 1.0) -> np.ndarray:
    """
    Detect snare/clap hits (mid-high frequency emphasis).
    Snares are the "crack" - sharp, crisp hits.
    
    Args:
        audio_path: Path to audio file
        min_interval: Minimum time between snares in seconds
    
    Returns:
        Array of snare hit timestamps in seconds
    """
    y, sr = librosa.load(audio_path)
    
    # Use percussive component
    y_harmonic, y_percussive = librosa.effects.hpss(y, margin=2.0)
    
    # Get onset strength emphasizing mid-high frequencies  
    onset_env = librosa.onset.onset_strength(
        y=y_percussive,
        sr=sr,
        aggregate=np.median,
        fmin=150,  # Focus on frequencies above 150Hz
        fmax=4000,
        n_mels=128
    )
    
    # Detect onsets
    onset_frames = librosa.onset.onset_detect(
        onset_envelope=onset_env,
        sr=sr,
        backtrack=False,
        pre_max=3,
        post_max=3,
        pre_avg=3,
        post_avg=5,
        delta=0.15,  # Very low threshold
        wait=8
    )
    
    snare_times = librosa.frames_to_time(onset_frames, sr=sr)
    
    logger.debug(f"Raw snare detections: {len(snare_times)}")
    
    # Filter to minimum interval
    return _filter_by_min_interval(snare_times, min_interval)


def get_downbeats(audio_path: str, min_interval: float = 1.0) -> np.ndarray:
    """
    Detect downbeats - every Nth beat based on tempo.
    More reliable than frequency filtering for finding the "1" count.
    
    Args:
        audio_path: Path to audio file
        min_interval: Minimum time between downbeats in seconds
    
    Returns:
        Array of downbeat timestamps in seconds
    """
    y, sr = librosa.load(audio_path)
    
    # Get all beats first
    tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr, units='frames')
    beat_times = librosa.frames_to_time(beat_frames, sr=sr)
    
    # Handle tempo being array or scalar
    tempo_val = tempo[0] if isinstance(tempo, np.ndarray) else tempo
    logger.debug(f"Detected {len(beat_times)} total beats at {tempo_val:.1f} BPM")
    
    if len(beat_times) == 0:
        return np.array([])
    
    # Most music is in 4/4 time, so take every 4th beat as downbeat
    # Or every 2nd beat for half-time feel
    beats_per_bar = 4
    
    # If we have very few beats, use every 2nd
    if len(beat_times) < 8:
        beats_per_bar = 2
    
    # Select every Nth beat
    downbeat_indices = np.arange(0, len(beat_times), beats_per_bar)
    downbeat_times = beat_times[downbeat_indices]
    
    logger.debug(f"Selected {len(downbeat_times)} downbeats (every {beats_per_bar} beats)")
    
    # Filter to minimum interval
    return _filter_by_min_interval(downbeat_times, min_interval)


def get_general_beats(audio_path: str, min_interval: float = 1.0) -> np.ndarray:
    """
    Fallback: Get general beat times (original method).
    
    Args:
        audio_path: Path to audio file
        min_interval: Minimum time between beats in seconds
    
    Returns:
        Array of beat timestamps in seconds
    """
    y, sr = librosa.load(audio_path)
    
    tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
    beat_times = librosa.frames_to_time(beat_frames, sr=sr)
    
    logger.debug(f"Tempo: {tempo} BPM")
    logger.debug(f"Beat times: {beat_times}")
    
    return _filter_by_min_interval(beat_times, min_interval)


def _filter_by_min_interval(times: np.ndarray, min_interval: float) -> np.ndarray:
    """Filter timestamps to ensure minimum interval between them."""
    if len(times) == 0:
        return times
    
    filtered = [times[0]]
    for t in times[1:]:
        if t - filtered[-1] >= min_interval:
            filtered.append(t)
    
    return np.array(filtered)


def get_beat_times(audio_path: str, beat_type: str = "downbeat", min_interval: float = 1.0) -> np.ndarray:
    """
    Get beat times based on specified drum element.
    
    Args:
        audio_path: Path to audio file
        beat_type: One of "kick", "snare", "downbeat", or "general"
        min_interval: Minimum time between beats in seconds
    
    Returns:
        Array of beat timestamps in seconds
    
    Recommendation: Start with "downbeat" - it's the most reliable!
    """
    logger.debug(f"Detecting {beat_type} beats with min_interval={min_interval}s...")
    
    if beat_type == "kick":
        result = get_kick_times(audio_path, min_interval)
    elif beat_type == "snare":
        result = get_snare_times(audio_path, min_interval)
    elif beat_type == "downbeat":
        result = get_downbeats(audio_path, min_interval)
    elif beat_type == "general":
        result = get_general_beats(audio_path, min_interval)
    else:
        raise ValueError(f"Unknown beat_type: {beat_type}. Use 'kick', 'snare', 'downbeat', or 'general'")
    
    logger.debug(f"Final result: {len(result)} {beat_type} beats detected")
    
    return result

def repeat_audio_ffmpeg(input_audio, output_audio, repeat: int):
    """
    Repeat audio multiple times, removing leading/trailing silence before repeating.
    Automatically determines the correct output format based on the file extension.
    
    Args:
        input_audio: Path to input audio file
        output_audio: Path to output audio file (extension determines format)
        repeat: Number of times to repeat the audio
        
    Returns:
        str: Path to the output file (may be modified if extension was incompatible)
    """
    
    # Determine output format and codec from extension
    output_ext = os.path.splitext(output_audio)[1].lower()
    output_base = os.path.splitext(output_audio)[0]
    
    # Map extensions to appropriate codec and container
    format_map = {
        '.mp3': {'codec': 'libmp3lame', 'bitrate': '192k'},
        '.m4a': {'codec': 'aac', 'bitrate': '192k'},
        '.aac': {'codec': 'aac', 'bitrate': '192k'},
        '.opus': {'codec': 'libopus', 'bitrate': '128k'},
        '.ogg': {'codec': 'libvorbis', 'bitrate': '192k'},
        '.wav': {'codec': 'pcm_s16le', 'bitrate': None},
    }
    
    # Default to m4a if extension not recognized or if using aac with mp3
    if output_ext not in format_map:
        output_ext = '.m4a'
        output_audio = output_base + output_ext
        logger.debug(f"Unknown format, defaulting to: {output_audio}")
    
    audio_config = format_map[output_ext]
    
    # Create a temporary file for the silence-trimmed audio (use same format)
    with tempfile.NamedTemporaryFile(suffix=output_ext, delete=False) as tmp:
        temp_trimmed = tmp.name
    
    try:
        # Step 1: Remove leading AND trailing silence from the original audio
        trim_cmd = [
            "ffmpeg", "-y",
            "-i", input_audio,
            "-af", "silenceremove=start_periods=1:start_threshold=-50dB:start_duration=0:stop_periods=-1:stop_threshold=-50dB:stop_duration=0",
            "-c:a", audio_config['codec']
        ]
        
        # Add bitrate if applicable (not for WAV)
        if audio_config['bitrate']:
            trim_cmd.extend(["-b:a", audio_config['bitrate']])
            
        trim_cmd.append(temp_trimmed)
        
        result = subprocess.run(trim_cmd, check=True, capture_output=True, text=True)
        
        # Step 2: Repeat the trimmed audio
        repeat_cmd = [
            "ffmpeg", "-y",
            "-stream_loop", str(repeat - 1),
            "-i", temp_trimmed,
            "-c:a", audio_config['codec']
        ]
        
        # Add bitrate if applicable
        if audio_config['bitrate']:
            repeat_cmd.extend(["-b:a", audio_config['bitrate']])
            
        repeat_cmd.append(output_audio)
        
        result = subprocess.run(repeat_cmd, check=True, capture_output=True, text=True)
        
        logger.debug(f"Successfully repeated audio {repeat} times, output: {output_audio}")
        
        return output_audio
        
    except subprocess.CalledProcessError as e:
        logger.error(f"FFmpeg error: STDOUT={e.stdout}, STDERR={e.stderr}")
        raise
        
    finally:
        # Clean up temporary file
        if os.path.exists(temp_trimmed):
            os.remove(temp_trimmed)

def clean_and_drop_empty(
    df: pd.DataFrame,
    column: str,
    extra_nulls: list[str] | None = None,
) -> pd.DataFrame:
    """
    Normalize Google Sheets empty values and drop rows
    where `column` is effectively empty.

    Handles:
    - NaN
    - ""
    - " "
    - "nan", "None", "NULL", "N/A"

    Args:
        df: Input DataFrame
        column: Column to validate (e.g. "VIDEO_LINK")
        extra_nulls: Optional extra string values to treat as null

    Returns:
        Cleaned DataFrame with valid rows only
    """

    if column not in df.columns:
        raise KeyError(f"Column '{column}' not found in DataFrame")

    null_values = ["", "nan", "none", "null", "n/a"]
    if extra_nulls:
        null_values.extend([v.lower() for v in extra_nulls])

    df = df.copy()

    df[column] = (
        df[column]
        .astype(str)
        .str.strip()
        # .str.lower()
        .replace(null_values, np.nan)
    )

    return df.dropna(subset=[column])

def is_valid_video(path: str) -> bool:
    if not os.path.exists(path):
        return False
    if os.path.getsize(path) < 100 * 1024:  # <100KB = almost certainly invalid
        return False
    return True