File size: 46,688 Bytes
547fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cccb95
547fa82
3cccb95
 
0d82b88
547fa82
0d82b88
547fa82
0d82b88
 
547fa82
0d82b88
 
547fa82
 
 
 
 
0d82b88
 
 
 
547fa82
 
 
3cccb95
 
 
547fa82
 
 
 
 
 
 
 
 
0d82b88
 
547fa82
 
 
 
 
 
 
0d82b88
 
547fa82
 
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547fa82
0d82b88
 
 
 
547fa82
 
 
 
 
0d82b88
 
 
547fa82
 
0d82b88
 
 
 
547fa82
 
 
0d82b88
 
 
547fa82
 
0d82b88
 
 
 
547fa82
 
 
0d82b88
 
 
 
 
 
 
 
 
547fa82
0d82b88
 
 
 
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
 
 
547fa82
 
 
0d82b88
 
 
 
 
 
 
 
 
 
 
 
547fa82
 
 
0d82b88
 
547fa82
0d82b88
 
547fa82
0d82b88
547fa82
 
0d82b88
547fa82
 
 
0d82b88
 
 
 
547fa82
0d82b88
 
547fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d82b88
547fa82
0d82b88
547fa82
 
 
0d82b88
547fa82
0d82b88
547fa82
 
 
0d82b88
 
 
547fa82
 
 
 
 
 
 
0d82b88
547fa82
0d82b88
547fa82
 
 
0d82b88
 
 
 
 
 
547fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d82b88
547fa82
 
 
 
 
 
 
 
 
0d82b88
 
547fa82
0d82b88
 
547fa82
0d82b88
 
 
547fa82
0d82b88
 
 
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
 
547fa82
 
 
 
0d82b88
 
547fa82
3cccb95
547fa82
 
0d82b88
547fa82
0d82b88
547fa82
 
3cccb95
 
 
 
 
547fa82
 
 
0d82b88
547fa82
 
 
0d82b88
547fa82
ddb87db
 
 
547fa82
0d82b88
547fa82
0d82b88
ddb87db
0d82b88
547fa82
0d82b88
 
547fa82
0d82b88
 
 
 
 
 
90af475
0d82b88
 
 
 
 
547fa82
0d82b88
547fa82
0d82b88
547fa82
0d82b88
 
 
 
547fa82
0d82b88
 
 
 
547fa82
0d82b88
 
547fa82
0d82b88
 
547fa82
0d82b88
 
 
 
547fa82
0d82b88
547fa82
0d82b88
 
547fa82
 
0d82b88
547fa82
0d82b88
547fa82
0d82b88
 
 
 
90af475
0d82b88
 
 
 
 
 
547fa82
0d82b88
 
 
 
 
547fa82
0d82b88
547fa82
0d82b88
547fa82
0d82b88
 
 
 
547fa82
0d82b88
 
 
 
547fa82
0d82b88
 
547fa82
0d82b88
 
547fa82
0d82b88
 
 
 
547fa82
 
 
 
0d82b88
 
 
 
 
547fa82
0d82b88
547fa82
0d82b88
 
547fa82
0d82b88
 
 
 
 
547fa82
0d82b88
547fa82
0d82b88
 
 
 
 
 
 
547fa82
0d82b88
547fa82
0d82b88
 
 
 
 
 
547fa82
0d82b88
547fa82
0d82b88
547fa82
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547fa82
 
 
 
 
 
 
 
 
 
 
 
90af475
 
 
 
 
 
 
 
547fa82
 
 
 
 
90af475
 
547fa82
 
 
90af475
 
 
 
0d82b88
547fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d82b88
547fa82
 
 
 
 
0d82b88
3cccb95
 
 
 
547fa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d82b88
547fa82
 
0d82b88
 
 
 
 
90af475
0d82b88
547fa82
0d82b88
 
 
 
 
 
 
 
 
547fa82
 
0d82b88
 
547fa82
0d82b88
 
90af475
0d82b88
547fa82
0d82b88
 
 
 
 
 
 
 
 
547fa82
 
 
 
 
 
0d82b88
547fa82
0d82b88
547fa82
0d82b88
 
547fa82
 
90af475
0d82b88
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
 
 
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547fa82
 
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f995c33
 
 
 
 
 
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547fa82
 
0d82b88
 
547fa82
0d82b88
547fa82
0d82b88
 
547fa82
 
0d82b88
 
 
 
 
 
547fa82
 
 
0d82b88
 
547fa82
 
 
 
 
 
0d82b88
547fa82
0d82b88
 
 
547fa82
 
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547fa82
 
 
 
 
 
2c7be3c
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7be3c
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547fa82
0d82b88
 
 
 
 
2c7be3c
0d82b88
 
 
 
2c7be3c
0d82b88
 
 
 
2c7be3c
0d82b88
 
 
 
 
 
2c7be3c
0d82b88
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7be3c
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
afc761a
0d82b88
 
afc761a
0d82b88
 
 
 
 
 
 
 
547fa82
0d82b88
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7be3c
0d82b88
 
 
 
 
 
547fa82
0d82b88
 
 
 
 
547fa82
0d82b88
 
 
 
 
 
 
 
 
547fa82
0d82b88
 
 
 
 
f995c33
0d82b88
 
 
 
 
 
 
 
 
a0d10f1
0d82b88
547fa82
 
 
0d82b88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import os
import json
import requests
from datetime import datetime
import time
from typing import List, Dict, Any, Generator, Tuple, Optional, Set
import logging
import re
import tempfile
from pathlib import Path
import sqlite3
import hashlib
import threading
from contextlib import contextmanager
from dataclasses import dataclass, field, asdict
from collections import defaultdict
import random
from huggingface_hub import HfApi, upload_file, hf_hub_download

# --- Logging setup ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# --- Document export imports ---
try:
    from docx import Document
    from docx.shared import Inches, Pt, RGBColor, Mm
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    from docx.enum.style import WD_STYLE_TYPE
    from docx.oxml.ns import qn
    from docx.oxml import OxmlElement
    DOCX_AVAILABLE = True
except ImportError:
    DOCX_AVAILABLE = False
    logger.warning("python-docx not installed. DOCX export will be disabled.")

import io  # Add io import for DOCX export

# --- Environment variables and constants ---
FIREWORKS_API_KEY = os.getenv("FIREWORKS_API_KEY", "")
BRAVE_SEARCH_API_KEY = os.getenv("BRAVE_SEARCH_API_KEY", "")
API_URL = "https://api.fireworks.ai/inference/v1/chat/completions"
MODEL_ID = "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507"
DB_PATH = "webtoon_sessions_v1.db"

# Target settings for webtoon - UPDATED FOR WEBTOON
TARGET_EPISODES = 40  # 40ν™” μ™„κ²°
PANELS_PER_EPISODE = 30  # 각 ν™”λ‹Ή 30개 νŒ¨λ„
TARGET_PANELS = TARGET_EPISODES * PANELS_PER_EPISODE  # 총 1200 νŒ¨λ„

# Webtoon genres
WEBTOON_GENRES = {
    "둜맨슀": "Romance",
    "둜판": "Romance Fantasy", 
    "νŒνƒ€μ§€": "Fantasy",
    "ν˜„νŒ": "Modern Fantasy",
    "λ¬΄ν˜‘": "Martial Arts",
    "슀릴러": "Thriller",
    "일상": "Slice of Life",
    "개그": "Comedy",
    "슀포츠": "Sports"
}

# --- Environment validation ---
if not FIREWORKS_API_KEY:
    logger.error("FIREWORKS_API_KEY not set. Application will not work properly.")
    FIREWORKS_API_KEY = "dummy_token_for_testing"

if not BRAVE_SEARCH_API_KEY:
    logger.warning("BRAVE_SEARCH_API_KEY not set. Web search features will be disabled.")

# --- Global variables ---
db_lock = threading.Lock()

# --- Data classes ---
@dataclass
class WebtoonBible:
    """Webtoon story bible for maintaining consistency"""
    genre: str = ""
    title: str = ""
    characters: Dict[str, Dict[str, Any]] = field(default_factory=dict)
    settings: Dict[str, str] = field(default_factory=dict)
    plot_points: List[Dict[str, Any]] = field(default_factory=list)
    episode_hooks: Dict[int, str] = field(default_factory=dict)
    genre_elements: Dict[str, Any] = field(default_factory=dict)
    visual_style: Dict[str, Any] = field(default_factory=dict)
    panel_compositions: List[str] = field(default_factory=list)
    
