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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
import gradio as gr
import os
import tempfile
import base64
import math
import traceback
import numpy as np
from PIL import Image

from moviepy.editor import VideoFileClip, vfx
from shutil import copyfile
from datetime import datetime, timedelta

# 별도 CSS 파일 뢈러였기 ν•¨μˆ˜
def load_css():
    """μ™ΈλΆ€ CSS νŒŒμΌμ„ λΆˆλŸ¬μ˜€κ±°λ‚˜, 파일이 없을 경우 λ‚΄μž₯ μŠ€νƒ€μΌ λ°˜ν™˜"""
    try:
        with open('styles.css', 'r', encoding='utf-8') as f:
            return f.read()
    except:
        # 파일이 없을 경우 λ‚΄μž₯ μŠ€νƒ€μΌ λ°˜ν™˜ (닀크λͺ¨λ“œ 지원)
        return """
        /* FontAwesome μ•„μ΄μ½˜ 포함 */
        @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css");
        
        /* ============================================
           닀크λͺ¨λ“œ μžλ™ λ³€κ²½ ν…œν”Œλ¦Ώ CSS
           ============================================ */

        /* 1. CSS λ³€μˆ˜ μ •μ˜ (라이트λͺ¨λ“œ - κΈ°λ³Έκ°’) */
        :root {
            /* 메인 컬러 */
            --primary-color: #FB7F0D;
            --secondary-color: #ff9a8b;
            --accent-color: #FF6B6B;
            
            /* 배경 컬러 */
            --background-color: #FFFFFF;
            --card-bg: #ffffff;
            --input-bg: #ffffff;
            
            /* ν…μŠ€νŠΈ 컬러 */
            --text-color: #334155;
            --text-secondary: #64748b;
            
            /* 보더 및 ꡬ뢄선 */
            --border-color: #dddddd;
            --border-light: #e5e5e5;
            
            /* ν…Œμ΄λΈ” 컬러 */
            --table-even-bg: #f3f3f3;
            --table-hover-bg: #f0f0f0;
            
            /* 그림자 */
            --shadow: 0 8px 30px rgba(251, 127, 13, 0.08);
            --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.1);
            
            /* 기타 */
            --border-radius: 18px;
        }

        /* 2. 닀크λͺ¨λ“œ 색상 λ³€μˆ˜ (μžλ™ 감지) */
        @media (prefers-color-scheme: dark) {
            :root {
                /* 배경 컬러 */
                --background-color: #1a1a1a;
                --card-bg: #2d2d2d;
                --input-bg: #2d2d2d;
                
                /* ν…μŠ€νŠΈ 컬러 */
                --text-color: #e5e5e5;
                --text-secondary: #a1a1aa;
                
                /* 보더 및 ꡬ뢄선 */
                --border-color: #404040;
                --border-light: #525252;
                
                /* ν…Œμ΄λΈ” 컬러 */
                --table-even-bg: #333333;
                --table-hover-bg: #404040;
                
                /* 그림자 */
                --shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
                --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.2);
            }
        }

        /* 3. μˆ˜λ™ 닀크λͺ¨λ“œ 클래슀 (Gradio ν† κΈ€μš©) */
        [data-theme="dark"], 
        .dark,
        .gr-theme-dark {
            /* 배경 컬러 */
            --background-color: #1a1a1a;
            --card-bg: #2d2d2d;
            --input-bg: #2d2d2d;
            
            /* ν…μŠ€νŠΈ 컬러 */
            --text-color: #e5e5e5;
            --text-secondary: #a1a1aa;
            
            /* 보더 및 ꡬ뢄선 */
            --border-color: #404040;
            --border-light: #525252;
            
            /* ν…Œμ΄λΈ” 컬러 */
            --table-even-bg: #333333;
            --table-hover-bg: #404040;
            
            /* 그림자 */
            --shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
            --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        /* 4. κΈ°λ³Έ μš”μ†Œ 닀크λͺ¨λ“œ 적용 */
        body {
            font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
            background-color: var(--background-color) !important;
            color: var(--text-color) !important;
            line-height: 1.6;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        footer {
            visibility: hidden;
        }

        /* 5. Gradio μ»¨ν…Œμ΄λ„ˆ κ°•μ œ 적용 */
        .gradio-container,
        .gradio-container *,
        .gr-app,
        .gr-app *,
        .gr-interface {
            background-color: var(--background-color) !important;
            color: var(--text-color) !important;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            background: linear-gradient(135deg, #FB7F0D, #FF9A5B);
            padding: 2rem;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: var(--shadow);
            text-align: center;
            color: white;
        }
        
        .header h1 {
            margin: 0;
            font-size: 2.5rem;
            font-weight: 700;
        }
        
        .header p {
            margin: 10px 0 0;
            font-size: 1.2rem;
            opacity: 0.9;
        }
        
        .card {
            background-color: var(--card-bg) !important;
            border-radius: var(--border-radius);
            padding: 20px;
            margin: 10px 0;
            box-shadow: var(--shadow);
            border: 1px solid var(--border-color);
            color: var(--text-color) !important;
            transition: all 0.3s ease;
        }
        
        .button-primary {
            border-radius: 30px !important;
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)) !important;
            color: white !important;
            font-size: 18px !important;
            padding: 10px 20px !important;
            border: none;
            box-shadow: 0 4px 8px rgba(251, 127, 13, 0.25);
            transition: transform 0.3s ease;
            text-align: center;
            font-weight: 600;
        }
        
        .button-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(251, 127, 13, 0.3);
        }
        
        .section-title {
            display: flex;
            align-items: center;
            font-size: 20px;
            font-weight: 700;
            color: var(--text-color) !important;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid var(--primary-color);
        }
        
        .section-title i {
            margin-right: 10px;
            color: var(--primary-color);
        }
        
        .guide-container {
            background-color: var(--card-bg) !important;
            border-radius: var(--border-radius);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid var(--border-color);
            color: var(--text-color) !important;
        }
        
        .guide-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: var(--primary-color) !important;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
        }
        
        .guide-title i {
            margin-right: 0.8rem;
            font-size: 1.3rem;
        }
        
        .guide-item {
            display: flex;
            margin-bottom: 0.8rem;
            align-items: flex-start;
        }
        
        .guide-number {
            background-color: var(--primary-color);
            color: white;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
            flex-shrink: 0;
            font-size: 14px;
        }
        
        .guide-text {
            flex: 1;
            line-height: 1.6;
            color: var(--text-color) !important;
        }
        
        .feature-tag {
            display: inline-block;
            background-color: rgba(251, 127, 13, 0.1);
            color: var(--primary-color);
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            margin-right: 8px;
            margin-bottom: 8px;
        }
        
        .input-label {
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--text-color) !important;
        }
        
        /* 6. μΉ΄λ“œ 및 νŒ¨λ„ μŠ€νƒ€μΌ */
        .gr-form,
        .gr-box,
        .gr-panel,
        .custom-frame,
        [class*="frame"],
        [class*="panel"] {
            background-color: var(--card-bg) !important;
            border-color: var(--border-color) !important;
            color: var(--text-color) !important;
            box-shadow: var(--shadow) !important;
        }

        /* 7. μž…λ ₯ ν•„λ“œ μŠ€νƒ€μΌ */
        input[type="text"],
        input[type="number"],
        input[type="email"],
        input[type="password"],
        textarea,
        select,
        .gr-input,
        .gr-text-input,
        .gr-textarea,
        .gr-dropdown {
            background-color: var(--input-bg) !important;
            color: var(--text-color) !important;
            border-color: var(--border-color) !important;
            border-radius: var(--border-radius) !important;
            border: 1px solid var(--border-color) !important;
            padding: 12px !important;
            transition: all 0.3s ease !important;
        }

        input[type="text"]:focus,
        input[type="number"]:focus,
        input[type="email"]:focus,
        input[type="password"]:focus,
        textarea:focus,
        select:focus,
        .gr-input:focus,
        .gr-text-input:focus,
        .gr-textarea:focus,
        .gr-dropdown:focus {
            border-color: var(--primary-color) !important;
            outline: none !important;
            box-shadow: 0 0 0 2px rgba(251, 127, 13, 0.2) !important;
        }

        /* 8. 라벨 및 ν…μŠ€νŠΈ μš”μ†Œ */
        label,
        .gr-label,
        .gr-checkbox label,
        .gr-radio label,
        p, span, div {
            color: var(--text-color) !important;
        }

        /* 9. ν…Œμ΄λΈ” μŠ€νƒ€μΌ */
        table {
            background-color: var(--card-bg) !important;
            color: var(--text-color) !important;
            border-color: var(--border-color) !important;
        }

        table th {
            background-color: var(--primary-color) !important;
            color: white !important;
            border-color: var(--border-color) !important;
        }

        table td {
            background-color: var(--card-bg) !important;
            color: var(--text-color) !important;
            border-color: var(--border-color) !important;
        }

        table tbody tr:nth-child(even) {
            background-color: var(--table-even-bg) !important;
        }

        table tbody tr:hover {
            background-color: var(--table-hover-bg) !important;
        }

        /* 10. μ²΄ν¬λ°•μŠ€ 및 λΌλ””μ˜€ λ²„νŠΌ */
        input[type="checkbox"],
        input[type="radio"] {
            accent-color: var(--primary-color) !important;
        }

        /* 11. μŠ€ν¬λ‘€λ°” μŠ€νƒ€μΌ */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--card-bg);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--primary-color);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--secondary-color);
        }

        /* 12. μ•„μ½”λ””μ–Έ 및 λ“œλ‘­λ‹€μš΄ */
        details {
            background-color: var(--card-bg) !important;
            border-color: var(--border-color) !important;
            color: var(--text-color) !important;
        }

        details summary {
            background-color: var(--card-bg) !important;
            color: var(--text-color) !important;
        }

        /* 13. μΆ”κ°€ Gradio μ»΄ν¬λ„ŒνŠΈλ“€ */
        .gr-block,
        .gr-group,
        .gr-row,
        .gr-column {
            background-color: var(--background-color) !important;
            color: var(--text-color) !important;
        }

        /* 14. λ²„νŠΌμ€ κΈ°μ‘΄ μŠ€νƒ€μΌ μœ μ§€ (primary-color μ‚¬μš©) */
        button:not([class*="custom"]):not([class*="primary"]):not([class*="secondary"]) {
            background-color: var(--card-bg) !important;
            color: var(--text-color) !important;
            border-color: var(--border-color) !important;
        }

        /* 15. μ½”λ“œ 블둝 및 pre νƒœκ·Έ */
        code,
        pre,
        .code-block {
            background-color: var(--table-even-bg) !important;
            color: var(--text-color) !important;
            border-color: var(--border-color) !important;
        }

        /* 16. μ „ν™˜ μ• λ‹ˆλ©”μ΄μ…˜ */
        * {
            transition: background-color 0.3s ease, 
                        color 0.3s ease, 
                        border-color 0.3s ease !important;
        }
        
        /* κΈ°μ‘΄ GIF λ³€ν™˜κΈ° μ „μš© μŠ€νƒ€μΌ μœ μ§€ */
        .left-column, .right-column {
            border: 2px solid var(--primary-color);
            border-radius: var(--border-radius);
            padding: 20px;
            background-color: var(--card-bg) !important;
            color: var(--text-color) !important;
        }
        .left-column {
            margin-right: 10px;
        }
        .right-column {
            margin-left: 10px;
        }
        .section-border {
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 10px;
            margin-bottom: 15px;
            background-color: var(--card-bg) !important;
            color: var(--text-color) !important;
        }
        """

