File size: 65,016 Bytes
763c94d
 
 
 
 
 
 
 
 
 
 
 
 
4fde749
 
 
763c94d
 
 
39fa25b
763c94d
 
 
 
 
 
 
4fde749
9dd9c8e
 
 
39fa25b
9dd9c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763c94d
 
 
 
 
 
 
 
 
4fde749
e1c4426
763c94d
4fde749
 
763c94d
 
 
 
 
4fde749
763c94d
2c78469
763c94d
 
 
 
2c78469
 
 
763c94d
 
 
2c78469
 
763c94d
 
 
 
 
4fde749
 
763c94d
4fde749
763c94d
4fde749
 
2c78469
e1c4426
763c94d
 
 
e1c4426
4fde749
763c94d
 
 
4fde749
 
39fa25b
763c94d
 
 
4fde749
2c78469
 
763c94d
2c78469
763c94d
 
 
 
2c78469
763c94d
 
 
 
 
2c78469
763c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c78469
763c94d
2c78469
 
763c94d
95cc944
763c94d
2c78469
 
763c94d
95cc944
 
763c94d
2c78092
763c94d
2c78092
95cc944
 
763c94d
 
 
 
 
 
 
2c78469
 
 
39fa25b
763c94d
 
 
2c78469
763c94d
 
 
 
 
4fde749
2c78469
763c94d
95cc944
 
 
 
 
 
2c78469
95cc944
763c94d
2c78469
95cc944
 
763c94d
2c78469
 
 
763c94d
 
 
 
 
 
 
 
2c78469
39fa25b
763c94d
 
 
95cc944
 
763c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95cc944
763c94d
95cc944
763c94d
95cc944
763c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95cc944
763c94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c78469
 
763c94d
2c78469
763c94d
2c78469
763c94d
2c78469
763c94d
2c78469
763c94d
2c78469
763c94d
2c78469
763c94d
39fa25b
763c94d
 
 
2c78469
763c94d
 
 
 
 
 
 
 
 
 
39fa25b
763c94d
 
 
2c78469
763c94d
 
 
 
 
 
 
 
 
 
 
2c78469
763c94d
4fde749
763c94d
 
 
2c78469
763c94d
2c78469
 
 
763c94d
2c78469
763c94d
2c78469
 
4fde749
763c94d
 
 
4fde749
2c78469
 
 
4fde749
 
 
763c94d
 
 
 
4fde749
763c94d
2c78469
763c94d
 
 
 
 
 
 
 
2c78469
 
 
4fde749
39fa25b
2c78469
 
 
763c94d
 
2c78469
 
 
 
763c94d
 
 
 
2c78469
 
 
763c94d
 
 
2c78469
 
39fa25b
763c94d
2c78469
 
 
 
 
 
 
 
 
4fde749
2c78469
39fa25b
763c94d
 
 
2c78469
 
 
 
 
763c94d
 
 
 
 
 
 
 
 
2c78469
763c94d
 
 
 
 
 
2c78469
 
763c94d
2c78469
 
763c94d
2c78469
763c94d
2c78469
763c94d
 
 
 
 
 
 
 
 
 
 
2c78469
 
 
 
763c94d
 
 
 
 
 
 
 
 
2c78469
763c94d
2c78469
763c94d
2c78469
763c94d
 
 
 
2c78469
763c94d
2c78469
763c94d
 
 
 
 
 
 
 
2c78469
763c94d
 
2c78469
763c94d
 
 
 
 
 
 
 
 
 
 
 
 
2c78469
763c94d
 
 
 
 
 
2c78469
763c94d
 
 
 
 
 
 
 
 
2c78469
763c94d
 
 
 
 
 
 
2c78469
763c94d
 
2c78469
763c94d
 
 
 
2c78469
763c94d
 
 
 
 
 
 
 
 
2c78469
763c94d
2c78469
763c94d
 
 
 
4fde749
 
763c94d
2c78469
 
 
763c94d
 
 
2c78469
 
 
763c94d
 
 
 
 
2c78469
763c94d
 
 
2c78469
763c94d
 
4fde749
2c78469
 
763c94d
 
 
 
 
 
2c78469
763c94d
 
2c78469
763c94d
 
 
9dd9c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c78469
763c94d
 
 
2c78469
763c94d
9dd9c8e
2c78469
 
 
763c94d
9dd9c8e
2c78469
763c94d
2c78469
 
763c94d
2c78469
763c94d
2c78469
763c94d
9dd9c8e
763c94d
9dd9c8e
763c94d
9dd9c8e
763c94d
 
 
9dd9c8e
763c94d
 
9dd9c8e
763c94d
9dd9c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763c94d
2c78469
9dd9c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763c94d
9dd9c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763c94d
 
 
9dd9c8e
2c78469
763c94d
 
9dd9c8e
763c94d
 
9dd9c8e
 
 
 
 
 
763c94d
 
9dd9c8e
763c94d
 
 
 
9dd9c8e
 
 
 
 
 
 
 
 
763c94d
9dd9c8e
 
e1c4426
763c94d
 
 
 
 
9dd9c8e
763c94d
 
 
 
 
 
 
9dd9c8e
763c94d
e1c4426
2c78469
 
763c94d
2c78469
763c94d
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
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
#!/usr/bin/env python3
"""
YouTube Video Analyzer & Downloader Pro
(μΏ ν‚€ μžλ™ 처리 버전)

Β· `www.youtube.com_cookies.txt` 파일이 **app.py**와 같은 폴더에 있으면
  μžλ™μœΌλ‘œ μ‚¬μš©ν•©λ‹ˆλ‹€.
Β· Gradio UIμ—μ„œ μΏ ν‚€ νŒŒμΌμ„ μ—…λ‘œλ“œν•˜λ©΄, μ—…λ‘œλ“œλœ 파일이 **μš°μ„ ** μ μš©λ©λ‹ˆλ‹€.
"""

# ──────────────────────────────────────────────────────────────
# ν‘œμ€€ 라이브러리
# ──────────────────────────────────────────────────────────────
import os
import re
import json
import uuid
import shutil
import tempfile
from datetime import datetime
from pathlib import Path

# ──────────────────────────────────────────────────────────────
# μ™ΈλΆ€ 라이브러리
# ──────────────────────────────────────────────────────────────
import gradio as gr
import yt_dlp
import google.generativeai as genai
# ───────── transcript_utils.py ─────────
from youtube_transcript_api import YouTubeTranscriptApi
from datetime import timedelta

def fetch_transcript(video_id, lang_pref=("ko","en")):
    # available_transcripts()κ°€ 1.1.0λΆ€ν„° 좔가됨
    for lang in lang_pref:
        try:
            transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=[lang])
            break
        except Exception:
            continue
    else:
        raise RuntimeError("μžλ§‰μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")

    lines = []
    for seg in transcript:
        t = str(timedelta(seconds=int(seg["start"])))  # 0:01:23
        t_mmss = ":".join(t.split(":")[-2:])           # 01:23
        lines.append(f"**[{t_mmss}]** {seg['text']}")
    return "\n".join(lines)
# ──────────────────────────────────────────────────────────────
# κΈ°λ³Έ μΏ ν‚€ 파일 경둜 ― 파일λͺ…이 λ™μΌν•˜λ©΄ μžλ™ μ‚¬μš©
# ──────────────────────────────────────────────────────────────
DEFAULT_COOKIE_FILE = Path(__file__).with_name("www.youtube.com_cookies.txt")


