File size: 53,909 Bytes
e84d121
da3d22d
 
 
 
 
 
 
8238573
da3d22d
 
 
 
 
 
e84d121
da3d22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e84d121
 
 
da3d22d
 
 
 
 
f4227af
da3d22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c72d96
 
da3d22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c72d96
da3d22d
e84d121
 
da3d22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e84d121
da3d22d
 
 
 
 
e84d121
da3d22d
e84d121
da3d22d
 
 
 
e84d121
da3d22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e84d121
da3d22d
 
 
 
 
 
 
 
 
 
 
6c72d96
da3d22d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e84d121
da3d22d
e84d121
da3d22d
e84d121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da3d22d
 
 
 
 
60fe207
da3d22d
 
 
60fe207
e84d121
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
import gradio as gr
import requests
from urllib.parse import quote_plus, urlparse
import re
import logging
import tempfile
import pandas as pd
import mecab  # python‑mecab‑ko 라이브러리 μ‚¬μš©
import os
import time
import hmac
import hashlib
import base64
import random
from concurrent.futures import ThreadPoolExecutor, as_completed

# API μ„€μ •
API_BASE_URL = os.getenv("API_BASE_UR", "")
API_KEY = os.getenv("API_KEY", "")
HEADERS = {
    "x-api-key": API_KEY,
    "content-type": "application/json"
}

