File size: 35,553 Bytes
763c94d
 
 
11bafec
 
 
 
 
9dd9c8e
 
11bafec
 
 
 
 
 
 
 
 
 
9dd9c8e
 
11bafec
 
 
9dd9c8e
 
 
11bafec
 
 
 
 
 
9dd9c8e
184adfb
 
 
9dd9c8e
 
11bafec
 
 
 
 
 
 
 
 
 
184adfb
592f28f
11bafec
 
 
 
9dd9c8e
 
11bafec
 
 
 
9dd9c8e
11bafec
592f28f
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b075ad9
11bafec
 
 
 
 
 
 
 
 
 
 
21a72e9
 
 
 
11bafec
 
b075ad9
21a72e9
 
 
 
 
b075ad9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11bafec
 
 
21a72e9
11bafec
 
 
 
 
 
 
 
21a72e9
11bafec
 
 
 
 
21a72e9
11bafec
21a72e9
 
b075ad9
 
11bafec
21a72e9
 
b075ad9
 
 
 
 
 
 
 
21a72e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11bafec
 
 
 
 
 
b075ad9
11bafec
 
 
 
 
21a72e9
11bafec
 
21a72e9
 
 
 
11bafec
b075ad9
11bafec
b075ad9
11bafec
b075ad9
11bafec
b075ad9
9dd9c8e
b075ad9
11bafec
21a72e9
 
11bafec
 
 
 
 
 
 
 
 
21a72e9
b075ad9
 
 
 
 
 
 
 
 
 
21a72e9
 
 
11bafec
21a72e9
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21a72e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21a72e9
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21a72e9
 
 
 
11bafec
 
 
 
 
 
 
 
 
21a72e9
11bafec
21a72e9
 
 
 
 
11bafec
21a72e9
11bafec
21a72e9
 
 
 
11bafec
21a72e9
11bafec
21a72e9
 
 
 
b075ad9
21a72e9
 
11bafec
b075ad9
11bafec
21a72e9
11bafec
21a72e9
11bafec
 
21a72e9
11bafec
 
21a72e9
 
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184adfb
11bafec
 
 
 
 
 
184adfb
 
11bafec
 
 
 
184adfb
11bafec
184adfb
11bafec
 
 
 
 
 
 
 
 
 
184adfb
11bafec
 
 
 
 
 
 
 
 
 
9dd9c8e
11bafec
 
184adfb
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184adfb
 
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184adfb
11bafec
 
 
 
 
 
 
9dd9c8e
 
11bafec
 
 
 
9dd9c8e
 
11bafec
 
9dd9c8e
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dd9c8e
11bafec
9dd9c8e
 
11bafec
 
 
 
 
 
 
 
 
 
9dd9c8e
11bafec
9dd9c8e
11bafec
 
 
 
 
 
 
 
 
 
 
 
763c94d
11bafec
9dd9c8e
11bafec
 
 
 
 
 
 
 
 
9dd9c8e
 
11bafec
 
 
 
 
 
 
 
 
 
 
592f28f
11bafec
184adfb
11bafec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1c4426
763c94d
11bafec
763c94d
11bafec
 
 
763c94d
 
 
11bafec
592f28f
11bafec
 
 
 
