File size: 21,077 Bytes
d5fb63f
 
f9c1fca
 
d5fb63f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c1fca
 
d5fb63f
 
 
 
 
 
 
 
 
 
f9c1fca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5fb63f
 
 
 
f9c1fca
d5fb63f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c1fca
 
c850803
d5fb63f
 
 
 
 
 
 
 
 
 
 
f9c1fca
 
 
d5fb63f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c850803
d5fb63f
 
f9c1fca
 
c850803
d5fb63f
 
 
 
 
 
 
 
f9c1fca
 
 
 
 
 
 
 
 
d5fb63f
 
 
 
f9c1fca
c850803
d5fb63f
 
f9c1fca
 
2c541cf
 
 
 
f9c1fca
2c541cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c1fca
 
 
 
2c541cf
 
 
 
f9c1fca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c850803
 
 
 
 
ce7fa06
 
 
 
c850803
 
f9c1fca
c850803
 
 
 
 
 
d5fb63f
f9c1fca
 
08f7932
 
 
 
 
 
 
 
 
f9c1fca
 
 
 
 
 
 
 
 
 
 
 
 
08f7932
 
 
 
 
f9c1fca
 
1a9c589
f9c1fca
1a9c589
 
 
 
 
 
 
 
 
 
f9c1fca
1a9c589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c541cf
f9c1fca
 
08f7932
 
f9c1fca
08f7932
f9c1fca
08f7932
f9c1fca
 
110447f
f9c1fca
110447f
 
ad33187
b3072ce
08f7932
b3072ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b06ebdb
 
 
 
b3072ce
 
 
 
b06ebdb
 
b3072ce
 
 
 
 
 
 
 
 
 
 
b06ebdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08f7932
b3072ce
 
 
b06ebdb
b3072ce
 
 
 
 
 
110447f
b3072ce
 
 
 
 
 
 
 
 
 
 
1a9c589
b3072ce
1a9c589
b06ebdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c1fca
110447f
b3072ce
 
 
d5fb63f
 
 
 
 
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
import gradio as gr
import requests
import aiohttp
import asyncio
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

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

# --- 넀이버 λΈ”λ‘œκ·Έ μŠ€ν¬λž˜ν•‘ (비동기 버전) ---
async 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:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers) as response:
                debug_log("HTTP GET μš”μ²­(메인 νŽ˜μ΄μ§€) μ™„λ£Œ")
                if response.status != 200:
                    debug_log(f"μš”μ²­ μ‹€νŒ¨, μƒνƒœμ½”λ“œ: {response.status}")
                    return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μƒνƒœμ½”λ“œ: {response.status}"
                html = await response.text()
                soup = BeautifulSoup(html, "html.parser")
                debug_log("HTML νŒŒμ‹±(메인 νŽ˜μ΄μ§€) μ™„λ£Œ")
                iframe = soup.select_one("iframe#mainFrame")
                if not iframe:
                    debug_log("iframe#mainFrame νƒœκ·Έλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
                    return "λ³Έλ¬Έ iframe을 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
                iframe_src = iframe.get("src")
                if not iframe_src:
                    debug_log("iframe srcκ°€ μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.")
                    return "λ³Έλ¬Έ iframe의 srcλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
                parsed_iframe_url = urllib.parse.urljoin(url, iframe_src)
                debug_log(f"iframe νŽ˜μ΄μ§€ μš”μ²­ URL: {parsed_iframe_url}")
            async with aiohttp.ClientSession() as session:
                async with session.get(parsed_iframe_url, headers=headers) as iframe_response:
                    debug_log("HTTP GET μš”μ²­(iframe νŽ˜μ΄μ§€) μ™„λ£Œ")
                    if iframe_response.status != 200:
                        debug_log(f"iframe μš”μ²­ μ‹€νŒ¨, μƒνƒœμ½”λ“œ: {iframe_response.status}")
                        return f"iframeμ—μ„œ 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μƒνƒœμ½”λ“œ: {iframe_response.status}"
                    iframe_html = await iframe_response.text()
                    iframe_soup = BeautifulSoup(iframe_html, "html.parser")
                    debug_log("HTML νŒŒμ‹±(iframe νŽ˜μ΄μ§€) μ™„λ£Œ")
                    title_div = iframe_soup.select_one('.se-module.se-module-text.se-title-text')
                    title = title_div.get_text(strip=True) if title_div else "제λͺ©μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
                    debug_log(f"μΆ”μΆœλœ 제λͺ©: {title}")
                    content_div = iframe_soup.select_one('.se-main-container')
                    if content_div:
                        content = content_div.get_text("\n", strip=True)
                    else:
                        content = "본문을 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
                    debug_log("λ³Έλ¬Έ μΆ”μΆœ μ™„λ£Œ")
                    result = f"[제λͺ©]\n{title}\n\n[λ³Έλ¬Έ]\n{content}"
                    debug_log("제λͺ©κ³Ό λ³Έλ¬Έ ν•©μΉ¨ μ™„λ£Œ")
                    return result
    except Exception as e:
        debug_log(f"μ—λŸ¬ λ°œμƒ: {str(e)}")
        return f"μŠ€ν¬λž˜ν•‘ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"

# --- 넀이버 검색 및 κ΄‘κ³  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
    }

