File size: 48,243 Bytes
44f4dde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beda4f
44f4dde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75c3863
 
 
 
 
 
 
 
44f4dde
 
 
 
 
 
75c3863
44f4dde
 
75c3863
44f4dde
75c3863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44f4dde
75c3863
 
 
 
 
 
44f4dde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75c3863
 
44f4dde
12996e6
44f4dde
75c3863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44f4dde
 
 
5beda4f
 
 
75c3863
5beda4f
 
 
75c3863
 
 
5beda4f
 
44f4dde
5beda4f
 
 
 
 
 
 
 
 
 
44f4dde
 
 
 
 
 
 
 
5beda4f
 
 
 
44f4dde
 
 
 
5beda4f
 
 
 
 
 
 
 
 
44f4dde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beda4f
 
 
 
 
 
 
 
 
 
44f4dde
 
5beda4f
 
44f4dde
 
 
 
 
 
 
5beda4f
 
 
44f4dde
 
 
 
 
5beda4f
 
 
 
 
 
 
 
 
 
44f4dde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beda4f
44f4dde
 
 
 
 
 
 
 
 
5beda4f
 
 
 
 
 
44f4dde
 
 
 
 
 
12996e6
 
 
 
 
44f4dde
 
12996e6
 
 
 
75c3863
12996e6
44f4dde
 
12996e6
 
 
 
 
 
44f4dde
 
 
 
 
 
75c3863
44f4dde
 
 
 
 
 
 
75c3863
44f4dde
 
 
 
 
 
 
75c3863
44f4dde
 
 
 
 
 
 
 
 
 
 
 
75c3863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beda4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f0666
5beda4f
75c3863
 
5beda4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75c3863
5beda4f
 
f2f0666
5beda4f
 
 
 
f2f0666
75c3863
 
 
 
 
5beda4f
75c3863
 
 
 
5beda4f
 
 
 
 
 
 
75c3863
 
 
 
5beda4f
 
 
 
 
 
75c3863
 
 
 
 
 
 
 
5beda4f
 
 
75c3863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beda4f
75c3863
5beda4f
75c3863
 
5beda4f
 
 
 
 
 
 
 
 
 
75c3863
 
 
 
 
 
5beda4f
 
75c3863
5beda4f
 
75c3863
5beda4f
 
75c3863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f0666
75c3863
f2f0666
5beda4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f0666
5beda4f
75c3863
f2f0666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beda4f
f2f0666
 
 
 
 
 
5beda4f
f2f0666
 
 
 
75c3863
5beda4f
 
 
 
75c3863
5beda4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f0666
5beda4f
 
 
 
 
 
 
 
 
 
 
75c3863
 
5beda4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75c3863
44f4dde
5beda4f
 
 
 
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
import gradio as gr
from gradio_toggle import Toggle
import torch
from huggingface_hub import snapshot_download
from transformers import pipeline

from xora.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
from xora.models.transformers.transformer3d import Transformer3DModel
from xora.models.transformers.symmetric_patchifier import SymmetricPatchifier
from xora.schedulers.rf import RectifiedFlowScheduler
from xora.pipelines.pipeline_xora_video import XoraVideoPipeline
from transformers import T5EncoderModel, T5Tokenizer
from xora.utils.conditioning_method import ConditioningMethod
from pathlib import Path
import safetensors.torch
import json
import numpy as np
import cv2
from PIL import Image
import tempfile
import os
import gc
from openai import OpenAI
import re
import time
# Load system prompts
system_prompt_t2v = """당신은 λΉ„λ””μ˜€ 생성을 μœ„ν•œ ν”„λ‘¬ν”„νŠΈ μ „λ¬Έκ°€μž…λ‹ˆλ‹€. 
주어진 ν”„λ‘¬ν”„νŠΈλ₯Ό λ‹€μŒ ꡬ쑰에 맞게 κ°œμ„ ν•΄μ£Όμ„Έμš”:
1. μ£Όμš” λ™μž‘μ„ λͺ…ν™•ν•œ ν•œ λ¬Έμž₯으둜 μ‹œμž‘
2. ꡬ체적인 λ™μž‘κ³Ό 제슀처λ₯Ό μ‹œκ°„ μˆœμ„œλŒ€λ‘œ μ„€λͺ…
3. 캐릭터/객체의 μ™Έλͺ¨λ₯Ό μƒμ„Ένžˆ λ¬˜μ‚¬
4. λ°°κ²½κ³Ό ν™˜κ²½ μ„ΈλΆ€ 사항을 ꡬ체적으둜 포함
5. 카메라 각도와 μ›€μ§μž„μ„ λͺ…μ‹œ
6. μ‘°λͺ…κ³Ό 색상을 μžμ„Ένžˆ μ„€λͺ…
7. λ³€ν™”λ‚˜ κ°‘μž‘μŠ€λŸ¬μš΄ 사건을 μžμ—°μŠ€λŸ½κ²Œ 포함
λͺ¨λ“  μ„€λͺ…은 ν•˜λ‚˜μ˜ μžμ—°μŠ€λŸ¬μš΄ λ¬Έλ‹¨μœΌλ‘œ μž‘μ„±ν•˜κ³ , 
촬영 감독이 촬영 λͺ©λ‘μ„ μ„€λͺ…ν•˜λŠ” κ²ƒμ²˜λŸΌ ꡬ체적이고 μ‹œκ°μ μœΌλ‘œ μž‘μ„±ν•˜μ„Έμš”.
200단어λ₯Ό λ„˜μ§€ μ•Šλ„λ‘ ν•˜λ˜, μ΅œλŒ€ν•œ μƒμ„Έν•˜κ²Œ μž‘μ„±ν•˜μ„Έμš”."""

system_prompt_i2v = """당신은 이미지 기반 λΉ„λ””μ˜€ 생성을 μœ„ν•œ ν”„λ‘¬ν”„νŠΈ μ „λ¬Έκ°€μž…λ‹ˆλ‹€. 
주어진 ν”„λ‘¬ν”„νŠΈλ₯Ό λ‹€μŒ ꡬ쑰에 맞게 κ°œμ„ ν•΄μ£Όμ„Έμš”:
1. μ£Όμš” λ™μž‘μ„ λͺ…ν™•ν•œ ν•œ λ¬Έμž₯으둜 μ‹œμž‘
2. ꡬ체적인 λ™μž‘κ³Ό 제슀처λ₯Ό μ‹œκ°„ μˆœμ„œλŒ€λ‘œ μ„€λͺ…
3. 캐릭터/객체의 μ™Έλͺ¨λ₯Ό μƒμ„Ένžˆ λ¬˜μ‚¬
4. λ°°κ²½κ³Ό ν™˜κ²½ μ„ΈλΆ€ 사항을 ꡬ체적으둜 포함
5. 카메라 각도와 μ›€μ§μž„μ„ λͺ…μ‹œ
6. μ‘°λͺ…κ³Ό 색상을 μžμ„Ένžˆ μ„€λͺ…
7. λ³€ν™”λ‚˜ κ°‘μž‘μŠ€λŸ¬μš΄ 사건을 μžμ—°μŠ€λŸ½κ²Œ 포함
λͺ¨λ“  μ„€λͺ…은 ν•˜λ‚˜μ˜ μžμ—°μŠ€λŸ¬μš΄ λ¬Έλ‹¨μœΌλ‘œ μž‘μ„±ν•˜κ³ , 
촬영 감독이 촬영 λͺ©λ‘μ„ μ„€λͺ…ν•˜λŠ” κ²ƒμ²˜λŸΌ ꡬ체적이고 μ‹œκ°μ μœΌλ‘œ μž‘μ„±ν•˜μ„Έμš”.
200단어λ₯Ό λ„˜μ§€ μ•Šλ„λ‘ ν•˜λ˜, μ΅œλŒ€ν•œ μƒμ„Έν•˜κ²Œ μž‘μ„±ν•˜μ„Έμš”."""