# =================================================================
# Main Class
# =================================================================
class YouTubeDownloader:
    def __init__(self):
        # μž„μ‹œ 디렉터리 (Gradio ν˜Έν™˜)
        self.download_dir = tempfile.mkdtemp()
        self.temp_downloads = tempfile.mkdtemp(prefix="youtube_downloads_")

        # μ‚¬μš©μž Downloads ν•˜μœ„ 폴더
        self.downloads_folder = os.path.join(
            os.path.expanduser("~"), "Downloads", "YouTube_Downloads"
        )
        os.makedirs(self.downloads_folder, exist_ok=True)

        self.gemini_model = None

    # ---------------------------------------------------------
    # Google Gemini API
    # ---------------------------------------------------------
    def configure_gemini(self, api_key):
        try:
            genai.configure(api_key=api_key)
            self.gemini_model = genai.GenerativeModel(
                model_name="gemini-1.5-flash-latest"
            )
            return True, "βœ… Gemini API configured successfully!"
        except Exception as e:
            return False, f"❌ Failed to configure Gemini API: {e}"

    # ---------------------------------------------------------
    # μž„μ‹œ 디렉터리 정리
    # ---------------------------------------------------------
    def cleanup(self):
        try:
            if hasattr(self, "download_dir") and os.path.exists(self.download_dir):
                shutil.rmtree(self.download_dir)
            if hasattr(self, "temp_downloads") and os.path.exists(self.temp_downloads):
                shutil.rmtree(self.temp_downloads)
        except Exception as e:
            print(f"⚠️ Warning: Could not clean up temporary directory: {e}")

    # ---------------------------------------------------------
    # 유튜브 URL 검증
    # ---------------------------------------------------------
    def is_valid_youtube_url(self, url):
        youtube_regex = re.compile(
            r"(https?://)?(www\.)?"
            r"(youtube|youtu|youtube-nocookie)\.(com|be)/"
            r"(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})"
        )
        return youtube_regex.match(url) is not None

    # ---------------------------------------------------------
    # Gemini-AI μž₯λ©΄ 뢄석
    # ---------------------------------------------------------
    def generate_scene_breakdown_gemini(self, video_info):
        if not self.gemini_model:
            return self.generate_scene_breakdown_fallback(video_info)

        try:
            duration = video_info.get("duration", 0)
            title = video_info.get("title", "")
            description = video_info.get("description", "")[:1500]

            if not duration:
                return [
                    "**[Duration Unknown]**: Unable to generate timestamped breakdown - "
                    "video duration not available"
                ]

            prompt = f"""
Analyze this YouTube video and create a highly detailed, scene-by-scene breakdown
with precise timestamps and specific descriptions:

Title: {title}
Duration: {duration} seconds
Description: {description}

IMPORTANT INSTRUCTIONS:
1. Create detailed scene descriptions that include:
   - Physical appearance of people (age, gender, clothing, hair, etc.)
   - Exact actions being performed
   - Dialogue or speech (include actual lines if audible, or infer probable spoken
     lines based on actions and setting; format them as "Character: line…")
   - Setting and environment details
   - Props, objects, or products being shown
   - Visual effects, text overlays, or graphics
   - Mood, tone, and atmosphere
   - Camera movements or angles (if apparent)
2. Dialogue Emphasis:
   - Include short dialogue lines in **every scene** wherever plausible.
   - Write lines like: Character: "Actual or inferred line…"
   - If dialogue is not available, intelligently infer probable phrases
     (e.g., "Welcome!", "Try this now!", "It feels amazing!").
3. Timestamp Guidelines:
   - For videos under 1 minute: 2-3 second segments
   - For videos 1-5 minutes: 3-5 second segments
   - For videos 5-15 minutes: 5-10 second segments
   - For videos over 15 minutes: 10-15 second segments
   - Maximum 20 scenes total for longer videos
4. Format each scene EXACTLY like this:
   **[MM:SS-MM:SS]**: Detailed description…
5. Write descriptions as if you're watching the video in real-time,
   noting everything visible and audible.
"""
            response = self.gemini_model.generate_content(prompt)

            if response and response.text:
                scenes = []
                lines = response.text.split("\n")
                current_scene = ""

                for line in lines:
                    line = line.strip()
                    if line.startswith("**[") and "]**:" in line:
                        if current_scene:
                            scenes.append(current_scene.strip())
                        current_scene = line
                    elif current_scene:
                        current_scene += "\n" + line

                if current_scene:
                    scenes.append(current_scene.strip())

                return (
                    scenes if scenes else self.generate_scene_breakdown_fallback(video_info)
                )

            return self.generate_scene_breakdown_fallback(video_info)

        except Exception as e:
            print(f"Gemini API error: {e}")
            return self.generate_scene_breakdown_fallback(video_info)

    # ---------------------------------------------------------
    # Fallback μž₯λ©΄ 뢄석
    # ---------------------------------------------------------
    def generate_scene_breakdown_fallback(self, video_info):
        duration = video_info.get("duration", 0)
        title = video_info.get("title", "").lower()
        description = video_info.get("description", "").lower()
        uploader = video_info.get("uploader", "Content creator")

        if not duration:
            return ["**[Duration Unknown]**: Unable to generate timestamped breakdown"]

        if duration <= 60:
            segment_length = 3
        elif duration <= 300:
            segment_length = 5
        elif duration <= 900:
            segment_length = 10
        else:
            segment_length = 15

        scenes = []
        num_segments = min(duration // segment_length + 1, 20)
        video_type = self.detect_video_type_detailed(title, description)

        for i in range(num_segments):
            start_time = i * segment_length
            end_time = min(start_time + segment_length - 1, duration)

            start_fmt = f"{start_time//60}:{start_time%60:02d}"
            end_fmt = f"{end_time//60}:{end_time%60:02d}"
            desc = self.generate_contextual_description(
                i, num_segments, video_type, uploader, title
            )
            scenes.append(f"**[{start_fmt}-{end_fmt}]**: {desc}")

        return scenes

    # ---------------------------------------------------------
    # λΉ„λ””μ˜€ μœ ν˜• 감지(상세)
    # ---------------------------------------------------------
    def detect_video_type_detailed(self, title, description):
        text = (title + " " + description).lower()
        if any(w in text for w in ["tutorial", "how to", "guide", "learn", "diy"]):
            return "tutorial"
        if any(w in text for w in ["review", "unboxing", "test", "comparison", "vs"]):
            return "review"
        if any(w in text for w in ["vlog", "daily", "routine", "day in"]):
            return "vlog"
        if any(w in text for w in ["music", "song", "cover", "lyrics"]):
            return "music"
        if any(w in text for w in ["comedy", "funny", "prank", "challenge"]):
            return "entertainment"
        if any(w in text for w in ["news", "breaking", "update", "report"]):
            return "news"
        if any(w in text for w in ["cooking", "recipe", "food", "kitchen"]):
            return "cooking"
        if any(w in text for w in ["workout", "fitness", "exercise", "yoga"]):
            return "fitness"
        return "general"

    # ---------------------------------------------------------
    # μž₯면별 μ„€λͺ… 생성
    # ---------------------------------------------------------
    def generate_contextual_description(
        self, scene_index, total_scenes, video_type, uploader, title
    ):
        presenter_desc = "The content creator"
        if "woman" in title or "girl" in title:
            presenter_desc = "A woman"
        elif "man" in title or "guy" in title:
            presenter_desc = "A man"

        if scene_index == 0:
            if video_type == "tutorial":
                return (
                    f"{presenter_desc} appears on screen, introducing themselves and the "
                    f"topic. They are in a well-lit workspace, wearing casual clothes."
                )
            if video_type == "vlog":
                return (
                    f"{presenter_desc} greets the camera cheerfully, perhaps waving, and "
                    f"explains what today's vlog is about."
                )
            if video_type == "review":
                return (
                    f"{presenter_desc} holds up the product to be reviewed, giving a brief "
                    f"overview of its features."
                )
            return (
                f"{presenter_desc} starts the video with an engaging introduction to "
                f"capture viewers' attention."
            )

        if scene_index == total_scenes - 1:
            if video_type == "tutorial":
                return (
                    f"{presenter_desc} shows the final result, thanks viewers, and "
                    f"encourages them to like and subscribe."
                )
            if video_type == "vlog":
                return (
                    f"{presenter_desc} wraps up the day, sharing final thoughts and "
                    f"bidding farewell."
                )
            return (
                f"{presenter_desc} concludes, summarizing key points and prompting "
                f"engagement through likes and comments."
            )

        if video_type == "tutorial":
            return (
                f"{presenter_desc} demonstrates the next step, providing clear "
                f"instructions with close-up shots."
            )
        if video_type == "review":
            return (
                f"{presenter_desc} examines a specific feature of the product, showing "
                f"it in use and commenting on performance."
            )
        if video_type == "vlog":
            return (
                f"{presenter_desc} continues the day's activities, sharing candid "
                f"moments and personal reflections."
            )
        if video_type == "cooking":
            return (
                f"{presenter_desc} prepares ingredients, chopping and mixing while "
                f"explaining each step."
            )
        if video_type == "fitness":
            return (
                f"{presenter_desc} performs an exercise set, demonstrating proper form "
                f"and offering tips."
            )
        return (
            f"{presenter_desc} proceeds with the main content, engaging viewers through "
            f"clear explanations."
        )

    # ---------------------------------------------------------
    # λΉ„λ””μ˜€ μœ ν˜• (κ°„λž΅)
    # ---------------------------------------------------------
    def detect_video_type(self, title, description):
        text = (title + " " + description).lower()
        if any(w in text for w in ["music", "song", "album", "artist", "band", "lyrics"]):
            return "🎡 Music Video"
        if any(w in text for w in ["tutorial", "how to", "guide", "learn"]):
            return "πŸ“š Tutorial/Educational"
        if any(w in text for w in ["funny", "comedy", "entertainment", "vlog"]):
            return "🎭 Entertainment/Comedy"
        if any(w in text for w in ["news", "breaking", "report", "update"]):
            return "πŸ“° News/Information"
        if any(w in text for w in ["review", "unboxing", "test", "comparison"]):
            return "⭐ Review/Unboxing"
        if any(w in text for w in ["commercial", "ad", "brand", "product"]):
            return "πŸ“Ί Commercial/Advertisement"
        return "🎬 General Content"

    # ---------------------------------------------------------
    # λ°°κ²½ μŒμ•… μΆ”μ •
    # ---------------------------------------------------------
    def detect_background_music(self, video_info):
        title = video_info.get("title", "").lower()
        if "music" in title or "song" in title:
            return "🎡 Original Music/Soundtrack"
        if "commercial" in title or "ad" in title:
            return "🎢 Upbeat Commercial Music"
        if "tutorial" in title or "how to" in title:
            return "πŸ”‡ Minimal/No Background Music"
        if "vlog" in title or "daily" in title:
            return "🎼 Ambient Background Music"
        return "🎡 Background Music"

    # ---------------------------------------------------------
    # μΈν”Œλ£¨μ–Έμ„œ 규λͺ¨ μΆ”μ •
    # ---------------------------------------------------------
    def detect_influencer_status(self, video_info):
        subs = video_info.get("channel_followers", 0)
        views = video_info.get("view_count", 0)
        if subs > 10_000_000:
            return "🌟 Mega Influencer (10M+)"
        if subs > 1_000_000:
            return "⭐ Major Influencer (1M+)"
        if subs > 100_000:
            return "🎯 Mid-tier Influencer (100K+)"
        if subs > 10_000:
            return "πŸ“ˆ Micro Influencer (10K+)"
        if views > 100_000:
            return "πŸ”₯ Viral Content Creator"
        return "πŸ‘€ Regular Content Creator"

    # ---------------------------------------------------------
    # 숫자 포맷터
    # ---------------------------------------------------------
    def format_number(self, num):
        if not num:
            return "0"
        if num >= 1_000_000_000:
            return f"{num/1_000_000_000:.1f}B"
        if num >= 1_000_000:
            return f"{num/1_000_000:.1f}M"
        if num >= 1_000:
            return f"{num/1_000:.1f}K"
        return str(num)

    # ---------------------------------------------------------
    # μ΅œμ’… 리포트 생성
    # ---------------------------------------------------------
    def format_video_info(self, video_info):
        if not video_info:
            return "❌ No video information available."

        title = video_info.get("title", "Unknown")
        uploader = video_info.get("uploader", "Unknown")
        duration = video_info.get("duration", 0)
        dur_str = f"{duration//60}:{duration%60:02d}" if duration else "Unknown"
        views = video_info.get("view_count", 0)
        likes = video_info.get("like_count", 0)
        comments = video_info.get("comment_count", 0)
        upload_date = video_info.get("upload_date", "Unknown")

        if len(upload_date) == 8:
            upload_date = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"

        scenes = self.generate_scene_breakdown_gemini(video_info)
        vtype = self.detect_video_type(title, video_info.get("description", ""))
        bgm = self.detect_background_music(video_info)
        creator = self.detect_influencer_status(video_info)
        engagement = (likes / views) * 100 if views else 0

        report = f"""
🎬 YOUTUBE VIDEO ANALYSIS REPORT
{'='*50}

πŸ“‹ BASIC INFORMATION
{'─'*25}
πŸ“Ή **Title:** {title}
πŸ‘€ **Uploader:** {uploader}
πŸ“… **Upload Date:** {upload_date}
⏱️ **Duration:** {dur_str}
πŸ†” **Video ID:** {video_info.get('id', 'Unknown')}

πŸ“Š PERFORMANCE METRICS
{'─'*25}
πŸ‘€ **Views:** {self.format_number(views)} ({views:,})
πŸ‘ **Likes:** {self.format_number(likes)} ({likes:,})
πŸ’¬ **Comments:** {self.format_number(comments)} ({comments:,})
πŸ“ˆ **Engagement Rate:** {engagement:.2f}%

🎯 CONTENT ANALYSIS
{'─'*25}
πŸ“‚ **Video Type:** {vtype}
🎡 **Background Music:** {bgm}
πŸ‘‘ **Creator Status:** {creator}

🎬 DETAILED SCENE BREAKDOWN
{'─'*30}
{chr(10).join(scenes)}

πŸ“ DESCRIPTION PREVIEW
{'─'*25}
{video_info.get('description', 'No description available')[:500]}
{'...(truncated)' if len(video_info.get('description', '')) > 500 else ''}

{'='*50}
πŸ“Š **Analysis completed:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
πŸ€– **AI Enhancement:** {'Gemini AI' if self.gemini_model else 'Standard Analysis'}
"""
        return report.strip()

    # ---------------------------------------------------------
    # 메타데이터 μΆ”μΆœ
    # ---------------------------------------------------------
    def get_video_info(self, url, progress=gr.Progress(), cookiefile=None):
        if not url or not url.strip():
            return None, "❌ Please enter a YouTube URL"
        if not self.is_valid_youtube_url(url):
            return None, "❌ Invalid YouTube URL format"

        # μΏ ν‚€ 선택 μˆœμ„œ: UI μ—…λ‘œλ“œ β†’ κΈ°λ³Έ μΏ ν‚€ β†’ None
        if cookiefile and os.path.exists(cookiefile):
            cookiefile = cookiefile
        elif DEFAULT_COOKIE_FILE.exists():
            cookiefile = str(DEFAULT_COOKIE_FILE)
        else:
            cookiefile = None

        try:
            progress(0.1, desc="Initializing YouTube extractor…")
            ydl_opts = {"noplaylist": True, "extract_flat": False}
            if cookiefile:
                ydl_opts["cookiefile"] = cookiefile

            progress(0.5, desc="Extracting video metadata…")
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=False)

            progress(1.0, desc="βœ… Analysis complete!")
            return info, "βœ… Video information extracted successfully"

        except Exception as e:
            return None, f"❌ Error: {e}"

    # ---------------------------------------------------------
    # λ‹€μš΄λ‘œλ“œ
    # ---------------------------------------------------------
    def download_video(
        self,
        url,
        quality="best",
        audio_only=False,
        progress=gr.Progress(),
        cookiefile=None,
    ):
        if not url or not url.strip():
            return None, "❌ Please enter a YouTube URL"
        if not self.is_valid_youtube_url(url):
            return None, "❌ Invalid YouTube URL format"

        # μΏ ν‚€ 선택 μˆœμ„œ
        if cookiefile and os.path.exists(cookiefile):
            cookiefile = cookiefile
        elif DEFAULT_COOKIE_FILE.exists():
            cookiefile = str(DEFAULT_COOKIE_FILE)
        else:
            cookiefile = None

        try:
            progress(0.1, desc="Preparing download…")
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

            ydl_opts = {
                "outtmpl": os.path.join(
                    self.temp_downloads, f"%(title)s_{timestamp}.%(ext)s"
                ),
                "noplaylist": True,
            }

            if audio_only:
                ydl_opts["format"] = "bestaudio/best"
                ydl_opts["postprocessors"] = [
                    {
                        "key": "FFmpegExtractAudio",
                        "preferredcodec": "mp3",
                        "preferredquality": "192",
                    }
                ]
            else:
                if quality == "720p":
                    ydl_opts["format"] = "best[height<=720]"
                elif quality == "480p":
                    ydl_opts["format"] = "best[height<=480]"
                else:  # "best"
                    ydl_opts["format"] = "best[height<=1080]"

            if cookiefile:
                ydl_opts["cookiefile"] = cookiefile

            # μ§„ν–‰λ₯  ν›…
            def hook(d):
                if d["status"] == "downloading":
                    if "total_bytes" in d:
                        pct = d["downloaded_bytes"] / d["total_bytes"] * 100
                        progress(0.1 + pct / 100 * 0.7, desc=f"Downloading… {pct:.1f}%")
                    else:
                        progress(0.5, desc="Downloading…")
                elif d["status"] == "finished":
                    progress(0.8, desc="Processing download…")

            ydl_opts["progress_hooks"] = [hook]

            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.extract_info(url, download=True)

            progress(0.9, desc="Copying to Downloads folder…")

            # temp λ””λ ‰ν„°λ¦¬μ—μ„œ 파일 μ°ΎκΈ°
            downloaded_temp = None
            for f in os.listdir(self.temp_downloads):
                if timestamp in f:
                    downloaded_temp = os.path.join(self.temp_downloads, f)
                    break

            if not downloaded_temp:
                return None, "❌ Downloaded file not found"

            final_name = os.path.basename(downloaded_temp)
            final_path = os.path.join(self.downloads_folder, final_name)

            try:
                shutil.copy2(downloaded_temp, final_path)
                saved = True
            except Exception as e:
                print(f"Copy warning: {e}")
                saved = False
                final_path = "File kept only in temp folder"

            progress(1.0, desc="βœ… Download complete!")

            msg = (
                "βœ… Download successful!\n"
                f"πŸ“ Temp file: {os.path.basename(downloaded_temp)}\n"
                f"πŸ“ Saved to: {final_path if saved else 'Copy failed'}\n"
                f"🎯 Size: {os.path.getsize(downloaded_temp)/(1024*1024):.1f} MB"
            )
            return downloaded_temp, msg

        except Exception as e:
            return None, f"❌ Download failed: {e}"