########################################
# 1) PIL ANTIALIAS μ—λŸ¬ λŒ€μ‘ (Monkey-patch)
########################################
try:
    from PIL import Resampling
    if not hasattr(Image, "ANTIALIAS"):
        Image.ANTIALIAS = Resampling.LANCZOS
except ImportError:
    pass

########################################
# 2) λ‚΄λΆ€ 디버그 λ‘œκΉ… (UIμ—μ„œ 미좜λ ₯)
########################################
DEBUG_LOG_LIST = []

def log_debug(msg: str):
    print("[DEBUG]", msg)
    DEBUG_LOG_LIST.append(msg)

########################################
# 3) μ‹œκ°„ ν˜•μ‹ λ³€ν™˜ μœ ν‹Έλ¦¬ν‹° ν•¨μˆ˜
########################################
END_EPSILON = 0.01

def round_down_to_one_decimal(value: float) -> float:
    return math.floor(value * 10) / 10

def safe_end_time(duration: float) -> float:
    tmp = duration - END_EPSILON
    if tmp < 0:
        tmp = 0
    return round_down_to_one_decimal(tmp)

def coalesce_to_zero(val):
    """
    Noneμ΄λ‚˜ NaN, λ¬Έμžμ—΄ 였λ₯˜ 등이 λ“€μ–΄μ˜€λ©΄ 0.0으둜 λ³€ν™˜
    """
    if val is None:
        return 0.0
    try:
        return float(val)
    except:
        return 0.0