# Load Hugging Face token if needed
hf_token = os.getenv("HF_TOKEN")
openai_api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=openai_api_key)

# Initialize translation pipeline with device and clean_up settings
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
translator = pipeline(
    "translation", 
    model="Helsinki-NLP/opus-mt-ko-en",
    device=device,
    clean_up_tokenization_spaces=True
)

# Korean text detection function
def contains_korean(text):
    korean_pattern = re.compile('[γ„±-γ…Žγ…-γ…£κ°€-힣]')
    return bool(korean_pattern.search(text))

def translate_korean_prompt(prompt, max_length=450):
    """
    Translate Korean prompt to English if Korean text is detected
    Split long text into chunks if necessary
    """
    if not contains_korean(prompt):
        return prompt
        
    # Split long text into chunks
    def split_text(text, max_length):
        words = text.split()
        chunks = []
        current_chunk = []
        current_length = 0
        
        for word in words:
            if current_length + len(word) + 1 > max_length:
                chunks.append(' '.join(current_chunk))
                current_chunk = [word]
                current_length = len(word)
            else:
                current_chunk.append(word)
                current_length += len(word) + 1
                
        if current_chunk:
            chunks.append(' '.join(current_chunk))
        return chunks

    try:
        if len(prompt) > max_length:
            chunks = split_text(prompt, max_length)
            translated_chunks = []
            
            for chunk in chunks:
                translated = translator(chunk, max_length=512)[0]['translation_text']
                translated_chunks.append(translated)
                
            final_translation = ' '.join(translated_chunks)
        else:
            final_translation = translator(prompt, max_length=512)[0]['translation_text']
            
        print(f"Original Korean prompt: {prompt}")
        print(f"Translated English prompt: {final_translation}")
        return final_translation
        
    except Exception as e:
        print(f"Translation error: {e}")
        return prompt  # Return original prompt if translation fails

def enhance_prompt(prompt, type="t2v"):
    system_prompt = system_prompt_t2v if type == "t2v" else system_prompt_i2v
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": prompt},
    ]

    try:
        response = client.chat.completions.create(
            model="gpt-4-1106-preview",
            messages=messages,
            max_tokens=2000,
        )
        enhanced_prompt = response.choices[0].message.content.strip()
        
        print("\n=== ν”„λ‘¬ν”„νŠΈ 증강 κ²°κ³Ό ===")
        print("Original Prompt:")
        print(prompt)
        print("\nEnhanced Prompt:")
        print(enhanced_prompt)
        print("========================\n")
        
        return enhanced_prompt
    except Exception as e:
        print(f"Error during prompt enhancement: {e}")
        return prompt

def update_prompt_t2v(prompt, enhance_toggle):
    return update_prompt(prompt, enhance_toggle, "t2v")

def update_prompt_i2v(prompt, enhance_toggle):
    return update_prompt(prompt, enhance_toggle, "i2v")
    
def update_prompt(prompt, enhance_toggle, type="t2v"):
    if enhance_toggle:
        return enhance_prompt(prompt, type)
    return prompt

# Set model download directory within Hugging Face Spaces
model_path = "asset"
if not os.path.exists(model_path):
    snapshot_download(
        "Lightricks/LTX-Video", local_dir=model_path, repo_type="model", token=hf_token
    )

# Global variables to load components
vae_dir = Path(model_path) / "vae"
unet_dir = Path(model_path) / "unet"
scheduler_dir = Path(model_path) / "scheduler"

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def load_vae(vae_dir):
    vae_ckpt_path = vae_dir / "vae_diffusion_pytorch_model.safetensors"
    vae_config_path = vae_dir / "config.json"
    with open(vae_config_path, "r") as f:
        vae_config = json.load(f)
    vae = CausalVideoAutoencoder.from_config(vae_config)
    vae_state_dict = safetensors.torch.load_file(vae_ckpt_path)
    vae.load_state_dict(vae_state_dict)
    return vae.to(device=device, dtype=torch.bfloat16)

def load_unet(unet_dir):
    unet_ckpt_path = unet_dir / "unet_diffusion_pytorch_model.safetensors"
    unet_config_path = unet_dir / "config.json"
    transformer_config = Transformer3DModel.load_config(unet_config_path)
    transformer = Transformer3DModel.from_config(transformer_config)
    unet_state_dict = safetensors.torch.load_file(unet_ckpt_path)
    transformer.load_state_dict(unet_state_dict, strict=True)
    return transformer.to(device=device, dtype=torch.bfloat16)

def load_scheduler(scheduler_dir):
    scheduler_config_path = scheduler_dir / "scheduler_config.json"
    scheduler_config = RectifiedFlowScheduler.load_config(scheduler_config_path)
    return RectifiedFlowScheduler.from_config(scheduler_config)

# Helper function for image processing
def center_crop_and_resize(frame, target_height, target_width):
    h, w, _ = frame.shape
    aspect_ratio_target = target_width / target_height
    aspect_ratio_frame = w / h
    if aspect_ratio_frame > aspect_ratio_target:
        new_width = int(h * aspect_ratio_target)
        x_start = (w - new_width) // 2
        frame_cropped = frame[:, x_start : x_start + new_width]
    else:
        new_height = int(w / aspect_ratio_target)
        y_start = (h - new_height) // 2
        frame_cropped = frame[y_start : y_start + new_height, :]
    frame_resized = cv2.resize(frame_cropped, (target_width, target_height))
    return frame_resized

def load_image_to_tensor_with_resize(image_path, target_height=512, target_width=768):
    image = Image.open(image_path).convert("RGB")
    image_np = np.array(image)
    frame_resized = center_crop_and_resize(image_np, target_height, target_width)
    frame_tensor = torch.tensor(frame_resized).permute(2, 0, 1).float()
    frame_tensor = (frame_tensor / 127.5) - 1.0
    return frame_tensor.unsqueeze(0).unsqueeze(2)

# Load models
vae = load_vae(vae_dir)
unet = load_unet(unet_dir)
scheduler = load_scheduler(scheduler_dir)
patchifier = SymmetricPatchifier(patch_size=1)
text_encoder = T5EncoderModel.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS", subfolder="text_encoder"
).to(device)
tokenizer = T5Tokenizer.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS", subfolder="tokenizer"
)

pipeline = XoraVideoPipeline(
    transformer=unet,
    patchifier=patchifier,
    text_encoder=text_encoder,
    tokenizer=tokenizer,
    scheduler=scheduler,
    vae=vae,
).to(device)