# =================================================================
# Helper functions for Gradio
# =================================================================
downloader = YouTubeDownloader()


def configure_api_key(api_key):
    if not api_key or not api_key.strip():
        return "❌ Please enter a valid Google API key", gr.update(visible=False)
    ok, msg = downloader.configure_gemini(api_key.strip())
    return msg, gr.update(visible=ok)


def analyze_with_cookies(url, cookies_file, progress=gr.Progress()):
    try:
        progress(0.05, desc="Starting analysis…")
        cookiefile = cookies_file if cookies_file else None
        info, msg = downloader.get_video_info(
            url, progress=progress, cookiefile=cookiefile
        )
        if info:
            progress(0.95, desc="Generating report…")
            return downloader.format_video_info(info)
        return f"❌ Analysis Failed: {msg}"
    except Exception as e:
        return f"❌ System Error: {e}"


def download_with_cookies(url, quality, audio_only, cookies_file, progress=gr.Progress()):
    try:
        progress(0.05, desc="Preparing download…")
        cookiefile = cookies_file if cookies_file else None
        file_path, status = downloader.download_video(
            url, quality, audio_only, progress=progress, cookiefile=cookiefile
        )
        return (file_path, status) if file_path else (None, status)
    except Exception as e:
        return None, f"❌ System Error: {e}"


