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