File size: 60,438 Bytes
476b1ae
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1236aa5
 
 
49e7687
 
 
 
 
 
023a9e4
 
 
49e7687
 
 
 
 
 
 
476b1ae
49e7687
 
 
 
 
 
 
476b1ae
 
 
 
 
 
 
 
 
 
 
 
49e7687
 
 
 
 
 
 
 
 
476b1ae
 
 
 
 
 
49e7687
 
 
 
 
 
 
1236aa5
 
 
49e7687
 
 
1e01dd8
49e7687
476b1ae
 
 
 
 
a342866
1e01dd8
 
 
 
1236aa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e01dd8
 
 
 
 
1236aa5
1e01dd8
1236aa5
 
1e01dd8
 
 
 
 
 
 
 
 
 
 
1236aa5
1e01dd8
49e7687
1236aa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49e7687
1e01dd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49e7687
 
 
 
476b1ae
 
 
 
 
49e7687
 
 
 
 
476b1ae
49e7687
 
476b1ae
49e7687
476b1ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1236aa5
476b1ae
 
 
 
 
 
 
 
 
 
 
 
49e7687
 
 
 
476b1ae
 
49e7687
 
476b1ae
 
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476b1ae
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
023a9e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476b1ae
 
 
 
 
 
 
1236aa5
 
1e01dd8
 
 
1236aa5
 
 
49e7687
1e01dd8
49e7687
 
 
1e01dd8
 
 
 
 
 
 
 
a342866
 
 
 
49e7687
 
 
1236aa5
 
 
 
 
 
 
 
1e01dd8
1236aa5
1e01dd8
 
 
 
 
 
 
 
 
 
 
 
1236aa5
49e7687
1236aa5
 
 
49e7687
1e01dd8
49e7687
 
 
1e01dd8
 
 
 
 
 
 
 
a342866
 
 
 
49e7687
 
 
1236aa5
 
 
 
 
 
 
 
1e01dd8
 
 
 
 
 
 
 
 
 
 
 
 
 
1236aa5
49e7687
1236aa5
 
 
 
49e7687
1236aa5
1e01dd8
476b1ae
a342866
1e01dd8
 
1236aa5
1e01dd8
 
 
 
 
 
a342866
476b1ae
a342866
1e01dd8
 
 
 
 
 
 
 
 
a342866
476b1ae
 
 
1236aa5
476b1ae
49e7687
476b1ae
 
1e01dd8
49e7687
1e01dd8
1236aa5
1e01dd8
1236aa5
 
 
 
 
 
 
 
 
476b1ae
 
 
 
 
 
1e01dd8
db70ad9
a342866
1e01dd8
 
 
 
 
 
 
 
 
 
a342866
db70ad9
a342866
1e01dd8
 
 
 
 
 
 
 
 
a342866
49e7687
476b1ae
 
 
 
 
 
 
 
1e01dd8
476b1ae
 
a342866
476b1ae
 
 
 
 
1236aa5
476b1ae
 
 
 
 
 
49e7687
 
476b1ae
49e7687
476b1ae
 
 
1e01dd8
 
 
 
 
 
476b1ae
 
 
49e7687
476b1ae
1236aa5
49e7687
476b1ae
1236aa5
1e01dd8
476b1ae
 
 
1e01dd8
db70ad9
a342866
1e01dd8
 
 
 
a342866
db70ad9
a342866
1e01dd8
 
 
 
a342866
49e7687
476b1ae
 
1236aa5
476b1ae
49e7687
476b1ae
 
 
 
49e7687
476b1ae
 
 
 
 
 
 
 
 
 
 
 
a342866
476b1ae
1e01dd8
476b1ae
 
49e7687
476b1ae
 
49e7687
476b1ae
 
 
49e7687
476b1ae
 
 
 
db70ad9
476b1ae
 
 
 
 
1e01dd8
49e7687
1e01dd8
49e7687
1e01dd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49e7687
476b1ae
1e01dd8
476b1ae
 
 
 
1236aa5
 
1e01dd8
1236aa5
 
 
 
 
 
 
 
 
1e01dd8
db70ad9
a342866
1e01dd8
 
 
 
 
 
a342866
db70ad9
a342866
1e01dd8
 
 
 
 
 
a342866
476b1ae
 
 
 
1236aa5
476b1ae
 
1e01dd8
476b1ae
 
 
 
 
 
 
 
db70ad9
476b1ae
 
 
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a342866
49e7687
 
a342866
 
49e7687
 
 
a342866
 
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476b1ae
49e7687
 
 
 
 
 
 
 
 
 
 
 
a342866
 
49e7687
 
 
a342866
 
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476b1ae
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
023a9e4
1e01dd8
49e7687
023a9e4
 
 
 
 
1e01dd8
023a9e4
 
 
1e01dd8
 
 
 
 
 
49e7687
 
 
 
 
 
 
476b1ae
 
 
 
 
 
 
 
 
 
 
 
 
 
49e7687
 
476b1ae
 
 
 
 
 
 
 
 
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e01dd8
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
023a9e4
49e7687
023a9e4
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
023a9e4
1e01dd8
023a9e4
1e01dd8
 
 
 
 
023a9e4
 
476b1ae
 
 
 
 
 
 
 
 
 
 
 
 
49e7687
1e01dd8
 
 
49e7687
476b1ae
 
 
1e01dd8
476b1ae
 
 
1e01dd8
1236aa5
1e01dd8
476b1ae
 
49e7687
 
1e01dd8
023a9e4
1e01dd8
023a9e4
 
1e01dd8
023a9e4
 
 
49e7687
 
 
023a9e4
 
 
 
 
 
 
 
 
49e7687
023a9e4
1e01dd8
 
 
 
 
 
 
 
 
49e7687
1e01dd8
49e7687
 
 
 
db70ad9
49e7687
 
 
476b1ae
 
49e7687
476b1ae
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
1e01dd8
 
 
 
 
49e7687
1e01dd8
 
 
 
49e7687
1e01dd8
 
 
 
 
49e7687
 
 
 
 
 
 
 
1e01dd8
 
49e7687
1e01dd8
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
023a9e4
1e01dd8
023a9e4
1e01dd8
49e7687
023a9e4
49e7687
 
 
 
 
1e01dd8
023a9e4
 
 
1e01dd8
023a9e4
 
49e7687
 
 
 
 
 
 
023a9e4
1e01dd8
023a9e4
 
 
1e01dd8
023a9e4
1e01dd8
 
023a9e4
49e7687
1e01dd8
 
023a9e4
1e01dd8
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import spaces  # ์ถ”๊ฐ€
import gradio as gr
import os
import asyncio
import torch
import io
import json
import re
import httpx
import tempfile
import wave
import base64
import numpy as np
import soundfile as sf
import subprocess
import shutil
import requests
import logging
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import List, Tuple, Dict, Optional
from pathlib import Path
from threading import Thread
from dotenv import load_dotenv

# PDF processing imports
from langchain_community.document_loaders import PyPDFLoader

# Edge TTS imports
import edge_tts
from pydub import AudioSegment

# OpenAI imports
from openai import OpenAI

# Transformers imports (for legacy local mode)
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    TextIteratorStreamer,
    BitsAndBytesConfig,
)

# Llama CPP imports (for new local mode)
try:
    from llama_cpp import Llama
    from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
    from llama_cpp_agent.providers import LlamaCppPythonProvider
    from llama_cpp_agent.chat_history import BasicChatHistory
    from llama_cpp_agent.chat_history.messages import Roles
    from huggingface_hub import hf_hub_download
    LLAMA_CPP_AVAILABLE = True
except ImportError:
    LLAMA_CPP_AVAILABLE = False

# Spark TTS imports
try:
    from huggingface_hub import snapshot_download
    SPARK_AVAILABLE = True
except:
    SPARK_AVAILABLE = False

# MeloTTS imports (for local mode)
try:
    # unidic ๋‹ค์šด๋กœ๋“œ๋ฅผ ์กฐ๊ฑด๋ถ€๋กœ ์ฒ˜๋ฆฌ
    if not os.path.exists("/usr/local/lib/python3.10/site-packages/unidic"):
        try:
            os.system("python -m unidic download")
        except:
            pass
    from melo.api import TTS as MeloTTS
    MELO_AVAILABLE = True
except:
    MELO_AVAILABLE = False

load_dotenv()

# Brave Search API ์„ค์ •
BRAVE_KEY = os.getenv("BSEARCH_API")
BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"

@dataclass
class ConversationConfig:
    max_words: int = 6000  # 4000์—์„œ 6000์œผ๋กœ ์ฆ๊ฐ€ (1.5๋ฐฐ)
    prefix_url: str = "https://r.jina.ai/"
    api_model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"
    legacy_local_model_name: str = "NousResearch/Hermes-2-Pro-Llama-3-8B"
    # ์ƒˆ๋กœ์šด ๋กœ์ปฌ ๋ชจ๋ธ ์„ค์ •
    local_model_name: str = "Private-BitSix-Mistral-Small-3.1-24B-Instruct-2503.gguf"
    local_model_repo: str = "ginigen/Private-BitSix-Mistral-Small-3.1-24B-Instruct-2503"
    # ํ† ํฐ ์ˆ˜ ์ฆ๊ฐ€
    max_tokens: int = 4500  # 3000์—์„œ 4500์œผ๋กœ ์ฆ๊ฐ€ (1.5๋ฐฐ)
    max_new_tokens: int = 9000  # 6000์—์„œ 9000์œผ๋กœ ์ฆ๊ฐ€ (1.5๋ฐฐ)
    min_conversation_turns: int = 12  # ์ตœ์†Œ ๋Œ€ํ™” ํ„ด ์ˆ˜
    max_conversation_turns: int = 15  # ์ตœ๋Œ€ ๋Œ€ํ™” ํ„ด ์ˆ˜