# --- μ—°κ΄€ ν‚€μ›Œλ“œ 쑰회 (비동기) ---
async def fetch_related_keywords(keyword):
    debug_log(f"fetch_related_keywords 호좜, ν‚€μ›Œλ“œ: {keyword}")
    API_KEY = os.environ["NAVER_API_KEY"]
    SECRET_KEY = os.environ["NAVER_SECRET_KEY"]
    CUSTOMER_ID = os.environ["NAVER_CUSTOMER_ID"]
    BASE_URL = "https://api.naver.com"
    uri = "/keywordstool"
    method = "GET"
    headers = get_header(method, uri, API_KEY, SECRET_KEY, CUSTOMER_ID)
    params = {
        "hintKeywords": [keyword],
        "showDetail": "1"
    }
    async with aiohttp.ClientSession() as session:
        async with session.get(BASE_URL + uri, headers=headers, params=params) as response:
            data = await response.json()
    if "keywordList" not in data:
        return pd.DataFrame()
    df = pd.DataFrame(data["keywordList"])
    if len(df) > 100:
        df = df.head(100)
    def parse_count(x):
        try:
            return int(str(x).replace(",", ""))
        except:
            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)
    result_df = df[["μ •λ³΄ν‚€μ›Œλ“œ", "PCμ›”κ²€μƒ‰λŸ‰", "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰", "ν† νƒˆμ›”κ²€μƒ‰λŸ‰"]]
    debug_log("fetch_related_keywords μ™„λ£Œ")
    return result_df

# --- λΈ”λ‘œκ·Έ λ¬Έμ„œμˆ˜ 쑰회 (비동기) ---
async def fetch_blog_count(keyword):
    debug_log(f"fetch_blog_count 호좜, ν‚€μ›Œλ“œ: {keyword}")
    client_id = os.environ["NAVER_SEARCH_CLIENT_ID"]
    client_secret = os.environ["NAVER_SEARCH_CLIENT_SECRET"]
    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}
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers, params=params) as response:
            if response.status == 200:
                data = await response.json()
                debug_log(f"fetch_blog_count κ²°κ³Ό: {data.get('total', 0)}")
                return data.get("total", 0)
            else:
                debug_log(f"fetch_blog_count 였λ₯˜, μƒνƒœμ½”λ“œ: {response.status}")
                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, engine='openpyxl')
    debug_log(f"Excel 파일 생성됨: {excel_path}")
    return excel_path

# --- ν‚€μ›Œλ“œ 검색 (비동기) ---
async 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()]
    result_dfs = []
    for idx, kw in enumerate(input_keywords):
        df_kw = await fetch_related_keywords(kw)
        if df_kw.empty:
            continue
        row_kw = df_kw[df_kw["μ •λ³΄ν‚€μ›Œλ“œ"] == kw]
        if not row_kw.empty:
            result_dfs.append(row_kw)
        else:
            result_dfs.append(df_kw.head(1))
        if include_related and idx == 0:
            df_related = df_kw[df_kw["μ •λ³΄ν‚€μ›Œλ“œ"] != kw]
            if not df_related.empty:
                result_dfs.append(df_related)
    if result_dfs:
        result_df = pd.concat(result_dfs, ignore_index=True)
        result_df.drop_duplicates(subset=["μ •λ³΄ν‚€μ›Œλ“œ"], inplace=True)
    else:
        result_df = pd.DataFrame(columns=["μ •λ³΄ν‚€μ›Œλ“œ", "PCμ›”κ²€μƒ‰λŸ‰", "λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰", "ν† νƒˆμ›”κ²€μƒ‰λŸ‰"])
    # λΈ”λ‘œκ·Έ λ¬Έμ„œμˆ˜ 쑰회λ₯Ό λ³‘λ ¬λ‘œ 처리
    tasks = [fetch_blog_count(kw) for kw in result_df["μ •λ³΄ν‚€μ›Œλ“œ"]]
    counts = await asyncio.gather(*tasks)
    result_df["λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜"] = counts
    result_df.sort_values(by="ν† νƒˆμ›”κ²€μƒ‰λŸ‰", ascending=False, inplace=True)
    debug_log("process_keyword μ™„λ£Œ")
    return result_df, create_excel_file(result_df)

# --- ν˜•νƒœμ†Œ 뢄석 (μ°Έκ³  μ½”λ“œ-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

# --- ν˜•νƒœμ†Œ 뢄석과 κ²€μƒ‰λŸ‰/λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜ 병합 (비동기) ---
async 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 = "\n".join(df_freq["단어"].tolist())
    debug_log(f"λΆ„μ„λœ ν‚€μ›Œλ“œ: {keywords}")
    df_keyword_info, _ = await process_keyword(keywords, include_related=False)
    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

# --- 직접 ν‚€μ›Œλ“œ 뢄석 (단독 뢄석, 비동기) ---
async 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}")
        # 직접 μž…λ ₯ ν‚€μ›Œλ“œκ°€ 본문에 μ—†μœΌλ©΄ μΆ”κ°€ 쑰회
        if kw not in text:
            df_direct, _ = await process_keyword(kw, include_related=False)
            if (not df_direct.empty) and (kw in df_direct["μ •λ³΄ν‚€μ›Œλ“œ"].values):
                row = df_direct[df_direct["μ •λ³΄ν‚€μ›Œλ“œ"] == kw].iloc[0]
                pc = row.get("PCμ›”κ²€μƒ‰λŸ‰", None)
                mobile = row.get("λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰", None)
                total = row.get("ν† νƒˆμ›”κ²€μƒ‰λŸ‰", None)
                blog_count = row.get("λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜", None)
            else:
                pc = mobile = total = blog_count = None
            # 결과에 μƒˆ ν–‰ μΆ”κ°€
            results.append((kw, count))
    df = pd.DataFrame(results, columns=["ν‚€μ›Œλ“œ", "λΉˆλ„μˆ˜"])
    excel_path = create_excel_file(df)
    debug_log("direct_keyword_analysis ν•¨μˆ˜ μ™„λ£Œ")
    return df, excel_path

# --- 톡합 뢄석 (ν˜•νƒœμ†Œ 뢄석 + 직접 ν‚€μ›Œλ“œ 뢄석, 비동기) ---
async def combined_analysis(blog_text: str, remove_freq1: bool, direct_keyword_input: str):
    debug_log("combined_analysis ν•¨μˆ˜ μ‹œμž‘")
    merged_df, _ = await 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)
            df_direct, _ = await process_keyword(dk, include_related=False)
            if (not df_direct.empty) and (dk in df_direct["μ •λ³΄ν‚€μ›Œλ“œ"].values):
                row = df_direct[df_direct["μ •λ³΄ν‚€μ›Œλ“œ"] == dk].iloc[0]
                pc = row.get("PCμ›”κ²€μƒ‰λŸ‰", None)
                mobile = row.get("λͺ¨λ°”μΌμ›”κ²€μƒ‰λŸ‰", None)
                total = row.get("ν† νƒˆμ›”κ²€μƒ‰λŸ‰", None)
                blog_count = row.get("λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜", None)
            else:
                pc = mobile = total = blog_count = None
            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

# --- 뢄석 ν•Έλ“€λŸ¬ (비동기) ---
async def analysis_handler(blog_text: str, remove_freq1: bool, direct_keyword_input: str, direct_keyword_only: bool):
    debug_log("analysis_handler ν•¨μˆ˜ μ‹œμž‘")
    if direct_keyword_only:
        return await direct_keyword_analysis(blog_text, direct_keyword_input)
    else:
        return await combined_analysis(blog_text, remove_freq1, direct_keyword_input)

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

