Spaces:
Paused

File size: 28,918 Bytes
f9fe182
 
 
0ac0dbc
 
eb5e8ef
e72db42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9fe182
 
 
 
 
 
ee41baf
f9fe182
 
 
 
ee41baf
f9fe182
 
 
 
 
35278ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4a8164
f9fe182
 
 
954f824
 
 
 
 
f9fe182
79dd8b3
 
 
 
 
f4cb96e
79dd8b3
 
 
 
 
 
 
 
 
f4cb96e
79dd8b3
 
 
 
 
ee41baf
 
d8a29fe
 
79dd8b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85f8c2
 
954f824
e85f8c2
 
 
 
d8a29fe
79dd8b3
 
954f824
ee41baf
 
e85f8c2
ee41baf
 
954f824
ee41baf
 
 
 
 
 
 
 
 
d8a29fe
ee41baf
 
 
d8a29fe
e85f8c2
 
ee41baf
 
 
 
 
 
 
e85f8c2
 
 
 
 
 
79dd8b3
 
ee41baf
 
 
 
79dd8b3
e85f8c2
79dd8b3
e85f8c2
ee41baf
 
 
 
 
 
 
e85f8c2
d8a29fe
 
e85f8c2
79dd8b3
 
 
ee41baf
 
 
 
79dd8b3
d8a29fe
79dd8b3
ee41baf
 
 
e4a8164
ee41baf
 
 
 
 
 
 
 
 
 
d8a29fe
79dd8b3
e85f8c2
ee41baf
 
 
 
 
 
 
e85f8c2
 
79dd8b3
e85f8c2
 
ee41baf
e85f8c2
 
ee41baf
 
 
 
79dd8b3
e85f8c2
 
 
79dd8b3
e85f8c2
 
 
 
 
 
 
79dd8b3
 
ee41baf
 
 
 
 
 
 
79dd8b3
 
ee41baf
 
 
 
79dd8b3
 
 
 
f9fe182
 
 
 
79dd8b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb5e8ef
 
 
 
 
 
 
 
 
 
f4cb96e
 
eb5e8ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35278ad
eb5e8ef
35278ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e72db42
35278ad
 
eb5e8ef
 
 
 
35278ad
 
 
eb5e8ef
 
 
35278ad
 
 
e72db42
 
 
 
 
 
eb5e8ef
 
 
 
 
 
 
 
 
 
f4cb96e
 
 
 
 
 
 
 
 
 
 
 
35278ad
 
eb5e8ef
 
 
f4cb96e
35278ad
 
e72db42
 
 
 
 
 
 
 
 
 
35278ad
 
 
 
 
eb5e8ef
 
 
 
35278ad
 
 
 
eb5e8ef
 
e72db42
f9fe182
 
 
 
eb5e8ef
f9fe182
 
e4a8164
f9fe182
 
eb5e8ef
f9fe182
 
35278ad
f9fe182
 
 
 
35278ad
e72db42
eb5e8ef
 
 
 
0ac0dbc
eb5e8ef
 
 
 
 
 
35278ad
f9fe182
 
 
 
 
 
eb5e8ef
 
 
 
 
 
 
 
 
f4cb96e
e72db42
 
 
35278ad
e72db42
 
35278ad
f4cb96e
 
 
 
 
 
 
 
eb5e8ef
35278ad
f9fe182
 
 
 
f4cb96e
 
 
 
 
 
 
35278ad
eb5e8ef
35278ad
 
e72db42
35278ad
 
 
 
e72db42
eb5e8ef
 
f9fe182
 
 
 
 
 
eb5e8ef
f9fe182
e72db42
f9fe182
eb5e8ef
f9fe182
eb5e8ef
 
35278ad
 
 
 
e72db42
 
eb5e8ef
 
 
 
 
f4cb96e
e72db42
35278ad
e72db42
 
 
 
 
f9fe182
 
 
 
 
 
 
 
 
e4a8164
e72db42
eb5e8ef
f9fe182
 
 
eb5e8ef
 
 
e72db42
 
eb5e8ef
f9fe182
 
eb5e8ef
e72db42
eb5e8ef
f9fe182
 
 
 
 
 
 
e4a8164
f9fe182
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
import re
import pandas as pd
import io
import tempfile
import os
from collections import Counter, defaultdict
import gradio as gr
import requests
import time
import hmac
import hashlib
import base64
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading

# ๋„ค์ด๋ฒ„ 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):
    """ํ‚ค์›Œ๋“œ ๋ฐฐ์น˜์— ๋Œ€ํ•œ ๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ์กฐํšŒ"""
    try:
        # ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ API ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
        API_KEY = os.environ.get("NAVER_API_KEY")
        SECRET_KEY = os.environ.get("NAVER_SECRET_KEY")
        CUSTOMER_ID = os.environ.get("NAVER_CUSTOMER_ID")
        
        if not all([API_KEY, SECRET_KEY, CUSTOMER_ID]):
            print("๋„ค์ด๋ฒ„ API ํ‚ค๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
            return {}
        
        BASE_URL = "https://api.naver.com"
        uri = "/keywordstool"
        method = "POST"  # POST ๋ฉ”์„œ๋“œ๋กœ ๋ณ€๊ฒฝ
        headers = get_header(method, uri, API_KEY, SECRET_KEY, int(CUSTOMER_ID))
        
        # JSON body๋กœ ๋ฐ์ดํ„ฐ ์ „์†ก
        data = {
            "hintKeywords": keywords_batch,
            "showDetail": "1"
        }
        
        response = requests.post(BASE_URL + uri, json=data, headers=headers)
        
        if response.status_code != 200:
            print(f"๋„ค์ด๋ฒ„ API ์‘๋‹ต ์˜ค๋ฅ˜: {response.status_code} - {response.text}")
            return {}
        
        data = response.json()
        
        # ๊ฒฐ๊ณผ ํŒŒ์‹ฑ
        result = {}
        if "keywordList" in data:
            for item in data["keywordList"]:
                keyword = item.get("relKeyword", "")
                pc_count = item.get("monthlyPcQcCnt", 0)
                mobile_count = item.get("monthlyMobileQcCnt", 0)
                
                # ๋ฌธ์ž์—ด์„ ์ˆซ์ž๋กœ ๋ณ€ํ™˜
                try:
                    pc_count = int(str(pc_count).replace(",", "")) if pc_count else 0
                    mobile_count = int(str(mobile_count).replace(",", "")) if mobile_count else 0
                except:
                    pc_count = mobile_count = 0
                    
                total_count = pc_count + mobile_count
                
                result[keyword] = {
                    "PC๊ฒ€์ƒ‰๋Ÿ‰": pc_count,
                    "๋ชจ๋ฐ”์ผ๊ฒ€์ƒ‰๋Ÿ‰": mobile_count,
                    "์ด๊ฒ€์ƒ‰๋Ÿ‰": total_count
                }
        
        return result
        
    except Exception as e:
        print(f"๋„ค์ด๋ฒ„ API ํ˜ธ์ถœ ์˜ค๋ฅ˜: {str(e)}")
        return {}

def fetch_all_search_volumes(keywords, batch_size=5):  # ๋ฐฐ์น˜ ํฌ๊ธฐ๋ฅผ 5๋กœ ์ค„์ž„
    """ํ‚ค์›Œ๋“œ ๋ฆฌ์ŠคํŠธ์— ๋Œ€ํ•œ ๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ๋ณ‘๋ ฌ ์กฐํšŒ"""
    results = {}
    batches = []
    
    # ํ‚ค์›Œ๋“œ๋ฅผ ๋ฐฐ์น˜๋กœ ๋‚˜๋ˆ„๊ธฐ
    for i in range(0, len(keywords), batch_size):
        batch = keywords[i:i + batch_size]
        batches.append(batch)
    
    print(f"์ด {len(batches)}๊ฐœ ๋ฐฐ์น˜๋กœ {len(keywords)}๊ฐœ ํ‚ค์›Œ๋“œ ์ฒ˜๋ฆฌ ์ค‘...")
    
    # ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ
    with ThreadPoolExecutor(max_workers=3) as executor:  # ์›Œ์ปค ์ˆ˜๋„ 3์œผ๋กœ ์ค„์ž„
        future_to_batch = {executor.submit(fetch_search_volume_batch, batch): batch for batch in batches}
        
        for future in as_completed(future_to_batch):
            batch = future_to_batch[future]
            try:
                batch_results = future.result()
                results.update(batch_results)
                print(f"๋ฐฐ์น˜ ์ฒ˜๋ฆฌ ์™„๋ฃŒ: {len(batch)}๊ฐœ ํ‚ค์›Œ๋“œ")
            except Exception as e:
                print(f"๋ฐฐ์น˜ ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {str(e)}")
            
            # API ๋ ˆ์ดํŠธ ๋ฆฌ๋ฏธํŠธ ๋ฐฉ์ง€๋ฅผ ์œ„ํ•œ ๋”œ๋ ˆ์ด
            time.sleep(1)  # ๋”œ๋ ˆ์ด๋ฅผ 1์ดˆ๋กœ ์ฆ๊ฐ€
    
    print(f"๊ฒ€์ƒ‰๋Ÿ‰ ์กฐํšŒ ์™„๋ฃŒ: {len(results)}๊ฐœ ํ‚ค์›Œ๋“œ")
    return results

def preprocess_text(text):
    """
    ํ…์ŠคํŠธ ์ „์ฒ˜๋ฆฌ ํ•จ์ˆ˜:
    1. "*" ๋ฌธ์ œ๊ฐ€ ๋‚˜์˜ค๋ฉด ์ œ๊ฑฐ
    2. "  "์ด๋ฉด " "๋กœ ๋ณ€๊ฒฝ
    3. ์ŠคํŽ˜์ด์Šค๊ฐ€ 1๊ฐœ ์ด์ƒ์ด๋ฉด ๋ฌด์กฐ๊ฑด 2๊ฐœ๋ฉด 1๊ฐœ๋กœ ์ˆ˜์ •
    """
    # 1. "*" ์ œ๊ฑฐ
    processed = re.sub(r'\*', '', text)
    
    # 2 & 3. ์ŠคํŽ˜์ด์Šค๊ฐ€ 2๊ฐœ ์ด์ƒ์ด๋ฉด 1๊ฐœ๋กœ ์ˆ˜์ •
    processed = re.sub(r'\s{2,}', ' ', processed)
    
    return processed.strip()


def extract_product_categories(text):
    """
    ํ…์ŠคํŠธ์—์„œ ์ƒํ’ˆ๋ช…๊ณผ ํ•ด๋‹น ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜
    """
    main_categories = [
        '๊ฐ€๊ตฌ/์ธํ…Œ๋ฆฌ์–ด',
        '์ƒํ™œ/๊ฑด๊ฐ•',
        'ํŒจ์…˜์žกํ™”',
        '๋””์ง€ํ„ธ/๊ฐ€์ „',
        '์ถœ์‚ฐ/์œก์•„',
        '์Šคํฌ์ธ /๋ ˆ์ €',
        'ํ™”์žฅํ’ˆ/๋ฏธ์šฉ',
        'ํŒจ์…˜์˜๋ฅ˜',
        '์—ฌ๊ฐ€/์ƒํ™œํŽธ์˜',
        '์‹ํ’ˆ'
    ]
    
    lines = text.split('\n')
    
    # ์ƒํ’ˆ๋ช…๊ณผ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ๋งคํ•‘
    product_categories = {}
    current_product = None
    
    for i, line in enumerate(lines):
        clean_line = preprocess_text(line)
        
        # ์ฐœํ•˜๊ธฐ๊ฐ€ ํฌํ•จ๋œ ๋ผ์ธ์ด๋ฉด ์งํ›„์˜ ๋ผ์ธ์ด ์ƒํ’ˆ๋ช…
        if '์ฐœํ•˜๊ธฐ' in clean_line:
            # ์ด์ „ ์ƒํ’ˆ ์ €์žฅ
            if current_product and current_category:
                product_categories[current_product] = current_category
            
            # ์ƒˆ๋กœ์šด ์ƒํ’ˆ ์‹œ์ž‘
            if i + 1 < len(lines):
                current_product = preprocess_text(lines[i + 1])
                current_category = None
        
        # ์นดํ…Œ๊ณ ๋ฆฌ ๋ผ์ธ ์ฒดํฌ - ์ „์ฒด ๋ผ์ธ์„ ๊ทธ๋Œ€๋กœ ์ €์žฅ
        else:
            for main_cat in main_categories:
                if clean_line.startswith(main_cat):
                    if current_product:
                        current_category = clean_line  # ์ „์ฒด ๋ผ์ธ์„ ์ €์žฅ
                    break
    
    # ๋งˆ์ง€๋ง‰ ์ƒํ’ˆ ์ €์žฅ
    if current_product and current_category:
        product_categories[current_product] = current_category
    
    return product_categories


def extract_titles(text, debug=False):
    """
    ํ…์ŠคํŠธ์—์„œ ์ œํ’ˆ ์ œ๋ชฉ์„ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜
    """
    # ์›๋ณธ ์ค„ ์ €์žฅ (** ํŒจํ„ด ๋ณด์กด)
    original_lines = text.split('\n')
    
    # ์ „์ฒ˜๋ฆฌ๋œ ์ค„ ์ €์žฅ
    lines = [preprocess_text(line) for line in original_lines]
    
    # ์ œ๋ชฉ์ด ์•„๋‹Œ ๊ฒƒ์œผ๋กœ ๊ฐ„์ฃผํ•  ๋ช…ํ™•ํ•œ ํŒจํ„ด๋“ค (์ •๊ทœํ‘œํ˜„์‹)
    exclude_patterns = [
        r'^์ƒํ’ˆ๋งŒ ๋ณด๊ธฐ$',
        r'^๊ตฌ๋งค์ •๋ณด$',
        r'^ํฌ์ธํŠธ ์ตœ๋Œ€.*$',
        r'^์ƒํ™œ/๊ฑด๊ฐ•.*$',
        r'^์ ๋ฆฝ์ฟ ํฐ$',
        r'^๋ณ„์ .*$',
        r'^๋ฆฌ๋ทฐ.*$',
        r'^์‡ผํ•‘๋ชฐ๋ณ„.*$',
        r'^ํŒŒ์›Œ$',
        r'^์„œ๋น„์Šค$',
        r'^๋น…ํŒŒ์›Œ.*$',
        r'^๊ตฟ์„œ๋น„์Šค$',
        r'^๋ฌด๋ฃŒ๊ตํ™˜๋ฐ˜ํ’ˆ$',
        r'^์˜ค๋Š˜์ถœ๋ฐœ$',
        r'^๋„ค์ด๋ฒ„ํ”Œ๋Ÿฌ์Šค.*$',
        r'^๋ฉค๋ฒ„์‹ญ.*$',
        r'^์‹ ๊ณ ํ•˜๊ธฐ$',
        r'^๋“ฑ๋ก์ผ.*$',
        r'^ํ†กํ†ก$',
        r'^.*ํฌ์ธํŠธ ์ ๋ฆฝ์˜ˆ์ •$',
        r'^์™€์šฐ ๋ฉค๋ฒ„์‹ญ.*$',
    ]
    
    # ์ œํ’ˆ ๋ธ”๋ก ๊ฒฝ๊ณ„ ์ฐพ๊ธฐ
    block_boundaries = []
    for i in range(len(lines)):
        if '์ฐœํ•˜๊ธฐ' in lines[i]:
            block_boundaries.append(i)
    
    # ๋งˆ์ง€๋ง‰ ๋ธ”๋ก ๋ ์ถ”๊ฐ€
    if len(block_boundaries) > 0:
        block_boundaries.append(len(lines))
    else:
        # ์ฐœํ•˜๊ธฐ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ, ์ „์ฒด ํ…์ŠคํŠธ๋ฅผ ํ•˜๋‚˜์˜ ๋ธ”๋ก์œผ๋กœ ์ฒ˜๋ฆฌ
        block_boundaries = [0, len(lines)]
    
    if debug:
        print(f"์ด {len(block_boundaries) - 1}๊ฐœ์˜ ์ œํ’ˆ ๋ธ”๋ก ๋ฐœ๊ฒฌ")
    
    # ์ตœ์ข… ์ œ๋ชฉ ๋ชฉ๋ก
    final_titles = []
    
    # ๊ฐ ์ œํ’ˆ ๋ธ”๋ก๋ณ„๋กœ ์ฒ˜๋ฆฌ
    for b in range(len(block_boundaries) - 1):
        block_start = block_boundaries[b]
        block_end = block_boundaries[b + 1]
        
        # ํ˜„์žฌ ๋ธ”๋ก ๋‚ด์—์„œ๋งŒ ์‚ฌ์šฉํ•  ์ œ๋ชฉ ํ›„๋ณด ๋ฆฌ์ŠคํŠธ
        block_title_candidates = []
        
        # ๋ธ”๋ก ๋‚ด ๊ด‘๊ณ  ์œ„์น˜ ํŒŒ์•…
        ad_indices = []
        for i in range(block_start, block_end):
            if '๊ด‘๊ณ ' in lines[i]:
                ad_indices.append(i)
        
        # ๋ธ”๋ก ๋‚ด ๊ด‘๊ณ  ์œ„์น˜ ๊ธฐ๋ฐ˜ ๊ด‘๊ณ  ๊ทผ์ฒ˜ ํ‘œ์‹œ (๋ธ”๋ก ๊ฒฝ๊ณ„ ๋‚ด์—์„œ๋งŒ)
        has_ad_nearby = [False] * (block_end - block_start)
        for ad_idx in ad_indices:
            # ๊ด‘๊ณ  ์ฃผ๋ณ€ 5์ค„ ๋ฒ”์œ„๋ฅผ ๋ธ”๋ก ๋‚ด์—์„œ๋งŒ ๊ณ„์‚ฐ
            for j in range(max(0, ad_idx - block_start - 5), min(block_end - block_start, ad_idx - block_start + 6)):
                has_ad_nearby[j] = True
        
        # ๋ธ”๋ก์— ๊ด‘๊ณ ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ
        block_has_ad = len(ad_indices) > 0
        
        # ๊ด‘๊ณ ๊ฐ€ ์žˆ๋Š” ๋ธ”๋ก์€ ์ œ์™ธํ•˜์ง€ ์•Š๊ณ , ๊ด‘๊ณ  ์ฃผ๋ณ€ ํ…์ŠคํŠธ๋งŒ ์ œ์™ธ
        if debug and block_has_ad:
            print(f"๋ธ”๋ก {b+1} (๋ผ์ธ {block_start+1}-{block_end}): ๊ด‘๊ณ  ํฌํ•จ")
        
        # ํŒจํ„ด 1: ** ํŒจํ„ด ํ™•์ธ
        for i in range(block_start, block_end):
            # ๋ธ”๋ก ๋‚ด ์ƒ๋Œ€์  ์ธ๋ฑ์Šค
            relative_idx = i - block_start
            
            # ๊ด‘๊ณ  ์ฃผ๋ณ€์ด๋ฉด ๊ฑด๋„ˆ๋›ฐ๊ธฐ
            if block_has_ad and has_ad_nearby[relative_idx]:
                continue
                
            original_line = original_lines[i]
            if '**' in original_line:
                matches = re.findall(r'\*\*(.*?)\*\*', original_line)
                for match in matches:
                    clean_match = preprocess_text(match)
                    
                    # ์ œ๋ชฉ์œผ๋กœ ์ ํ•ฉํ•œ์ง€ ํ™•์ธ
                    if is_valid_title(clean_match, exclude_patterns):
                        # ํ•ด์™ธ ์ ‘๋‘์‚ฌ ์ œ๊ฑฐ
                        if clean_match.startswith('ํ•ด์™ธ'):
                            clean_match = clean_match[2:]
                            
                        block_title_candidates.append(clean_match)
        
        # ํŒจํ„ด 2: ๊ฐ€๊ฒฉ ์ •๋ณด ๋ฐ”๋กœ ์œ„ ์ค„ ํ™•์ธ
        for i in range(block_start, block_end - 1):
            # ๋ธ”๋ก ๋‚ด ์ƒ๋Œ€์  ์ธ๋ฑ์Šค
            relative_idx = i - block_start
            
            # ๊ด‘๊ณ  ์ฃผ๋ณ€์ด๋ฉด ๊ฑด๋„ˆ๋›ฐ๊ธฐ
            if block_has_ad and has_ad_nearby[relative_idx]:
                continue
                
            current_line = lines[i]
            next_line = lines[i + 1]
            
            # ๊ฐ€๊ฒฉ ํŒจํ„ด ํ™•์ธ
            price_pattern = re.search(r'\d+,?\d*์›', next_line) or '์›๋ฐฐ์†ก๋น„' in next_line
            
            if price_pattern and is_valid_title(current_line, exclude_patterns) and '์ฐœํ•˜๊ธฐ' not in current_line:
                # ํ•ด์™ธ ์ ‘๋‘์‚ฌ ์ œ๊ฑฐ
                if current_line.startswith('ํ•ด์™ธ'):
                    current_line = current_line[2:]
                    
                block_title_candidates.append(current_line)
        
        # ํŒจํ„ด 3: ์ฐœํ•˜๊ธฐ ๋‹ค์Œ ์ค„ ํ™•์ธ
        if block_start + 1 < block_end:
            # ๋ธ”๋ก ๋‚ด ์ƒ๋Œ€์  ์ธ๋ฑ์Šค
            relative_idx = 1  # ์ฒซ ์ค„ ๋‹ค์Œ
            
            # ๊ด‘๊ณ  ์ฃผ๋ณ€์ด ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ์ฒ˜๋ฆฌ
            if not (block_has_ad and has_ad_nearby[relative_idx]):
                next_line = lines[block_start + 1]
                
                if is_valid_title(next_line, exclude_patterns):
                    # ํ•ด์™ธ ์ ‘๋‘์‚ฌ ์ œ๊ฑฐ
                    if next_line.startswith('ํ•ด์™ธ'):
                        next_line = next_line[2:]
                        
                    block_title_candidates.append(next_line)
                
        # ํŒจํ„ด 4: ์œ„์•„๋ž˜๋กœ 3์ค„ ๋‚ด์— ๋™์ผํ•œ ํ…์ŠคํŠธ ํ™•์ธ (๊ทœ์น™ 4)
        for i in range(block_start, block_end):
            # ๋ธ”๋ก ๋‚ด ์ƒ๋Œ€์  ์ธ๋ฑ์Šค
            relative_idx = i - block_start
            
            # ๊ด‘๊ณ  ์ฃผ๋ณ€์ด๋ฉด ๊ฑด๋„ˆ๋›ฐ๊ธฐ
            if block_has_ad and has_ad_nearby[relative_idx]:
                continue
                
            current_line = lines[i]
            
            if not is_valid_title(current_line, exclude_patterns):
                continue
            
            # ์œ„์•„๋ž˜๋กœ 3์ค„ ๋ฒ”์œ„ ๋‚ด์— ๋™์ผํ•œ ํ…์ŠคํŠธ ํ™•์ธ (๋ธ”๋ก ๊ฒฝ๊ณ„ ๋‚ด์—์„œ)
            for j in range(max(block_start, i - 3), min(block_end, i + 4)):
                if i != j and lines[i] == lines[j]:
                    # ํ•ด์™ธ ์ ‘๋‘์‚ฌ ์ œ๊ฑฐ
                    if current_line.startswith('ํ•ด์™ธ'):
                        current_line = current_line[2:]
                        
                    block_title_candidates.append(current_line)
                    break
        
        # ํ˜„์žฌ ๋ธ”๋ก์—์„œ ๊ฐ€์žฅ ์ ํ•ฉํ•œ ์ œ๋ชฉ ์„ ํƒ
        best_title = select_best_title(block_title_candidates)
        
        # ์ ํ•ฉํ•œ ์ œ๋ชฉ์„ ์ฐพ์•˜์œผ๋ฉด ์ตœ์ข… ๋ชฉ๋ก์— ์ถ”๊ฐ€
        if best_title:
            final_titles.append(best_title)
            if debug:
                print(f"๋ธ”๋ก {b+1}์˜ ์ œ๋ชฉ: {best_title}")
        else:
            # ์ œ๋ชฉ์„ ์ฐพ์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ, ๋ธ”๋ก์˜ ์ฒซ ์ค„ ์ดํ›„ 5์ค„ ๋‚ด์—์„œ ์ฐพ๊ธฐ
            for i in range(block_start + 1, min(block_start + 6, block_end)):
                # ๋ธ”๋ก ๋‚ด ์ƒ๋Œ€์  ์ธ๋ฑ์Šค
                relative_idx = i - block_start
                
                # ๊ด‘๊ณ  ์ฃผ๋ณ€์ด๋ฉด ๊ฑด๋„ˆ๋›ฐ๊ธฐ
                if block_has_ad and has_ad_nearby[relative_idx]:
                    continue
                    
                current_line = lines[i]
                if is_valid_title(current_line, exclude_patterns):
                    # ํ•ด์™ธ ์ ‘๋‘์‚ฌ ์ œ๊ฑฐ
                    if current_line.startswith('ํ•ด์™ธ'):
                        current_line = current_line[2:]
                        
                    final_titles.append(current_line)
                    if debug:
                        print(f"๋ธ”๋ก {b+1}์˜ ๋Œ€์ฒด ์ œ๋ชฉ: {current_line}")
                    break
    
    return final_titles


def is_valid_title(text, exclude_patterns):
    """
    ์ œ๋ชฉ์œผ๋กœ ์ ํ•ฉํ•œ์ง€ ํ™•์ธํ•˜๋Š” ํ•จ์ˆ˜
    * ํŠน์ • ํ‚ค์›Œ๋“œ ์š”๊ตฌ ๋Œ€์‹  ๊ตฌ์กฐ์  ํŒจํ„ด ๊ฒ€์‚ฌ
    """
    # ๊ธธ์ด ๊ฒ€์‚ฌ (๋„ˆ๋ฌด ์งง์œผ๋ฉด ์ œ๋ชฉ์ด ์•„๋‹˜)
    if len(text) < 10:
        return False
    
    # ์ˆซ์ž๋งŒ์œผ๋กœ ๊ตฌ์„ฑ๋œ ํ…์ŠคํŠธ ์ œ์™ธ
    if re.match(r'^[\d,.\s]+$', text):
        return False
    
    # ์ œ์™ธ ํŒจํ„ด ๊ฒ€์‚ฌ
    for pattern in exclude_patterns:
        if re.match(pattern, text):
            return False
    
    return True


def select_best_title(candidates):
    """
    ์—ฌ๋Ÿฌ ์ œ๋ชฉ ํ›„๋ณด ์ค‘ ๊ฐ€์žฅ ์ ํ•ฉํ•œ ๊ฒƒ์„ ์„ ํƒ
    """
    if not candidates:
        return None
    
    # ์ œ๋ชฉ ์ ์ˆ˜ ๊ณ„์‚ฐ ํ•จ์ˆ˜
    def score_title(title):
        score = 0
        
        # ๊ธธ์ด๊ฐ€ ์ ์ ˆํ•œ ์ œ๋ชฉ ์„ ํ˜ธ (10-50์ž)
        if 10 <= len(title) <= 50:
            score += 3
        elif 50 < len(title) <= 100:
            score += 2
        else:
            score += 1
        
        # ํŠน์ • ํŒจํ„ด์ด ์ œ๋ชฉ์— ํฌํ•จ๋˜์–ด ์žˆ์œผ๋ฉด ์ ์ˆ˜ ์ถ”๊ฐ€
        if re.search(r'[A-Za-z0-9\-]+', title):  # ๋ชจ๋ธ๋ฒˆํ˜ธ ํฌํ•จ ๊ฐ€๋Šฅ์„ฑ
            score += 2
            
        # ๋ธŒ๋žœ๋“œ๋ช…์ด ์•ž์— ์˜ค๋Š” ๊ฒฝ์šฐ ์ ์ˆ˜ ์ถ”๊ฐ€
        if re.match(r'^[๊ฐ€-ํžฃA-Za-z]+\s', title):
            score += 1
            
        return score
    
    # ์ ์ˆ˜ ๊ธฐ๋ฐ˜์œผ๋กœ ์ •๋ ฌ
    scored_candidates = [(score_title(title), title) for title in candidates]
    scored_candidates.sort(reverse=True)
    
    return scored_candidates[0][1] if scored_candidates else None


def extract_keywords(titles):
    """
    ์ œ๋ชฉ์—์„œ ์˜๋ฏธ ์žˆ๋Š” ํ‚ค์›Œ๋“œ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜
    """
    # ๋ถˆ์šฉ์–ด ๋ชฉ๋ก (์ œ์™ธํ•  ๋‹จ์–ด๋“ค)
    stop_words = [
        '๋ฐ', '๋“ฑ', '์™ธ', 'ํฌํ•จ', '์„ธํŠธ', '๊ตฌ์„ฑ', '๊ฐ€๋Šฅ', '์šฉ',
        '์žˆ๋Š”', '์œ„ํ•œ', '๊ธฐํƒ€', '์—†์Œ', '์‚ฌ์šฉ', '๊ฐœ', '์žˆ์Œ', '์—†์Œ',
        '๊ธฐ๋ณธ', '๊ฐ€๋Šฅํ•œ', '๋˜๋Š”', 'ํฌํ•จ๋œ', 'ํ•จ๊ป˜', '๊ฒฝ์šฐ', '์ œ๊ณต',
        '์ ์šฉ', '์ˆ˜', '์‹œ', 'ํ•จ', '์˜', '์ด', '๊ฐ€', '์„', '๋ฅผ',
        '์—', '์—์„œ', '์œผ๋กœ', '๋กœ', '๋Š”', '์€', '์ด๋‹ค', '์žˆ๋‹ค',
        '๋”', '์™€', '๊ณผ', 'ํ•ด๋„'
    ]
    
    # ๋ชจ๋“  ํ‚ค์›Œ๋“œ๋ฅผ ์ €์žฅํ•  ๋”•์…”๋„ˆ๋ฆฌ: {ํ‚ค์›Œ๋“œ: [๋“ฑ์žฅ ์ œ๋ชฉ ์ธ๋ฑ์Šค ๋ฆฌ์ŠคํŠธ]}
    keyword_indices = defaultdict(list)
    
    # ๋ชจ๋“  ์ œ๋ชฉ์—์„œ ํ‚ค์›Œ๋“œ ์ถ”์ถœ
    for idx, title in enumerate(titles):
        # ์ œ๋ชฉ์—์„œ ํŠน์ˆ˜๋ฌธ์ž, ๊ด„ํ˜ธ ๋“ฑ ์ œ๊ฑฐ
        clean_title = re.sub(r'[^\w\s]', ' ', title)
        
        # ์ œ๋ชฉ์„ ๋‹จ์–ด๋กœ ๋ถ„๋ฆฌ
        words = clean_title.split()
        
        # ํ•œ ์ œ๋ชฉ ๋‚ด์—์„œ ์ด๋ฏธ ์ฒ˜๋ฆฌํ•œ ํ‚ค์›Œ๋“œ ์ถ”์ 
        processed_words = set()
        
        for word in words:
            # 2๊ธ€์ž ๋ฏธ๋งŒ ๋‹จ์–ด, ์ˆซ์ž๋งŒ์œผ๋กœ ๋œ ๋‹จ์–ด, ๋ถˆ์šฉ์–ด ์ œ์™ธ
            if len(word) < 2 or word.isdigit() or word.lower() in stop_words:
                continue
                
            # ๊ฐ ํ‚ค์›Œ๋“œ๋Š” ์ œ๋ชฉ๋‹น ํ•œ ๋ฒˆ๋งŒ ์นด์šดํŠธ
            if word not in processed_words:
                keyword_indices[word].append(idx)
                processed_words.add(word)
    
    return keyword_indices


def categorize_keywords_by_products(keyword_indices, titles, product_categories):
    """
    ์ƒํ’ˆ๋ช…์— ๋”ฐ๋ผ ํ‚ค์›Œ๋“œ๋ฅผ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ๋ถ„๋ฅ˜ํ•˜๋Š” ํ•จ์ˆ˜
    """
    # ๋ชจ๋“  ์นดํ…Œ๊ณ ๋ฆฌ ๋ชฉ๋ก ์ถ”์ถœ
    all_categories = set(product_categories.values())
    
    # ๊ฐ ํ‚ค์›Œ๋“œ๋ณ„๋กœ ์นดํ…Œ๊ณ ๋ฆฌ ๋งคํ•‘
    keyword_mappings = {}
    
    # ๊ฐ ํ‚ค์›Œ๋“œ์— ๋Œ€ํ•ด ์นดํ…Œ๊ณ ๋ฆฌ ํŒ๋‹จ
    for keyword, indices in keyword_indices.items():
        keyword_mappings[keyword] = set()
        
        # ํ‚ค์›Œ๋“œ๊ฐ€ ๋“ฑ์žฅํ•œ ๊ฐ ์ƒํ’ˆ์— ๋Œ€ํ•ด ์นดํ…Œ๊ณ ๋ฆฌ ํ™•์ธ
        for idx in indices:
            if idx < len(titles):
                title = titles[idx]
                # ํ•ด๋‹น ์ƒํ’ˆ์˜ ์นดํ…Œ๊ณ ๋ฆฌ ์ฐพ๊ธฐ
                if title in product_categories:
                    category = product_categories[title]
                    keyword_mappings[keyword].add(category)
    
    return keyword_mappings, sorted(list(all_categories))


def analyze_keywords_with_categories(titles, text, include_search_volume=True):
    """
    ์ œ๋ชฉ์—์„œ ํ‚ค์›Œ๋“œ๋ฅผ ๋ถ„์„ํ•˜๊ณ  ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ๋ถ„๋ฅ˜ํ•˜๋Š” ํ•จ์ˆ˜
    
    ๋ฐ˜ํ™˜:
    - keyword_stats: ํ‚ค์›Œ๋“œ ๋ถ„์„ ์ •๋ณด๊ฐ€ ๋‹ด๊ธด DataFrame
    """
    # ์ƒํ’ˆ๋ช…๊ณผ ์นดํ…Œ๊ณ ๋ฆฌ ๋งคํ•‘ ์ถ”์ถœ
    product_categories = extract_product_categories(text)
    
    # ์ œ๋ชฉ์—์„œ ํ‚ค์›Œ๋“œ ์ถ”์ถœ
    keyword_indices = extract_keywords(titles)
    
    # ํ‚ค์›Œ๋“œ ์นดํ…Œ๊ณ ๋ฆฌ ๋ถ„๋ฅ˜
    keyword_mappings, all_categories = categorize_keywords_by_products(keyword_indices, titles, product_categories)
    
    # ๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ์กฐํšŒ (๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ)
    search_volumes = {}
    if include_search_volume:
        keywords_list = list(keyword_indices.keys())
        search_volumes = fetch_all_search_volumes(keywords_list)
    
    # ํ‚ค์›Œ๋“œ ํ†ต๊ณ„ ์ •๋ณด ์ƒ์„ฑ
    keyword_stats = []
    
    for keyword, indices in keyword_indices.items():
        # ํ•ด๋‹น ํ‚ค์›Œ๋“œ๊ฐ€ ๋“ฑ์žฅํ•œ ์ œ๋ชฉ ์ˆ˜
        count = len(indices)
        
        # ๋“ฑ์žฅํ•œ ์ œ๋ชฉ ์ˆœ์œ„ ๋ฌธ์ž์—ด
        ranks = ", ".join(str(idx + 1) for idx in indices)
        
        # ์ƒ์œ„ ๋…ธ์ถœ ์นดํ…Œ๊ณ ๋ฆฌ ๊ฒฐ์ •
        if any(idx < 10 for idx in indices):
            exposure_category = "์ƒ์œ„ 10๊ฐœ"
        elif any(idx < 20 for idx in indices):
            exposure_category = "์ƒ์œ„ 20๊ฐœ"
        elif any(idx < 30 for idx in indices):
            exposure_category = "์ƒ์œ„ 30๊ฐœ"
        elif any(idx < 40 for idx in indices):
            exposure_category = "์ƒ์œ„ 40๊ฐœ"
        else:
            exposure_category = "1ํŽ˜์ด์ง€ ๋ฏธํฌํ•จ"
        
        # ๊ธฐ๋ณธ ํ‚ค์›Œ๋“œ ์ •๋ณด
        keyword_data = {
            'ํ‚ค์›Œ๋“œ': keyword,
            '๋“ฑ์žฅ ์ˆœ์œ„': ranks,
            '์‚ฌ์šฉ ํšŸ์ˆ˜': count,
            '์ƒ์œ„๋…ธ์ถœ ํ‚ค์›Œ๋“œ': exposure_category
        }
        
        # ๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ์ •๋ณด ์ถ”๊ฐ€
        if keyword in search_volumes:
            keyword_data['PC๊ฒ€์ƒ‰๋Ÿ‰'] = search_volumes[keyword]['PC๊ฒ€์ƒ‰๋Ÿ‰']
            keyword_data['๋ชจ๋ฐ”์ผ๊ฒ€์ƒ‰๋Ÿ‰'] = search_volumes[keyword]['๋ชจ๋ฐ”์ผ๊ฒ€์ƒ‰๋Ÿ‰']
            keyword_data['์ด๊ฒ€์ƒ‰๋Ÿ‰'] = search_volumes[keyword]['์ด๊ฒ€์ƒ‰๋Ÿ‰']
        else:
            keyword_data['PC๊ฒ€์ƒ‰๋Ÿ‰'] = 0
            keyword_data['๋ชจ๋ฐ”์ผ๊ฒ€์ƒ‰๋Ÿ‰'] = 0
            keyword_data['์ด๊ฒ€์ƒ‰๋Ÿ‰'] = 0
        
        # ๊ฐ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ "O" ํ‘œ์‹œ ์ถ”๊ฐ€
        for category in all_categories:
            keyword_data[category] = "O" if category in keyword_mappings[keyword] else ""
        
        keyword_stats.append(keyword_data)
    
    # ์‚ฌ์šฉ ํšŸ์ˆ˜ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ
    keyword_stats = sorted(keyword_stats, key=lambda x: x['์‚ฌ์šฉ ํšŸ์ˆ˜'], reverse=True)
    
    # DataFrame์œผ๋กœ ๋ณ€ํ™˜
    df = pd.DataFrame(keyword_stats)
    
    return df


def process_text_and_download(input_text, debug=False, include_search_volume=True):
    """
    ํ…์ŠคํŠธ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ์ œ๋ชฉ์„ ์ถ”์ถœํ•˜๊ณ  ์—‘์…€ ํŒŒ์ผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜
    """
    if not input_text.strip():
        return None, None, "ํ…์ŠคํŠธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
    
    # ์ œ๋ชฉ ์ถ”์ถœ
    titles = extract_titles(input_text, debug)
    
    if not titles:
        return None, None, "์ถ”์ถœ๋œ ์ œ๋ชฉ์ด ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ํ…์ŠคํŠธ๋ฅผ ์‹œ๋„ํ•ด๋ณด์„ธ์š”."
    
    # ๋ฒˆํ˜ธ ๋ถ€์—ฌ ๋ฐ DataFrame ์ƒ์„ฑ
    df_titles = pd.DataFrame({
        '๋ฒˆํ˜ธ': range(1, len(titles) + 1),
        '์ œ๋ชฉ': titles
    })
    
    # ํ‚ค์›Œ๋“œ ๋ถ„์„ ์ˆ˜ํ–‰ (์นดํ…Œ๊ณ ๋ฆฌ ํฌํ•จ)
    keyword_df = analyze_keywords_with_categories(titles, input_text, include_search_volume)
    
    # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ (์ œ๋ชฉ์šฉ)
    titles_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx')
    titles_file.close()
    
    # ์ž„์‹œ ํŒŒ์ผ๋กœ ์ €์žฅ (ํ‚ค์›Œ๋“œ์šฉ)
    keywords_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx')
    keywords_file.close()
    
    # ์ œ๋ชฉ ๋ฐ์ดํ„ฐ ์—‘์…€ ํŒŒ์ผ๋กœ ๋ณ€ํ™˜
    with pd.ExcelWriter(titles_file.name, engine='xlsxwriter') as writer:
        df_titles.to_excel(writer, sheet_name='์ œ๋ชฉ ๋ชฉ๋ก', index=False)
        
        # ์—ด ๋„ˆ๋น„ ์ž๋™ ์กฐ์ •
        worksheet = writer.sheets['์ œ๋ชฉ ๋ชฉ๋ก']
        worksheet.set_column('A:A', 5)   # ๋ฒˆํ˜ธ ์—ด
        worksheet.set_column('B:B', 100)  # ์ œ๋ชฉ ์—ด
    
    # ํ‚ค์›Œ๋“œ ๋ฐ์ดํ„ฐ ์—‘์…€ ํŒŒ์ผ๋กœ ๋ณ€ํ™˜
    with pd.ExcelWriter(keywords_file.name, engine='xlsxwriter') as writer:
        keyword_df.to_excel(writer, sheet_name='ํ‚ค์›Œ๋“œ ๋ถ„์„', index=False)
        
        # ์—ด ๋„ˆ๋น„ ์ž๋™ ์กฐ์ •
        worksheet = writer.sheets['ํ‚ค์›Œ๋“œ ๋ถ„์„']
        worksheet.set_column('A:A', 15)  # ํ‚ค์›Œ๋“œ ์—ด
        worksheet.set_column('B:B', 30)  # ๋“ฑ์žฅ ์ˆœ์œ„ ์—ด
        worksheet.set_column('C:C', 10)  # ์‚ฌ์šฉ ํšŸ์ˆ˜ ์—ด
        worksheet.set_column('D:D', 15)  # ์ƒ์œ„๋…ธ์ถœ ํ‚ค์›Œ๋“œ ์—ด
        worksheet.set_column('E:E', 10)  # PC๊ฒ€์ƒ‰๋Ÿ‰ ์—ด
        worksheet.set_column('F:F', 12)  # ๋ชจ๋ฐ”์ผ๊ฒ€์ƒ‰๋Ÿ‰ ์—ด
        worksheet.set_column('G:G', 10)  # ์ด๊ฒ€์ƒ‰๋Ÿ‰ ์—ด
        
        # H์—ด๋ถ€ํ„ฐ ์นดํ…Œ๊ณ ๋ฆฌ ๋งคํŠธ๋ฆญ์Šค ์—ด ๋„ˆ๋น„ ์กฐ์ •
        for i, col in enumerate(keyword_df.columns[7:], start=7):
            worksheet.set_column(f'{chr(65+i)}:{chr(65+i)}', 20)
    
    # ๋…ธ์ถœ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ํ‚ค์›Œ๋“œ ์ˆ˜ ๊ณ„์‚ฐ
    exposure_counts = keyword_df['์ƒ์œ„๋…ธ์ถœ ํ‚ค์›Œ๋“œ'].value_counts().to_dict()
    top10_count = exposure_counts.get('์ƒ์œ„ 10๊ฐœ', 0)
    top20_count = exposure_counts.get('์ƒ์œ„ 20๊ฐœ', 0)
    top30_count = exposure_counts.get('์ƒ์œ„ 30๊ฐœ', 0)
    top40_count = exposure_counts.get('์ƒ์œ„ 40๊ฐœ', 0)
    not_included_count = exposure_counts.get('1ํŽ˜์ด์ง€ ๋ฏธํฌํ•จ', 0)
    
    # ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ํ‚ค์›Œ๋“œ ์ˆ˜ ๊ณ„์‚ฐ
    result_text = f"์ด {len(titles)}๊ฐœ์˜ ์ œ๋ชฉ์ด ์ถ”์ถœ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.\n\n"
    for i, title in enumerate(titles, 1):
        result_text += f"{i}. {title}\n"
    
    result_text += f"\n\nํ‚ค์›Œ๋“œ ๋ถ„์„ ๊ฒฐ๊ณผ (์ด {len(keyword_df)}๊ฐœ ํ‚ค์›Œ๋“œ):\n"
    result_text += f"- ์ƒ์œ„ 10๊ฐœ ์ œ๋ชฉ์— ํฌํ•จ๋œ ํ‚ค์›Œ๋“œ: {top10_count}๊ฐœ\n"
    result_text += f"- ์ƒ์œ„ 20๊ฐœ ์ œ๋ชฉ์— ํฌํ•จ๋œ ํ‚ค์›Œ๋“œ: {top20_count}๊ฐœ\n"
    result_text += f"- ์ƒ์œ„ 30๊ฐœ ์ œ๋ชฉ์— ํฌํ•จ๋œ ํ‚ค์›Œ๋“œ: {top30_count}๊ฐœ\n"
    result_text += f"- ์ƒ์œ„ 40๊ฐœ ์ œ๋ชฉ์— ํฌํ•จ๋œ ํ‚ค์›Œ๋“œ: {top40_count}๊ฐœ\n"
    result_text += f"- 1ํŽ˜์ด์ง€์— ํฌํ•จ๋˜์ง€ ์•Š์€ ํ‚ค์›Œ๋“œ: {not_included_count}๊ฐœ\n\n"
    
    result_text += f"\n๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ๋œ ํ‚ค์›Œ๋“œ (์ƒ์œ„ 20๊ฐœ):\n"
    for i, row in keyword_df.head(20).iterrows():
        # ํ•ด๋‹น ํ‚ค์›Œ๋“œ๊ฐ€ ์†ํ•œ ๋ชจ๋“  ์นดํ…Œ๊ณ ๋ฆฌ ์ฐพ๊ธฐ
        categories = []
        for col in keyword_df.columns[7:]:  # ์นดํ…Œ๊ณ ๋ฆฌ ์—ด๋“ค
            if row[col] == "O":
                categories.append(col)
        
        category_text = ", ".join(categories) if categories else "๋ฏธ๋ถ„๋ฅ˜"
        result_text += f"{row['ํ‚ค์›Œ๋“œ']} - {row['์‚ฌ์šฉ ํšŸ์ˆ˜']}ํšŒ ๋“ฑ์žฅ ({row['์ƒ์œ„๋…ธ์ถœ ํ‚ค์›Œ๋“œ']}, PC:{row['PC๊ฒ€์ƒ‰๋Ÿ‰']}, ๋ชจ๋ฐ”์ผ:{row['๋ชจ๋ฐ”์ผ๊ฒ€์ƒ‰๋Ÿ‰']}, ์ด:{row['์ด๊ฒ€์ƒ‰๋Ÿ‰']}, ์นดํ…Œ๊ณ ๋ฆฌ: {category_text})\n"
    
    return titles_file.name, keywords_file.name, result_text


def create_app():
    """
    ๊ทธ๋ผ๋””์˜ค ์•ฑ ์ƒ์„ฑ ํ•จ์ˆ˜
    """
    with gr.Blocks(title="์ œํ’ˆ ์ œ๋ชฉ ๋ฐ ํ‚ค์›Œ๋“œ ์ถ”์ถœ๊ธฐ") as app:
        gr.Markdown("""
        # ํ…์ŠคํŠธ์—์„œ ์ œํ’ˆ ์ œ๋ชฉ ๋ฐ ํ‚ค์›Œ๋“œ ์ถ”์ถœ๊ธฐ (๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ํฌํ•จ)
        
        ์ œํ’ˆ ๋ชฉ๋ก์ด ํฌํ•จ๋œ ํ…์ŠคํŠธ๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ์ œํ’ˆ ์ œ๋ชฉ์„ ์ž๋™์œผ๋กœ ์ถ”์ถœํ•˜๊ณ , ํ‚ค์›Œ๋“œ ๋ถ„์„์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.
        
        ### ๊ธฐ๋Šฅ:
        1. ์ œํ’ˆ ์ œ๋ชฉ ์ถ”์ถœ
        2. ์นดํ…Œ๊ณ ๋ฆฌ ์ถ”์ถœ (๊ฐ€๊ตฌ/์ธํ…Œ๋ฆฌ์–ด, ์ƒํ™œ/๊ฑด๊ฐ•, ํŒจ์…˜์žกํ™”, ๋””์ง€ํ„ธ/๊ฐ€์ „, ์ถœ์‚ฐ/์œก์•„, ์Šคํฌ์ธ /๋ ˆ์ €, ํ™”์žฅํ’ˆ/๋ฏธ์šฉ, ํŒจ์…˜์˜๋ฅ˜, ์—ฌ๊ฐ€/์ƒํ™œํŽธ์˜, ์‹ํ’ˆ)
        3. ์ถ”์ถœ๋œ ์ œ๋ชฉ์—์„œ ํ‚ค์›Œ๋“œ ์ถ”์ถœ ๋ฐ ๋ถ„์„
        4. ํ‚ค์›Œ๋“œ ์‚ฌ์šฉ ๋นˆ๋„ ๋ฐ ๋“ฑ์žฅ ์ˆœ์œ„ ๋ถ„์„
        5. ์ƒ์œ„ ๋…ธ์ถœ ํ‚ค์›Œ๋“œ ๋ถ„์„ (์ƒ์œ„ 10๊ฐœ, 20๊ฐœ, 30๊ฐœ, 40๊ฐœ)
        6. **๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ์กฐํšŒ (PC๊ฒ€์ƒ‰๋Ÿ‰, ๋ชจ๋ฐ”์ผ๊ฒ€์ƒ‰๋Ÿ‰, ์ด๊ฒ€์ƒ‰๋Ÿ‰)**
        7. ํ‚ค์›Œ๋“œ๋ณ„ ์นดํ…Œ๊ณ ๋ฆฌ ๋ถ„๋ฅ˜ ๋ฐ ๋งคํŠธ๋ฆญ์Šค ์ƒ์„ฑ
        
        ### ์ฃผ์š” ํŠน์ง•:
        - "*" ๋ฌธ์ž ์ œ๊ฑฐ, ์ค‘๋ณต ๊ณต๋ฐฑ ์ฒ˜๋ฆฌ
        - ๊ด‘๊ณ  ์ฃผ๋ณ€ ํ…์ŠคํŠธ๋งŒ ์ œ์™ธํ•˜์—ฌ ์ •ํ™•ํ•œ ์ œ๋ชฉ ์ถ”์ถœ
        - 'ํ•ด์™ธ' ์ ‘๋‘์‚ฌ ์ž๋™ ์ œ๊ฑฐ
        - ํ‚ค์›Œ๋“œ ์ƒ์œ„ ๋…ธ์ถœ ๋ถ„์„
        - ๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ๋ณ‘๋ ฌ ์กฐํšŒ (25๊ฐœ ๋‹จ์œ„)
        - ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ํ‚ค์›Œ๋“œ ๋ถ„๋ฅ˜ ๋ฐ ๋งคํŠธ๋ฆญ์Šค ํ‘œ์‹œ
        
        ### ๋„ค์ด๋ฒ„ API ์„ค์ •:
        - NAVER_API_KEY ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ์„ค์ • ํ•„์š”
        - NAVER_SECRET_KEY ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ์„ค์ • ํ•„์š”
        - NAVER_CUSTOMER_ID ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ์„ค์ • ํ•„์š”
        """)
        
        with gr.Row():
            with gr.Column():
                input_text = gr.Textbox(
                    label="์ œ๋ชฉ์„ ์ถ”์ถœํ•  ํ…์ŠคํŠธ ์ž…๋ ฅ",
                    placeholder="์—ฌ๊ธฐ์— ์ œํ’ˆ ๋ชฉ๋ก์ด ํฌํ•จ๋œ ํ…์ŠคํŠธ๋ฅผ ๋ถ™์—ฌ๋„ฃ์œผ์„ธ์š”...",
                    lines=15
                )
                debug_mode = gr.Checkbox(label="๋””๋ฒ„๊น… ๋ชจ๋“œ (์ƒ์„ธ ๋กœ๊ทธ ์ถœ๋ ฅ)")
                search_volume_checkbox = gr.Checkbox(label="๋„ค์ด๋ฒ„ ๊ฒ€์ƒ‰๋Ÿ‰ ์กฐํšŒ", value=True)
                submit_btn = gr.Button("์ œ๋ชฉ ์ถ”์ถœ ๋ฐ ํ‚ค์›Œ๋“œ ๋ถ„์„")
            
            with gr.Column():
                output_text = gr.Textbox(label="์ถ”์ถœ ๊ฒฐ๊ณผ", lines=15)
                titles_download_btn = gr.File(label="์ œ๋ชฉ ๋ชฉ๋ก ๋‹ค์šด๋กœ๋“œ", file_types=[".xlsx"])
                keywords_download_btn = gr.File(label="ํ‚ค์›Œ๋“œ ๋ถ„์„ ๋‹ค์šด๋กœ๋“œ", file_types=[".xlsx"])
        
        def process_wrapper(text, debug, include_search_volume):
            titles_file, keywords_file, result_text = process_text_and_download(text, debug, include_search_volume)
            return [titles_file, keywords_file, result_text]
        
        submit_btn.click(
            process_wrapper,
            inputs=[input_text, debug_mode, search_volume_checkbox],
            outputs=[titles_download_btn, keywords_download_btn, output_text]
        )
        
    return app


# ์•ฑ ์‹คํ–‰
if __name__ == "__main__":
    demo = create_app()
    demo.launch()