# Preset options for resolution and frame configuration
# Convert frames to seconds assuming 25 FPS
preset_options = [
    {"label": "[16:9 HD] 1216x704, 1.6초", "width": 1216, "height": 704, "num_frames": 41},
    {"label": "[16:9] 1088x704, 2.0초", "width": 1088, "height": 704, "num_frames": 49},
    {"label": "[16:9] 1056x640, 2.3초", "width": 1056, "height": 640, "num_frames": 57},
    {"label": "[16:9] 992x608, 2.6초", "width": 992, "height": 608, "num_frames": 65},
    {"label": "[16:9] 896x608, 2.9초", "width": 896, "height": 608, "num_frames": 73},
    {"label": "[16:9] 896x544, 3.2초", "width": 896, "height": 544, "num_frames": 81},
    {"label": "[16:9] 832x544, 3.6초", "width": 832, "height": 544, "num_frames": 89},
    {"label": "[16:9] 800x512, 3.9초", "width": 800, "height": 512, "num_frames": 97},
    {"label": "[16:9] 768x512, 3.9초", "width": 768, "height": 512, "num_frames": 97},
    {"label": "[16:9] 800x480, 4.2초", "width": 800, "height": 480, "num_frames": 105},
    {"label": "[16:9] 736x480, 4.5초", "width": 736, "height": 480, "num_frames": 113},
    {"label": "[3:2] 704x480, 4.8초", "width": 704, "height": 480, "num_frames": 121},
    {"label": "[16:9] 704x448, 5.2초", "width": 704, "height": 448, "num_frames": 129},
    {"label": "[16:9] 672x448, 5.5초", "width": 672, "height": 448, "num_frames": 137},
    {"label": "[16:9] 640x416, 6.1초", "width": 640, "height": 416, "num_frames": 153},
    {"label": "[16:9] 672x384, 6.4초", "width": 672, "height": 384, "num_frames": 161},
    {"label": "[16:9] 640x384, 6.8초", "width": 640, "height": 384, "num_frames": 169},
    {"label": "[16:9] 608x384, 7.1초", "width": 608, "height": 384, "num_frames": 177},
    {"label": "[16:9] 576x384, 7.4초", "width": 576, "height": 384, "num_frames": 185},
    {"label": "[16:9] 608x352, 7.7초", "width": 608, "height": 352, "num_frames": 193},
    {"label": "[16:9] 576x352, 8.0초", "width": 576, "height": 352, "num_frames": 201},
    {"label": "[16:9] 544x352, 8.4초", "width": 544, "height": 352, "num_frames": 209},
    {"label": "[3:2] 512x352, 9.3초", "width": 512, "height": 352, "num_frames": 233},
    {"label": "[16:9] 544x320, 9.6초", "width": 544, "height": 320, "num_frames": 241},
    {"label": "[16:9] 512x320, 10.3초", "width": 512, "height": 320, "num_frames": 257},
]

def preset_changed(preset):
    selected = next((item for item in preset_options if item["label"] == preset), None)
    if selected is None:
        raise gr.Error("Invalid preset selected")
    return [
        gr.State(value=selected["height"]),
        gr.State(value=selected["width"]),
        gr.State(value=selected["num_frames"]),
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(visible=False),
    ]
    
def generate_video_from_text(
    prompt,
    enhance_prompt_toggle,
    negative_prompt,
    frame_rate,
    seed,
    num_inference_steps,
    guidance_scale,
    height,
    width,
    num_frames,
    progress=gr.Progress(),
):
    if len(prompt.strip()) < 50:
        raise gr.Error(
            "ν”„λ‘¬ν”„νŠΈλŠ” μ΅œμ†Œ 50자 이상이어야 ν•©λ‹ˆλ‹€. 더 μžμ„Έν•œ μ„€λͺ…을 μ œκ³΅ν•΄μ£Όμ„Έμš”.",
            duration=5,
        )

    # ν”„λ‘¬ν”„νŠΈ κ°œμ„ μ΄ ν™œμ„±ν™”λœ 경우
    if enhance_prompt_toggle:
        prompt = enhance_prompt(prompt, "t2v")

    # Translate Korean prompts to English
    prompt = translate_korean_prompt(prompt)
    negative_prompt = translate_korean_prompt(negative_prompt)

    # κΈ°λ³Έκ°’ μ„€μ •
    height = height or 320
    width = width or 512
    num_frames = num_frames or 257
    frame_rate = frame_rate or 25
    seed = seed or 171198
    num_inference_steps = num_inference_steps or 41
    guidance_scale = guidance_scale or 4.0

    sample = {
        "prompt": prompt,
        "prompt_attention_mask": None,
        "negative_prompt": negative_prompt,
        "negative_prompt_attention_mask": None,
        "media_items": None,
    }

    generator = torch.Generator(device="cpu").manual_seed(seed)

    def gradio_progress_callback(self, step, timestep, kwargs):
        progress((step + 1) / num_inference_steps)

    try:
        with torch.no_grad():
            images = pipeline(
                num_inference_steps=num_inference_steps,
                num_images_per_prompt=1,
                guidance_scale=guidance_scale,
                generator=generator,
                output_type="pt",
                height=height,
                width=width,
                num_frames=num_frames,
                frame_rate=frame_rate,
                **sample,
                is_video=True,
                vae_per_channel_normalize=True,
                conditioning_method=ConditioningMethod.UNCONDITIONAL,
                mixed_precision=True,
                callback_on_step_end=gradio_progress_callback,
            ).images
    except Exception as e:
        raise gr.Error(
            f"λΉ„λ””μ˜€ 생성 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”. 였λ₯˜: {e}",
            duration=5,
        )
    finally:
        torch.cuda.empty_cache()
        gc.collect()

    output_path = tempfile.mktemp(suffix=".mp4")
    video_np = images.squeeze(0).permute(1, 2, 3, 0).cpu().float().numpy()
    video_np = (video_np * 255).astype(np.uint8)
    height, width = video_np.shape[1:3]
    out = cv2.VideoWriter(
        output_path, cv2.VideoWriter_fourcc(*"mp4v"), frame_rate, (width, height)
    )
    for frame in video_np[..., ::-1]:
        out.write(frame)
    out.release()
    del images
    del video_np
    torch.cuda.empty_cache()
    return output_path

def generate_video_from_image(
    image_path,
    prompt,
    enhance_prompt_toggle,
    negative_prompt,
    frame_rate,
    seed,
    num_inference_steps,
    guidance_scale,
    height,
    width,
    num_frames,
    progress=gr.Progress(),
):
    if not image_path:
        raise gr.Error("μž…λ ₯ 이미지λ₯Ό μ œκ³΅ν•΄μ£Όμ„Έμš”.", duration=5)

    if len(prompt.strip()) < 50:
        raise gr.Error(
            "ν”„λ‘¬ν”„νŠΈλŠ” μ΅œμ†Œ 50자 이상이어야 ν•©λ‹ˆλ‹€. 더 μžμ„Έν•œ μ„€λͺ…을 μ œκ³΅ν•΄μ£Όμ„Έμš”.",
            duration=5,
        )

    # ν”„λ‘¬ν”„νŠΈ κ°œμ„ μ΄ ν™œμ„±ν™”λœ 경우
    if enhance_prompt_toggle:
        prompt = enhance_prompt(prompt, "i2v")

    # Translate Korean prompts to English
    prompt = translate_korean_prompt(prompt)
    negative_prompt = translate_korean_prompt(negative_prompt)

    # κΈ°λ³Έκ°’ μ„€μ •
    height = height or 320
    width = width or 512
    num_frames = num_frames or 257
    frame_rate = frame_rate or 25
    seed = seed or 171198
    num_inference_steps = num_inference_steps or 41
    guidance_scale = guidance_scale or 4.0

    # 이미지 λ‘œλ“œ 및 μ „μ²˜λ¦¬
    media_items = (
        load_image_to_tensor_with_resize(image_path, height, width).to(device).detach()
    )

    sample = {
        "prompt": prompt,
        "prompt_attention_mask": None,
        "negative_prompt": negative_prompt,
        "negative_prompt_attention_mask": None,
        "media_items": media_items,
    }

    generator = torch.Generator(device="cpu").manual_seed(seed)

    def gradio_progress_callback(self, step, timestep, kwargs):
        progress((step + 1) / num_inference_steps)

    try:
        with torch.no_grad():
            images = pipeline(
                num_inference_steps=num_inference_steps,
                num_images_per_prompt=1,
                guidance_scale=guidance_scale,
                generator=generator,
                output_type="pt",
                height=height,
                width=width,
                num_frames=num_frames,
                frame_rate=frame_rate,
                **sample,
                is_video=True,
                vae_per_channel_normalize=True,
                conditioning_method=ConditioningMethod.FIRST_FRAME,
                mixed_precision=True,
                callback_on_step_end=gradio_progress_callback,
            ).images

        output_path = tempfile.mktemp(suffix=".mp4")
        video_np = images.squeeze(0).permute(1, 2, 3, 0).cpu().float().numpy()
        video_np = (video_np * 255).astype(np.uint8)
        height, width = video_np.shape[1:3]
        out = cv2.VideoWriter(
            output_path, cv2.VideoWriter_fourcc(*"mp4v"), frame_rate, (width, height)
        )
        for frame in video_np[..., ::-1]:
            out.write(frame)
        out.release()

    except Exception as e:
        raise gr.Error(
            f"λΉ„λ””μ˜€ 생성 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”. 였λ₯˜: {e}",
            duration=5,
        )

    finally:
        torch.cuda.empty_cache()
        gc.collect()
        if 'images' in locals():
            del images
        if 'video_np' in locals():
            del video_np
        if 'media_items' in locals():
            del media_items

    return output_path