def brave_search(query: str, count: int = 8, freshness_days: int | None = None):
    """Brave Search API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ตœ์‹  ์ •๋ณด ๊ฒ€์ƒ‰"""
    if not BRAVE_KEY:
        return []
    params = {"q": query, "count": str(count)}
    if freshness_days:
        dt_from = (datetime.utcnow() - timedelta(days=freshness_days)).strftime("%Y-%m-%d")
        params["freshness"] = dt_from
    try:
        r = requests.get(
            BRAVE_ENDPOINT,
            headers={"Accept": "application/json", "X-Subscription-Token": BRAVE_KEY},
            params=params,
            timeout=15
        )
        raw = r.json().get("web", {}).get("results") or []
        return [{
            "title": r.get("title", ""),
            "url": r.get("url", r.get("link", "")),
            "snippet": r.get("description", r.get("text", "")),
            "host": re.sub(r"https?://(www\.)?", "", r.get("url", "")).split("/")[0]
        } for r in raw[:count]]
    except Exception as e:
        logging.error(f"Brave search error: {e}")
        return []

def format_search_results(query: str, for_keyword: bool = False) -> str:
    """๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋ฅผ ํฌ๋งทํŒ…ํ•˜์—ฌ ๋ฐ˜ํ™˜"""
    # ํ‚ค์›Œ๋“œ ๊ฒ€์ƒ‰์˜ ๊ฒฝ์šฐ ๋” ๋งŽ์€ ๊ฒฐ๊ณผ ์‚ฌ์šฉ
    count = 5 if for_keyword else 3
    rows = brave_search(query, count, freshness_days=7 if not for_keyword else None)
    if not rows:
        return ""
    
    results = []
    # ํ‚ค์›Œ๋“œ ๊ฒ€์ƒ‰์˜ ๊ฒฝ์šฐ ๋” ์ƒ์„ธํ•œ ์ •๋ณด ํฌํ•จ
    max_results = 4 if for_keyword else 2
    for r in rows[:max_results]:
        if for_keyword:
            # ํ‚ค์›Œ๋“œ ๊ฒ€์ƒ‰์€ ๋” ๊ธด ์Šค๋‹ˆํŽซ ์‚ฌ์šฉ
            snippet = r['snippet'][:200] + "..." if len(r['snippet']) > 200 else r['snippet']
            results.append(f"**{r['title']}**\n{snippet}\nSource: {r['host']}")
        else:
            # ์ผ๋ฐ˜ ๊ฒ€์ƒ‰์€ ์งง์€ ์Šค๋‹ˆํŽซ
            snippet = r['snippet'][:100] + "..." if len(r['snippet']) > 100 else r['snippet']
            results.append(f"- {r['title']}: {snippet}")
    
    return "\n\n".join(results) + "\n"

def extract_keywords_for_search(text: str, language: str = "English") -> List[str]:
    """ํ…์ŠคํŠธ์—์„œ ๊ฒ€์ƒ‰ํ•  ํ‚ค์›Œ๋“œ ์ถ”์ถœ (๊ฐœ์„ )"""
    # ํ…์ŠคํŠธ ์•ž๋ถ€๋ถ„๋งŒ ์‚ฌ์šฉ (๋„ˆ๋ฌด ๋งŽ์€ ํ…์ŠคํŠธ ์ฒ˜๋ฆฌ ๋ฐฉ์ง€)
    text_sample = text[:500]  
    
    if language == "Korean":
        import re
        # ํ•œ๊ตญ์–ด ๋ช…์‚ฌ ์ถ”์ถœ (2๊ธ€์ž ์ด์ƒ)
        keywords = re.findall(r'[๊ฐ€-ํžฃ]{2,}', text_sample)
        # ์ค‘๋ณต ์ œ๊ฑฐํ•˜๊ณ  ๊ฐ€์žฅ ๊ธด ๋‹จ์–ด 1๊ฐœ๋งŒ ์„ ํƒ
        unique_keywords = list(dict.fromkeys(keywords))
        # ๊ธธ์ด ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๊ณ  ๊ฐ€์žฅ ์˜๋ฏธ์žˆ์„ ๊ฒƒ ๊ฐ™์€ ๋‹จ์–ด ์„ ํƒ
        unique_keywords.sort(key=len, reverse=True)
        return unique_keywords[:1]  # 1๊ฐœ๋งŒ ๋ฐ˜ํ™˜
    else:
        # ์˜์–ด๋Š” ๋Œ€๋ฌธ์ž๋กœ ์‹œ์ž‘ํ•˜๋Š” ๋‹จ์–ด ์ค‘ ๊ฐ€์žฅ ๊ธด ๊ฒƒ 1๊ฐœ
        words = text_sample.split()
        keywords = [word.strip('.,!?;:') for word in words 
                   if len(word) > 4 and word[0].isupper()]
        if keywords:
            return [max(keywords, key=len)]  # ๊ฐ€์žฅ ๊ธด ๋‹จ์–ด 1๊ฐœ
        return []

def search_and_compile_content(keyword: str, language: str = "English") -> str:
    """ํ‚ค์›Œ๋“œ๋กœ ๊ฒ€์ƒ‰ํ•˜์—ฌ ์ฝ˜ํ…์ธ  ์ปดํŒŒ์ผ"""
    if not BRAVE_KEY:
        return f"Search API not available. Using keyword: {keyword}"
    
    # ์–ธ์–ด์— ๋”ฐ๋ฅธ ๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ ์กฐ์ •
    if language == "Korean":
        queries = [
            f"{keyword} ์ตœ์‹  ๋‰ด์Šค",
            f"{keyword} ์ •๋ณด",
            f"{keyword} ํŠธ๋ Œ๋“œ 2024"
        ]
    else:
        queries = [
            f"{keyword} latest news",
            f"{keyword} explained",
            f"{keyword} trends 2024"
        ]
    
    all_content = []
    
    for query in queries:
        results = brave_search(query, count=3)
        for r in results[:2]:  # ๊ฐ ์ฟผ๋ฆฌ๋‹น ์ƒ์œ„ 2๊ฐœ ๊ฒฐ๊ณผ
            content = f"**{r['title']}**\n{r['snippet']}\n"
            all_content.append(content)
    
    if not all_content:
        return f"No search results found for: {keyword}"
    
    # ์ปดํŒŒ์ผ๋œ ์ฝ˜ํ…์ธ  ๋ฐ˜ํ™˜
    compiled = "\n\n".join(all_content)
    
    # ํ‚ค์›Œ๋“œ ๊ธฐ๋ฐ˜ ์†Œ๊ฐœ ์ถ”๊ฐ€
    if language == "Korean":
        intro = f"'{keyword}'์— ๋Œ€ํ•œ ์ตœ์‹  ์ •๋ณด์™€ ํŠธ๋ Œ๋“œ:\n\n"
    else:
        intro = f"Latest information and trends about '{keyword}':\n\n"
    
    return intro + compiled