@dataclass
class StoryboardPanel:
    """Individual storyboard panel"""
    panel_number: int
    scene_type: str  # wide, close-up, medium, establishing
    image_prompt: str  # Image generation prompt
    dialogue: List[str] = field(default_factory=list)
    narration: str = ""
    sound_effects: List[str] = field(default_factory=list)
    emotion_notes: str = ""
    camera_angle: str = ""
    background: str = ""

@dataclass
class EpisodeStoryboard:
    """Complete storyboard for one episode"""
    episode_number: int
    title: str
    panels: List[StoryboardPanel] = field(default_factory=list)
    total_panels: int = 30
    cliffhanger: str = ""

# --- Genre-specific prompts and elements ---
GENRE_ELEMENTS = {
    "둜맨슀": {
        "key_elements": ["감정선", "μ˜€ν•΄μ™€ ν™”ν•΄", "λ‹¬μ½€ν•œ μˆœκ°„", "질투", "κ³ λ°±"],
        "visual_styles": ["μ†Œν”„νŠΈ 톀", "νŒŒμŠ€ν…”", "꽃 λ°°κ²½", "λΉ›λ§μšΈ 효과", "뢄홍빛 ν•„ν„°"],
        "panel_types": ["ν΄λ‘œμ¦ˆμ—… 감정샷", "νˆ¬μƒ·", "손 ν΄λ‘œμ¦ˆμ—…", "λˆˆλΉ› κ΅ν™˜", "λ°±ν—ˆκ·Έ"],
        "typical_scenes": ["카페 데이트", "μš°μ‚° 씬", "λΆˆκ½ƒλ†€μ΄", "μ˜₯상 κ³ λ°±", "곡항 이별"]
    },
    "둜판": {
        "key_elements": ["νšŒκ·€/λΉ™μ˜", "λ“œλ ˆμŠ€", "λ¬΄λ„νšŒ", "λ§ˆλ²•", "μ‹ λΆ„ μƒμŠΉ"],
        "visual_styles": ["ν™”λ €ν•œ μ˜μƒ", "μœ λŸ½ν’ λ°°κ²½", "반짝이 효과", "λ§ˆλ²•μ§„", "μ„± λ°°κ²½"],
        "panel_types": ["μ „μ‹ μƒ·", "λ“œλ ˆμŠ€ λ””ν…ŒμΌ", "λ§ˆλ²• μ΄νŽ™νŠΈ", "νšŒμƒμ”¬", "좩격 λ¦¬μ•‘μ…˜"],
        "typical_scenes": ["λ¬΄λ„νšŒμž₯", "정원 μ‚°μ±…", "μ„œμž¬", "λ§ˆλ²• μˆ˜μ—…", "μ•Œν˜„μ‹€"]
    },
    "νŒνƒ€μ§€": {
        "key_elements": ["λ§ˆλ²•μ²΄κ³„", "λ ˆλ²¨μ—…", "λ˜μ „", "κΈΈλ“œ", "λͺ¨ν—˜"],
        "visual_styles": ["λ‹€μ΄λ‚˜λ―Ή μ•‘μ…˜", "μ΄νŽ™νŠΈ κ°•μ‘°", "λͺ¬μŠ€ν„° λ””μžμΈ", "νŒνƒ€μ§€ λ°°κ²½", "λΉ› 효과"],
        "panel_types": ["μ•‘μ…˜μ”¬", "ν’€μƒ· μ „νˆ¬", "μŠ€ν‚¬ λ°œλ™", "λͺ¬μŠ€ν„° λ“±μž₯", "νŒŒμ›Œμ—…"],
        "typical_scenes": ["λ˜μ „ μž…κ΅¬", "λ³΄μŠ€μ „", "κΈΈλ“œ νšŒκ΄€", "수련μž₯", "μ•„μ΄ν…œ νšλ“"]
    },
    "ν˜„νŒ": {
        "key_elements": ["게이트", "ν—Œν„°", "각성", "ν˜„λŒ€ λ„μ‹œ", "λŠ₯λ ₯"],
        "visual_styles": ["λ„μ‹œ λ°°κ²½", "λ„€μ˜¨ 효과", "ν˜„λŒ€μ  μ•‘μ…˜", "특수 효과", "μ–΄λ°˜ νŒνƒ€μ§€"],
        "panel_types": ["λ„μ‹œ μ „κ²½", "λŠ₯λ ₯ λ°œν˜„", "게이트 μΆœν˜„", "μ „νˆ¬ μ•‘μ…˜", "일상 λŒ€λΉ„"],
        "typical_scenes": ["게이트 ν˜„μž₯", "ν—Œν„° ν˜‘νšŒ", "ν›ˆλ ¨μž₯", "병원", "학ꡐ"]
    },
    "λ¬΄ν˜‘": {
        "key_elements": ["무곡", "문파", "κ°•ν˜Έ", "볡수", "μ˜ν˜‘"],
        "visual_styles": ["동양풍", "λ¨Ή 효과", "κΈ° ν‘œν˜„", "쀑ꡭ풍 μ˜μƒ", "μ‚°μˆ˜ν™” λ°°κ²½"],
        "panel_types": ["κ²€μˆ  λ™μž‘", "경곡술", "기곡 수련", "λŒ€κ²° ꡬ도", "폭발 μ΄νŽ™νŠΈ"],
        "typical_scenes": ["무림맹", "κ°μž”", "절벽", "폭포 수련", "λΉ„λ¬΄λŒ€νšŒ"]
    },
    "슀릴러": {
        "key_elements": ["μ„œμŠ€νŽœμŠ€", "곡포", "좔격", "심리전", "λ°˜μ „"],
        "visual_styles": ["μ–΄λ‘μš΄ 톀", "그림자 κ°•μ‘°", "λŒ€λΉ„ 효과", "λΆˆμ•ˆν•œ ꡬ도", "뢉은색 κ°•μ‘°"],
        "panel_types": ["극단 ν΄λ‘œμ¦ˆμ—…", "Dutch angle", "싀루엣", "좩격 μ»·", "곡포 μ—°μΆœ"],
        "typical_scenes": ["μ–΄λ‘μš΄ 골λͺ©", "폐건물", "μ§€ν•˜μ‹€", "좔격씬", "λŒ€μΉ˜ 상황"]
    },
    "일상": {
        "key_elements": ["일상", "곡감", "μ†Œμ†Œν•œ 재미", "관계", "μ„±μž₯"],
        "visual_styles": ["λ”°λœ»ν•œ 색감", "λΆ€λ“œλŸ¬μš΄ μ„ ", "일상 λ°°κ²½", "캐주얼", "νŽΈμ•ˆν•œ ꡬ도"],
        "panel_types": ["일상 μ»·", "λ¦¬μ•‘μ…˜", "λŒ€ν™”μ”¬", "λ°°κ²½ λ¬˜μ‚¬", "감정 ν‘œν˜„"],
        "typical_scenes": ["μ§‘", "학ꡐ", "νšŒμ‚¬", "동넀", "편의점"]
    },
    "개그": {
        "key_elements": ["개그", "νŒ¨λŸ¬λ””", "κ³Όμž₯", "λ°˜μ „", "μŠ¬λž©μŠ€ν‹±"],
        "visual_styles": ["κ³Όμž₯된 ν‘œμ •", "데포λ₯΄λ©”", "νš¨κ³Όμ„ ", "말풍선 μ—°μΆœ", "파격 ꡬ도"],
        "panel_types": ["κ³Όμž₯ λ¦¬μ•‘μ…˜", "개그 μ»·", "νŒ¨λŸ¬λ””", "좩격 ν‘œμ •", "망가짐"],
        "typical_scenes": ["개그 상황", "일상 λΆ•κ΄΄", "μ˜€ν•΄ 상황", "좔격전", "단체 개그"]
    },
    "슀포츠": {
        "key_elements": ["κ²½κΈ°", "ν›ˆλ ¨", "νŒ€μ›Œν¬", "라이벌", "μ„±μž₯"],
        "visual_styles": ["λ‹€μ΄λ‚˜λ―Ή", "μŠ€ν”Όλ“œμ„ ", "λ•€ ν‘œν˜„", "근윑 λ¬˜μ‚¬", "κ²½κΈ°μž₯"],
        "panel_types": ["μ•‘μ…˜ μ»·", "결정적 μˆœκ°„", "μ „μ‹  λ™μž‘", "ν‘œμ • ν΄λ‘œμ¦ˆμ—…", "κ²½κΈ° μ „κ²½"],
        "typical_scenes": ["κ²½κΈ°μž₯", "ν›ˆλ ¨μž₯", "라컀룸", "벀치", "μ‹œμƒλŒ€"]
    }
}