def create_advanced_options():
    with gr.Accordion("Step 4: Advanced Options (Optional)", open=False):
        seed = gr.Slider(
            label="Seed",
            minimum=0,
            maximum=1000000,
            step=1,
            value=171198
        )
        inference_steps = gr.Slider(
            label="4.2 Inference Steps",
            minimum=1,
            maximum=50,
            step=1,
            value=41,
            visible=False
        )
        guidance_scale = gr.Slider(
            label="4.3 Guidance Scale",
            minimum=1.0,
            maximum=5.0,
            step=0.1,
            value=4.0,
            visible=False
        )
        height_slider = gr.Slider(
            label="4.4 Height",
            minimum=256,
            maximum=1024,
            step=64,
            value=320,
            visible=False,
        )
        width_slider = gr.Slider(
            label="4.5 Width",
            minimum=256,
            maximum=1024,
            step=64,
            value=512,
            visible=False,
        )
        num_frames_slider = gr.Slider(
            label="4.5 Number of Frames",
            minimum=1,
            maximum=200,
            step=1,
            value=257,
            visible=False,
        )

        return [
            seed,
            inference_steps,
            guidance_scale,
            height_slider,
            width_slider,
            num_frames_slider,
        ]

system_prompt_scenario = """당신은 μ˜μƒ μŠ€ν¬λ¦½νŠΈμ— λ§žλŠ” λ°°κ²½ μ˜μƒμ„ μƒμ„±ν•˜κΈ° μœ„ν•œ ν”„λ‘¬ν”„νŠΈ μ „λ¬Έκ°€μž…λ‹ˆλ‹€.
주어진 슀크립트의 λΆ„μœ„κΈ°μ™€ λ§₯락을 μ‹œκ°μ  배경으둜 ν‘œν˜„ν•˜λ˜, λ‹€μŒ 원칙을 λ°˜λ“œμ‹œ μ€€μˆ˜ν•˜μ„Έμš”:

1. μ œν’ˆμ΄λ‚˜ μ„œλΉ„μŠ€λ₯Ό μ§μ ‘μ μœΌλ‘œ λ¬˜μ‚¬ν•˜μ§€ 말 것
2. 슀크립트의 감성과 ν†€μ•€λ§€λ„ˆλ₯Ό ν‘œν˜„ν•˜λŠ” λ°°κ²½ μ˜μƒμ— 집쀑할 것
3. 5개 μ„Ήμ…˜μ΄ ν•˜λ‚˜μ˜ μ΄μ•ΌκΈ°μ²˜λŸΌ μžμ—°μŠ€λŸ½κ²Œ μ—°κ²°λ˜λ„λ‘ ν•  것
4. 좔상적이고 μ€μœ μ μΈ μ‹œκ° ν‘œν˜„μ„ ν™œμš©ν•  것

각 μ„Ήμ…˜λ³„ ν”„λ‘¬ν”„νŠΈ μž‘μ„± κ°€μ΄λ“œ:
1. λ°°κ²½ 및 ν•„μš”μ„±: 주제의 μ „λ°˜μ μΈ λΆ„μœ„κΈ°λ₯Ό ν‘œν˜„ν•˜λŠ” λ°°κ²½ 씬
2. 문제 제기: κΈ΄μž₯κ°μ΄λ‚˜ κ°ˆλ“±μ„ μ•”μ‹œν•˜λŠ” λΆ„μœ„κΈ° μžˆλŠ” λ°°κ²½
3. ν•΄κ²°μ±… μ œμ‹œ: 희망적이고 밝은 ν†€μ˜ λ°°κ²½ μ „ν™˜
4. λ³Έλ‘ : μ•ˆμ •κ° 있고 신뒰도λ₯Ό λ†’μ΄λŠ” λ°°κ²½
5. κ²°λ‘ : μž„νŒ©νŠΈ μžˆλŠ” 마무리λ₯Ό μœ„ν•œ 역동적인 λ°°κ²½

λͺ¨λ“  μ„Ήμ…˜μ΄ μΌκ΄€λœ μŠ€νƒ€μΌκ³Ό 톀을 μœ μ§€ν•˜λ©΄μ„œλ„ μžμ—°μŠ€λŸ½κ²Œ 이어지도둝 κ΅¬μ„±ν•˜μ„Έμš”.

각 μ„Ήμ…˜μ˜ ν”„λ‘¬ν”„νŠΈ μž‘μ„±μ‹œ λ°˜λ“œμ‹œ λ‹€μŒ ꡬ쑰에 맞게 κ°œμ„ ν•΄μ£Όμ„Έμš”:
1. μ£Όμš” λ™μž‘μ„ λͺ…ν™•ν•œ ν•œ λ¬Έμž₯으둜 μ‹œμž‘
2. ꡬ체적인 λ™μž‘κ³Ό 제슀처λ₯Ό μ‹œκ°„ μˆœμ„œλŒ€λ‘œ μ„€λͺ…
3. 캐릭터/객체의 μ™Έλͺ¨λ₯Ό μƒμ„Ένžˆ λ¬˜μ‚¬
4. λ°°κ²½κ³Ό ν™˜κ²½ μ„ΈλΆ€ 사항을 ꡬ체적으둜 포함
5. 카메라 각도와 μ›€μ§μž„μ„ λͺ…μ‹œ
6. μ‘°λͺ…κ³Ό 색상을 μžμ„Ένžˆ μ„€λͺ…
7. λ³€ν™”λ‚˜ κ°‘μž‘μŠ€λŸ¬μš΄ 사건을 μžμ—°μŠ€λŸ½κ²Œ 포함
λͺ¨λ“  μ„€λͺ…은 ν•˜λ‚˜μ˜ μžμ—°μŠ€λŸ¬μš΄ λ¬Έλ‹¨μœΌλ‘œ μž‘μ„±ν•˜κ³ , 
촬영 감독이 촬영 λͺ©λ‘μ„ μ„€λͺ…ν•˜λŠ” κ²ƒμ²˜λŸΌ ꡬ체적이고 μ‹œκ°μ μœΌλ‘œ μž‘μ„±ν•˜μ„Έμš”.
200단어λ₯Ό λ„˜μ§€ μ•Šλ„λ‘ ν•˜λ˜, μ΅œλŒ€ν•œ μƒμ„Έν•˜κ²Œ μž‘μ„±ν•˜μ„Έμš”.

"""