e1c4426
11bafec
2c78469
763c94d
11bafec
21a72e9
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
#!/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

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ๊ธฐ๋ณธ ์ฟ ํ‚ค ํŒŒ์ผ ๊ฒฝ๋กœ โ€• ํŒŒ์ผ๋ช…์ด ๋™์ผํ•˜๋ฉด ์ž๋™ ์‚ฌ์šฉ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
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 {
                    "korean": ["**[์žฌ์ƒ์‹œ๊ฐ„ ์•Œ ์ˆ˜ ์—†์Œ]**: ๋น„๋””์˜ค ์žฌ์ƒ์‹œ๊ฐ„์„ ํ™•์ธํ•  ์ˆ˜ ์—†์–ด ํƒ€์ž„์Šคํƒฌํ”„๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค"],
                    "english": ["**[Duration Unknown]**: Unable to generate timestamped breakdown - video duration not available"]
                }

            prompt = f"""
์ด YouTube ๋น„๋””์˜ค์˜ ์Œ์„ฑ/๋Œ€์‚ฌ๋ฅผ ํƒ€์ž„์Šคํƒฌํ”„๋ณ„๋กœ ์ถ”์ถœํ•ด์ฃผ์„ธ์š”.

์ œ๋ชฉ: {title}
์žฌ์ƒ์‹œ๊ฐ„: {duration}์ดˆ
์„ค๋ช…: {description}

๋งค์šฐ ์ค‘์š”ํ•œ ์ง€์นจ:
1. ์‹ค์ œ ์˜์ƒ์—์„œ ๋“ค๋ฆฌ๋Š” ๋Œ€์‚ฌ, ๋‚ด๋ ˆ์ด์…˜, ์Œ์„ฑ์„ ๊ทธ๋Œ€๋กœ ์ ์–ด์ฃผ์„ธ์š”
2. ์žฅ๋ฉด ์„ค๋ช…์ด ์•„๋‹Œ ์‹ค์ œ ์Œ์„ฑ ๋‚ด์šฉ๋งŒ ์ž‘์„ฑํ•˜์„ธ์š”
3. ์Œ์„ฑ์ด ์—†๋Š” ๋ถ€๋ถ„์€ (...) ๋˜๋Š” (๋ฐฐ๊ฒฝ์Œ์•…) ๋“ฑ์œผ๋กœ ํ‘œ์‹œ
4. ํƒ€์ž„์Šคํƒฌํ”„ ๊ฐ€์ด๋“œ๋ผ์ธ:
   - ๋Œ€์‚ฌ๋‚˜ ๋‚ด๋ ˆ์ด์…˜์ด ์‹œ์ž‘ํ•˜๊ณ  ๋๋‚˜๋Š” ์ง€์  ๊ธฐ์ค€
   - ์—ฐ์†๋œ ๋Œ€์‚ฌ๋Š” ํ•˜๋‚˜๋กœ ๋ฌถ์–ด์„œ ํ‘œ์‹œ
   - ์ตœ๋Œ€ํ•œ ์ž์—ฐ์Šค๋Ÿฌ์šด ๋‹จ์œ„๋กœ ๊ตฌ๋ถ„
5. ํ˜•์‹:
   **[MM:SS-MM:SS]**: "์‹ค์ œ ๋Œ€์‚ฌ๋‚˜ ๋‚ด๋ ˆ์ด์…˜ ๋‚ด์šฉ"
   **[MM:SS-MM:SS]**: (๋ฐฐ๊ฒฝ์Œ์•…) ๋˜๋Š” (...์žฅ๋ฉด ์ „ํ™˜...)
6. ๋ชจ๋“  ์Œ์„ฑ ๋‚ด์šฉ์„ ๋น ์ง์—†์ด ์ ์–ด์ฃผ์„ธ์š”
7. ์ž๋ง‰์ด๋‚˜ ํ™”๋ฉด์— ํ‘œ์‹œ๋œ ํ…์ŠคํŠธ๋„ ํฌํ•จํ•˜์„ธ์š”
8. ์žฅ๋ฉด ์„ค๋ช…์€ ์ ˆ๋Œ€ ํ•˜์ง€ ๋งˆ์„ธ์š”. ์˜ค์ง ์Œ์„ฑ๊ณผ ํ…์ŠคํŠธ๋งŒ ์ถ”์ถœํ•˜์„ธ์š”.

์˜ˆ์‹œ:
**[00:00-00:05]**: "์•ˆ๋…•ํ•˜์„ธ์š”. ์˜ค๋Š˜์€ ๋ฏธ๋ฅต์‚ฐ์—์„œ ๋ฐœ๊ฒฌ๋œ ๋ฐฑ์ œ ์œ ์ ์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค."
**[00:05-00:08]**: (๋ฐฐ๊ฒฝ์Œ์•…)
**[00:08-00:15]**: "๋ฏธ๋ฅต์‚ฌ์ง€๋ฅผ ํ’ˆ๊ณ  ์žˆ๋Š” ์ต์‚ฐ ๋ฏธ๋ฅต์‚ฐ์˜ ์ •์ƒ๋ถ€์—์„œ ๋ฐฑ์ œ์‹œ๋Œ€์— ๋งŒ๋“  ๊ฒƒ์œผ๋กœ ์ถ”์ •๋˜๋Š” ์ €์ˆ˜์กฐ๊ฐ€ ๋ฐœ๊ตด๋์Šต๋‹ˆ๋‹ค."
**[00:15-00:18]**: (์ธํ„ฐ๋ทฐ ์ค€๋น„ ์ค‘...)
**[00:18-00:25]**: [์ด๋„ํ•™ ๊ต์ˆ˜] "์ด๋ฒˆ ๋ฐœ๊ตด์€ ๋ฐฑ์ œ ์—ญ์‚ฌ ์—ฐ๊ตฌ์— ์ค‘์š”ํ•œ ์ „ํ™˜์ ์ด ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค."

๋‰ด์Šค์˜ ๊ฒฝ์šฐ:
- ์•ต์ปค๋‚˜ ๊ธฐ์ž์˜ ๋ฉ˜ํŠธ๋Š” ๊ทธ๋Œ€๋กœ ์ ๊ธฐ
- ์ธํ„ฐ๋ทฐ๋Š” [์ธํ„ฐ๋ทฐ์ด ์ด๋ฆ„] "๋‚ด์šฉ" ํ˜•์‹์œผ๋กœ
- ์ž๋ง‰์€ [์ž๋ง‰] ๋‚ด์šฉ ํ˜•์‹์œผ๋กœ
"""
            response = self.gemini_model.generate_content(prompt)

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

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

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

            # ์˜์–ด ๋ฒˆ์—ญ ์ƒ์„ฑ
            english_prompt = f"""
Translate the following Korean speech/dialogue transcription to English, maintaining the exact same timestamps.
Translate ONLY the actual speech content, not descriptions:

{chr(10).join(korean_scenes)}

Important rules:
- Keep the format exactly the same: **[MM:SS-MM:SS]**: "English translation of speech"
- For non-speech parts like (๋ฐฐ๊ฒฝ์Œ์•…), translate as (background music)
- For (...) keep as is
- For interview tags like [์ด๋„ํ•™ ๊ต์ˆ˜], translate as [Professor Lee Do-hak]
- For [์ž๋ง‰], translate as [Subtitle]
- Keep quotation marks for actual speech
- Do NOT add any scene descriptions or explanations
"""
            english_response = self.gemini_model.generate_content(english_prompt)
            
            english_scenes = []
            if english_response and english_response.text:
                lines = english_response.text.split("\n")
                current_scene = ""

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

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

            return {
                "korean": korean_scenes if korean_scenes else self.generate_scene_breakdown_fallback(video_info)["korean"],
                "english": english_scenes if english_scenes else self.generate_scene_breakdown_fallback(video_info)["english"]
            }

        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", "์ฝ˜ํ…์ธ  ์ œ์ž‘์ž")

        if not duration:
            return {
                "korean": ["**[์žฌ์ƒ์‹œ๊ฐ„ ์•Œ ์ˆ˜ ์—†์Œ]**: ํƒ€์ž„์Šคํƒฌํ”„๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค"],
                "english": ["**[Duration Unknown]**: Unable to generate timestamped breakdown"]
            }

        # ๋น„๋””์˜ค ํƒ€์ž…์— ๋”ฐ๋ฅธ ๋Œ€์‚ฌ ํ…œํ”Œ๋ฆฟ
        if duration <= 60:
            segment_length = 10
        elif duration <= 300:
            segment_length = 15
        elif duration <= 900:
            segment_length = 20
        else:
            segment_length = 30

        korean_scenes = []
        english_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}"
            
            # ์Œ์„ฑ ์ถ”์ถœ์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ์˜ ๊ธฐ๋ณธ ํ…œํ”Œ๋ฆฟ
            if i == 0:
                korean_desc = f"(์Œ์„ฑ ์ถ”์ถœ์„ ์œ„ํ•ด Gemini API๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์ธํŠธ๋กœ ๋ถ€๋ถ„...)"
                english_desc = f"(Gemini API required for speech extraction. Intro section...)"
            elif i == num_segments - 1:
                korean_desc = f"(์•„์›ƒํŠธ๋กœ ๋ถ€๋ถ„...)"
                english_desc = f"(Outro section...)"
            else:
                korean_desc = f"(๋ณธ๋ฌธ ๋‚ด์šฉ...)"
                english_desc = f"(Main content...)"
            
            korean_scenes.append(f"**[{start_fmt}-{end_fmt}]**: {korean_desc}")
            english_scenes.append(f"**[{start_fmt}-{end_fmt}]**: {english_desc}")

        return {"korean": korean_scenes, "english": english_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_korean(
        self, scene_index, total_scenes, video_type, uploader, title
    ):
        presenter_desc = "์ฝ˜ํ…์ธ  ์ œ์ž‘์ž"
        if "woman" in title or "girl" in title or "์—ฌ์„ฑ" in title or "์—ฌ์ž" in title:
            presenter_desc = "์—ฌ์„ฑ ์ง„ํ–‰์ž"
        elif "man" in title or "guy" in title or "๋‚จ์„ฑ" in title or "๋‚จ์ž" in title:
            presenter_desc = "๋‚จ์„ฑ ์ง„ํ–‰์ž"

        if scene_index == 0:
            if video_type == "tutorial":
                return f"{presenter_desc}๊ฐ€ ํ™”๋ฉด์— ๋“ฑ์žฅํ•˜์—ฌ ์ž์‹ ์„ ์†Œ๊ฐœํ•˜๊ณ  ์ฃผ์ œ๋ฅผ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค. ๋ฐ์€ ์กฐ๋ช…์˜ ์ž‘์—… ๊ณต๊ฐ„์—์„œ ์บ์ฃผ์–ผํ•œ ์˜ท์„ ์ž…๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค."
            if video_type == "vlog":
                return f"{presenter_desc}๊ฐ€ ์นด๋ฉ”๋ผ๋ฅผ ํ–ฅํ•ด ๋ฐ๊ฒŒ ์ธ์‚ฌํ•˜๋ฉฐ ์˜ค๋Š˜์˜ ๋ธŒ์ด๋กœ๊ทธ ์ฃผ์ œ๋ฅผ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค."
            if video_type == "review":
                return f"{presenter_desc}๊ฐ€ ๋ฆฌ๋ทฐํ•  ์ œํ’ˆ์„ ๋“ค์–ด ๋ณด์ด๋ฉฐ ๊ฐ„๋‹จํ•œ ํŠน์ง•์„ ์†Œ๊ฐœํ•ฉ๋‹ˆ๋‹ค."
            return f"{presenter_desc}๊ฐ€ ์‹œ์ฒญ์ž์˜ ๊ด€์‹ฌ์„ ๋Œ๊ธฐ ์œ„ํ•œ ๋งค๋ ฅ์ ์ธ ์ธํŠธ๋กœ๋กœ ์˜์ƒ์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค."

        if scene_index == total_scenes - 1:
            if video_type == "tutorial":
                return f"{presenter_desc}๊ฐ€ ์ตœ์ข… ๊ฒฐ๊ณผ๋ฌผ์„ ๋ณด์—ฌ์ฃผ๊ณ  ์‹œ์ฒญ์ž์—๊ฒŒ ๊ฐ์‚ฌ ์ธ์‚ฌ๋ฅผ ์ „ํ•˜๋ฉฐ ์ข‹์•„์š”์™€ ๊ตฌ๋…์„ ๋ถ€ํƒํ•ฉ๋‹ˆ๋‹ค."
            if video_type == "vlog":
                return f"{presenter_desc}๊ฐ€ ํ•˜๋ฃจ๋ฅผ ๋งˆ๋ฌด๋ฆฌํ•˜๋ฉฐ ์ตœ์ข… ์ƒ๊ฐ์„ ๊ณต์œ ํ•˜๊ณ  ์ž‘๋ณ„ ์ธ์‚ฌ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค."
            return f"{presenter_desc}๊ฐ€ ์ฃผ์š” ๋‚ด์šฉ์„ ์š”์•ฝํ•˜๊ณ  ์ข‹์•„์š”์™€ ๋Œ“๊ธ€์„ ํ†ตํ•œ ์ฐธ์—ฌ๋ฅผ ๋…๋ คํ•˜๋ฉฐ ๋งˆ๋ฌด๋ฆฌํ•ฉ๋‹ˆ๋‹ค."

        if video_type == "tutorial":
            return f"{presenter_desc}๊ฐ€ ๋‹ค์Œ ๋‹จ๊ณ„๋ฅผ ์‹œ์—ฐํ•˜๋ฉฐ ํด๋กœ์ฆˆ์—… ์ƒท๊ณผ ํ•จ๊ป˜ ๋ช…ํ™•ํ•œ ์ง€์นจ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค."
        if video_type == "review":
            return f"{presenter_desc}๊ฐ€ ์ œํ’ˆ์˜ ํŠน์ • ๊ธฐ๋Šฅ์„ ์‚ดํŽด๋ณด๋ฉฐ ์‚ฌ์šฉ ๋ชจ์Šต์„ ๋ณด์—ฌ์ฃผ๊ณ  ์„ฑ๋Šฅ์— ๋Œ€ํ•ด ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค."
        if video_type == "vlog":
            return f"{presenter_desc}๊ฐ€ ์ผ์ƒ ํ™œ๋™์„ ๊ณ„์†ํ•˜๋ฉฐ ์†”์งํ•œ ์ˆœ๊ฐ„๊ณผ ๊ฐœ์ธ์ ์ธ ์ƒ๊ฐ์„ ๊ณต์œ ํ•ฉ๋‹ˆ๋‹ค."
        if video_type == "cooking":
            return f"{presenter_desc}๊ฐ€ ์žฌ๋ฃŒ๋ฅผ ์ค€๋น„ํ•˜๋ฉฐ ์ž๋ฅด๊ณ  ์„ž์œผ๋ฉด์„œ ๊ฐ ๋‹จ๊ณ„๋ฅผ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค."
        if video_type == "fitness":
            return f"{presenter_desc}๊ฐ€ ์šด๋™ ์„ธํŠธ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉฐ ์˜ฌ๋ฐ”๋ฅธ ์ž์„ธ๋ฅผ ์‹œ์—ฐํ•˜๊ณ  ํŒ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค."
        return f"{presenter_desc}๊ฐ€ ๋ช…ํ™•ํ•œ ์„ค๋ช…์„ ํ†ตํ•ด ์‹œ์ฒญ์ž์™€ ์†Œํ†ตํ•˜๋ฉฐ ์ฃผ์š” ์ฝ˜ํ…์ธ ๋ฅผ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค."

    # ---------------------------------------------------------
    # ์žฅ๋ฉด๋ณ„ ์„ค๋ช… ์ƒ์„ฑ (์˜์–ด - ๊ธฐ์กด ๋ฉ”์„œ๋“œ ์œ ์ง€)
    # ---------------------------------------------------------
    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]}"

        scene_data = self.generate_scene_breakdown_gemini(video_info)
        korean_scenes = scene_data.get("korean", [])
        english_scenes = scene_data.get("english", [])
        
        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}
