File size: 45,802 Bytes
37b4640
 
ac4205f
37b4640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
import gradio as gr
import pandas as pd
import os
import logging
from datetime import datetime
import pytz
import time
import tempfile
import zipfile
import re
import json

# λ‘œκΉ… μ„€μ •
logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# μ™ΈλΆ€ 라이브러리 둜그 λΉ„ν™œμ„±ν™”
logging.getLogger('gradio').setLevel(logging.WARNING)
logging.getLogger('gradio_client').setLevel(logging.WARNING)
logging.getLogger('httpx').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)

# ===== API ν΄λΌμ΄μ–ΈνŠΈ μ„€μ • =====
def get_api_client():
    """ν™˜κ²½λ³€μˆ˜μ—μ„œ API μ—”λ“œν¬μΈνŠΈλ₯Ό 가져와 ν΄λΌμ΄μ–ΈνŠΈ 생성"""
    try:
        from gradio_client import Client
        
        # ν™˜κ²½λ³€μˆ˜μ—μ„œ API μ—”λ“œν¬μΈνŠΈ κ°€μ Έμ˜€κΈ°
        api_endpoint = os.getenv('API_ENDPOINT')
        
        if not api_endpoint:
            logger.error("API_ENDPOINT ν™˜κ²½λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
            raise ValueError("API_ENDPOINT ν™˜κ²½λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
        
        client = Client(api_endpoint)
        logger.info("원격 API ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™” 성곡")
        return client
        
    except Exception as e:
        logger.error(f"API ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™” μ‹€νŒ¨: {e}")
        return None

# ===== ν•œκ΅­μ‹œκ°„ κ΄€λ ¨ ν•¨μˆ˜ =====
def get_korean_time():
    """ν•œκ΅­μ‹œκ°„ λ°˜ν™˜"""
    korea_tz = pytz.timezone('Asia/Seoul')
    return datetime.now(korea_tz)

def format_korean_datetime(dt=None, format_type="filename"):
    """ν•œκ΅­μ‹œκ°„ ν¬λ§·νŒ…"""
    if dt is None:
        dt = get_korean_time()
    
    if format_type == "filename":
        return dt.strftime("%y%m%d_%H%M")
    elif format_type == "display":
        return dt.strftime('%Yλ…„ %mμ›” %d일 %Hμ‹œ %MλΆ„')
    elif format_type == "full":
        return dt.strftime('%Y-%m-%d %H:%M:%S')
    else:
        return dt.strftime("%y%m%d_%H%M")

# ===== 데이터 처리 및 검증 ν•¨μˆ˜λ“€ =====
def create_export_data_from_html(analysis_keyword, main_keyword, analysis_html, step1_data=None):
    """뢄석 HTMLκ³Ό 1단계 데이터λ₯Ό 기반으둜 export용 데이터 ꡬ쑰 생성 (더미 데이터 제거)"""
    logger.info("=== πŸ“Š Export 데이터 ꡬ쑰 생성 μ‹œμž‘ (더미 데이터 제거 버전) ===")
    
    # κΈ°λ³Έ export 데이터 ꡬ쑰
    export_data = {
        "main_keyword": main_keyword or analysis_keyword,
        "analysis_keyword": analysis_keyword,
        "analysis_html": analysis_html,
        "main_keywords_df": None,
        "related_keywords_df": None,
        "analysis_completed": True,
        "created_at": get_korean_time().isoformat()
    }
    
    # 1단계 λ°μ΄ν„°μ—μ„œ main_keywords_df μΆ”μΆœ (μ‹€μ œ λ°μ΄ν„°λ§Œ)
    if step1_data and isinstance(step1_data, dict):
        if "keywords_df" in step1_data:
            keywords_df = step1_data["keywords_df"]
            if isinstance(keywords_df, dict):
                try:
                    export_data["main_keywords_df"] = pd.DataFrame(keywords_df)
                    logger.info(f"βœ… 1단계 ν‚€μ›Œλ“œ 데이터λ₯Ό DataFrame으둜 λ³€ν™˜: {export_data['main_keywords_df'].shape}")
                except Exception as e:
                    logger.warning(f"⚠️ 1단계 데이터 λ³€ν™˜ μ‹€νŒ¨: {e}")
                    export_data["main_keywords_df"] = None
            elif hasattr(keywords_df, 'shape'):
                export_data["main_keywords_df"] = keywords_df
                logger.info(f"βœ… 1단계 ν‚€μ›Œλ“œ DataFrame μ‚¬μš©: {keywords_df.shape}")
            else:
                logger.info("πŸ“‹ 1단계 ν‚€μ›Œλ“œ 데이터가 μœ νš¨ν•˜μ§€ μ•ŠμŒ - None으둜 μœ μ§€")
                export_data["main_keywords_df"] = None
    
    # 뢄석 HTMLμ—μ„œ 연관검색어 정보 μΆ”μΆœ μ‹œλ„ (μ‹€μ œ λ°μ΄ν„°λ§Œ)
    if analysis_html and "연관검색어 뢄석" in analysis_html:
        logger.info("πŸ” 뢄석 HTMLμ—μ„œ 연관검색어 정보 발견 - μ‹€μ œ νŒŒμ‹± ν•„μš”")
        # μ‹€μ œ HTML νŒŒμ‹± 둜직이 ν•„μš”ν•œ λΆ€λΆ„
        # ν˜„μž¬λŠ” 더미 데이터 λŒ€μ‹  None으둜 μœ μ§€
        export_data["related_keywords_df"] = None
        logger.info("πŸ’‘ μ‹€μ œ HTML νŒŒμ‹± 둜직 κ΅¬ν˜„ ν•„μš” - 연관검색어 λ°μ΄ν„°λŠ” None으둜 μœ μ§€")
    
    logger.info(f"πŸ“Š Export 데이터 ꡬ쑰 생성 μ™„λ£Œ (더미 데이터 μ—†μŒ):")
    logger.info(f"   - analysis_keyword: {export_data['analysis_keyword']}")
    logger.info(f"   - main_keywords_df: {export_data['main_keywords_df'].shape if export_data['main_keywords_df'] is not None else 'None'}")
    logger.info(f"   - related_keywords_df: {export_data['related_keywords_df'].shape if export_data['related_keywords_df'] is not None else 'None'}")
    logger.info(f"   - analysis_html: {len(str(export_data['analysis_html']))} 문자")
    
    return export_data

def validate_and_repair_export_data(export_data):
    """Export 데이터 μœ νš¨μ„± 검사 및 볡ꡬ (더미 데이터 제거)"""
    logger.info("πŸ”§ Export 데이터 μœ νš¨μ„± 검사 및 볡ꡬ μ‹œμž‘ (더미 데이터 제거 버전)")
    
    if not export_data or not isinstance(export_data, dict):
        logger.warning("⚠️ Export 데이터가 μ—†κ±°λ‚˜ λ”•μ…”λ„ˆλ¦¬κ°€ μ•„λ‹˜ - κΈ°λ³Έ ꡬ쑰 생성")
        return {
            "main_keyword": "κΈ°λ³Έν‚€μ›Œλ“œ",
            "analysis_keyword": "κΈ°λ³ΈλΆ„μ„ν‚€μ›Œλ“œ",
            "analysis_html": "<div>κΈ°λ³Έ 뢄석 κ²°κ³Ό</div>",
            "main_keywords_df": None,  # 더미 데이터 λŒ€μ‹  None
            "related_keywords_df": None,  # 더미 데이터 λŒ€μ‹  None
            "analysis_completed": True
        }
    
    # ν•„μˆ˜ ν‚€λ“€ 확인 및 볡ꡬ
    required_keys = {
        "analysis_keyword": "λΆ„μ„ν‚€μ›Œλ“œ",
        "main_keyword": "λ©”μΈν‚€μ›Œλ“œ", 
        "analysis_html": "<div>뢄석 μ™„λ£Œ</div>",
        "analysis_completed": True
    }
    
    for key, default_value in required_keys.items():
        if key not in export_data or not export_data[key]:
            export_data[key] = default_value
            logger.info(f"πŸ”§ {key} ν‚€ 볡ꡬ: {default_value}")
    
    # DataFrame 데이터 검증 및 λ³€ν™˜ (더미 데이터 생성 μ•ˆν•¨)
    for df_key in ["main_keywords_df", "related_keywords_df"]:
        if df_key in export_data and export_data[df_key] is not None:
            df_data = export_data[df_key]
            
            # λ”•μ…”λ„ˆλ¦¬λ₯Ό DataFrame으둜 λ³€ν™˜
            if isinstance(df_data, dict):
                try:
                    # 빈 λ”•μ…”λ„ˆλ¦¬λŠ” None으둜 처리
                    if not df_data:
                        export_data[df_key] = None
                        logger.info(f"πŸ“‹ {df_key} 빈 λ”•μ…”λ„ˆλ¦¬ - None으둜 μ„€μ •")
                    else:
                        export_data[df_key] = pd.DataFrame(df_data)
                        logger.info(f"βœ… {df_key} λ”•μ…”λ„ˆλ¦¬λ₯Ό DataFrame으둜 λ³€ν™˜ 성곡")
                except Exception as e:
                    logger.warning(f"⚠️ {df_key} λ³€ν™˜ μ‹€νŒ¨: {e}")
                    export_data[df_key] = None
            elif not hasattr(df_data, 'shape'):
                logger.warning(f"⚠️ {df_key}κ°€ DataFrame이 μ•„λ‹˜ - None으둜 μ„€μ •")
                export_data[df_key] = None
    
    logger.info("βœ… Export 데이터 μœ νš¨μ„± 검사 및 볡ꡬ μ™„λ£Œ (더미 데이터 μ—†μŒ)")
    return export_data

# ===== 파일 좜λ ₯ ν•¨μˆ˜λ“€ =====
def create_timestamp_filename(analysis_keyword):
    """νƒ€μž„μŠ€νƒ¬ν”„κ°€ ν¬ν•¨λœ 파일λͺ… 생성 - ν•œκ΅­μ‹œκ°„ 적용"""
    timestamp = format_korean_datetime(format_type="filename")
    safe_keyword = re.sub(r'[^\w\s-]', '', analysis_keyword).strip()
    safe_keyword = re.sub(r'[-\s]+', '_', safe_keyword)
    return f"{safe_keyword}_{timestamp}_뢄석결과"

def export_to_excel(main_keyword, main_keywords_df, analysis_keyword, related_keywords_df, filename_base):
    """μ—‘μ…€ 파일둜 좜λ ₯ (μ‹€μ œ λ°μ΄ν„°λ§Œ)"""
    try:
        # μ‹€μ œ 데이터가 μžˆλŠ”μ§€ 확인
        has_main_data = main_keywords_df is not None and not main_keywords_df.empty
        has_related_data = related_keywords_df is not None and not related_keywords_df.empty
        
        if not has_main_data and not has_related_data:
            logger.info("πŸ“‹ 생성할 데이터가 μ—†μ–΄ μ—‘μ…€ 파일 생성 κ±΄λ„ˆλœ€")
            return None
        
        excel_filename = f"{filename_base}.xlsx"
        excel_path = os.path.join(tempfile.gettempdir(), excel_filename)
        
        with pd.ExcelWriter(excel_path, engine='xlsxwriter') as writer:
            # μ›Œν¬λΆκ³Ό μ›Œν¬μ‹œνŠΈ μŠ€νƒ€μΌ μ„€μ •
            workbook = writer.book
            
            # 헀더 μŠ€νƒ€μΌ
            header_format = workbook.add_format({
                'bold': True,
                'text_wrap': True,
                'valign': 'top',
                'fg_color': '#D7E4BC',
                'border': 1
            })
            
            # 데이터 μŠ€νƒ€μΌ
            data_format = workbook.add_format({
                'text_wrap': True,
                'valign': 'top',
                'border': 1
            })
            
            # 숫자 포맷
            number_format = workbook.add_format({
                'num_format': '#,##0',
                'text_wrap': True,
                'valign': 'top',
                'border': 1
            })
            
            # 첫 번째 μ‹œνŠΈ: λ©”μΈν‚€μ›Œλ“œ μ‘°ν•©ν‚€μ›Œλ“œ (μ‹€μ œ λ°μ΄ν„°λ§Œ)
            if has_main_data:
                main_keywords_df.to_excel(writer, sheet_name=f'{main_keyword}_μ‘°ν•©ν‚€μ›Œλ“œ', index=False)
                worksheet1 = writer.sheets[f'{main_keyword}_μ‘°ν•©ν‚€μ›Œλ“œ']
                
                # 헀더 μŠ€νƒ€μΌ 적용
                for col_num, value in enumerate(main_keywords_df.columns.values):
                    worksheet1.write(0, col_num, value, header_format)
                
                # 데이터 μŠ€νƒ€μΌ 적용
                for row_num in range(1, len(main_keywords_df) + 1):
                    for col_num, value in enumerate(main_keywords_df.iloc[row_num-1]):
                        if isinstance(value, (int, float)) and col_num in [1, 2, 3]:  # κ²€μƒ‰λŸ‰ 컬럼
                            worksheet1.write(row_num, col_num, value, number_format)
                        else:
                            worksheet1.write(row_num, col_num, value, data_format)
                
                # μ—΄ λ„ˆλΉ„ μžλ™ μ‘°μ •
                for i, col in enumerate(main_keywords_df.columns):
                    max_len = max(
                        main_keywords_df[col].astype(str).map(len).max(),
                        len(str(col))
                    )
                    worksheet1.set_column(i, i, min(max_len + 2, 50))
                
                logger.info(f"βœ… λ©”μΈν‚€μ›Œλ“œ μ‹œνŠΈ 생성: {main_keywords_df.shape}")
            
            # 두 번째 μ‹œνŠΈ: λΆ„μ„ν‚€μ›Œλ“œ 연관검색어 (μ‹€μ œ λ°μ΄ν„°λ§Œ)
            if has_related_data:
                related_keywords_df.to_excel(writer, sheet_name=f'{analysis_keyword}_연관검색어', index=False)
                worksheet2 = writer.sheets[f'{analysis_keyword}_연관검색어']
                
                # 헀더 μŠ€νƒ€μΌ 적용
                for col_num, value in enumerate(related_keywords_df.columns.values):
                    worksheet2.write(0, col_num, value, header_format)
                
                # 데이터 μŠ€νƒ€μΌ 적용
                for row_num in range(1, len(related_keywords_df) + 1):
                    for col_num, value in enumerate(related_keywords_df.iloc[row_num-1]):
                        if isinstance(value, (int, float)) and col_num in [1, 2, 3]:  # κ²€μƒ‰λŸ‰ 컬럼
                            worksheet2.write(row_num, col_num, value, number_format)
                        else:
                            worksheet2.write(row_num, col_num, value, data_format)
                
                # μ—΄ λ„ˆλΉ„ μžλ™ μ‘°μ •
                for i, col in enumerate(related_keywords_df.columns):
                    max_len = max(
                        related_keywords_df[col].astype(str).map(len).max(),
                        len(str(col))
                    )
                    worksheet2.set_column(i, i, min(max_len + 2, 50))
                
                logger.info(f"βœ… 연관검색어 μ‹œνŠΈ 생성: {related_keywords_df.shape}")
        
        logger.info(f"μ—‘μ…€ 파일 생성 μ™„λ£Œ: {excel_path}")
        return excel_path
        
    except Exception as e:
        logger.error(f"μ—‘μ…€ 파일 생성 였λ₯˜: {e}")
        return None

def export_to_html(analysis_html, filename_base):
    """HTML 파일둜 좜λ ₯ - ν•œκ΅­μ‹œκ°„ 적용"""
    try:
        html_filename = f"{filename_base}.html"
        html_path = os.path.join(tempfile.gettempdir(), html_filename)
        
        # ν•œκ΅­μ‹œκ°„μœΌλ‘œ 생성 μ‹œκ°„ ν‘œμ‹œ
        korean_time = format_korean_datetime(format_type="display")
        
        # μ™„μ „ν•œ HTML λ¬Έμ„œ 생성
        full_html = f"""
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ν‚€μ›Œλ“œ 심좩뢄석 κ²°κ³Ό</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css">
    <style>
        body {{
            font-family: 'Pretendard', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            line-height: 1.6;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            overflow: hidden;
        }}
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }}
        .header h1 {{
            margin: 0;
            font-size: 28px;
            font-weight: 700;
        }}
        .header p {{
            margin: 10px 0 0 0;
            font-size: 16px;
            opacity: 0.9;
        }}
        .content {{
            padding: 30px;
        }}
        .timestamp {{
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            color: #6c757d;
            font-size: 14px;
            border-top: 1px solid #dee2e6;
        }}
        
        /* 차트 μŠ€νƒ€μΌ κ°œμ„  */
        .chart-container {{
            margin: 20px 0;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }}
        
        /* λ°˜μ‘ν˜• μŠ€νƒ€μΌ */
        @media (max-width: 768px) {{
            .container {{
                margin: 10px;
                border-radius: 8px;
            }}
            .header {{
                padding: 20px;
            }}
            .header h1 {{
                font-size: 24px;
            }}
            .content {{
                padding: 20px;
            }}
        }}
        
        /* μ• λ‹ˆλ©”μ΄μ…˜ */
        @keyframes spin {{
            0% {{ transform: rotate(0deg); }}
            100% {{ transform: rotate(360deg); }}
        }}
        
        @keyframes progress {{
            0% {{ transform: translateX(-100%); }}
            100% {{ transform: translateX(100%); }}
        }}
        
        /* ν”„λ¦°νŠΈ μŠ€νƒ€μΌ */
        @media print {{
            body {{
                background: white;
                padding: 0;
            }}
            .container {{
                box-shadow: none;
                border-radius: 0;
            }}
            .header {{
                background: #667eea !important;
                -webkit-print-color-adjust: exact;
            }}
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-chart-line"></i> ν‚€μ›Œλ“œ 심좩뢄석 κ²°κ³Ό</h1>
            <p>AI μƒν’ˆ μ†Œμ‹± 뢄석 μ‹œμŠ€ν…œ v3.2 (더미 데이터 제거 버전)</p>
        </div>
        <div class="content">
            {analysis_html}
        </div>
        <div class="timestamp">
            <i class="fas fa-clock"></i> 생성 μ‹œκ°„: {korean_time} (ν•œκ΅­μ‹œκ°„)
        </div>
    </div>
</body>
</html>
        """
        
        with open(html_path, 'w', encoding='utf-8') as f:
            f.write(full_html)
        
        logger.info(f"HTML 파일 생성 μ™„λ£Œ: {html_path}")
        return html_path
        
    except Exception as e:
        logger.error(f"HTML 파일 생성 였λ₯˜: {e}")
        return None

def create_zip_file(excel_path, html_path, filename_base):
    """μ••μΆ• 파일 생성"""
    try:
        zip_filename = f"{filename_base}.zip"
        zip_path = os.path.join(tempfile.gettempdir(), zip_filename)
        
        files_added = 0
        with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            if excel_path and os.path.exists(excel_path):
                zipf.write(excel_path, f"{filename_base}.xlsx")
                logger.info(f"μ—‘μ…€ 파일 μ••μΆ• μΆ”κ°€: {filename_base}.xlsx")
                files_added += 1
            
            if html_path and os.path.exists(html_path):
                zipf.write(html_path, f"{filename_base}.html")
                logger.info(f"HTML 파일 μ••μΆ• μΆ”κ°€: {filename_base}.html")
                files_added += 1
        
        if files_added == 0:
            logger.warning("μ••μΆ•ν•  파일이 μ—†μŒ")
            return None
        
        logger.info(f"μ••μΆ• 파일 생성 μ™„λ£Œ: {zip_path} ({files_added}개 파일)")
        return zip_path
        
    except Exception as e:
        logger.error(f"μ••μΆ• 파일 생성 였λ₯˜: {e}")
        return None

def export_analysis_results_enhanced(export_data):
    """κ°•ν™”λœ 뢄석 κ²°κ³Ό 좜λ ₯ 메인 ν•¨μˆ˜ (더미 데이터 제거)"""
    try:
        logger.info("=== πŸ“Š κ°•ν™”λœ 좜λ ₯ ν•¨μˆ˜ μ‹œμž‘ (더미 데이터 제거 버전) ===")
        
        # 데이터 μœ νš¨μ„± 검사 및 볡ꡬ
        export_data = validate_and_repair_export_data(export_data)
        
        analysis_keyword = export_data.get("analysis_keyword", "κΈ°λ³Έν‚€μ›Œλ“œ")
        analysis_html = export_data.get("analysis_html", "<div>뢄석 μ™„λ£Œ</div>")
        main_keyword = export_data.get("main_keyword", analysis_keyword)
        main_keywords_df = export_data.get("main_keywords_df")
        related_keywords_df = export_data.get("related_keywords_df")
        
        logger.info(f"πŸ” μ²˜λ¦¬ν•  데이터:")
        logger.info(f"   - analysis_keyword: '{analysis_keyword}'")
        logger.info(f"   - main_keyword: '{main_keyword}'")
        logger.info(f"   - analysis_html: {len(str(analysis_html))} 문자")
        logger.info(f"   - main_keywords_df: {main_keywords_df.shape if main_keywords_df is not None else 'None'}")
        logger.info(f"   - related_keywords_df: {related_keywords_df.shape if related_keywords_df is not None else 'None'}")
        
        # 파일λͺ… 생성 (ν•œκ΅­μ‹œκ°„ 적용)
        filename_base = create_timestamp_filename(analysis_keyword)
        logger.info(f"πŸ“ 좜λ ₯ 파일λͺ…: {filename_base}")
        
        # HTML νŒŒμΌμ€ 뢄석 κ²°κ³Όκ°€ 있으면 생성
        html_path = None
        if analysis_html and len(str(analysis_html).strip()) > 20:  # μ˜λ―ΈμžˆλŠ” HTML인지 확인
            logger.info("🌐 HTML 파일 생성 μ‹œμž‘...")
            html_path = export_to_html(analysis_html, filename_base)
            if html_path:
                logger.info(f"βœ… HTML 파일 생성 성곡: {html_path}")
            else:
                logger.error("❌ HTML 파일 생성 μ‹€νŒ¨")
        else:
            logger.info("πŸ“„ 뢄석 HTML이 μ—†μ–΄ HTML 파일 생성 κ±΄λ„ˆλœ€")
        
        # μ—‘μ…€ 파일 생성 (μ‹€μ œ DataFrame이 μžˆλŠ” 경우만)
        excel_path = None
        if (main_keywords_df is not None and not main_keywords_df.empty) or \
           (related_keywords_df is not None and not related_keywords_df.empty):
            logger.info("πŸ“Š μ—‘μ…€ 파일 생성 μ‹œμž‘...")
            excel_path = export_to_excel(
                main_keyword,
                main_keywords_df,
                analysis_keyword,
                related_keywords_df,
                filename_base
            )
            if excel_path:
                logger.info(f"βœ… μ—‘μ…€ 파일 생성 성곡: {excel_path}")
            else:
                logger.warning("⚠️ μ—‘μ…€ 파일 생성 μ‹€νŒ¨")
        else:
            logger.info("πŸ“Š μ‹€μ œ DataFrame 데이터가 μ—†μ–΄ μ—‘μ…€ 파일 생성 μƒλž΅")
        
        # μƒμ„±λœ 파일이 μžˆλŠ”μ§€ 확인
        if not html_path and not excel_path:
            logger.warning("⚠️ μƒμ„±λœ 파일이 μ—†μŒ")
            return None, "⚠️ 생성할 수 μžˆλŠ” 데이터가 μ—†μŠ΅λ‹ˆλ‹€. 뢄석을 λ¨Όμ € μ™„λ£Œν•΄μ£Όμ„Έμš”."
        
        # μ••μΆ• 파일 생성
        logger.info("πŸ“¦ μ••μΆ• 파일 생성 μ‹œμž‘...")
        zip_path = create_zip_file(excel_path, html_path, filename_base)
        if zip_path:
            file_types = []
            if html_path:
                file_types.append("HTML")
            if excel_path:
                file_types.append("μ—‘μ…€")
            
            file_list = " + ".join(file_types)
            logger.info(f"βœ… μ••μΆ• 파일 생성 성곡: {zip_path} ({file_list})")
            return zip_path, f"βœ… 뢄석 κ²°κ³Όκ°€ μ„±κ³΅μ μœΌλ‘œ 좜λ ₯λ˜μ—ˆμŠ΅λ‹ˆλ‹€!\n파일λͺ…: {filename_base}.zip\n포함 파일: {file_list}\n\nπŸ’‘ 더미 데이터 제거 버전 - μ‹€μ œ 뢄석 λ°μ΄ν„°λ§Œ ν¬ν•¨λ©λ‹ˆλ‹€."
        else:
            logger.error("❌ μ••μΆ• 파일 생성 μ‹€νŒ¨")
            return None, "μ••μΆ• 파일 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€."
    
    except Exception as e:
        logger.error(f"❌ κ°•ν™”λœ 좜λ ₯ ν•¨μˆ˜ 전체 였λ₯˜: {e}")
        import traceback
        logger.error(f"μŠ€νƒ 트레이슀:\n{traceback.format_exc()}")
        return None, f"좜λ ₯ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"

# ===== λ‘œλ”© μ• λ‹ˆλ©”μ΄μ…˜ =====
def create_loading_animation():
    """λ‘œλ”© μ• λ‹ˆλ©”μ΄μ…˜ HTML"""
    return """
    <div style="display: flex; flex-direction: column; align-items: center; padding: 40px; background: white; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
        <div style="width: 60px; height: 60px; border: 4px solid #f3f3f3; border-top: 4px solid #FB7F0D; border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 20px;"></div>
        <h3 style="color: #FB7F0D; margin: 10px 0; font-size: 18px;">뢄석 μ€‘μž…λ‹ˆλ‹€...</h3>
        <p style="color: #666; margin: 5px 0; text-align: center;">원격 μ„œλ²„μ—μ„œ 데이터λ₯Ό μˆ˜μ§‘ν•˜κ³  AIκ°€ λΆ„μ„ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€.<br>μž μ‹œλ§Œ κΈ°λ‹€λ €μ£Όμ„Έμš”.</p>
        <div style="width: 200px; height: 4px; background: #f0f0f0; border-radius: 2px; margin-top: 15px; overflow: hidden;">
            <div style="width: 100%; height: 100%; background: linear-gradient(90deg, #FB7F0D, #ff9a8b); border-radius: 2px; animation: progress 2s ease-in-out infinite;"></div>
        </div>
    </div>
    
    <style>
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    @keyframes progress {
        0% { transform: translateX(-100%); }
        100% { transform: translateX(100%); }
    }
    </style>
    """

# ===== μ—λŸ¬ 처리 ν•¨μˆ˜ =====
def generate_error_response(error_message):
    """μ—λŸ¬ 응닡 생성"""
    return f'''
    <div style="color: red; padding: 30px; text-align: center; width: 100%; 
                background-color: #f8d7da; border-radius: 12px; border: 1px solid #f5c6cb;">
        <h3 style="margin-bottom: 15px;">❌ μ—°κ²° 였λ₯˜</h3>
        <p style="margin-bottom: 20px;">{error_message}</p>
        <div style="background: white; padding: 15px; border-radius: 8px; color: #333;">
            <h4>ν•΄κ²° 방법:</h4>
            <ul style="text-align: left; padding-left: 20px;">
                <li>λ„€νŠΈμ›Œν¬ 연결을 ν™•μΈν•΄μ£Όμ„Έμš”</li>
                <li>원격 μ„œλ²„ μƒνƒœλ₯Ό ν™•μΈν•΄μ£Όμ„Έμš”</li>
                <li>μž μ‹œ ν›„ λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”</li>
                <li>λ¬Έμ œκ°€ μ§€μ†λ˜λ©΄ κ΄€λ¦¬μžμ—κ²Œ λ¬Έμ˜ν•˜μ„Έμš”</li>
            </ul>
        </div>
    </div>
    '''

# ===== 원격 API 호좜 ν•¨μˆ˜λ“€ =====
def call_collect_data_api(keyword):
    """1단계: μƒν’ˆ 데이터 μˆ˜μ§‘ API 호좜"""
    try:
        client = get_api_client()
        if not client:
            return generate_error_response("API ν΄λΌμ΄μ–ΈνŠΈλ₯Ό μ΄ˆκΈ°ν™”ν•  수 μ—†μŠ΅λ‹ˆλ‹€."), {}
        
        logger.info("원격 API 호좜: μƒν’ˆ 데이터 μˆ˜μ§‘")
        result = client.predict(
            keyword=keyword,
            api_name="/on_collect_data"
        )
        
        logger.info(f"데이터 μˆ˜μ§‘ API κ²°κ³Ό νƒ€μž…: {type(result)}")
        
        # κ²°κ³Όκ°€ νŠœν”ŒμΈ 경우 첫 번째 μš”μ†ŒλŠ” HTML, 두 λ²ˆμ§ΈλŠ” μ„Έμ…˜ 데이터
        if isinstance(result, tuple) and len(result) == 2:
            html_result, session_data = result
            
            # μ„Έμ…˜ 데이터가 μ œλŒ€λ‘œ μžˆλŠ”μ§€ 확인
            if isinstance(session_data, dict):
                logger.info(f"데이터 μˆ˜μ§‘ μ„Έμ…˜ 데이터 μˆ˜μ‹ : {list(session_data.keys()) if session_data else '빈 λ”•μ…”λ„ˆλ¦¬'}")
                return html_result, session_data
            else:
                logger.warning("μ„Έμ…˜ 데이터가 λ”•μ…”λ„ˆλ¦¬κ°€ μ•„λ‹™λ‹ˆλ‹€.")
                return html_result, {}
        else:
            logger.warning("μ˜ˆμƒκ³Ό λ‹€λ₯Έ 데이터 μˆ˜μ§‘ κ²°κ³Ό ν˜•νƒœ")
            return str(result), {"keywords_collected": True}
            
    except Exception as e:
        logger.error(f"μƒν’ˆ 데이터 μˆ˜μ§‘ API 호좜 였λ₯˜: {e}")
        return generate_error_response(f"원격 μ„œλ²„ μ—°κ²° μ‹€νŒ¨: {str(e)}"), {}

def call_analyze_keyword_api_enhanced(analysis_keyword, base_keyword, keywords_data):
    """3단계: κ°•ν™”λœ ν‚€μ›Œλ“œ 심좩뢄석 API 호좜 (더미 데이터 제거)"""
    try:
        client = get_api_client()
        if not client:
            return generate_error_response("API ν΄λΌμ΄μ–ΈνŠΈλ₯Ό μ΄ˆκΈ°ν™”ν•  수 μ—†μŠ΅λ‹ˆλ‹€."), {}
        
        logger.info("=== πŸš€ κ°•ν™”λœ ν‚€μ›Œλ“œ 심좩뢄석 API 호좜 (더미 데이터 제거) ===")
        logger.info(f"νŒŒλΌλ―Έν„° - analysis_keyword: '{analysis_keyword}'")
        logger.info(f"νŒŒλΌλ―Έν„° - base_keyword: '{base_keyword}'")
        logger.info(f"νŒŒλΌλ―Έν„° - keywords_data νƒ€μž…: {type(keywords_data)}")
        
        # 원격 API 호좜
        result = client.predict(
            analysis_keyword,
            base_keyword, 
            keywords_data,
            api_name="/on_analyze_keyword"
        )
        
        logger.info(f"πŸ“‘ 원격 API 응닡 μˆ˜μ‹ :")
        logger.info(f"   - 응닡 νƒ€μž…: {type(result)}")
        logger.info(f"   - 응닡 길이: {len(result) if hasattr(result, '__len__') else 'N/A'}")
        
        # 응닡 처리 및 Export 데이터 ꡬ쑰 생성
        if isinstance(result, tuple) and len(result) == 2:
            html_result, remote_export_data = result
            
            logger.info(f"πŸ“Š 원격 export 데이터:")
            logger.info(f"   - νƒ€μž…: {type(remote_export_data)}")
            logger.info(f"   - ν‚€λ“€: {list(remote_export_data.keys()) if isinstance(remote_export_data, dict) else 'None'}")
            
            # HTML κ²°κ³Όκ°€ 있으면 Export 데이터 ꡬ쑰 생성 (더미 데이터 없이)
            if html_result:
                logger.info("πŸ”§ Export 데이터 ꡬ쑰 생성 μ‹œμž‘ (더미 데이터 제거)")
                enhanced_export_data = create_export_data_from_html(
                    analysis_keyword=analysis_keyword,
                    main_keyword=base_keyword,
                    analysis_html=html_result,
                    step1_data=keywords_data
                )
                
                # μ›κ²©μ—μ„œ 온 μ‹€μ œ 데이터가 있으면 병합
                if isinstance(remote_export_data, dict) and remote_export_data:
                    logger.info("πŸ”— 원격 μ‹€μ œ 데이터와 둜컬 데이터 병합")
                    for key, value in remote_export_data.items():
                        if value is not None and key in ["main_keywords_df", "related_keywords_df"]:
                            # DataFrame λ°μ΄ν„°λ§Œ κ²€μ¦ν•˜μ—¬ 병합
                            if isinstance(value, dict) and value:  # 빈 λ”•μ…”λ„ˆλ¦¬κ°€ μ•„λ‹Œ 경우만
                                enhanced_export_data[key] = value
                                logger.info(f"   - {key} 원격 μ‹€μ œ λ°μ΄ν„°λ‘œ μ—…λ°μ΄νŠΈ")
                            elif hasattr(value, 'shape') and not value.empty:  # DataFrame이고 λΉ„μ–΄μžˆμ§€ μ•Šμ€ 경우
                                enhanced_export_data[key] = value
                                logger.info(f"   - {key} 원격 DataFrame λ°μ΄ν„°λ‘œ μ—…λ°μ΄νŠΈ")
                        elif value is not None and key not in ["main_keywords_df", "related_keywords_df"]:
                            enhanced_export_data[key] = value
                            logger.info(f"   - {key} 원격 λ°μ΄ν„°λ‘œ μ—…λ°μ΄νŠΈ")
                
                logger.info(f"βœ… μ΅œμ’… Export 데이터 ꡬ쑰 (더미 데이터 μ—†μŒ):")
                logger.info(f"   - ν‚€ 개수: {len(enhanced_export_data)}")
                logger.info(f"   - ν‚€ λͺ©λ‘: {list(enhanced_export_data.keys())}")
                
                return html_result, enhanced_export_data
            else:
                logger.warning("⚠️ HTML κ²°κ³Όκ°€ λΉ„μ–΄μžˆμŒ")
                return str(result), {}
        else:
            logger.warning("⚠️ μ˜ˆμƒκ³Ό λ‹€λ₯Έ API 응닡 ν˜•νƒœ")
            # HTML만 λ°˜ν™˜λœ κ²½μš°λ„ 처리
            if isinstance(result, str) and len(result) > 100:  # HTML일 κ°€λŠ₯성이 λ†’μŒ
                logger.info("πŸ“„ HTML λ¬Έμžμ—΄λ‘œ μΆ”μ •λ˜λŠ” 응닡 - Export 데이터 생성 (더미 데이터 없이)")
                enhanced_export_data = create_export_data_from_html(
                    analysis_keyword=analysis_keyword,
                    main_keyword=base_keyword,
                    analysis_html=result,
                    step1_data=keywords_data
                )
                return result, enhanced_export_data
            else:
                return str(result), {}
            
    except Exception as e:
        logger.error(f"❌ ν‚€μ›Œλ“œ 심좩뢄석 API 호좜 였λ₯˜: {e}")
        import traceback
        logger.error(f"μŠ€νƒ 트레이슀:\n{traceback.format_exc()}")
        return generate_error_response(f"원격 μ„œλ²„ μ—°κ²° μ‹€νŒ¨: {str(e)}"), {}

# ===== κ·ΈλΌλ””μ˜€ μΈν„°νŽ˜μ΄μŠ€ =====
def create_interface():
    # CSS μŠ€νƒ€μΌλ§ (κΈ°μ‘΄κ³Ό 동일)
    custom_css = """
    /* κΈ°μ‘΄ 닀크λͺ¨λ“œ μžλ™ λ³€κ²½ AI μƒν’ˆ μ†Œμ‹± 뢄석 μ‹œμŠ€ν…œ CSS */
    :root {
        --primary-color: #FB7F0D;
        --secondary-color: #ff9a8b;
        --accent-color: #FF6B6B;
        --background-color: #FFFFFF;
        --card-bg: #ffffff;
        --input-bg: #ffffff;
        --text-color: #334155;
        --text-secondary: #64748b;
        --border-color: #dddddd;
        --border-light: #e5e5e5;
        --table-even-bg: #f3f3f3;
        --table-hover-bg: #f0f0f0;
        --shadow: 0 8px 30px rgba(251, 127, 13, 0.08);
        --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.1);
        --border-radius: 18px;
    }
    @media (prefers-color-scheme: dark) {
        :root {
            --background-color: #1a1a1a;
            --card-bg: #2d2d2d;
            --input-bg: #2d2d2d;
            --text-color: #e5e5e5;
            --text-secondary: #a1a1aa;
            --border-color: #404040;
            --border-light: #525252;
            --table-even-bg: #333333;
            --table-hover-bg: #404040;
            --shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
            --shadow-light: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
    }
    body {
        font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
        background-color: var(--background-color) !important;
        color: var(--text-color) !important;
        line-height: 1.6;
        margin: 0;
        padding: 0;
        transition: background-color 0.3s ease, color 0.3s ease;
    }
    .gradio-container {
        width: 100%;
        margin: 0 auto;
        padding: 20px;
        background-color: var(--background-color) !important;
    }
    .custom-frame {
        background-color: var(--card-bg) !important;
        border: 1px solid var(--border-light) !important;
        border-radius: var(--border-radius);
        padding: 20px;
        margin: 10px 0;
        box-shadow: var(--shadow) !important;
        color: var(--text-color) !important;
    }
    .custom-button {
        border-radius: 30px !important;
        background: var(--primary-color) !important;
        color: white !important;
        font-size: 18px !important;
        padding: 10px 20px !important;
        border: none;
        box-shadow: 0 4px 8px rgba(251, 127, 13, 0.25);
        transition: transform 0.3s ease;
        height: 45px !important;
        width: 100% !important;
    }
    .custom-button:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(251, 127, 13, 0.3);
    }
    .export-button {
        background: linear-gradient(135deg, #28a745, #20c997) !important;
        color: white !important; 
        border-radius: 25px !important; 
        height: 50px !important;
        font-size: 17px !important; 
        font-weight: bold !important; 
        width: 100% !important;
        margin-top: 20px !important;
    }
    .section-title {
        display: flex;
        align-items: center;
        font-size: 20px;
        font-weight: 700;
        color: var(--text-color) !important;
        margin-bottom: 10px;
        padding-bottom: 5px;
        border-bottom: 2px solid var(--primary-color);
        font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
    }
    .section-title img, .section-title i {
        margin-right: 10px;
        font-size: 20px;
        color: var(--primary-color);
    }
    .gr-input, .gr-text-input, .gr-sample-inputs,
    input[type="text"], input[type="number"], textarea, select {
        border-radius: var(--border-radius) !important;
        border: 1px solid var(--border-color) !important;
        padding: 12px !important;
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05) !important;
        transition: all 0.3s ease !important;
        background-color: var(--input-bg) !important;
        color: var(--text-color) !important;
    }
    .gr-input:focus, .gr-text-input:focus,
    input[type="text"]:focus, textarea:focus, select:focus {
        border-color: var(--primary-color) !important;
        outline: none !important;
        box-shadow: 0 0 0 2px rgba(251, 127, 13, 0.2) !important;
    }
    .fade-in {
        animation: fadeIn 0.5s ease-out;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    """
    
    with gr.Blocks(
        css=custom_css, 
        title="πŸ›’ AI μƒν’ˆ μ†Œμ‹± 뢄석기 v3.2 (더미 데이터 제거)",
        theme=gr.themes.Default(primary_hue="orange", secondary_hue="orange")
    ) as interface:
        
        # 폰트 및 μ•„μ΄μ½˜ λ‘œλ“œ
        gr.HTML("""
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css">
        """)
        
        # μ„Έμ…˜λ³„ μƒνƒœ λ³€μˆ˜
        keywords_data_state = gr.State()
        export_data_state = gr.State({})
        
        # === UI μ»΄ν¬λ„ŒνŠΈλ“€ ===
        with gr.Column(elem_classes="custom-frame fade-in"):
            gr.HTML('<div class="section-title"><i class="fas fa-search"></i> 1단계: 메인 ν‚€μ›Œλ“œ μž…λ ₯</div>')
            
            keyword_input = gr.Textbox(
                label="μƒν’ˆ λ©”μΈν‚€μ›Œλ“œ", 
                placeholder="예: 슬리퍼, 무선이어폰, ν•Έλ“œν¬λ¦Ό",
                value="",
                elem_id="keyword_input"
            )
            
            collect_data_btn = gr.Button("1단계: μƒν’ˆ 데이터 μˆ˜μ§‘ν•˜κΈ°", elem_classes="custom-button", size="lg")
        
        with gr.Column(elem_classes="custom-frame fade-in"):
            gr.HTML('<div class="section-title"><i class="fas fa-database"></i> 2단계: μˆ˜μ§‘λœ ν‚€μ›Œλ“œ λͺ©λ‘</div>')
            keywords_result = gr.HTML()
        
        with gr.Column(elem_classes="custom-frame fade-in"):
            gr.HTML('<div class="section-title"><i class="fas fa-bullseye"></i> 3단계: 뢄석할 ν‚€μ›Œλ“œ 선택</div>')
            
            analysis_keyword_input = gr.Textbox(
                label="뢄석할 ν‚€μ›Œλ“œ", 
                placeholder="μœ„ λͺ©λ‘μ—μ„œ μ›ν•˜λŠ” ν‚€μ›Œλ“œλ₯Ό μž…λ ₯ν•˜μ„Έμš” (예: 톡꡽ 슬리퍼)",
                value="",
                elem_id="analysis_keyword_input"
            )
            
            analyze_keyword_btn = gr.Button("ν‚€μ›Œλ“œ 심좩뢄석 ν•˜κΈ°", elem_classes="custom-button", size="lg")
        
        with gr.Column(elem_classes="custom-frame fade-in"):
            gr.HTML('<div class="section-title"><i class="fas fa-chart-line"></i> ν‚€μ›Œλ“œ 심좩뢄석</div>')
            analysis_result = gr.HTML(label="ν‚€μ›Œλ“œ 심좩뢄석")
        
        with gr.Column(elem_classes="custom-frame fade-in"):
            gr.HTML('<div class="section-title"><i class="fas fa-download"></i> 뢄석 κ²°κ³Ό 좜λ ₯</div>')
            
            gr.HTML("""
            <div style="background: #e3f2fd; border-left: 4px solid #2196f3; padding: 15px; margin: 10px 0; border-radius: 5px;">
                <h4 style="margin: 0 0 10px 0; color: #1976d2;"><i class="fas fa-info-circle"></i> μ‹€μ œ 데이터 좜λ ₯ 버전</h4>
                <p style="margin: 0; color: #1976d2; font-size: 14px;">
                    β€’ λΆ„μ„λœ 데이터λ₯Ό 파일둜 좜λ ₯λ©λ‹ˆλ‹€<br>
                </p>
            </div>
            """)
        
            export_btn = gr.Button("πŸ“Š 뢄석결과 좜λ ₯ν•˜κΈ°", elem_classes="export-button", size="lg")
            export_result = gr.HTML()
            download_file = gr.File(label="λ‹€μš΄λ‘œλ“œ", visible=False)
        
        # ===== 이벀트 ν•Έλ“€λŸ¬ =====
        def on_collect_data(keyword):
            if not keyword.strip():
                return ("<div style='color: red; padding: 20px; text-align: center; width: 100%;'>ν‚€μ›Œλ“œλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”.</div>", None)
            
            # λ‘œλ”© μƒνƒœ ν‘œμ‹œ
            yield (create_loading_animation(), None)
            
            # 원격 API 호좜
            result_html, result_data = call_collect_data_api(keyword)
            
            yield (result_html, result_data)
        
        def on_analyze_keyword(analysis_keyword, base_keyword, keywords_data):
            if not analysis_keyword.strip():
                return "<div style='color: red; padding: 20px; text-align: center; width: 100%;'>뢄석할 ν‚€μ›Œλ“œλ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”.</div>", {}
            
            # λ‘œλ”© μƒνƒœ ν‘œμ‹œ
            yield create_loading_animation(), {}
            
            # κ°•ν™”λœ API 호좜 (더미 데이터 제거)
            html_result, enhanced_export_data = call_analyze_keyword_api_enhanced(
                analysis_keyword, base_keyword, keywords_data
            )
            
            yield html_result, enhanced_export_data
                
        def on_export_results(export_data):
            """κ°•ν™”λœ 뢄석 κ²°κ³Ό 좜λ ₯ ν•Έλ“€λŸ¬ (더미 데이터 제거)"""
            try:
                logger.info(f"πŸ“Š μž…λ ₯ export_data: {type(export_data)}")
                if isinstance(export_data, dict):
                    logger.info(f"πŸ“‹ export_data ν‚€λ“€: {list(export_data.keys())}")
                
                # κ°•ν™”λœ 좜λ ₯ ν•¨μˆ˜ 호좜 (더미 데이터 제거)
                zip_path, message = export_analysis_results_enhanced(export_data)
                
                if zip_path:
                    success_html = f"""
                    <div style="background: #d4edda; border: 1px solid #c3e6cb; padding: 20px; border-radius: 8px; margin: 10px 0;">
                        <h4 style="color: #155724; margin: 0 0 15px 0;"><i class="fas fa-check-circle"></i> 좜λ ₯ μ™„λ£Œ!</h4>
                        <p style="color: #155724; margin: 0; line-height: 1.6;">
                            {message}<br>
                            <strong>λ°μ΄ν„°μΆœλ ₯:</strong><br>
                            <br>
                            <i class="fas fa-download"></i> μ•„λž˜ λ‹€μš΄λ‘œλ“œ λ²„νŠΌμ„ ν΄λ¦­ν•˜μ—¬ νŒŒμΌμ„ μ €μž₯ν•˜μ„Έμš”.<br>
                            <small style="color: #666;">⏰ ν•œκ΅­μ‹œκ°„ κΈ°μ€€μœΌλ‘œ 파일λͺ…이 μƒμ„±λ©λ‹ˆλ‹€.</small>
                        </p>
                    </div>
                    """
                    return success_html, gr.update(value=zip_path, visible=True)
                else:
                    error_html = f"""
                    <div style="background: #f8d7da; border: 1px solid #f5c6cb; padding: 20px; border-radius: 8px; margin: 10px 0;">
                        <h4 style="color: #721c24; margin: 0 0 10px 0;"><i class="fas fa-exclamation-triangle"></i> 좜λ ₯ μ‹€νŒ¨</h4>
                        <p style="color: #721c24; margin: 0;">{message}</p>
                        <div style="margin-top: 15px; padding: 15px; background: white; border-radius: 5px;">
                            <h5 style="color: #721c24; margin: 0 0 10px 0;">πŸ” 디버깅 정보:</h5>
                            <ul style="color: #721c24; margin: 0; padding-left: 20px;">
                                <li>Export 데이터 νƒ€μž…: {type(export_data)}</li>
                                <li>Export 데이터 μœ νš¨μ„±: {'유효' if export_data else '무효'}</li>
                                <li>ν‚€μ›Œλ“œ 심좩뢄석 μƒνƒœ: {'μ™„λ£Œ' if export_data.get('analysis_completed') else 'λ―Έμ™„λ£Œ'}</li>
                            </ul>
                        </div>
                    </div>
                    """
                    logger.error("❌ κ°•ν™”λœ 좜λ ₯ μ‹€νŒ¨")
                    return error_html, gr.update(visible=False)
                    
            except Exception as e:
                logger.error(f"❌ κ°•ν™”λœ 좜λ ₯ ν•Έλ“€λŸ¬ 였λ₯˜: {e}")
                import traceback
                logger.error(f"μŠ€νƒ 트레이슀:\n{traceback.format_exc()}")
                
                error_html = f"""
                <div style="background: #f8d7da; border: 1px solid #f5c6cb; padding: 20px; border-radius: 8px; margin: 10px 0;">
                    <h4 style="color: #721c24; margin: 0 0 10px 0;"><i class="fas fa-exclamation-triangle"></i> μ‹œμŠ€ν…œ 였λ₯˜</h4>
                    <p style="color: #721c24; margin: 0;">κ°•ν™”λœ 좜λ ₯ 쀑 μ‹œμŠ€ν…œ 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€:</p>
                    <code style="display: block; margin: 10px 0; padding: 10px; background: #f8f9fa; border-radius: 3px; color: #721c24;">
                        {type(e).__name__}: {str(e)}
                    </code>
                    <div style="margin-top: 15px; padding: 10px; background: #fff3cd; border-radius: 5px;">
                        <p style="margin: 0; color: #856404; font-size: 14px;">
                            πŸ’‘ μ‹€μ œ 뢄석 κ²°κ³Όκ°€ μžˆμ–΄μ•Όλ§Œ 파일이 μƒμ„±λ©λ‹ˆλ‹€.
                        </p>
                    </div>
                </div>
                """
                return error_html, gr.update(visible=False)
        
        # ===== 이벀트 μ—°κ²° =====
        collect_data_btn.click(
            fn=on_collect_data,
            inputs=[keyword_input],
            outputs=[keywords_result, keywords_data_state],
            api_name="on_collect_data"
        )
        
        analyze_keyword_btn.click(
            fn=on_analyze_keyword,
            inputs=[analysis_keyword_input, keyword_input, keywords_data_state],  
            outputs=[analysis_result, export_data_state],
            api_name="on_analyze_keyword"
        )
        
        export_btn.click(
            fn=on_export_results,
            inputs=[export_data_state],
            outputs=[export_result, download_file],
            api_name="on_export_results"
        )
    
    return interface

# ===== 메인 μ‹€ν–‰ =====
if __name__ == "__main__":
    # pytz λͺ¨λ“ˆ μ„€μΉ˜ 확인
    try:
        import pytz
        logger.info("βœ… pytz λͺ¨λ“ˆ λ‘œλ“œ 성곡 - ν•œκ΅­μ‹œκ°„ 지원")
    except ImportError:
        logger.info("μ‹œμŠ€ν…œ μ‹œκ°„μ„ μ‚¬μš©ν•©λ‹ˆλ‹€.")
    
    # μ•± μ‹€ν–‰
    app = create_interface()
    app.launch(server_name="0.0.0.0", server_port=7860, share=True)