class UnifiedAudioConverter:
    def __init__(self, config: ConversationConfig):
        self.config = config
        self.llm_client = None
        self.legacy_local_model = None
        self.legacy_tokenizer = None
        # ์ƒˆ๋กœ์šด ๋กœ์ปฌ LLM ๊ด€๋ จ
        self.local_llm = None
        self.local_llm_model = None
        self.melo_models = None
        self.spark_model_dir = None
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        
    def initialize_api_mode(self, api_key: str):
        """Initialize API mode with Together API (now fallback)"""
        self.llm_client = OpenAI(api_key=api_key, base_url="https://api.together.xyz/v1")
        
    @spaces.GPU(duration=120)
    def initialize_local_mode(self):
        """Initialize new local mode with Llama CPP"""
        if not LLAMA_CPP_AVAILABLE:
            raise RuntimeError("Llama CPP dependencies not available. Please install llama-cpp-python and llama-cpp-agent.")
        
        if self.local_llm is None or self.local_llm_model != self.config.local_model_name:
            try:
                # ๋ชจ๋ธ ๋‹ค์šด๋กœ๋“œ
                model_path = hf_hub_download(
                    repo_id=self.config.local_model_repo,
                    filename=self.config.local_model_name,
                    local_dir="./models"
                )
                
                model_path_local = os.path.join("./models", self.config.local_model_name)
                
                if not os.path.exists(model_path_local):
                    raise RuntimeError(f"Model file not found at {model_path_local}")
                
                # Llama ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
                self.local_llm = Llama(
                    model_path=model_path_local,
                    flash_attn=True,
                    n_gpu_layers=81 if torch.cuda.is_available() else 0,
                    n_batch=1024,
                    n_ctx=16384,
                )
                self.local_llm_model = self.config.local_model_name
                print(f"Local LLM initialized: {model_path_local}")
                
            except Exception as e:
                print(f"Failed to initialize local LLM: {e}")
                raise RuntimeError(f"Failed to initialize local LLM: {e}")

    @spaces.GPU(duration=60)
    def initialize_legacy_local_mode(self):
        """Initialize legacy local mode with Hugging Face model (fallback)"""
        if self.legacy_local_model is None:
            quantization_config = BitsAndBytesConfig(
                load_in_4bit=True, 
                bnb_4bit_compute_dtype=torch.float16
            )
            self.legacy_local_model = AutoModelForCausalLM.from_pretrained(
                self.config.legacy_local_model_name, 
                quantization_config=quantization_config
            )
            self.legacy_tokenizer = AutoTokenizer.from_pretrained(
                self.config.legacy_local_model_name,
                revision='8ab73a6800796d84448bc936db9bac5ad9f984ae'
            )

    def initialize_spark_tts(self):
        """Initialize Spark TTS model by downloading if needed"""
        if not SPARK_AVAILABLE:
            raise RuntimeError("Spark TTS dependencies not available")
        
        model_dir = "pretrained_models/Spark-TTS-0.5B"
        
        # Check if model exists, if not download it
        if not os.path.exists(model_dir):
            print("Downloading Spark-TTS model...")
            try:
                os.makedirs("pretrained_models", exist_ok=True)
                snapshot_download(
                    "SparkAudio/Spark-TTS-0.5B", 
                    local_dir=model_dir
                )
                print("Spark-TTS model downloaded successfully")
            except Exception as e:
                raise RuntimeError(f"Failed to download Spark-TTS model: {e}")
        
        self.spark_model_dir = model_dir
        
        # Check if we have the CLI inference script
        if not os.path.exists("cli/inference.py"):
            print("Warning: Spark-TTS CLI not found. Please clone the Spark-TTS repository.")

    @spaces.GPU(duration=60)
    def initialize_melo_tts(self):
        """Initialize MeloTTS models"""        
        if MELO_AVAILABLE and self.melo_models is None:
            self.melo_models = {"EN": MeloTTS(language="EN", device=self.device)}

    def fetch_text(self, url: str) -> str:
        """Fetch text content from URL"""
        if not url:
            raise ValueError("URL cannot be empty")
            
        if not url.startswith("http://") and not url.startswith("https://"):
            raise ValueError("URL must start with 'http://' or 'https://'")

        full_url = f"{self.config.prefix_url}{url}"
        try:
            response = httpx.get(full_url, timeout=60.0)
            response.raise_for_status()
            return response.text
        except httpx.HTTPError as e:
            raise RuntimeError(f"Failed to fetch URL: {e}")

    def extract_text_from_pdf(self, pdf_file) -> str:
        """Extract text content from PDF file"""
        try:
            # Gradio returns file path, not file object
            if isinstance(pdf_file, str):
                pdf_path = pdf_file
            else:
                # If it's a file object (shouldn't happen with Gradio)
                with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
                    tmp_file.write(pdf_file.read())
                    pdf_path = tmp_file.name
            
            # PDF ๋กœ๋“œ ๋ฐ ํ…์ŠคํŠธ ์ถ”์ถœ
            loader = PyPDFLoader(pdf_path)
            pages = loader.load()
            
            # ๋ชจ๋“  ํŽ˜์ด์ง€์˜ ํ…์ŠคํŠธ๋ฅผ ๊ฒฐํ•ฉ
            text = "\n".join([page.page_content for page in pages])
            
            # ์ž„์‹œ ํŒŒ์ผ์ธ ๊ฒฝ์šฐ ์‚ญ์ œ
            if not isinstance(pdf_file, str) and os.path.exists(pdf_path):
                os.unlink(pdf_path)
            
            return text
        except Exception as e:
            raise RuntimeError(f"Failed to extract text from PDF: {e}")

    def _get_messages_formatter_type(self, model_name):
        """Get appropriate message formatter for the model"""
        if "Mistral" in model_name or "BitSix" in model_name:
            return MessagesFormatterType.CHATML
        else:
            return MessagesFormatterType.LLAMA_3


    def _build_prompt(self, text: str, language: str = "English", search_context: str = "") -> str:
        """Build prompt for conversation generation with enhanced radio talk show style"""
        # ํ…์ŠคํŠธ ๊ธธ์ด ์ œํ•œ
        max_text_length = 4500 if search_context else 6000
        if len(text) > max_text_length:
            text = text[:max_text_length] + "..."
        
        if language == "Korean":
            # ๋Œ€ํ™” ํ…œํ”Œ๋ฆฟ์„ ๋” ๋งŽ์€ ํ„ด์œผ๋กœ ํ™•์žฅ
            template = """
            {
                "conversation": [
                    {"speaker": "์ค€์ˆ˜", "text": ""},
                    {"speaker": "๋ฏผํ˜ธ", "text": ""},
                    {"speaker": "์ค€์ˆ˜", "text": ""},
                    {"speaker": "๋ฏผํ˜ธ", "text": ""},
                    {"speaker": "์ค€์ˆ˜", "text": ""},
                    {"speaker": "๋ฏผํ˜ธ", "text": ""},
                    {"speaker": "์ค€์ˆ˜", "text": ""},
                    {"speaker": "๋ฏผํ˜ธ", "text": ""},
                    {"speaker": "์ค€์ˆ˜", "text": ""},
                    {"speaker": "๋ฏผํ˜ธ", "text": ""},
                    {"speaker": "์ค€์ˆ˜", "text": ""},
                    {"speaker": "๋ฏผํ˜ธ", "text": ""}
                ]
            }
            """
            
            context_part = ""
            if search_context:
                context_part = f"# ์ตœ์‹  ๊ด€๋ จ ์ •๋ณด:\n{search_context}\n"
        
            base_prompt = (
                f"# ์›๋ณธ ์ฝ˜ํ…์ธ :\n{text}\n\n"
                f"{context_part}"
                f"์œ„ ๋‚ด์šฉ์œผ๋กœ ๋ผ๋””์˜ค ๋Œ€๋‹ด ํ”„๋กœ๊ทธ๋žจ ๋Œ€๋ณธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.\n\n"
                f"## ํ•ต์‹ฌ ์ง€์นจ:\n"
                f"1. **๋Œ€ํ™” ์Šคํƒ€์ผ**: ์‹ค์ œ ๋ผ๋””์˜ค ๋Œ€๋‹ด์ฒ˜๋Ÿผ ์•„์ฃผ ์ž์—ฐ์Šค๋Ÿฝ๊ณ  ํŽธ์•ˆํ•œ ๊ตฌ์–ด์ฒด ์‚ฌ์šฉ\n"
                f"2. **ํ™”์ž ์—ญํ• **:\n"
                f"   - ์ค€์ˆ˜: ์ง„ํ–‰์ž/ํ˜ธ์ŠคํŠธ (์ฃผ๋กœ ์งˆ๋ฌธํ•˜๊ณ  ๋Œ€ํ™”๋ฅผ ์ด๋Œ์–ด๊ฐ)\n"
                f"   - ๋ฏผํ˜ธ: ์ „๋ฌธ๊ฐ€ (์งˆ๋ฌธ์— ๋‹ตํ•˜๊ณ  ์„ค๋ช…ํ•จ)\n"
                f"3. **๋Œ€ํ™” ํŒจํ„ด**:\n"
                f"   - ์ค€์ˆ˜๋Š” ์ฃผ๋กœ ์งง์€ ์งˆ๋ฌธ์ด๋‚˜ ๋ฆฌ์•ก์…˜ (\"์•„, ๊ทธ๋ ‡๊ตฐ์š”\", \"ํฅ๋ฏธ๋กญ๋„ค์š”\", \"๊ทธ๋Ÿผ ~๋Š” ์–ด๋–ค๊ฐ€์š”?\")\n"
                f"   - ๋ฏผํ˜ธ๋Š” 1-2๋ฌธ์žฅ์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋‹ต๋ณ€\n"
                f"   - ์ ˆ๋Œ€ ํ•œ ์‚ฌ๋žŒ์ด 3๋ฌธ์žฅ ์ด์ƒ ์—ฐ์†์œผ๋กœ ๋งํ•˜์ง€ ์•Š์Œ\n"
                f"4. **์ž์—ฐ์Šค๋Ÿฌ์›€**:\n"
                f"   - \"์Œ...\", \"์•„...\", \"๋„ค,\" ๊ฐ™์€ ์ถ”์ž„์ƒˆ ์‚ฌ์šฉ\n"
                f"   - ๋•Œ๋กœ๋Š” ์ƒ๋Œ€๋ฐฉ ๋ง์— ์งง๊ฒŒ ๋ฐ˜์‘ (\"๋งž์•„์š”\", \"๊ทธ๋ ‡์ฃ \")\n"
                f"5. **ํ•„์ˆ˜ ๊ทœ์น™**: ์„œ๋กœ ์กด๋Œ“๋ง ์‚ฌ์šฉ, 12-15ํšŒ ๋Œ€ํ™” ๊ตํ™˜\n\n"
                f"JSON ํ˜•์‹์œผ๋กœ๋งŒ ๋ฐ˜ํ™˜:\n{template}"
            )
            
            return base_prompt
            
        else:
            # ์˜์–ด ํ…œํ”Œ๋ฆฟ๋„ ํ™•์žฅ
            template = """
            {
                "conversation": [
                    {"speaker": "Alex", "text": ""},
                    {"speaker": "Jordan", "text": ""},
                    {"speaker": "Alex", "text": ""},
                    {"speaker": "Jordan", "text": ""},
                    {"speaker": "Alex", "text": ""},
                    {"speaker": "Jordan", "text": ""},
                    {"speaker": "Alex", "text": ""},
                    {"speaker": "Jordan", "text": ""},
                    {"speaker": "Alex", "text": ""},
                    {"speaker": "Jordan", "text": ""},
                    {"speaker": "Alex", "text": ""},
                    {"speaker": "Jordan", "text": ""}
                ]
            }
            """
            
            context_part = ""
            if search_context:
                context_part = f"# Latest Information:\n{search_context}\n"
            
            base_prompt = (
                f"# Content:\n{text}\n\n"
                f"{context_part}"
                f"Create a natural radio talk show conversation.\n\n"
                f"## Key Guidelines:\n"
                f"1. **Style**: Natural, conversational English like a real radio show\n"
                f"2. **Roles**:\n"
                f"   - Alex: Host (asks questions, guides conversation)\n"
                f"   - Jordan: Expert (answers, explains)\n"
                f"3. **Pattern**:\n"
                f"   - Alex mostly asks short questions or reacts (\"I see\", \"Interesting\", \"What about...?\")\n"
                f"   - Jordan gives brief 1-2 sentence answers\n"
                f"   - Never more than 2-3 sentences per turn\n"
                f"4. **Natural flow**:\n"
                f"   - Use fillers like \"Well,\" \"You know,\" \"Actually,\"\n"
                f"   - Short reactions (\"Right\", \"Exactly\")\n"
                f"5. **Length**: 12-15 exchanges total\n\n"
                f"Return JSON only:\n{template}"
            )
            
            return base_prompt



    def _build_messages_for_local(self, text: str, language: str = "English", search_context: str = "") -> List[Dict]:
        """Build messages for local LLM with enhanced radio talk show style"""
        if language == "Korean":
            system_message = (
                "๋‹น์‹ ์€ ํ•œ๊ตญ ์ตœ๊ณ ์˜ ๋ผ๋””์˜ค ๋Œ€๋‹ด ํ”„๋กœ๊ทธ๋žจ ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. "
                "์‹ค์ œ ๋ผ๋””์˜ค ๋ฐฉ์†ก์ฒ˜๋Ÿผ ์ž์—ฐ์Šค๋Ÿฝ๊ณ  ์ƒ๋™๊ฐ ์žˆ๋Š” ๋Œ€ํ™”๋ฅผ ๋งŒ๋“ค์–ด๋ƒ…๋‹ˆ๋‹ค.\n\n"
                "ํ•ต์‹ฌ ์›์น™:\n"
                "1. ๋ผ๋””์˜ค ์ง„ํ–‰์ž(์ค€์ˆ˜)๋Š” ์ฃผ๋กœ ์งง์€ ์งˆ๋ฌธ๊ณผ ๋ฆฌ์•ก์…˜์œผ๋กœ ๋Œ€ํ™”๋ฅผ ์ด๋Œ์–ด๊ฐ‘๋‹ˆ๋‹ค\n"
                "2. ์ „๋ฌธ๊ฐ€(๋ฏผํ˜ธ)๋Š” ์งˆ๋ฌธ์— ๊ฐ„๊ฒฐํ•˜๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋‹ตํ•ฉ๋‹ˆ๋‹ค\n"
                "3. ํ•œ ๋ฒˆ์— ๋„ˆ๋ฌด ๋งŽ์€ ์ •๋ณด๋ฅผ ์ „๋‹ฌํ•˜์ง€ ์•Š๊ณ , ๋Œ€ํ™”๋ฅผ ํ†ตํ•ด ์ ์ง„์ ์œผ๋กœ ํ’€์–ด๊ฐ‘๋‹ˆ๋‹ค\n"
                "4. \"์Œ...\", \"์•„...\", \"๋„ค,\" ๋“ฑ ์ž์—ฐ์Šค๋Ÿฌ์šด ๊ตฌ์–ด์ฒด ํ‘œํ˜„์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค\n"
                "5. ์ฒญ์ทจ์ž๊ฐ€ ๋ผ๋””์˜ค๋ฅผ ๋“ฃ๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ๋ชฐ์ž…ํ•  ์ˆ˜ ์žˆ๋„๋ก ์ƒ์ƒํ•˜๊ฒŒ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค\n"
                "6. ๋ฐ˜๋“œ์‹œ ์„œ๋กœ ์กด๋Œ“๋ง์„ ์‚ฌ์šฉํ•˜๋ฉฐ, ์ •์ค‘ํ•˜๋ฉด์„œ๋„ ์นœ๊ทผํ•œ ํ†ค์„ ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค"
            )
        else:
            system_message = (
                "You are an expert radio talk show scriptwriter who creates engaging, "
                "natural conversations that sound like real radio broadcasts.\n\n"
                "Key principles:\n"
                "1. The host (Alex) mainly asks short questions and gives reactions to guide the conversation\n"
                "2. The expert (Jordan) answers concisely and clearly\n"
                "3. Information is revealed gradually through dialogue, not in long monologues\n"
                "4. Use natural speech patterns with fillers like 'Well,' 'You know,' etc.\n"
                "5. Make it sound like an actual radio show that listeners would enjoy\n"
                "6. Keep each turn brief - no more than 2-3 sentences"
            )
        
        return [
            {"role": "system", "content": system_message},
            {"role": "user", "content": self._build_prompt(text, language, search_context)}
        ]

    @spaces.GPU(duration=120)
    def extract_conversation_local(self, text: str, language: str = "English", progress=None) -> Dict:
        """Extract conversation using new local LLM with enhanced search and style"""
        try:
            # ๊ฒ€์ƒ‰ ์ปจํ…์ŠคํŠธ ์ƒ์„ฑ (ํ‚ค์›Œ๋“œ ๊ธฐ๋ฐ˜์ด ์•„๋‹Œ ๊ฒฝ์šฐ)
            search_context = ""
            if BRAVE_KEY and not text.startswith("Keyword-based content:"):
                try:
                    keywords = extract_keywords_for_search(text, language)
                    if keywords:
                        search_query = keywords[0] if language == "Korean" else f"{keywords[0]} latest news"
                        search_context = format_search_results(search_query)
                        print(f"Search context added for: {search_query}")
                except Exception as e:
                    print(f"Search failed, continuing without context: {e}")
            
            # ๋จผ์ € ์ƒˆ๋กœ์šด ๋กœ์ปฌ LLM ์‹œ๋„
            self.initialize_local_mode()
            
            chat_template = self._get_messages_formatter_type(self.config.local_model_name)
            provider = LlamaCppPythonProvider(self.local_llm)

            # ๊ฐ•ํ™”๋œ ๋ผ๋””์˜ค ์Šคํƒ€์ผ ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€
            if language == "Korean":
                system_message = (
                    "๋‹น์‹ ์€ ํ•œ๊ตญ์˜ ์ธ๊ธฐ ๋ผ๋””์˜ค ๋Œ€๋‹ด ํ”„๋กœ๊ทธ๋žจ ์ „๋ฌธ ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. "
                    "์ฒญ์ทจ์ž๋“ค์ด ์‹ค์ œ ๋ผ๋””์˜ค๋ฅผ ๋“ฃ๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ๋ชฐ์ž…ํ•  ์ˆ˜ ์žˆ๋Š” ์ž์—ฐ์Šค๋Ÿฌ์šด ๋Œ€ํ™”๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค.\n\n"
                    "์ž‘์„ฑ ๊ทœ์น™:\n"
                    "1. ์ง„ํ–‰์ž(์ค€์ˆ˜)๋Š” ์ฃผ๋กœ ์งง์€ ์งˆ๋ฌธ์œผ๋กœ ๋Œ€ํ™”๋ฅผ ์ด๋Œ์–ด๊ฐ€์„ธ์š” (\"๊ทธ๋ ‡๊ตฐ์š”\", \"์–ด๋–ค ์ ์ด ํŠน๋ณ„ํ•œ๊ฐ€์š”?\", \"์ฒญ์ทจ์ž๋ถ„๋“ค์ด ๊ถ๊ธˆํ•ดํ•˜์‹ค ๊ฒƒ ๊ฐ™์€๋ฐ์š”\")\n"
                    "2. ์ „๋ฌธ๊ฐ€(๋ฏผํ˜ธ)๋Š” 1-2๋ฌธ์žฅ์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋‹ต๋ณ€ํ•˜์„ธ์š”\n"
                    "3. ์ ˆ๋Œ€ ํ•œ ์‚ฌ๋žŒ์ด 3๋ฌธ์žฅ ์ด์ƒ ์—ฐ์†์œผ๋กœ ๋งํ•˜์ง€ ๋งˆ์„ธ์š”\n"
                    "4. ๊ตฌ์–ด์ฒด์™€ ์ถ”์ž„์ƒˆ๋ฅผ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ์‚ฌ์šฉํ•˜์„ธ์š”\n"
                    "5. ๋ฐ˜๋“œ์‹œ ์„œ๋กœ ์กด๋Œ“๋ง์„ ์‚ฌ์šฉํ•˜์„ธ์š”\n"
                    "6. 12-15ํšŒ์˜ ๋Œ€ํ™” ๊ตํ™˜์œผ๋กœ ๊ตฌ์„ฑํ•˜์„ธ์š”\n"
                    "7. JSON ํ˜•์‹์œผ๋กœ๋งŒ ์‘๋‹ตํ•˜์„ธ์š”"
                )
            else:
                system_message = (
                    "You are a professional radio talk show scriptwriter creating engaging, "
                    "natural conversations that sound like real radio broadcasts.\n\n"
                    "Writing rules:\n"
                    "1. Host (Alex) mainly asks short questions to guide the conversation (\"I see\", \"What makes it special?\", \"Our listeners might wonder...\")\n"
                    "2. Expert (Jordan) answers in 1-2 concise sentences\n"
                    "3. Never have one person speak more than 2-3 sentences at once\n"
                    "4. Use natural speech patterns and fillers\n"
                    "5. Create 12-15 conversation exchanges\n"
                    "6. Respond only in JSON format"
                )

            agent = LlamaCppAgent(
                provider,
                system_prompt=system_message,
                predefined_messages_formatter_type=chat_template,
                debug_output=False
            )
            
            settings = provider.get_provider_default_settings()
            settings.temperature = 0.85  # ์•ฝ๊ฐ„ ๋†’์—ฌ์„œ ๋” ์ž์—ฐ์Šค๋Ÿฌ์šด ๋Œ€ํ™” ์ƒ์„ฑ
            settings.top_k = 40
            settings.top_p = 0.95
            settings.max_tokens = self.config.max_tokens  # ์ฆ๊ฐ€๋œ ํ† ํฐ ์ˆ˜ ์‚ฌ์šฉ
            settings.repeat_penalty = 1.1
            settings.stream = False

            messages = BasicChatHistory()
            
            prompt = self._build_prompt(text, language, search_context)
            response = agent.get_chat_response(
                prompt,
                llm_sampling_settings=settings,
                chat_history=messages,
                returns_streaming_generator=False,
                print_output=False
            )

            # JSON ํŒŒ์‹ฑ
            pattern = r"\{(?:[^{}]|(?:\{[^{}]*\}))*\}"
            json_match = re.search(pattern, response)
            
            if json_match:
                conversation_data = json.loads(json_match.group())
                # ๋Œ€ํ™” ๊ธธ์ด ํ™•์ธ ๋ฐ ์กฐ์ •
                if len(conversation_data["conversation"]) < self.config.min_conversation_turns:
                    print(f"Conversation too short ({len(conversation_data['conversation'])} turns), regenerating...")
                    # ์žฌ์‹œ๋„ ๋กœ์ง ์ถ”๊ฐ€ ๊ฐ€๋Šฅ
                return conversation_data
            else:
                raise ValueError("No valid JSON found in local LLM response")
                
        except Exception as e:
            print(f"Local LLM failed: {e}, falling back to legacy local method")
            return self.extract_conversation_legacy_local(text, language, progress, search_context)

    @spaces.GPU(duration=120)
    def extract_conversation_legacy_local(self, text: str, language: str = "English", progress=None, search_context: str = "") -> Dict:
        """Extract conversation using legacy local model with enhanced style"""
        try:
            self.initialize_legacy_local_mode()
            
            # ๊ฐ•ํ™”๋œ ๋ผ๋””์˜ค ์Šคํƒ€์ผ ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€
            if language == "Korean":
                system_message = (
                    "๋‹น์‹ ์€ ๋ผ๋””์˜ค ๋Œ€๋‹ด ํ”„๋กœ๊ทธ๋žจ ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. "
                    "์ง„ํ–‰์ž(์ค€์ˆ˜)๋Š” ์งง์€ ์งˆ๋ฌธ์œผ๋กœ, ์ „๋ฌธ๊ฐ€(๋ฏผํ˜ธ)๋Š” ๊ฐ„๊ฒฐํ•œ ๋‹ต๋ณ€์œผ๋กœ "
                    "์ž์—ฐ์Šค๋Ÿฌ์šด ๋Œ€ํ™”๋ฅผ ๋งŒ๋“œ์„ธ์š”. ์„œ๋กœ ์กด๋Œ“๋ง์„ ์‚ฌ์šฉํ•˜๊ณ , "
                    "ํ•œ ๋ฒˆ์— 2-3๋ฌธ์žฅ ์ด๋‚ด๋กœ ๋งํ•˜์„ธ์š”. 12-15ํšŒ ๋Œ€ํ™” ๊ตํ™˜์œผ๋กœ ๊ตฌ์„ฑํ•˜์„ธ์š”."
                )
            else:
                system_message = (
                    "You are a radio talk show scriptwriter. "
                    "Create natural dialogue where the host (Alex) asks short questions "
                    "and the expert (Jordan) gives brief answers. "
                    "Keep each turn to 2-3 sentences max. Create 12-15 exchanges."
                )

            chat = [
                {"role": "system", "content": system_message},
                {"role": "user", "content": self._build_prompt(text, language, search_context)}
            ]

            terminators = [
                self.legacy_tokenizer.eos_token_id,
                self.legacy_tokenizer.convert_tokens_to_ids("<|eot_id|>")
            ]

            messages = self.legacy_tokenizer.apply_chat_template(
                chat, tokenize=False, add_generation_prompt=True
            )
            model_inputs = self.legacy_tokenizer([messages], return_tensors="pt").to(self.device)
            
            streamer = TextIteratorStreamer(
                self.legacy_tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
            )
            
            generate_kwargs = dict(
                model_inputs,
                streamer=streamer,
                max_new_tokens=self.config.max_new_tokens,  # ์ฆ๊ฐ€๋œ ํ† ํฐ ์ˆ˜ ์‚ฌ์šฉ
                do_sample=True,
                temperature=0.85,
                eos_token_id=terminators,
            )

            t = Thread(target=self.legacy_local_model.generate, kwargs=generate_kwargs)
            t.start()

            partial_text = ""
            for new_text in streamer:
                partial_text += new_text

            pattern = r"\{(?:[^{}]|(?:\{[^{}]*\}))*\}"
            json_match = re.search(pattern, partial_text)
            
            if json_match:
                return json.loads(json_match.group())
            else:
                raise ValueError("No valid JSON found in legacy local response")
                
        except Exception as e:
            print(f"Legacy local model also failed: {e}")
            # Return enhanced default template
            if language == "Korean":
                return self._get_default_korean_conversation()
            else:
                return self._get_default_english_conversation()

    def _get_default_korean_conversation(self) -> Dict:
        """๋” ๊ธด ๊ธฐ๋ณธ ํ•œ๊ตญ์–ด ๋Œ€ํ™” ํ…œํ”Œ๋ฆฟ"""
        return {
            "conversation": [
                {"speaker": "์ค€์ˆ˜", "text": "์•ˆ๋…•ํ•˜์„ธ์š”, ์—ฌ๋Ÿฌ๋ถ„! ์˜ค๋Š˜๋„ ์ €ํฌ ํŒŸ์บ์ŠคํŠธ๋ฅผ ์ฐพ์•„์ฃผ์…”์„œ ์ •๋ง ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค."},
                {"speaker": "๋ฏผํ˜ธ", "text": "๋„ค, ์•ˆ๋…•ํ•˜์„ธ์š”! ์˜ค๋Š˜ ์ •๋ง ํฅ๋ฏธ๋กœ์šด ์ฃผ์ œ๋ฅผ ์ค€๋น„ํ–ˆ์Šต๋‹ˆ๋‹ค."},
                {"speaker": "์ค€์ˆ˜", "text": "์•„, ๊ทธ๋ž˜์š”? ์–ด๋–ค ๋‚ด์šฉ์ธ์ง€ ์ •๋ง ๊ถ๊ธˆํ•œ๋ฐ์š”?"},
                {"speaker": "๋ฏผํ˜ธ", "text": "์˜ค๋Š˜์€ ์ตœ๊ทผ ๋งŽ์€ ๋ถ„๋“ค์ด ๊ด€์‹ฌ์„ ๊ฐ€์ง€๊ณ  ๊ณ„์‹  ์ฃผ์ œ์— ๋Œ€ํ•ด ์ด์•ผ๊ธฐํ•ด๋ณผ๊นŒ ํ•ด์š”."},
                {"speaker": "์ค€์ˆ˜", "text": "์Œ, ์š”์ฆ˜ ์ •๋ง ํ™”์ œ๊ฐ€ ๋˜๊ณ  ์žˆ์ฃ . ๊ตฌ์ฒด์ ์œผ๋กœ ์–ด๋–ค ์ธก๋ฉด์„ ๋‹ค๋ฃฐ ์˜ˆ์ •์ด์‹ ๊ฐ€์š”?"},
                {"speaker": "๋ฏผํ˜ธ", "text": "๋„ค, ๋จผ์ € ๊ธฐ๋ณธ์ ์ธ ๊ฐœ๋…๋ถ€ํ„ฐ ์ฐจ๊ทผ์ฐจ๊ทผ ์„ค๋ช…๋“œ๋ฆฌ๊ณ , ์‹ค์ƒํ™œ์— ์–ด๋–ป๊ฒŒ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์•Œ์•„๋ณผ๊ฒŒ์š”."},
                {"speaker": "์ค€์ˆ˜", "text": "์ข‹์•„์š”! ์ฒญ์ทจ์ž๋ถ„๋“ค๋„ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์„ค๋ช…ํ•ด์ฃผ์‹ค ๊ฑฐ์ฃ ?"},
                {"speaker": "๋ฏผํ˜ธ", "text": "๋ฌผ๋ก ์ด์ฃ . ์ตœ๋Œ€ํ•œ ์‰ฝ๊ณ  ์žฌ๋ฏธ์žˆ๊ฒŒ ํ’€์–ด์„œ ์„ค๋ช…๋“œ๋ฆด๊ฒŒ์š”."},
                {"speaker": "์ค€์ˆ˜", "text": "๊ทธ๋Ÿผ ๋ณธ๊ฒฉ์ ์œผ๋กœ ์‹œ์ž‘ํ•ด๋ณผ๊นŒ์š”?"},
                {"speaker": "๋ฏผํ˜ธ", "text": "๋„ค, ์ข‹์Šต๋‹ˆ๋‹ค. ์šฐ์„  ์ด ์ฃผ์ œ๊ฐ€ ์™œ ์ค‘์š”ํ•œ์ง€๋ถ€ํ„ฐ ๋ง์”€๋“œ๋ฆด๊ฒŒ์š”."},
                {"speaker": "์ค€์ˆ˜", "text": "์•„, ๋งž์•„์š”. ๊ทธ ๋ถ€๋ถ„์ด ์ •๋ง ์ค‘์š”ํ•˜์ฃ ."},
                {"speaker": "๋ฏผํ˜ธ", "text": "์ตœ๊ทผ ์—ฐ๊ตฌ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ์ •๋ง ๋†€๋ผ์šด ๋ฐœ๊ฒฌ๋“ค์ด ๋งŽ์•˜์–ด์š”."}
            ]
        }

    def _get_default_english_conversation(self) -> Dict:
        """Enhanced default English conversation template"""
        return {
            "conversation": [
                {"speaker": "Alex", "text": "Welcome everyone to our podcast! We have a fascinating topic today."},
                {"speaker": "Jordan", "text": "Thanks, Alex. I'm excited to dive into this subject with our listeners."},
                {"speaker": "Alex", "text": "So, what makes this topic particularly relevant right now?"},
                {"speaker": "Jordan", "text": "Well, there have been some significant developments recently that everyone should know about."},
                {"speaker": "Alex", "text": "Interesting! Can you break it down for us?"},
                {"speaker": "Jordan", "text": "Absolutely. Let me start with the basics and build from there."},
                {"speaker": "Alex", "text": "That sounds perfect. Our listeners will appreciate that approach."},
                {"speaker": "Jordan", "text": "So, first, let's understand what we're really talking about here."},
                {"speaker": "Alex", "text": "Right, the fundamentals are crucial."},
                {"speaker": "Jordan", "text": "Exactly. And once we grasp that, the rest becomes much clearer."},
                {"speaker": "Alex", "text": "I'm already learning something new! What's next?"},
                {"speaker": "Jordan", "text": "Now, here's where it gets really interesting..."}
            ]
        }

    def extract_conversation_api(self, text: str, language: str = "English") -> Dict:
        """Extract conversation using API with enhanced radio style"""
        if not self.llm_client:
            raise RuntimeError("API mode not initialized")

        try:
            # ๊ฒ€์ƒ‰ ์ปจํ…์ŠคํŠธ ์ƒ์„ฑ
            search_context = ""
            if BRAVE_KEY and not text.startswith("Keyword-based content:"):
                try:
                    keywords = extract_keywords_for_search(text, language)
                    if keywords:
                        search_query = keywords[0] if language == "Korean" else f"{keywords[0]} latest news"
                        search_context = format_search_results(search_query)
                        print(f"Search context added for: {search_query}")
                except Exception as e:
                    print(f"Search failed, continuing without context: {e}")

            # ๊ฐ•ํ™”๋œ ๋ผ๋””์˜ค ์Šคํƒ€์ผ ํ”„๋กฌํ”„ํŠธ
            if language == "Korean":
                system_message = (
                    "๋‹น์‹ ์€ ํ•œ๊ตญ์˜ ์ธ๊ธฐ ๋ผ๋””์˜ค ๋Œ€๋‹ด ํ”„๋กœ๊ทธ๋žจ ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. "
                    "์‹ค์ œ ๋ผ๋””์˜ค ๋ฐฉ์†ก์ฒ˜๋Ÿผ ์ž์—ฐ์Šค๋Ÿฝ๊ณ  ํŽธ์•ˆํ•œ ๋Œ€ํ™”๋ฅผ ๋งŒ๋“œ์„ธ์š”.\n"
                    "์ค€์ˆ˜(์ง„ํ–‰์ž)๋Š” ์ฃผ๋กœ ์งง์€ ์งˆ๋ฌธ๊ณผ ๋ฆฌ์•ก์…˜์œผ๋กœ ๋Œ€ํ™”๋ฅผ ์ด๋Œ๊ณ , "
                    "๋ฏผํ˜ธ(์ „๋ฌธ๊ฐ€)๋Š” 1-2๋ฌธ์žฅ์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋‹ต๋ณ€ํ•ฉ๋‹ˆ๋‹ค. "
                    "๊ตฌ์–ด์ฒด์™€ ์ถ”์ž„์ƒˆ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ , ๋ฐ˜๋“œ์‹œ ์„œ๋กœ ์กด๋Œ“๋ง์„ ์‚ฌ์šฉํ•˜์„ธ์š”. "
                    "12-15ํšŒ์˜ ๋Œ€ํ™” ๊ตํ™˜์œผ๋กœ ๊ตฌ์„ฑํ•˜์„ธ์š”."
                )
            else:
                system_message = (
                    "You are a professional radio talk show scriptwriter. "
                    "Create natural, engaging dialogue like a real radio broadcast. "
                    "Alex (host) mainly asks short questions and gives reactions, "
                    "while Jordan (expert) answers in 1-2 concise sentences. "
                    "Use conversational language with natural fillers. "
                    "Create 12-15 conversation exchanges."
                )

            chat_completion = self.llm_client.chat.completions.create(
                messages=[
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": self._build_prompt(text, language, search_context)}
                ],
                model=self.config.api_model_name,
                temperature=0.85,
            )

            pattern = r"\{(?:[^{}]|(?:\{[^{}]*\}))*\}"
            json_match = re.search(pattern, chat_completion.choices[0].message.content)

            if not json_match:
                raise ValueError("No valid JSON found in response")

            return json.loads(json_match.group())
        except Exception as e:
            raise RuntimeError(f"Failed to extract conversation: {e}")

    def parse_conversation_text(self, conversation_text: str) -> Dict:
        """Parse conversation text back to JSON format"""
        lines = conversation_text.strip().split('\n')
        conversation_data = {"conversation": []}
        
        for line in lines:
            if ':' in line:
                speaker, text = line.split(':', 1)
                conversation_data["conversation"].append({
                    "speaker": speaker.strip(),
                    "text": text.strip()
                })
        
        return conversation_data

    async def text_to_speech_edge(self, conversation_json: Dict, language: str = "English") -> Tuple[str, str]:
        """Convert text to speech using Edge TTS"""
        output_dir = Path(self._create_output_directory())
        filenames = []

        try:
            # ์–ธ์–ด๋ณ„ ์Œ์„ฑ ์„ค์ • - ํ•œ๊ตญ์–ด๋Š” ๋ชจ๋‘ ๋‚จ์„ฑ ์Œ์„ฑ
            if language == "Korean":
                voices = [
                    "ko-KR-HyunsuNeural",  # ๋‚จ์„ฑ ์Œ์„ฑ 1 (์ฐจ๋ถ„ํ•˜๊ณ  ์‹ ๋ขฐ๊ฐ ์žˆ๋Š”)
                    "ko-KR-InJoonNeural"   # ๋‚จ์„ฑ ์Œ์„ฑ 2 (ํ™œ๊ธฐ์ฐจ๊ณ  ์นœ๊ทผํ•œ)
                ]
            else:
                voices = [
                    "en-US-AndrewMultilingualNeural",    # ๋‚จ์„ฑ ์Œ์„ฑ 1
                    "en-US-BrianMultilingualNeural"      # ๋‚จ์„ฑ ์Œ์„ฑ 2
                ]

            for i, turn in enumerate(conversation_json["conversation"]):
                filename = output_dir / f"output_{i}.wav"
                voice = voices[i % len(voices)]

                tmp_path = await self._generate_audio_edge(turn["text"], voice)
                os.rename(tmp_path, filename)
                filenames.append(str(filename))

            # Combine audio files
            final_output = os.path.join(output_dir, "combined_output.wav")
            self._combine_audio_files(filenames, final_output)
            
            # Generate conversation text
            conversation_text = "\n".join(
                f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
                for i, turn in enumerate(conversation_json["conversation"])
            )
            
            return final_output, conversation_text
        except Exception as e:
            raise RuntimeError(f"Failed to convert text to speech: {e}")

    async def _generate_audio_edge(self, text: str, voice: str) -> str:
        """Generate audio using Edge TTS"""
        if not text.strip():
            raise ValueError("Text cannot be empty")
            
        voice_short_name = voice.split(" - ")[0] if " - " in voice else voice
        communicate = edge_tts.Communicate(text, voice_short_name)

        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
            tmp_path = tmp_file.name
            await communicate.save(tmp_path)

        return tmp_path

    @spaces.GPU(duration=60)
    def text_to_speech_spark(self, conversation_json: Dict, language: str = "English", progress=None) -> Tuple[str, str]:
        """Convert text to speech using Spark TTS CLI"""
        if not SPARK_AVAILABLE or not self.spark_model_dir:
            raise RuntimeError("Spark TTS not available")

        try:
            output_dir = self._create_output_directory()
            audio_files = []
            
            # Create different voice characteristics for different speakers
            if language == "Korean":
                voice_configs = [
                    {"prompt_text": "์•ˆ๋…•ํ•˜์„ธ์š”, ์˜ค๋Š˜ ํŒŸ์บ์ŠคํŠธ ์ง„ํ–‰์„ ๋งก์€ ์ค€์ˆ˜์ž…๋‹ˆ๋‹ค. ์—ฌ๋Ÿฌ๋ถ„๊ณผ ํ•จ๊ป˜ ํฅ๋ฏธ๋กœ์šด ์ด์•ผ๊ธฐ๋ฅผ ๋‚˜๋ˆ ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.", "gender": "male"},
                    {"prompt_text": "์•ˆ๋…•ํ•˜์„ธ์š”, ์ €๋Š” ์˜ค๋Š˜ ์ด ์ฃผ์ œ์— ๋Œ€ํ•ด ์„ค๋ช…๋“œ๋ฆด ๋ฏผํ˜ธ์ž…๋‹ˆ๋‹ค. ์‰ฝ๊ณ  ์žฌ๋ฏธ์žˆ๊ฒŒ ์„ค๋ช…๋“œ๋ฆด๊ฒŒ์š”.", "gender": "male"}
                ]
            else:
                voice_configs = [
                    {"prompt_text": "Hello everyone, I'm Alex, your host for today's podcast. Let's explore this fascinating topic together.", "gender": "male"},
                    {"prompt_text": "Hi, I'm Jordan. I'm excited to share my insights on this subject with you all today.", "gender": "male"}
                ]

            for i, turn in enumerate(conversation_json["conversation"]):
                text = turn["text"]
                if not text.strip():
                    continue
                
                # Use different voice config for each speaker
                voice_config = voice_configs[i % len(voice_configs)]
                
                output_file = os.path.join(output_dir, f"spark_output_{i}.wav")
                
                # Run Spark TTS CLI inference
                cmd = [
                    "python", "-m", "cli.inference",
                    "--text", text,
                    "--device", "0" if torch.cuda.is_available() else "cpu",
                    "--save_dir", output_dir,
                    "--model_dir", self.spark_model_dir,
                    "--prompt_text", voice_config["prompt_text"],
                    "--output_name", f"spark_output_{i}.wav"
                ]
                
                try:
                    # Run the command
                    result = subprocess.run(
                        cmd, 
                        capture_output=True, 
                        text=True, 
                        timeout=60,
                        cwd="."  # Make sure we're in the right directory
                    )
                    
                    if result.returncode == 0:
                        audio_files.append(output_file)
                    else:
                        print(f"Spark TTS error for turn {i}: {result.stderr}")
                        # Create a short silence as fallback
                        silence = np.zeros(int(22050 * 1.0))  # 1 second of silence
                        sf.write(output_file, silence, 22050)
                        audio_files.append(output_file)
                        
                except subprocess.TimeoutExpired:
                    print(f"Spark TTS timeout for turn {i}")
                    # Create silence as fallback
                    silence = np.zeros(int(22050 * 1.0))
                    sf.write(output_file, silence, 22050)
                    audio_files.append(output_file)
                except Exception as e:
                    print(f"Error running Spark TTS for turn {i}: {e}")
                    # Create silence as fallback
                    silence = np.zeros(int(22050 * 1.0))
                    sf.write(output_file, silence, 22050)
                    audio_files.append(output_file)

            # Combine all audio files
            if audio_files:
                final_output = os.path.join(output_dir, "spark_combined.wav")
                self._combine_audio_files(audio_files, final_output)
            else:
                raise RuntimeError("No audio files generated")

            # Generate conversation text
            conversation_text = "\n".join(
                f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
                for i, turn in enumerate(conversation_json["conversation"])
            )
            
            return final_output, conversation_text
            
        except Exception as e:
            raise RuntimeError(f"Failed to convert text to speech with Spark TTS: {e}")

    @spaces.GPU(duration=60)
    def text_to_speech_melo(self, conversation_json: Dict, progress=None) -> Tuple[str, str]:
        """Convert text to speech using MeloTTS"""
        if not MELO_AVAILABLE or not self.melo_models:
            raise RuntimeError("MeloTTS not available")

        speakers = ["EN-Default", "EN-US"]
        combined_audio = AudioSegment.empty()

        for i, turn in enumerate(conversation_json["conversation"]):
            bio = io.BytesIO()
            text = turn["text"]
            speaker = speakers[i % 2]
            speaker_id = self.melo_models["EN"].hps.data.spk2id[speaker]
            
            # Generate audio
            self.melo_models["EN"].tts_to_file(
                text, speaker_id, bio, speed=1.0, 
                pbar=progress.tqdm if progress else None, 
                format="wav"
            )
            
            bio.seek(0)
            audio_segment = AudioSegment.from_file(bio, format="wav")
            combined_audio += audio_segment

        # Save final audio
        final_audio_path = "melo_podcast.mp3"
        combined_audio.export(final_audio_path, format="mp3")
        
        # Generate conversation text
        conversation_text = "\n".join(
            f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
            for i, turn in enumerate(conversation_json["conversation"])
        )
        
        return final_audio_path, conversation_text

    def _create_output_directory(self) -> str:
        """Create a unique output directory"""
        random_bytes = os.urandom(8)
        folder_name = base64.urlsafe_b64encode(random_bytes).decode("utf-8")
        os.makedirs(folder_name, exist_ok=True)
        return folder_name

    def _combine_audio_files(self, filenames: List[str], output_file: str) -> None:
        """Combine multiple audio files into one"""
        if not filenames:
            raise ValueError("No input files provided")

        try:
            audio_segments = []
            for filename in filenames:
                if os.path.exists(filename):
                    audio_segment = AudioSegment.from_file(filename)
                    audio_segments.append(audio_segment)

            if audio_segments:
                combined = sum(audio_segments)
                combined.export(output_file, format="wav")

            # Clean up temporary files
            for filename in filenames:
                if os.path.exists(filename):
                    os.remove(filename)

        except Exception as e:
            raise RuntimeError(f"Failed to combine audio files: {e}")