def seconds_to_hms(seconds: float) -> str:
    """초λ₯Ό HH:MM:SS ν˜•μ‹μœΌλ‘œ λ³€ν™˜"""
    try:
        seconds = max(0, seconds)
        td = timedelta(seconds=round(seconds))
        return str(td)
    except Exception as e:
        log_debug(f"[seconds_to_hms] λ³€ν™˜ 였λ₯˜: {e}")
        return "00:00:00"

def hms_to_seconds(time_str: str) -> float:
    """HH:MM:SS ν˜•μ‹μ„ 초둜 λ³€ν™˜"""
    try:
        parts = time_str.strip().split(':')
        parts = [int(p) for p in parts]
        while len(parts) < 3:
            parts.insert(0, 0)  # λΆ€μ‘±ν•œ 뢀뢄은 0으둜 채움
        hours, minutes, seconds = parts
        return hours * 3600 + minutes * 60 + seconds
    except Exception as e:
        log_debug(f"[hms_to_seconds] λ³€ν™˜ 였λ₯˜: {e}")
        return -1  # 였λ₯˜ μ‹œ -1 λ°˜ν™˜

########################################
# 4) μ—…λ‘œλ“œλœ μ˜μƒ 파일 μ €μž₯
########################################
def save_uploaded_video(video_input):
    if not video_input:
        log_debug("[save_uploaded_video] video_input is None.")
        return None

    if isinstance(video_input, str):
        log_debug(f"[save_uploaded_video] video_input is str: {video_input}")
        if os.path.exists(video_input):
            return video_input
        else:
            log_debug("[save_uploaded_video] Path does not exist.")
            return None

    if isinstance(video_input, dict):
        log_debug(f"[save_uploaded_video] video_input is dict: {list(video_input.keys())}")
        if 'data' in video_input:
            file_data = video_input['data']
            if isinstance(file_data, str) and file_data.startswith("data:"):
                base64_str = file_data.split(';base64,')[-1]
                try:
                    video_binary = base64.b64decode(base64_str)
                    tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
                    tmp.write(video_binary)
                    tmp.flush()
                    tmp.close()
                    log_debug(f"[save_uploaded_video] Created temp file: {tmp.name}")
                    return tmp.name
                except Exception as e:
                    log_debug(f"[save_uploaded_video] base64 λ””μ½”λ”© 였λ₯˜: {e}")
                    return None
            else:
                if isinstance(file_data, str) and os.path.exists(file_data):
                    log_debug("[save_uploaded_video] data ν•„λ“œκ°€ μ‹€μ œ 경둜")
                    return file_data
                else:
                    log_debug("[save_uploaded_video] data ν•„λ“œκ°€ μ˜ˆμƒμΉ˜ λͺ»ν•œ ν˜•νƒœ.")
                    return None
        else:
            log_debug("[save_uploaded_video] dictμ΄μ§€λ§Œ 'data' ν‚€κ°€ μ—†μŒ.")
        return None

    log_debug("[save_uploaded_video] Unrecognized type.")
    return None