def analyze_scenario(scenario):
    """μ‹œλ‚˜λ¦¬μ˜€λ₯Ό λΆ„μ„ν•˜μ—¬ 각 μ„Ήμ…˜λ³„ λ°°κ²½ μ˜μƒμš© ν”„λ‘¬ν”„νŠΈ 생성"""
    try:
        # 각 μ„Ήμ…˜λ³„ ν”„λ‘¬ν”„νŠΈ 생성을 μœ„ν•œ λ©”μ‹œμ§€ ꡬ성
        section_prompts = []
        
        for section_num in range(1, 6):
            section_descriptions = {
                1: "λ°°κ²½ 및 ν•„μš”μ„±: 주제의 μ „λ°˜μ μΈ λΆ„μœ„κΈ°λ₯Ό ν‘œν˜„ν•˜λŠ” λ°°κ²½ 씬",
                2: "ν₯λ―Έ 유발: κΈ΄μž₯κ°μ΄λ‚˜ κ°ˆλ“±μ„ μ•”μ‹œν•˜λŠ” λΆ„μœ„κΈ° μžˆλŠ” λ°°κ²½",
                3: "ν•΄κ²°μ±… μ œμ‹œ: 희망적이고 밝은 ν†€μ˜ λ°°κ²½ μ „ν™˜",
                4: "λ³Έλ‘ : μ•ˆμ •κ° 있고 신뒰도λ₯Ό λ†’μ΄λŠ” λ°°κ²½",
                5: "κ²°λ‘ : μž„νŒ©νŠΈ μžˆλŠ” 마무리λ₯Ό μœ„ν•œ 역동적인 λ°°κ²½"
            }
            
            messages = [
                {"role": "system", "content": system_prompt_scenario},
                {"role": "user", "content": f"""
λ‹€μŒ 슀크립트의 {section_num}번째 μ„Ήμ…˜({section_descriptions[section_num]})에 λŒ€ν•œ 
λ°°κ²½ μ˜μƒ ν”„λ‘¬ν”„νŠΈλ₯Ό μƒμ„±ν•΄μ£Όμ„Έμš”.

슀크립트:
{scenario}

μ£Όμ˜μ‚¬ν•­:
1. ν•΄λ‹Ή μ„Ήμ…˜μ˜ νŠΉμ„±({section_descriptions[section_num]})에 λ§žλŠ” λΆ„μœ„κΈ°μ™€ 톀을 λ°˜μ˜ν•˜μ„Έμš”.
2. 직접적인 μ œν’ˆ/μ„œλΉ„μŠ€ λ¬˜μ‚¬λŠ” ν”Όν•˜κ³ , 감성적이고 μ€μœ μ μΈ λ°°κ²½ μ˜μƒμ— μ§‘μ€‘ν•˜μ„Έμš”.
3. λ‹€μŒ ꡬ쑰λ₯Ό λ°˜λ“œμ‹œ ν¬ν•¨ν•˜μ„Έμš”:
   - μ£Όμš” λ™μž‘μ„ λͺ…ν™•ν•œ ν•œ λ¬Έμž₯으둜 μ‹œμž‘
   - ꡬ체적인 λ™μž‘κ³Ό 제슀처λ₯Ό μ‹œκ°„ μˆœμ„œλŒ€λ‘œ μ„€λͺ…
   - λ°°κ²½κ³Ό ν™˜κ²½ μ„ΈλΆ€ 사항을 ꡬ체적으둜 포함
   - 카메라 각도와 μ›€μ§μž„μ„ λͺ…μ‹œ
   - μ‘°λͺ…κ³Ό 색상을 μžμ„Ένžˆ μ„€λͺ…
   - λ³€ν™”λ‚˜ κ°‘μž‘μŠ€λŸ¬μš΄ 사건을 μžμ—°μŠ€λŸ½κ²Œ 포함"""}
            ]

            response = client.chat.completions.create(
                model="gpt-4-1106-preview",
                messages=messages,
                max_tokens=1000,
                temperature=0.7
            )
            
            section_prompt = response.choices[0].message.content.strip()
            section_prompts.append(f"{section_num}. {section_prompt}")
            
            # API μš”μ²­ 사이에 짧은 λ”œλ ˆμ΄ μΆ”κ°€
            time.sleep(1)
        
        return section_prompts
        
    except Exception as e:
        print(f"Error during scenario analysis: {e}")
        return ["Error occurred during analysis"] * 5

def generate_section_video(prompt, preset, section_number=1, base_seed=171198, progress=gr.Progress()):
    """각 μ„Ήμ…˜μ˜ λΉ„λ””μ˜€ 생성"""
    try:
        if not prompt or len(prompt.strip()) < 50:
            raise gr.Error("ν”„λ‘¬ν”„νŠΈλŠ” μ΅œμ†Œ 50자 이상이어야 ν•©λ‹ˆλ‹€.")
            
        if not preset:
            raise gr.Error("해상도 프리셋을 μ„ νƒν•΄μ£Όμ„Έμš”.")
            
        selected = next((item for item in preset_options if item["label"] == preset), None)
        if not selected:
            raise gr.Error("μ˜¬λ°”λ₯΄μ§€ μ•Šμ€ ν”„λ¦¬μ…‹μž…λ‹ˆλ‹€.")
            
        section_seed = base_seed + section_number
        
        return generate_video_from_text(
            prompt=prompt,
            enhance_prompt_toggle=False,  # μ„Ήμ…˜ μƒμ„±μ‹œλŠ” ν”„λ‘¬ν”„νŠΈ 증강 λΉ„ν™œμ„±ν™”
            negative_prompt="low quality, worst quality, deformed, distorted, warped",
            frame_rate=25,
            seed=section_seed,
            num_inference_steps=41,
            guidance_scale=4.0,
            height=selected["height"],
            width=selected["width"],
            num_frames=selected["num_frames"],
            progress=progress
        )
    except Exception as e:
        print(f"Error in section {section_number}: {e}")
        raise gr.Error(f"μ„Ήμ…˜ {section_number} 생성 쀑 였λ₯˜: {str(e)}")
    finally:
        torch.cuda.empty_cache()
        gc.collect()

def generate_single_section_prompt(scenario, section_number):
    """κ°œλ³„ μ„Ήμ…˜μ— λŒ€ν•œ ν”„λ‘¬ν”„νŠΈ 생성"""
    section_descriptions = {
        1: "λ°°κ²½ 및 ν•„μš”μ„±: 주제의 μ „λ°˜μ μΈ λΆ„μœ„κΈ°λ₯Ό ν‘œν˜„ν•˜λŠ” λ°°κ²½ 씬",
        2: "ν₯λ―Έ 유발: ν₯λ―Έλ₯Ό μœ λ°œν•˜κ³  κΈ°λŒ€κ°μ„ μ¦ν­μ‹œν‚€λŠ” λ°°κ²½",
        3: "ν•΄κ²°μ±… μ œμ‹œ: 희망적이고 밝은 ν†€μ˜ λ°°κ²½ μ „ν™˜",
        4: "λ³Έλ‘ : μ•ˆμ •κ° 있고 신뒰도λ₯Ό λ†’μ΄λŠ” λ°°κ²½",
        5: "κ²°λ‘ : μž„νŒ©νŠΈ μžˆλŠ” 마무리λ₯Ό μœ„ν•œ 역동적인 λ°°κ²½"
    }
    
    messages = [
        {"role": "system", "content": system_prompt_scenario},
        {"role": "user", "content": f"""
λ‹€μŒ 슀크립트의 {section_number}번째 μ„Ήμ…˜({section_descriptions[section_number]})에 λŒ€ν•œ 
λ°°κ²½ μ˜μƒ ν”„λ‘¬ν”„νŠΈλ₯Ό μƒμ„±ν•΄μ£Όμ„Έμš”.

슀크립트:
{scenario}

μ£Όμ˜μ‚¬ν•­:
1. ν•΄λ‹Ή μ„Ήμ…˜μ˜ νŠΉμ„±({section_descriptions[section_number]})에 λ§žλŠ” λΆ„μœ„κΈ°μ™€ 톀을 λ°˜μ˜ν•˜μ„Έμš”.
2. 직접적인 μ œν’ˆ/μ„œλΉ„μŠ€ λ¬˜μ‚¬λŠ” ν”Όν•˜κ³ , 감성적이고 μ€μœ μ μΈ λ°°κ²½ μ˜μƒμ— μ§‘μ€‘ν•˜μ„Έμš”.
3. λ‹€μŒ ꡬ쑰λ₯Ό λ°˜λ“œμ‹œ ν¬ν•¨ν•˜μ„Έμš”:
   - μ£Όμš” λ™μž‘μ„ λͺ…ν™•ν•œ ν•œ λ¬Έμž₯으둜 μ‹œμž‘
   - ꡬ체적인 λ™μž‘κ³Ό 제슀처λ₯Ό μ‹œκ°„ μˆœμ„œλŒ€λ‘œ μ„€λͺ…
   - λ°°κ²½κ³Ό ν™˜κ²½ μ„ΈλΆ€ 사항을 ꡬ체적으둜 포함
   - 카메라 각도와 μ›€μ§μž„μ„ λͺ…μ‹œ
   - μ‘°λͺ…κ³Ό 색상을 μžμ„Ένžˆ μ„€λͺ…
   - λ³€ν™”λ‚˜ κ°‘μž‘μŠ€λŸ¬μš΄ 사건을 μžμ—°μŠ€λŸ½κ²Œ 포함"""}
    ]
    
    try:
        response = client.chat.completions.create(
            model="gpt-4-1106-preview",
            messages=messages,
            max_tokens=1000,  # 토큰 수 증가
            temperature=0.7
        )
        generated_prompt = response.choices[0].message.content.strip()
        return f"{section_number}. {generated_prompt}"
    except Exception as e:
        print(f"Error during prompt generation for section {section_number}: {e}")
        return f"Error occurred during prompt generation for section {section_number}"