# Global converter instance
converter = UnifiedAudioConverter(ConversationConfig())


async def synthesize(article_input, input_type: str = "URL", mode: str = "Local", tts_engine: str = "Edge-TTS", language: str = "English"):
    """Main synthesis function - handles URL, PDF, and Keyword inputs"""
    try:
        # Extract text based on input type
        if input_type == "URL":
            if not article_input or not isinstance(article_input, str):
                return "Please provide a valid URL.", None
            text = converter.fetch_text(article_input)
        elif input_type == "PDF":
            if not article_input:
                return "Please upload a PDF file.", None
            text = converter.extract_text_from_pdf(article_input)
        else:  # Keyword
            if not article_input or not isinstance(article_input, str):
                return "Please provide a keyword or topic.", None
            # ํ‚ค์›Œ๋“œ๋กœ ๊ฒ€์ƒ‰ํ•˜์—ฌ ์ฝ˜ํ…์ธ  ์ƒ์„ฑ
            text = search_and_compile_content(article_input, language)
            text = f"Keyword-based content:\n{text}"  # ๋งˆ์ปค ์ถ”๊ฐ€
        
        # Limit text to max words
        words = text.split()
        if len(words) > converter.config.max_words:
            text = " ".join(words[:converter.config.max_words])

        # Extract conversation based on mode
        if mode == "Local":
            # ๋กœ์ปฌ ๋ชจ๋“œ๊ฐ€ ๊ธฐ๋ณธ (์ƒˆ๋กœ์šด Local LLM ์‚ฌ์šฉ)
            try:
                conversation_json = converter.extract_conversation_local(text, language)
            except Exception as e:
                print(f"Local mode failed: {e}, trying API fallback")
                # API ํด๋ฐฑ
                api_key = os.environ.get("TOGETHER_API_KEY")
                if api_key:
                    converter.initialize_api_mode(api_key)
                    conversation_json = converter.extract_conversation_api(text, language)
                else:
                    raise RuntimeError("Local mode failed and no API key available for fallback")
        else:  # API mode (now secondary)
            api_key = os.environ.get("TOGETHER_API_KEY")
            if not api_key:
                print("API key not found, falling back to local mode")
                conversation_json = converter.extract_conversation_local(text, language)
            else:
                try:
                    converter.initialize_api_mode(api_key)
                    conversation_json = converter.extract_conversation_api(text, language)
                except Exception as e:
                    print(f"API mode failed: {e}, falling back to local mode")
                    conversation_json = converter.extract_conversation_local(text, language)

        # Generate conversation text
        conversation_text = "\n".join(
            f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
            for i, turn in enumerate(conversation_json["conversation"])
        )

        return conversation_text, None
        
    except Exception as e:
        return f"Error: {str(e)}", None