########################################
# 5) μ˜μƒ 길이, 해상도, μŠ€ν¬λ¦°μƒ·
########################################
def get_video_duration(video_dict):
    path = save_uploaded_video(video_dict)
    if not path:
        return "00:00:00"
    try:
        clip = VideoFileClip(path)
        dur = clip.duration
        clip.close()
        log_debug(f"[get_video_duration] duration={dur}")
        return seconds_to_hms(dur)
    except Exception as e:
        log_debug(f"[get_video_duration] 였λ₯˜: {e}\n{traceback.format_exc()}")
        return "00:00:00"

def get_resolution(video_dict):
    path = save_uploaded_video(video_dict)
    if not path:
        return "0x0"
    try:
        clip = VideoFileClip(path)
        w, h = clip.size
        clip.close()
        log_debug(f"[get_resolution] w={w}, h={h}")
        return f"{w}x{h}"
    except Exception as e:
        log_debug(f"[get_resolution] 였λ₯˜: {e}\n{traceback.format_exc()}")
        return "0x0"

def get_screenshot_at_time(video_dict, time_in_seconds):
    path = save_uploaded_video(video_dict)
    if not path:
        return None
    try:
        clip = VideoFileClip(path)
        actual_duration = clip.duration

        # λ§ˆμ§€λ§‰ ν”„λ ˆμž„ μ ‘κ·Ό λ°©μ§€
        if time_in_seconds >= actual_duration - END_EPSILON:
            time_in_seconds = safe_end_time(actual_duration)

        t = max(0, min(time_in_seconds, clip.duration))
        log_debug(f"[get_screenshot_at_time] t={t:.3f} / duration={clip.duration:.3f}")
        frame = clip.get_frame(t)
        clip.close()
        return frame  # numpy λ°°μ—΄λ‘œ λ°˜ν™˜
    except Exception as e:
        log_debug(f"[get_screenshot_at_time] 였λ₯˜: {e}\n{traceback.format_exc()}")
        return None