# --- Custom CSS ---
custom_css = """
/* 전체 μ»¨ν…Œμ΄λ„ˆ μŠ€νƒ€μΌ */
.gradio-container {
    max-width: 960px;
    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;
    transition: background-color 0.3s;
}
.custom-button:hover {
    background-color: #0056b3;
}
/* μ²΄ν¬λ°•μŠ€ μŠ€νƒ€μΌ */
.custom-checkbox {
    margin-right: 1rem;
    font-size: 1rem;
    font-weight: bold;
}
/* κ²°κ³Ό ν…Œμ΄λΈ” 및 λ‹€μš΄λ‘œλ“œ λ²„νŠΌ */
.custom-result {
    margin-top: 1.5rem;
}
/* κ°€μš΄λ° μ •λ ¬ */
.centered {
    display: flex;
    justify-content: center;
    align-items: center;
}
/* μ‚¬μš©μ„€λͺ… μŠ€νƒ€μΌ */
.usage-instructions {
    font-size: 1.1rem;
    line-height: 1.6;
    color: #555;
    background: #fff;
    padding: 1.5rem;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    margin-top: 2rem;
}
.usage-instructions h2 {
    font-size: 1.8rem;
    font-weight: bold;
    margin-bottom: 1rem;
    color: #333;
}
.usage-instructions ul {
    list-style: disc;
    margin-left: 2rem;
}
"""