async def regenerate_audio(conversation_text: str, tts_engine: str = "Edge-TTS", language: str = "English"):
    """Regenerate audio from edited conversation text"""
    if not conversation_text.strip():
        return "Please provide conversation text.", None

    try:
        # Parse the conversation text back to JSON format
        conversation_json = converter.parse_conversation_text(conversation_text)
        
        if not conversation_json["conversation"]:
            return "No valid conversation found in the text.", None

        # ํ•œ๊ตญ์–ด์ธ ๊ฒฝ์šฐ Edge-TTS๋งŒ ์‚ฌ์šฉ (๋‹ค๋ฅธ TTS๋Š” ํ•œ๊ตญ์–ด ์ง€์›์ด ์ œํ•œ์ )
        if language == "Korean" and tts_engine != "Edge-TTS":
            tts_engine = "Edge-TTS"  # ์ž๋™์œผ๋กœ Edge-TTS๋กœ ๋ณ€๊ฒฝ

        # Generate audio based on TTS engine
        if tts_engine == "Edge-TTS":
            output_file, _ = await converter.text_to_speech_edge(conversation_json, language)
        elif tts_engine == "Spark-TTS":
            if not SPARK_AVAILABLE:
                return "Spark TTS not available. Please install required dependencies and clone the Spark-TTS repository.", None
            converter.initialize_spark_tts()
            output_file, _ = converter.text_to_speech_spark(conversation_json, language)
        else:  # MeloTTS
            if not MELO_AVAILABLE:
                return "MeloTTS not available. Please install required dependencies.", None
            if language == "Korean":
                return "MeloTTS does not support Korean. Please use Edge-TTS for Korean.", None
            converter.initialize_melo_tts()
            output_file, _ = converter.text_to_speech_melo(conversation_json)

        return "Audio generated successfully!", output_file
        
    except Exception as e:
        return f"Error generating audio: {str(e)}", None