# ν™˜κ²½λ³€μˆ˜μ—μ„œ API μ„€μ • λ‘œλ“œ
def get_api_configs():
    """ν™˜κ²½λ³€μˆ˜μ—μ„œ API 섀정을 λ‘œλ“œ"""
    api_configs_str = os.getenv('API_CONFIGS', '')
    
    if not api_configs_str:
        debug_log("API_CONFIGS ν™˜κ²½λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
        return [], []
    
    try:
        # ν™˜κ²½λ³€μˆ˜ 값을 exec둜 μ‹€ν–‰ν•˜μ—¬ μ„€μ • λ‘œλ“œ
        local_vars = {}
        exec(api_configs_str, {}, local_vars)
        
        return (
            local_vars.get('NAVER_API_KEYS_LIST', []),
            local_vars.get('NAVER_SEARCH_API_KEYS_LIST', [])
        )
    except Exception as e:
        debug_log(f"ν™˜κ²½λ³€μˆ˜ νŒŒμ‹± 였λ₯˜: {e}")
        return [], []

# API μ„€μ • λ‘œλ“œ
NAVER_API_KEYS_LIST, NAVER_SEARCH_API_KEYS_LIST = get_api_configs()

# API ν‚€ 관리λ₯Ό μœ„ν•œ μ „μ—­ λ³€μˆ˜
naver_api_manager = {
    'keys': [],
    'current_index': -1,
    'failed_keys': set(),  # μ‹€νŒ¨ν•œ 킀듀을 좔적
    'is_initialized': False
}

naver_search_api_manager = {
    'keys': [],
    'current_index': -1,
    'failed_keys': set(),  # μ‹€νŒ¨ν•œ 킀듀을 좔적
    'is_initialized': False
}

# 디버깅(둜그)용 ν•¨μˆ˜
def debug_log(message: str):
    print(f"[DEBUG] {message}")

def load_naver_api_keys():
    """넀이버 κ΄‘κ³  API ν‚€λ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€."""
    if not NAVER_API_KEYS_LIST:
        debug_log("넀이버 κ΄‘κ³  API ν‚€κ°€ ν™˜κ²½λ³€μˆ˜μ— μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
        return []
    
    # 빈 ν‚€λ‚˜ ν”Œλ ˆμ΄μŠ€ν™€λ” 제거
    api_keys = []
    for config in NAVER_API_KEYS_LIST:
        if (config.get("API_KEY") and config.get("SECRET_KEY") and config.get("CUSTOMER_ID") and
            not config["API_KEY"].startswith("YOUR_") and
            not config["SECRET_KEY"].startswith("YOUR_") and
            not config["CUSTOMER_ID"].startswith("YOUR_") and
            config["API_KEY"].strip() and config["SECRET_KEY"].strip() and config["CUSTOMER_ID"].strip()):
            api_keys.append(config)
    
    if not api_keys:
        debug_log("μœ νš¨ν•œ 넀이버 κ΄‘κ³  API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€.")
        return []
    
    debug_log(f"총 {len(api_keys)}개의 넀이버 κ΄‘κ³  API ν‚€κ°€ λ‘œλ“œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
    return api_keys

def load_naver_search_api_keys():
    """넀이버 검색 API ν‚€λ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€."""
    if not NAVER_SEARCH_API_KEYS_LIST:
        debug_log("넀이버 검색 API ν‚€κ°€ ν™˜κ²½λ³€μˆ˜μ— μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
        return []
    
    # 빈 ν‚€λ‚˜ ν”Œλ ˆμ΄μŠ€ν™€λ” 제거
    api_keys = []
    for config in NAVER_SEARCH_API_KEYS_LIST:
        if (config.get("CLIENT_ID") and config.get("CLIENT_SECRET") and
            not config["CLIENT_ID"].startswith("YOUR_") and
            not config["CLIENT_SECRET"].startswith("YOUR_") and
            config["CLIENT_ID"].strip() and config["CLIENT_SECRET"].strip()):
            api_keys.append(config)
    
    if not api_keys:
        debug_log("μœ νš¨ν•œ 넀이버 검색 API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€.")
        return []
    
    debug_log(f"총 {len(api_keys)}개의 넀이버 검색 API ν‚€κ°€ λ‘œλ“œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
    return api_keys

def initialize_api_configs():
    """API 섀정을 μ΄ˆκΈ°ν™”ν•˜κ³  λžœλ€ν•˜κ²Œ μ •λ ¬"""
    global naver_api_manager, naver_search_api_manager
    
    try:
        # API ν‚€ λ‘œλ“œ 및 랜덀 μ„žκΈ°
        naver_keys = load_naver_api_keys()
        search_keys = load_naver_search_api_keys()
        
        if naver_keys:
            random.shuffle(naver_keys)
        if search_keys:
            random.shuffle(search_keys)
        
        # API κ΄€λ¦¬μž μ΄ˆκΈ°ν™”
        naver_api_manager['keys'] = naver_keys
        naver_api_manager['is_initialized'] = True
        
        naver_search_api_manager['keys'] = search_keys
        naver_search_api_manager['is_initialized'] = True
        
        debug_log("API μ„€μ • μ΄ˆκΈ°ν™” μ™„λ£Œ:")
        debug_log(f"  - 넀이버 κ΄‘κ³  API: {len(naver_keys)}개")
        debug_log(f"  - 넀이버 검색 API: {len(search_keys)}개")
        
    except Exception as e:
        debug_log(f"API μ„€μ • μ΄ˆκΈ°ν™” μ‹€νŒ¨: {str(e)}")

def initialize_naver_api_keys():
    """넀이버 κ΄‘κ³  API ν‚€ κ΄€λ¦¬μžλ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€."""
    global naver_api_manager
    
    if naver_api_manager['is_initialized']:
        return
    
    initialize_api_configs()

def initialize_naver_search_api_keys():
    """넀이버 검색 API ν‚€ κ΄€λ¦¬μžλ₯Ό μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€."""
    global naver_search_api_manager
    
    if naver_search_api_manager['is_initialized']:
        return
    
    initialize_api_configs()

def get_next_naver_api_key():
    """λ‹€μŒ μ‚¬μš©ν•  넀이버 κ΄‘κ³  API ν‚€λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€. μ‹€νŒ¨ν•œ ν‚€λŠ” κ±΄λ„ˆλœλ‹ˆλ‹€."""
    global naver_api_manager
    
    # μ΄ˆκΈ°ν™” 확인
    if not naver_api_manager['is_initialized']:
        initialize_naver_api_keys()
    
    if not naver_api_manager['keys']:
        debug_log("μ‚¬μš© κ°€λŠ₯ν•œ 넀이버 κ΄‘κ³  API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€.")
        return None
    
    available_keys = [
        key for i, key in enumerate(naver_api_manager['keys']) 
        if i not in naver_api_manager['failed_keys']
    ]
    
    if not available_keys:
        # λͺ¨λ“  ν‚€κ°€ μ‹€νŒ¨ν–ˆμœΌλ©΄ μ‹€νŒ¨ λͺ©λ‘μ„ μ΄ˆκΈ°ν™”ν•˜κ³  λ‹€μ‹œ μ‹œλ„
        debug_log("λͺ¨λ“  넀이버 κ΄‘κ³  API ν‚€κ°€ μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. μ‹€νŒ¨ λͺ©λ‘μ„ μ΄ˆκΈ°ν™”ν•˜κ³  λ‹€μ‹œ μ‹œλ„ν•©λ‹ˆλ‹€.")
        naver_api_manager['failed_keys'].clear()
        available_keys = naver_api_manager['keys']
    
    # 첫 번째 μ‚¬μš©μ€ 랜덀으둜 선택
    if naver_api_manager['current_index'] == -1:
        available_indices = [
            i for i, key in enumerate(naver_api_manager['keys']) 
            if i not in naver_api_manager['failed_keys']
        ]
        naver_api_manager['current_index'] = random.choice(available_indices)
        debug_log(f"첫 번째 넀이버 κ΄‘κ³  API ν‚€ 선택: 랜덀 인덱슀 {naver_api_manager['current_index'] + 1}")
    else:
        # 이후 μ‚¬μš©μ€ 순차적으둜 λ‹€μŒ ν‚€ 선택 (μ‹€νŒ¨ν•œ ν‚€λŠ” κ±΄λ„ˆλœ€)
        for _ in range(len(naver_api_manager['keys'])):
            naver_api_manager['current_index'] = (naver_api_manager['current_index'] + 1) % len(naver_api_manager['keys'])
            if naver_api_manager['current_index'] not in naver_api_manager['failed_keys']:
                break
        
        if naver_api_manager['current_index'] in naver_api_manager['failed_keys']:
            # λͺ¨λ“  ν‚€λ₯Ό μ‹œλ„ν–ˆμ§€λ§Œ μ‚¬μš©ν•  수 μžˆλŠ” ν‚€κ°€ μ—†μŒ
            debug_log("μ‚¬μš© κ°€λŠ₯ν•œ 넀이버 κ΄‘κ³  API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€. μ‹€νŒ¨ λͺ©λ‘μ„ μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.")
            naver_api_manager['failed_keys'].clear()
            naver_api_manager['current_index'] = 0
        
        debug_log(f"λ‹€μŒ 넀이버 κ΄‘κ³  API ν‚€ 선택: 인덱슀 {naver_api_manager['current_index'] + 1}")
    
    return naver_api_manager['keys'][naver_api_manager['current_index']]

def get_next_naver_search_api_key():
    """λ‹€μŒ μ‚¬μš©ν•  넀이버 검색 API ν‚€λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€. μ‹€νŒ¨ν•œ ν‚€λŠ” κ±΄λ„ˆλœλ‹ˆλ‹€."""
    global naver_search_api_manager
    
    # μ΄ˆκΈ°ν™” 확인
    if not naver_search_api_manager['is_initialized']:
        initialize_naver_search_api_keys()
    
    if not naver_search_api_manager['keys']:
        debug_log("μ‚¬μš© κ°€λŠ₯ν•œ 넀이버 검색 API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€.")
        return None
    
    available_keys = [
        key for i, key in enumerate(naver_search_api_manager['keys']) 
        if i not in naver_search_api_manager['failed_keys']
    ]
    
    if not available_keys:
        # λͺ¨λ“  ν‚€κ°€ μ‹€νŒ¨ν–ˆμœΌλ©΄ μ‹€νŒ¨ λͺ©λ‘μ„ μ΄ˆκΈ°ν™”ν•˜κ³  λ‹€μ‹œ μ‹œλ„
        debug_log("λͺ¨λ“  넀이버 검색 API ν‚€κ°€ μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. μ‹€νŒ¨ λͺ©λ‘μ„ μ΄ˆκΈ°ν™”ν•˜κ³  λ‹€μ‹œ μ‹œλ„ν•©λ‹ˆλ‹€.")
        naver_search_api_manager['failed_keys'].clear()
        available_keys = naver_search_api_manager['keys']
    
    # 첫 번째 μ‚¬μš©μ€ 랜덀으둜 선택
    if naver_search_api_manager['current_index'] == -1:
        available_indices = [
            i for i, key in enumerate(naver_search_api_manager['keys']) 
            if i not in naver_search_api_manager['failed_keys']
        ]
        naver_search_api_manager['current_index'] = random.choice(available_indices)
        debug_log(f"첫 번째 넀이버 검색 API ν‚€ 선택: 랜덀 인덱슀 {naver_search_api_manager['current_index'] + 1}")
    else:
        # 이후 μ‚¬μš©μ€ 순차적으둜 λ‹€μŒ ν‚€ 선택 (μ‹€νŒ¨ν•œ ν‚€λŠ” κ±΄λ„ˆλœ€)
        for _ in range(len(naver_search_api_manager['keys'])):
            naver_search_api_manager['current_index'] = (naver_search_api_manager['current_index'] + 1) % len(naver_search_api_manager['keys'])
            if naver_search_api_manager['current_index'] not in naver_search_api_manager['failed_keys']:
                break
        
        if naver_search_api_manager['current_index'] in naver_search_api_manager['failed_keys']:
            # λͺ¨λ“  ν‚€λ₯Ό μ‹œλ„ν–ˆμ§€λ§Œ μ‚¬μš©ν•  수 μžˆλŠ” ν‚€κ°€ μ—†μŒ
            debug_log("μ‚¬μš© κ°€λŠ₯ν•œ 넀이버 검색 API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€. μ‹€νŒ¨ λͺ©λ‘μ„ μ΄ˆκΈ°ν™”ν•©λ‹ˆλ‹€.")
            naver_search_api_manager['failed_keys'].clear()
            naver_search_api_manager['current_index'] = 0
        
        debug_log(f"λ‹€μŒ 넀이버 검색 API ν‚€ 선택: 인덱슀 {naver_search_api_manager['current_index'] + 1}")
    
    return naver_search_api_manager['keys'][naver_search_api_manager['current_index']]

def mark_naver_api_key_failed(api_config):
    """넀이버 κ΄‘κ³  API ν‚€λ₯Ό μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€ν•©λ‹ˆλ‹€."""
    global naver_api_manager
    
    try:
        key_index = naver_api_manager['keys'].index(api_config)
        naver_api_manager['failed_keys'].add(key_index)
        debug_log(f"넀이버 κ΄‘κ³  API ν‚€ 인덱슀 {key_index + 1}λ₯Ό μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€ν–ˆμŠ΅λ‹ˆλ‹€.")
    except ValueError:
        debug_log("μ‹€νŒ¨ν•œ 넀이버 κ΄‘κ³  API ν‚€λ₯Ό λͺ©λ‘μ—μ„œ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")

def mark_naver_search_api_key_failed(api_config):
    """넀이버 검색 API ν‚€λ₯Ό μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€ν•©λ‹ˆλ‹€."""
    global naver_search_api_manager
    
    try:
        key_index = naver_search_api_manager['keys'].index(api_config)
        naver_search_api_manager['failed_keys'].add(key_index)
        debug_log(f"넀이버 검색 API ν‚€ 인덱슀 {key_index + 1}λ₯Ό μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€ν–ˆμŠ΅λ‹ˆλ‹€.")
    except ValueError:
        debug_log("μ‹€νŒ¨ν•œ 넀이버 검색 API ν‚€λ₯Ό λͺ©λ‘μ—μ„œ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")

# --- 제λͺ© 제거 ν•¨μˆ˜ ---
def remove_title_from_content(content: str) -> str:
    """λΈ”λ‘œκ·Έ λ‚΄μš©μ—μ„œ 제λͺ© 뢀뢄을 μ œκ±°ν•˜λŠ” ν•¨μˆ˜"""
    debug_log("제λͺ© 제거 ν•¨μˆ˜ μ‹œμž‘")
    
    # "[제λͺ©]\n제λͺ©λ‚΄μš©\n\n[λ³Έλ¬Έ]\nλ³Έλ¬Έλ‚΄μš©" ν˜•νƒœμ˜ ν…μŠ€νŠΈμ—μ„œ 제λͺ© λΆ€λΆ„λ§Œ 제거
    if content.startswith("[제λͺ©]"):
        try:
            # "[λ³Έλ¬Έ]" λ˜λŠ” 첫 번째 double newline의 μœ„μΉ˜ μ°ΎκΈ°
            parts = content.split("\n\n", 1)
            if len(parts) > 1:
                # λ³Έλ¬Έ λΆ€λΆ„λ§Œ λ°˜ν™˜
                body_parts = parts[1].split("\n", 1)
                if len(body_parts) > 1 and body_parts[0] == "[λ³Έλ¬Έ]":
                    result = body_parts[1]
                else:
                    result = parts[1]
                debug_log("제λͺ© 제거 μ™„λ£Œ")
                return result
        except Exception as e:
            debug_log(f"제λͺ© 제거 쀑 였λ₯˜: {str(e)}")
    
    # 제λͺ© ν˜•νƒœκ°€ μ•„λ‹ˆλ©΄ κ·ΈλŒ€λ‘œ λ°˜ν™˜
    return content

# --- 넀이버 λΈ”λ‘œκ·Έ μŠ€ν¬λž˜ν•‘ (API 방식) ---
def scrape_naver_blog(url: str) -> str:
    debug_log("scrape_naver_blog ν•¨μˆ˜ μ‹œμž‘ (API 방식)")
    debug_log(f"μš”μ²­λ°›μ€ URL: {url}")
    
    try:
        if not url:
            return "URL이 ν•„μš”ν•©λ‹ˆλ‹€."
        
        # URL 인코딩
        encoded_url = quote_plus(url.strip(), encoding='utf-8')
        api_url = f"{API_BASE_URL}/blog?url={encoded_url}"
        
        debug_log(f"API URL: {api_url}")
        
        # API μš”μ²­
        response = requests.get(api_url, headers=HEADERS)
        debug_log(f"API μš”μ²­ μ™„λ£Œ, μƒνƒœμ½”λ“œ: {response.status_code}")
        
        if response.ok:
            data = response.json()
            if 'content' in data:
                content = data['content']
                debug_log("μ½˜ν…μΈ  μΆ”μΆœ μ™„λ£Œ")
                # μ½˜ν…μΈ κ°€ 이미 μ μ ˆν•œ ν˜•νƒœλ‘œ ν¬λ§·λ˜μ–΄ μžˆλ‹€κ³  κ°€μ •
                return content
            else:
                debug_log("μ½˜ν…μΈ λ₯Ό 찾을 수 μ—†μŒ")
                return "μ½˜ν…μΈ λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
        else:
            debug_log(f"API 였λ₯˜ 응닡: {response.text}")
            return f"API 였λ₯˜: {response.text}"
            
    except Exception as e:
        debug_log(f"μ—λŸ¬ λ°œμƒ: {str(e)}")
        return f"μŠ€ν¬λž˜ν•‘ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"

# --- ν˜•νƒœμ†Œ 뢄석 (μ°Έμ‘°μ½”λ“œ-1) ---
def analyze_text(text: str):
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    logger.debug("원본 ν…μŠ€νŠΈ: %s", text)
    filtered_text = re.sub(r'[^κ°€-힣]', '', text)
    logger.debug("ν•„ν„°λ§λœ ν…μŠ€νŠΈ: %s", filtered_text)
    if not filtered_text:
        logger.debug("μœ νš¨ν•œ ν•œκ΅­μ–΄ ν…μŠ€νŠΈκ°€ μ—†μŒ.")
        return pd.DataFrame(columns=["단어", "λΉˆλ„μˆ˜"]), ""
    mecab_instance = mecab.MeCab()
    tokens = mecab_instance.pos(filtered_text)
    logger.debug("ν˜•νƒœμ†Œ 뢄석 κ²°κ³Ό: %s", tokens)
    freq = {}
    for word, pos in tokens:
        if word and word.strip() and pos.startswith("NN"):
            freq[word] = freq.get(word, 0) + 1
            logger.debug("단어: %s, ν’ˆμ‚¬: %s, λΉˆλ„: %d", word, pos, freq[word])
    sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    logger.debug("μ •λ ¬λœ 단어 λΉˆλ„: %s", sorted_freq)
    df = pd.DataFrame(sorted_freq, columns=["단어", "λΉˆλ„μˆ˜"])
    logger.debug("ν˜•νƒœμ†Œ 뢄석 DataFrame 생성됨, shape: %s", df.shape)
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
    df.to_excel(temp_file.name, index=False, engine='openpyxl')
    temp_file.close()
    logger.debug("Excel 파일 생성됨: %s", temp_file.name)
    return df, temp_file.name

# --- 넀이버 검색 및 κ΄‘κ³  API κ΄€λ ¨ (병렬 처리 적용) ---
def generate_signature(timestamp, method, uri, secret_key):
    message = f"{timestamp}.{method}.{uri}"
    digest = hmac.new(secret_key.encode("utf-8"), message.encode("utf-8"), hashlib.sha256).digest()
    return base64.b64encode(digest).decode()

def get_header(method, uri, api_key, secret_key, customer_id):
    timestamp = str(round(time.time() * 1000))
    signature = generate_signature(timestamp, method, uri, secret_key)
    return {
        "Content-Type": "application/json; charset=UTF-8",
        "X-Timestamp": timestamp,
        "X-API-KEY": api_key,
        "X-Customer": str(customer_id),
        "X-Signature": signature
    }

def fetch_search_volume_batch(keywords_batch):
    """ν‚€μ›Œλ“œ λ°°μΉ˜μ— λŒ€ν•œ 넀이버 κ²€μƒ‰λŸ‰ 쑰회"""
    result = {}
    
    # 순차적으둜 API μ„€μ • κ°€μ Έμ˜€κΈ° (λ°°μΉ˜λ§ˆλ‹€ ν•œ 번만 호좜)
    api_config = get_next_naver_api_key()
    
    if not api_config:
        debug_log("❌ μ‚¬μš© κ°€λŠ₯ν•œ 넀이버 κ΄‘κ³  API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€.")
        return result
    
    API_KEY = api_config["API_KEY"]
    SECRET_KEY = api_config["SECRET_KEY"]
    CUSTOMER_ID_STR = api_config["CUSTOMER_ID"]
    
    debug_log(f"=== ν™˜κ²½ λ³€μˆ˜ 체크 (API 계정 {naver_api_manager['current_index'] + 1}) ===")
    debug_log(f"API_KEY: {'있음' if API_KEY else 'μ—†μŒ'}")
    debug_log(f"SECRET_KEY: {'있음' if SECRET_KEY else 'μ—†μŒ'}")
    debug_log(f"CUSTOMER_ID: {'있음' if CUSTOMER_ID_STR else 'μ—†μŒ'}")
    debug_log(f"배치 크기: {len(keywords_batch)}개 ν‚€μ›Œλ“œ")
    
    # CUSTOMER_IDλ₯Ό μ •μˆ˜λ‘œ λ³€ν™˜
    try:
        CUSTOMER_ID = int(CUSTOMER_ID_STR)
    except ValueError:
        debug_log(f"❌ CUSTOMER_ID λ³€ν™˜ 였λ₯˜: '{CUSTOMER_ID_STR}'λŠ” μœ νš¨ν•œ μˆ«μžκ°€ μ•„λ‹™λ‹ˆλ‹€.")
        mark_naver_api_key_failed(api_config)
        return result
    
    try:
        BASE_URL = "https://api.naver.com"
        uri = "/keywordstool"
        method = "GET"
        headers = get_header(method, uri, API_KEY, SECRET_KEY, CUSTOMER_ID)
        
        # ν‚€μ›Œλ“œ 배치λ₯Ό ν•œ λ²ˆμ— API둜 전솑
        params = {
            "hintKeywords": keywords_batch,
            "showDetail": "1"
        }
        
        debug_log(f"μš”μ²­ νŒŒλΌλ―Έν„°: {len(keywords_batch)}개 ν‚€μ›Œλ“œ")
        
        # API 호좜
        response = requests.get(BASE_URL + uri, params=params, headers=headers)
        
        debug_log(f"응닡 μƒνƒœ μ½”λ“œ: {response.status_code}")
        
        if response.status_code != 200:
            debug_log(f"❌ API 였λ₯˜ 응닡:")
            debug_log(f"  λ³Έλ¬Έ: {response.text}")
            # API ν‚€ 문제인 경우 μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€
            if response.status_code in [401, 403]:
                mark_naver_api_key_failed(api_config)
            return result
        
        # 응닡 데이터 νŒŒμ‹±
        result_data = response.json()
        
        if isinstance(result_data, dict) and "keywordList" in result_data:
            debug_log(f"  keywordList 길이: {len(result_data['keywordList'])}")
            
            # 배치 λ‚΄ 각 ν‚€μ›Œλ“œμ™€ λ§€μΉ­
            for keyword in keywords_batch:
                found = False
                for item in result_data["keywordList"]:
                    rel_keyword = item.get("relKeyword", "")
                    if rel_keyword == keyword:
                        pc_count = item.get("monthlyPcQcCnt", 0)
                        mobile_count = item.get("monthlyMobileQcCnt", 0)
                        
                        # 숫자 λ³€ν™˜
                        try:
                            if isinstance(pc_count, str):
                                pc_count_converted = int(pc_count.replace(",", ""))
                            else:
                                pc_count_converted = int(pc_count)
                        except:
                            pc_count_converted = 0
                            
                        try:
                            if isinstance(mobile_count, str):
                                mobile_count_converted = int(mobile_count.replace(",", ""))
                            else:
                                mobile_count_converted = int(mobile_count)
                        except:
                            mobile_count_converted = 0
                            
                        total_count = pc_count_converted + mobile_count_converted
                        
                        result[keyword] = {
                            "PCμ›”κ²€μƒ‰λŸ‰": pc_count_converted,
                            "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰": mobile_count_converted,
                            "ν† νƒˆμ›”κ²€μƒ‰λŸ‰": total_count
                        }
                        debug_log(f"βœ… '{keyword}': PC={pc_count_converted}, Mobile={mobile_count_converted}, Total={total_count}")
                        found = True
                        break
                
                if not found:
                    debug_log(f"❌ '{keyword}': λ§€μΉ­λ˜λŠ” 데이터λ₯Ό 찾을 수 μ—†μŒ")
                    # κ²€μƒ‰λŸ‰μ΄ μ—†λŠ” 경우 0으둜 μ„€μ •
                    result[keyword] = {
                        "PCμ›”κ²€μƒ‰λŸ‰": 0,
                        "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰": 0,
                        "ν† νƒˆμ›”κ²€μƒ‰λŸ‰": 0
                    }
        else:
            debug_log(f"❌ keywordListκ°€ μ—†μŒ")
    
    except Exception as e:
        debug_log(f"❌ 배치 처리 쀑 였λ₯˜: {str(e)}")
        # API ν‚€ 문제인 경우 μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€
        if "api" in str(e).lower() or "key" in str(e).lower() or "auth" in str(e).lower():
            mark_naver_api_key_failed(api_config)
        import traceback
        traceback.print_exc()
    
    debug_log(f"\n=== 배치 처리 μ™„λ£Œ ===")
    debug_log(f"μ„±κ³΅μ μœΌλ‘œ 처리된 ν‚€μ›Œλ“œ 수: {len(result)}")
    
    return result

def fetch_all_search_volumes(keywords, batch_size=5):
    """ν‚€μ›Œλ“œ λ¦¬μŠ€νŠΈμ— λŒ€ν•œ 넀이버 κ²€μƒ‰λŸ‰ 병렬 쑰회"""
    results = {}
    batches = []

    # ν‚€μ›Œλ“œλ₯Ό 5κ°œμ”© λ¬Άμ–΄μ„œ 배치 생성
    for i in range(0, len(keywords), batch_size):
        batch = keywords[i:i + batch_size]
        batches.append(batch)

    debug_log(f"총 {len(batches)}개 배치둜 {len(keywords)}개 ν‚€μ›Œλ“œ 처리 쀑…")
    debug_log(f"배치 크기: {batch_size}, 병렬 μ›Œμ»€: 10개, API 계정: {len(naver_api_manager['keys'])}개 순차 μ‚¬μš©")

    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = {executor.submit(fetch_search_volume_batch, batch): batch for batch in batches}
        for future in as_completed(futures):
            batch = futures[future]
            try:
                batch_results = future.result()
                results.update(batch_results)
                debug_log(f"배치 처리 μ™„λ£Œ: {len(batch)}개 ν‚€μ›Œλ“œ (성곡: {len(batch_results)}개)")
            except Exception as e:
                debug_log(f"배치 처리 였λ₯˜: {e}")
            time.sleep(0.5)  # API 레이트 리밋 λ°©μ§€

    debug_log(f"κ²€μƒ‰λŸ‰ 쑰회 μ™„λ£Œ: {len(results)}개 ν‚€μ›Œλ“œ")
    return results

def fetch_blog_count_batch(keywords_batch):
    """ν‚€μ›Œλ“œ λ°°μΉ˜μ— λŒ€ν•œ 넀이버 λΈ”λ‘œκ·Έ λ°œμƒμˆ˜ 쑰회"""
    result = {}
    
    # 순차적으둜 검색 API μ„€μ • κ°€μ Έμ˜€κΈ°
    api_config = get_next_naver_search_api_key()
    
    if not api_config:
        debug_log("❌ μ‚¬μš© κ°€λŠ₯ν•œ 넀이버 검색 API ν‚€κ°€ μ—†μŠ΅λ‹ˆλ‹€.")
        return result
    
    client_id = api_config["CLIENT_ID"]
    client_secret = api_config["CLIENT_SECRET"]
    
    debug_log(f"=== λΈ”λ‘œκ·Έ 검색 API 체크 (계정 {naver_search_api_manager['current_index'] + 1}) ===")
    debug_log(f"CLIENT_ID: {'있음' if client_id else 'μ—†μŒ'}")
    debug_log(f"CLIENT_SECRET: {'있음' if client_secret else 'μ—†μŒ'}")
    debug_log(f"배치 크기: {len(keywords_batch)}개 ν‚€μ›Œλ“œ")
    
    url = "https://openapi.naver.com/v1/search/blog.json"
    headers = {
        "X-Naver-Client-Id": client_id,
        "X-Naver-Client-Secret": client_secret
    }
    
    for keyword in keywords_batch:
        try:
            params = {"query": keyword, "display": 1}
            response = requests.get(url, headers=headers, params=params)
            
            if response.status_code == 200:
                data = response.json()
                blog_count = data.get("total", 0)
                result[keyword] = blog_count
                debug_log(f"βœ… '{keyword}': λΈ”λ‘œκ·Έ λ¬Έμ„œμˆ˜ = {blog_count}")
            else:
                debug_log(f"❌ '{keyword}': API 였λ₯˜ (μƒνƒœμ½”λ“œ: {response.status_code})")
                # API ν‚€ 문제인 경우 μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€
                if response.status_code in [401, 403]:
                    mark_naver_search_api_key_failed(api_config)
                result[keyword] = 0
                
        except Exception as e:
            debug_log(f"❌ '{keyword}': 처리 쀑 였λ₯˜ = {str(e)}")
            # API ν‚€ 문제인 경우 μ‹€νŒ¨ λͺ©λ‘μ— μΆ”κ°€
            if "api" in str(e).lower() or "key" in str(e).lower() or "auth" in str(e).lower():
                mark_naver_search_api_key_failed(api_config)
            result[keyword] = 0
    
    return result

def fetch_all_blog_counts(keywords, batch_size=10):
    """ν‚€μ›Œλ“œ λ¦¬μŠ€νŠΈμ— λŒ€ν•œ 넀이버 λΈ”λ‘œκ·Έ λ°œμƒμˆ˜ 병렬 쑰회"""
    results = {}
    batches = []

    # ν‚€μ›Œλ“œλ₯Ό 10κ°œμ”© λ¬Άμ–΄μ„œ 배치 생성
    for i in range(0, len(keywords), batch_size):
        batch = keywords[i:i + batch_size]
        batches.append(batch)

    debug_log(f"총 {len(batches)}개 배치둜 {len(keywords)}개 ν‚€μ›Œλ“œμ˜ λΈ”λ‘œκ·Έ λ°œμƒμˆ˜ 처리 쀑…")
    debug_log(f"배치 크기: {batch_size}, 병렬 μ›Œμ»€: 5개, API 계정: {len(naver_search_api_manager['keys'])}개 순차 μ‚¬μš©")

    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = {executor.submit(fetch_blog_count_batch, batch): batch for batch in batches}
        for future in as_completed(futures):
            batch = futures[future]
            try:
                batch_results = future.result()
                results.update(batch_results)
                debug_log(f"배치 처리 μ™„λ£Œ: {len(batch)}개 ν‚€μ›Œλ“œ (성곡: {len(batch_results)}개)")
            except Exception as e:
                debug_log(f"배치 처리 였λ₯˜: {e}")
            time.sleep(0.3)  # API 레이트 리밋 λ°©μ§€

    debug_log(f"λΈ”λ‘œκ·Έ λ°œμƒμˆ˜ 쑰회 μ™„λ£Œ: {len(results)}개 ν‚€μ›Œλ“œ")
    return results

def fetch_related_keywords(keyword):
    """μ—°κ΄€ ν‚€μ›Œλ“œ 쑰회 (κΈ°μ‘΄ λ‘œμ§μ€ κ·ΈλŒ€λ‘œ μœ μ§€)"""
    debug_log(f"fetch_related_keywords 호좜, ν‚€μ›Œλ“œ: {keyword}")
    
    # 단일 ν‚€μ›Œλ“œλ§Œ 있으면 배치 처리
    keywords_list = [keyword]
    search_volumes = fetch_all_search_volumes(keywords_list)
    
    # κ²°κ³Όκ°€ 있으면 λ°μ΄ν„°ν”„λ ˆμž„μœΌλ‘œ λ³€ν™˜
    if search_volumes:
        data = []
        for kw, vol in search_volumes.items():
            data.append({
                "μ •λ³΄ν‚€μ›Œλ“œ": kw,
                "PCμ›”κ²€μƒ‰λŸ‰": vol["PCμ›”κ²€μƒ‰λŸ‰"],
                "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰": vol["λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰"],
                "ν† νƒˆμ›”κ²€μƒ‰λŸ‰": vol["ν† νƒˆμ›”κ²€μƒ‰λŸ‰"]
            })
        df = pd.DataFrame(data)
        debug_log("fetch_related_keywords μ™„λ£Œ")
        return df
    else:
        return pd.DataFrame()

def fetch_blog_count(keyword):
    """단일 ν‚€μ›Œλ“œμ˜ λΈ”λ‘œκ·Έ λ°œμƒμˆ˜ 쑰회"""
    debug_log(f"fetch_blog_count 호좜, ν‚€μ›Œλ“œ: {keyword}")
    
    # 단일 ν‚€μ›Œλ“œλ§Œ μžˆμœΌλ―€λ‘œ 배치 처리
    keywords_list = [keyword]
    blog_counts = fetch_all_blog_counts(keywords_list)
    
    # κ²°κ³Ό λ°˜ν™˜
    if keyword in blog_counts:
        count = blog_counts[keyword]
        debug_log(f"fetch_blog_count κ²°κ³Ό: {count}")
        return count
    else:
        debug_log(f"fetch_blog_count 였λ₯˜")
        return 0

def create_excel_file(df):
    with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as tmp:
        excel_path = tmp.name
    df.to_excel(excel_path, index=False)
    debug_log(f"Excel 파일 생성됨: {excel_path}")
    return excel_path

def process_keyword(keywords: str, include_related: bool):
    debug_log(f"process_keyword 호좜, ν‚€μ›Œλ“œλ“€: {keywords}, 연관검색어 포함: {include_related}")
    input_keywords = [k.strip() for k in keywords.splitlines() if k.strip()]
    
    # λͺ¨λ“  ν‚€μ›Œλ“œλ₯Ό ν•œ λ²ˆμ— κ²€μƒ‰λŸ‰ 쑰회
    search_volumes = fetch_all_search_volumes(input_keywords)
    
    # κ²°κ³Όλ₯Ό DataFrame으둜 ꡬ성
    result_data = []
    for kw in input_keywords:
        if kw in search_volumes:
            vol = search_volumes[kw]
            result_data.append({
                "μ •λ³΄ν‚€μ›Œλ“œ": kw,
                "PCμ›”κ²€μƒ‰λŸ‰": vol["PCμ›”κ²€μƒ‰λŸ‰"],
                "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰": vol["λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰"],
                "ν† νƒˆμ›”κ²€μƒ‰λŸ‰": vol["ν† νƒˆμ›”κ²€μƒ‰λŸ‰"]
            })
    
    if result_data:
        result_df = pd.DataFrame(result_data)
    else:
        result_df = pd.DataFrame(columns=["μ •λ³΄ν‚€μ›Œλ“œ", "PCμ›”κ²€μƒ‰λŸ‰", "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰", "ν† νƒˆμ›”κ²€μƒ‰λŸ‰"])
    
    # λΈ”λ‘œκ·Έ λ¬Έμ„œμˆ˜ 쑰회 (병렬 처리)
    blog_counts = fetch_all_blog_counts(input_keywords)
    result_df["λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜"] = result_df["μ •λ³΄ν‚€μ›Œλ“œ"].map(blog_counts).fillna(0).astype(int)
    
    result_df.sort_values(by="ν† νƒˆμ›”κ²€μƒ‰λŸ‰", ascending=False, inplace=True)
    debug_log("process_keyword μ™„λ£Œ")
    return result_df, create_excel_file(result_df)

# --- ν˜•νƒœμ†Œ 뢄석과 κ²€μƒ‰λŸ‰/λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜ 병합 ---
def morphological_analysis_and_enrich(text: str, remove_freq1: bool):
    debug_log("morphological_analysis_and_enrich ν•¨μˆ˜ μ‹œμž‘")
    df_freq, _ = analyze_text(text)
    if df_freq.empty:
        debug_log("ν˜•νƒœμ†Œ 뢄석 κ²°κ³Όκ°€ 빈 λ°μ΄ν„°ν”„λ ˆμž„μž…λ‹ˆλ‹€.")
        return df_freq, ""
    if remove_freq1:
        before_shape = df_freq.shape
        df_freq = df_freq[df_freq["λΉˆλ„μˆ˜"] != 1]
        debug_log(f"λΉˆλ„μˆ˜ 1 제거 적용됨. {before_shape} -> {df_freq.shape}")
    
    # λͺ¨λ“  ν‚€μ›Œλ“œλ₯Ό ν•œ λ²ˆμ— κ²€μƒ‰λŸ‰ 쑰회 (병렬 처리)
    keywords_list = df_freq["단어"].tolist()
    search_volumes = fetch_all_search_volumes(keywords_list)
    blog_counts = fetch_all_blog_counts(keywords_list)
    
    # κ²€μƒ‰λŸ‰ 정보λ₯Ό λ°μ΄ν„°ν”„λ ˆμž„μ— λ§€ν•‘
    df_keyword_info = []
    for kw in keywords_list:
        if kw in search_volumes:
            vol = search_volumes[kw]
            df_keyword_info.append({
                "μ •λ³΄ν‚€μ›Œλ“œ": kw,
                "PCμ›”κ²€μƒ‰λŸ‰": vol["PCμ›”κ²€μƒ‰λŸ‰"],
                "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰": vol["λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰"],
                "ν† νƒˆμ›”κ²€μƒ‰λŸ‰": vol["ν† νƒˆμ›”κ²€μƒ‰λŸ‰"],
                "λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜": blog_counts.get(kw, 0)
            })
    
    if df_keyword_info:
        df_keyword_info = pd.DataFrame(df_keyword_info)
    else:
        df_keyword_info = pd.DataFrame(columns=["μ •λ³΄ν‚€μ›Œλ“œ", "PCμ›”κ²€μƒ‰λŸ‰", "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰", "ν† νƒˆμ›”κ²€μƒ‰λŸ‰", "λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜"])
    
    debug_log("κ²€μƒ‰λŸ‰ 및 λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜ 쑰회 μ™„λ£Œ")
    merged_df = pd.merge(df_freq, df_keyword_info, left_on="단어", right_on="μ •λ³΄ν‚€μ›Œλ“œ", how="left")
    merged_df.drop(columns=["μ •λ³΄ν‚€μ›Œλ“œ"], inplace=True)
    merged_excel_path = create_excel_file(merged_df)
    debug_log("morphological_analysis_and_enrich ν•¨μˆ˜ μ™„λ£Œ")
    return merged_df, merged_excel_path

# --- 직접 ν‚€μ›Œλ“œ 뢄석 (단독 뢄석) ---
def direct_keyword_analysis(text: str, keyword_input: str):
    debug_log("direct_keyword_analysis ν•¨μˆ˜ μ‹œμž‘")
    keywords = re.split(r'[\n,]+', keyword_input)
    keywords = [kw.strip() for kw in keywords if kw.strip()]
    debug_log(f"μž…λ ₯된 ν‚€μ›Œλ“œ λͺ©λ‘: {keywords}")
    results = []
    for kw in keywords:
        count = text.count(kw)
        results.append((kw, count))
        debug_log(f"ν‚€μ›Œλ“œ '{kw}'의 λΉˆλ„μˆ˜: {count}")
    df = pd.DataFrame(results, columns=["ν‚€μ›Œλ“œ", "λΉˆλ„μˆ˜"])
    excel_path = create_excel_file(df)
    debug_log("direct_keyword_analysis ν•¨μˆ˜ μ™„λ£Œ")
    return df, excel_path

# --- 톡합 뢄석 (ν˜•νƒœμ†Œ 뢄석 + 직접 ν‚€μ›Œλ“œ 뢄석) ---
def combined_analysis(blog_text: str, remove_freq1: bool, direct_keyword_input: str):
    debug_log("combined_analysis ν•¨μˆ˜ μ‹œμž‘")
    merged_df, _ = morphological_analysis_and_enrich(blog_text, remove_freq1)
    if "μ§μ ‘μž…λ ₯" not in merged_df.columns:
        merged_df["μ§μ ‘μž…λ ₯"] = ""
    direct_keywords = re.split(r'[\n,]+', direct_keyword_input)
    direct_keywords = [kw.strip() for kw in direct_keywords if kw.strip()]
    debug_log(f"μž…λ ₯된 직접 ν‚€μ›Œλ“œ: {direct_keywords}")
    
    # 직접 μž…λ ₯된 ν‚€μ›Œλ“œλ“€μ„ λ³‘λ ¬λ‘œ 처리
    for dk in direct_keywords:
        if dk in merged_df["단어"].values:
            merged_df.loc[merged_df["단어"] == dk, "μ§μ ‘μž…λ ₯"] = "μ§μ ‘μž…λ ₯"
        else:
            freq = blog_text.count(dk)
            # 병렬 처리둜 κ²€μƒ‰λŸ‰ 및 λΈ”λ‘œκ·Έ λ¬Έμ„œμˆ˜ 쑰회
            search_volumes = fetch_all_search_volumes([dk])
            blog_counts = fetch_all_blog_counts([dk])
            
            if dk in search_volumes:
                vol = search_volumes[dk]
                pc = vol["PCμ›”κ²€μƒ‰λŸ‰"]
                mobile = vol["λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰"]
                total = vol["ν† νƒˆμ›”κ²€μƒ‰λŸ‰"]
            else:
                pc = mobile = total = 0
            
            blog_count = blog_counts.get(dk, 0)
            
            new_row = {
                "단어": dk,
                "λΉˆλ„μˆ˜": freq,
                "PCμ›”κ²€μƒ‰λŸ‰": pc,
                "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰": mobile,
                "ν† νƒˆμ›”κ²€μƒ‰λŸ‰": total,
                "λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜": blog_count,
                "μ§μ ‘μž…λ ₯": "μ§μ ‘μž…λ ₯"
            }
            merged_df = pd.concat([merged_df, pd.DataFrame([new_row])], ignore_index=True)
    
    merged_df = merged_df.sort_values(by="λΉˆλ„μˆ˜", ascending=False).reset_index(drop=True)
    combined_excel = create_excel_file(merged_df)
    debug_log("combined_analysis ν•¨μˆ˜ μ™„λ£Œ")
    return merged_df, combined_excel

# --- 뢄석 ν•Έλ“€λŸ¬ ---
def analysis_handler(blog_text: str, remove_freq1: bool, include_title: bool, direct_keyword_input: str, direct_keyword_only: bool):
    debug_log("analysis_handler ν•¨μˆ˜ μ‹œμž‘")
    
    # 제λͺ© 포함/μ œμ™Έ 처리
    if not include_title:
        debug_log("제λͺ© 제거 둜직 적용")
        analysis_text = remove_title_from_content(blog_text)
    else:
        debug_log("제λͺ© ν¬ν•¨ν•˜μ—¬ 뢄석")
        analysis_text = blog_text
    
    if direct_keyword_only:
        # "직접 ν‚€μ›Œλ“œ μž…λ ₯만 뢄석" 선택 μ‹œ 단독 뢄석 μˆ˜ν–‰
        return direct_keyword_analysis(analysis_text, direct_keyword_input)
    else:
        # κΈ°λ³Έ 톡합 뢄석 μˆ˜ν–‰
        return combined_analysis(analysis_text, remove_freq1, direct_keyword_input)

# --- μŠ€ν¬λž˜ν•‘ μ‹€ν–‰ ---
def fetch_blog_content(url: str):
    debug_log("fetch_blog_content ν•¨μˆ˜ μ‹œμž‘")
    content = scrape_naver_blog(url)
    debug_log("fetch_blog_content ν•¨μˆ˜ μ™„λ£Œ")
    return content

# --- Gradio μΈν„°νŽ˜μ΄μŠ€ ꡬ성 ---
def create_interface():
    css = """
    /* ============================================
       닀크λͺ¨λ“œ μžλ™ λ³€κ²½ ν…œν”Œλ¦Ώ CSS
       λ‹€λ₯Έ ν”„λ‘œμ νŠΈμ— λ³΅μ‚¬ν•΄μ„œ μ‚¬μš© κ°€λŠ₯
       ============================================ */
    /* 1. CSS λ³€μˆ˜ μ •μ˜ (라이트λͺ¨λ“œ - κΈ°λ³Έκ°’) */
    :root {
        /* 메인 컬러 */
        --primary-color: #FB7F0D;
        --secondary-color: #ff9a8b;
        --accent-color: #FF6B6B;
        
        /* 배경 컬러 */
        --background-color: #FFFFFF;
        --card-bg: #ffffff;
        --input-bg: #ffffff;
        
        /* ν…μŠ€νŠΈ 컬러 */
        --text-color: #334155;
        --text-secondary: #64748b;
        
        /* 보더 및 ꡬ뢄선 */
        --border-color: #dddddd;
        --border-light: #e5e5e5;
        
        /* ν…Œμ΄λΈ” 컬러 */
        --table-even-bg: #f3f3f3;
        --table-hover-bg: #f0f0f0;
        
        /* 그림자 */
        --shadow: 0 8px 30px rgba(251, 127, 13, 0.08);
        --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.1);
        
        /* 기타 */
        --border-radius: 18px;
    }
    /* 2. 닀크λͺ¨λ“œ 색상 λ³€μˆ˜ (μžλ™ 감지) */
    @media (prefers-color-scheme: dark) {
        :root {
            /* 배경 컬러 */
            --background-color: #1a1a1a;
            --card-bg: #2d2d2d;
            --input-bg: #2d2d2d;
            
            /* ν…μŠ€νŠΈ 컬러 */
            --text-color: #e5e5e5;
            --text-secondary: #a1a1aa;
            
            /* 보더 및 ꡬ뢄선 */
            --border-color: #404040;
            --border-light: #525252;
            
            /* ν…Œμ΄λΈ” 컬러 */
            --table-even-bg: #333333;
            --table-hover-bg: #404040;
            
            /* 그림자 */
            --shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
            --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
    }
    /* 3. μˆ˜λ™ 닀크λͺ¨λ“œ 클래슀 (Gradio ν† κΈ€μš©) */
    [data-theme="dark"], 
    .dark,
    .gr-theme-dark {
        /* 배경 컬러 */
        --background-color: #1a1a1a;
        --card-bg: #2d2d2d;
        --input-bg: #2d2d2d;
        
        /* ν…μŠ€νŠΈ 컬러 */
        --text-color: #e5e5e5;
        --text-secondary: #a1a1aa;
        
        /* 보더 및 ꡬ뢄선 */
        --border-color: #404040;
        --border-light: #525252;
        
        /* ν…Œμ΄λΈ” 컬러 */
        --table-even-bg: #333333;
        --table-hover-bg: #404040;
        
        /* 그림자 */
        --shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
        --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.2);
    }
    /* 4. κΈ°λ³Έ μš”μ†Œ 닀크λͺ¨λ“œ 적용 */
    body {
        font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
        background-color: var(--background-color) !important;
        color: var(--text-color) !important;
        line-height: 1.6;
        transition: background-color 0.3s ease, color 0.3s ease;
    }
    footer {
        visibility: hidden;
    }
    /* 5. Gradio μ»¨ν…Œμ΄λ„ˆ κ°•μ œ 적용 */
    .gradio-container,
    .gradio-container *,
    .gr-app,
    .gr-app *,
    .gr-interface {
        background-color: var(--background-color) !important;
        color: var(--text-color) !important;
    }
    /* 6. μΉ΄λ“œ 및 νŒ¨λ„ μŠ€νƒ€μΌ */
    .gr-form,
    .gr-box,
    .gr-panel,
    .custom-frame,
    [class*="frame"],
    [class*="card"],
    [class*="panel"] {
        background-color: var(--card-bg) !important;
        border-color: var(--border-color) !important;
        color: var(--text-color) !important;
        box-shadow: var(--shadow) !important;
    }
    /* 7. μž…λ ₯ ν•„λ“œ μŠ€νƒ€μΌ */
    input[type="text"],
    input[type="number"],
    input[type="email"],
    input[type="password"],
    textarea,
    select,
    .gr-input,
    .gr-text-input,
    .gr-textarea,
    .gr-dropdown {
        background-color: var(--input-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
    }
    input[type="text"]:focus,
    input[type="number"]:focus,
    input[type="email"]:focus,
    input[type="password"]:focus,
    textarea:focus,
    select:focus,
    .gr-input:focus,
    .gr-text-input:focus,
    .gr-textarea:focus,
    .gr-dropdown:focus {
        border-color: var(--primary-color) !important;
        box-shadow: 0 0 0 2px rgba(251, 127, 13, 0.2) !important;
    }
    /* 8. 라벨 및 ν…μŠ€νŠΈ μš”μ†Œ */
    label,
    .gr-label,
    .gr-checkbox label,
    .gr-radio label,
    p, span, div {
        color: var(--text-color) !important;
    }
    /* 폼 라벨 ν…μŠ€νŠΈ 크기 λŒ€ν­ 증가 */
    .gr-form label,
    .gr-textbox label,
    .gr-checkbox label,
    .gr-radio label {
        font-size: 20px !important;
        font-weight: 600 !important;
        color: var(--text-color) !important;
    }
    /* μ„€λͺ… ν…μŠ€νŠΈ 크기 λŒ€ν­ 증가 */
    .gr-form .gr-form-label,
    .gr-textbox .gr-form-label,
    .gr-checkbox .gr-form-label,
    .gr-radio .gr-form-label,
    .gr-info {
        font-size: 18px !important;
        color: var(--text-secondary) !important;
        line-height: 1.4 !important;
    }
    /* 9. ν…Œμ΄λΈ” μŠ€νƒ€μΌ */
    table {
        background-color: var(--card-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
    }
    table th {
        background-color: var(--primary-color) !important;
        color: white !important;
        border-color: var(--border-color) !important;
    }
    table td {
        background-color: var(--card-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
    }
    table tbody tr:nth-child(even) {
        background-color: var(--table-even-bg) !important;
    }
    table tbody tr:hover {
        background-color: var(--table-hover-bg) !important;
    }
    /* 10. μ²΄ν¬λ°•μŠ€ 및 λΌλ””μ˜€ λ²„νŠΌ μŠ€νƒ€μΌ κ°œμ„  */
    input[type="checkbox"],
    input[type="radio"] {
        accent-color: var(--primary-color) !important;
        width: 24px !important;
        height: 24px !important;
        cursor: pointer !important;
    }
    /* μ²΄ν¬λ°•μŠ€ μ»€μŠ€ν…€ μŠ€νƒ€μΌ - 더 κ°•λ ₯ν•œ μ„ νƒμž μ‚¬μš© */
    .gradio-container input[type="checkbox"],
    .gr-checkbox input[type="checkbox"],
    input[type="checkbox"] {
        -webkit-appearance: none !important;
        -moz-appearance: none !important;
        appearance: none !important;
        width: 24px !important;
        height: 24px !important;
        border: 2px solid var(--border-color) !important;
        border-radius: 6px !important;
        background-color: var(--card-bg) !important;
        cursor: pointer !important;
        position: relative !important;
        transition: all 0.3s ease !important;
        margin-right: 12px !important;
        flex-shrink: 0 !important;
    }
    .gradio-container input[type="checkbox"]:checked,
    .gr-checkbox input[type="checkbox"]:checked,
    input[type="checkbox"]:checked {
        background-color: var(--primary-color) !important;
        border-color: var(--primary-color) !important;
    }
    .gradio-container input[type="checkbox"]:checked::before,
    .gr-checkbox input[type="checkbox"]:checked::before,
    input[type="checkbox"]:checked::before {
        content: "βœ“" !important;
        position: absolute !important;
        top: 50% !important;
        left: 50% !important;
        transform: translate(-50%, -50%) !important;
        color: white !important;
        font-size: 16px !important;
        font-weight: bold !important;
        line-height: 1 !important;
    }
    .gradio-container input[type="checkbox"]:hover,
    .gr-checkbox input[type="checkbox"]:hover,
    input[type="checkbox"]:hover {
        border-color: var(--primary-color) !important;
        box-shadow: 0 0 0 2px rgba(251, 127, 13, 0.2) !important;
    }
    /* μ²΄ν¬λ°•μŠ€ 라벨 ν…μŠ€νŠΈ 크기 λŒ€ν­ 증가 */
    .gradio-container .gr-checkbox label,
    .gr-checkbox label,
    label[for] {
        font-size: 20px !important;
        font-weight: 600 !important;
        color: var(--text-color) !important;
        cursor: pointer !important;
        margin-left: 8px !important;
        display: flex !important;
        align-items: center !important;
    }
    /* μ²΄ν¬λ°•μŠ€ μ»¨ν…Œμ΄λ„ˆ μ •λ ¬ */
    .gr-checkbox {
        display: flex !important;
        align-items: center !important;
        gap: 8px !important;
    }
    /* 11. μŠ€ν¬λ‘€λ°” μŠ€νƒ€μΌ */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }
    ::-webkit-scrollbar-track {
        background: var(--card-bg);
        border-radius: 10px;
    }
    ::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 10px;
    }
    ::-webkit-scrollbar-thumb:hover {
        background: var(--secondary-color);
    }
    /* 12. μ•„μ½”λ””μ–Έ 및 λ“œλ‘­λ‹€μš΄ */
    details {
        background-color: var(--card-bg) !important;
        border-color: var(--border-color) !important;
        color: var(--text-color) !important;
    }
    details summary {
        background-color: var(--card-bg) !important;
        color: var(--text-color) !important;
    }
    /* 13. 툴팁 및 νŒμ—… */
    [data-tooltip]:hover::after,
    .tooltip,
    .popup {
        background-color: var(--card-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
        box-shadow: var(--shadow-light) !important;
    }
    /* 14. λͺ¨λ‹¬ 및 μ˜€λ²„λ ˆμ΄ */
    .modal,
    .overlay,
    [class*="modal"],
    [class*="overlay"] {
        background-color: var(--card-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
    }
    /* 15. μΆ”κ°€ Gradio μ»΄ν¬λ„ŒνŠΈλ“€ */
    .gr-block,
    .gr-group,
    .gr-row,
    .gr-column {
        background-color: var(--background-color) !important;
        color: var(--text-color) !important;
    }
    /* 16. λ²„νŠΌμ€ κΈ°μ‘΄ μŠ€νƒ€μΌ μœ μ§€ (primary-color μ‚¬μš©) */
    button:not([class*="custom"]):not([class*="primary"]):not([class*="secondary"]) {
        background-color: var(--card-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
    }
    /* 17. μ½”λ“œ 블둝 및 pre νƒœκ·Έ */
    code,
    pre,
    .code-block {
        background-color: var(--table-even-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
    }
    /* 18. μ•Œλ¦Ό 및 λ©”μ‹œμ§€ */
    .alert,
    .message,
    .notification,
    [class*="alert"],
    [class*="message"],
    [class*="notification"] {
        background-color: var(--card-bg) !important;
        color: var(--text-color) !important;
        border-color: var(--border-color) !important;
    }
    /* 19. μ „ν™˜ μ• λ‹ˆλ©”μ΄μ…˜ */
    * {
        transition: background-color 0.3s ease, 
                    color 0.3s ease, 
                    border-color 0.3s ease !important;
    }
    /* 20. κΈ°μ‘΄ μŠ€νƒ€μΌ μœ μ§€ */
    .container {
        max-width: 1200px;
        margin: 0 auto;
    }
    
    .header {
        background: linear-gradient(135deg, #FB7F0D, #FF9A5B);
        padding: 2rem;
        border-radius: 15px;
        margin-bottom: 20px;
        box-shadow: var(--shadow);
        text-align: center;
        color: white;
    }
    
    .header h1 {
        margin: 0;
        font-size: 2.5rem;
        font-weight: 700;
    }
    
    .header p {
        margin: 10px 0 0;
        font-size: 1.2rem;
        opacity: 0.9;
    }
    
    .card {
        background-color: var(--card-bg);
        border-radius: var(--border-radius);
        padding: 20px;
        margin: 10px 0;
        box-shadow: var(--shadow);
        border: 1px solid var(--border-color);
    }
    
    .button-primary {
        border-radius: 30px !important;
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)) !important;
        color: white !important;
        font-size: 18px !important;
        padding: 10px 20px !important;
        border: none;
        box-shadow: 0 4px 8px rgba(251, 127, 13, 0.25);
        transition: transform 0.3s ease;
        text-align: center;
        font-weight: 600;
    }
    
    .button-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(251, 127, 13, 0.3);
    }
    
    .section-title {
        display: flex;
        align-items: center;
        font-size: 20px;
        font-weight: 700;
        color: var(--text-color);
        margin-bottom: 15px;
        padding-bottom: 8px;
        border-bottom: 2px solid var(--primary-color);
    }
    
    .section-title i {
        margin-right: 10px;
        color: var(--primary-color);
    }
    
    .guide-container {
        background-color: var(--card-bg);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        border: 1px solid var(--border-color);
    }
    
    .guide-title {
        font-size: 1.3rem;
        font-weight: 700;
        color: var(--primary-color);
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
    }
    
    .guide-title i {
        margin-right: 0.8rem;
        font-size: 1.3rem;
    }
    
    .guide-item {
        display: flex;
        margin-bottom: 0.8rem;
        align-items: flex-start;
    }
    
    .guide-number {
        background-color: var(--primary-color);
        color: white;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        margin-right: 10px;
        flex-shrink: 0;
        font-size: 14px;
    }
    
    .guide-text {
        flex: 1;
        line-height: 1.6;
        color: var(--text-color);
    }
    
    /* κ·ΈλΌλ””μ˜€ μš”μ†Œ μŠ€νƒ€μΌ μ»€μŠ€ν„°λ§ˆμ΄μ§• */
    .gr-input, .gr-text-input, .gr-textarea {
        border-radius: var(--border-radius) !important;
        border: 1px solid var(--border-color) !important;
        padding: 12px !important;
        transition: all 0.3s ease !important;
    }
    
    .gr-input:focus, .gr-text-input:focus, .gr-textarea:focus {
        border-color: var(--primary-color) !important;
        outline: none !important;
        box-shadow: 0 0 0 2px rgba(251, 127, 13, 0.2) !important;
    }
    """
    
    # FontAwesome μ•„μ΄μ½˜ μΆ”κ°€
    fontawesome = """
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
    """
    
    with gr.Blocks(css=css, theme=gr.themes.Soft(
        primary_hue=gr.themes.Color(
            c50="#FFF7ED", 
            c100="#FFEDD5",
            c200="#FED7AA",
            c300="#FDBA74",
            c400="#FB923C",
            c500="#F97316", 
            c600="#EA580C",
            c700="#C2410C",
            c800="#9A3412",
            c900="#7C2D12", 
            c950="#431407",
        ),
        secondary_hue="zinc",
        neutral_hue="zinc",
        font=("Pretendard", "sans-serif")
    )) as demo:
        
        gr.HTML(fontawesome)
        
        # 메인 컨텐츠
        with gr.Row():
            # μ™Όμͺ½ μž…λ ₯ μ˜μ—­
            with gr.Column(scale=1, elem_classes="card"):
                # λΈ”λ‘œκ·Έ 링크 μž…λ ₯
                gr.HTML('<div class="section-title"><i class="fas fa-link"></i> λΈ”λ‘œκ·Έ 링크 μž…λ ₯</div>')
                blog_url_input = gr.Textbox(
                    label="",
                    placeholder="넀이버 λΈ”λ‘œκ·Έ URL을 μž…λ ₯ν•˜μ„Έμš”...",
                    lines=1,
                )
                scrape_button = gr.Button("μŠ€ν¬λž˜ν•‘ μ‹€ν–‰", elem_classes="button-primary")
                
                # λΈ”λ‘œκ·Έ λ‚΄μš©
                gr.HTML('<div class="section-title"><i class="fas fa-file-text"></i> λΈ”λ‘œκ·Έ λ‚΄μš©</div>')
                blog_content_box = gr.Textbox(
                    label="",
                    placeholder="μŠ€ν¬λž˜ν•‘λœ λΈ”λ‘œκ·Έ λ‚΄μš©μ΄ 여기에 ν‘œμ‹œλ©λ‹ˆλ‹€...",
                    lines=10,
                )
                
                # 뢄석 μ˜΅μ…˜
                gr.HTML('<div class="section-title"><i class="fas fa-cogs"></i> 뢄석 μ˜΅μ…˜</div>')
                with gr.Row():
                    remove_freq_checkbox = gr.Checkbox(
                        label="λΉˆλ„μˆ˜1 제거", 
                        value=True,
                        info="λΉˆλ„μˆ˜κ°€ 1인 단어듀을 뢄석 κ²°κ³Όμ—μ„œ μ œμ™Έν•©λ‹ˆλ‹€"
                    )
                    include_title_checkbox = gr.Checkbox(
                        label="제λͺ©ν¬ν•¨κΈ°λŠ₯", 
                        value=True,
                        info="λΈ”λ‘œκ·Έ 제λͺ©μ„ ν¬ν•¨ν•˜μ—¬ 뢄석을 μˆ˜ν–‰ν•©λ‹ˆλ‹€"
                    )
                with gr.Row():
                    direct_keyword_only_checkbox = gr.Checkbox(
                        label="직접 ν‚€μ›Œλ“œ μž…λ ₯만 뢄석", 
                        value=False,
                        info="ν˜•νƒœμ†Œ 뢄석 없이 직접 μž…λ ₯ν•œ ν‚€μ›Œλ“œλ§Œ λΆ„μ„ν•©λ‹ˆλ‹€"
                    )
                
                # 직접 ν‚€μ›Œλ“œ μž…λ ₯
                direct_keyword_box = gr.Textbox(
                    label="직접 ν‚€μ›Œλ“œ μž…λ ₯ (μ—”ν„° λ˜λŠ” ','둜 ꡬ뢄)",
                    placeholder="ν‚€μ›Œλ“œ1, ν‚€μ›Œλ“œ2, ν‚€μ›Œλ“œ3...",
                    lines=2,
                )
                
                analyze_button = gr.Button("뢄석 μ‹€ν–‰", elem_classes="button-primary")
            
            # 였λ₯Έμͺ½ 좜λ ₯ μ˜μ—­
            with gr.Column(scale=1, elem_classes="card"):
                # 뢄석 κ²°κ³Ό
                gr.HTML('<div class="section-title"><i class="fas fa-chart-bar"></i> 뢄석 κ²°κ³Ό</div>')
                result_df = gr.Dataframe(
                    label="",
                    interactive=True,
                )
                
                # 파일 λ‹€μš΄λ‘œλ“œ
                gr.HTML('<div class="section-title"><i class="fas fa-download"></i> κ²°κ³Ό λ‹€μš΄λ‘œλ“œ</div>')
                excel_file = gr.File(label="", file_types=[".xlsx"])
        
        # 이벀트 μ—°κ²°
        scrape_button.click(fn=fetch_blog_content, inputs=blog_url_input, outputs=blog_content_box)
        analyze_button.click(fn=analysis_handler, 
                             inputs=[blog_content_box, remove_freq_checkbox, include_title_checkbox, direct_keyword_box, direct_keyword_only_checkbox],
                             outputs=[result_df, excel_file])
    
    return demo

if __name__ == "__main__":
    debug_log("Gradio μ•± μ‹€ν–‰ μ‹œμž‘")
    # API_BASE_URLκ³Ό API_KEY ν™˜κ²½ λ³€μˆ˜ 체크
    if not API_BASE_URL or not API_KEY:
        print("주의: API_BASE_URL λ˜λŠ” API_KEY ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
        print("API_BASE_URL:", API_BASE_URL)
        print("API_KEY:", "섀정됨" if API_KEY else "μ—†μŒ")
    
    # API ν‚€ κ΄€λ¦¬μž μ΄ˆκΈ°ν™”
    initialize_naver_api_keys()
    initialize_naver_search_api_keys()
    
    demo = create_interface()
    demo.queue()
    demo.launch()