########################################
# 6) μ—…λ‘œλ“œ 이벀트
########################################
def on_video_upload(video_dict):
    log_debug("[on_video_upload] Called.")
    dur_hms = get_video_duration(video_dict)
    w, h = map(int, get_resolution(video_dict).split('x'))
    resolution_str = f"{w}x{h}"

    start_t = 0.0
    end_t = safe_end_time(hms_to_seconds(dur_hms))

    start_img = get_screenshot_at_time(video_dict, start_t)
    end_img = None
    if end_t > 0:
        end_img = get_screenshot_at_time(video_dict, end_t)

    # μˆœμ„œλŒ€λ‘œ: μ˜μƒ 길이, 해상도(λ¬Έμžμ—΄), μ‹œμž‘ μ‹œκ°„, 끝 μ‹œκ°„, μ‹œμž‘ μŠ€ν¬λ¦°μƒ·, 끝 μŠ€ν¬λ¦°μƒ·
    return dur_hms, resolution_str, seconds_to_hms(start_t), seconds_to_hms(end_t), start_img, end_img

########################################
# 7) μŠ€ν¬λ¦°μƒ· κ°±μ‹ 
########################################
def update_screenshots(video_dict, start_time_str, end_time_str):
    start_time = hms_to_seconds(start_time_str)
    end_time = hms_to_seconds(end_time_str)

    if start_time < 0 or end_time < 0:
        return (None, None)

    log_debug(f"[update_screenshots] start={start_time_str}, end={end_time_str}")

    end_time = round_down_to_one_decimal(end_time)
    img_start = get_screenshot_at_time(video_dict, start_time)
    img_end = get_screenshot_at_time(video_dict, end_time)
    return (img_start, img_end)

########################################
# 8) GIF 생성
########################################
def generate_gif(video_dict, start_time_str, end_time_str, fps, resize_factor, speed_factor, duration, resolution_str):
    # "WxH" ν˜•νƒœ 해상도 νŒŒμ‹±
    parts = resolution_str.split("x")
    if len(parts) == 2:
        try:
            orig_w = float(parts[0])
            orig_h = float(parts[1])
        except:
            orig_w = 0
            orig_h = 0
    else:
        orig_w = 0
        orig_h = 0

    start_time = hms_to_seconds(start_time_str)
    end_time = hms_to_seconds(end_time_str)

    if start_time < 0 or end_time < 0:
        return "잘λͺ»λœ μ‹œκ°„ ν˜•μ‹μž…λ‹ˆλ‹€. HH:MM:SS ν˜•μ‹μœΌλ‘œ μž…λ ₯ν•΄μ£Όμ„Έμš”."

    fps = coalesce_to_zero(fps)
    resize_factor = coalesce_to_zero(resize_factor)
    speed_factor = coalesce_to_zero(speed_factor)

    log_debug("[generate_gif] Called.")
    log_debug(f"  start_time={start_time}, end_time={end_time}, fps={fps}, resize_factor={resize_factor}, speed_factor={speed_factor}")

    path = save_uploaded_video(video_dict)
    if not path:
        err_msg = "[generate_gif] μ˜μƒμ΄ μ—…λ‘œλ“œλ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€."
        log_debug(err_msg)
        return err_msg

    try:
        clip = VideoFileClip(path)
        end_time = round_down_to_one_decimal(end_time)

        st = max(0, start_time)
        et = max(0, end_time)
        if et > clip.duration:
            et = clip.duration

        # λ§ˆμ§€λ§‰ ν”„λ ˆμž„ μ ‘κ·Ό λ°©μ§€
        if et >= clip.duration - END_EPSILON:
            et = safe_end_time(clip.duration)

        log_debug(f"  subclip range => st={st:.2f}, et={et:.2f}, totalDur={clip.duration:.2f}")

        if st >= et:
            clip.close()
            err_msg = "μ‹œμž‘ μ‹œκ°„μ΄ 끝 μ‹œκ°„λ³΄λ‹€ κ°™κ±°λ‚˜ ν½λ‹ˆλ‹€."
            log_debug(f"[generate_gif] {err_msg}")
            return err_msg

        sub_clip = clip.subclip(st, et)

        # 배속 μ‘°μ •
        if speed_factor != 1.0:
            sub_clip = sub_clip.fx(vfx.speedx, speed_factor)
            log_debug(f"  speed_factor applied: {speed_factor}x")

        # λ¦¬μ‚¬μ΄μ¦ˆ
        if resize_factor < 1.0 and orig_w > 0 and orig_h > 0:
            new_w = int(orig_w * resize_factor)
            new_h = int(orig_h * resize_factor)
            log_debug(f"  resizing => {new_w}x{new_h}")
            sub_clip = sub_clip.resize((new_w, new_h))

        # κ³ μœ ν•œ 파일 이름 생성
        gif_fd, gif_path = tempfile.mkstemp(suffix=".gif")
        os.close(gif_fd)  # 파일 λ””μŠ€ν¬λ¦½ν„° λ‹«κΈ°

        log_debug(f"  writing GIF to {gif_path}")
        sub_clip.write_gif(gif_path, fps=int(fps), program='ffmpeg')  # ffmpeg μ‚¬μš©

        clip.close()
        sub_clip.close()

        if os.path.exists(gif_path):
            log_debug(f"  GIF 생성 μ™„λ£Œ! size={os.path.getsize(gif_path)} bytes.")
            return gif_path
        else:
            err_msg = "GIF 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€."
            log_debug(f"[generate_gif] {err_msg}")
            return err_msg

    except Exception as e:
        err_msg = f"[generate_gif] 였λ₯˜ λ°œμƒ: {e}\n{traceback.format_exc()}"
        log_debug(err_msg)
        return err_msg