# Panel composition types
PANEL_COMPOSITIONS = {
    "establishing": "전체 λ°°κ²½κ³Ό λΆ„μœ„κΈ°λ₯Ό λ³΄μ—¬μ£ΌλŠ” 원거리 μƒ·",
    "wide": "캐릭터와 배경이 λͺ¨λ‘ λ³΄μ΄λŠ” μ™€μ΄λ“œ μƒ·",
    "medium": "캐릭터 μƒλ°˜μ‹ μ΄ λ³΄μ΄λŠ” λ―Έλ””μ—„ μƒ·",
    "close_up": "μ–Όκ΅΄μ΄λ‚˜ ν‘œμ •μ— μ§‘μ€‘ν•˜λŠ” ν΄λ‘œμ¦ˆμ—…",
    "extreme_close_up": "눈, μž… λ“± νŠΉμ • λΆ€μœ„ 극단 ν΄λ‘œμ¦ˆμ—…",
    "over_shoulder": "μ–΄κΉ¨ λ„ˆλ¨Έλ‘œ λ³΄λŠ” μ˜€λ²„μˆ„λ” μƒ·",
    "dutch_angle": "κΈ΄μž₯감을 μœ„ν•œ κΈ°μšΈμ–΄μ§„ μ•΅κΈ€",
    "bird_eye": "μœ„μ—μ„œ λ‚΄λ €λ‹€λ³΄λŠ” 뢀감 μƒ·",
    "worm_eye": "μ•„λž˜μ„œ μ˜¬λ €λ‹€λ³΄λŠ” 앙각 μƒ·",
    "action": "μ›€μ§μž„μ„ κ°•μ‘°ν•˜λŠ” μ•‘μ…˜ μƒ·"
}

# --- Core logic classes ---
class WebtoonTracker:
    """Webtoon narrative and storyboard tracker"""
    def __init__(self):
        self.story_bible = WebtoonBible()
        self.episode_storyboards: Dict[int, EpisodeStoryboard] = {}
        self.episodes: Dict[int, str] = {}
        self.total_panel_count = 0
        
    def set_genre(self, genre: str):
        """Set the webtoon genre"""
        self.story_bible.genre = genre
        self.story_bible.genre_elements = GENRE_ELEMENTS.get(genre, {})
        
    def add_storyboard(self, episode_num: int, storyboard: EpisodeStoryboard):
        """Add episode storyboard"""
        self.episode_storyboards[episode_num] = storyboard
        self.total_panel_count += len(storyboard.panels)