# =================================================================
# Gradio UI
# =================================================================
#!/usr/bin/env python3
"""
YouTube Video Analyzer & Downloader Pro
───────────────────────────────────────
β€’  `www.youtube.com_cookies.txt` κ°€ app.py 와 같은 폴더에 있으면 μžλ™μœΌλ‘œ μ‚¬μš©
β€’  UIμ—μ„œ μΏ ν‚€λ₯Ό μ—…λ‘œλ“œν•˜λ©΄ κ·Έ 파일이 *μš°μ„ * 적용
β€’  β€œTranscript” 탭을 μΆ”κ°€ν•΄ **전체 μžλ§‰ + MM:SS νƒ€μž„μŠ€νƒ¬ν”„** 좜λ ₯
"""

# ── ν‘œμ€€ 라이브러리 ───────────────────────────────────────────
import os, re, json, shutil, tempfile
from datetime import datetime, timedelta
from pathlib import Path

# ── μ„œλ“œνŒŒν‹° ──────────────────────────────────────────────────
import gradio as gr
import yt_dlp
import google.generativeai as genai
from youtube_transcript_api import YouTubeTranscriptApi  # NEW

# ── μƒμˆ˜ ──────────────────────────────────────────────────────
DEFAULT_COOKIE_FILE = Path(__file__).with_name("www.youtube.com_cookies.txt")

# YouTube URL μ •κ·œμ‹(캑처 κ·Έλ£Ή 6이 μ˜μƒ ID)
_YT_REGEX = re.compile(
    r"(https?://)?(www\.)?"
    r"(youtube|youtu|youtube-nocookie)\.(com|be)/"
    r"(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})"
)


# =================================================================
# Helper :  video-ID μΆ”μΆœ + μžλ§‰ κ°€μ Έμ˜€κΈ°
# =================================================================
def extract_video_id(url: str) -> str | None:
    """유튜브 URLμ—μ„œ 11-κΈ€μž λΉ„λ””μ˜€ ID λ°˜ν™˜(μ—†μœΌλ©΄ None)"""
    m = _YT_REGEX.match(url)
    return m.group(6) if m else None


def fetch_transcript(video_id: str, pref_lang=("ko", "en")) -> str:
    """
    유튜브 μžλ§‰μ„ 가져와
    **[MM:SS]** line ν˜•μ‹μœΌλ‘œ κ²°ν•©ν•œ λ’€ λ¬Έμžμ—΄λ‘œ λ°˜ν™˜.
    """
    transcript = None
    # μ–Έμ–΄ μš°μ„ μˆœμœ„λŒ€λ‘œ μ‹œλ„
    for lang in pref_lang:
        try:
            transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=[lang])
            break
        except Exception:
            continue
    # κ·Έλž˜λ„ μ‹€νŒ¨ν•˜λ©΄ μž„μ˜ μ–Έμ–΄
    if transcript is None:
        transcript = YouTubeTranscriptApi.get_transcript(video_id)

    lines = []
    for seg in transcript:
        t = str(timedelta(seconds=int(seg["start"])))       # H:MM:SS
        t_mmss = ":".join(t.split(":")[-2:])                # MM:SS
        lines.append(f"**[{t_mmss}]** {seg['text']}")
    return "\n".join(lines)