########################################
# 9) GIF λ‹€μš΄λ‘œλ“œ 파일 이름 λ³€κ²½ ν•¨μˆ˜
########################################
def prepare_download_gif(gif_path, input_video_dict):
    """GIF 파일의 λ‹€μš΄λ‘œλ“œ 이름을 λ³€κ²½ν•˜κ³  경둜λ₯Ό λ°˜ν™˜"""
    if gif_path is None:
        return None

    # ν•œκ΅­ μ‹œκ°„ νƒ€μž„μŠ€νƒ¬ν”„ 생성 ν•¨μˆ˜
    def get_korean_timestamp():
        korea_time = datetime.utcnow() + timedelta(hours=9)
        return korea_time.strftime('%Y%m%d_%H%M%S')

    timestamp = get_korean_timestamp()
    
    # μž…λ ₯된 GIF μ΄λ¦„μ—μ„œ κΈ°λ³Έ 이름 μΆ”μΆœ
    if input_video_dict and isinstance(input_video_dict, dict) and 'data' in input_video_dict:
        file_data = input_video_dict['data']
        if isinstance(file_data, str) and file_data.startswith("data:"):
            base_name = "GIF"  # base64 λ°μ΄ν„°μ—μ„œλŠ” 원본 파일 이름을 μ•Œ 수 μ—†μœΌλ―€λ‘œ κΈ°λ³Έ 이름 μ‚¬μš©
        elif isinstance(file_data, str) and os.path.exists(file_data):
            base_name = os.path.splitext(os.path.basename(file_data))[0]
        else:
            base_name = "GIF"
    else:
        base_name = "GIF"

    # μƒˆλ‘œμš΄ 파일 이름 생성
    file_name = f"[끝μž₯AI]끝μž₯GIF_{base_name}_{timestamp}.gif"

    # μž„μ‹œ 디렉토리에 파일 μ €μž₯
    temp_file_path = os.path.join(tempfile.gettempdir(), file_name)
    
    try:
        # κΈ°μ‘΄ GIF νŒŒμΌμ„ μƒˆλ‘œμš΄ μ΄λ¦„μœΌλ‘œ 볡사
        copyfile(gif_path, temp_file_path)
    except Exception as e:
        log_debug(f"[prepare_download_gif] 파일 볡사 였λ₯˜: {e}")
        return gif_path  # 볡사에 μ‹€νŒ¨ν•˜λ©΄ 원본 경둜 λ°˜ν™˜
    
    return temp_file_path

########################################
# 10) 콜백 ν•¨μˆ˜
########################################
def on_any_change(video_dict, start_time_str, end_time_str):
    # μŠ€ν¬λ¦°μƒ·λ§Œ μ—…λ°μ΄νŠΈ
    start_img, end_img = update_screenshots(video_dict, start_time_str, end_time_str)
    return (start_img, end_img)

