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() |