# =================================================================
# 메인 클래슀
# =================================================================
class YouTubeDownloader:
    def __init__(self):
        self.download_dir = tempfile.mkdtemp()
        self.temp_downloads = tempfile.mkdtemp(prefix="youtube_downloads_")
        self.downloads_folder = os.path.join(
            os.path.expanduser("~"), "Downloads", "YouTube_Downloads"
        )
        os.makedirs(self.downloads_folder, exist_ok=True)
        self.gemini_model = None

    # ───────── Gemini ─────────
    def configure_gemini(self, api_key):
        try:
            genai.configure(api_key=api_key)
            self.gemini_model = genai.GenerativeModel(
                model_name="gemini-1.5-flash-latest"
            )
            return True, "βœ… Gemini API configured successfully!"
        except Exception as e:
            return False, f"❌ Failed to configure Gemini API: {e}"

    # ───────── 정리 ─────────
    def cleanup(self):
        try:
            if os.path.exists(self.download_dir):
                shutil.rmtree(self.download_dir)
            if os.path.exists(self.temp_downloads):
                shutil.rmtree(self.temp_downloads)
        except Exception:
            pass

    # ───────── URL 검증 ──────
    def is_valid_youtube_url(self, url):
        return _YT_REGEX.match(url) is not None

    # ───────── Gemini scene breakdown (μƒλž΅ 없이 전체 κ΅¬ν˜„) ──────
    def generate_scene_breakdown_gemini(self, video_info):
        if not self.gemini_model:
            return self.generate_scene_breakdown_fallback(video_info)
        try:
            duration = video_info.get("duration", 0)
            title = video_info.get("title", "")
            description = video_info.get("description", "")[:1500]
            if not duration:
                return [
                    "**[Duration Unknown]**: Unable to generate timestamped breakdown – "
                    "video duration not available"
                ]

            prompt = f"""
Analyze this YouTube video and create a highly detailed, scene-by-scene breakdown
with precise timestamps and specific descriptions:

Title: {title}
Duration: {duration} seconds
Description: {description}

IMPORTANT INSTRUCTIONS:
1. Create detailed scene descriptions that include:
   - Physical appearance of people (age, gender, clothing, hair, etc.)
   - Exact actions being performed
   - Dialogue or speech (include actual lines if audible, or infer probable spoken
     lines based on actions and setting; format them as "Character: line…")
   - Setting and environment details
   - Props, objects, or products being shown
   - Visual effects, text overlays, or graphics
   - Mood, tone, and atmosphere
   - Camera movements or angles (if apparent)
2. Dialogue Emphasis:
   - Include short dialogue lines in **every scene** wherever plausible.
   - Write lines like: Character: "Actual or inferred line…"
   - If dialogue is not available, intelligently infer probable phrases
3. Timestamp Guidelines:
   - <1 min : 2–3 s | 1–5 min : 3–5 s | 5–15 min : 5–10 s | >15 min : 10–15 s
   - Max 20 scenes
4. Format: **[MM:SS-MM:SS]** description
"""
            resp = self.gemini_model.generate_content(prompt)
            if not resp or not resp.text:
                return self.generate_scene_breakdown_fallback(video_info)

            scenes, cur = [], ""
            for line in resp.text.splitlines():
                line = line.strip()
                if line.startswith("**[") and "]**:" in line:
                    if cur:
                        scenes.append(cur.strip())
                    cur = line
                elif cur:
                    cur += "\n" + line
            if cur:
                scenes.append(cur.strip())
            return scenes if scenes else self.generate_scene_breakdown_fallback(video_info)
        except Exception:
            return self.generate_scene_breakdown_fallback(video_info)

    # ───────── fallback breakdown ──────
    def generate_scene_breakdown_fallback(self, video_info):
        duration = video_info.get("duration", 0)
        if not duration:
            return ["**[Duration Unknown]**: Unable to generate timestamped breakdown"]

        if duration <= 60:
            seg = 3
        elif duration <= 300:
            seg = 5
        elif duration <= 900:
            seg = 10
        else:
            seg = 15

        total = min(duration // seg + 1, 20)
        vtype = self.detect_video_type_detailed(
            video_info.get("title", ""), video_info.get("description", "")
        )
        scenes = []
        for i in range(total):
            s, e = i * seg, min(i * seg + seg - 1, duration)
            scenes.append(
                f"**[{s//60:02d}:{s%60:02d}-{e//60:02d}:{e%60:02d}]**: "
                f"{self.generate_contextual_description(i, total, vtype, '', video_info.get('title',''))}"
            )
        return scenes

    # ───────── detect helpers (상세) ──────
    def detect_video_type_detailed(self, title, desc):
        t = (title + " " + desc).lower()
        if any(x in t for x in ["tutorial", "how to", "guide", "diy"]):
            return "tutorial"
        if any(x in t for x in ["review", "unboxing", "comparison"]):
            return "review"
        if any(x in t for x in ["vlog", "daily", "routine"]):
            return "vlog"
        if any(x in t for x in ["music", "song", "cover"]):
            return "music"
        if any(x in t for x in ["comedy", "prank", "challenge"]):
            return "entertainment"
        if any(x in t for x in ["news", "update", "report"]):
            return "news"
        if any(x in t for x in ["cooking", "recipe", "food"]):
            return "cooking"
        if any(x in t for x in ["workout", "fitness", "yoga"]):
            return "fitness"
        return "general"

    def generate_contextual_description(
        self, idx, total, vtype, uploader, title
    ):
        if idx == 0:
            return "The creator greets viewers and introduces the video."
        if idx == total - 1:
            return "The creator wraps up and thanks viewers."
        return "Content continues according to the video type."

    # ───────── quick-detect helpers (μš”μ•½) ──────
    def detect_video_type(self, title, desc):
        t = (title + " " + desc).lower()
        if any(x in t for x in ["music", "song", "album"]):
            return "🎡 Music"
        if any(x in t for x in ["tutorial", "guide"]):
            return "πŸ“š Tutorial"
        if any(x in t for x in ["comedy", "vlog"]):
            return "🎭 Entertainment"
        if any(x in t for x in ["news", "report"]):
            return "πŸ“° News"
        if any(x in t for x in ["review", "unboxing"]):
            return "⭐ Review"
        return "🎬 General"

    def detect_background_music(self, video_info):
        title = video_info.get("title", "").lower()
        if "music" in title:
            return "🎡 Original music"
        if "tutorial" in title:
            return "πŸ”‡ Minimal music"
        return "🎼 Background music"

    def detect_influencer_status(self, video_info):
        subs = video_info.get("channel_followers", 0)
        if subs > 10_000_000:
            return "🌟 Mega (10 M+)"
        if subs > 1_000_000:
            return "⭐ Major (1 M+)"
        if subs > 100_000:
            return "🎯 Mid (100 K+)"
        return "πŸ‘€"

    @staticmethod
    def format_number(n):
        if n >= 1_000_000:
            return f"{n/1_000_000:.1f} M"
        if n >= 1_000:
            return f"{n/1_000:.1f} K"
        return str(n)

    # ───────── 리포트 ──────
    def format_video_info(self, info):
        title = info.get("title", "")
        uploader = info.get("uploader", "")
        duration = info.get("duration", 0)
        dur = f"{duration//60}:{duration%60:02d}"
        views = info.get("view_count", 0)
        likes = info.get("like_count", 0)
        comments = info.get("comment_count", 0)
        scenes = self.generate_scene_breakdown_gemini(info)

        return f"""
🎬 **{title}**
Uploader: {uploader} Duration: {dur}

Views / Likes / Comments: {self.format_number(views)} / {self.format_number(likes)} / {self.format_number(comments)}

{'-'*48}
{"".join(scenes)}
"""

    # ───────── 메타데이터 μΆ”μΆœ ──────
    def get_video_info(self, url, progress=gr.Progress(), cookiefile=None):
        if not self.is_valid_youtube_url(url):
            return None, "❌ Invalid URL"

        if cookiefile and os.path.exists(cookiefile):
            cookiefile = cookiefile
        elif DEFAULT_COOKIE_FILE.exists():
            cookiefile = str(DEFAULT_COOKIE_FILE)
        else:
            cookiefile = None

        try:
            ydl_opts = {"noplaylist": True, "quiet": True}
            if cookiefile:
                ydl_opts["cookiefile"] = cookiefile
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=False)
            return info, "OK"
        except Exception as e:
            return None, f"yt-dlp error: {e}"

    # ───────── λ‹€μš΄λ‘œλ“œ ──────
    def download_video(
        self, url, quality="best", audio_only=False, progress=gr.Progress(), cookiefile=None
    ):
        if not self.is_valid_youtube_url(url):
            return None, "❌ Invalid URL"
        if cookiefile and os.path.exists(cookiefile):
            cookiefile = cookiefile
        elif DEFAULT_COOKIE_FILE.exists():
            cookiefile = str(DEFAULT_COOKIE_FILE)
        else:
            cookiefile = None

        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        ydl_opts = {
            "outtmpl": os.path.join(self.temp_downloads, f"%(title)s_{ts}.%(ext)s"),
            "noplaylist": True,
        }
        if audio_only:
            ydl_opts["format"] = "bestaudio/best"
            ydl_opts["postprocessors"] = [
                {"key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "192"}
            ]
        else:
            if quality == "720p":
                ydl_opts["format"] = "best[height<=720]"
            elif quality == "480p":
                ydl_opts["format"] = "best[height<=480]"
            else:
                ydl_opts["format"] = "best[height<=1080]"
        if cookiefile:
            ydl_opts["cookiefile"] = cookiefile

        try:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.extract_info(url, download=True)
            # 첫 파일 찾기
            for f in os.listdir(self.temp_downloads):
                if ts in f:
                    temp_fp = os.path.join(self.temp_downloads, f)
                    final_fp = os.path.join(self.downloads_folder, f)
                    try:
                        shutil.copy2(temp_fp, final_fp)
                        saved = final_fp
                    except Exception:
                        saved = temp_fp
                    return temp_fp, f"βœ… Saved: {saved}"
            return None, "❌ Downloaded file not found"
        except Exception as e:
            return None, f"❌ Download failed: {e}"


# =================================================================
# Gradio Helper ν•¨μˆ˜
# =================================================================
downloader = YouTubeDownloader()


def configure_api_key(api_key):
    ok, msg = downloader.configure_gemini(api_key.strip()) if api_key else (False, "❌ API key required")
    return msg, gr.update(visible=ok)


def analyze_with_cookies(url, cookies_file, progress=gr.Progress()):
    info, err = downloader.get_video_info(url, progress, cookies_file)
    return downloader.format_video_info(info) if info else f"❌ {err}"


def download_with_cookies(url, qual, audio, cookies_file, progress=gr.Progress()):
    fp, msg = downloader.download_video(url, qual, audio, progress, cookies_file)
    return fp, msg


def get_transcript(url, cookies_file):
    vid = extract_video_id(url)
    if not vid:
        return "❌ Invalid YouTube URL"
    try:
        return fetch_transcript(vid)
    except Exception as e:
        return f"❌ {e}"


# =================================================================
# UI
# =================================================================
def create_interface():
    with gr.Blocks(
        theme=gr.themes.Soft(), title="πŸŽ₯ YouTube Video Analyzer & Downloader Pro"
    ) as iface:
        gr.HTML("<h1>πŸŽ₯ YouTube Video Analyzer & Downloader Pro</h1>")

        # API μ„€μ •
        with gr.Group():
            gr.HTML("<h3>πŸ”‘ Google Gemini API Configuration</h3>")
            with gr.Row():
                api_key_in = gr.Textbox(
                    label="πŸ”‘ Google API Key", type="password", placeholder="Paste your Google API key…"
                )
                api_btn = gr.Button("πŸ”§ Configure API", variant="secondary")
            api_status = gr.Textbox(
                label="API Status",
                value="❌ Gemini API not configured – Using fallback analysis",
                interactive=False,
                lines=1,
            )

        # 곡톡 μž…λ ₯
        with gr.Row():
            url_in = gr.Textbox(label="πŸ”— YouTube URL", placeholder="Paste YouTube video URL…")
            cookies_in = gr.File(
                label="πŸͺ Upload cookies.txt (optional)", file_types=[".txt"], type="filepath"
            )

        with gr.Tabs():
            # 뢄석 νƒ­
            with gr.TabItem("πŸ“Š Video Analysis"):
                analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
                analysis_out = gr.Textbox(label="πŸ“Š Analysis Report", lines=30, show_copy_button=True)
                analyze_btn.click(
                    analyze_with_cookies, inputs=[url_in, cookies_in], outputs=analysis_out, show_progress=True
                )
            # λ‹€μš΄λ‘œλ“œ νƒ­
            with gr.TabItem("⬇️ Video Download"):
                with gr.Row():
                    quality_dd = gr.Dropdown(
                        choices=["best", "720p", "480p"], value="best", label="πŸ“Ί Quality"
                    )
                    audio_cb = gr.Checkbox(label="🎡 Audio only (MP3)")
                download_btn = gr.Button("⬇️ Download Video", variant="primary")
                dl_status = gr.Textbox(label="πŸ“₯ Download Status", lines=5, show_copy_button=True)
                dl_file = gr.File(label="πŸ“ Downloaded File", visible=False)

                def wrapped_dl(u, q, a, c, prog=gr.Progress()):
                    fp, st = download_with_cookies(u, q, a, c, prog)
                    return (st, gr.update(value=fp, visible=True)) if fp and os.path.exists(fp) else (
                        st,
                        gr.update(visible=False),
                    )

                download_btn.click(
                    wrapped_dl,
                    inputs=[url_in, quality_dd, audio_cb, cookies_in],
                    outputs=[dl_status, dl_file],
                    show_progress=True,
                )
            # μžλ§‰ νƒ­  NEW
            with gr.TabItem("πŸ—’οΈ Transcript"):
                tr_btn = gr.Button("πŸ“œ Get Full Transcript", variant="primary")
                tr_out = gr.Textbox(
                    label="πŸ—’οΈ Transcript (full)", lines=30, show_copy_button=True
                )
                tr_btn.click(
                    get_transcript, inputs=[url_in, cookies_in], outputs=tr_out, show_progress=True
                )

        # API λ²„νŠΌ
        api_btn.click(configure_api_key, inputs=[api_key_in], outputs=[api_status])

        gr.HTML(
            """
<div style="margin-top:20px;padding:15px;background:#f0f8ff;border-left:5px solid #4285f4;border-radius:10px;">
  <h3>πŸ’‘ Tip: μΏ ν‚€ 파일 μžλ™ μ‚¬μš©</h3>
  <p><code>www.youtube.com_cookies.txt</code> νŒŒμΌμ„ <strong>app.py</strong>와 같은
  폴더에 두면 μ—…λ‘œλ“œ 없이 μžλ™ μ‚¬μš©λ©λ‹ˆλ‹€.</p>
</div>
"""
        )
    return iface


# =================================================================
# μ‹€ν–‰
# =================================================================
if __name__ == "__main__":
    demo = create_interface()
    import atexit

    atexit.register(downloader.cleanup)
    demo.launch(debug=True, show_error=True)
#!/usr/bin/env python3
"""
YouTube Video Analyzer & Downloader Pro
───────────────────────────────────────
β€’  `www.youtube.com_cookies.txt` κ°€ app.py 와 같은 폴더에 있으면 μžλ™μœΌλ‘œ μ‚¬μš©
β€’  UIμ—μ„œ μΏ ν‚€λ₯Ό μ—…λ‘œλ“œν•˜λ©΄ κ·Έ 파일이 *μš°μ„ * 적용
β€’  β€œTranscript” 탭을 μΆ”κ°€ν•΄ **전체 μžλ§‰ + MM:SS νƒ€μž„μŠ€νƒ¬ν”„** 좜λ ₯
"""

# ── ν‘œμ€€ 라이브러리 ───────────────────────────────────────────
import os, re, json, shutil, tempfile
from datetime import datetime, timedelta
from pathlib import Path

# ── μ„œλ“œνŒŒν‹° ──────────────────────────────────────────────────
import gradio as gr
import yt_dlp
import google.generativeai as genai
from youtube_transcript_api import YouTubeTranscriptApi  # NEW

# ── μƒμˆ˜ ──────────────────────────────────────────────────────
DEFAULT_COOKIE_FILE = Path(__file__).with_name("www.youtube.com_cookies.txt")

# YouTube URL μ •κ·œμ‹(캑처 κ·Έλ£Ή 6이 μ˜μƒ ID)
_YT_REGEX = re.compile(
    r"(https?://)?(www\.)?"
    r"(youtube|youtu|youtube-nocookie)\.(com|be)/"
    r"(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})"
)


# =================================================================
# Helper :  video-ID μΆ”μΆœ + μžλ§‰ κ°€μ Έμ˜€κΈ°
# =================================================================
def extract_video_id(url: str) -> str | None:
    """유튜브 URLμ—μ„œ 11-κΈ€μž λΉ„λ””μ˜€ ID λ°˜ν™˜(μ—†μœΌλ©΄ None)"""
    m = _YT_REGEX.match(url)
    return m.group(6) if m else None


def fetch_transcript(video_id: str, pref_lang=("ko", "en")) -> str:
    """
    유튜브 μžλ§‰μ„ 가져와
    **[MM:SS]** line ν˜•μ‹μœΌλ‘œ κ²°ν•©ν•œ λ’€ λ¬Έμžμ—΄λ‘œ λ°˜ν™˜.
    """
    transcript = None
    # μ–Έμ–΄ μš°μ„ μˆœμœ„λŒ€λ‘œ μ‹œλ„
    for lang in pref_lang:
        try:
            transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=[lang])
            break
        except Exception:
            continue
    # κ·Έλž˜λ„ μ‹€νŒ¨ν•˜λ©΄ μž„μ˜ μ–Έμ–΄
    if transcript is None:
        transcript = YouTubeTranscriptApi.get_transcript(video_id)

    lines = []
    for seg in transcript:
        t = str(timedelta(seconds=int(seg["start"])))       # H:MM:SS
        t_mmss = ":".join(t.split(":")[-2:])                # MM:SS
        lines.append(f"**[{t_mmss}]** {seg['text']}")
    return "\n".join(lines)