# λΉ„λ””μ˜€ κ²°ν•© ν•¨μˆ˜ μΆ”κ°€
def combine_videos(video_paths, output_path):
    """μ—¬λŸ¬ λΉ„λ””μ˜€λ₯Ό ν•˜λ‚˜λ‘œ κ²°ν•©"""
    if not all(video_paths):
        raise gr.Error("λͺ¨λ“  μ„Ήμ…˜μ˜ μ˜μƒμ΄ μƒμ„±λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.")
        
    try:
        # 첫 번째 λΉ„λ””μ˜€μ˜ 속성 κ°€μ Έμ˜€κΈ°
        cap = cv2.VideoCapture(video_paths[0])
        fps = int(cap.get(cv2.CAP_PROP_FPS))
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        cap.release()

        # 좜λ ₯ λΉ„λ””μ˜€ μ„€μ •
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

        # 각 λΉ„λ””μ˜€ 순차적으둜 κ²°ν•©
        for video_path in video_paths:
            if video_path and os.path.exists(video_path):
                cap = cv2.VideoCapture(video_path)
                while True:
                    ret, frame = cap.read()
                    if not ret:
                        break
                    out.write(frame)
                cap.release()

        out.release()
        return output_path
    except Exception as e:
        raise gr.Error(f"λΉ„λ””μ˜€ κ²°ν•© 쀑 였λ₯˜ λ°œμƒ: {e}")