def synthesize_sync(article_input, input_type: str = "URL", mode: str = "Local", tts_engine: str = "Edge-TTS", language: str = "English"):
    """Synchronous wrapper for async synthesis"""
    return asyncio.run(synthesize(article_input, input_type, mode, tts_engine, language))


def regenerate_audio_sync(conversation_text: str, tts_engine: str = "Edge-TTS", language: str = "English"):
    """Synchronous wrapper for async audio regeneration"""
    return asyncio.run(regenerate_audio(conversation_text, tts_engine, language))


def update_tts_engine_for_korean(language):
    """ํ•œ๊ตญ์–ด ์„ ํƒ ์‹œ TTS ์—”์ง„ ์˜ต์…˜ ์—…๋ฐ์ดํŠธ"""
    if language == "Korean":
        return gr.Radio(
            choices=["Edge-TTS"],
            value="Edge-TTS",
            label="TTS Engine",
            info="ํ•œ๊ตญ์–ด๋Š” Edge-TTS๋งŒ ์ง€์›๋ฉ๋‹ˆ๋‹ค",
            interactive=False
        )
    else:
        return gr.Radio(
            choices=["Edge-TTS", "Spark-TTS", "MeloTTS"],
            value="Edge-TTS",
            label="TTS Engine",
            info="Edge-TTS: Cloud-based, natural voices | Spark-TTS: Local AI model | MeloTTS: Local, requires GPU",
            interactive=True
        )