# =================================================================
# 메인 클래슀
# =================================================================
class YouTubeDownloader:
    def __init__(self):
        self.download_dir = tempfile.mkdtemp()
        self.temp_downloads = tempfile.mkdtemp(prefix="youtube_downloads_")
        self.downloads_folder = os.path.join(
            os.path.expanduser("~"), "Downloads", "YouTube_Downloads"
        )
        os.makedirs(self.downloads_folder, exist_ok=True)
        self.gemini_model = None

    # ───────── Gemini ─────────
    def configure_gemini(self, api_key):
        try:
            genai.configure(api_key=api_key)
            self.gemini_model = genai.GenerativeModel(
                model_name="gemini-1.5-flash-latest"
            )
            return True, "βœ… Gemini API configured successfully!"
        except Exception as e:
            return False, f"❌ Failed to configure Gemini API: {e}"

    # ───────── 정리 ─────────
    def cleanup(self):
        try:
            if os.path.exists(self.download_dir):
                shutil.rmtree(self.download_dir)
            if os.path.exists(self.temp_downloads):
                shutil.rmtree(self.temp_downloads)
        except Exception:
            pass

    # ───────── URL 검증 ──────
    def is_valid_youtube_url(self, url):
        return _YT_REGEX.match(url) is not None

    # ───────── Gemini scene breakdown (μƒλž΅ 없이 전체 κ΅¬ν˜„) ──────
    def generate_scene_breakdown_gemini(self, video_info):
        if not self.gemini_model:
            return self.generate_scene_breakdown_fallback(video_info)
        try:
            duration = video_info.get("duration", 0)
            title = video_info.get("title", "")
            description = video_info.get("description", "")[:1500]
            if not duration:
                return [
                    "**[Duration Unknown]**: Unable to generate timestamped breakdown – "
                    "video duration not available"
                ]

            prompt = f"""
Analyze this YouTube video and create a highly detailed, scene-by-scene breakdown
with precise timestamps and specific descriptions:

Title: {title}
Duration: {duration} seconds
Description: {description}

IMPORTANT INSTRUCTIONS:
1. Create detailed scene descriptions that include:
   - Physical appearance of people (age, gender, clothing, hair, etc.)
   - Exact actions being performed
   - Dialogue or speech (include actual lines if audible, or infer probable spoken
     lines based on actions and setting; format them as "Character: line…")
   - Setting and environment details
   - Props, objects, or products being shown
   - Visual effects, text overlays, or graphics
   - Mood, tone, and atmosphere
   - Camera movements or angles (if apparent)
2. Dialogue Emphasis:
   - Include short dialogue lines in **every scene** wherever plausible.
   - Write lines like: Character: "Actual or inferred line…"
   - If dialogue is not available, intelligently infer probable phrases
3. Timestamp Guidelines:
   - <1 min : 2–3 s | 1–5 min : 3–5 s | 5–15 min : 5–10 s | >15 min : 10–15 s
   - Max 20 scenes
4. Format: **[MM:SS-MM:SS]** description
"""
            resp = self.gemini_model.generate_content(prompt)
            if not resp or not resp.text:
                return self.generate_scene_breakdown_fallback(video_info)

            scenes, cur = [], ""
            for line in resp.text.splitlines():
                line = line.strip()
                if line.startswith("**[") and "]**:" in line:
                    if cur:
                        scenes.append(cur.strip())
                    cur = line
                elif cur:
                    cur += "\n" + line
            if cur:
                scenes.append(cur.strip())
            return scenes if scenes else self.generate_scene_breakdown_fallback(video_info)
        except Exception:
            return self.generate_scene_breakdown_fallback(video_info)

    # ───────── fallback breakdown ──────
    def generate_scene_breakdown_fallback(self, video_info):
        duration = video_info.get("duration", 0)
        if not duration:
            return ["**[Duration Unknown]**: Unable to generate timestamped breakdown"]

        if duration <= 60:
            seg = 3
        elif duration <= 300:
            seg = 5
        elif duration <= 900:
            seg = 10
        else:
            seg = 15

        total = min(duration // seg + 1, 20)
        vtype = self.detect_video_type_detailed(
            video_info.get("title", ""), video_info.get("description", "")
        )
        scenes = []
        for i in range(total):
            s, e = i * seg, min(i * seg + seg - 1, duration)
            scenes.append(
                f"**[{s//60:02d}:{s%60:02d}-{e//60:02d}:{e%60:02d}]**: "
                f"{self.generate_contextual_description(i, total, vtype, '', video_info.get('title',''))}"
            )
        return scenes

    # ───────── detect helpers (상세) ──────
    def detect_video_type_detailed(self, title, desc):
        t = (title + " " + desc).lower()
        if any(x in t for x in ["tutorial", "how to", "guide", "diy"]):
            return "tutorial"
        if any(x in t for x in ["review", "unboxing", "comparison"]):
            return "review"
        if any(x in t for x in ["vlog", "daily", "routine"]):
            return "vlog"
        if any(x in t for x in ["music", "song", "cover"]):
            return "music"
        if any(x in t for x in ["comedy", "prank", "challenge"]):
            return "entertainment"
        if any(x in t for x in ["news", "update", "report"]):
            return "news"
        if any(x in t for x in ["cooking", "recipe", "food"]):
            return "cooking"
        if any(x in t for x in ["workout", "fitness", "yoga"]):
            return "fitness"
        return "general"

    def generate_contextual_description(
        self, idx, total, vtype, uploader, title
    ):
        if idx == 0:
            return "The creator greets viewers and introduces the video."
        if idx == total - 1:
            return "The creator wraps up and thanks viewers."
        return "Content continues according to the video type."

    # ───────── quick-detect helpers (μš”μ•½) ──────
    def detect_video_type(self, title, desc):
        t = (title + " " + desc).lower()
        if any(x in t for x in ["music", "song", "album"]):
            return "🎡 Music"
        if any(x in t for x in ["tutorial", "guide"]):
            return "πŸ“š Tutorial"
        if any(x in t for x in ["comedy", "vlog"]):
            return "🎭 Entertainment"
        if any(x in t for x in ["news", "report"]):
            return "πŸ“° News"
        if any(x in t for x in ["review", "unboxing"]):
            return "⭐ Review"
        return "🎬 General"

    def detect_background_music(self, video_info):
        title = video_info.get("title", "").lower()
        if "music" in title:
            return "🎡 Original music"
        if "tutorial" in title:
            return "πŸ”‡ Minimal music"
        return "🎼 Background music"

    def detect_influencer_status(self, video_info):
        subs = video_info.get("channel_followers", 0)
        if subs > 10_000_000:
            return "🌟 Mega (10 M+)"
        if subs > 1_000_000:
            return "⭐ Major (1 M+)"
        if subs > 100_000:
            return "🎯 Mid (100 K+)"
        return "πŸ‘€"

    @staticmethod
    def format_number(n):
        if n >= 1_000_000:
            return f"{n/1_000_000:.1f} M"
        if n >= 1_000:
            return f"{n/1_000:.1f} K"
        return str(n)

    # ───────── 리포트 ──────
    def format_video_info(self, info):
        title = info.get("title", "")
        uploader = info.get("uploader", "")
        duration = info.get("duration", 0)
        dur = f"{duration//60}:{duration%60:02d}"
        views = info.get("view_count", 0)
        likes = info.get("like_count", 0)
        comments = info.get("comment_count", 0)
        scenes = self.generate_scene_breakdown_gemini(info)

        return f"""
🎬 **{title}**
Uploader: {uploader} Duration: {dur}

Views / Likes / Comments: {self.format_number(views)} / {self.format_number(likes)} / {self.format_number(comments)}

{'-'*48}
{"".join(scenes)}
"""

    # ───────── 메타데이터 μΆ”μΆœ ──────
    def get_video_info(self, url, progress=gr.Progress(), cookiefile=None):
        if not self.is_valid_youtube_url(url):
            return None, "❌ Invalid URL"

        if cookiefile and os.path.exists(cookiefile):
            cookiefile = cookiefile
        elif DEFAULT_COOKIE_FILE.exists():
            cookiefile = str(DEFAULT_COOKIE_FILE)
        else:
            cookiefile = None

        try:
            ydl_opts = {"noplaylist": True, "quiet": True}
            if cookiefile:
                ydl_opts["cookiefile"] = cookiefile
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=False)
            return info, "OK"
        except Exception as e:
            return None, f"yt-dlp error: {e}"

    # ───────── λ‹€μš΄λ‘œλ“œ ──────
    def download_video(
        self, url, quality="best", audio_only=False, progress=gr.Progress(), cookiefile=None
    ):
        if not self.is_valid_youtube_url(url):
            return None, "❌ Invalid URL"
        if cookiefile and os.path.exists(cookiefile):
            cookiefile = cookiefile
        elif DEFAULT_COOKIE_FILE.exists():
            cookiefile = str(DEFAULT_COOKIE_FILE)
        else:
            cookiefile = None

        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        ydl_opts = {
            "outtmpl": os.path.join(self.temp_downloads, f"%(title)s_{ts}.%(ext)s"),
            "noplaylist": True,
        }
        if audio_only:
            ydl_opts["format"] = "bestaudio/best"
            ydl_opts["postprocessors"] = [
                {"key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "192"}
            ]
        else:
            if quality == "720p":
                ydl_opts["format"] = "best[height<=720]"
            elif quality == "480p":
                ydl_opts["format"] = "best[height<=480]"
            else:
                ydl_opts["format"] = "best[height<=1080]"
        if cookiefile:
            ydl_opts["cookiefile"] = cookiefile

        try:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.extract_info(url, download=True)
            # 첫 파일 찾기
            for f in os.listdir(self.temp_downloads):
                if ts in f:
                    temp_fp = os.path.join(self.temp_downloads, f)
                    final_fp = os.path.join(self.downloads_folder, f)
                    try:
                        shutil.copy2(temp_fp, final_fp)
                        saved = final_fp
                    except Exception:
                        saved = temp_fp
                    return temp_fp, f"βœ… Saved: {saved}"
            return None, "❌ Downloaded file not found"
        except Exception as e:
            return None, f"❌ Download failed: {e}"


# =================================================================
# Gradio Helper ν•¨μˆ˜
# =================================================================
downloader = YouTubeDownloader()


def configure_api_key(api_key):
    ok, msg = downloader.configure_gemini(api_key.strip()) if api_key else (False, "❌ API key required")
    return msg, gr.update(visible=ok)


def analyze_with_cookies(url, cookies_file, progress=gr.Progress()):
    info, err = downloader.get_video_info(url, progress, cookies_file)
    return downloader.format_video_info(info) if info else f"❌ {err}"


def download_with_cookies(url, qual, audio, cookies_file, progress=gr.Progress()):
    fp, msg = downloader.download_video(url, qual, audio, progress, cookies_file)
    return fp, msg


def get_transcript(url, cookies_file):
    vid = extract_video_id(url)
    if not vid:
        return "❌ Invalid YouTube URL"
    try:
        return fetch_transcript(vid)
    except Exception as e:
        return f"❌ {e}"


# =================================================================
# UI
# =================================================================
def create_interface():
    with gr.Blocks(
        theme=gr.themes.Soft(), title="πŸŽ₯ YouTube Video Analyzer & Downloader Pro"
    ) as iface:
        gr.HTML("<h1>πŸŽ₯ YouTube Video Analyzer & Downloader Pro</h1>")

        # API μ„€μ •
        with gr.Group():
            gr.HTML("<h3>πŸ”‘ Google Gemini API Configuration</h3>")
            with gr.Row():
                api_key_in = gr.Textbox(
                    label="πŸ”‘ Google API Key", type="password", placeholder="Paste your Google API key…"
                )
                api_btn = gr.Button("πŸ”§ Configure API", variant="secondary")
            api_status = gr.Textbox(
                label="API Status",
                value="❌ Gemini API not configured – Using fallback analysis",
                interactive=False,
                lines=1,
            )

        # 곡톡 μž…λ ₯
        with gr.Row():
            url_in = gr.Textbox(label="πŸ”— YouTube URL", placeholder="Paste YouTube video URL…")
            cookies_in = gr.File(
                label="πŸͺ Upload cookies.txt (optional)", file_types=[".txt"], type="filepath"
            )

        with gr.Tabs():
            # 뢄석 νƒ­
            with gr.TabItem("πŸ“Š Video Analysis"):
                analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
                analysis_out = gr.Textbox(label="πŸ“Š Analysis Report", lines=30, show_copy_button=True)
                analyze_btn.click(
                    analyze_with_cookies, inputs=[url_in, cookies_in], outputs=analysis_out, show_progress=True
                )
            # λ‹€μš΄λ‘œλ“œ νƒ­
            with gr.TabItem("⬇️ Video Download"):
                with gr.Row():
                    quality_dd = gr.Dropdown(
                        choices=["best", "720p", "480p"], value="best", label="πŸ“Ί Quality"
                    )
                    audio_cb = gr.Checkbox(label="🎡 Audio only (MP3)")
                download_btn = gr.Button("⬇️ Download Video", variant="primary")
                dl_status = gr.Textbox(label="πŸ“₯ Download Status", lines=5, show_copy_button=True)
                dl_file = gr.File(label="πŸ“ Downloaded File", visible=False)

                def wrapped_dl(u, q, a, c, prog=gr.Progress()):
                    fp, st = download_with_cookies(u, q, a, c, prog)
                    return (st, gr.update(value=fp, visible=True)) if fp and os.path.exists(fp) else (
                        st,
                        gr.update(visible=False),
                    )

                download_btn.click(
                    wrapped_dl,
                    inputs=[url_in, quality_dd, audio_cb, cookies_in],
                    outputs=[dl_status, dl_file],
                    show_progress=True,
                )
            # μžλ§‰ νƒ­  NEW
            with gr.TabItem("πŸ—’οΈ Transcript"):
                tr_btn = gr.Button("πŸ“œ Get Full Transcript", variant="primary")
                tr_out = gr.Textbox(
                    label="πŸ—’οΈ Transcript (full)", lines=30, show_copy_button=True
                )
                tr_btn.click(
                    get_transcript, inputs=[url_in, cookies_in], outputs=tr_out, show_progress=True
                )

        # API λ²„νŠΌ
        api_btn.click(configure_api_key, inputs=[api_key_in], outputs=[api_status])

        gr.HTML(
            """
<div style="margin-top:20px;padding:15px;background:#f0f8ff;border-left:5px solid #4285f4;border-radius:10px;">
  <h3>πŸ’‘ Tip: μΏ ν‚€ 파일 μžλ™ μ‚¬μš©</h3>
  <p><code>www.youtube.com_cookies.txt</code> νŒŒμΌμ„ <strong>app.py</strong>와 같은
  폴더에 두면 μ—…λ‘œλ“œ 없이 μžλ™ μ‚¬μš©λ©λ‹ˆλ‹€.</p>
</div>
"""
        )
    return iface


# =================================================================
# μ‹€ν–‰
# =================================================================
if __name__ == "__main__":
    demo = create_interface()
    import atexit

    atexit.register(downloader.cleanup)
    demo.launch(debug=True, show_error=True)