class WebtoonDatabase:
    """Database management for webtoon system"""
    @staticmethod
    def init_db():
        with sqlite3.connect(DB_PATH) as conn:
            conn.execute("PRAGMA journal_mode=WAL")
            cursor = conn.cursor()
            
            # Sessions table with genre
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sessions (
                    session_id TEXT PRIMARY KEY,
                    user_query TEXT NOT NULL,
                    genre TEXT NOT NULL,
                    language TEXT NOT NULL,
                    title TEXT,
                    created_at TEXT DEFAULT (datetime('now')),
                    updated_at TEXT DEFAULT (datetime('now')),
                    status TEXT DEFAULT 'active',
                    current_episode INTEGER DEFAULT 0,
                    total_episodes INTEGER DEFAULT 40,
                    planning_doc TEXT,
                    story_bible TEXT,
                    visual_style TEXT
                )
            ''')
            
            # Storyboards table
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS storyboards (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    session_id TEXT NOT NULL,
                    episode_number INTEGER NOT NULL,
                    title TEXT,
                    storyboard_data TEXT,
                    panel_count INTEGER DEFAULT 30,
                    status TEXT DEFAULT 'pending',
                    created_at TEXT DEFAULT (datetime('now')),
                    FOREIGN KEY (session_id) REFERENCES sessions(session_id),
                    UNIQUE(session_id, episode_number)
                )
            ''')
            
            # Panels table
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS panels (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    session_id TEXT NOT NULL,
                    episode_number INTEGER NOT NULL,
                    panel_number INTEGER NOT NULL,
                    scene_type TEXT,
                    image_prompt TEXT,
                    dialogue TEXT,
                    narration TEXT,
                    sound_effects TEXT,
                    created_at TEXT DEFAULT (datetime('now')),
                    FOREIGN KEY (session_id) REFERENCES sessions(session_id)
                )
            ''')
            
            conn.commit()

    @staticmethod
    @contextmanager
    def get_db():
        with db_lock:
            conn = sqlite3.connect(DB_PATH, timeout=30.0)
            conn.row_factory = sqlite3.Row
            try:
                yield conn
            finally:
                conn.close()

    @staticmethod
    def create_session(user_query: str, genre: str, language: str) -> str:
        session_id = hashlib.md5(f"{user_query}{genre}{datetime.now()}".encode()).hexdigest()
        with WebtoonDatabase.get_db() as conn:
            conn.cursor().execute(
                '''INSERT INTO sessions (session_id, user_query, genre, language) 
                   VALUES (?, ?, ?, ?)''',
                (session_id, user_query, genre, language)
            )
            conn.commit()
        return session_id

    @staticmethod
    def save_storyboard(session_id: str, episode_num: int, storyboard: EpisodeStoryboard):
        with WebtoonDatabase.get_db() as conn:
            cursor = conn.cursor()
            
            # Save storyboard
            cursor.execute('''
                INSERT INTO storyboards (session_id, episode_number, title, 
                                        storyboard_data, panel_count, status)
                VALUES (?, ?, ?, ?, ?, 'complete')
                ON CONFLICT(session_id, episode_number)
                DO UPDATE SET title=?, storyboard_data=?, panel_count=?, status='complete'
            ''', (session_id, episode_num, storyboard.title, 
                  json.dumps(asdict(storyboard)), len(storyboard.panels),
                  storyboard.title, json.dumps(asdict(storyboard)), len(storyboard.panels)))
            
            # Save individual panels
            for panel in storyboard.panels:
                cursor.execute('''
                    INSERT INTO panels (session_id, episode_number, panel_number,
                                      scene_type, image_prompt, dialogue, narration, sound_effects)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ''', (session_id, episode_num, panel.panel_number,
                      panel.scene_type, panel.image_prompt,
                      json.dumps(panel.dialogue), panel.narration,
                      json.dumps(panel.sound_effects)))
            
            conn.commit()

# --- LLM Integration ---
class WebtoonSystem:
    """Webtoon planning and storyboard generation system"""
    def __init__(self):
        self.api_key = FIREWORKS_API_KEY
        self.api_url = API_URL
        self.model_id = MODEL_ID
        self.tracker = WebtoonTracker()
        self.current_session_id = None
        WebtoonDatabase.init_db()

    def create_headers(self):
        return {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

    # --- Prompt generation functions ---
    def create_planning_prompt(self, query: str, genre: str, language: str) -> str:
        """Create initial planning prompt for webtoon"""
        genre_info = GENRE_ELEMENTS.get(genre, {})
        
        lang_prompts = {
            "Korean": f"""ν•œκ΅­ μ›Ήνˆ° μ‹œμž₯을 겨λƒ₯ν•œ {genre} μž₯λ₯΄ μ›Ήνˆ°μ„ κΈ°νšν•˜μ„Έμš”.

**[핡심 μŠ€ν† λ¦¬ μ„€μ • - λ°˜λ“œμ‹œ 이 λ‚΄μš©μ„ μ€‘μ‹¬μœΌλ‘œ μ „κ°œν•˜μ„Έμš”]**
{query}

**μž₯λ₯΄:** {genre}
**λͺ©ν‘œ:** 40ν™” μ™„κ²° μ›Ήνˆ°

⚠️ **μ€‘μš”**: μœ„μ— μ œμ‹œλœ μŠ€ν† λ¦¬ 섀정을 λ°˜λ“œμ‹œ 기반으둜 ν•˜μ—¬ ν”Œλ‘―μ„ κ΅¬μ„±ν•˜μ„Έμš”.

**μž₯λ₯΄ ν•„μˆ˜ μš”μ†Œ:**
- 핡심 μš”μ†Œ: {', '.join(genre_info.get('key_elements', []))}
- λΉ„μ£Όμ–Ό μŠ€νƒ€μΌ: {', '.join(genre_info.get('visual_styles', []))}
- μ£Όμš” 씬: {', '.join(genre_info.get('typical_scenes', []))}

**전체 ꡬ성 (40ν™” κΈ°μ€€):**
1. **1-5ν™”**: 세계관 μ†Œκ°œ, 주인곡 λ“±μž₯, 핡심 κ°ˆλ“± μ œμ‹œ
2. **6-15ν™”**: κ°ˆλ“± 심화, 캐릭터 관계 λ°œμ „, μ„œλΈŒν”Œλ‘― μ „κ°œ
3. **16-25ν™”**: 쀑간 클라이λ§₯슀, λ°˜μ „, μƒˆλ‘œμš΄ μœ„κΈ°
4. **26-35ν™”**: μ΅œμ’… κ°ˆλ“± κ³ μ‘°, κ²°μ „ μ€€λΉ„
5. **36-40ν™”**: 클라이λ§₯슀, ν•΄κ²°, μ—ν•„λ‘œκ·Έ

**μ›Ήνˆ° νŠΉν™” μš”μ†Œ:**
- λ§€ ν™” λ§ˆμ§€λ§‰ κ°•λ ₯ν•œ 클리프행어
- μ„Έλ‘œ μŠ€ν¬λ‘€μ— μ ν•©ν•œ μ—°μΆœ
- μž„νŒ©νŠΈ μžˆλŠ” λŒ€μ‚¬μ™€ μ•‘μ…˜
- λ…μž λŒ“κΈ€μ„ μœ λ°œν•˜λŠ” μ „κ°œ

λ‹€μŒ ν˜•μ‹μœΌλ‘œ μž‘μ„±ν•˜μ„Έμš”:

πŸ“š **μž‘ν’ˆ 제λͺ©:** [μž„νŒ©νŠΈ μžˆλŠ” 제λͺ©]

🎨 **λΉ„μ£Όμ–Ό 컨셉:**
- 그림체: [μž‘ν’ˆμ— μ–΄μšΈλ¦¬λŠ” 그림체]
- 색감: [μ£Όμš” 색상 톀]
- 캐릭터 λ””μžμΈ νŠΉμ§•: [μ£ΌμΈκ³΅λ“€μ˜ λΉ„μ£Όμ–Ό νŠΉμ§•]

πŸ‘₯ **μ£Όμš” 캐릭터:**
- 주인곡: [이름] - [μ™Έλͺ¨ νŠΉμ§•, 성격, λͺ©ν‘œ]
- 캐릭터2: [이름] - [μ—­ν• , νŠΉμ§•]
- 캐릭터3: [이름] - [μ—­ν• , νŠΉμ§•]

πŸ“– **μ‹œλ†‰μ‹œμŠ€:**
[3-4μ€„λ‘œ 전체 μŠ€ν† λ¦¬ μš”μ•½]

πŸ“ **40ν™” 전체 κ΅¬μ„±μ•ˆ:**
각 ν™”λ³„λ‘œ 핡심 사건과 클리프행어λ₯Ό ν¬ν•¨ν•˜μ—¬ μž‘μ„±ν•˜μ„Έμš”.

1ν™”: [제λͺ©] - [핡심 사건] - 클리프행어: [좩격적인 마무리]
2ν™”: [제λͺ©] - [핡심 사건] - 클리프행어: [좩격적인 마무리]
...
40ν™”: [제λͺ©] - [핡심 사건] - [λŒ€λ‹¨μ›μ˜ 마무리]""",

            "English": f"""Plan a Korean-style webtoon for {genre} genre.

**[Core Story Setting - MUST base the story on this]**
{query}

**Genre:** {genre}
**Goal:** 40 episodes webtoon

⚠️ **IMPORTANT**: You MUST base the plot on the story setting provided above.

**Genre Requirements:**
- Key elements: {', '.join(genre_info.get('key_elements', []))}
- Visual styles: {', '.join(genre_info.get('visual_styles', []))}
- Typical scenes: {', '.join(genre_info.get('typical_scenes', []))}

**Overall Structure (40 episodes):**
1. **Episodes 1-5**: World introduction, protagonist debut, core conflict
2. **Episodes 6-15**: Deepening conflict, character development, subplots
3. **Episodes 16-25**: Mid-climax, plot twist, new crisis
4. **Episodes 26-35**: Final conflict escalation, preparation for showdown
5. **Episodes 36-40**: Climax, resolution, epilogue

**Webtoon-specific elements:**
- Strong cliffhanger at end of each episode
- Vertical scroll-optimized directing
- Impactful dialogue and action
- Comment-inducing development

Format as follows:

πŸ“š **Title:** [Impactful title]

🎨 **Visual Concept:**
- Art style: [Suitable art style]
- Color tone: [Main color palette]
- Character design: [Visual characteristics]

πŸ‘₯ **Main Characters:**
- Protagonist: [Name] - [Appearance, personality, goal]
- Character2: [Name] - [Role, traits]
- Character3: [Name] - [Role, traits]

πŸ“– **Synopsis:**
[3-4 line story summary]

πŸ“ **40 Episode Structure:**
Include key events and cliffhangers for each episode.

Episode 1: [Title] - [Key event] - Cliffhanger: [Shocking ending]
Episode 2: [Title] - [Key event] - Cliffhanger: [Shocking ending]
...
Episode 40: [Title] - [Key event] - [Grand finale]"""
        }
        
        return lang_prompts.get(language, lang_prompts["Korean"])

    def create_storyboard_prompt(self, episode_num: int, plot_outline: str, 
                                genre: str, language: str) -> str:
        """Create prompt for episode 1 storyboard with 30 panels"""
        genre_info = GENRE_ELEMENTS.get(genre, {})
        
        lang_prompts = {
            "Korean": f"""μ›Ήνˆ° {episode_num}ν™” μŠ€ν† λ¦¬λ³΄λ“œλ₯Ό 30개 νŒ¨λ„λ‘œ μž‘μ„±ν•˜μ„Έμš”.

**μž₯λ₯΄:** {genre}
**1ν™” λ‚΄μš©:** {self._extract_episode_plan(plot_outline, episode_num)}

**νŒ¨λ„ ꡬ성 μ§€μΉ¨:**
- 총 30개 νŒ¨λ„λ‘œ ꡬ성
- λ‹€μ–‘ν•œ μƒ· μ‚¬μ΄μ¦ˆ ν™œμš© (μ™€μ΄λ“œμƒ·, ν΄λ‘œμ¦ˆμ—…, λ―Έλ””μ—„μƒ· λ“±)
- μž₯λ₯΄ νŠΉμ„±μ— λ§žλŠ” μ—°μΆœ: {', '.join(genre_info.get('panel_types', []))}
- μ„Έλ‘œ 슀크둀 μ›Ήνˆ°μ— μ΅œμ ν™”λœ ꡬ성

**각 νŒ¨λ„λ³„λ‘œ λ‹€μŒμ„ ν¬ν•¨ν•˜μ—¬ μž‘μ„±:**

νŒ¨λ„ 1:
- μƒ· νƒ€μž…: [establishing/wide/medium/close_up λ“±]
- 이미지 ν”„λ‘¬ν”„νŠΈ: [μƒμ„Έν•œ ν•œκΈ€ 이미지 생성 ν”„λ‘¬ν”„νŠΈ]
- λŒ€μ‚¬: [캐릭터 λŒ€μ‚¬κ°€ μžˆλ‹€λ©΄]
- λ‚˜λ ˆμ΄μ…˜: [해섀이 μžˆλ‹€λ©΄]
- 효과음: [ν•„μš”ν•œ 효과음]
- λ°°κ²½: [λ°°κ²½ μ„€λͺ…]

...이런 μ‹μœΌλ‘œ 30개 νŒ¨λ„ λͺ¨λ‘ μž‘μ„±

**μ€‘μš” μ—°μΆœ 포인트:**
1. 첫 νŒ¨λ„μ€ μž„νŒ©νŠΈ μžˆλŠ” establishing shot
2. 감정선은 ν΄λ‘œμ¦ˆμ—…μœΌλ‘œ κ°•μ‘°
3. μ•‘μ…˜μ€ λ‹€μ΄λ‚˜λ―Ήν•œ μ•΅κΈ€ ν™œμš©
4. λ§ˆμ§€λ§‰ νŒ¨λ„μ€ κ°•λ ₯ν•œ 클리프행어
5. λŒ€μ‚¬μ™€ 이미지가 μ‘°ν™”λ‘­κ²Œ ꡬ성

λ°˜λ“œμ‹œ 30개 νŒ¨λ„μ„ λͺ¨λ‘ μž‘μ„±ν•˜μ„Έμš”.""",

            "English": f"""Create Episode {episode_num} storyboard with 30 panels.

**Genre:** {genre}
**Episode 1 content:** {self._extract_episode_plan(plot_outline, episode_num)}

**Panel composition guidelines:**
- Total 30 panels
- Various shot sizes (wide, close-up, medium, etc.)
- Genre-appropriate directing: {', '.join(genre_info.get('panel_types', []))}
- Optimized for vertical scroll webtoon

**For each panel include:**

Panel 1:
- Shot type: [establishing/wide/medium/close_up etc]
- Image prompt: [Detailed Korean image generation prompt]
- Dialogue: [Character dialogue if any]
- Narration: [Narration if any]
- Sound effects: [Required sound effects]
- Background: [Background description]

...continue for all 30 panels

**Key directing points:**
1. First panel: impactful establishing shot
2. Emphasize emotions with close-ups
3. Dynamic angles for action
4. Last panel: powerful cliffhanger
5. Harmonious dialogue and image composition

Must write all 30 panels."""
        }
        
        return lang_prompts.get(language, lang_prompts["Korean"])

    def _extract_episode_plan(self, plot_outline: str, episode_num: int) -> str:
        """Extract specific episode plan from outline"""
        lines = plot_outline.split('\n')
        episode_section = []
        capturing = False
        
        patterns = [
            f"{episode_num}ν™”:", f"Episode {episode_num}:", 
            f"제{episode_num}ν™”:", f"EP{episode_num}:",
            f"{episode_num}.", f"[{episode_num}]"
        ]
        
        next_patterns = [
            f"{episode_num+1}ν™”:", f"Episode {episode_num+1}:", 
            f"제{episode_num+1}ν™”:", f"EP{episode_num+1}:",
            f"{episode_num+1}.", f"[{episode_num+1}]"
        ]
        
        for line in lines:
            if any(pattern in line for pattern in patterns):
                capturing = True
                episode_section.append(line)
            elif capturing and any(pattern in line for pattern in next_patterns):
                break
            elif capturing:
                episode_section.append(line)
        
        if episode_section:
            return '\n'.join(episode_section)
        
        return f"μ—ν”Όμ†Œλ“œ {episode_num} λ‚΄μš©μ„ ν”Œλ‘―μ—μ„œ μ°Έμ‘°ν•˜μ—¬ μž‘μ„±ν•˜μ„Έμš”."

    # --- LLM call functions ---
    def call_llm_sync(self, messages: List[Dict[str, str]], role: str, language: str) -> str:
        full_content = ""
        for chunk in self.call_llm_streaming(messages, role, language):
            full_content += chunk
        if full_content.startswith("❌"):
            raise Exception(f"LLM Call Failed: {full_content}")
        return full_content

    def call_llm_streaming(self, messages: List[Dict[str, str]], role: str, 
                          language: str) -> Generator[str, None, None]:
        try:
            system_prompts = self.get_system_prompts(language)
            full_messages = [{"role": "system", "content": system_prompts.get(role, "")}, *messages]
            
            max_tokens = 15000 if role == "storyboarder" else 10000
            
            payload = {
                "model": self.model_id,
                "messages": full_messages,
                "max_tokens": max_tokens,
                "temperature": 0.7,
                "top_p": 1,
                "top_k": 40,
                "presence_penalty": 0,
                "frequency_penalty": 0,
                "stream": True
            }
            
            response = requests.post(
                self.api_url, 
                headers=self.create_headers(), 
                json=payload, 
                stream=True, 
                timeout=180
            )
            
            if response.status_code != 200:
                yield f"❌ API Error (Status Code: {response.status_code})"
                return
            
            buffer = ""
            for line in response.iter_lines():
                if not line:
                    continue
                
                try:
                    line_str = line.decode('utf-8').strip()
                    if not line_str.startswith("data: "):
                        continue
                    
                    data_str = line_str[6:]
                    if data_str == "[DONE]":
                        break
                    
                    data = json.loads(data_str)
                    choices = data.get("choices", [])
                    if choices and choices[0].get("delta", {}).get("content"):
                        content = choices[0]["delta"]["content"]
                        buffer += content
                        
                        if len(buffer) >= 50 or '\n' in buffer:
                            yield buffer
                            buffer = ""
                            time.sleep(0.01)
                    
                except Exception as e:
                    logger.error(f"Chunk processing error: {str(e)}")
                    continue
            
            if buffer:
                yield buffer
                
        except Exception as e:
            logger.error(f"Streaming error: {type(e).__name__}: {str(e)}")
            yield f"❌ Error occurred: {str(e)}"

    def get_system_prompts(self, language: str) -> Dict[str, str]:
        """System prompts for webtoon roles"""
        base_prompts = {
            "Korean": {
                "planner": """당신은 ν•œκ΅­ μ›Ήνˆ° μ‹œμž₯을 μ™„λ²½νžˆ μ΄ν•΄ν•˜λŠ” μ›Ήνˆ° κΈ°νšμžμž…λ‹ˆλ‹€.
λ…μžλ₯Ό μ‚¬λ‘œμž‘λŠ” μŠ€ν† λ¦¬μ™€ λΉ„μ£Όμ–Ό μ—°μΆœμ„ κΈ°νšν•©λ‹ˆλ‹€.
40ν™” μ™„κ²° ꡬ쑰둜 μ™„λ²½ν•œ κΈ°μŠΉμ „κ²°μ„ μ„€κ³„ν•©λ‹ˆλ‹€.
각 ν™”λ§ˆλ‹€ κ°•λ ₯ν•œ ν΄λ¦¬ν”„ν–‰μ–΄λ‘œ λ‹€μŒ ν™”λ₯Ό κΈ°λŒ€ν•˜κ²Œ λ§Œλ“­λ‹ˆλ‹€.
μž₯λ₯΄λ³„ νŠΉμ„±κ³Ό λ…μžμΈ΅μ„ μ •ν™•νžˆ νŒŒμ•…ν•©λ‹ˆλ‹€.

⚠️ κ°€μž₯ μ€‘μš”ν•œ 원칙: μ‚¬μš©μžκ°€ μ œκ³΅ν•œ μŠ€ν† λ¦¬ 섀정을 μ ˆλŒ€μ μœΌλ‘œ μš°μ„ μ‹œν•˜κ³ , 이λ₯Ό μ€‘μ‹¬μœΌλ‘œ λͺ¨λ“  ν”Œλ‘―μ„ κ΅¬μ„±ν•©λ‹ˆλ‹€.""",
                
                "storyboarder": """당신은 μ›Ήνˆ° μŠ€ν† λ¦¬λ³΄λ“œ μ „λ¬Έκ°€μž…λ‹ˆλ‹€.
30개 νŒ¨λ„λ‘œ ν•œ ν™”λ₯Ό μ™„λ²½ν•˜κ²Œ κ΅¬μ„±ν•©λ‹ˆλ‹€.
μ„Έλ‘œ μŠ€ν¬λ‘€μ— μ΅œμ ν™”λœ μ—°μΆœμ„ ν•©λ‹ˆλ‹€.
각 νŒ¨λ„λ§ˆλ‹€ μƒμ„Έν•œ 이미지 ν”„λ‘¬ν”„νŠΈλ₯Ό ν•œκΈ€λ‘œ μž‘μ„±ν•©λ‹ˆλ‹€.
λŒ€μ‚¬, λ‚˜λ ˆμ΄μ…˜, νš¨κ³ΌμŒμ„ 적절히 λ°°μΉ˜ν•©λ‹ˆλ‹€.
λ‹€μ–‘ν•œ 카메라 μ•΅κΈ€κ³Ό μƒ· μ‚¬μ΄μ¦ˆλ₯Ό ν™œμš©ν•©λ‹ˆλ‹€.
감정선과 μ•‘μ…˜μ„ μ‹œκ°μ μœΌλ‘œ κ·ΉλŒ€ν™”ν•©λ‹ˆλ‹€.

⚠️ κ°€μž₯ μ€‘μš”ν•œ 원칙: λ°˜λ“œμ‹œ 30개 νŒ¨λ„μ„ λͺ¨λ‘ μž‘μ„±ν•˜κ³ , 각 νŒ¨λ„λ§ˆλ‹€ 이미지 생성이 κ°€λŠ₯ν•œ ꡬ체적인 ν•œκΈ€ ν”„λ‘¬ν”„νŠΈλ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€."""
            },
            "English": {
                "planner": """You perfectly understand the Korean webtoon market.
Design stories and visual direction that captivate readers.
Create perfect story structure in 40 episodes.
Make readers anticipate next episode with strong cliffhangers.
Accurately understand genre characteristics and readership.

⚠️ Most important principle: Absolutely prioritize the user's story setting and build all plots around it.""",
                
                "storyboarder": """You are a webtoon storyboard specialist.
Perfectly compose one episode with 30 panels.
Optimize direction for vertical scrolling.
Write detailed image prompts in Korean for each panel.
Properly place dialogue, narration, and sound effects.
Use various camera angles and shot sizes.
Visually maximize emotions and action.

⚠️ Most important principle: Must write all 30 panels and provide specific Korean prompts for image generation for each panel."""
            }
        }
        
        return base_prompts.get(language, base_prompts["Korean"])

    # --- Main process ---
    def process_webtoon_stream(self, query: str, genre: str, language: str, 
                              session_id: Optional[str] = None) -> Generator[Tuple[str, str, str, str], None, None]:
        """Webtoon planning and storyboard generation process"""
        try:
            if not session_id:
                self.current_session_id = WebtoonDatabase.create_session(query, genre, language)
                self.tracker.set_genre(genre)
                logger.info(f"Created new session: {self.current_session_id}")
                self.original_query = query
            else:
                self.current_session_id = session_id

            # Phase 1: Generate planning document (40 episodes structure)
            yield "🎬 μ›Ήνˆ° κΈ°νšμ•ˆ μž‘μ„± 쀑...", "", f"μž₯λ₯΄: {genre}", self.current_session_id
            
            planning_prompt = self.create_planning_prompt(query, genre, language)
            planning_doc = self.call_llm_sync(
                [{"role": "user", "content": planning_prompt}], 
                "planner", language
            )
            
            self.planning_doc = planning_doc
            
            yield "βœ… κΈ°νšμ•ˆ μ™„μ„±!", planning_doc, "40ν™” ꡬ성 μ™„λ£Œ", self.current_session_id

            # Phase 2: Generate Episode 1 Storyboard (30 panels)
            yield "🎨 1ν™” μŠ€ν† λ¦¬λ³΄λ“œ μž‘μ„± 쀑...", planning_doc, "30개 νŒ¨λ„ ꡬ성 쀑", self.current_session_id
            
            storyboard_prompt = self.create_storyboard_prompt(1, planning_doc, genre, language)
            storyboard_content = self.call_llm_sync(
                [{"role": "user", "content": storyboard_prompt}],
                "storyboarder", language
            )
            
            # Parse storyboard into structured format
            storyboard = self.parse_storyboard(storyboard_content, 1)
            
            # Save to database
            WebtoonDatabase.save_storyboard(self.current_session_id, 1, storyboard)
            
            # Format final output
            final_output = f"{planning_doc}\n\n{'='*50}\n\n## πŸ“‹ 1ν™” μŠ€ν† λ¦¬λ³΄λ“œ (30 νŒ¨λ„)\n\n{storyboard_content}"
            
            yield "πŸŽ‰ μ™„μ„±!", final_output, "κΈ°νšμ•ˆ + 1ν™” μŠ€ν† λ¦¬λ³΄λ“œ μ™„λ£Œ", self.current_session_id

        except Exception as e:
            logger.error(f"Webtoon generation error: {e}", exc_info=True)
            yield f"❌ 였λ₯˜ λ°œμƒ: {e}", "", "였λ₯˜", self.current_session_id

    def parse_storyboard(self, content: str, episode_num: int) -> EpisodeStoryboard:
        """Parse storyboard text into structured format"""
        storyboard = EpisodeStoryboard(episode_number=episode_num, title=f"{episode_num}ν™”")
        
        # Simple parsing - can be enhanced
        panels = []
        current_panel = None
        panel_number = 0
        
        lines = content.split('\n')
        for line in lines:
            if 'νŒ¨λ„' in line or 'Panel' in line:
                if current_panel:
                    panels.append(current_panel)
                panel_number += 1
                # Initialize with empty image_prompt as required argument
                current_panel = StoryboardPanel(
                    panel_number=panel_number, 
                    scene_type="medium",
                    image_prompt=""  # Initialize with empty string
                )
            elif current_panel:
                if '이미지 ν”„λ‘¬ν”„νŠΈ:' in line or 'Image prompt:' in line:
                    current_panel.image_prompt = line.split(':', 1)[1].strip()
                elif 'λŒ€μ‚¬:' in line or 'Dialogue:' in line:
                    dialogue = line.split(':', 1)[1].strip()
                    if dialogue:
                        current_panel.dialogue.append(dialogue)
                elif 'λ‚˜λ ˆμ΄μ…˜:' in line or 'Narration:' in line:
                    current_panel.narration = line.split(':', 1)[1].strip()
                elif '효과음:' in line or 'Sound effects:' in line:
                    effects = line.split(':', 1)[1].strip()
                    if effects:
                        current_panel.sound_effects.append(effects)
                elif 'μƒ· νƒ€μž…:' in line or 'Shot type:' in line:
                    current_panel.scene_type = line.split(':', 1)[1].strip()
        
        if current_panel:
            panels.append(current_panel)
        
        storyboard.panels = panels[:30]  # Limit to 30 panels
        return storyboard

# --- Export functions ---
def export_to_txt(planning_doc: str, storyboard: str, genre: str, title: str = "") -> str:
    """Export webtoon planning and storyboard to TXT format"""
    content = f"{'=' * 50}\n"
    content += f"{title if title else genre + ' μ›Ήνˆ°'}\n"
    content += f"{'=' * 50}\n\n"
    content += f"μž₯λ₯΄: {genre}\n"
    content += f"총 40ν™” 기획\n"
    content += f"{'=' * 50}\n\n"
    
    content += "πŸ“š κΈ°νšμ•ˆ\n\n"
    content += planning_doc
    content += f"\n\n{'=' * 50}\n\n"
    
    content += "🎨 1ν™” μŠ€ν† λ¦¬λ³΄λ“œ (30 νŒ¨λ„)\n\n"
    content += storyboard
    
    return content

def export_to_docx(planning_doc: str, storyboard: str, genre: str, title: str = "") -> bytes:
    """Export webtoon planning and storyboard to DOCX format"""
    if not DOCX_AVAILABLE:
        raise Exception("python-docx is not installed")
    
    doc = Document()
    
    # Title
    doc.add_heading(title if title else f"{genre} μ›Ήνˆ°", 0)
    
    # Info
    doc.add_paragraph(f"μž₯λ₯΄: {genre}")
    doc.add_paragraph("총 40ν™” 기획")
    doc.add_page_break()
    
    # Planning document
    doc.add_heading("πŸ“š κΈ°νšμ•ˆ", 1)
    for line in planning_doc.split('\n'):
        if line.strip():
            if line.startswith('#'):
                doc.add_heading(line.replace('#', '').strip(), 2)
            else:
                doc.add_paragraph(line)
    
    doc.add_page_break()
    
    # Storyboard
    doc.add_heading("🎨 1ν™” μŠ€ν† λ¦¬λ³΄λ“œ (30 νŒ¨λ„)", 1)
    for line in storyboard.split('\n'):
        if line.strip():
            if 'νŒ¨λ„' in line or 'Panel' in line:
                doc.add_heading(line, 2)
            else:
                doc.add_paragraph(line)
    
    # Save to bytes
    bytes_io = io.BytesIO()
    doc.save(bytes_io)
    bytes_io.seek(0)
    return bytes_io.getvalue()

def generate_random_webtoon_theme(genre: str, language: str) -> str:
    """Generate random webtoon theme"""
    templates = {
        "둜맨슀": [
            "재벌 3μ„Έ 상사와 μ‹ μž…μ‚¬μ›μ˜ λΉ„λ°€ 계약연애",
            "고등학ꡐ λ•Œ μ²«μ‚¬λž‘κ³Ό 10λ…„ 만의 재회",
            "λƒ‰ν˜ˆ 검사와 μ—΄ν˜ˆ λ³€ν˜Έμ‚¬μ˜ 법정 둜맨슀"
        ],
        "둜판": [
            "μ•…λ…€λ‘œ λΉ™μ˜ν–ˆλŠ”λ° 1λ…„ ν›„ μ²˜ν˜• μ˜ˆμ •",
            "νšŒκ·€ν•œ ν™©λ…€, 버렀진 μ™•μžμ™€ μ†μž‘λ‹€",
            "κ³„μ•½κ²°ν˜Όν•œ 뢁뢀 κ³΅μž‘μ΄ 집착남이 λ˜μ—ˆλ‹€"
        ],
        "νŒνƒ€μ§€": [
            "FκΈ‰ ν—Œν„°κ°€ SSSκΈ‰ λ„€ν¬λ‘œλ§¨μ„œλ‘œ 각성",
            "100μΈ΅ 탑을 μ—­μ£Όν–‰ν•˜λŠ” νšŒκ·€μž",
            "λ²„κ·Έλ‘œ μ΅œκ°•μ΄ 된 κ²Œμž„ 속 NPC"
        ],
        "ν˜„νŒ": [
            "무λŠ₯λ ₯자인 쀄 μ•Œμ•˜λŠ”λ° SSSκΈ‰ 생산직",
            "게이트 μ†μ—μ„œ 10λ…„, λŒμ•„μ˜¨ μ΅œκ°•μž",
            "ν—Œν„° κ³ λ“±ν•™κ΅μ˜ μˆ¨κ²¨μ§„ λž­ν‚Ή 1μœ„"
        ],
        "λ¬΄ν˜‘": [
            "μ²œν•˜μ œμΌλ¬Έ 막내가 마ꡐ ꡐ주 μ œμžκ°€ λ˜λ‹€",
            "100λ…„ μ „μœΌλ‘œ νšŒκ·€ν•œ ν™”μ‚°νŒŒ μž₯문인",
            "폐급 무곡으둜 μ²œν•˜λ₯Ό μ œνŒ¨ν•˜λ‹€"
        ],
        "슀릴러": [
            "폐ꡐ에 κ°‡νžŒ λ™μ°½νšŒ, ν•œ λͺ…μ”© 사라진닀",
            "νƒ€μž„λ£¨ν”„ 속 연쇄살인범 μ°ΎκΈ°",
            "λ‚΄ λ‚¨νŽΈμ΄ μ‚¬μ΄μ½”νŒ¨μŠ€μ˜€λ‹€"
        ],
        "일상": [
            "편의점 μ•Œλ°”μƒμ˜ μ†Œμ†Œν•œ 일상",
            "30λŒ€ 직μž₯인의 퇴사 μ€€λΉ„ 일기",
            "우리 동넀 κ³ μ–‘μ΄λ“€μ˜ λΉ„λ°€ 회의"
        ],
        "개그": [
            "이세계 μš©μ‚¬μΈλ° μŠ€νƒ―μ΄ μ΄μƒν•˜λ‹€",
            "우리 학ꡐ μ„ μƒλ‹˜μ€ 전직 λ§ˆμ™•",
            "μ’€λΉ„ μ•„ν¬μΉΌλ¦½μŠ€μΈλ° λ‚˜λ§Œ 개그 캐릭터"
        ],
        "슀포츠": [
            "벀치 λ©€λ²„μ—μ„œ μ—μ΄μŠ€κ°€ λ˜κΈ°κΉŒμ§€",
            "μ—¬μž 야ꡬ뢀 μ°½μ„€κΈ°",
            "은퇴 μ„ μˆ˜μ˜ μ½”μΉ˜ 도전기"
        ]
    }
    
    genre_themes = templates.get(genre, templates["둜맨슀"])
    return random.choice(genre_themes)

# --- UI functions ---
def format_planning_display(planning_doc: str) -> str:
    """Format planning document for display"""
    return planning_doc

def format_storyboard_display(storyboard: str) -> str:
    """Format storyboard for display"""
    return storyboard

# --- Gradio interface ---
def create_interface():
    with gr.Blocks(theme=gr.themes.Soft(), title="K-Webtoon Storyboard Generator") as interface:
        gr.HTML("""
        <style>
            .main-header {
                text-align: center;
                margin-bottom: 2rem;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                padding: 2rem;
                border-radius: 15px;
                color: white;
            }
            
            .header-title {
                font-size: 3rem;
                margin-bottom: 1rem;
                text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
            }
            
            .header-subtitle {
                font-size: 1.2rem;
                margin-bottom: 0.5rem;
            }
            
            .header-description {
                margin-bottom: 1.5rem;
            }
        </style>
        
        <div class="main-header">
            <h1 class="header-title">🎨 K-Webtoon Storyboard Generator</h1>
            <p class="header-subtitle">ν•œκ΅­ν˜• μ›Ήνˆ° 기획 및 μŠ€ν† λ¦¬λ³΄λ“œ μžλ™ 생성 μ‹œμŠ€ν…œ</p>
            <p class="header-description">40ν™” 전체 κΈ°νšμ•ˆκ³Ό 1ν™” μŠ€ν† λ¦¬λ³΄λ“œ(30νŒ¨λ„)λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€</p>
        </div>
        """)
        
        # State
        current_session_id = gr.State(None)
        
        with gr.Tab("🎨 μ›Ήνˆ° κΈ°νšν•˜κΈ°"):
            with gr.Group():
                gr.Markdown("### 🎯 μ›Ήνˆ° μ„€μ •")
                
                with gr.Row():
                    with gr.Column(scale=2):
                        genre_select = gr.Radio(
                            choices=list(WEBTOON_GENRES.keys()),
                            value="둜맨슀",
                            label="μž₯λ₯΄ 선택",
                            info="μ›ν•˜λŠ” μž₯λ₯΄λ₯Ό μ„ νƒν•˜μ„Έμš”"
                        )
                        
                        query_input = gr.Textbox(
                            label="μŠ€ν† λ¦¬ μ½˜μ…‰νŠΈ",
                            placeholder="μ›Ήνˆ°μ˜ κΈ°λ³Έ μ„€μ •μ΄λ‚˜ 주제λ₯Ό μž…λ ₯ν•˜μ„Έμš”...",
                            lines=3
                        )
                        
                        with gr.Row():
                            random_btn = gr.Button("🎲 랜덀 ν…Œλ§ˆ", variant="secondary")
                            submit_btn = gr.Button("πŸ“ 기획 μ‹œμž‘", variant="primary", size="lg")
                    
                    with gr.Column(scale=1):
                        language_select = gr.Radio(
                            choices=["Korean", "English"],
                            value="Korean",
                            label="μ–Έμ–΄"
                        )
                        
                        gr.Markdown("""
                        **μž₯λ₯΄λ³„ νŠΉμ§•:**
                        - 둜맨슀: 감정선, 관계 쀑심
                        - 둜판: νšŒκ·€/λΉ™μ˜ νŒνƒ€μ§€
                        - νŒνƒ€μ§€: λͺ¨ν—˜κ³Ό μ„±μž₯
                        - ν˜„νŒ: ν˜„λŒ€ λ°°κ²½ λŠ₯λ ₯λ¬Ό
                        - λ¬΄ν˜‘: 무곡과 볡수
                        - 슀릴러: μ„œμŠ€νŽœμŠ€μ™€ λ°˜μ „
                        - 일상: 곡감과 힐링
                        - 개그: μ›ƒμŒκ³Ό νŒ¨λŸ¬λ””
                        - 슀포츠: μ—΄μ •κ³Ό μ„±μž₯
                        """)
                
                status_text = gr.Textbox(
                    label="μ§„ν–‰ 상황",
                    interactive=False,
                    value="μž₯λ₯΄λ₯Ό μ„ νƒν•˜κ³  μ½˜μ…‰νŠΈλ₯Ό μž…λ ₯ν•˜μ„Έμš”"
                )
            
            # Output
            with gr.Row():
                with gr.Column():
                    planning_display = gr.Markdown("*κΈ°νšμ•ˆμ΄ 여기에 ν‘œμ‹œλ©λ‹ˆλ‹€*")
                
                with gr.Column():
                    storyboard_display = gr.Markdown("*1ν™” μŠ€ν† λ¦¬λ³΄λ“œκ°€ 여기에 ν‘œμ‹œλ©λ‹ˆλ‹€*")
                    
                    with gr.Row():
                        download_format = gr.Radio(
                            choices=["TXT", "DOCX"],
                            value="TXT",
                            label="λ‹€μš΄λ‘œλ“œ ν˜•μ‹"
                        )
                        download_btn = gr.Button("πŸ“₯ λ‹€μš΄λ‘œλ“œ", variant="secondary")
                    
                    download_file = gr.File(visible=False)
        
        with gr.Tab("πŸ“š μ½˜μ…‰νŠΈ μ˜ˆμ‹œ"):
            gr.Markdown("""
            ### μž₯λ₯΄λ³„ 인기 μ½˜μ…‰νŠΈ
            
            **둜맨슀**
            - κ³„μ•½κ²°ν˜Όν•œ 재벌과 ν‰λ²”ν•œ νšŒμ‚¬μ›
            - μ²«μ‚¬λž‘κ³Όμ˜ 운λͺ…적 재회
            - λΌμ΄λ²Œμ—μ„œ 연인이 λ˜κΈ°κΉŒμ§€
            
            **νŒνƒ€μ§€**
            - FκΈ‰μ—μ„œ SSSκΈ‰μœΌλ‘œ 각성
            - νšŒκ·€μžμ˜ 두 번째 기회
            - 버그 μΊλ¦­ν„°μ˜ 세계 정볡
            
            **ν˜„νŒ**
            - μˆ¨κ²¨μ§„ μ΅œκ°•μžμ˜ 일상
            - κ²Œμ΄νŠΈμ™€ ν—Œν„°μ˜ 세계
            - κ°μ„±μž ν•™κ΅μ˜ λΉ„λ°€
            
            **λ¬΄ν˜‘**
            - 천재의 λͺ°λ½κ³Ό λΆ€ν™œ
            - μ •νŒŒμ™€ 마ꡐ의 경계
            - μ „μ„€μ˜ 비급을 μ–»λ‹€
            """)
        
        # Event handlers
        def process_query(query, genre, language, session_id):
            system = WebtoonSystem()
            planning = ""
            storyboard = ""
            
            for planning_content, storyboard_content, status, new_session_id in system.process_webtoon_stream(query, genre, language, session_id):
                # Split the combined output if it contains both planning and storyboard
                if '1ν™” μŠ€ν† λ¦¬λ³΄λ“œ' in storyboard_content:
                    parts = storyboard_content.split('=' * 50)
                    if len(parts) >= 2:
                        planning = parts[0]
                        storyboard = ('=' * 50) + ('=' * 50).join(parts[1:])
                    else:
                        planning = planning_content
                        storyboard = storyboard_content
                else:
                    planning = planning_content
                    storyboard = storyboard_content
                    
                yield planning, storyboard, status, new_session_id
        
        def handle_random_theme(genre, language):
            return generate_random_webtoon_theme(genre, language)
        
        def handle_download(download_format, session_id, planning, storyboard, genre):
            """Handle download request"""
            try:
                title = f"{genre} μ›Ήνˆ°"
                
                if download_format == "TXT":
                    content = export_to_txt(planning, storyboard, genre, title)
                    
                    with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', 
                                                   suffix='.txt', delete=False) as f:
                        f.write(content)
                        return f.name
                
                elif download_format == "DOCX":
                    if not DOCX_AVAILABLE:
                        gr.Warning("DOCX export requires python-docx library")
                        return None
                    
                    content = export_to_docx(planning, storyboard, genre, title)
                    
                    with tempfile.NamedTemporaryFile(mode='wb', suffix='.docx', 
                                                   delete=False) as f:
                        f.write(content)
                        return f.name
                        
            except Exception as e:
                logger.error(f"Download error: {e}")
                gr.Warning(f"λ‹€μš΄λ‘œλ“œ 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
                return None
        
        # Connect events
        submit_btn.click(
            fn=process_query,
            inputs=[query_input, genre_select, language_select, current_session_id],
            outputs=[planning_display, storyboard_display, status_text, current_session_id]
        )
        
        random_btn.click(
            fn=handle_random_theme,
            inputs=[genre_select, language_select],
            outputs=[query_input]
        )
        
        download_btn.click(
            fn=handle_download,
            inputs=[download_format, current_session_id, planning_display, storyboard_display, genre_select],
            outputs=[download_file]
        ).then(
            fn=lambda x: gr.update(visible=True) if x else gr.update(visible=False),
            inputs=[download_file],
            outputs=[download_file]
        )
        
        # Examples
        gr.Examples(
            examples=[
                ["재벌 3μ„Έ 상사와 μ‹ μž…μ‚¬μ›μ˜ λΉ„λ°€ 계약연애", "둜맨슀"],
                ["μ•…λ…€λ‘œ λΉ™μ˜ν–ˆλŠ”λ° 1λ…„ ν›„ μ²˜ν˜• μ˜ˆμ •", "둜판"],
                ["FκΈ‰ ν—Œν„°κ°€ SSSκΈ‰ λ„€ν¬λ‘œλ§¨μ„œλ‘œ 각성", "νŒνƒ€μ§€"],
                ["무λŠ₯λ ₯자인 쀄 μ•Œμ•˜λŠ”λ° SSSκΈ‰ 생산직", "ν˜„νŒ"],
                ["μ²œν•˜μ œμΌλ¬Έ 막내가 마ꡐ ꡐ주 μ œμžκ°€ λ˜λ‹€", "λ¬΄ν˜‘"],
                ["폐ꡐ에 κ°‡νžŒ λ™μ°½νšŒ, ν•œ λͺ…μ”© 사라진닀", "슀릴러"],
                ["편의점 μ•Œλ°”μƒμ˜ μ†Œμ†Œν•œ 일상", "일상"],
                ["이세계 μš©μ‚¬μΈλ° μŠ€νƒ―μ΄ μ΄μƒν•˜λ‹€", "개그"],
                ["벀치 λ©€λ²„μ—μ„œ μ—μ΄μŠ€κ°€ λ˜κΈ°κΉŒμ§€", "슀포츠"]
            ],
            inputs=[query_input, genre_select]
        )
    
    return interface

# Main
if __name__ == "__main__":
    logger.info("K-Webtoon Storyboard Generator Starting...")
    logger.info("=" * 60)
    
    # Environment check
    logger.info(f"API Endpoint: {API_URL}")
    logger.info(f"Model: {MODEL_ID}")
    logger.info(f"Target: {TARGET_EPISODES} episodes, {PANELS_PER_EPISODE} panels per episode")
    logger.info("Genres: " + ", ".join(WEBTOON_GENRES.keys()))
    
    logger.info("=" * 60)
    
    # Initialize database
    logger.info("Initializing database...")
    WebtoonDatabase.init_db()
    logger.info("Database ready.")
    
    # Launch interface
    interface = create_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )