Spaces:
Sleeping
Sleeping
File size: 42,002 Bytes
d5fb63f 0fedf9f d5fb63f 0fedf9f d5fb63f 0fedf9f d5fb63f 0fedf9f d5fb63f b4650b8 f8570dc d5fb63f 0fedf9f f8570dc 0fedf9f f8570dc 0fedf9f f8570dc 0fedf9f f8570dc 0fedf9f f8570dc 0fedf9f f8570dc b4650b8 f8570dc 0fedf9f d5fb63f 0fedf9f d5fb63f b4650b8 f8570dc 0fedf9f f8570dc 0fedf9f f8570dc 0fedf9f f8570dc 0fedf9f b4650b8 0fedf9f f8570dc 0fedf9f f8570dc 0fedf9f f8570dc b4650b8 d5fb63f 0fedf9f f8570dc 0fedf9f d5fb63f 0fedf9f d5fb63f f8570dc c850803 0fedf9f d5fb63f 0fedf9f f8570dc 0fedf9f d5fb63f 0fedf9f d5fb63f f8570dc 0fedf9f 2c541cf 0fedf9f 2c541cf 0fedf9f 2c541cf 0fedf9f b4650b8 fb6f347 c850803 0fedf9f c850803 0fedf9f fb6f347 0fedf9f c850803 d5fb63f 0fedf9f 82bbb8a 0fedf9f 82bbb8a 0fedf9f 82bbb8a b4650b8 0fedf9f b4650b8 0fedf9f fdac880 82bbb8a 0fedf9f 82bbb8a 6faa7b9 0fedf9f 82bbb8a 6faa7b9 0fedf9f 82bbb8a b4650b8 989a45c 0fedf9f 989a45c 0fedf9f 989a45c 6faa7b9 82bbb8a 6faa7b9 0fedf9f 6faa7b9 0fedf9f 6faa7b9 0fedf9f 6faa7b9 82bbb8a 6faa7b9 0fedf9f 771fcfc 0fedf9f b4650b8 989a45c 0fedf9f d5fb63f 0fedf9f d5fb63f 0fedf9f |
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 |
import gradio as gr
import requests
from bs4 import BeautifulSoup
import urllib.parse # iframe κ²½λ‘ λ³΄μ μ μν λͺ¨λ
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
from concurrent.futures import ThreadPoolExecutor, as_completed
# --- λ³λ ¬ μ²λ¦¬ μ€μ ---
# API νΈμΆ μ νμ λ§μΆ° μ μ ν μ‘°μ νμΈμ.
# λ무 λμ κ°μ API μ νμ 걸릴 μ μμ΅λλ€.
MAX_WORKERS_RELATED_KEYWORDS = 5 # fetch_related_keywords λ³λ ¬ μμ
μ μ
MAX_WORKERS_BLOG_COUNT = 10 # fetch_blog_count λ³λ ¬ μμ
μ μ
# λλ²κΉ
(λ‘κ·Έ)μ© ν¨μ
def debug_log(message: str):
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [DEBUG] {message}")
# --- λ€μ΄λ² λΈλ‘κ·Έ μ€ν¬λν ---
def scrape_naver_blog(url: str) -> str:
debug_log("scrape_naver_blog ν¨μ μμ")
debug_log(f"μμ²λ°μ URL: {url}")
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/96.0.4664.110 Safari/537.36"
)
}
try:
response = requests.get(url, headers=headers, timeout=10)
debug_log("HTTP GET μμ²(λ©μΈ νμ΄μ§) μλ£")
if response.status_code != 200:
debug_log(f"μμ² μ€ν¨, μνμ½λ: {response.status_code}")
return f"μ€λ₯κ° λ°μνμ΅λλ€. μνμ½λ: {response.status_code}"
soup = BeautifulSoup(response.text, "html.parser")
debug_log("HTML νμ±(λ©μΈ νμ΄μ§) μλ£")
iframe = soup.select_one("iframe#mainFrame")
if not iframe:
debug_log("iframe#mainFrame νκ·Έλ₯Ό μ°Ύμ μ μμ΅λλ€.")
# μΌλΆ λΈλ‘κ·Έλ mainFrameμ΄ μμ μ μμ. λ³Έλ¬Έ μ§μ μλ
content_div_direct = soup.select_one('.se-main-container')
if content_div_direct:
title_div_direct = soup.select_one('.se-module.se-module-text.se-title-text')
title = title_div_direct.get_text(strip=True) if title_div_direct else "μ λͺ©μ μ°Ύμ μ μμ΅λλ€."
content = content_div_direct.get_text("\n", strip=True)
debug_log("iframe μμ΄ λ³Έλ¬Έ μ§μ μΆμΆ μλ£")
return f"[μ λͺ©]\n{title}\n\n[λ³Έλ¬Έ]\n{content}"
return "λ³Έλ¬Έ iframeμ μ°Ύμ μ μμ΅λλ€. (λ³Έλ¬Έ μ§μ μΆμΆ μ€ν¨)"
iframe_src = iframe.get("src")
if not iframe_src:
debug_log("iframe srcκ° μ‘΄μ¬νμ§ μμ΅λλ€.")
return "λ³Έλ¬Έ iframeμ srcλ₯Ό μ°Ύμ μ μμ΅λλ€."
# iframe_srcκ° μ λ URLμ΄ μλ κ²½μ°λ₯Ό λλΉ
if iframe_src.startswith("//"):
parsed_iframe_url = "https:" + iframe_src
elif iframe_src.startswith("/"):
parsed_main_url = urllib.parse.urlparse(url)
parsed_iframe_url = urllib.parse.urlunparse(
(parsed_main_url.scheme, parsed_main_url.netloc, iframe_src, None, None, None)
)
else:
parsed_iframe_url = urllib.parse.urljoin(url, iframe_src)
debug_log(f"iframe νμ΄μ§ μμ² URL: {parsed_iframe_url}")
iframe_response = requests.get(parsed_iframe_url, headers=headers, timeout=10)
debug_log("HTTP GET μμ²(iframe νμ΄μ§) μλ£")
if iframe_response.status_code != 200:
debug_log(f"iframe μμ² μ€ν¨, μνμ½λ: {iframe_response.status_code}")
return f"iframeμμ μ€λ₯κ° λ°μνμ΅λλ€. μνμ½λ: {iframe_response.status_code}"
iframe_soup = BeautifulSoup(iframe_response.text, "html.parser")
debug_log("HTML νμ±(iframe νμ΄μ§) μλ£")
# μ λͺ© μΆμΆ (λ€μν ꡬ쑰 μλ)
title_selectors = [
'.se-module.se-module-text.se-title-text', # μΌλ°μ μΈ μ€λ§νΈμλν° ONE
'.title_text', # ꡬλ²μ μλν° λλ λ€λ₯Έ ꡬ쑰
'div[class*="title"] h3',
'h1', 'h2', 'h3' # μΌλ°μ μΈ μ λͺ© νκ·Έ
]
title = "μ λͺ©μ μ°Ύμ μ μμ΅λλ€."
for selector in title_selectors:
title_div = iframe_soup.select_one(selector)
if title_div:
title = title_div.get_text(strip=True)
break
debug_log(f"μΆμΆλ μ λͺ©: {title}")
# λ³Έλ¬Έ μΆμΆ (λ€μν ꡬ쑰 μλ)
content_selectors = [
'.se-main-container', # μ€λ§νΈμλν° ONE
'div#content', # ꡬλ²μ μλν°
'div.post_ct', # μΌλΆ λΈλ‘κ·Έ ꡬ쑰
'article', 'main' # μλ§¨ν± νκ·Έ
]
content = "λ³Έλ¬Έμ μ°Ύμ μ μμ΅λλ€."
for selector in content_selectors:
content_div = iframe_soup.select_one(selector)
if content_div:
# λΆνμν μ€ν¬λ¦½νΈ, μ€νμΌ νκ·Έ μ κ±°
for s in content_div(['script', 'style']):
s.decompose()
content = content_div.get_text("\n", strip=True)
break
debug_log("λ³Έλ¬Έ μΆμΆ μλ£")
result = f"[μ λͺ©]\n{title}\n\n[λ³Έλ¬Έ]\n{content}"
debug_log("μ λͺ©κ³Ό λ³Έλ¬Έ ν©μΉ¨ μλ£")
return result
except requests.exceptions.Timeout:
debug_log(f"μμ² μκ° μ΄κ³Ό: {url}")
return f"μ€ν¬λν μ€ μκ° μ΄κ³Όκ° λ°μνμ΅λλ€: {url}"
except Exception as e:
debug_log(f"μ€ν¬λν μλ¬ λ°μ: {str(e)}")
return f"μ€ν¬λν μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
# --- ννμ λΆμ (μ°Έμ‘°μ½λ-1) ---
def analyze_text(text: str):
logging.basicConfig(level=logging.INFO) # INFO λ λ²¨λ‘ λ³κ²½νμ¬ λ무 λ§μ λ‘κ·Έ λ°©μ§
logger = logging.getLogger(__name__)
# logger.debug("μλ³Έ ν
μ€νΈ: %s", text) # λ무 κΈΈ μ μμΌλ―λ‘ μ£Όμ μ²λ¦¬
filtered_text = re.sub(r'[^κ°-ν£a-zA-Z0-9\s]', '', text) # μμ΄, μ«μ, 곡백 ν¬ν¨
# logger.debug("νν°λ§λ ν
μ€νΈ: %s", filtered_text)
if not filtered_text.strip():
logger.info("μ ν¨ν ν
μ€νΈκ° μμ (νν°λ§ ν).")
return pd.DataFrame(columns=["λ¨μ΄", "λΉλμ"]), ""
try:
mecab_instance = mecab.MeCab()
tokens = mecab_instance.pos(filtered_text)
except Exception as e:
logger.error(f"MeCab ννμ λΆμ μ€ μ€λ₯: {e}")
return pd.DataFrame(columns=["λ¨μ΄", "λΉλμ"]), ""
# logger.debug("ννμ λΆμ κ²°κ³Ό: %s", tokens)
freq = {}
for word, pos in tokens:
# μΌλ°λͺ
μ¬(NNG), κ³ μ λͺ
μ¬(NNP), μΈκ΅μ΄(SL), μ«μ(SN) λ± ν¬ν¨, ν κΈμ λ¨μ΄λ μ μΈ (μ ν μ¬ν)
if word and word.strip() and (pos.startswith("NN") or pos in ["SL", "SH"]) and len(word) > 1 :
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.info(f"ννμ λΆμ DataFrame μμ±λ¨, shape: {df.shape}")
temp_file_path = ""
if not df.empty:
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx", mode='w+b') as temp_file:
df.to_excel(temp_file.name, index=False, engine='openpyxl')
temp_file_path = temp_file.name
logger.info(f"Excel νμΌ μμ±λ¨: {temp_file_path}")
except Exception as e:
logger.error(f"Excel νμΌ μ μ₯ μ€ μ€λ₯: {e}")
temp_file_path = "" # μ€λ₯ λ°μ μ κ²½λ‘ μ΄κΈ°ν
return df, temp_file_path
# --- λ€μ΄λ² κ²μ λ° κ΄κ³ API κ΄λ ¨ (μ°Έμ‘°μ½λ-2) ---
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
}
# API ν€ νκ²½ λ³μ νμΈ ν¨μ
def get_env_variable(var_name):
value = os.environ.get(var_name)
if value is None:
debug_log(f"νκ²½ λ³μ '{var_name}'κ° μ€μ λμ§ μμμ΅λλ€. API νΈμΆμ΄ μ€ν¨ν μ μμ΅λλ€.")
# νμμ μ¬κΈ°μ raise Exception λλ κΈ°λ³Έκ° λ°ν
return value
def fetch_related_keywords(keyword):
debug_log(f"fetch_related_keywords νΈμΆ μμ, ν€μλ: {keyword}")
API_KEY = get_env_variable("NAVER_API_KEY")
SECRET_KEY = get_env_variable("NAVER_SECRET_KEY")
CUSTOMER_ID = get_env_variable("NAVER_CUSTOMER_ID")
if not all([API_KEY, SECRET_KEY, CUSTOMER_ID]):
debug_log(f"λ€μ΄λ² κ΄κ³ API ν€ μ 보 λΆμ‘±μΌλ‘ '{keyword}' μ°κ΄ ν€μλ μ‘°νλ₯Ό 건λ<0xEB><0xB5>λλ€.")
return pd.DataFrame()
BASE_URL = "https://api.naver.com"
uri = "/keywordstool"
method = "GET"
try:
headers = get_header(method, uri, API_KEY, SECRET_KEY, CUSTOMER_ID)
params = {
"hintKeywords": keyword, # λ¨μΌ ν€μλ λ¬Έμμ΄λ‘ μ λ¬
"showDetail": "1"
}
# hintKeywordsλ 리μ€νΈλ‘ λ°μ μ μμΌλ, μ¬κΈ°μλ λ¨μΌ ν€μλ μ²λ¦¬λ₯Ό κ°μ νκ³ λ¬Έμμ΄λ‘ μ λ¬
# λ§μ½ APIκ° hintKeywordsλ₯Ό 리μ€νΈλ‘λ§ λ°λλ€λ©΄ [keyword]λ‘ μμ νμ
response = requests.get(BASE_URL + uri, params=params, headers=headers, timeout=10)
response.raise_for_status() # μ€λ₯ λ°μ μ μμΈ λ°μ
data = response.json()
if "keywordList" not in data or not data["keywordList"]:
debug_log(f"'{keyword}'μ λν μ°κ΄ ν€μλ κ²°κ³Ό μμ.")
return pd.DataFrame() # λΉ DataFrame λ°ν
df = pd.DataFrame(data["keywordList"])
# API μλ΅μ ν΄λΉ 컬λΌμ΄ μμ κ²½μ°λ₯Ό λλΉ
df["monthlyPcQcCnt"] = df.get("monthlyPcQcCnt", 0)
df["monthlyMobileQcCnt"] = df.get("monthlyMobileQcCnt", 0)
def parse_count(x):
if pd.isna(x) or str(x).lower() == '< 10': # λ€μ΄λ² APIλ 10 λ―Έλ§μΌ λ "< 10"μΌλ‘ λ°ν
return 5 # λλ 0, λλ λ€λ₯Έ λνκ° (μ: 5)
try:
return int(str(x).replace(",", ""))
except ValueError:
return 0
df["PCμκ²μλ"] = df["monthlyPcQcCnt"].apply(parse_count)
df["λͺ¨λ°μΌμκ²μλ"] = df["monthlyMobileQcCnt"].apply(parse_count)
df["ν νμκ²μλ"] = df["PCμκ²μλ"] + df["λͺ¨λ°μΌμκ²μλ"]
df.rename(columns={"relKeyword": "μ 보ν€μλ"}, inplace=True)
# νμν 컬λΌλ§ μ ν, μλ κ²½μ° λλΉ
required_cols = ["μ 보ν€μλ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ"]
result_df = pd.DataFrame(columns=required_cols)
for col in required_cols:
if col in df.columns:
result_df[col] = df[col]
else: # ν΄λΉ 컬λΌμ΄ API μλ΅μ μμ κ²½μ° κΈ°λ³Έκ°μΌλ‘ μ±μ
if col == "μ 보ν€μλ": # μ 보ν€μλλ νμ
debug_log(f"API μλ΅μ 'relKeyword'κ° μμ΅λλ€. '{keyword}' μ²λ¦¬ μ€λ¨.")
return pd.DataFrame()
result_df[col] = 0
debug_log(f"fetch_related_keywords '{keyword}' μλ£, κ²°κ³Ό {len(result_df)}κ°")
return result_df.head(100) # μ΅λ 100κ°λ‘ μ ν
except requests.exceptions.HTTPError as http_err:
debug_log(f"HTTP μ€λ₯ λ°μ (fetch_related_keywords for '{keyword}'): {http_err} - μλ΅: {response.text if 'response' in locals() else 'N/A'}")
except requests.exceptions.RequestException as req_err:
debug_log(f"μμ² μ€λ₯ λ°μ (fetch_related_keywords for '{keyword}'): {req_err}")
except Exception as e:
debug_log(f"μ μ μλ μ€λ₯ λ°μ (fetch_related_keywords for '{keyword}'): {e}")
return pd.DataFrame() # μ€λ₯ λ°μ μ λΉ DataFrame λ°ν
def fetch_blog_count(keyword):
debug_log(f"fetch_blog_count νΈμΆ, ν€μλ: {keyword}")
client_id = get_env_variable("NAVER_SEARCH_CLIENT_ID")
client_secret = get_env_variable("NAVER_SEARCH_CLIENT_SECRET")
if not client_id or not client_secret:
debug_log(f"λ€μ΄λ² κ²μ API ν€ μ 보 λΆμ‘±μΌλ‘ '{keyword}' λΈλ‘κ·Έ μ μ‘°νλ₯Ό 건λ<0xEB><0xB5>λλ€.")
return 0
url = "https://openapi.naver.com/v1/search/blog.json"
headers = {
"X-Naver-Client-Id": client_id,
"X-Naver-Client-Secret": client_secret
}
params = {"query": keyword, "display": 1} # display=1λ‘ μ€μ νμ¬ total κ°λ§ λΉ λ₯΄κ² νμΈ
try:
response = requests.get(url, headers=headers, params=params, timeout=5)
response.raise_for_status() # HTTP μ€λ₯ λ°μ μ μμΈ λ°μ
data = response.json()
total_count = data.get("total", 0)
debug_log(f"fetch_blog_count κ²°κ³Ό: {total_count} for '{keyword}'")
return total_count
except requests.exceptions.HTTPError as http_err:
debug_log(f"HTTP μ€λ₯ λ°μ (fetch_blog_count for '{keyword}'): {http_err} - μλ΅: {response.text}")
except requests.exceptions.RequestException as req_err: # Timeout, ConnectionError λ±
debug_log(f"μμ² μ€λ₯ λ°μ (fetch_blog_count for '{keyword}'): {req_err}")
except Exception as e: # JSONDecodeError λ± κΈ°ν μμΈ
debug_log(f"μ μ μλ μ€λ₯ λ°μ (fetch_blog_count for '{keyword}'): {e}")
return 0 # μ€λ₯ λ°μ μ 0 λ°ν
def create_excel_file(df):
if df.empty:
debug_log("λΉ DataFrameμΌλ‘ Excel νμΌμ μμ±νμ§ μμ΅λλ€.")
# λΉ νμΌμ μμ±νκ±°λ, Noneμ λ°ννμ¬ Gradioμμ μ²λ¦¬νλλ‘ ν μ μμ
# μ¬κΈ°μλ λΉ μμ νμΌμ μμ±νμ¬ λ°ν (Gradio File μ»΄ν¬λνΈκ° κ²½λ‘λ₯Ό κΈ°λνλ―λ‘)
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as tmp:
excel_path = tmp.name
# λΉ μμ
νμΌμ ν€λλ§μ΄λΌλ μ¨μ£Όλ €λ©΄
# pd.DataFrame(columns=df.columns).to_excel(excel_path, index=False)
# μλλ©΄ κ·Έλ₯ λΉ νμΌμ λ°ν
return excel_path
try:
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False, mode='w+b') as tmp:
excel_path = tmp.name
df.to_excel(excel_path, index=False, engine='openpyxl')
debug_log(f"Excel νμΌ μμ±λ¨: {excel_path}")
return excel_path
except Exception as e:
debug_log(f"Excel νμΌ μμ± μ€ μ€λ₯: {e}")
# μ€λ₯ λ°μ μ λΉ νμΌ κ²½λ‘λΌλ λ°ν (Gradio νΈνμ±)
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as tmp:
return tmp.name
def process_keyword(keywords: str, include_related: bool):
debug_log(f"process_keyword νΈμΆ μμ, ν€μλλ€: '{keywords[:100]}...', μ°κ΄κ²μμ΄ ν¬ν¨: {include_related}")
input_keywords_orig = [k.strip() for k in keywords.splitlines() if k.strip()]
if not input_keywords_orig:
debug_log("μ
λ ₯λ ν€μλκ° μμ΅λλ€.")
return pd.DataFrame(columns=["μ 보ν€μλ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]), ""
all_related_keywords_dfs = []
# 1. fetch_related_keywords λ³λ ¬ μ²λ¦¬
debug_log(f"μ°κ΄ ν€μλ μ‘°ν λ³λ ¬ μ²λ¦¬ μμ (μ΅λ μμ
μ μ: {MAX_WORKERS_RELATED_KEYWORDS})")
with ThreadPoolExecutor(max_workers=MAX_WORKERS_RELATED_KEYWORDS) as executor:
future_to_keyword_related = {
executor.submit(fetch_related_keywords, kw): kw for kw in input_keywords_orig
}
for i, future in enumerate(as_completed(future_to_keyword_related)):
kw = future_to_keyword_related[future]
try:
df_kw_related = future.result() # DataFrame λ°ν
if not df_kw_related.empty:
# μλ³Έ ν€μλκ° κ²°κ³Όμ ν¬ν¨λμ΄ μλμ§ νμΈνκ³ , μμΌλ©΄ μΆκ° μλ (APIκ° νμ relKeywordλ‘ μμ μ μ£Όμ§ μμ)
# νμ§λ§ fetch_related_keywordsμμ μ΄λ―Έ hintKeywordλ₯Ό κΈ°λ°μΌλ‘ κ²μνλ―λ‘,
# μΌλ°μ μΌλ‘λ ν΄λΉ ν€μλ μ λ³΄κ° μκ±°λ, μ°κ΄ ν€μλλ§ λμ΄.
# μ¬κΈ°μλ API μλ΅μ κ·Έλλ‘ νμ©.
# 첫 λ²μ§Έ μ
λ ₯ ν€μλμ΄κ³ , μ°κ΄ ν€μλ ν¬ν¨ μ΅μ
μ΄ μΌμ Έ μμΌλ©΄ λͺ¨λ μ°κ΄ ν€μλλ₯Ό μΆκ°
# κ·Έ μΈμ κ²½μ°μλ ν΄λΉ ν€μλ μ체μ μ λ³΄λ§ (μλ€λ©΄) μ¬μ©νκ±°λ, μ΅μλ¨ ν€μλ μ¬μ©
if include_related and kw == input_keywords_orig[0]:
all_related_keywords_dfs.append(df_kw_related)
debug_log(f"첫 λ²μ§Έ ν€μλ '{kw}'μ λͺ¨λ μ°κ΄ ν€μλ ({len(df_kw_related)}κ°) μΆκ°λ¨.")
else:
# ν΄λΉ ν€μλμ μΌμΉνλ νμ μ°Ύκ±°λ, μμΌλ©΄ APIκ° λ°νν 첫λ²μ§Έ νμ μ¬μ©
row_kw = df_kw_related[df_kw_related["μ 보ν€μλ"] == kw]
if not row_kw.empty:
all_related_keywords_dfs.append(row_kw)
debug_log(f"ν€μλ '{kw}'μ μ§μ μ 보 μΆκ°λ¨.")
elif not df_kw_related.empty : # μ§μ μ 보λ μμ§λ§ μ°κ΄ ν€μλλ μμ λ
all_related_keywords_dfs.append(df_kw_related.head(1)) # κ°μ₯ μ°κ΄μ± λμ ν€μλ μΆκ°
debug_log(f"ν€μλ '{kw}'μ μ§μ μ 보λ μμΌλ, κ°μ₯ μ°κ΄μ± λμ ν€μλ 1κ° μΆκ°λ¨.")
# else: ν€μλ μ 보λ, μ°κ΄ μ 보λ μμ λ (df_kw_relatedκ° λΉμ΄μμ)
debug_log(f"'{kw}' μ°κ΄ ν€μλ μ²λ¦¬ μλ£ ({i+1}/{len(input_keywords_orig)})")
except Exception as e:
debug_log(f"'{kw}' μ°κ΄ ν€μλ μ‘°ν μ€ λ³λ ¬ μμ
μ€λ₯: {e}")
if not all_related_keywords_dfs:
debug_log("μ°κ΄ ν€μλ μ‘°ν κ²°κ³Όκ° λͺ¨λ λΉμ΄μμ΅λλ€.")
# λΉ DataFrameμ λΈλ‘κ·Έ λ¬Έμμ μ»¬λΌ μΆκ°
empty_df = pd.DataFrame(columns=["μ 보ν€μλ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ"])
empty_df["λΈλ‘κ·Έλ¬Έμμ"] = None
return empty_df, create_excel_file(empty_df)
result_df = pd.concat(all_related_keywords_dfs, ignore_index=True)
result_df.drop_duplicates(subset=["μ 보ν€μλ"], inplace=True) # μ€λ³΅ μ κ±°
debug_log(f"μ°κ΄ ν€μλ λ³λ ¬ μ²λ¦¬ μλ£. ν΅ν©λ DataFrame shape: {result_df.shape}")
# 2. fetch_blog_count λ³λ ¬ μ²λ¦¬
keywords_for_blog_count = result_df["μ 보ν€μλ"].dropna().unique().tolist()
blog_counts_map = {}
if keywords_for_blog_count:
debug_log(f"λΈλ‘κ·Έ λ¬Έμ μ μ‘°ν λ³λ ¬ μ²λ¦¬ μμ (ν€μλ {len(keywords_for_blog_count)}κ°, μ΅λ μμ
μ μ: {MAX_WORKERS_BLOG_COUNT})")
with ThreadPoolExecutor(max_workers=MAX_WORKERS_BLOG_COUNT) as executor:
future_to_keyword_blog = {
executor.submit(fetch_blog_count, kw): kw for kw in keywords_for_blog_count
}
for i, future in enumerate(as_completed(future_to_keyword_blog)):
kw = future_to_keyword_blog[future]
try:
count = future.result() # μ«μ λ°ν
blog_counts_map[kw] = count
if (i+1) % 50 == 0: # λ무 λ§μ λ‘κ·Έ λ°©μ§
debug_log(f"λΈλ‘κ·Έ μ μ‘°ν μ§ν μ€... ({i+1}/{len(keywords_for_blog_count)})")
except Exception as e:
debug_log(f"'{kw}' λΈλ‘κ·Έ μ μ‘°ν μ€ λ³λ ¬ μμ
μ€λ₯: {e}")
blog_counts_map[kw] = 0 # μ€λ₯ μ 0μΌλ‘ μ²λ¦¬
result_df["λΈλ‘κ·Έλ¬Έμμ"] = result_df["μ 보ν€μλ"].map(blog_counts_map).fillna(0).astype(int)
debug_log("λΈλ‘κ·Έ λ¬Έμ μ λ³λ ¬ μ²λ¦¬ μλ£.")
else:
result_df["λΈλ‘κ·Έλ¬Έμμ"] = 0 # μ‘°νν ν€μλκ° μμΌλ©΄ 0μΌλ‘ μ±μ
result_df.sort_values(by="ν νμκ²μλ", ascending=False, inplace=True)
debug_log(f"process_keyword μ΅μ’
μλ£. DataFrame shape: {result_df.shape}")
# μ΅μ’
μ»¬λΌ μμ λ° μ‘΄μ¬ μ¬λΆ νμΈ
final_columns = ["μ 보ν€μλ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]
for col in final_columns:
if col not in result_df.columns:
result_df[col] = 0 if col != "μ 보ν€μλ" else "" # μλ 컬λΌμ κΈ°λ³Έκ°μΌλ‘ μ±μ
result_df = result_df[final_columns] # μ»¬λΌ μμ κ³ μ
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 pd.DataFrame(columns=["λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]), ""
if remove_freq1:
before_count = len(df_freq)
df_freq = df_freq[df_freq["λΉλμ"] > 1].copy() # .copy() μΆκ°
debug_log(f"λΉλμ 1 μ κ±° μ μ©λ¨. {before_count} -> {len(df_freq)}")
if df_freq.empty:
debug_log("λΉλμ 1 μ κ±° ν λ°μ΄ν°κ° μμ΅λλ€.")
return pd.DataFrame(columns=["λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]), ""
keywords_from_morph = "\n".join(df_freq["λ¨μ΄"].tolist())
debug_log(f"ννμ λΆμ κΈ°λ° ν€μλ ({len(df_freq['λ¨μ΄'])}κ°)μ λν μ 보 μ‘°ν μμ")
# process_keywordλ μ°κ΄ ν€μλλ₯Ό ν¬ν¨νμ§ μλλ‘ νΈμΆ (include_related=False)
df_keyword_info, _ = process_keyword(keywords_from_morph, include_related=False)
debug_log("ννμ λΆμ ν€μλμ λν κ²μλ λ° λΈλ‘κ·Έλ¬Έμμ μ‘°ν μλ£")
if df_keyword_info.empty:
debug_log("ννμ λΆμ ν€μλμ λν API μ 보 μ‘°ν κ²°κ³Όκ° μμ΅λλ€.")
# df_freqμ λΉ μ»¬λΌλ€ μΆκ°
for col in ["PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]:
df_freq[col] = None
merged_df = df_freq
else:
merged_df = pd.merge(df_freq, df_keyword_info, left_on="λ¨μ΄", right_on="μ 보ν€μλ", how="left")
if "μ 보ν€μλ" in merged_df.columns: # merge ν μ 보ν€μλ 컬λΌμ΄ μκ²Όλ€λ©΄ μμ
merged_df.drop(columns=["μ 보ν€μλ"], inplace=True, errors='ignore')
# λλ½λ μ»¬λΌ κΈ°λ³Έκ°μΌλ‘ μ±μ°κΈ°
expected_cols = ["λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]
for col in expected_cols:
if col not in merged_df.columns:
merged_df[col] = None if col not in ["λΉλμ"] else 0
merged_df = merged_df[expected_cols] # μ»¬λΌ μμ κ³ μ
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 ν¨μ μμ")
direct_keywords_list = [kw.strip() for kw in re.split(r'[\n,]+', keyword_input) if kw.strip()]
debug_log(f"μ
λ ₯λ μ§μ ν€μλ λͺ©λ‘: {direct_keywords_list}")
if not direct_keywords_list:
debug_log("μ§μ μ
λ ₯λ ν€μλκ° μμ΅λλ€.")
return pd.DataFrame(columns=["ν€μλ", "λΉλμ"]), ""
# 1. λ³Έλ¬Έ λ΄ λΉλμ κ³μ°
results_freq = []
for kw in direct_keywords_list:
count = text.count(kw) # λμλ¬Έμ ꡬλΆ, μ νν λ¬Έμμ΄ μΉ΄μ΄νΈ
results_freq.append({"ν€μλ": kw, "λΉλμ": count})
debug_log(f"μ§μ ν€μλ '{kw}'μ λ³Έλ¬Έ λ΄ λΉλμ: {count}")
df_direct_freq = pd.DataFrame(results_freq)
# 2. APIλ₯Ό ν΅ν΄ κ²μλ λ° λΈλ‘κ·Έ μ μ‘°ν (λ³λ ¬ μ²λ¦¬λ process_keyword μ¬μ©)
# μ¬κΈ°μλ κ° μ§μ ν€μλμ λν μ λ³΄λ§ νμνλ―λ‘ include_related=False
keywords_for_api = "\n".join(direct_keywords_list)
df_direct_api_info, _ = process_keyword(keywords_for_api, include_related=False)
# 3. λΉλμ κ²°κ³Όμ API κ²°κ³Ό λ³ν©
if not df_direct_api_info.empty:
# API κ²°κ³Όμ 'μ 보ν€μλ'λ₯Ό 'ν€μλ'λ‘ λ³κ²½νμ¬ λ³ν© κΈ°μ€ ν΅μΌ
df_direct_api_info.rename(columns={"μ 보ν€μλ": "ν€μλ"}, inplace=True)
merged_df = pd.merge(df_direct_freq, df_direct_api_info, on="ν€μλ", how="left")
else:
merged_df = df_direct_freq
for col in ["PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]:
merged_df[col] = None # API μ λ³΄κ° μμ κ²½μ° λΉ μ»¬λΌ μΆκ°
# μ»¬λΌ μμ λ° κΈ°λ³Έκ° μ 리
final_cols = ["ν€μλ", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]
for col in final_cols:
if col not in merged_df.columns:
merged_df[col] = 0 if col != "ν€μλ" else ""
merged_df = merged_df[final_cols]
excel_path = create_excel_file(merged_df)
debug_log("direct_keyword_analysis ν¨μ μλ£")
return merged_df, excel_path
# --- ν΅ν© λΆμ (ννμ λΆμ + μ§μ ν€μλ λΆμ) ---
def combined_analysis(blog_text: str, remove_freq1: bool, direct_keyword_input: str):
debug_log("combined_analysis ν¨μ μμ")
# 1. ννμ λΆμ κΈ°λ° κ²°κ³Ό (API μ 보 ν¬ν¨)
df_morph, _ = morphological_analysis_and_enrich(blog_text, remove_freq1)
# df_morph 컬λΌ: "λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"
# 2. μ§μ μ
λ ₯ ν€μλ μ²λ¦¬
direct_keywords_list = [kw.strip() for kw in re.split(r'[\n,]+', direct_keyword_input) if kw.strip()]
debug_log(f"ν΅ν© λΆμ - μ
λ ₯λ μ§μ ν€μλ: {direct_keywords_list}")
if not direct_keywords_list: # μ§μ μ
λ ₯ ν€μλκ° μμΌλ©΄ ννμ λΆμ κ²°κ³Όλ§ λ°ν
if "μ§μ μ
λ ₯" not in df_morph.columns and not df_morph.empty:
df_morph["μ§μ μ
λ ₯"] = "" # μ§μ μ
λ ₯ μ»¬λΌ μΆκ°
# μ»¬λΌ μμ μ‘°μ
cols = ["λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ", "μ§μ μ
λ ₯"]
for col in cols:
if col not in df_morph.columns:
df_morph[col] = "" if col == "μ§μ μ
λ ₯" else (0 if col != "λ¨μ΄" else "")
df_morph = df_morph[cols]
return df_morph, create_excel_file(df_morph)
# μ§μ μ
λ ₯ ν€μλμ λν μ 보 (λΉλμ, API μ 보) κ°μ Έμ€κΈ°
# direct_keyword_analysisλ "ν€μλ" 컬λΌμ μ¬μ©νλ―λ‘, df_morphμ "λ¨μ΄"μ ν΅μΌ νμ
df_direct_raw, _ = direct_keyword_analysis(blog_text, direct_keyword_input)
# df_direct_raw 컬λΌ: "ν€μλ", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"
df_direct_raw.rename(columns={"ν€μλ": "λ¨μ΄"}, inplace=True) # 컬λΌλͺ
ν΅μΌ
# ννμ λΆμ κ²°κ³Όμ 'μ§μ μ
λ ₯' νκΈ°
if not df_morph.empty:
df_morph["μ§μ μ
λ ₯"] = df_morph["λ¨μ΄"].apply(lambda x: "μ§μ μ
λ ₯" if x in direct_keywords_list else "")
else: # ννμ λΆμ κ²°κ³Όκ° λΉμ΄μμ μ μμ
df_morph = pd.DataFrame(columns=["λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ", "μ§μ μ
λ ₯"])
# μ§μ μ
λ ₯λ ν€μλ μ€ ννμ λΆμ κ²°κ³Όμ μλ κ²λ€μ μΆκ°
# df_direct_rawμλ λͺ¨λ μ§μ μ
λ ₯ ν€μλμ μ λ³΄κ° μμ
# df_morphμ df_direct_rawλ₯Ό ν©μΉλ, 'λ¨μ΄' κΈ°μ€μΌλ‘ μ€λ³΅ μ²λ¦¬
# λ¨Όμ df_direct_rawμ 'μ§μ μ
λ ₯' 컬λΌμ μΆκ°νκ³ "μ§μ μ
λ ₯"μΌλ‘ μ±μ
df_direct_raw["μ§μ μ
λ ₯"] = "μ§μ μ
λ ₯"
# df_morphμ μλ λ¨μ΄λ df_morph μ 보λ₯Ό μ°μ μ¬μ© (μ§μ μ
λ ₯ νλκ·Έλ§ μ
λ°μ΄νΈ)
# df_direct_rawμμ df_morphμ μλ λ¨μ΄λ§ 골λΌμ μΆκ°
# ν©μΉκΈ°: df_morphλ₯Ό κΈ°μ€μΌλ‘ df_direct_rawμ μ 보λ₯Ό μΆκ°/μ
λ°μ΄νΈ
# Pandas 0.25.0 μ΄μμμλ combine_firstμ overwrite λμμ΄ μ½κ° λ€λ₯Ό μ μμΌλ―λ‘ merge μ¬μ© κ³ λ €
# 1. df_morphμ λ¨μ΄λ€μ λν΄ df_direct_rawμ μ λ³΄λ‘ μ
λ°μ΄νΈ (API μ 보 λ±)
# λ¨, λΉλμλ κ°μ κ³μ°ν κ²μ μ μ§ν μ§, μλλ©΄ νμͺ½μ νν μ§ κ²°μ νμ.
# μ¬κΈ°μλ df_morphμ λΉλμ(ννμλΆμ κΈ°λ°)μ df_direct_rawμ λΉλμ(λ¨μ count)κ° λ€λ₯Ό μ μμ.
# μΌλ¨μ df_morph κΈ°μ€μΌλ‘ νκ³ , μλ μ§μ ν€μλλ§ df_direct_rawμμ μΆκ°νλ λ°©μ.
# df_morphμ 'μ§μ μ
λ ₯' 컬λΌμ μ΄λ―Έ μμμ μ²λ¦¬λ¨.
# μ΄μ df_direct_rawμλ§ μλ ν€μλλ₯Ό df_morphμ μΆκ°
# df_morphμ μλ λ¨μ΄ λͺ©λ‘
morph_words = df_morph['λ¨μ΄'].tolist() if not df_morph.empty else []
rows_to_add = []
for idx, row in df_direct_raw.iterrows():
if row['λ¨μ΄'] not in morph_words:
rows_to_add.append(row)
if rows_to_add:
df_to_add = pd.DataFrame(rows_to_add)
combined_df = pd.concat([df_morph, df_to_add], ignore_index=True)
else:
combined_df = df_morph.copy() # df_morphκ° λΉμ΄μμ μλ μμ
# μ΅μ’
μ»¬λΌ μ 리 λ° μμ
final_cols_combined = ["λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ", "μ§μ μ
λ ₯"]
for col in final_cols_combined:
if col not in combined_df.columns:
# κΈ°λ³Έκ° μ€μ : 'μ§μ μ
λ ₯'μ "", λλ¨Έμ§λ 0 λλ None (API κ°μ None νμ©)
if col == "μ§μ μ
λ ₯":
combined_df[col] = ""
elif col == "λΉλμ":
combined_df[col] = 0
elif col == "λ¨μ΄":
combined_df[col] = ""
else: # API κ΄λ ¨ 컬λΌ
combined_df[col] = None # pd.NAλ κ°λ₯
# NA κ°λ€μ μ μ ν μ²λ¦¬ (μ: 0μΌλ‘ μ±μ°κ±°λ κ·Έλλ‘ λκΈ°)
# API κ°λ€μ μ«μκ° μλ μ μμΌλ―λ‘ (μ: "< 10"), process_keywordμμ μ²λ¦¬λ¨. μ¬κΈ°μλ intν λ³ν μ μ΄λ―λ‘ κ·Έλλ‘ λ .
# Gradio Dataframeμ Noneμ μ νμν¨.
# λΉλμλ μ μνμ΄μ΄μΌ ν¨
if "λΉλμ" in combined_df.columns:
combined_df["λΉλμ"] = combined_df["λΉλμ"].fillna(0).astype(int)
combined_df = combined_df[final_cols_combined].drop_duplicates(subset=['λ¨μ΄'], keep='first') # λ§μ½μ μν μ€λ³΅ μ κ±°
combined_df.sort_values(by=["μ§μ μ
λ ₯", "λΉλμ"], ascending=[False, False], inplace=True, na_position='last') # μ§μ μ
λ ₯ μ°μ , κ·Έ λ€μ λΉλμ
combined_df.reset_index(drop=True, inplace=True)
combined_excel = create_excel_file(combined_df)
debug_log("combined_analysis ν¨μ μλ£")
return combined_df, combined_excel
# --- λΆμ νΈλ€λ¬ ---
def analysis_handler(blog_text: str, remove_freq1: bool, direct_keyword_input: str, direct_keyword_only: bool):
debug_log(f"analysis_handler ν¨μ μμ. μ§μ ν€μλλ§ λΆμ: {direct_keyword_only}")
start_time = time.time()
if not blog_text or blog_text.strip() == "μ€ν¬λνλ λΈλ‘κ·Έ λ΄μ©μ΄ μ¬κΈ°μ νμλ©λλ€." or blog_text.strip() == "":
debug_log("λΆμν λΈλ‘κ·Έ λ΄μ©μ΄ μμ΅λλ€.")
# λΉ κ²°κ³Όλ₯Ό λ°ννκΈ° μν DataFrame ꡬ쑰 λͺ
μ
empty_cols_direct = ["ν€μλ", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]
empty_cols_combined = ["λ¨μ΄", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ", "μ§μ μ
λ ₯"]
df_empty = pd.DataFrame(columns=empty_cols_direct if direct_keyword_only else empty_cols_combined)
return df_empty, create_excel_file(df_empty)
if direct_keyword_only:
# "μ§μ ν€μλ μ
λ ₯λ§ λΆμ" μ ν μ λ¨λ
λΆμ μν
if not direct_keyword_input or not direct_keyword_input.strip():
debug_log("μ§μ ν€μλλ§ λΆμ μ νλμμΌλ, μ
λ ₯λ μ§μ ν€μλκ° μμ΅λλ€.")
empty_cols_direct = ["ν€μλ", "λΉλμ", "PCμκ²μλ", "λͺ¨λ°μΌμκ²μλ", "ν νμκ²μλ", "λΈλ‘κ·Έλ¬Έμμ"]
df_empty = pd.DataFrame(columns=empty_cols_direct)
return df_empty, create_excel_file(df_empty)
result_df, excel_path = direct_keyword_analysis(blog_text, direct_keyword_input)
else:
# κΈ°λ³Έ ν΅ν© λΆμ μν
result_df, excel_path = combined_analysis(blog_text, remove_freq1, direct_keyword_input)
end_time = time.time()
debug_log(f"analysis_handler μ΄ μ€ν μκ°: {end_time - start_time:.2f} μ΄")
return result_df, excel_path
# --- μ€ν¬λν μ€ν ---
def fetch_blog_content(url: str):
debug_log("fetch_blog_content ν¨μ μμ")
if not url or not url.strip():
return "λΈλ‘κ·Έ URLμ μ
λ ₯ν΄μ£ΌμΈμ."
if not url.startswith("http://") and not url.startswith("https://"):
return "μ ν¨ν URL νμ(http:// λλ https://)μΌλ‘ μ
λ ₯ν΄μ£ΌμΈμ."
start_time = time.time()
content = scrape_naver_blog(url)
end_time = time.time()
debug_log(f"fetch_blog_content μ΄ μ€ν μκ°: {end_time - start_time:.2f} μ΄. λ΄μ© κΈΈμ΄: {len(content)}")
return content
# --- Custom CSS ---
custom_css = """
/* μ 체 컨ν
μ΄λ μ€νμΌ */
.gradio-container {
max-width: 1080px; /* λλΉ νμ₯ */
margin: auto;
font-family: 'Helvetica Neue', Arial, sans-serif;
background: #f5f7fa;
padding: 2rem;
}
/* ν€λ μ€νμΌ */
.custom-header {
text-align: center;
font-size: 2.5rem;
font-weight: bold;
margin-bottom: 1.5rem;
color: #333;
}
/* κ·Έλ£Ή λ°μ€ μ€νμΌ */
.custom-group {
background: #ffffff;
border-radius: 8px;
padding: 1.5rem;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin-bottom: 1.5rem;
}
/* λ²νΌ μ€νμΌ */
.custom-button {
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
padding: 0.6rem 1.2rem;
font-size: 1rem;
cursor: pointer;
min-width: 150px; /* λ²νΌ μ΅μ λλΉ */
}
.custom-button:hover {
background-color: #0056b3;
}
/* 체ν¬λ°μ€ μ€νμΌ */
.custom-checkbox {
margin-right: 1rem;
}
/* κ²°κ³Ό ν
μ΄λΈ λ° λ€μ΄λ‘λ λ²νΌ */
.custom-result {
margin-top: 1.5rem;
}
/* κ°μ΄λ° μ λ ¬ */
.centered {
display: flex;
justify-content: center;
align-items: center;
}
"""
# --- Gradio μΈν°νμ΄μ€ κ΅¬μ± ---
with gr.Blocks(title="λ€μ΄λ² λΈλ‘κ·Έ ν€μλ λΆμ μλΉμ€", css=custom_css) as demo:
gr.HTML("<div class='custom-header'>λ€μ΄λ² λΈλ‘κ·Έ ν€μλ λΆμ μλΉμ€</div>")
with gr.Row():
with gr.Column(scale=2): # μΌμͺ½ μ»¬λΌ (μ
λ ₯ μμ)
with gr.Group(elem_classes="custom-group"):
blog_url_input = gr.Textbox(
label="λ€μ΄λ² λΈλ‘κ·Έ λ§ν¬",
placeholder="μ: https://blog.naver.com/μμ΄λ/κΈλ²νΈ",
lines=1,
info="λΆμν λ€μ΄λ² λΈλ‘κ·Έ κ²μλ¬Ό URLμ μ
λ ₯νμΈμ."
)
with gr.Row(elem_classes="centered"):
scrape_button = gr.Button("λΈλ‘κ·Έ λ΄μ© κ°μ Έμ€κΈ°", elem_classes="custom-button", variant="primary")
with gr.Group(elem_classes="custom-group"):
blog_content_box = gr.Textbox(
label="λΈλ‘κ·Έ λ΄μ© (μμ κ°λ₯)",
lines=10,
placeholder="μ€ν¬λνλ λΈλ‘κ·Έ λ΄μ©μ΄ μ¬κΈ°μ νμλ©λλ€. μ§μ μμ νκ±°λ λΆμ¬λ£μ μ μμ΅λλ€."
)
with gr.Group(elem_classes="custom-group"):
gr.Markdown("### λΆμ μ΅μ
μ€μ ")
with gr.Row():
remove_freq_checkbox = gr.Checkbox(
label="λΉλμ 1μΈ λ¨μ΄ μ κ±° (ννμ λΆμ μ)",
value=True,
elem_classes="custom-checkbox",
info="ννμ λΆμ κ²°κ³Όμμ λΉλμκ° 1μΈ λ¨μ΄λ₯Ό μ μΈν©λλ€."
)
with gr.Row():
direct_keyword_only_checkbox = gr.Checkbox(
label="μ§μ ν€μλλ§ λΆμ",
value=False,
elem_classes="custom-checkbox",
info="μ΄ μ΅μ
μ μ ννλ©΄ μλ μ
λ ₯ν μ§μ ν€μλμ λν΄μλ§ λΆμμ μνν©λλ€ (ννμ λΆμ μλ΅)."
)
with gr.Row():
direct_keyword_box = gr.Textbox(
label="μ§μ ν€μλ μ
λ ₯ (μν° λλ ','λ‘ κ΅¬λΆ)",
lines=3,
placeholder="μ: ν€μλ1, ν€μλ2\nν€μλ3\n...\n(ννμ λΆμ κ²°κ³Όμ λ³λλ‘ λΆμνκ±°λ, ν΅ν© λΆμμ μΆκ°ν ν€μλ)",
info="λΆμμ ν¬ν¨νκ±°λ λ¨λ
μΌλ‘ λΆμν ν€μλλ₯Ό μ§μ μ
λ ₯ν©λλ€."
)
with gr.Group(elem_classes="custom-group"):
with gr.Row(elem_classes="centered"):
analyze_button = gr.Button("ν€μλ λΆμ μ€ν", elem_classes="custom-button", variant="primary")
with gr.Column(scale=3): # μ€λ₯Έμͺ½ μ»¬λΌ (κ²°κ³Ό μμ)
with gr.Group(elem_classes="custom-group custom-result"):
gr.Markdown("### λΆμ κ²°κ³Ό")
result_df_display = gr.Dataframe(
label="ν΅ν© λΆμ κ²°κ³Ό (λ¨μ΄, λΉλμ, κ²μλ, λΈλ‘κ·Έλ¬Έμμ, μ§μ μ
λ ₯ μ¬λΆ)",
interactive=False, # μ¬μ©μκ° μ§μ μμ λΆκ°
height=600, # λμ΄ μ‘°μ
wrap=True # κΈ΄ ν
μ€νΈ μ€λ°κΏ
)
with gr.Group(elem_classes="custom-group"):
gr.Markdown("### κ²°κ³Ό λ€μ΄λ‘λ")
excel_file_display = gr.File(label="λΆμ κ²°κ³Ό Excel νμΌ λ€μ΄λ‘λ")
# μ΄λ²€νΈ μ°κ²°
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, direct_keyword_box, direct_keyword_only_checkbox],
outputs=[result_df_display, excel_file_display]
)
if __name__ == "__main__":
# νκ²½ λ³μ μ€μ μμ (μ€μ μ€ν μμλ μμ€ν
νκ²½ λ³μλ‘ μ€μ νκ±°λ, .env νμΌ λ±μ μ¬μ©)
# os.environ["NAVER_API_KEY"] = "YOUR_NAVER_API_KEY"
# os.environ["NAVER_SECRET_KEY"] = "YOUR_NAVER_SECRET_KEY"
# os.environ["NAVER_CUSTOMER_ID"] = "YOUR_NAVER_CUSTOMER_ID"
# os.environ["NAVER_SEARCH_CLIENT_ID"] = "YOUR_NAVER_SEARCH_CLIENT_ID"
# os.environ["NAVER_SEARCH_CLIENT_SECRET"] = "YOUR_NAVER_SEARCH_CLIENT_SECRET"
# νκ²½ λ³μ μ€μ νμΈ
required_env_vars = [
"NAVER_API_KEY", "NAVER_SECRET_KEY", "NAVER_CUSTOMER_ID",
"NAVER_SEARCH_CLIENT_ID", "NAVER_SEARCH_CLIENT_SECRET"
]
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
if missing_vars:
debug_log(f"κ²½κ³ : λ€μ νμ νκ²½ λ³μκ° μ€μ λμ§ μμμ΅λλ€ - {', '.join(missing_vars)}")
debug_log("API νΈμΆ κΈ°λ₯μ΄ μ μμ μΌλ‘ λμνμ§ μμ μ μμ΅λλ€.")
debug_log("μ€ν¬λ¦½νΈ μ€ν μ μ ν΄λΉ νκ²½ λ³μλ₯Ό μ€μ ν΄μ£ΌμΈμ.")
# Gradio μ±μ μ€ννλ, API νΈμΆ μ μ€λ₯κ° λ°μν μ μμμ μ¬μ©μμκ² μλ¦Ό.
debug_log("Gradio μ± μ€ν μμ")
demo.launch(debug=True) # κ°λ° μ€μλ debug=Trueλ‘ μ€μ νμ¬ μ€λ₯ νμΈ μ©μ΄
debug_log("Gradio μ± μ€ν μ’
λ£") |