File size: 106,001 Bytes
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
0de860d
8c7b732
 
393e229
 
 
 
8c7b732
 
0de860d
 
 
 
 
8c7b732
 
 
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
0de860d
 
393e229
 
0de860d
 
 
 
393e229
 
0de860d
 
 
 
 
 
 
 
 
 
393e229
0de860d
 
393e229
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
0de860d
 
 
 
 
 
 
 
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
8c7b732
393e229
 
 
 
 
 
8c7b732
393e229
 
 
 
8c7b732
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
393e229
8c7b732
 
393e229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
 
 
 
 
 
 
0de860d
393e229
 
 
 
 
 
 
 
 
 
 
0de860d
 
 
393e229
 
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
 
 
 
 
 
 
 
 
 
0de860d
 
 
 
 
 
 
 
393e229
0de860d
 
 
 
 
393e229
0de860d
 
 
393e229
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
8c7b732
393e229
8c7b732
0de860d
8c7b732
 
 
 
393e229
 
8c7b732
 
 
393e229
8c7b732
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
0de860d
 
393e229
 
0de860d
 
8c7b732
393e229
0de860d
 
393e229
8c7b732
 
393e229
 
 
 
8c7b732
 
0de860d
 
393e229
 
0de860d
 
 
 
 
 
393e229
0de860d
 
393e229
0de860d
393e229
 
0de860d
 
 
 
393e229
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
0de860d
 
393e229
 
0de860d
 
8c7b732
393e229
0de860d
 
393e229
8c7b732
 
393e229
 
 
 
8c7b732
 
393e229
0de860d
393e229
 
0de860d
 
393e229
0de860d
393e229
0de860d
393e229
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
0de860d
 
393e229
0de860d
 
 
393e229
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
0de860d
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
8c7b732
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
 
 
 
0de860d
7a610d2
0de860d
 
 
 
 
 
 
 
7a610d2
 
 
 
 
 
 
0de860d
 
 
 
 
393e229
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
393e229
8c7b732
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de860d
 
 
 
 
8c7b732
 
 
 
 
 
 
0de860d
8c7b732
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a610d2
0de860d
8c7b732
 
 
 
393e229
 
 
 
 
 
 
8c7b732
393e229
8c7b732
 
0de860d
 
393e229
0de860d
8c7b732
0de860d
 
393e229
 
8c7b732
 
 
0de860d
8c7b732
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
 
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a610d2
 
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
 
 
 
 
 
 
 
 
 
 
393e229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c7b732
 
 
 
 
0de860d
 
 
 
 
 
7a610d2
0de860d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393e229
8c7b732
 
 
 
 
393e229
0de860d
 
 
 
 
393e229
0de860d
 
 
 
 
393e229
0de860d
 
 
 
 
393e229
0de860d
 
 
393e229
 
 
 
 
0de860d
393e229
 
0de860d
393e229
 
 
0de860d
 
393e229
 
 
 
 
 
 
 
 
 
 
 
0de860d
393e229
 
0de860d
7a610d2
393e229
 
0de860d
7a610d2
393e229
0de860d
 
393e229
0de860d
393e229
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
import replicate
import requests
import os
import json
from io import BytesIO
from PIL import Image
from typing import List, Tuple, Dict
from datetime import datetime
import time
import traceback
import base64
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
from pptx.enum.shapes import MSO_SHAPE
import PyPDF2
import pandas as pd
import chardet
import gradio as gr

# 예제 ν…œν”Œλ¦Ώ μ •μ˜
EXAMPLE_TOPICS = {
    "λΉ„μ¦ˆλ‹ˆμŠ€ μ œμ•ˆμ„œ": "AI 기반 고객 μ„œλΉ„μŠ€ μžλ™ν™” ν”Œλž«νΌ 투자 μ œμ•ˆ",
    "μ œν’ˆ μ†Œκ°œ": "슀마트 ν™ˆ IoT λ³΄μ•ˆ μ‹œμŠ€ν…œ μ‹ μ œν’ˆ 런칭",
    "ν”„λ‘œμ νŠΈ 보고": "λ””μ§€ν„Έ μ „ν™˜ ν”„λ‘œμ νŠΈ 3λΆ„κΈ° μ„±κ³Ό 보고",
    "μ „λž΅ 기획": "2025λ…„ κΈ€λ‘œλ²Œ μ‹œμž₯ μ§„μΆœ μ „λž΅ 수립"
}

# ν™˜κ²½ λ³€μˆ˜μ—μ„œ 토큰 κ°€μ Έμ˜€κΈ°
REPLICATE_API_TOKEN = os.getenv("RAPI_TOKEN")
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN")
BRAVE_API_TOKEN = os.getenv("BAPI_TOKEN")

# μ „μ—­ λ³€μˆ˜λ‘œ ν˜„μž¬ μŠ¬λΌμ΄λ“œ 데이터 μ €μž₯
current_slides_data = []
current_topic = ""
current_template = ""
current_theme = ""

# λ””μžμΈ ν…Œλ§ˆ μ •μ˜
DESIGN_THEMES = {
    "λ―Έλ‹ˆλ©€ 라이트": {
        "name": "Minimal Light",
        "description": "밝고 κΉ¨λ—ν•œ λ―Έλ‹ˆλ©€ λ””μžμΈ",
        "background": RGBColor(250, 250, 252),
        "title_color": RGBColor(33, 37, 41),
        "subtitle_color": RGBColor(52, 58, 64),
        "text_color": RGBColor(73, 80, 87),
        "accent_color": RGBColor(0, 123, 255),
        "box_fill": RGBColor(255, 255, 255),
        "box_opacity": 0.95,
        "shadow": True,
        "gradient": False
    },
    "λͺ¨λ˜ κ·ΈλΌλ””μ–ΈνŠΈ": {
        "name": "Modern Gradient",
        "description": "λΆ€λ“œλŸ¬μš΄ κ·ΈλΌλ””μ–ΈνŠΈμ™€ ν˜„λŒ€μ  λŠλ‚Œ",
        "background": RGBColor(245, 247, 250),
        "title_color": RGBColor(25, 42, 86),
        "subtitle_color": RGBColor(68, 85, 102),
        "text_color": RGBColor(85, 102, 119),
        "accent_color": RGBColor(103, 58, 183),
        "box_fill": RGBColor(249, 250, 251),
        "box_opacity": 0.9,
        "shadow": True,
        "gradient": True
    },
    "닀크 μ—˜λ ˆκ°•μŠ€": {
        "name": "Dark Elegance",
        "description": "μ„Έλ ¨λœ 닀크 λͺ¨λ“œ λ””μžμΈ",
        "background": RGBColor(25, 25, 35),
        "title_color": RGBColor(240, 240, 245),
        "subtitle_color": RGBColor(200, 200, 210),
        "text_color": RGBColor(170, 170, 180),
        "accent_color": RGBColor(0, 188, 212),
        "box_fill": RGBColor(35, 35, 45),
        "box_opacity": 0.85,
        "shadow": False,
        "gradient": False
    },
    "λ„€μ΄μ²˜ κ·Έλ¦°": {
        "name": "Nature Green",
        "description": "μžμ—° μΉœν™”μ μΈ κ·Έλ¦° ν…Œλ§ˆ",
        "background": RGBColor(242, 248, 244),
        "title_color": RGBColor(27, 67, 50),
        "subtitle_color": RGBColor(45, 106, 79),
        "text_color": RGBColor(64, 125, 98),
        "accent_color": RGBColor(76, 175, 80),
        "box_fill": RGBColor(255, 255, 255),
        "box_opacity": 0.92,
        "shadow": True,
        "gradient": False
    },
    "μ½”νΌλ ˆμ΄νŠΈ 블루": {
        "name": "Corporate Blue",
        "description": "전문적인 λΉ„μ¦ˆλ‹ˆμŠ€ μŠ€νƒ€μΌ",
        "background": RGBColor(244, 247, 252),
        "title_color": RGBColor(13, 71, 161),
        "subtitle_color": RGBColor(25, 118, 210),
        "text_color": RGBColor(42, 63, 84),
        "accent_color": RGBColor(33, 150, 243),
        "box_fill": RGBColor(255, 255, 255),
        "box_opacity": 0.95,
        "shadow": True,
        "gradient": False
    }
}

# μŠ€νƒ€μΌ μ •μ˜ (ν‘œμ§€μ™€ μ’…λ£Œ μŠ¬λΌμ΄λ“œ μŠ€νƒ€μΌ μΆ”κ°€)
STYLE_TEMPLATES = {
    "Title Slide (Hero)": {
        "name": "Title Slide",
        "description": "Impactful hero image for title slide",
        "use_case": "ν‘œμ§€, 타이틀",
        "example": "A dramatic wide-angle view of a modern glass skyscraper reaching into clouds with golden sunset lighting, symbolizing growth and ambition. Ultra-realistic photography style, cinematic composition, lens flare, professional corporate aesthetic"
    },
    "Thank You Slide": {
        "name": "Closing Slide",
        "description": "Elegant closing slide design with conclusion",
        "use_case": "ν”„λ ˆμ  ν…Œμ΄μ…˜ 마무리",
        "example": "Abstract elegant background with soft gradient from deep blue to purple, golden particles floating like celebration confetti, subtle light rays, with space for conclusion text. Minimalist, professional, warm feeling"
    },
    "3D Style (Pixar-like)": {
        "name": "3D Style",
        "description": "Pixar-esque 3D render with volumetric lighting",
        "use_case": "ν‘œμ§€, λΉ„μ „, 미래 컨셉",
        "example": "A fluffy ginger cat wearing a tiny spacesuit, floating amidst a vibrant nebula in a 3D render. The cat is gazing curiously at a swirling planet with rings made of candy. Background is filled with sparkling stars and colorful gas clouds, lit with soft, volumetric lighting. Style: Pixar-esque, highly detailed, playful. Colors: Deep blues, purples, oranges, and pinks. Rendered in Octane, 8k resolution."
    },
    "Elegant SWOT Quadrant": {
        "name": "SWOT Analysis",
        "description": "Flat-design 4-grid layout with minimal shadows",
        "use_case": "ν˜„ν™© 뢄석, μ „λž΅ 평가",
        "example": "Elegant SWOT quadrant: flat-design 4-grid on matte-white backdrop, thin pastel separators, top-left 'Strengths' panel shows glowing shield icon and subtle motif, top-right 'Weaknesses' panel with cracked chain icon in soft crimson, bottom-left 'Opportunities' panel with sunrise-over-horizon icon in optimistic teal, bottom-right 'Threats' panel with storm-cloud & lightning icon in deep indigo, minimal shadows, no text, no watermark, 16:9, 4K"
    },
    "Colorful Mind Map": {
        "name": "Mind Map",
        "description": "Hand-drawn educational style with vibrant colors",
        "use_case": "λΈŒλ ˆμΈμŠ€ν† λ°, 아이디어 정리",
        "example": "A handrawn colorful mind map diagram: educational style, vibrant colors, clear hierarchy, golden ratio layout. Central concept with branching sub-topics, each branch with unique color coding, organic flowing connections, doodle-style icons for each node"
    },
    "Business Workflow": {
        "name": "Business Process",
        "description": "End-to-end business workflow with clear phases",
        "use_case": "ν”„λ‘œμ„ΈμŠ€ μ„€λͺ…, 단계별 μ§„ν–‰",
        "example": "A detailed hand-drawn diagram illustrating an end-to-end business workflow with Market Analysis, Strategy Development, Product Design, Implementation, and Post-Launch Review phases. Clear directional arrows, iconography for each component, vibrant educational yet professional style"
    },
    "Industrial Design": {
        "name": "Product Design",
        "description": "Sleek industrial design concept sketch",
        "use_case": "μ œν’ˆ μ†Œκ°œ, 컨셉 λ””μžμΈ",
        "example": "A sleek industrial design concept: Curved metallic body with minimal bezel, Touchscreen panel for settings, Modern matte black finish, Hand-drawn concept sketch style with annotations and dimension lines"
    },
    "3D Bubble Chart": {
        "name": "Bubble Chart",
        "description": "Clean 3D bubble visualization",
        "use_case": "비ꡐ 뢄석, 포지셔닝",
        "example": "3-D bubble chart on clean white 2Γ—2 grid, quadrant titles hidden, four translucent spheres in lime, azure, amber, magenta, gentle depth-of-field, modern consulting aesthetic, no text, 4K"
    },
    "Timeline Ribbon": {
        "name": "Timeline",
        "description": "Horizontal ribbon timeline with cyber-futuristic vibe",
        "use_case": "일정, λ‘œλ“œλ§΅, λ§ˆμΌμŠ€ν†€",
        "example": "Horizontal ribbon timeline, milestone pins glowing hot pink on charcoal, year markers as circles, faint motion streaks, cyber-futuristic vibe, no text, 1920Γ—1080"
    },
    "Risk Heat Map": {
        "name": "Heat Map",
        "description": "Risk assessment heat map with gradient colors",
        "use_case": "리슀크 뢄석, μš°μ„ μˆœμœ„",
        "example": "Risk Heat Map: square grid, smooth gradient from mint to fire-red, cells beveled, simple legend strip hidden, long subtle shadow, sterile white frame, no text"
    },
    "Pyramid/Funnel": {
        "name": "Funnel Chart",
        "description": "Multi-layer gradient funnel visualization",
        "use_case": "단계별 μΆ•μ†Œ, 핡심 λ„μΆœ",
        "example": "Pyramid / Funnel: 5-layer gradient funnel narrowing downwards, top vivid sky-blue, mid mint-green, bottom sunset-orange, glass reflection, minimal background, no text"
    },
    "KPI Dashboard": {
        "name": "Dashboard",
        "description": "Dark-mode analytics dashboard with sci-fi interface",
        "use_case": "μ„±κ³Ό μ§€ν‘œ, 싀적 λŒ€μ‹œλ³΄λ“œ",
        "example": "KPI Dashboard: Dark-mode analytic dashboard, three glass speedometers glowing neon lime, two sparkline charts under, black glass background, sci-fi interface, no text, 4K"
    },
    "Value Chain": {
        "name": "Value Chain",
        "description": "Horizontal value chain with industrial look",
        "use_case": "κ°€μΉ˜ μ‚¬μŠ¬, λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ",
        "example": "Value Chain Diagram: Horizontal value chain blocks, steel-blue gradient bars with subtle bevel, small gear icons above each segment, sleek industrial look, shadow cast, no text"
    },
    "Gantt Chart": {
        "name": "Gantt Chart",
        "description": "Hand-drawn style Gantt chart with playful colors",
        "use_case": "ν”„λ‘œμ νŠΈ 일정, μž‘μ—… 관리",
        "example": "Gantt Chart: Hand-drawn style Gantt bars sketched with vibrant markers on dotted grid notebook page, sticky-note color palette, playful yet organized, perspective tilt, no text"
    },
    "Mobile App Mockup": {
        "name": "App Mockup",
        "description": "Clean wireframe for mobile app design",
        "use_case": "μ•±/μ›Ή UI, ν™”λ©΄ 섀계",
        "example": "MOCKUP DESIGN: A clean hand-drawn style wireframe for a mobile app with Title screen, Login screen, Dashboard with sections, Bottom navigation bar, minimalist design with annotations"
    },
    "Flowchart": {
        "name": "Flowchart",
        "description": "Vibrant flowchart with minimalistic icons",
        "use_case": "μ˜μ‚¬κ²°μ •, ν”„λ‘œμ„ΈμŠ€ 흐름",
        "example": "FLOWCHART DESIGN: A hand-drawn style flowchart, vibrant colors, minimalistic icons showing process flow from START to END with decision points, branches, and clear directional arrows"
    }
}

# PPT ν…œν”Œλ¦Ώ μ •μ˜ (λ™μ μœΌλ‘œ μŠ¬λΌμ΄λ“œ 수 μ‘°μ • κ°€λŠ₯)
PPT_TEMPLATES = {
    "λΉ„μ¦ˆλ‹ˆμŠ€ μ œμ•ˆμ„œ": {
        "description": "투자 유치, 사업 μ œμ•ˆμš©",
        "core_slides": [
            {"title": "λͺ©μ°¨", "style": "Flowchart", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ ꡬ쑰"},
            {"title": "문제 μ •μ˜", "style": "Colorful Mind Map", "prompt_hint": "ν˜„μž¬ μ‹œμž₯의 문제점"},
            {"title": "ν˜„ν™© 뢄석", "style": "Elegant SWOT Quadrant", "prompt_hint": "강점, 약점, 기회, μœ„ν˜‘"},
            {"title": "μ†”λ£¨μ…˜", "style": "Industrial Design", "prompt_hint": "μ œν’ˆ/μ„œλΉ„μŠ€ 컨셉"},
            {"title": "ν”„λ‘œμ„ΈμŠ€", "style": "Business Workflow", "prompt_hint": "μ‹€ν–‰ 단계"},
            {"title": "일정", "style": "Timeline Ribbon", "prompt_hint": "μ£Όμš” λ§ˆμΌμŠ€ν†€"}
        ],
        "optional_slides": [
            {"title": "μ‹œμž₯ 규λͺ¨", "style": "3D Bubble Chart", "prompt_hint": "μ‹œμž₯ κΈ°νšŒμ™€ μ„±μž₯μ„±"},
            {"title": "경쟁 뢄석", "style": "Risk Heat Map", "prompt_hint": "κ²½μŸμ‚¬ 포지셔닝"},
            {"title": "λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ", "style": "Value Chain", "prompt_hint": "수읡 ꡬ쑰"},
            {"title": "νŒ€ μ†Œκ°œ", "style": "Colorful Mind Map", "prompt_hint": "핡심 νŒ€μ›κ³Ό μ—­λŸ‰"},
            {"title": "재무 κ³„νš", "style": "KPI Dashboard", "prompt_hint": "μ˜ˆμƒ 맀좜과 손읡"},
            {"title": "μœ„ν—˜ 관리", "style": "Risk Heat Map", "prompt_hint": "μ£Όμš” λ¦¬μŠ€ν¬μ™€ λŒ€μ‘"},
            {"title": "νŒŒνŠΈλ„ˆμ‹­", "style": "Business Workflow", "prompt_hint": "μ „λž΅μ  제휴"},
            {"title": "기술 μŠ€νƒ", "style": "Flowchart", "prompt_hint": "핡심 기술 ꡬ쑰"},
            {"title": "고객 사둀", "style": "Industrial Design", "prompt_hint": "성곡 사둀"},
            {"title": "μ„±μž₯ μ „λž΅", "style": "Timeline Ribbon", "prompt_hint": "ν™•μž₯ κ³„νš"},
            {"title": "투자 ν™œμš©", "style": "Pyramid/Funnel", "prompt_hint": "자금 μ‚¬μš© κ³„νš"},
            {"title": "Exit μ „λž΅", "style": "Timeline Ribbon", "prompt_hint": "좜ꡬ μ „λž΅"}
        ]
    },
    "μ œν’ˆ μ†Œκ°œ": {
        "description": "μ‹ μ œν’ˆ 런칭, μ„œλΉ„μŠ€ μ†Œκ°œμš©",
        "core_slides": [
            {"title": "μ œν’ˆ 컨셉", "style": "Industrial Design", "prompt_hint": "μ œν’ˆ λ””μžμΈ"},
            {"title": "μ‚¬μš©μž λ‹ˆμ¦ˆ", "style": "Colorful Mind Map", "prompt_hint": "고객 페인포인트"},
            {"title": "κΈ°λŠ₯ μ†Œκ°œ", "style": "Mobile App Mockup", "prompt_hint": "UI/UX ν™”λ©΄"},
            {"title": "μž‘λ™ 원리", "style": "Flowchart", "prompt_hint": "κΈ°λŠ₯ ν”Œλ‘œμš°"},
            {"title": "μ‹œμž₯ ν¬μ§€μ…˜", "style": "3D Bubble Chart", "prompt_hint": "κ²½μŸμ‚¬ 비ꡐ"},
            {"title": "μΆœμ‹œ 일정", "style": "Timeline Ribbon", "prompt_hint": "런칭 λ‘œλ“œλ§΅"}
        ],
        "optional_slides": [
            {"title": "νƒ€κ²Ÿ 고객", "style": "Colorful Mind Map", "prompt_hint": "μ£Όμš” 고객측"},
            {"title": "가격 μ •μ±…", "style": "Pyramid/Funnel", "prompt_hint": "가격 μ „λž΅"},
            {"title": "기술 μš°μœ„", "style": "Industrial Design", "prompt_hint": "핡심 기술"},
            {"title": "μ‚¬μš© μ‹œλ‚˜λ¦¬μ˜€", "style": "Business Workflow", "prompt_hint": "ν™œμš© 사둀"},
            {"title": "고객 ν›„κΈ°", "style": "KPI Dashboard", "prompt_hint": "μ‚¬μš©μž 평가"},
            {"title": "판맀 채널", "style": "Value Chain", "prompt_hint": "μœ ν†΅ μ „λž΅"},
            {"title": "λ§ˆμΌ€νŒ… μ „λž΅", "style": "Timeline Ribbon", "prompt_hint": "홍보 κ³„νš"},
            {"title": "μ„±λŠ₯ 비ꡐ", "style": "3D Bubble Chart", "prompt_hint": "벀치마크"}
        ]
    },
    "ν”„λ‘œμ νŠΈ 보고": {
        "description": "μ§„ν–‰ 상황, μ„±κ³Ό 보고용",
        "core_slides": [
            {"title": "ν”„λ‘œμ νŠΈ κ°œμš”", "style": "Business Workflow", "prompt_hint": "전체 ν”„λ‘œμ„ΈμŠ€"},
            {"title": "μ§„ν–‰ ν˜„ν™©", "style": "Gantt Chart", "prompt_hint": "μž‘μ—… 일정"},
            {"title": "리슀크 관리", "style": "Risk Heat Map", "prompt_hint": "μœ„ν—˜ μš”μ†Œ"},
            {"title": "μ„±κ³Ό μ§€ν‘œ", "style": "KPI Dashboard", "prompt_hint": "달성 싀적"},
            {"title": "ν–₯ν›„ κ³„νš", "style": "Timeline Ribbon", "prompt_hint": "λ‹€μŒ 단계"}
        ],
        "optional_slides": [
            {"title": "μ˜ˆμ‚° ν˜„ν™©", "style": "Pyramid/Funnel", "prompt_hint": "μ˜ˆμ‚° μ§‘ν–‰"},
            {"title": "νŒ€ μ„±κ³Ό", "style": "3D Bubble Chart", "prompt_hint": "νŒ€λ³„ 기여도"},
            {"title": "이슈 관리", "style": "Risk Heat Map", "prompt_hint": "μ£Όμš” 이슈"},
            {"title": "κ°œμ„  사항", "style": "Colorful Mind Map", "prompt_hint": "ν”„λ‘œμ„ΈμŠ€ κ°œμ„ "},
            {"title": "κ΅ν›ˆ", "style": "Business Workflow", "prompt_hint": "배운 점"}
        ]
    },
    "μ „λž΅ 기획": {
        "description": "쀑μž₯κΈ° μ „λž΅, λΉ„μ „ 수립용",
        "core_slides": [
            {"title": "λΉ„μ „", "style": "3D Style (Pixar-like)", "prompt_hint": "미래 λΉ„μ „"},
            {"title": "ν™˜κ²½ 뢄석", "style": "Elegant SWOT Quadrant", "prompt_hint": "λ‚΄μ™ΈλΆ€ ν™˜κ²½"},
            {"title": "μ „λž΅ 체계", "style": "Colorful Mind Map", "prompt_hint": "μ „λž΅ ꡬ쑰"},
            {"title": "κ°€μΉ˜ μ‚¬μŠ¬", "style": "Value Chain", "prompt_hint": "λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ"},
            {"title": "μ‹€ν–‰ λ‘œλ“œλ§΅", "style": "Timeline Ribbon", "prompt_hint": "단계별 κ³„νš"},
            {"title": "λͺ©ν‘œ μ§€ν‘œ", "style": "KPI Dashboard", "prompt_hint": "KPI λͺ©ν‘œ"}
        ],
        "optional_slides": [
            {"title": "μ‹œμž₯ 전망", "style": "3D Bubble Chart", "prompt_hint": "미래 μ‹œμž₯"},
            {"title": "ν˜μ‹  λ°©ν–₯", "style": "Industrial Design", "prompt_hint": "ν˜μ‹  μ „λž΅"},
            {"title": "쑰직 λ³€ν™”", "style": "Business Workflow", "prompt_hint": "쑰직 개편"},
            {"title": "λ””μ§€ν„Έ μ „ν™˜", "style": "Flowchart", "prompt_hint": "DX μ „λž΅"},
            {"title": "지속가λŠ₯μ„±", "style": "Timeline Ribbon", "prompt_hint": "ESG μ „λž΅"}
        ]
    },
    "μ‚¬μš©μž μ •μ˜": {
        "description": "직접 κ΅¬μ„±ν•˜κΈ°",
        "core_slides": [],
        "optional_slides": []
    }
}

def brave_search(query: str) -> List[Dict]:
    """Brave Search APIλ₯Ό μ‚¬μš©ν•œ μ›Ή 검색"""
    if not BRAVE_API_TOKEN:
        print("[Brave Search] API 토큰이 μ—†μ–΄ 검색을 κ±΄λ„ˆλœλ‹ˆλ‹€.")
        return []
    
    print(f"[Brave Search] 검색어: {query}")
    
    headers = {
        "Accept": "application/json",
        "X-Subscription-Token": BRAVE_API_TOKEN
    }
    
    params = {
        "q": query,
        "count": 5
    }
    
    try:
        response = requests.get(
            "https://api.search.brave.com/res/v1/web/search",
            headers=headers,
            params=params,
            timeout=10
        )
        
        if response.status_code == 200:
            data = response.json()
            results = []
            for item in data.get("web", {}).get("results", [])[:3]:
                results.append({
                    "title": item.get("title", ""),
                    "description": item.get("description", ""),
                    "url": item.get("url", "")
                })
            print(f"[Brave Search] {len(results)}개 κ²°κ³Ό νšλ“")
            return results
        else:
            print(f"[Brave Search] 였λ₯˜: {response.status_code}")
            return []
    except Exception as e:
        print(f"[Brave Search] μ˜ˆμ™Έ: {str(e)}")
        return []

def read_uploaded_file(file_path: str) -> str:
    """μ—…λ‘œλ“œλœ 파일 읽기 (PDF, CSV, TXT)"""
    print(f"[파일 읽기] {file_path}")
    
    try:
        # 파일 ν™•μž₯자 확인
        ext = os.path.splitext(file_path)[1].lower()
        
        if ext == '.pdf':
            # PDF 읽기
            with open(file_path, 'rb') as file:
                pdf_reader = PyPDF2.PdfReader(file)
                text = ""
                for page in pdf_reader.pages:
                    text += page.extract_text() + "\n"
                return text[:5000]  # μ΅œλŒ€ 5000자
                
        elif ext == '.csv':
            # CSV 읽기
            # 인코딩 감지
            with open(file_path, 'rb') as file:
                raw_data = file.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding'] or 'utf-8'
            
            df = pd.read_csv(file_path, encoding=encoding)
            return f"CSV 데이터:\n{df.head(20).to_string()}\n\nμš”μ•½: {len(df)} ν–‰, {len(df.columns)} μ—΄"
            
        elif ext in ['.txt', '.text']:
            # ν…μŠ€νŠΈ 파일 읽기
            with open(file_path, 'rb') as file:
                raw_data = file.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding'] or 'utf-8'
            
            with open(file_path, 'r', encoding=encoding) as file:
                return file.read()[:5000]  # μ΅œλŒ€ 5000자
        else:
            return "μ§€μ›ν•˜μ§€ μ•ŠλŠ” 파일 ν˜•μ‹μž…λ‹ˆλ‹€."
            
    except Exception as e:
        return f"파일 읽기 였λ₯˜: {str(e)}"

def generate_presentation_notes(topic: str, slide_title: str, content: Dict) -> str:
    """각 μŠ¬λΌμ΄λ“œμ˜ λ°œν‘œμž λ…ΈνŠΈ 생성 (ꡬ어체)"""
    print(f"[λ°œν‘œμž λ…ΈνŠΈ] {slide_title} 생성 쀑...")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    system_prompt = """You are a professional presentation coach who creates natural, conversational speaker notes.

The slide content uses concise noun-ending style, but your speaker notes should be natural and conversational.

Create speaker notes that:
1. Sound natural and conversational, as if speaking to an audience
2. Expand on the concise bullet points with additional context
3. Include transitions and engagement phrases
4. Use a warm, professional tone
5. Be 100-150 words long
6. Include pauses and emphasis markers where appropriate

Note: The bullet points may include emojis - incorporate their meaning into your speech.

Format:
- Use conversational language
- Include transition phrases
- Add engagement questions or comments
- Keep it professional but friendly"""
    
    bullet_text = "\n".join(content.get("bullet_points", []))
    user_message = f"""Topic: {topic}
Slide Title: {slide_title}
Subtitle: {content.get('subtitle', '')}
Key Points (concise style with emojis):
{bullet_text}

Create natural speaker notes that expand on these concise points for presenting this slide."""
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": user_message
            }
        ],
        "max_tokens": 300,
        "temperature": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            notes = result['choices'][0]['message']['content'].strip()
            
            # ν•œκΈ€ 주제인 경우 λ²ˆμ—­
            if any(ord('κ°€') <= ord(char) <= ord('힣') for char in topic):
                notes = translate_content_to_korean_natural(notes)
            
            return notes
        else:
            return "이 μŠ¬λΌμ΄λ“œμ—μ„œλŠ” 핡심 λ‚΄μš©μ„ μ„€λͺ…ν•΄ μ£Όμ„Έμš”."
    except Exception as e:
        print(f"[λ°œν‘œμž λ…ΈνŠΈ] 였λ₯˜: {str(e)}")
        return "이 μŠ¬λΌμ΄λ“œμ—μ„œλŠ” 핡심 λ‚΄μš©μ„ μ„€λͺ…ν•΄ μ£Όμ„Έμš”."