def on_generate_click(video_dict, start_time_str, end_time_str, fps, resize_factor, speed_factor, duration, resolution_str):
    """GIF 생성 ν›„:
       - μ„±κ³΅μ‹œ: (μƒμ„±λœ GIF 경둜, 파일 μš©λŸ‰ λ¬Έμžμ—΄, 파일 λ‹€μš΄λ‘œλ“œ 경둜)
       - μ‹€νŒ¨μ‹œ: (None, μ—λŸ¬ λ©”μ‹œμ§€, None)
    """
    # Convert duration from hms to seconds for internal use if needed
    # durationλŠ” ν˜„μž¬ μ‚¬μš©λ˜μ§€ μ•ŠμœΌλ―€λ‘œ λ¬΄μ‹œν•˜κ±°λ‚˜ ν•„μš” μ‹œ μ²˜λ¦¬ν•  수 있음

    result = generate_gif(video_dict, start_time_str, end_time_str, fps, resize_factor, speed_factor, duration, resolution_str)

    if isinstance(result, str) and os.path.exists(result):
        # GIF 생성 성곡
        size_bytes = os.path.getsize(result)
        size_mb = size_bytes / (1024 * 1024)
        file_size_str = f"{size_mb:.2f} MB"

        # λ‹€μš΄λ‘œλ“œ 파일 이름 λ³€κ²½
        download_path = prepare_download_gif(result, video_dict)

        # Gradioκ°€ μžλ™μœΌλ‘œ νŒŒμΌμ„ μ²˜λ¦¬ν•˜λ„λ‘ `download_path`λ₯Ό λ°˜ν™˜
        return (result, file_size_str, download_path)
    else:
        # GIF 생성 μ‹€νŒ¨, μ—λŸ¬ λ©”μ‹œμ§€ λ°˜ν™˜
        err_msg = result if isinstance(result, str) else "GIF 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€."
        return (None, err_msg, None)

########################################
# 11) Gradio UI
########################################