# --- Gradio μΈν„°νŽ˜μ΄μŠ€ ꡬ성 ---
with gr.Blocks(title="넀이버 λΈ”λ‘œκ·Έ ν˜•νƒœμ†Œ 뢄석 μ„œλΉ„μŠ€", css=custom_css) as demo:
    gr.HTML("<div class='custom-header'>넀이버 λΈ”λ‘œκ·Έ ν˜•νƒœμ†Œ 뢄석 μ„œλΉ„μŠ€ πŸš€</div>")
    with gr.Group(elem_classes="custom-group"):
        with gr.Row():
            blog_url_input = gr.Textbox(label="넀이버 λΈ”λ‘œκ·Έ 링크", placeholder="예: https://blog.naver.com/ssboost/222983068507", lines=1)
        with gr.Row(elem_classes="centered"):
            scrape_button = gr.Button("μŠ€ν¬λž˜ν•‘ μ‹€ν–‰", elem_classes="custom-button")
    with gr.Group(elem_classes="custom-group"):
        blog_content_box = gr.Textbox(label="λΈ”λ‘œκ·Έ λ‚΄μš© (μˆ˜μ • κ°€λŠ₯)", lines=10, placeholder="μŠ€ν¬λž˜ν•‘λœ λΈ”λ‘œκ·Έ λ‚΄μš©μ΄ 여기에 ν‘œμ‹œλ©λ‹ˆλ‹€.")
    with gr.Group(elem_classes="custom-group"):
        with gr.Row():
            remove_freq_checkbox = gr.Checkbox(label="λΉˆλ„μˆ˜1 제거", value=True, elem_classes="custom-checkbox")
        with gr.Row():
            direct_keyword_only_checkbox = gr.Checkbox(label="직접 ν‚€μ›Œλ“œ μž…λ ₯만 뢄석", value=False, elem_classes="custom-checkbox")
        with gr.Row():
            direct_keyword_box = gr.Textbox(label="직접 ν‚€μ›Œλ“œ μž…λ ₯ (μ—”ν„° λ˜λŠ” ','둜 ꡬ뢄)", lines=2, placeholder="예: ν‚€μ›Œλ“œ1, ν‚€μ›Œλ“œ2\nν‚€μ›Œλ“œ3")
    with gr.Group(elem_classes="custom-group"):
        with gr.Row(elem_classes="centered"):
            analyze_button = gr.Button("뢄석 μ‹€ν–‰", elem_classes="custom-button")
    with gr.Group(elem_classes="custom-group custom-result"):
        result_df = gr.Dataframe(label="톡합 뢄석 κ²°κ³Ό (단어, λΉˆλ„μˆ˜, κ²€μƒ‰λŸ‰, λΈ”λ‘œκ·Έλ¬Έμ„œμˆ˜, μ§μ ‘μž…λ ₯)", interactive=True)
    with gr.Group(elem_classes="custom-group"):
        excel_file = gr.File(label="Excel λ‹€μš΄λ‘œλ“œ")
    with gr.Group(elem_classes="custom-group"):
        usage_html = gr.HTML("""
        <div class="usage-instructions">
            <h2>μ‚¬μš© μ„€λͺ… πŸ“–</h2>
            <ul>
                <li>πŸ”— <strong>넀이버 λΈ”λ‘œκ·Έ 링크</strong>: 뢄석할 넀이버 λΈ”λ‘œκ·Έμ˜ URL을 μž…λ ₯ν•˜μ„Έμš”.</li>
                <li>βœ‚οΈ <strong>μŠ€ν¬λž˜ν•‘ μ‹€ν–‰</strong>: 링크 μž…λ ₯ ν›„ λ²„νŠΌμ„ ν΄λ¦­ν•˜λ©΄ λΈ”λ‘œκ·Έμ˜ 제λͺ©κ³Ό 본문이 μžλ™μœΌλ‘œ λΆˆλŸ¬μ™€μ§‘λ‹ˆλ‹€.</li>
                <li>πŸ“ <strong>λΈ”λ‘œκ·Έ λ‚΄μš© (μˆ˜μ • κ°€λŠ₯)</strong>: 뢈러온 λΈ”λ‘œκ·Έ λ‚΄μš©μ΄ ν‘œμ‹œλ˜λ©°, ν•„μš”μ— 따라 직접 μˆ˜μ •ν•  수 μžˆμŠ΅λ‹ˆλ‹€.</li>
                <li>βš™οΈ <strong>μ˜΅μ…˜ μ„€μ •</strong>:
                    <ul>
                        <li><em>λΉˆλ„μˆ˜1 제거</em>: κΈ°λ³Έ μ„ νƒλ˜μ–΄ 있으며, λΉˆλ„μˆ˜κ°€ 1인 λ‹¨μ–΄λŠ” κ²°κ³Όμ—μ„œ μ œμ™Έν•©λ‹ˆλ‹€.</li>
                        <li><em>직접 ν‚€μ›Œλ“œ μž…λ ₯만 뢄석</em>: 이 μ˜΅μ…˜μ„ μ„ νƒν•˜λ©΄, λΈ”λ‘œκ·Έ λ³Έλ¬Έμ—μ„œ 직접 μž…λ ₯ν•œ ν‚€μ›Œλ“œλ§Œ λΆ„μ„ν•©λ‹ˆλ‹€.</li>
                    </ul>
                </li>
                <li>πŸ”€ <strong>직접 ν‚€μ›Œλ“œ μž…λ ₯</strong>: μ—”ν„° λ˜λŠ” μ‰Όν‘œ(,)둜 κ΅¬λΆ„ν•˜μ—¬ 뢄석할 ν‚€μ›Œλ“œλ₯Ό μž…λ ₯ν•˜μ„Έμš”.</li>
                <li>πŸš€ <strong>뢄석 μ‹€ν–‰</strong>: μ„€μ •ν•œ μ˜΅μ…˜μ— 따라 ν˜•νƒœμ†Œ 뢄석 및 ν‚€μ›Œλ“œ 뢄석이 μˆ˜ν–‰λ˜μ–΄ κ²°κ³Όκ°€ ν‘œμ™€ Excel 파일둜 좜λ ₯λ©λ‹ˆλ‹€.</li>
                <li>πŸ“₯ <strong>Excel λ‹€μš΄λ‘œλ“œ</strong>: 뢄석 κ²°κ³Όλ₯Ό Excel 파일둜 λ‹€μš΄λ‘œλ“œν•  수 μžˆμŠ΅λ‹ˆλ‹€.</li>
            </ul>
            <p><strong>Tip:</strong> 뢄석 κ²°κ³ΌλŠ” μ‹€μ‹œκ°„μœΌλ‘œ μ—…λ°μ΄νŠΈλ˜λ©°, ν•„μš”μ‹œ μˆ˜μ • ν›„ λ‹€μ‹œ 뢄석할 수 μžˆμŠ΅λ‹ˆλ‹€. 즐거운 뢄석 λ˜μ„Έμš”! 😊</p>
        </div>
        """)
    # 이벀트 μ—°κ²° (비동기 ν•¨μˆ˜ μ‚¬μš©)
    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, excel_file])

if __name__ == "__main__":
    debug_log("Gradio μ•± μ‹€ν–‰ μ‹œμž‘")
    demo.launch()
    debug_log("Gradio μ•± μ‹€ν–‰ μ’…λ£Œ")