def regenerate_slide_text(topic: str, slide_title: str, slide_context: str, 
                         user_instruction: str, uploaded_content: str = None) -> Dict[str, str]:
    """μ‚¬μš©μž μ§€μ‹œμ‚¬ν•­μ— 따라 μŠ¬λΌμ΄λ“œ ν…μŠ€νŠΈ μž¬μƒμ„±"""
    print(f"[AI μž¬μž‘μ„±] {slide_title} - μ§€μ‹œμ‚¬ν•­: {user_instruction}")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    system_prompt = """You are a professional presentation content writer. 
Follow the user's specific instructions to rewrite slide content.

Your task is to create:
1. A compelling subtitle (max 10 words)
2. Exactly 5 bullet points with emojis
3. Each bullet point should be 8-12 words
4. Use noun-ending style (λͺ…μ‚¬ν˜• μ’…κ²°) for Korean or concise fragments for English

IMPORTANT Style Guidelines:
- End sentences with nouns or concise phrases
- Avoid long verb endings like "μž…λ‹ˆλ‹€", "μŠ΅λ‹ˆλ‹€"
- Use short endings like "μž„", "함" or noun forms
- Start each bullet with a relevant emoji
- Follow the user's instructions while maintaining this style

Emoji Guidelines:
- Professional emojis: πŸ“Š 🎯 πŸ’‘ πŸš€ ⚑ πŸ” πŸ“ˆ πŸ’° πŸ† πŸ”§ 🌐 πŸ” ⭐ 🎨 πŸ“± 🀝 πŸ“ πŸŽͺ πŸ—οΈ 🌱
- Match emoji to content meaning
- Use different emojis for variety"""
    
    user_message = f"""Topic: {topic}
Slide Title: {slide_title}
Context: {slide_context}

User's specific instruction: {user_instruction}

Rewrite the content following the instruction above while maintaining concise, noun-ending style with emojis."""
    
    if uploaded_content:
        user_message += f"\n\nReference Material:\n{uploaded_content[:1000]}"
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": user_message
            }
        ],
        "max_tokens": 300,
        "temperature": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            content = result['choices'][0]['message']['content'].strip()
            
            # Parse content
            lines = content.split('\n')
            subtitle = ""
            bullet_points = []
            
            for line in lines:
                if line.startswith("Subtitle:"):
                    subtitle = line.replace("Subtitle:", "").strip()
                elif line.strip().startswith("β€’"):
                    bullet_points.append(line.strip())
            
            # ν•œκΈ€λ‘œ λ²ˆμ—­μ΄ ν•„μš”ν•œ 경우
            if any(ord('κ°€') <= ord(char) <= ord('힣') for char in topic):
                subtitle = translate_content_to_korean(subtitle)
                # 뢈릿 ν¬μΈνŠΈλŠ” 이λͺ¨μ§€λ₯Ό μœ μ§€ν•˜λ©΄μ„œ λ²ˆμ—­
                translated_bullets = []
                for point in bullet_points:
                    # 이λͺ¨μ§€μ™€ ν…μŠ€νŠΈ 뢄리
                    parts = point.split(' ', 2)
                    if len(parts) >= 3 and len(parts[1]) <= 2:  # 이λͺ¨μ§€κ°€ μžˆλŠ” 경우
                        emoji = parts[1]
                        text = ' '.join(parts[2:])
                        translated_text = translate_content_to_korean_concise(text)
                        translated_bullets.append(f"β€’ {emoji} {translated_text}")
                    else:
                        translated_bullets.append(translate_content_to_korean_concise(point))
                bullet_points = translated_bullets
            
            return {
                "subtitle": subtitle,
                "bullet_points": bullet_points[:5]
            }
        else:
            return {
                "subtitle": slide_title,
                "bullet_points": ["β€’ ❌ μž¬μƒμ„± μ‹€νŒ¨"] * 5
            }
    except Exception as e:
        print(f"[AI μž¬μž‘μ„±] 였λ₯˜: {str(e)}")
        return {
            "subtitle": slide_title,
            "bullet_points": ["β€’ ❌ μž¬μƒμ„± 였λ₯˜"] * 5
        }

def generate_closing_notes(topic: str, conclusion_phrase: str) -> str:
    """λ§ˆμ§€λ§‰ μŠ¬λΌμ΄λ“œμ˜ λ°œν‘œμž λ…ΈνŠΈ 생성"""
    print(f"[마무리 λ…ΈνŠΈ] 생성 쀑...")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    system_prompt = """You are a professional presentation coach creating closing speaker notes.

Create natural closing remarks that:
1. Thank the audience warmly
2. Briefly summarize the key message of the presentation
3. Reference the conclusion phrase naturally
4. End with an invitation for questions or next steps
5. Be 80-100 words long
6. Sound conversational and warm
7. NO stage directions or parentheses - only spoken words

Write only what the speaker would say out loud."""
    
    user_message = f"""Presentation topic: {topic}
Conclusion phrase on screen: {conclusion_phrase}

Create natural closing speaker notes that wrap up the presentation effectively."""
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": user_message
            }
        ],
        "max_tokens": 200,
        "temperature": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            notes = result['choices'][0]['message']['content'].strip()
            
            # ν•œκΈ€ 주제인 경우 λ²ˆμ—­
            if any(ord('κ°€') <= ord(char) <= ord('힣') for char in topic):
                notes = translate_content_to_korean_natural(notes)
            
            return notes
        else:
            return "였늘 λ°œν‘œλ₯Ό λ§ˆλ¬΄λ¦¬ν•˜λ©° κ°μ‚¬μ˜ 말씀을 λ“œλ¦½λ‹ˆλ‹€. 질문이 μžˆμœΌμ‹œλ©΄ νŽΈν•˜κ²Œ 말씀해 μ£Όμ„Έμš”."
    except Exception as e:
        print(f"[마무리 λ…ΈνŠΈ] 였λ₯˜: {str(e)}")
        return "였늘 λ°œν‘œλ₯Ό λ§ˆλ¬΄λ¦¬ν•˜λ©° κ°μ‚¬μ˜ 말씀을 λ“œλ¦½λ‹ˆλ‹€. 질문이 μžˆμœΌμ‹œλ©΄ νŽΈν•˜κ²Œ 말씀해 μ£Όμ„Έμš”."

def generate_conclusion_phrase(topic: str) -> str:
    """ν”„λ ˆμ  ν…Œμ΄μ…˜μ˜ 핡심을 담은 κ²°λ‘  문ꡬ 생성"""
    print(f"[κ²°λ‘  문ꡬ] 생성 쀑...")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    system_prompt = """You are a professional copywriter creating powerful closing statements for presentations.

Create a concise, impactful closing phrase that:
1. Captures the essence of the presentation topic
2. Is memorable and inspirational
3. Maximum 5-7 words
4. Uses powerful, action-oriented language
5. Leaves a lasting impression

Examples:
- "Innovation Starts Today"
- "Together We Transform"
- "Future Begins Now"
- "Excellence Through Innovation"

Output only the phrase, no explanation."""
    
    user_message = f"""Presentation topic: {topic}

Create a powerful closing phrase that encapsulates the main message."""
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": user_message
            }
        ],
        "max_tokens": 50,
        "temperature": 0.9,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            phrase = result['choices'][0]['message']['content'].strip()
            
            # ν•œκΈ€ 주제인 경우 λ²ˆμ—­
            if any(ord('κ°€') <= ord(char) <= ord('힣') for char in topic):
                phrase = translate_content_to_korean_concise(phrase)
            
            return phrase
        else:
            return "ν•¨κ»˜ λ§Œλ“œλŠ” 미래"
    except Exception as e:
        print(f"[κ²°λ‘  문ꡬ] 였λ₯˜: {str(e)}")
        return "ν•¨κ»˜ λ§Œλ“œλŠ” 미래"

def generate_slide_content(topic: str, slide_title: str, slide_context: str, uploaded_content: str = None, web_search_results: List[Dict] = None) -> Dict[str, str]:
    """각 μŠ¬λΌμ΄λ“œμ˜ ν…μŠ€νŠΈ λ‚΄μš© 생성"""
    print(f"[μŠ¬λΌμ΄λ“œ λ‚΄μš©] {slide_title} ν…μŠ€νŠΈ 생성 쀑...")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    system_prompt = """You are a professional presentation content writer specializing in creating concise, impactful slide content.

Your task is to create:
1. A compelling subtitle (max 10 words)
2. Exactly 5 bullet points with emojis
3. Each bullet point should be 8-12 words
4. Use noun-ending style (λͺ…μ‚¬ν˜• μ’…κ²°) for Korean or concise fragments for English

IMPORTANT Style Guidelines:
- End sentences with nouns or concise phrases (예: "μ „λž΅μ  ν™•λŒ€", "핡심 과제", "μ£Όμš” λͺ©ν‘œ")
- Avoid long verb endings like "μž…λ‹ˆλ‹€", "μŠ΅λ‹ˆλ‹€"
- Use short endings like "μž„", "함" or noun forms
- Start each bullet with a relevant emoji that represents the content
- Be extremely concise and impactful

Emoji Guidelines:
- Use professional emojis that match the content
- Common emojis: 
  πŸ“Š (data/analysis), 🎯 (goals/targets), πŸ’‘ (innovation/ideas), 
  πŸš€ (growth/launch), ⚑ (speed/efficiency), πŸ” (research/analysis),
  πŸ“ˆ (increase/growth), πŸ’° (finance/revenue), πŸ† (achievement/success),
  πŸ”§ (tools/solutions), 🌐 (global/network), πŸ” (security/safety),
  ⭐ (excellence/quality), 🎨 (creative/design), πŸ“± (mobile/tech),
  🀝 (partnership/collaboration), πŸ“ (location/focus), πŸŽ–οΈ (strategy),
  πŸ—οΈ (building/development), 🌱 (sustainability/growth)
- Each bullet should have a different, relevant emoji

Output format:
Subtitle: [subtitle here]
β€’ 🎯 [Point 1 - noun ending or fragment]
β€’ πŸ“Š [Point 2 - noun ending or fragment]
β€’ πŸ’‘ [Point 3 - noun ending or fragment]
β€’ πŸš€ [Point 4 - noun ending or fragment]
β€’ ⚑ [Point 5 - noun ending or fragment]"""
    
    user_message = f"""Topic: {topic}
Slide Title: {slide_title}
Context: {slide_context}"""
    
    # μ—…λ‘œλ“œλœ μ½˜ν…μΈ κ°€ 있으면 μΆ”κ°€
    if uploaded_content:
        user_message += f"\n\nReference Material:\n{uploaded_content[:1000]}"
    
    # μ›Ή 검색 κ²°κ³Όκ°€ 있으면 μΆ”κ°€
    if web_search_results:
        search_context = "\n\nWeb Search Results:\n"
        for result in web_search_results[:3]:
            search_context += f"- {result['title']}: {result['description']}\n"
        user_message += search_context
    
    user_message += "\n\nCreate compelling content for this presentation slide. Remember to use emojis and concise noun-ending style."
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": user_message
            }
        ],
        "max_tokens": 300,
        "top_p": 0.8,
        "temperature": 0.7,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            content = result['choices'][0]['message']['content'].strip()
            
            # Parse content
            lines = content.split('\n')
            subtitle = ""
            bullet_points = []
            
            for line in lines:
                if line.startswith("Subtitle:"):
                    subtitle = line.replace("Subtitle:", "").strip()
                elif line.strip().startswith("β€’"):
                    bullet_points.append(line.strip())
            
            # ν•œκΈ€λ‘œ λ²ˆμ—­μ΄ ν•„μš”ν•œ 경우
            if any(ord('κ°€') <= ord(char) <= ord('힣') for char in topic):
                subtitle = translate_content_to_korean(subtitle)
                # 뢈릿 ν¬μΈνŠΈλŠ” 이λͺ¨μ§€λ₯Ό μœ μ§€ν•˜λ©΄μ„œ λ²ˆμ—­
                translated_bullets = []
                for point in bullet_points:
                    # 이λͺ¨μ§€μ™€ ν…μŠ€νŠΈ 뢄리
                    parts = point.split(' ', 2)
                    if len(parts) >= 3 and len(parts[1]) <= 2:  # 이λͺ¨μ§€κ°€ μžˆλŠ” 경우
                        emoji = parts[1]
                        text = ' '.join(parts[2:])
                        translated_text = translate_content_to_korean_concise(text)
                        translated_bullets.append(f"β€’ {emoji} {translated_text}")
                    else:
                        translated_bullets.append(translate_content_to_korean_concise(point))
                bullet_points = translated_bullets
            
            return {
                "subtitle": subtitle,
                "bullet_points": bullet_points[:5]  # μ΅œλŒ€ 5개
            }
        else:
            return {
                "subtitle": slide_title,
                "bullet_points": ["β€’ πŸ“Œ λ‚΄μš© 생성 λΆˆκ°€"] * 5
            }
    except Exception as e:
        print(f"[μŠ¬λΌμ΄λ“œ λ‚΄μš©] 였λ₯˜: {str(e)}")
        return {
            "subtitle": slide_title,
            "bullet_points": ["β€’ ❌ λ‚΄μš© 생성 였λ₯˜"] * 5
        }