๐Ÿ†” **๋น„๋””์˜ค ID/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}

๐ŸŽ™๏ธ ์Œ์„ฑ/๋Œ€์‚ฌ ์ถ”์ถœ (ํ•œ๊ตญ์–ด) / SPEECH/DIALOGUE EXTRACTION (KOREAN)
{'โ”€'*30}
{chr(10).join(korean_scenes)}

๐ŸŽ™๏ธ ์Œ์„ฑ/๋Œ€์‚ฌ ์ถ”์ถœ (์˜์–ด) / SPEECH/DIALOGUE EXTRACTION (ENGLISH)
{'โ”€'*30}
{chr(10).join(english_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 ๊ฐ•ํ™”/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
# =================================================================
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",
                    placeholder="Paste your Google API keyโ€ฆ",
                    type="password",
                )
                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,
            )

        # ๋ฉ”์ธ UI
        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=25, show_copy_button=True
                )
                analyze_btn.click(
                    fn=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_download(url, q, a, cfile, progress=gr.Progress()):
                    fp, st = download_with_cookies(url, q, a, cfile, progress)
                    if fp and os.path.exists(fp):
                        return st, gr.update(value=fp, visible=True)
                    return st, gr.update(visible=False)

                download_btn.click(
                    fn=wrapped_download,
                    inputs=[url_in, quality_dd, audio_cb, cookies_in],
                    outputs=[dl_status, dl_file],
                    show_progress=True,
                )

        # API ๋ฒ„ํŠผ ๋™์ž‘
        api_btn.click(
            fn=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


# =================================================================
# Entrypoint
# =================================================================
if __name__ == "__main__":
    demo = create_interface()
    import atexit

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