def merge_section_videos(section1, section2, section3, section4, section5):
    """μ„Ήμ…˜ λΉ„λ””μ˜€λ“€μ„ ν•˜λ‚˜λ‘œ κ²°ν•©"""
    videos = []
    
    # 각 μ„Ήμ…˜ λΉ„λ””μ˜€ 확인 및 처리
    for i, video_path in enumerate([section1, section2, section3, section4, section5], 1):
        if video_path:
            if os.path.exists(video_path):
                try:
                    # λΉ„λ””μ˜€ 파일 검증
                    cap = cv2.VideoCapture(video_path)
                    if cap.isOpened():
                        videos.append(video_path)
                        cap.release()
                    else:
                        raise gr.Error(f"μ„Ήμ…˜ {i}의 μ˜μƒ 파일이 μ†μƒλ˜μ—ˆκ±°λ‚˜ 읽을 수 μ—†μŠ΅λ‹ˆλ‹€.")
                except Exception as e:
                    raise gr.Error(f"μ„Ήμ…˜ {i} μ˜μƒ 처리 쀑 였λ₯˜: {str(e)}")
            else:
                raise gr.Error(f"μ„Ήμ…˜ {i}의 μ˜μƒ νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
        else:
            raise gr.Error(f"μ„Ήμ…˜ {i}의 μ˜μƒμ΄ μ—†μŠ΅λ‹ˆλ‹€.")
    
    if not videos:
        raise gr.Error("κ²°ν•©ν•  μ˜μƒμ΄ μ—†μŠ΅λ‹ˆλ‹€.")
    
    try:
        output_path = tempfile.mktemp(suffix=".mp4")
        
        # 첫 번째 λΉ„λ””μ˜€μ˜ 속성 κ°€μ Έμ˜€κΈ°
        cap = cv2.VideoCapture(videos[0])
        fps = int(cap.get(cv2.CAP_PROP_FPS))
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        cap.release()

        # 좜λ ₯ λΉ„λ””μ˜€ μ„€μ •
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

        # 각 λΉ„λ””μ˜€ 순차적으둜 κ²°ν•©
        for video_path in videos:
            cap = cv2.VideoCapture(video_path)
            while True:
                ret, frame = cap.read()
                if not ret:
                    break
                # ν”„λ ˆμž„ 크기가 λ‹€λ₯Έ 경우 λ¦¬μ‚¬μ΄μ¦ˆ
                if frame.shape[:2] != (height, width):
                    frame = cv2.resize(frame, (width, height))
                out.write(frame)
            cap.release()

        out.release()
        print(f"Successfully merged {len(videos)} videos")
        return output_path
        
    except Exception as e:
        raise gr.Error(f"λΉ„λ””μ˜€ κ²°ν•© 쀑 였λ₯˜ λ°œμƒ: {e}")

def generate_script(topic):
    """μ£Όμ œμ— λ§žλŠ” 슀크립트 생성"""
    if not topic:
        return "주제λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”."
        
    messages = [
        {"role": "system", "content": """당신은 μ˜μƒ 슀크립트 μž‘μ„± μ „λ¬Έκ°€μž…λ‹ˆλ‹€.
주어진 주제둜 λ‹€μŒ ꡬ쑰에 λ§žλŠ” 5개 μ„Ήμ…˜μ˜ 슀크립트λ₯Ό μž‘μ„±ν•΄μ£Όμ„Έμš”:

1. λ°°κ²½ 및 ν•„μš”μ„±: 주제 μ†Œκ°œμ™€ μ‹œμ²­μžμ˜ ν₯λ―Έ 유발
2. ν₯λ―Έ 유발: ꡬ체적인 λ‚΄μš© μ „κ°œμ™€ ν˜ΈκΈ°μ‹¬ 자극
3. ν•΄κ²°μ±… μ œμ‹œ: 핡심 λ‚΄μš©κ³Ό ν•΄κ²°λ°©μ•ˆ μ œμ‹œ
4. λ³Έλ‘ : μƒμ„Έν•œ μ„€λͺ…κ³Ό μž₯점 뢀각
5. κ²°λ‘ : 핡심 λ©”μ‹œμ§€ 강쑰와 행동 μœ λ„

각 μ„Ήμ…˜μ€ μžμ—°μŠ€λŸ½κ²Œ μ—°κ²°λ˜μ–΄μ•Ό ν•˜λ©°, 
μ „μ²΄μ μœΌλ‘œ μΌκ΄€λœ 톀과 λΆ„μœ„κΈ°λ₯Ό μœ μ§€ν•˜λ©΄μ„œλ„ 
μ‹œμ²­μžμ˜ 관심을 λκΉŒμ§€ μœ μ§€ν•  수 μžˆλ„λ‘ μž‘μ„±ν•΄μ£Όμ„Έμš”."""},
        {"role": "user", "content": f"λ‹€μŒ 주제둜 μ˜μƒ 슀크립트λ₯Ό μž‘μ„±ν•΄μ£Όμ„Έμš”: {topic}"}
    ]
    
    try:
        response = client.chat.completions.create(
            model="gpt-4-1106-preview",
            messages=messages,
            max_tokens=2000,
            temperature=0.7
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        print(f"Error during script generation: {e}")
        return "슀크립트 생성 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€."


def cleanup():
    """λ©”λͺ¨λ¦¬ 정리 ν•¨μˆ˜"""
    torch.cuda.empty_cache()
    gc.collect()

with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange") as iface:
     # State λ³€μˆ˜λ“€μ˜ μ΄ˆκΈ°ν™”
     txt2vid_current_height = gr.State(value=320)
     txt2vid_current_width = gr.State(value=512)
     txt2vid_current_num_frames = gr.State(value=257)

     img2vid_current_height = gr.State(value=320)
     img2vid_current_width = gr.State(value=512)
     img2vid_current_num_frames = gr.State(value=257)

     with gr.Tabs():
          # Text to Video Tab
          with gr.TabItem("ν…μŠ€νŠΈλ‘œ λΉ„λ””μ˜€ λ§Œλ“€κΈ°"):
               with gr.Row():
                    with gr.Column():
                         txt2vid_prompt = gr.Textbox(
                              label="Step 1: ν”„λ‘¬ν”„νŠΈ μž…λ ₯",
                              placeholder="μƒμ„±ν•˜κ³  싢은 λΉ„λ””μ˜€λ₯Ό μ„€λͺ…ν•˜μ„Έμš” (μ΅œμ†Œ 50자)...",
                              value="κ·€μ—¬μš΄ 고양이",
                              lines=5,
                         )
                         txt2vid_enhance_toggle = Toggle(
                              label="ν”„λ‘¬ν”„νŠΈ 증강",
                              value=False,
                              interactive=True,
                         )
                         txt2vid_negative_prompt = gr.Textbox(
                              label="Step 2: λ„€κ±°ν‹°λΈŒ ν”„λ‘¬ν”„νŠΈ μž…λ ₯",
                              placeholder="λΉ„λ””μ˜€μ—μ„œ μ›ν•˜μ§€ μ•ŠλŠ” μš”μ†Œλ₯Ό μ„€λͺ…ν•˜μ„Έμš”...",
                              value="low quality, worst quality, deformed, distorted, warped, motion smear, motion artifacts, fused fingers, incorrect anatomy, strange hands, unattractive",
                              lines=2,
                              visible=False
                         )
                         txt2vid_preset = gr.Dropdown(
                              choices=[p["label"] for p in preset_options],
                              value="[16:9] 512x320, 10.3초",
                              label="Step 2: 해상도 프리셋 선택",
                         )
                         txt2vid_frame_rate = gr.Slider(
                              label="Step 3: ν”„λ ˆμž„ 레이트",
                              minimum=21,
                              maximum=30,
                              step=1,
                              value=25,
                              visible=False
                         )
                         txt2vid_advanced = create_advanced_options()
                         txt2vid_generate = gr.Button(
                              "Step 3: λΉ„λ””μ˜€ 생성",
                              variant="primary",
                              size="lg",
                         )
                    with gr.Column():
                         txt2vid_output = gr.Video(label="μƒμ„±λœ λΉ„λ””μ˜€")


# Image to Video Tab
          with gr.TabItem("μ΄λ―Έμ§€λ‘œ λΉ„λ””μ˜€ λ§Œλ“€κΈ°"):
               with gr.Row():
                    with gr.Column():
                         img2vid_image = gr.Image(
                              type="filepath",
                              label="Step 1: μž…λ ₯ 이미지 μ—…λ‘œλ“œ",
                              elem_id="image_upload",
                         )
                         img2vid_prompt = gr.Textbox(
                              label="Step 2: ν”„λ‘¬ν”„νŠΈ μž…λ ₯",
                              placeholder="이미지λ₯Ό μ–΄λ–»κ²Œ μ• λ‹ˆλ©”μ΄μ…˜ν™”ν• μ§€ μ„€λͺ…ν•˜μ„Έμš” (μ΅œμ†Œ 50자)...",
                              value="κ·€μ—¬μš΄ 고양이",
                              lines=5,
                         )
                         img2vid_enhance_toggle = Toggle(
                              label="ν”„λ‘¬ν”„νŠΈ 증강",
                              value=False,
                              interactive=True,
                         )
                         img2vid_negative_prompt = gr.Textbox(
                              label="Step 3: λ„€κ±°ν‹°λΈŒ ν”„λ‘¬ν”„νŠΈ μž…λ ₯",
                              placeholder="λΉ„λ””μ˜€μ—μ„œ μ›ν•˜μ§€ μ•ŠλŠ” μš”μ†Œλ₯Ό μ„€λͺ…ν•˜μ„Έμš”...",
                              value="low quality, worst quality, deformed, distorted, warped, motion smear, motion artifacts, fused fingers, incorrect anatomy, strange hands, unattractive",
                              lines=2,
                              visible=False
                         )
                         img2vid_preset = gr.Dropdown(
                              choices=[p["label"] for p in preset_options],
                              value="[16:9] 512x320, 10.3초",
                              label="Step 3: 해상도 프리셋 선택",
                         )
                         img2vid_frame_rate = gr.Slider(
                              label="Step 4: ν”„λ ˆμž„ 레이트",
                              minimum=21,
                              maximum=30,
                              step=1,
                              value=25,
                              visible=False
                         )
                         img2vid_advanced = create_advanced_options()
                         img2vid_generate = gr.Button(
                              "Step 4: λΉ„λ””μ˜€ 생성",
                              variant="primary",
                              size="lg",
                         )
                    with gr.Column():
                         img2vid_output = gr.Video(label="μƒμ„±λœ λΉ„λ””μ˜€")                        


# Scenario Tab
          with gr.TabItem("μ‹œλ‚˜λ¦¬μ˜€λ‘œ λΉ„λ””μ˜€ λ§Œλ“€κΈ°(숏폼)"):
               with gr.Row():
                    with gr.Column(scale=1):
                         script_topic = gr.Textbox(
                              label="슀크립트 생성",
                              placeholder="겨울 일본 온천 여행을 주제둜 밝은 λŠλ‚ŒμœΌλ‘œ 슀크립트 μƒμ„±ν•˜λΌ",
                              lines=2
                         )
                         generate_script_btn = gr.Button("슀크립트 생성", variant="primary")
                         
                         scenario_input = gr.Textbox(
                              label="μ˜μƒ 슀크립트 μž…λ ₯",
                              placeholder="전체 μ‹œλ‚˜λ¦¬μ˜€λ₯Ό μž…λ ₯ν•˜μ„Έμš”...",
                              lines=10
                         )
                         scenario_preset = gr.Dropdown(
                              choices=[p["label"] for p in preset_options],
                              value="[16:9] 512x320, 10.3초",
                              label="ν™”λ©΄ 크기 선택"
                         )
                         analyze_btn = gr.Button("μ‹œλ‚˜λ¦¬μ˜€ 뢄석 및 ν”„λ‘¬ν”„νŠΈ 생성", variant="primary")

                    with gr.Column(scale=2):
                         with gr.Row():
                              # μ„Ήμ…˜ 1
                              with gr.Column():
                                   section1_prompt = gr.Textbox(
                                        label="1. λ°°κ²½ 및 ν•„μš”μ„±",
                                        lines=4
                                   )
                                   with gr.Row():
                                        section1_regenerate = gr.Button("πŸ”„ ν”„λ‘¬ν”„νŠΈ 생성")
                                        section1_generate = gr.Button("πŸ”„ μ˜μƒ 생성")
                                   section1_video = gr.Video(label="μ„Ήμ…˜ 1 μ˜μƒ")
                              
                              # μ„Ήμ…˜ 2
                              with gr.Column():
                                   section2_prompt = gr.Textbox(
                                        label="2. ν₯λ―Έ 유발",
                                        lines=4
                                   )
                                   with gr.Row():
                                        section2_regenerate = gr.Button("πŸ”„ ν”„λ‘¬ν”„νŠΈ 생성")
                                        section2_generate = gr.Button("πŸ”„ μ˜μƒ 생성")
                                   section2_video = gr.Video(label="μ„Ήμ…˜ 2 μ˜μƒ")



                         with gr.Row():
                              # μ„Ήμ…˜ 3
                              with gr.Column():
                                   section3_prompt = gr.Textbox(
                                        label="3. ν•΄κ²°μ±… μ œμ‹œ",
                                        lines=4
                                   )
                                   with gr.Row():
                                        section3_regenerate = gr.Button("πŸ”„ ν”„λ‘¬ν”„νŠΈ 생성")
                                        section3_generate = gr.Button("πŸ”„ μ˜μƒ 생성")
                                   section3_video = gr.Video(label="μ„Ήμ…˜ 3 μ˜μƒ")
                              
                              # μ„Ήμ…˜ 4
                              with gr.Column():
                                   section4_prompt = gr.Textbox(
                                        label="4. λ³Έλ‘ ",
                                        lines=4
                                   )
                                   with gr.Row():
                                        section4_regenerate = gr.Button("πŸ”„ ν”„λ‘¬ν”„νŠΈ 생성")
                                        section4_generate = gr.Button("πŸ”„ μ˜μƒ 생성")
                                   section4_video = gr.Video(label="μ„Ήμ…˜ 4 μ˜μƒ")
                         
                         with gr.Row():
                              # μ„Ήμ…˜ 5
                              with gr.Column():
                                   section5_prompt = gr.Textbox(
                                        label="5. κ²°λ‘  및 κ°•μ‘°",
                                        lines=4
                                   )
                                   with gr.Row():
                                        section5_regenerate = gr.Button("πŸ”„ ν”„λ‘¬ν”„νŠΈ 생성")
                                        section5_generate = gr.Button("πŸ”„ μ˜μƒ 생성")
                                   section5_video = gr.Video(label="μ„Ήμ…˜ 5 μ˜μƒ")

                         # 톡합 μ˜μƒ μ„Ήμ…˜
                         with gr.Row():
                              with gr.Column(scale=1):
                                   merge_videos_btn = gr.Button("톡합 μ˜μƒ 생성", variant="primary", size="lg")
                              
                              with gr.Column(scale=2):
                                   with gr.Row():
                                        merged_video_output = gr.Video(label="톡합 μ˜μƒ")


# Text to Video Tab handlers
     txt2vid_preset.change(
          fn=preset_changed,
          inputs=[txt2vid_preset],
          outputs=[
               txt2vid_current_height,
               txt2vid_current_width,
               txt2vid_current_num_frames,
               txt2vid_advanced[3],  # height_slider
               txt2vid_advanced[4],  # width_slider
               txt2vid_advanced[5],  # num_frames_slider
          ]
     )

     txt2vid_enhance_toggle.change(
          fn=update_prompt_t2v,
          inputs=[txt2vid_prompt, txt2vid_enhance_toggle],
          outputs=txt2vid_prompt
     )

     txt2vid_generate.click(
          fn=generate_video_from_text,
          inputs=[
               txt2vid_prompt,
               txt2vid_enhance_toggle,
               txt2vid_negative_prompt,
               txt2vid_frame_rate,
               txt2vid_advanced[0],  # seed
               txt2vid_advanced[1],  # inference_steps
               txt2vid_advanced[2],  # guidance_scale
               txt2vid_current_height,
               txt2vid_current_width,
               txt2vid_current_num_frames,
          ],
          outputs=txt2vid_output,
     )

     # Image to Video Tab handlers
     img2vid_preset.change(
          fn=preset_changed,
          inputs=[img2vid_preset],
          outputs=[
               img2vid_current_height,
               img2vid_current_width,
               img2vid_current_num_frames,
               img2vid_advanced[3],  # height_slider
               img2vid_advanced[4],  # width_slider
               img2vid_advanced[5],  # num_frames_slider
          ]
     )

     img2vid_enhance_toggle.change(
          fn=update_prompt_i2v,
          inputs=[img2vid_prompt, img2vid_enhance_toggle],
          outputs=img2vid_prompt
     )

     img2vid_generate.click(
          fn=generate_video_from_image,
          inputs=[
               img2vid_image,
               img2vid_prompt,
               img2vid_enhance_toggle,
               img2vid_negative_prompt,
               img2vid_frame_rate,
               img2vid_advanced[0],  # seed
               img2vid_advanced[1],  # inference_steps
               img2vid_advanced[2],  # guidance_scale
               img2vid_current_height,
               img2vid_current_width,
               img2vid_current_num_frames,
          ],
          outputs=img2vid_output,
     )



# Scenario Tab handlers
     generate_script_btn.click(
          fn=generate_script,
          inputs=[script_topic],
          outputs=[scenario_input]
     )

     analyze_btn.click(
          fn=analyze_scenario,
          inputs=[scenario_input],
          outputs=[
               section1_prompt, section2_prompt, section3_prompt,
               section4_prompt, section5_prompt
          ]
     )

     # μ„Ήμ…˜λ³„ ν”„λ‘¬ν”„νŠΈ μž¬μƒμ„± ν•Έλ“€λŸ¬
     section1_regenerate.click(
          fn=lambda x: generate_single_section_prompt(x, 1),
          inputs=[scenario_input],
          outputs=section1_prompt
     )

     section2_regenerate.click(
          fn=lambda x: generate_single_section_prompt(x, 2),
          inputs=[scenario_input],
          outputs=section2_prompt
     )

     section3_regenerate.click(
          fn=lambda x: generate_single_section_prompt(x, 3),
          inputs=[scenario_input],
          outputs=section3_prompt
     )

     section4_regenerate.click(
          fn=lambda x: generate_single_section_prompt(x, 4),
          inputs=[scenario_input],
          outputs=section4_prompt
     )

     section5_regenerate.click(
          fn=lambda x: generate_single_section_prompt(x, 5),
          inputs=[scenario_input],
          outputs=section5_prompt
     )

     # μ„Ήμ…˜λ³„ λΉ„λ””μ˜€ 생성 ν•Έλ“€λŸ¬
     section1_generate.click(
          fn=lambda p, pr: generate_section_video(p, pr, 1),
          inputs=[section1_prompt, scenario_preset],
          outputs=section1_video
     )

     section2_generate.click(
          fn=lambda p, pr: generate_section_video(p, pr, 2),
          inputs=[section2_prompt, scenario_preset],
          outputs=section2_video
     )

     section3_generate.click(
          fn=lambda p, pr: generate_section_video(p, pr, 3),
          inputs=[section3_prompt, scenario_preset],
          outputs=section3_video
     )

     section4_generate.click(
          fn=lambda p, pr: generate_section_video(p, pr, 4),
          inputs=[section4_prompt, scenario_preset],
          outputs=section4_video
     )

     section5_generate.click(
          fn=lambda p, pr: generate_section_video(p, pr, 5),
          inputs=[section5_prompt, scenario_preset],
          outputs=section5_video
     )

     # 톡합 μ˜μƒ 생성 ν•Έλ“€λŸ¬
     merge_videos_btn.click(
          fn=merge_section_videos,
          inputs=[
               section1_video,
               section2_video,
               section3_video,
               section4_video,
               section5_video
          ],
          outputs=merged_video_output
     )

if __name__ == "__main__":
     iface.queue(max_size=64, default_concurrency_limit=1, api_open=False).launch(
          share=True, 
          show_api=False
     )