def translate_content_to_korean(text: str) -> str:
    """μ˜μ–΄ ν…μŠ€νŠΈλ₯Ό ν•œκΈ€λ‘œ λ²ˆμ—­ (일반용)"""
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": "You are a translator. Translate the given English text to Korean. Maintain professional business tone. Only return the translation without any explanation."
            },
            {
                "role": "user",
                "content": text
            }
        ],
        "max_tokens": 200,
        "top_p": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content'].strip()
        else:
            return text
    except Exception as e:
        return text

def translate_content_to_korean_concise(text: str) -> str:
    """μ˜μ–΄ ν…μŠ€νŠΈλ₯Ό κ°„κ²°ν•œ ν•œκΈ€λ‘œ λ²ˆμ—­ (λͺ…μ‚¬ν˜• μ’…κ²°)"""
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": """You are a translator specializing in concise Korean business presentations. 
Translate to Korean using noun-ending style (λͺ…μ‚¬ν˜• μ’…κ²°μ–΄λ―Έ).
End with "μž„", "함", or noun forms instead of "μž…λ‹ˆλ‹€", "μŠ΅λ‹ˆλ‹€".
Keep it extremely concise and professional.
Examples: "μ „λž΅μ  ν™•λŒ€", "핡심 과제 λ„μΆœ", "μ‹œμž₯ 선도 μ „λž΅ 수립"
Only return the translation without any explanation."""
            },
            {
                "role": "user",
                "content": text
            }
        ],
        "max_tokens": 200,
        "top_p": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content'].strip()
        else:
            return text
    except Exception as e:
        return text

def translate_content_to_korean_natural(text: str) -> str:
    """μ˜μ–΄ ν…μŠ€νŠΈλ₯Ό μžμ—°μŠ€λŸ¬μš΄ ν•œκΈ€λ‘œ λ²ˆμ—­ (λ°œν‘œ λ…ΈνŠΈμš©)"""
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": """You are a translator. Translate the given English text to natural, conversational Korean. 
Use polite spoken language suitable for presentations.
Only return the translation without any explanation."""
            },
            {
                "role": "user",
                "content": text
            }
        ],
        "max_tokens": 300,
        "top_p": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content'].strip()
        else:
            return text
    except Exception as e:
        return text

def generate_prompt_with_llm(topic: str, style_example: str = None, slide_context: str = None, uploaded_content: str = None) -> str:
    """μ£Όμ œμ™€ μŠ€νƒ€μΌ 예제λ₯Ό λ°›μ•„μ„œ LLM을 μ‚¬μš©ν•΄ 이미지 ν”„λ‘¬ν”„νŠΈλ₯Ό 생성"""
    print(f"[LLM] ν”„λ‘¬ν”„νŠΈ 생성 μ‹œμž‘: {slide_context}")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    system_prompt = """You are an expert image prompt engineer specializing in creating prompts for professional presentation slides. 

Your task is to create prompts that:
1. Are highly specific and visual, perfect for PPT backgrounds or main visuals
2. Consider the slide's purpose and maintain consistency across a presentation
3. Include style references matching the given example
4. Focus on clean, professional visuals that won't distract from text overlays
5. Ensure high contrast areas for text readability when needed
6. Maintain brand consistency and professional aesthetics