with gr.Blocks(
    theme=gr.themes.Soft(
        primary_hue=gr.themes.Color(
            c50="#FFF7ED",  # κ°€μž₯ 밝은 μ£Όν™©
            c100="#FFEDD5",
            c200="#FED7AA",
            c300="#FDBA74",
            c400="#FB923C",
            c500="#F97316",  # κΈ°λ³Έ μ£Όν™©
            c600="#EA580C",
            c700="#C2410C",
            c800="#9A3412",
            c900="#7C2D12",  # κ°€μž₯ μ–΄λ‘μš΄ μ£Όν™©
            c950="#431407",
        ),
        secondary_hue="zinc",  # λͺ¨λ˜ν•œ λŠλ‚Œμ˜ νšŒμƒ‰ 계열
        neutral_hue="zinc",
        font=("Pretendard", "sans-serif")
    ),
    css=load_css()  # μ™ΈλΆ€ CSS 파일 λ˜λŠ” λ‚΄μž₯ μŠ€νƒ€μΌ λ‘œλ“œ
) as demo:
    # FontAwesome μ•„μ΄μ½˜ 헀더 μΆ”κ°€
    gr.HTML("""
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
    """)
    
    with gr.Row():
        # μ™Όμͺ½ 컬럼: μ˜μƒ μ—…λ‘œλ“œ 및 정보
        with gr.Column(elem_classes="left-column"):
            # μ˜μƒ μ—…λ‘œλ“œ μ„Ήμ…˜
            with gr.Row(elem_classes="card"):
                gr.HTML('<div class="section-title"><i class="fas fa-cloud-upload-alt"></i> μ˜μƒ μ—…λ‘œλ“œ</div>')
                video_input = gr.Video(label="")

            # μ˜μƒ 길이 및 해상도 μ„Ήμ…˜
            with gr.Row(elem_classes="card"):
                gr.HTML('<div class="section-title"><i class="fas fa-info-circle"></i> μ˜μƒ 정보</div>')
                duration_box = gr.Textbox(label="μ˜μƒ 길이", interactive=False, value="00:00:00")
                resolution_box = gr.Textbox(label="해상도", interactive=False, value="0x0")

        # 였λ₯Έμͺ½ 컬럼: κ²°κ³Ό GIF 및 λ‹€μš΄λ‘œλ“œ
        with gr.Column(elem_classes="right-column"):
            # κ²°κ³Ό GIF μ„Ήμ…˜
            with gr.Row(elem_classes="card"):
                gr.HTML('<div class="section-title"><i class="fas fa-image"></i> κ²°κ³Ό GIF</div>')
                output_gif = gr.Image(label="")

            # 파일 μš©λŸ‰ 및 λ‹€μš΄λ‘œλ“œ μ„Ήμ…˜
            with gr.Row(elem_classes="card"):
                gr.HTML('<div class="section-title"><i class="fas fa-download"></i> λ‹€μš΄λ‘œλ“œ</div>')
                file_size_text = gr.Textbox(label="파일 μš©λŸ‰", interactive=False, value="0 MB")
                download_gif_component = gr.File(label="GIF λ‹€μš΄λ‘œλ“œ")

    # μΆ”κ°€ μ„€μ • μ„Ήμ…˜
    with gr.Row():
        with gr.Column():
            # μ‹œκ°„ μ„€μ • μ„Ήμ…˜
            with gr.Column(elem_classes="card"):
                gr.HTML('<div class="section-title"><i class="fas fa-clock"></i> μ‹œκ°„ μ„€μ •</div>')
                with gr.Row():
                    start_time_input = gr.Textbox(label="μ‹œμž‘ μ‹œκ°„ (HH:MM:SS)", value="00:00:00")
                    end_time_input = gr.Textbox(label="끝 μ‹œκ°„ (HH:MM:SS)", value="00:00:00")

            # μŠ€ν¬λ¦°μƒ· μ„Ήμ…˜
            with gr.Row(elem_classes="card"):
                gr.HTML('<div class="section-title"><i class="fas fa-camera"></i> 미리보기</div>')
                start_screenshot = gr.Image(label="μ‹œμž‘ 지점 캑쳐본")
                end_screenshot = gr.Image(label="끝 지점 캑쳐본")

            # μ„€μ • μŠ¬λΌμ΄λ” μ„Ήμ…˜
            with gr.Column(elem_classes="card"):
                gr.HTML('<div class="section-title"><i class="fas fa-sliders-h"></i> λ³€ν™˜ μ„€μ •</div>')
                
                # 배속 쑰절 μŠ¬λΌμ΄λ”
                speed_slider = gr.Slider(
                    label="배속",
                    minimum=0.5,
                    maximum=2.0,
                    step=0.1,
                    value=1.0,
                    info="0.5x: 절반 속도, 1.0x: μ›λž˜ 속도, 2.0x: 두 λ°° 속도"
                )

                # FPS μŠ¬λΌμ΄λ”
                fps_slider = gr.Slider(
                    label="FPS",
                    minimum=1,
                    maximum=30,
                    step=1,
                    value=10,
                    info="ν”„λ ˆμž„ 수λ₯Ό μ‘°μ ˆν•˜μ—¬ μ• λ‹ˆλ©”μ΄μ…˜μ˜ λΆ€λ“œλŸ¬μ›€μ„ λ³€κ²½ν•©λ‹ˆλ‹€."
                )

                # 해상도 배율 μŠ¬λΌμ΄λ”
                resize_slider = gr.Slider(
                    label="해상도 배율",
                    minimum=0.1,
                    maximum=1.0,
                    step=0.05,
                    value=1.0,
                    info="GIF의 해상도λ₯Ό μ‘°μ ˆν•©λ‹ˆλ‹€."
                )

            # GIF 생성 λ²„νŠΌ μ„Ήμ…˜
            with gr.Row(elem_classes="card"):
                generate_button = gr.Button("✨ GIF μƒμ„±ν•˜κΈ°", elem_classes="button-primary")

    # 이벀트 콜백 μ„€μ •
    # μ—…λ‘œλ“œ μ‹œ β†’ μ˜μƒ 길이, 해상도 μ—…λ°μ΄νŠΈ
    video_input.change(
        fn=on_video_upload,
        inputs=[video_input],
        outputs=[
            duration_box,    # μ˜μƒ 길이
            resolution_box,  # 해상도("WxH")
            start_time_input,
            end_time_input,
            start_screenshot,
            end_screenshot
        ]
    )

    # μ‹œμž‘/끝 μ‹œκ°„ λ³€κ²½ μ‹œ β†’ μŠ€ν¬λ¦°μƒ· μ—…λ°μ΄νŠΈ
    for c in [start_time_input, end_time_input]:
        c.change(
            fn=on_any_change,
            inputs=[video_input, start_time_input, end_time_input],
            outputs=[start_screenshot, end_screenshot]
        )

    # 배속, FPS, 해상도 배율 λ³€κ²½ μ‹œ β†’ μŠ€ν¬λ¦°μƒ· μ—…λ°μ΄νŠΈ
    for c in [speed_slider, fps_slider, resize_slider]:
        c.change(
            fn=on_any_change,
            inputs=[video_input, start_time_input, end_time_input],
            outputs=[start_screenshot, end_screenshot]
        )

    # GIF 생성 λ²„νŠΌ 클릭 μ‹œ β†’ GIF 생성 및 κ²°κ³Ό μ—…λ°μ΄νŠΈ
    generate_button.click(
        fn=on_generate_click,
        inputs=[
            video_input,
            start_time_input,
            end_time_input,
            fps_slider,
            resize_slider,
            speed_slider,      # 배속 μŠ¬λΌμ΄λ” μΆ”κ°€
            duration_box,
            resolution_box
        ],
        outputs=[
            output_gif,            # μƒμ„±λœ GIF 미리보기
            file_size_text,        # 파일 μš©λŸ‰ ν‘œμ‹œ
            download_gif_component # λ‹€μš΄λ‘œλ“œ 링크
        ]
    )

demo.launch()