def toggle_input_visibility(input_type):
    """Toggle visibility of URL input, file upload, and keyword input based on input type"""
    if input_type == "URL":
        return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
    elif input_type == "PDF":
        return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
    else:  # Keyword
        return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)


# ๋ชจ๋ธ ์ดˆ๊ธฐํ™” (์•ฑ ์‹œ์ž‘ ์‹œ)
if LLAMA_CPP_AVAILABLE:
    try:
        model_path = hf_hub_download(
            repo_id=converter.config.local_model_repo,
            filename=converter.config.local_model_name,
            local_dir="./models"
        )
        print(f"Model downloaded to: {model_path}")
    except Exception as e:
        print(f"Failed to download model at startup: {e}")


# Gradio Interface
with gr.Blocks(theme='soft', title="AI Podcast Generator") as demo:
    gr.Markdown("# ๐ŸŽ™๏ธ AI Podcast Generator")
    gr.Markdown("Convert any article, blog, PDF document, or topic into an engaging podcast conversation!")
    
    # ์ƒ๋‹จ์— ๋กœ์ปฌ LLM ์ƒํƒœ ํ‘œ์‹œ
    with gr.Row():
        gr.Markdown(f"""
        ### ๐Ÿค– Enhanced Configuration:
        - **Primary**: Local LLM ({converter.config.local_model_name}) - Runs on your device
        - **Fallback**: API LLM ({converter.config.api_model_name}) - Used when local fails
        - **Status**: {"โœ… Llama CPP Available" if LLAMA_CPP_AVAILABLE else "โŒ Llama CPP Not Available - Install llama-cpp-python"}
        - **Conversation Length**: {converter.config.min_conversation_turns}-{converter.config.max_conversation_turns} exchanges (1.5x longer)
        - **Search**: {"โœ… Brave Search Enabled" if BRAVE_KEY else "โŒ Brave Search Not Available - Set BSEARCH_API"}
        - **New**: ๐ŸŽฏ Keyword input for topic-based podcast generation
        """)
    
    with gr.Row():
        with gr.Column(scale=3):
            # Input type selector - ํ‚ค์›Œ๋“œ ์˜ต์…˜ ์ถ”๊ฐ€
            input_type_selector = gr.Radio(
                choices=["URL", "PDF", "Keyword"],
                value="URL",
                label="Input Type",
                info="Choose between URL, PDF file upload, or keyword/topic"
            )
            
            # URL input
            url_input = gr.Textbox(
                label="Article URL", 
                placeholder="Enter the article URL here...",
                value="",
                visible=True
            )
            
            # PDF upload
            pdf_input = gr.File(
                label="Upload PDF",
                file_types=[".pdf"],
                visible=False
            )
            
            # Keyword input (์ƒˆ๋กœ ์ถ”๊ฐ€)
            keyword_input = gr.Textbox(
                label="Topic/Keyword",
                placeholder="Enter a topic or keyword (e.g., 'AI trends', '์ธ๊ณต์ง€๋Šฅ ์ตœ์‹  ๋™ํ–ฅ')",
                value="",
                visible=False,
                info="The system will search for latest information about this topic"
            )
            
        with gr.Column(scale=1):
            # ์–ธ์–ด ์„ ํƒ
            language_selector = gr.Radio(
                choices=["English", "Korean"],
                value="English",
                label="Language / ์–ธ์–ด",
                info="Select output language / ์ถœ๋ ฅ ์–ธ์–ด๋ฅผ ์„ ํƒํ•˜์„ธ์š”"
            )
            
            mode_selector = gr.Radio(
                choices=["Local", "API"],
                value="Local",
                label="Processing Mode",
                info="Local: Runs on device (Primary) | API: Cloud-based (Fallback)"
            )
            
            # TTS ์—”์ง„ ์„ ํƒ
            with gr.Group():
                gr.Markdown("### TTS Engine Selection")
                tts_selector = gr.Radio(
                    choices=["Edge-TTS", "Spark-TTS", "MeloTTS"],
                    value="Edge-TTS",
                    label="TTS Engine",
                    info="Edge-TTS: Cloud-based, natural voices | Spark-TTS: Local AI model | MeloTTS: Local, requires GPU"
                )
                
                gr.Markdown("""
                **๐Ÿ“ป Radio Talk Show Style:**
                - Natural, conversational dialogue
                - Host asks short questions
                - Expert gives brief, clear answers
                - 12-15 conversation exchanges
                
                **๐Ÿ” Keyword Feature:**
                - Enter any topic to generate a podcast
                - Automatically searches latest information
                - Creates engaging discussion from search results
                
                **๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ์–ด ์ง€์›:**
                - ์ž์—ฐ์Šค๋Ÿฌ์šด ๋ผ๋””์˜ค ๋Œ€๋‹ด ์Šคํƒ€์ผ
                - ์ง„ํ–‰์ž(์ค€์ˆ˜)๊ฐ€ ์งง์€ ์งˆ๋ฌธ์œผ๋กœ ๋Œ€ํ™” ์œ ๋„
                - ์ „๋ฌธ๊ฐ€(๋ฏผํ˜ธ)๊ฐ€ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋‹ต๋ณ€
                - ์ตœ์‹  ์ •๋ณด ์ž๋™ ๊ฒ€์ƒ‰ ๋ฐ ๋ฐ˜์˜
                """)
    
    convert_btn = gr.Button("๐ŸŽฏ Generate Conversation / ๋Œ€ํ™” ์ƒ์„ฑ", variant="primary", size="lg")
    
    with gr.Row():
        with gr.Column():
            conversation_output = gr.Textbox(
                label="Generated Conversation (Editable) / ์ƒ์„ฑ๋œ ๋Œ€ํ™” (ํŽธ์ง‘ ๊ฐ€๋Šฅ)",
                lines=30,  # ๋” ๊ธด ๋Œ€ํ™”๋ฅผ ์œ„ํ•ด ์ฆ๊ฐ€
                max_lines=60,
                interactive=True,
                placeholder="Generated conversation will appear here. You can edit it before generating audio.\n์ƒ์„ฑ๋œ ๋Œ€ํ™”๊ฐ€ ์—ฌ๊ธฐ์— ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค. ์˜ค๋””์˜ค ์ƒ์„ฑ ์ „์— ํŽธ์ง‘ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.\n\n๋ผ๋””์˜ค ๋Œ€๋‹ด ์Šคํƒ€์ผ๋กœ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ์ง„ํ–‰๋ฉ๋‹ˆ๋‹ค.",
                info="Edit the conversation as needed. Format: 'Speaker Name: Text' / ํ•„์š”์— ๋”ฐ๋ผ ๋Œ€ํ™”๋ฅผ ํŽธ์ง‘ํ•˜์„ธ์š”. ํ˜•์‹: 'ํ™”์ž ์ด๋ฆ„: ํ…์ŠคํŠธ'"
            )
            
            # ์˜ค๋””์˜ค ์ƒ์„ฑ ๋ฒ„ํŠผ ์ถ”๊ฐ€
            with gr.Row():
                generate_audio_btn = gr.Button("๐ŸŽ™๏ธ Generate Audio from Text / ํ…์ŠคํŠธ์—์„œ ์˜ค๋””์˜ค ์ƒ์„ฑ", variant="secondary", size="lg")
                gr.Markdown("*Edit the conversation above, then click to generate audio / ์œ„์˜ ๋Œ€ํ™”๋ฅผ ํŽธ์ง‘ํ•œ ํ›„ ํด๋ฆญํ•˜์—ฌ ์˜ค๋””์˜ค๋ฅผ ์ƒ์„ฑํ•˜์„ธ์š”*")
            
        with gr.Column():
            audio_output = gr.Audio(
                label="Podcast Audio / ํŒŸ์บ์ŠคํŠธ ์˜ค๋””์˜ค",
                type="filepath",
                interactive=False
            )
            
            # ์ƒํƒœ ๋ฉ”์‹œ์ง€ ์ถ”๊ฐ€
            status_output = gr.Textbox(
                label="Status / ์ƒํƒœ",
                interactive=False,
                visible=True
            )
    
    
    gr.Examples(
        examples=[
            ["https://huggingface.co/blog/openfree/cycle-navigator", "URL", "Local", "Edge-TTS", "English"],
            ["", "Keyword", "Local", "Edge-TTS", "English"],  # Keyword example
            ["https://huggingface.co/papers/2505.14810", "URL", "Local", "Edge-TTS", "Korean"],
            ["", "Keyword", "Local", "Edge-TTS", "Korean"],  # Korean keyword example
        ],
        inputs=[url_input, input_type_selector, mode_selector, tts_selector, language_selector],
        outputs=[conversation_output, status_output],
        fn=synthesize_sync,
        cache_examples=False,
    )
    
    # Input type change handler - ์ˆ˜์ •๋จ
    input_type_selector.change(
        fn=toggle_input_visibility,
        inputs=[input_type_selector],
        outputs=[url_input, pdf_input, keyword_input]
    )
    
    # ์–ธ์–ด ๋ณ€๊ฒฝ ์‹œ TTS ์—”์ง„ ์˜ต์…˜ ์—…๋ฐ์ดํŠธ
    language_selector.change(
        fn=update_tts_engine_for_korean,
        inputs=[language_selector],
        outputs=[tts_selector]
    )
    
    # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ - ์ˆ˜์ •๋œ ๋ถ€๋ถ„
    def get_article_input(input_type, url_input, pdf_input, keyword_input):
        """Get the appropriate input based on input type"""
        if input_type == "URL":
            return url_input
        elif input_type == "PDF":
            return pdf_input
        else:  # Keyword
            return keyword_input
    
    convert_btn.click(
        fn=lambda input_type, url_input, pdf_input, keyword_input, mode, tts, lang: synthesize_sync(
            get_article_input(input_type, url_input, pdf_input, keyword_input), input_type, mode, tts, lang
        ),
        inputs=[input_type_selector, url_input, pdf_input, keyword_input, mode_selector, tts_selector, language_selector],
        outputs=[conversation_output, status_output]
    )
    
    generate_audio_btn.click(
        fn=regenerate_audio_sync,
        inputs=[conversation_output, tts_selector, language_selector],
        outputs=[status_output, audio_output]
    )


# Launch the app
if __name__ == "__main__":
    demo.queue(api_open=True, default_concurrency_limit=10).launch(
        show_api=True,
        share=False,
        server_name="0.0.0.0",
        server_port=7860
    )