Important guidelines:
- If given a style example, adapt the topic to match that specific visual style
- Consider the slide context (e.g., "ν‘œμ§€", "ν˜„ν™© 뢄석") to create appropriate visuals
- Always output ONLY the prompt without any explanation
- Keep prompts between 50-150 words for optimal results
- Ensure the visual supports rather than overwhelms the slide content"""
    
    user_message = f"Topic: {topic}"
    if style_example:
        user_message += f"\n\nStyle reference to follow:\n{style_example}"
    if slide_context:
        user_message += f"\n\nSlide context: {slide_context}"
    if uploaded_content:
        user_message += f"\n\nAdditional context from document:\n{uploaded_content[:500]}"
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": user_message
            }
        ],
        "max_tokens": 300,
        "top_p": 0.8,
        "temperature": 0.7,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            prompt = result['choices'][0]['message']['content'].strip()
            print(f"[LLM] ν”„λ‘¬ν”„νŠΈ 생성 μ™„λ£Œ: {prompt[:50]}...")
            return prompt
        else:
            error_msg = f"ν”„λ‘¬ν”„νŠΈ 생성 μ‹€νŒ¨: {response.status_code}"
            print(f"[LLM] {error_msg}")
            return error_msg
    except Exception as e:
        error_msg = f"ν”„λ‘¬ν”„νŠΈ 생성 쀑 였λ₯˜ λ°œμƒ: {str(e)}"
        print(f"[LLM] {error_msg}")
        return error_msg

def translate_to_english(text: str) -> str:
    """ν•œκΈ€ ν…μŠ€νŠΈλ₯Ό μ˜μ–΄λ‘œ λ²ˆμ—­ (LLM μ‚¬μš©)"""
    if not any(ord('κ°€') <= ord(char) <= ord('힣') for char in text):
        return text
    
    print(f"[λ²ˆμ—­] ν•œκΈ€ 감지, μ˜μ–΄λ‘œ λ²ˆμ—­ μ‹œμž‘")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": "You are a translator. Translate the given Korean text to English. Only return the translation without any explanation."
            },
            {
                "role": "user",
                "content": text
            }
        ],
        "max_tokens": 500,
        "top_p": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            translated = result['choices'][0]['message']['content'].strip()
            print(f"[λ²ˆμ—­] μ™„λ£Œ")
            return translated
        else:
            print(f"[λ²ˆμ—­] μ‹€νŒ¨, 원본 μ‚¬μš©")
            return text
    except Exception as e:
        print(f"[λ²ˆμ—­] 였λ₯˜: {str(e)}, 원본 μ‚¬μš©")
        return text

def generate_image(prompt: str, seed: int = 10, slide_info: str = "") -> Tuple[Image.Image, str]:
    """Replicate APIλ₯Ό μ‚¬μš©ν•΄ 이미지 생성"""
    print(f"\n[이미지 생성] {slide_info}")
    print(f"[이미지 생성] ν”„λ‘¬ν”„νŠΈ: {prompt[:50]}...")
    
    try:
        english_prompt = translate_to_english(prompt)
        
        if not REPLICATE_API_TOKEN:
            error_msg = "RAPI_TOKEN ν™˜κ²½λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€."
            print(f"[이미지 생성] 였λ₯˜: {error_msg}")
            return None, error_msg
        
        print(f"[이미지 생성] Replicate API 호좜 쀑...")
        client = replicate.Client(api_token=REPLICATE_API_TOKEN)
        
        input_params = {
            "seed": seed,
            "prompt": english_prompt,
            "speed_mode": "Extra Juiced πŸš€ (even more speed)",
            "output_quality": 100
        }
        
        start_time = time.time()
        output = client.run(
            "prunaai/hidream-l1-fast:17c237d753218fed0ed477cb553902b6b75735f48c128537ab829096ef3d3645",
            input=input_params
        )
        
        elapsed = time.time() - start_time
        print(f"[이미지 생성] API 응닡 λ°›μŒ ({elapsed:.1f}초)")
        
        if output:
            if isinstance(output, str) and output.startswith('http'):
                print(f"[이미지 생성] URLμ—μ„œ 이미지 λ‹€μš΄λ‘œλ“œ 쀑...")
                response = requests.get(output, timeout=30)
                img = Image.open(BytesIO(response.content))
                print(f"[이미지 생성] μ™„λ£Œ!")
                return img, english_prompt
            else:
                print(f"[이미지 생성] λ°”μ΄λ„ˆλ¦¬ 데이터 처리 쀑...")
                img = Image.open(BytesIO(output.read()))
                print(f"[이미지 생성] μ™„λ£Œ!")
                return img, english_prompt
        else:
            error_msg = "이미지 생성 μ‹€νŒ¨ - 빈 응닡"
            print(f"[이미지 생성] {error_msg}")
            return None, error_msg
            
    except Exception as e:
        error_msg = f"였λ₯˜: {str(e)}"
        print(f"[이미지 생성] {error_msg}")
        print(f"[이미지 생성] 상세 였λ₯˜:\n{traceback.format_exc()}")
        return None, error_msg

def create_slide_preview_html(slide_data: Dict) -> str:
    """16:9 λΉ„μœ¨μ˜ μŠ¬λΌμ΄λ“œ 프리뷰 HTML 생성 (λ‘₯κ·Ό λͺ¨μ„œλ¦¬μ™€ μž…μ²΄κ°)"""
    
    # 이미지λ₯Ό base64둜 인코딩
    img_base64 = ""
    if slide_data.get("image"):
        buffered = BytesIO()
        slide_data["image"].save(buffered, format="PNG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode()
    
    # ν…μŠ€νŠΈ λ‚΄μš© κ°€μ Έμ˜€κΈ°
    subtitle = slide_data.get("subtitle", "")
    bullet_points = slide_data.get("bullet_points", [])
    
    # HTML 생성
    html = f"""
    <div class="slide-container" style="
        width: 100%;
        max-width: 1200px;
        margin: 20px auto;
        background: white;
        border-radius: 12px;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        overflow: hidden;
    ">
        <div class="slide-header" style="
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 15px 30px;
            font-size: 18px;
            font-weight: bold;
        ">
            μŠ¬λΌμ΄λ“œ {slide_data.get('slide_number', '')}: {slide_data.get('title', '')}
        </div>
        
        <div class="slide-content" style="
            display: flex;
            height: 0;
            padding-bottom: 56.25%; /* 16:9 λΉ„μœ¨ */
            position: relative;
            background: #fafbfc;
        ">
            <div class="slide-inner" style="
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                display: flex;
                padding: 20px;
                gap: 20px;
            ">
    """
    
    # ν‘œμ§€μ™€ λ§ˆμ§€λ§‰ μŠ¬λΌμ΄λ“œλŠ” 전체 ν™”λ©΄ 이미지
    if slide_data.get('title') in ['ν‘œμ§€', 'Thank You']:
        html += f"""
                <!-- 전체 ν™”λ©΄ 이미지 -->
                <div style="
                    width: 100%;
                    height: 100%;
                    position: relative;
                    background: #e9ecef;
                    border-radius: 12px;
                    overflow: hidden;
                ">
        """
        
        if img_base64:
            html += f"""
                    <img src="data:image/png;base64,{img_base64}" style="
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    " alt="Slide Image">
                    <div style="
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                        text-align: center;
                        background: rgba(255, 255, 255, 0.9);
                        padding: 30px 60px;
                        border-radius: 20px;
                        box-shadow: 0 10px 40px rgba(0,0,0,0.3);
                        backdrop-filter: blur(10px);
                    ">
            """
            
            if slide_data.get('title') == 'ν‘œμ§€':
                html += f"""
                        <h1 style="font-size: 48px; margin-bottom: 10px; color: #000000; font-weight: 700;">{slide_data.get('topic', '')}</h1>
                        <h2 style="font-size: 24px; margin-top: 0; color: #212529; font-weight: 400;">{subtitle}</h2>
                """
            else:  # Thank You
                html += f"""
                        <h1 style="font-size: 42px; color: #000000; font-weight: 700; line-height: 1.2;">{subtitle}</h1>
                """
            
            html += """
                    </div>
            """
        
        html += """
                </div>
        """
    else:
        # 일반 μŠ¬λΌμ΄λ“œ λ ˆμ΄μ•„μ›ƒ
        html += f"""
                <!-- ν…μŠ€νŠΈ μ˜μ—­ (쒌츑) -->
                <div class="text-area" style="
                    flex: 1;
                    padding: 30px;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    background: rgba(255, 255, 255, 0.95);
                    border-radius: 12px;
                    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
                ">
                    <h2 style="
                        color: #212529;
                        font-size: 28px;
                        margin-bottom: 30px;
                        font-weight: 600;
                    ">{subtitle}</h2>
                    
                    <ul style="
                        list-style: none;
                        padding: 0;
                        margin: 0;
                    ">
        """
        
        for point in bullet_points:
            clean_point = point.replace('β€’', '').strip()
            html += f"""
                        <li style="
                            margin-bottom: 16px;
                            padding-left: 28px;
                            position: relative;
                            color: #495057;
                            font-size: 16px;
                            line-height: 1.6;
                        ">
                            <span style="
                                position: absolute;
                                left: 0;
                                color: #007bff;
                                font-size: 18px;
                            ">β€’</span>
                            {clean_point}
                        </li>
            """
        
        html += f"""
                    </ul>
                </div>
                
                <!-- 이미지 μ˜μ—­ (우츑) -->
                <div class="image-area" style="
                    flex: 1;
                    background: rgba(248, 249, 250, 0.9);
                    border-radius: 12px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
                ">
        """
        
        if img_base64:
            html += f"""
                    <img src="data:image/png;base64,{img_base64}" style="
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: contain;
                        border-radius: 8px;
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                    " alt="Slide Image">
            """
        else:
            html += """
                    <div style="
                        color: #6c757d;
                        text-align: center;
                    ">
                        <div style="font-size: 48px;">πŸ–ΌοΈ</div>
                        <p>이미지 생성 쀑...</p>
                    </div>
            """
        
        html += """
                </div>
        """
    
    html += """
            </div>
        </div>
    </div>
    """
    
    return html

def create_final_pptx_with_edits(results: List[Dict], topic: str, template_name: str, 
                                 theme_name: str, edited_data: Dict = None) -> str:
    """νŽΈμ§‘λœ λ‚΄μš©μ„ λ°˜μ˜ν•œ μ΅œμ’… PPTX 파일 생성"""
    print("[PPTX] νŽΈμ§‘λœ λ‚΄μš©μœΌλ‘œ μ΅œμ’… 파일 생성 쀑...")
    
    # νŽΈμ§‘λœ 데이터가 있으면 결과에 반영
    if edited_data:
        for slide_index, edits in edited_data.items():
            if slide_index < len(results):
                results[slide_index]["slide_data"].update(edits)
    
    # κΈ°μ‘΄ create_pptx_file ν•¨μˆ˜ 호좜
    return create_pptx_file(results, topic, template_name, theme_name)

def create_pptx_file(results: List[Dict], topic: str, template_name: str, theme_name: str = "λ―Έλ‹ˆλ©€ 라이트") -> str:
    """μƒμ„±λœ κ²°κ³Όλ₯Ό PPTX 파일둜 λ³€ν™˜ (λ°œν‘œμž λ…ΈνŠΈ 포함)"""
    print(f"[PPTX] 파일 생성 μ‹œμž‘... ν…Œλ§ˆ: {theme_name}")
    
    # ν”„λ ˆμ  ν…Œμ΄μ…˜ 생성 (16:9 λΉ„μœ¨)
    prs = Presentation()
    prs.slide_width = Inches(16)
    prs.slide_height = Inches(9)
    
    # μ„ νƒλœ ν…Œλ§ˆ κ°€μ Έμ˜€κΈ°
    theme = DESIGN_THEMES.get(theme_name, DESIGN_THEMES["λ―Έλ‹ˆλ©€ 라이트"])
    
    # 각 κ²°κ³Ό μŠ¬λΌμ΄λ“œ μΆ”κ°€
    for i, result in enumerate(results):
        if not result.get("success", False):
            continue
            
        slide_data = result.get("slide_data", {})
        
        # 빈 λ ˆμ΄μ•„μ›ƒ μ‚¬μš© (제λͺ© ν”Œλ ˆμ΄μŠ€ν™€λ” μ—†λŠ” μ™„μ „ν•œ 빈 μŠ¬λΌμ΄λ“œ)
        blank_layout = prs.slide_layouts[6]  # μ™„μ „νžˆ 빈 λ ˆμ΄μ•„μ›ƒ
        slide = prs.slides.add_slide(blank_layout)
        
        # ν‘œμ§€ μŠ¬λΌμ΄λ“œ
        if slide_data.get('title') == 'ν‘œμ§€':
            # λ°°κ²½ 이미지 μΆ”κ°€
            if slide_data.get('image'):
                try:
                    img_buffer = BytesIO()
                    slide_data['image'].save(img_buffer, format='PNG')
                    img_buffer.seek(0)
                    
                    # 전체 ν™”λ©΄ λ°°κ²½ 이미지
                    pic = slide.shapes.add_picture(
                        img_buffer, 
                        0, 0,
                        width=prs.slide_width, 
                        height=prs.slide_height
                    )
                    # 맨 λ’€λ‘œ 보내기
                    slide.shapes._spTree.remove(pic._element)
                    slide.shapes._spTree.insert(2, pic._element)
                except Exception as e:
                    print(f"[PPTX] ν‘œμ§€ 이미지 μΆ”κ°€ μ‹€νŒ¨: {str(e)}")
            
            # 제λͺ© λ°°κ²½ λ°•μŠ€ (반투λͺ… - 더 밝고 투λͺ…ν•˜κ²Œ)
            title_bg = slide.shapes.add_shape(
                MSO_SHAPE.ROUNDED_RECTANGLE,
                Inches(2), Inches(2.8),
                Inches(12), Inches(3.2)
            )
            title_bg.fill.solid()
            title_bg.fill.fore_color.rgb = RGBColor(255, 255, 255)  # 흰색 λ°°κ²½
            title_bg.fill.transparency = 0.2  # 20% 투λͺ…도 (80% 뢈투λͺ…)
            title_bg.line.fill.background()
            
            # 그림자 효과 μΆ”κ°€ (더 κ°•ν•˜κ²Œ)
            shadow = title_bg.shadow
            shadow.visible = True
            shadow.distance = Pt(8)
            shadow.size = 120
            shadow.blur_radius = Pt(15)
            shadow.transparency = 0.3
            shadow.angle = 45
            
            # 제λͺ© ν…μŠ€νŠΈ μΆ”κ°€
            title_box = slide.shapes.add_textbox(
                Inches(2), Inches(3.2), 
                Inches(12), Inches(1.5)
            )
            title_frame = title_box.text_frame
            title_frame.text = topic
            title_para = title_frame.paragraphs[0]
            title_para.font.size = Pt(48)
            title_para.font.bold = True
            title_para.font.color.rgb = RGBColor(0, 0, 0)  # μ™„μ „ν•œ 검정색
            title_para.alignment = PP_ALIGN.CENTER
            
            # λΆ€μ œλͺ© μΆ”κ°€ (제λͺ©κ³Ό κ°€κΉŒμ΄)
            subtitle_box = slide.shapes.add_textbox(
                Inches(2), Inches(4.3), 
                Inches(12), Inches(1.0)
            )
            subtitle_frame = subtitle_box.text_frame
            subtitle_frame.text = slide_data.get('subtitle', f'{template_name} - AI ν”„λ ˆμ  ν…Œμ΄μ…˜')
            subtitle_para = subtitle_frame.paragraphs[0]
            subtitle_para.font.size = Pt(28)  # 24μ—μ„œ 28둜 증가
            subtitle_para.font.color.rgb = RGBColor(33, 37, 41)  # μ§„ν•œ νšŒμƒ‰
            subtitle_para.alignment = PP_ALIGN.CENTER
            
        # Thank You μŠ¬λΌμ΄λ“œ
        elif slide_data.get('title') == 'Thank You':
            # λ°°κ²½ 이미지 μΆ”κ°€
            if slide_data.get('image'):
                try:
                    img_buffer = BytesIO()
                    slide_data['image'].save(img_buffer, format='PNG')
                    img_buffer.seek(0)
                    
                    # 전체 ν™”λ©΄ λ°°κ²½ 이미지
                    pic = slide.shapes.add_picture(
                        img_buffer, 
                        0, 0,
                        width=prs.slide_width, 
                        height=prs.slide_height
                    )
                    # 맨 λ’€λ‘œ 보내기
                    slide.shapes._spTree.remove(pic._element)
                    slide.shapes._spTree.insert(2, pic._element)
                except Exception as e:
                    print(f"[PPTX] Thank You 이미지 μΆ”κ°€ μ‹€νŒ¨: {str(e)}")
            
            # Thank You λ°°κ²½ λ°•μŠ€ (반투λͺ… - 더 밝고 투λͺ…ν•˜κ²Œ)
            thanks_bg = slide.shapes.add_shape(
                MSO_SHAPE.ROUNDED_RECTANGLE,
                Inches(2), Inches(3.5),
                Inches(12), Inches(2.5)
            )
            thanks_bg.fill.solid()
            thanks_bg.fill.fore_color.rgb = RGBColor(255, 255, 255)  # 흰색 λ°°κ²½
            thanks_bg.fill.transparency = 0.2  # 20% 투λͺ…도
            thanks_bg.line.fill.background()
            
            # 그림자 효과 μΆ”κ°€ (더 κ°•ν•˜κ²Œ)
            shadow = thanks_bg.shadow
            shadow.visible = True
            shadow.distance = Pt(8)
            shadow.size = 120
            shadow.blur_radius = Pt(15)
            shadow.transparency = 0.3
            shadow.angle = 45
            
            # Thank You ν…μŠ€νŠΈ (κ²°λ‘  문ꡬ)
            thanks_box = slide.shapes.add_textbox(
                Inches(2), Inches(4), 
                Inches(12), Inches(1.5)
            )
            thanks_frame = thanks_box.text_frame
            thanks_frame.text = slide_data.get('subtitle', 'Thank You')  # κ²°λ‘  문ꡬ μ‚¬μš©
            thanks_para = thanks_frame.paragraphs[0]
            thanks_para.font.size = Pt(42)  # 크기λ₯Ό 쑰금 μ€„μž„
            thanks_para.font.bold = True
            thanks_para.font.color.rgb = RGBColor(0, 0, 0)  # μ™„μ „ν•œ 검정색
            thanks_para.alignment = PP_ALIGN.CENTER
            
        # 일반 μŠ¬λΌμ΄λ“œ
        else:
            # 배경색 μ„€μ •
            background = slide.background
            fill = background.fill
            fill.solid()
            fill.fore_color.rgb = theme["background"]
            
            # μŠ¬λΌμ΄λ“œ 제λͺ© λ°°κ²½ λ°•μŠ€ (λ‘₯κ·Ό λͺ¨μ„œλ¦¬ 효과)
            title_box_bg = slide.shapes.add_shape(
                MSO_SHAPE.ROUNDED_RECTANGLE,
                Inches(0.3), Inches(0.2),
                Inches(15.4), Inches(1.0)
            )
            title_box_bg.fill.solid()
            title_box_bg.fill.fore_color.rgb = theme["box_fill"]
            title_box_bg.fill.transparency = 1 - theme["box_opacity"]
            
            # 그림자 효과
            if theme["shadow"]:
                shadow = title_box_bg.shadow
                shadow.visible = True
                shadow.distance = Pt(4)
                shadow.size = 100
                shadow.blur_radius = Pt(8)
                shadow.transparency = 0.75
                shadow.angle = 45
            
            title_box_bg.line.fill.background()  # ν…Œλ‘λ¦¬ μ—†μŒ
            
            # μŠ¬λΌμ΄λ“œ 제λͺ© μΆ”κ°€
            title_box = slide.shapes.add_textbox(
                Inches(0.5), Inches(0.3), 
                Inches(15), Inches(0.8)
            )
            title_frame = title_box.text_frame
            title_frame.text = f"{slide_data.get('title', '')}"
            title_para = title_frame.paragraphs[0]
            title_para.font.size = Pt(28)
            title_para.font.bold = True
            title_para.font.color.rgb = theme["title_color"]
            
            # 쒌츑 ν…μŠ€νŠΈ μ˜μ—­ λ°°κ²½ λ°•μŠ€
            text_box_bg = slide.shapes.add_shape(
                MSO_SHAPE.ROUNDED_RECTANGLE,
                Inches(0.3), Inches(1.4),
                Inches(7.8), Inches(6.8)
            )
            text_box_bg.fill.solid()
            text_box_bg.fill.fore_color.rgb = theme["box_fill"]
            text_box_bg.fill.transparency = 1 - theme["box_opacity"]
            
            if theme["shadow"]:
                shadow = text_box_bg.shadow
                shadow.visible = True
                shadow.distance = Pt(5)
                shadow.size = 100
                shadow.blur_radius = Pt(10)
                shadow.transparency = 0.7
                shadow.angle = 45
            
            text_box_bg.line.fill.background()
            
            # 쒌츑 ν…μŠ€νŠΈ μ˜μ—­
            text_box = slide.shapes.add_textbox(
                Inches(0.8), Inches(1.8),
                Inches(7.0), Inches(6.0)
            )
            text_frame = text_box.text_frame
            text_frame.word_wrap = True
            
            # μ†Œμ œλͺ© μΆ”κ°€
            subtitle_para = text_frame.paragraphs[0]
            subtitle_para.text = slide_data.get('subtitle', '')
            subtitle_para.font.size = Pt(20)
            subtitle_para.font.bold = True
            subtitle_para.font.color.rgb = theme["subtitle_color"]
            subtitle_para.space_after = Pt(20)
            
            # 뢈릿 포인트 μΆ”κ°€
            bullet_points = slide_data.get('bullet_points', [])
            for point in bullet_points:
                p = text_frame.add_paragraph()
                # β€’ μ œκ±°ν•˜κ³  ν…μŠ€νŠΈλ§Œ μΆ”κ°€ (이λͺ¨μ§€λŠ” μœ μ§€)
                clean_text = point.replace('β€’', '').strip()
                p.text = clean_text
                p.font.size = Pt(16)
                p.font.color.rgb = theme["text_color"]
                # 뢈릿 없이 λ“€μ—¬μ“°κΈ°λ§Œ
                p.level = 0
                p.space_after = Pt(12)
                p.line_spacing = 1.5
                # μ™Όμͺ½ μ—¬λ°± μ„€μ •
                p.left_indent = Pt(0)
                
                # 뢈릿 색상
                p.font.color.rgb = theme["text_color"]
            
            # 우츑 이미지 μ˜μ—­ λ°°κ²½ λ°•μŠ€
            img_box_bg = slide.shapes.add_shape(
                MSO_SHAPE.ROUNDED_RECTANGLE,
                Inches(8.3), Inches(1.4),
                Inches(7.4), Inches(6.8)
            )
            img_box_bg.fill.solid()
            img_box_bg.fill.fore_color.rgb = RGBColor(248, 249, 250)
            img_box_bg.fill.transparency = 0.1
            
            if theme["shadow"]:
                shadow = img_box_bg.shadow
                shadow.visible = True
                shadow.distance = Pt(5)
                shadow.size = 100
                shadow.blur_radius = Pt(10)
                shadow.transparency = 0.7
                shadow.angle = 45
            
            img_box_bg.line.fill.background()
            
            # 우츑 이미지 μΆ”κ°€
            if slide_data.get('image'):
                try:
                    img_buffer = BytesIO()
                    slide_data['image'].save(img_buffer, format='PNG')
                    img_buffer.seek(0)
                    
                    pic = slide.shapes.add_picture(
                        img_buffer, 
                        Inches(8.5), Inches(1.6),
                        width=Inches(6.8), height=Inches(6.4)
                    )
                    
                    # 이미지 ν…Œλ‘λ¦¬ 제거
                    pic.line.fill.background()
                    
                except Exception as e:
                    print(f"[PPTX] 이미지 μΆ”κ°€ μ‹€νŒ¨: {str(e)}")
            
            # νŽ˜μ΄μ§€ 번호 μΆ”κ°€
            page_num = slide.shapes.add_textbox(
                Inches(15), Inches(8.5),
                Inches(1), Inches(0.5)
            )
            page_frame = page_num.text_frame
            page_frame.text = str(i + 1)
            page_para = page_frame.paragraphs[0]
            page_para.font.size = Pt(12)
            page_para.font.color.rgb = theme["text_color"]
            page_para.alignment = PP_ALIGN.RIGHT
        
        # λ°œν‘œμž λ…ΈνŠΈ μΆ”κ°€
        notes_slide = slide.notes_slide
        notes_slide.notes_text_frame.text = slide_data.get('speaker_notes', '')
    
    # 파일 μ €μž₯
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"presentation_{timestamp}.pptx"
    filepath = os.path.join("/tmp", filename)
    prs.save(filepath)
    
    print(f"[PPTX] 파일 생성 μ™„λ£Œ: {filename}")
    return filepath

def generate_dynamic_slides(topic: str, template: Dict, slide_count: int) -> List[Dict]:
    """μ„ νƒλœ μŠ¬λΌμ΄λ“œ μˆ˜μ— 따라 λ™μ μœΌλ‘œ μŠ¬λΌμ΄λ“œ ꡬ성"""
    core_slides = template.get("core_slides", [])
    optional_slides = template.get("optional_slides", [])
    
    # ν‘œμ§€μ™€ Thank Youλ₯Ό μ œμ™Έν•œ λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ 수
    content_slide_count = slide_count
    
    # μ½”μ–΄ μŠ¬λΌμ΄λ“œκ°€ μš”μ²­λœ μˆ˜λ³΄λ‹€ 많으면 μ‘°μ •
    if len(core_slides) > content_slide_count:
        selected_slides = core_slides[:content_slide_count]
    else:
        # μ½”μ–΄ μŠ¬λΌμ΄λ“œ + μ˜΅μ…”λ„ μŠ¬λΌμ΄λ“œμ—μ„œ 선택
        selected_slides = core_slides.copy()
        remaining = content_slide_count - len(core_slides)
        
        if remaining > 0 and optional_slides:
            # μ˜΅μ…”λ„ μŠ¬λΌμ΄λ“œμ—μ„œ μΆ”κ°€ 선택
            additional = optional_slides[:remaining]
            selected_slides.extend(additional)
    
    # ν‘œμ§€ μΆ”κ°€ (맨 μ•ž)
    slides = [{"title": "ν‘œμ§€", "style": "Title Slide (Hero)", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ ν‘œμ§€"}]
    
    # λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ μΆ”κ°€
    slides.extend(selected_slides)
    
    # Thank You μŠ¬λΌμ΄λ“œ μΆ”κ°€ (맨 λ’€)
    slides.append({"title": "Thank You", "style": "Thank You Slide", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ λ§ˆλ¬΄λ¦¬μ™€ 핡심 λ©”μ‹œμ§€"})
    
    return slides

def create_editable_slide_interface(slide_data: Dict, slide_index: int, topic: str) -> str:
    """νŽΈμ§‘ κ°€λŠ₯ν•œ μŠ¬λΌμ΄λ“œ μΈν„°νŽ˜μ΄μŠ€ 생성"""
    
    # 이미지λ₯Ό base64둜 인코딩
    img_base64 = ""
    if slide_data.get("image"):
        buffered = BytesIO()
        slide_data["image"].save(buffered, format="PNG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode()
    
    # ν…μŠ€νŠΈ λ‚΄μš© κ°€μ Έμ˜€κΈ°
    subtitle = slide_data.get("subtitle", "")
    bullet_points = slide_data.get("bullet_points", [])
    
    # ν‘œμ§€μ™€ Thank YouλŠ” νŽΈμ§‘ λΆˆκ°€
    if slide_data.get('title') in ['ν‘œμ§€', 'Thank You']:
        return create_slide_preview_html(slide_data)
    
    # HTML 생성
    html = f"""
    <div class="slide-container" id="slide_container_{slide_index}" style="
        width: 100%;
        max-width: 1200px;
        margin: 20px auto;
        background: white;
        border-radius: 12px;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        overflow: hidden;
    ">
        <div class="slide-header" style="
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 15px 30px;
            font-size: 18px;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
        ">
            <span>μŠ¬λΌμ΄λ“œ {slide_data.get('slide_number', '')}: {slide_data.get('title', '')}</span>
            <button id="edit_btn_{slide_index}" style="
                background: #3498db;
                color: white;
                border: none;
                padding: 5px 15px;
                border-radius: 5px;
                cursor: pointer;
                font-size: 14px;
            ">✏️ νŽΈμ§‘</button>
        </div>
        
        <div class="slide-content" style="
            display: flex;
            min-height: 400px;
            background: #fafbfc;
            position: relative;
        ">
            <div class="slide-inner" style="
                width: 100%;
                display: flex;
                padding: 20px;
                gap: 20px;
            ">
                <!-- ν…μŠ€νŠΈ μ˜μ—­ (쒌츑) -->
                <div class="text-area" style="
                    flex: 1;
                    padding: 30px;
                    background: rgba(255, 255, 255, 0.95);
                    border-radius: 12px;
                    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
                ">
                    <div id="view_mode_{slide_index}" style="display: block;">
                        <h2 style="
                            color: #212529;
                            font-size: 28px;
                            margin-bottom: 30px;
                            font-weight: 600;
                        ">{subtitle}</h2>
                        
                        <ul style="
                            list-style: none;
                            padding: 0;
                            margin: 0;
                        ">
    """
    
    for point in bullet_points:
        clean_point = point.replace('β€’', '').strip()
        html += f"""
                            <li style="
                                margin-bottom: 16px;
                                padding-left: 28px;
                                position: relative;
                                color: #495057;
                                font-size: 16px;
                                line-height: 1.6;
                            ">
                                <span style="
                                    position: absolute;
                                    left: 0;
                                    color: #007bff;
                                    font-size: 18px;
                                ">β€’</span>
                                {clean_point}
                            </li>
        """
    
    html += f"""
                        </ul>
                    </div>
                    
                    <!-- νŽΈμ§‘ λͺ¨λ“œ -->
                    <div id="edit_mode_{slide_index}" style="display: none;">
                        <input type="text" id="subtitle_{slide_index}" value="{subtitle}" style="
                            width: 100%;
                            font-size: 24px;
                            font-weight: 600;
                            margin-bottom: 20px;
                            padding: 10px;
                            border: 2px solid #e9ecef;
                            border-radius: 5px;
                        " placeholder="μ†Œμ œλͺ© μž…λ ₯">
                        
                        <div style="margin-bottom: 20px;">
    """
    
    for i, point in enumerate(bullet_points):
        # 이λͺ¨μ§€λ₯Ό ν¬ν•¨ν•œ 전체 ν…μŠ€νŠΈ (β€’ 제거)
        clean_point = point.replace('β€’', '').strip()
        html += f"""
                            <input type="text" id="bullet_{slide_index}_{i}" value="{clean_point}" style="
                                width: 100%;
                                margin-bottom: 10px;
                                padding: 8px 8px 8px 25px;
                                border: 1px solid #e9ecef;
                                border-radius: 5px;
                                font-size: 16px;
                            " placeholder="예: 🎯 포인트 {i+1}">
        """
    
    html += f"""
                        </div>
                        
                        <div style="
                            background: #f3e5f5;
                            border-radius: 8px;
                            padding: 15px;
                            margin-top: 20px;
                        ">
                            <h4 style="margin-bottom: 10px; color: #7b1fa2;">πŸ€– AI둜 λ‹€μ‹œ μž‘μ„±ν•˜κΈ°</h4>
                            <textarea id="instruction_{slide_index}" style="
                                width: 100%;
                                height: 60px;
                                padding: 10px;
                                border: 2px solid #e1bee7;
                                border-radius: 5px;
                                font-size: 14px;
                                resize: vertical;
                                background: white;
                            " placeholder="예: 더 μ „λ¬Έμ μœΌλ‘œ, μˆ«μžμ™€ 톡계 포함, 더 κ°„λ‹¨ν•˜κ²Œ, μž„νŒ©νŠΈ 있게"></textarea>
                            <button id="ai_btn_{slide_index}" style="
                                background: #9b59b6;
                                color: white;
                                border: none;
                                padding: 8px 20px;
                                border-radius: 5px;
                                cursor: pointer;
                                margin-top: 10px;
                                font-size: 14px;
                            ">πŸ”„ AI μƒˆλ‘œ μž‘μ„±</button>
                        </div>
                        
                        <div style="margin-top: 20px;">
                            <button id="save_btn_{slide_index}" style="
                                background: #27ae60;
                                color: white;
                                border: none;
                                padding: 8px 20px;
                                border-radius: 5px;
                                cursor: pointer;
                                margin-right: 10px;
                            ">μ €μž₯</button>
                            <button id="cancel_btn_{slide_index}" style="
                                background: #95a5a6;
                                color: white;
                                border: none;
                                padding: 8px 20px;
                                border-radius: 5px;
                                cursor: pointer;
                            ">μ·¨μ†Œ</button>
                        </div>
                    </div>
                </div>
                
                <!-- 이미지 μ˜μ—­ (우츑) -->
                <div class="image-area" style="
                    flex: 1;
                    background: rgba(248, 249, 250, 0.9);
                    border-radius: 12px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 20px;
                    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
                ">
    """
    
    if img_base64:
        html += f"""
                    <img src="data:image/png;base64,{img_base64}" style="
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: contain;
                        border-radius: 8px;
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                    " alt="Slide Image">
        """
    
    html += f"""
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // μ¦‰μ‹œ μ‹€ν–‰ ν•¨μˆ˜λ‘œ μŠ€μ½”ν”„ 뢄리
        (function() {{
            const slideIndex = {slide_index};
            
            // DOM이 μ€€λΉ„λ˜λ©΄ μ‹€ν–‰
            setTimeout(function() {{
                const viewMode = document.getElementById('view_mode_' + slideIndex);
                const editMode = document.getElementById('edit_mode_' + slideIndex);
                const editBtn = document.getElementById('edit_btn_' + slideIndex);
                const saveBtn = document.getElementById('save_btn_' + slideIndex);
                const cancelBtn = document.getElementById('cancel_btn_' + slideIndex);
                const aiBtn = document.getElementById('ai_btn_' + slideIndex);
                
                if (editBtn) {{
                    editBtn.onclick = function(e) {{
                        e.preventDefault();
                        e.stopPropagation();
                        viewMode.style.display = 'none';
                        editMode.style.display = 'block';
                        return false;
                    }};
                }}
                
                if (saveBtn) {{
                    saveBtn.onclick = function(e) {{
                        e.preventDefault();
                        e.stopPropagation();
                        const subtitle = document.getElementById('subtitle_' + slideIndex).value;
                        const bullets = [];
                        for (let i = 0; i < 5; i++) {{
                            const bullet = document.getElementById('bullet_' + slideIndex + '_' + i);
                            if (bullet && bullet.value) {{
                                let bulletText = bullet.value.trim();
                                if (!bulletText.startsWith('β€’')) {{
                                    bulletText = 'β€’ ' + bulletText;
                                }}
                                bullets.push(bulletText);
                            }}
                        }}
                        
                        window.savedSlideData = window.savedSlideData || {{}};
                        window.savedSlideData[slideIndex] = {{
                            subtitle: subtitle,
                            bullet_points: bullets
                        }};
                        
                        // λ·° λͺ¨λ“œ μ—…λ°μ΄νŠΈ
                        const h2 = viewMode.querySelector('h2');
                        if (h2) h2.textContent = subtitle;
                        
                        const ul = viewMode.querySelector('ul');
                        if (ul) {{
                            ul.innerHTML = bullets.map(b => `
                                <li style="margin-bottom: 16px; padding-left: 28px; position: relative; color: #495057; font-size: 16px; line-height: 1.6;">
                                    <span style="position: absolute; left: 0; color: #007bff; font-size: 18px;">β€’</span>
                                    ${{b.replace('β€’', '').trim()}}
                                </li>
                            `).join('');
                        }}
                        
                        viewMode.style.display = 'block';
                        editMode.style.display = 'none';
                        return false;
                    }};
                }}
                
                if (cancelBtn) {{
                    cancelBtn.onclick = function(e) {{
                        e.preventDefault();
                        e.stopPropagation();
                        viewMode.style.display = 'block';
                        editMode.style.display = 'none';
                        return false;
                    }};
                }}
                
                if (aiBtn) {{
                    aiBtn.onclick = function(e) {{
                        e.preventDefault();
                        e.stopPropagation();
                        const instruction = document.getElementById('instruction_' + slideIndex).value;
                        if (instruction) {{
                            window.aiRegenerateRequest = {{
                                slideIndex: slideIndex,
                                instruction: instruction,
                                topic: "{topic}"
                            }};
                            alert('AI μž¬μƒμ„±μ΄ μš”μ²­λ˜μ—ˆμŠ΅λ‹ˆλ‹€. μ‹€μ œ κ΅¬ν˜„μ—μ„œλŠ” μ„œλ²„μ™€ ν†΅μ‹ ν•©λ‹ˆλ‹€.');
                        }}
                        return false;
                    }};
                }}
            }}, 100);
        }})();
    </script>
    """
    
    return html

def generate_ppt_with_content(topic: str, template_name: str, custom_slides: List[Dict], 
                             slide_count: int, seed: int, uploaded_file, 
                             use_web_search: bool, theme_name: str = "λ―Έλ‹ˆλ©€ 라이트", 
                             progress=gr.Progress()):
    """PPT 이미지와 ν…μŠ€νŠΈ λ‚΄μš©μ„ ν•¨κ»˜ 생성 (λ°œν‘œμž λ…ΈνŠΈ 포함)"""
    results = []
    preview_html = ""
    
    # μ—…λ‘œλ“œλœ 파일 λ‚΄μš© 읽기
    uploaded_content = ""
    if uploaded_file is not None:
        try:
            uploaded_content = read_uploaded_file(uploaded_file.name)
            print(f"[파일 μ—…λ‘œλ“œ] λ‚΄μš© 길이: {len(uploaded_content)}자")
        except Exception as e:
            print(f"[파일 μ—…λ‘œλ“œ] 였λ₯˜: {str(e)}")
            uploaded_content = ""
    
    # ν…œν”Œλ¦Ώ 선택 및 μŠ¬λΌμ΄λ“œ ꡬ성
    if template_name == "μ‚¬μš©μž μ •μ˜" and custom_slides:
        slides = [{"title": "ν‘œμ§€", "style": "Title Slide (Hero)", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ ν‘œμ§€"}]
        slides.extend(custom_slides)
        slides.append({"title": "Thank You", "style": "Thank You Slide", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ λ§ˆλ¬΄λ¦¬μ™€ 핡심 λ©”μ‹œμ§€"})
    else:
        template = PPT_TEMPLATES[template_name]
        slides = generate_dynamic_slides(topic, template, slide_count)
    
    if not slides:
        yield "", "μŠ¬λΌμ΄λ“œκ°€ μ •μ˜λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.", None
        return
    
    total_slides = len(slides)
    print(f"\n[PPT 생성] μ‹œμž‘ - 총 {total_slides}개 μŠ¬λΌμ΄λ“œ (ν‘œμ§€ + λ³Έλ¬Έ {slide_count} + Thank You)")
    print(f"[PPT 생성] 주제: {topic}")
    print(f"[PPT 생성] ν…œν”Œλ¦Ώ: {template_name}")
    print(f"[PPT 생성] λ””μžμΈ ν…Œλ§ˆ: {theme_name}")
    print(f"[PPT 생성] μ›Ή 검색: {'μ‚¬μš©' if use_web_search else 'λ―Έμ‚¬μš©'}")
    
    # μ›Ή 검색 μ‹€ν–‰ (μ„ νƒλœ 경우)
    web_search_results = []
    if use_web_search and BRAVE_API_TOKEN:
        progress(0.05, "μ›Ή 검색 쀑...")
        web_search_results = brave_search(topic)
    
    # CSS μŠ€νƒ€μΌ μΆ”κ°€
    preview_html = """
    <style>
        .slides-container {
            width: 100%;
            max-width: 1400px;
            margin: 0 auto;
        }
    </style>
    <div class="slides-container">
    """
    
    # 각 μŠ¬λΌμ΄λ“œ 순차 처리
    for i, slide in enumerate(slides):
        progress((i + 1) / (total_slides + 1), f"μŠ¬λΌμ΄λ“œ {i+1}/{total_slides} 처리 쀑...")
        
        slide_info = f"μŠ¬λΌμ΄λ“œ {i+1}: {slide['title']}"
        
        # ν…μŠ€νŠΈ λ‚΄μš© 생성
        slide_context = f"{slide['title']} - {slide.get('prompt_hint', '')}"
        
        # Thank You μŠ¬λΌμ΄λ“œλŠ” κ²°λ‘  문ꡬ 생성
        if slide['title'] == 'Thank You':
            conclusion_phrase = generate_conclusion_phrase(topic)
            content = {
                "subtitle": conclusion_phrase,
                "bullet_points": []
            }
            # Thank You μŠ¬λΌμ΄λ“œμš© νŠΉλ³„ λ…ΈνŠΈ
            speaker_notes = generate_closing_notes(topic, conclusion_phrase)
        else:
            content = generate_slide_content(
                topic, slide['title'], slide_context, 
                uploaded_content, web_search_results
            )
            # 일반 μŠ¬λΌμ΄λ“œ λ°œν‘œμž λ…ΈνŠΈ
            speaker_notes = generate_presentation_notes(topic, slide['title'], content)
        
        # ν”„λ‘¬ν”„νŠΈ 생성 및 이미지 생성
        style_key = slide["style"]
        if style_key in STYLE_TEMPLATES:
            style_info = STYLE_TEMPLATES[style_key]
            prompt = generate_prompt_with_llm(
                topic, style_info["example"], 
                slide_context, uploaded_content
            )
            
            # 이미지 생성
            slide_seed = seed + i
            img, used_prompt = generate_image(prompt, slide_seed, slide_info)
            
            # μŠ¬λΌμ΄λ“œ 데이터 ꡬ성
            slide_data = {
                "slide_number": i + 1,
                "title": slide["title"],
                "subtitle": content["subtitle"],
                "bullet_points": content["bullet_points"],
                "image": img,
                "style": style_info["name"],
                "speaker_notes": speaker_notes,
                "topic": topic  # ν‘œμ§€μš©
            }
            
            # 프리뷰 HTML 생성 (νŽΈμ§‘ κ°€λŠ₯ν•œ μΈν„°νŽ˜μ΄μŠ€)
            if slide_data.get('title') not in ['ν‘œμ§€', 'Thank You']:
                preview_html += create_editable_slide_interface(slide_data, i, topic)
            else:
                preview_html += create_slide_preview_html(slide_data)
            
            # ν˜„μž¬κΉŒμ§€μ˜ μƒνƒœ μ—…λ°μ΄νŠΈ
            yield preview_html + "</div>", f"### πŸ”„ {slide_info} 생성 쀑...", None
            
            results.append({
                "slide_data": slide_data,
                "success": img is not None
            })
    
    # PPTX 파일 생성
    progress(0.95, "PPTX 파일 생성 쀑...")
    pptx_path = None
    try:
        pptx_path = create_pptx_file(results, topic, template_name, theme_name)
    except Exception as e:
        print(f"[PPTX] 파일 생성 였λ₯˜: {str(e)}")
    
    # μ΅œμ’… 결과에 νŽΈμ§‘ κ°€λŠ₯ν•œ μŠ¬λΌμ΄λ“œ 데이터 μ €μž₯
    preview_html += """
    <div style="margin: 40px auto; max-width: 1200px; text-align: center; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.3);">
        <h3 style="color: white; margin-bottom: 20px;">✨ λͺ¨λ“  νŽΈμ§‘μ΄ μ™„λ£Œλ˜μ—ˆλ‚˜μš”?</h3>
        <button id="finalDownloadBtn" onclick="prepareFinalDownload()" style="
            background: white;
            color: #667eea;
            border: none;
            padding: 18px 50px;
            border-radius: 50px;
            cursor: pointer;
            font-size: 20px;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
        " onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">
            πŸ’Ύ νŽΈμ§‘ λ‚΄μš© λ°˜μ˜ν•˜μ—¬ μ΅œμ’… λ‹€μš΄λ‘œλ“œ
        </button>
        <p style="color: white; margin-top: 15px; font-size: 14px;">
            πŸ’‘ νŽΈμ§‘ν•œ λ‚΄μš©μ΄ μ΅œμ’… PPT에 λ°˜μ˜λ©λ‹ˆλ‹€
        </p>
    </div>
    
    <script>
        function prepareFinalDownload() {
            // νŽΈμ§‘λœ λͺ¨λ“  데이터 μˆ˜μ§‘
            alert('νŽΈμ§‘λœ λ‚΄μš©μ„ λ°˜μ˜ν•œ μ΅œμ’… PPTλ₯Ό λ‹€μš΄λ‘œλ“œν•©λ‹ˆλ‹€.');
            // μ‹€μ œ κ΅¬ν˜„μ—μ„œλŠ” Gradio 이벀트둜 처리
        }
    </script>
    """
    
    preview_html += "</div>"
    progress(1.0, "μ™„λ£Œ!")
    successful = sum(1 for r in results if r["success"])
    final_status = f"### πŸŽ‰ 생성 μ™„λ£Œ! 총 {total_slides}개 μŠ¬λΌμ΄λ“œ 쀑 {successful}개 성곡"
    
    # νŽΈμ§‘ κ°€λŠ₯ν•œ μŠ¬λΌμ΄λ“œ 데이터λ₯Ό μ „μ—­ λ³€μˆ˜λ‘œ μ €μž₯
    global current_slides_data, current_topic, current_template, current_theme
    current_slides_data = results
    current_topic = topic
    current_template = template_name
    current_theme = theme_name
    
    if pptx_path:
        final_status += f"\n\n### πŸ“₯ PPTX 파일이 μ€€λΉ„λ˜μ—ˆμŠ΅λ‹ˆλ‹€!"
        final_status += f"\n\nπŸ’‘ **각 μŠ¬λΌμ΄λ“œλ₯Ό νŽΈμ§‘ν•œ ν›„ 'νŽΈμ§‘ μ™„λ£Œ ν›„ μ΅œμ’… λ‹€μš΄λ‘œλ“œ' λ²„νŠΌμ„ ν΄λ¦­ν•˜μ„Έμš”**"
        final_status += f"\n\n🎀 **λ°œν‘œμž λ…ΈνŠΈκ°€ 각 μŠ¬λΌμ΄λ“œμ— ν¬ν•¨λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€!**"
    
    yield preview_html, final_status, pptx_path

def create_custom_slides_ui():
    """μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ ꡬ성 UI (3-20μž₯)"""
    slides = []
    for i in range(20):  # μ΅œλŒ€ 20μž₯
        with gr.Row(visible=(i < 3)):  # κΈ°λ³Έ 3μž₯만 ν‘œμ‹œ
            with gr.Column(scale=2):
                title = gr.Textbox(
                    label=f"μŠ¬λΌμ΄λ“œ {i+1} 제λͺ©",
                    placeholder="예: ν˜„ν™© 뢄석, μ†”λ£¨μ…˜, λ‘œλ“œλ§΅...",
                )
            with gr.Column(scale=3):
                style = gr.Dropdown(
                    choices=list(STYLE_TEMPLATES.keys()),
                    label=f"μŠ€νƒ€μΌ 선택",
                    value="Colorful Mind Map"
                )
            with gr.Column(scale=3):
                hint = gr.Textbox(
                    label=f"ν”„λ‘¬ν”„νŠΈ 힌트",
                    placeholder="이 μŠ¬λΌμ΄λ“œμ—μ„œ ν‘œν˜„ν•˜κ³  싢은 λ‚΄μš©"
                )
        slides.append({"title": title, "style": style, "hint": hint, "row": gr.Row})
    return slides

# Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
with gr.Blocks(title="PPT 이미지 생성기", theme=gr.themes.Soft(), css="""
    .preview-container { max-width: 1400px; margin: 0 auto; }
    .slide-container { transition: all 0.3s ease; }
    .slide-container:hover { transform: translateY(-2px); box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15) !important; }
    input[type="text"], textarea { transition: all 0.3s ease; }
    input[type="text"]:focus, textarea:focus { border-color: #3498db !important; outline: none; box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2); }
    button { 
        transition: all 0.3s ease; 
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; 
        cursor: pointer !important; 
        user-select: none;
        -webkit-user-select: none;
    }
    button:hover { transform: translateY(-1px); box-shadow: 0 4px 8px rgba(0,0,0,0.2); opacity: 0.9; }
    button:active { transform: translateY(0); }
    .edit-mode { background: #f8f9fa; padding: 20px; border-radius: 8px; }
    .ai-instruction { background: #f3e5f5; padding: 15px; border-radius: 8px; margin-top: 15px; }
""") as demo:
    gr.Markdown("""
    # 🎯 AI 기반 PPT 톡합 생성기 (κ°„κ²°ν•œ μŠ€νƒ€μΌ 버전)
    
    ### ν…μŠ€νŠΈμ™€ 이미지가 μ™„λ²½ν•˜κ²Œ μ‘°ν™”λœ ν”„λ ˆμ  ν…Œμ΄μ…˜μ„ μžλ™μœΌλ‘œ μƒμ„±ν•˜κ³  νŽΈμ§‘ ν›„ λ‹€μš΄λ‘œλ“œν•˜μ„Έμš”!
    
    #### πŸ†• μƒˆλ‘œμš΄ κΈ°λŠ₯:
    - πŸ“ **κ°„κ²°ν•œ λͺ…μ‚¬ν˜• ν…μŠ€νŠΈ**: "~μž„", "~함" μŠ€νƒ€μΌμ˜ ν”„λ‘œνŽ˜μ…”λ„ν•œ 문체
    - 🎨 **이λͺ¨μ§€ μžλ™ μΆ”κ°€**: 각 ν¬μΈνŠΈλ³„ μ μ ˆν•œ 이λͺ¨μ§€λ‘œ μ‹œκ°μ  ꡬ뢄
    - ✏️ **μŠ¬λΌμ΄λ“œ ν…μŠ€νŠΈ νŽΈμ§‘**: μƒμ„±λœ 각 μŠ¬λΌμ΄λ“œμ˜ ν…μŠ€νŠΈλ₯Ό 직접 μˆ˜μ •
    - πŸ€– **AI μž¬μž‘μ„±**: μ§€μ‹œμ‚¬ν•­μ„ μž…λ ₯ν•˜λ©΄ AIκ°€ ν…μŠ€νŠΈλ₯Ό λ‹€μ‹œ μž‘μ„±
    - πŸ“‹ **예제 ν…œν”Œλ¦Ώ**: λ²„νŠΌ 클릭으둜 예제 주제 뢈러였기
    - 🎨 **λ””μžμΈ ν…Œλ§ˆ**: 5κ°€μ§€ 전문적인 λ””μžμΈ ν…Œλ§ˆ 선택 κ°€λŠ₯
    - πŸ’Ž **κ°œμ„ λœ ν‘œμ§€ λ””μžμΈ**: 반투λͺ… λ°°κ²½κ³Ό μ„ λͺ…ν•œ ν…μŠ€νŠΈ
    - πŸ“Š **ν‘œμ§€μ™€ Thank You μŠ¬λΌμ΄λ“œ** μžλ™ μΆ”κ°€
    - πŸ“ **λ°œν‘œμž λ…ΈνŠΈ** μžλ™ 생성 (ꡬ어체)
    - πŸ“ **파일 μ—…λ‘œλ“œ** 지원 (PDF/CSV/TXT)
    - πŸ” **μ›Ή 검색** κΈ°λŠ₯ (Brave Search)
    - 🎚️ **μŠ¬λΌμ΄λ“œ 수 쑰절** (6-20μž₯)
    """)
    
    # API 토큰 μƒνƒœ 확인
    token_status = []
    if not REPLICATE_API_TOKEN:
        token_status.append("⚠️ RAPI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
    if not FRIENDLI_TOKEN:
        token_status.append("⚠️ FRIENDLI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
    if not BRAVE_API_TOKEN:
        token_status.append("ℹ️ BAPI_TOKEN이 μ—†μ–΄ μ›Ή 검색 κΈ°λŠ₯이 λΉ„ν™œμ„±ν™”λ©λ‹ˆλ‹€.")
    
    if token_status:
        gr.Markdown("\n".join(token_status))
    
    with gr.Row():
        with gr.Column(scale=1):
            # 예제 선택
            with gr.Row():
                example_btn = gr.Button("πŸ“‹ 예제 뢈러였기", size="sm", variant="secondary")
                
            # κΈ°λ³Έ μž…λ ₯
            topic_input = gr.Textbox(
                label="ν”„λ ˆμ  ν…Œμ΄μ…˜ 주제",
                placeholder="예: AI μŠ€νƒ€νŠΈμ—… 투자 유치, μ‹ μ œν’ˆ 런칭, λ””μ§€ν„Έ μ „ν™˜ μ „λž΅",
                lines=2
            )
            
            # PPT ν…œν”Œλ¦Ώ 선택
            template_select = gr.Dropdown(
                choices=list(PPT_TEMPLATES.keys()),
                label="PPT ν…œν”Œλ¦Ώ 선택",
                value="λΉ„μ¦ˆλ‹ˆμŠ€ μ œμ•ˆμ„œ",
                info="λͺ©μ μ— λ§žλŠ” ν…œν”Œλ¦Ώμ„ μ„ νƒν•˜μ„Έμš”"
            )
            
            # λ””μžμΈ ν…Œλ§ˆ 선택
            theme_select = gr.Dropdown(
                choices=list(DESIGN_THEMES.keys()),
                label="λ””μžμΈ ν…Œλ§ˆ 선택",
                value="λ―Έλ‹ˆλ©€ 라이트",
                info="ν”„λ ˆμ  ν…Œμ΄μ…˜μ˜ 전체적인 λ””μžμΈ μŠ€νƒ€μΌ"
            )
            
            # ν…Œλ§ˆ 미리보기
            theme_preview = gr.HTML()
            
            # μŠ¬λΌμ΄λ“œ 수 선택
            slide_count = gr.Slider(
                minimum=6,
                maximum=20,
                value=8,
                step=1,
                label="λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ 수 (ν‘œμ§€μ™€ Thank You μ œμ™Έ)",
                info="생성할 λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ 수λ₯Ό μ„ νƒν•˜μ„Έμš”"
            )
            
            # 파일 μ—…λ‘œλ“œ
            file_upload = gr.File(
                label="μ°Έκ³  자료 μ—…λ‘œλ“œ (선택)",
                file_types=[".pdf", ".csv", ".txt"],
                type="filepath",
                value=None
            )
            
            # μ›Ή 검색 μ˜΅μ…˜
            use_web_search = gr.Checkbox(
                label="μ›Ή 검색 μ‚¬μš©",
                value=False,
                info="Brave Searchλ₯Ό μ‚¬μš©ν•˜μ—¬ μ΅œμ‹  정보 반영"
            )
            
            # ν…œν”Œλ¦Ώ μ„€λͺ…
            template_info = gr.Markdown()
            
            # μ‹œλ“œ κ°’
            seed_input = gr.Slider(
                minimum=1,
                maximum=100,
                value=10,
                step=1,
                label="μ‹œλ“œ κ°’"
            )
            
            generate_btn = gr.Button("πŸš€ PPT 생성 μ‹œμž‘ (AIκ°€ λͺ¨λ“  λ‚΄μš©μ„ μžλ™ 생성)", variant="primary", size="lg")
            
            # μ‚¬μš© 방법 μ•ˆλ‚΄
            with gr.Accordion("πŸ“– μ‚¬μš© 방법", open=False):
                gr.Markdown("""
                ### πŸ”„ μž‘μ—… μˆœμ„œ:
                1. **예제 뢈러였기** λ²„νŠΌμœΌλ‘œ μƒ˜ν”Œ 주제λ₯Ό λ‘œλ“œν•˜κ±°λ‚˜ 직접 μž…λ ₯
                2. **ν…œν”Œλ¦Ώκ³Ό ν…Œλ§ˆ 선택** ν›„ 생성 λ²„νŠΌ 클릭
                3. **각 μŠ¬λΌμ΄λ“œ νŽΈμ§‘**: ✏️ νŽΈμ§‘ λ²„νŠΌμœΌλ‘œ ν…μŠ€νŠΈ μˆ˜μ •
                4. **AI μž¬μž‘μ„±**: μ§€μ‹œμ‚¬ν•­ μž…λ ₯ ν›„ AI둜 λ‹€μ‹œ μž‘μ„±
                5. **μ΅œμ’… λ‹€μš΄λ‘œλ“œ**: νŽΈμ§‘ μ™„λ£Œ ν›„ λ‹€μš΄λ‘œλ“œ
                
                ### πŸ’‘ ν…μŠ€νŠΈ μŠ€νƒ€μΌ νŠΉμ§•:
                - **κ°„κ²°ν•œ λͺ…μ‚¬ν˜• μ’…κ²°**: "~μž„", "~함" λ˜λŠ” λͺ…μ‚¬λ‘œ 끝남
                - **이λͺ¨μ§€ ν™œμš©**: 각 포인트 μ•žμ— λ‚΄μš© κ΄€λ ¨ 이λͺ¨μ§€ μžλ™ μΆ”κ°€
                - **8-12단어**: 각 뢈릿 ν¬μΈνŠΈλŠ” 맀우 κ°„κ²°ν•˜κ²Œ ꡬ성
                
                **μŠ€νƒ€μΌ μ˜ˆμ‹œ:**
                - ❌ "μ‹œμž₯ μ μœ μœ¨μ„ ν™•λŒ€ν•˜κΈ° μœ„ν•œ μ „λž΅μ„ μˆ˜λ¦½ν•©λ‹ˆλ‹€"
                - βœ… "🎯 μ‹œμž₯ 점유율 ν™•λŒ€ μ „λž΅ 수립"
                - ❌ "AI κΈ°μˆ μ„ ν™œμš©ν•˜μ—¬ νš¨μœ¨μ„±μ„ ν–₯μƒμ‹œν‚΅λ‹ˆλ‹€"
                - βœ… "πŸš€ AI 기술 ν™œμš©ν•œ νš¨μœ¨μ„± κ·ΉλŒ€ν™”"
                
                ### πŸ€– AI μž¬μž‘μ„± 팁:
                - "더 κ°„λ‹¨ν•˜κ²Œ": ν•΅μ‹¬λ§Œ 남기고 μΆ•μ•½
                - "숫자 포함": ꡬ체적 μˆ˜μΉ˜λ‚˜ 톡계 μΆ”κ°€
                - "μ „λ¬Έμ μœΌλ‘œ": 업계 μ „λ¬Έ μš©μ–΄ μ‚¬μš©
                - "μž„νŒ©νŠΈ 있게": 강쑰점과 핡심 μ„±κ³Ό 뢀각
                """)
            
            # PPTX λ‹€μš΄λ‘œλ“œ μ˜μ—­
            with gr.Row():
                download_file = gr.File(
                    label="πŸ“₯ μƒμ„±λœ PPTX 파일 λ‹€μš΄λ‘œλ“œ",
                    visible=True,
                    elem_id="download-file"
                )
            
            # μ‚¬μš©μž μ •μ˜ μ„Ήμ…˜
            with gr.Accordion("πŸ“ μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ ꡬ성", open=False) as custom_accordion:
                gr.Markdown("ν…œν”Œλ¦Ώμ„ μ‚¬μš©ν•˜μ§€ μ•Šκ³  직접 μŠ¬λΌμ΄λ“œλ₯Ό κ΅¬μ„±ν•˜μ„Έμš”. (3-20μž₯)")
                
                # μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ 수 선택
                custom_slide_count = gr.Slider(
                    minimum=3,
                    maximum=20,
                    value=3,
                    step=1,
                    label="μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ 수"
                )
                
                custom_slides_components = create_custom_slides_ui()
    
    # μƒνƒœ ν‘œμ‹œ
    status_output = gr.Markdown(
        value="### πŸ‘† ν…œν”Œλ¦Ώμ„ μ„ νƒν•˜κ³  생성 λ²„νŠΌμ„ ν΄λ¦­ν•˜μ„Έμš”!"
    )
    
    # 프리뷰 μ˜μ—­
    preview_output = gr.HTML(
        label="PPT 프리뷰 (16:9)",
        elem_classes="preview-container"
    )
    
    # 이벀트 ν•Έλ“€λŸ¬
    def load_example(template_name):
        """ν…œν”Œλ¦Ώμ— λ§žλŠ” 예제 주제 λ‘œλ“œ"""
        example_topic = EXAMPLE_TOPICS.get(template_name, "")
        return example_topic
    
    def update_theme_preview(theme_name):
        """ν…Œλ§ˆ 미리보기 HTML 생성"""
        theme = DESIGN_THEMES.get(theme_name, DESIGN_THEMES["λ―Έλ‹ˆλ©€ 라이트"])
        
        # RGB 값을 hex둜 λ³€ν™˜
        def rgb_to_hex(rgb_color):
            return f"#{rgb_color[0]:02x}{rgb_color[1]:02x}{rgb_color[2]:02x}"
        
        bg_hex = rgb_to_hex(theme["background"])
        box_hex = rgb_to_hex(theme["box_fill"])
        title_hex = rgb_to_hex(theme["title_color"])
        text_hex = rgb_to_hex(theme["text_color"])
        accent_hex = rgb_to_hex(theme["accent_color"])
        
        preview_html = f"""
        <div style="
            background: {bg_hex};
            padding: 20px;
            border-radius: 8px;
            margin: 10px 0;
        ">
            <div style="
                background: {box_hex};
                opacity: {theme['box_opacity']};
                padding: 15px;
                border-radius: 12px;
                margin-bottom: 10px;
                {'box-shadow: 0 4px 8px rgba(0,0,0,0.1);' if theme['shadow'] else ''}
            ">
                <h4 style="color: {title_hex}; margin: 0 0 10px 0;">{theme['name']}</h4>
                <p style="color: {text_hex}; margin: 0; font-size: 14px;">
                    {theme['description']}
                </p>
                <div style="
                    width: 40px;
                    height: 4px;
                    background: {accent_hex};
                    margin-top: 10px;
                    border-radius: 2px;
                "></div>
            </div>
        </div>
        """
        return preview_html
    
    def update_template_info(template_name, slide_count):
        if template_name in PPT_TEMPLATES:
            template = PPT_TEMPLATES[template_name]
            info = f"**{template['description']}**\n\n"
            
            # λ™μ μœΌλ‘œ 생성될 μŠ¬λΌμ΄λ“œ ꡬ성 ν‘œμ‹œ
            slides = generate_dynamic_slides("", template, slide_count)
            info += f"생성될 μŠ¬λΌμ΄λ“œ ({len(slides)}μž₯):\n"
            for i, slide in enumerate(slides):
                style_info = STYLE_TEMPLATES.get(slide['style'], {})
                info += f"{i+1}. {slide['title']} - {style_info.get('use_case', '')}\n"
            
            return info
        return ""
    
    def update_custom_slides_visibility(count):
        """μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ μˆ˜μ— 따라 UI ν‘œμ‹œ/μˆ¨κΉ€"""
        updates = []
        for i in range(20):
            updates.extend([
                gr.update(visible=(i < count)),  # title
                gr.update(visible=(i < count)),  # style
                gr.update(visible=(i < count))   # hint
            ])
        return updates
    
    def generate_ppt_handler(topic, template_name, theme_name, slide_count, seed, file_upload, 
                           use_web_search, custom_slide_count, progress=gr.Progress(), 
                           *custom_inputs):
        if not topic.strip():
            yield "", "❌ 주제λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”.", None
            return
        
        # μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ 처리
        custom_slides = []
        if template_name == "μ‚¬μš©μž μ •μ˜":
            for i in range(0, custom_slide_count * 3, 3):
                if i < len(custom_inputs):
                    title = custom_inputs[i]
                    style = custom_inputs[i+1] if i+1 < len(custom_inputs) else None
                    hint = custom_inputs[i+2] if i+2 < len(custom_inputs) else ""
                    
                    if title and style:
                        custom_slides.append({
                            "title": title,
                            "style": style,
                            "prompt_hint": hint
                        })
        
        # PPT 생성
        for preview, status, pptx_file in generate_ppt_with_content(
            topic, template_name, custom_slides, slide_count, seed, 
            file_upload, use_web_search, theme_name, progress
        ):
            yield preview, status, pptx_file
    
    # 이벀트 μ—°κ²°
# --- 이벀트 μ—°κ²° -------------------------------------------------
    example_btn.click(
        fn=load_example,
        inputs=[template_select],
        outputs=[topic_input]
    )

    theme_select.change(
        fn=update_theme_preview,
        inputs=[theme_select],
        outputs=[theme_preview]
    )

    template_select.change(
        fn=update_template_info,
        inputs=[template_select, slide_count],
        outputs=[template_info]
    )

    slide_count.change(
        fn=update_template_info,
        inputs=[template_select, slide_count],
        outputs=[template_info]
    )

    custom_slide_count.change(
        fn=update_custom_slides_visibility,
        inputs=[custom_slide_count],
        outputs=[
            comp
            for slide in custom_slides_components
            for comp in (slide["title"], slide["style"], slide["hint"])
        ]
    )

    # μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ μž…λ ₯ μ»΄ν¬λ„ŒνŠΈ 평탄화
    all_custom_inputs = []
    for slide in custom_slides_components:
        all_custom_inputs.extend([slide["title"], slide["style"], slide["hint"]])

    generate_btn.click(
        fn=generate_ppt_handler,
        inputs=[
            topic_input,
            template_select,
            theme_select,
            slide_count,
            seed_input,
            file_upload,
            use_web_search,
            custom_slide_count,
        ]
        + all_custom_inputs,
        outputs=[preview_output, status_output, download_file],
    )

    # 초기 λ‘œλ“œμ‹œ ν…œν”Œλ¦Ώ/ν…Œλ§ˆ 정보 ν‘œμ‹œ
    demo.load(
        fn=lambda: (
            update_template_info(template_select.value, slide_count.value),
            update_theme_preview(theme_select.value),
        ),
        inputs=[],
        outputs=[template_info, theme_preview],
    )

# --- μ•± μ‹€ν–‰ --------------------------------------------------------
if __name__ == "__main__":
    demo.launch(ssr_mode=False)