Spaces:
Building
Building
File size: 33,556 Bytes
b79e8b5 c6beee2 cc1a9a6 dcba978 5a8f642 7c3b41f 5a8f642 bca6d69 5a8f642 c6beee2 5a8f642 3f93809 5a8f642 a899d7b 3f93809 5a8f642 7c3b41f bca6d69 7c3b41f 5a8f642 7c3b41f 5a8f642 7c3b41f bca6d69 c6beee2 bca6d69 c6beee2 bca6d69 7c3b41f 3c561b8 bca6d69 5a8f642 3c561b8 5a8f642 bca6d69 5a8f642 3c561b8 5a8f642 3c561b8 bca6d69 5a8f642 c6beee2 bca6d69 c6beee2 5a8f642 bca6d69 5a8f642 c6beee2 5a8f642 c6beee2 bca6d69 5a8f642 c6beee2 3c561b8 c6beee2 3c561b8 c6beee2 3c561b8 c6beee2 3c561b8 c6beee2 3c561b8 c6beee2 5a8f642 c6beee2 bca6d69 5a8f642 c6beee2 5a8f642 7c3b41f 5a8f642 3c561b8 5a8f642 c6beee2 bca6d69 c6beee2 3c561b8 c6beee2 3c561b8 c6beee2 3c561b8 bca6d69 3c561b8 c6beee2 3c561b8 c6beee2 bca6d69 c6beee2 bca6d69 b79e8b5 dcba978 bca6d69 c6beee2 cc1a9a6 b79e8b5 3f93809 b79e8b5 cc1a9a6 b79e8b5 cc1a9a6 b79e8b5 c6beee2 dcba978 b79e8b5 cc1a9a6 5a8f642 cc1a9a6 5a8f642 cc1a9a6 b79e8b5 cc1a9a6 b79e8b5 3f93809 5a8f642 cc1a9a6 b79e8b5 cc1a9a6 5a8f642 c6beee2 5a8f642 cc1a9a6 b79e8b5 bca6d69 c6beee2 b79e8b5 dcba978 b79e8b5 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f dcba978 7c3b41f cc1a9a6 dcba978 cc1a9a6 dcba978 7c3b41f 5a8f642 dcba978 cc1a9a6 dcba978 cc1a9a6 dcba978 7c3b41f cc1a9a6 dcba978 7c3b41f cc1a9a6 dcba978 7c3b41f dcba978 cc1a9a6 dcba978 cc1a9a6 dcba978 7c3b41f cc1a9a6 7c3b41f cc1a9a6 7c3b41f cc1a9a6 7c3b41f cc1a9a6 7c3b41f cc1a9a6 7c3b41f cc1a9a6 7c3b41f cc1a9a6 dcba978 c6beee2 cc1a9a6 5a8f642 7c3b41f b79e8b5 c6beee2 a1e836a bca6d69 7c3b41f bca6d69 7c3b41f 5a8f642 7c3b41f 5a8f642 7c3b41f bca6d69 b79e8b5 5a8f642 dcba978 5a8f642 bca6d69 5a8f642 bca6d69 5a8f642 bca6d69 5a8f642 bca6d69 5a8f642 bca6d69 7c3b41f dcba978 5a8f642 |
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 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 |
import gradio as gr
import requests
import json
import os
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import lru_cache
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from openai import OpenAI
from bs4 import BeautifulSoup
import re
import pathlib
import sqlite3
import pytz
# νκ΅ κΈ°μ
리μ€νΈ
KOREAN_COMPANIES = [
"NVIDIA",
"ALPHABET",
"APPLE",
"TESLA",
"AMAZON",
"MICROSOFT",
"META",
"INTEL",
"SAMSUNG",
"HYNIX",
"BITCOIN",
"crypto",
"stock",
"Economics",
"Finance",
"investing"
]
#########################################################
# κ³΅ν΅ ν¨μ
#########################################################
def convert_to_seoul_time(timestamp_str):
try:
dt = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
seoul_tz = pytz.timezone('Asia/Seoul')
seoul_time = seoul_tz.localize(dt)
return seoul_time.strftime('%Y-%m-%d %H:%M:%S KST')
except Exception as e:
print(f"μκ° λ³ν μ€λ₯: {str(e)}")
return timestamp_str
def analyze_sentiment_batch(articles, client):
"""
OpenAI APIλ₯Ό ν΅ν΄ λ΄μ€ κΈ°μ¬λ€μ μ’
ν© κ°μ± λΆμμ μν
"""
try:
combined_text = "\n\n".join([
f"μ λͺ©: {article.get('title', '')}\nλ΄μ©: {article.get('snippet', '')}"
for article in articles
])
prompt = f"""λ€μ λ΄μ€ λͺ¨μμ λν΄ μ λ°μ μΈ κ°μ± λΆμμ μννμΈμ:
λ΄μ€ λ΄μ©:
{combined_text}
λ€μ νμμΌλ‘ λΆμν΄μ£ΌμΈμ:
1. μ λ°μ κ°μ±: [κΈμ /λΆμ /μ€λ¦½]
2. μ£Όμ κΈμ μ μμ:
- [νλͺ©1]
- [νλͺ©2]
3. μ£Όμ λΆμ μ μμ:
- [νλͺ©1]
- [νλͺ©2]
4. μ’
ν© νκ°: [μμΈ μ€λͺ
]
"""
response = client.chat.completions.create(
model="CohereForAI/c4ai-command-r-plus-08-2024",
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=1000
)
return response.choices[0].message.content
except Exception as e:
return f"κ°μ± λΆμ μ€ν¨: {str(e)}"
#########################################################
# DB κ΄λ ¨
#########################################################
def init_db():
db_path = pathlib.Path("search_results.db")
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS searches
(id INTEGER PRIMARY KEY AUTOINCREMENT,
keyword TEXT,
country TEXT,
results TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
conn.commit()
conn.close()
def save_to_db(keyword, country, results):
conn = sqlite3.connect("search_results.db")
c = conn.cursor()
seoul_tz = pytz.timezone('Asia/Seoul')
now = datetime.now(seoul_tz)
timestamp = now.strftime('%Y-%m-%d %H:%M:%S')
c.execute("""INSERT INTO searches
(keyword, country, results, timestamp)
VALUES (?, ?, ?, ?)""",
(keyword, country, json.dumps(results), timestamp))
conn.commit()
conn.close()
def load_from_db(keyword, country):
conn = sqlite3.connect("search_results.db")
c = conn.cursor()
c.execute("SELECT results, timestamp FROM searches WHERE keyword=? AND country=? ORDER BY timestamp DESC LIMIT 1",
(keyword, country))
result = c.fetchone()
conn.close()
if result:
return json.loads(result[0]), convert_to_seoul_time(result[1])
return None, None
#########################################################
# "id"λ‘ μ§μ λ‘λ©νκΈ° (νμ€ν 리μμ μ¬μ©)
#########################################################
def load_by_id(search_id):
"""
DBμ PRIMARY KEY(id)λ‘ νΉμ κ²μ κΈ°λ‘μ λ‘λ©
"""
conn = sqlite3.connect("search_results.db")
c = conn.cursor()
c.execute("SELECT keyword, country, results, timestamp FROM searches WHERE id=?", (search_id,))
row = c.fetchone()
conn.close()
if row:
keyword, country, results_json, ts = row
data = json.loads(results_json)
return {
"keyword": keyword,
"country": country,
"data": data,
"timestamp": convert_to_seoul_time(ts)
}
return None
def display_results(articles):
output = ""
for idx, article in enumerate(articles, 1):
output += f"### {idx}. {article['title']}\n"
output += f"μΆμ²: {article['channel']}\n"
output += f"μκ°: {article['time']}\n"
output += f"λ§ν¬: {article['link']}\n"
output += f"μμ½: {article['snippet']}\n\n"
return output
#########################################################
# (1) κ²μ μ => κΈ°μ¬ + λΆμ λμ μΆλ ₯, DB μ μ₯
#########################################################
def search_company(company):
error_message, articles = serphouse_search(company, "United States")
if not error_message and articles:
analysis = analyze_sentiment_batch(articles, client)
store_dict = {
"articles": articles,
"analysis": analysis
}
save_to_db(company, "United States", store_dict)
output = display_results(articles)
output += f"\n\n### λΆμ λ³΄κ³ \n{analysis}\n"
return output
return f"{company}μ λν κ²μ κ²°κ³Όκ° μμ΅λλ€."
#########################################################
# (2) μΆλ ₯ μ => DBμ μ μ₯λ κΈ°μ¬ + λΆμ ν¨κ» μΆλ ₯
#########################################################
def load_company(company):
data, timestamp = load_from_db(company, "United States")
if data:
articles = data.get("articles", [])
analysis = data.get("analysis", "")
output = f"### {company} κ²μ κ²°κ³Ό\nμ μ₯ μκ°: {timestamp}\n\n"
output += display_results(articles)
output += f"\n\n### λΆμ λ³΄κ³ \n{analysis}\n"
return output
return f"{company}μ λν μ μ₯λ κ²°κ³Όκ° μμ΅λλ€."
#########################################################
# (3) EarnBOT λΆμ 리ν¬νΈ
#########################################################
def show_stats():
"""
κΈ°μ‘΄ "νκ΅ κΈ°μ
λ΄μ€ λΆμ 리ν¬νΈ" -> "EarnBOT λΆμ 리ν¬νΈ"
"""
conn = sqlite3.connect("search_results.db")
c = conn.cursor()
output = "## EarnBOT λΆμ 리ν¬νΈ\n\n"
data_list = []
for company in KOREAN_COMPANIES:
c.execute("""
SELECT results, timestamp
FROM searches
WHERE keyword = ?
ORDER BY timestamp DESC
LIMIT 1
""", (company,))
row = c.fetchone()
if row:
results_json, tstamp = row
data_list.append((company, tstamp, results_json))
conn.close()
def analyze_data(item):
comp, tstamp, results_json = item
data = json.loads(results_json)
articles = data.get("articles", [])
analysis = data.get("analysis", "")
count_articles = len(articles)
return (comp, tstamp, count_articles, analysis)
results_list = []
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(analyze_data, dl) for dl in data_list]
for future in as_completed(futures):
results_list.append(future.result())
for comp, tstamp, count, analysis in results_list:
seoul_time = convert_to_seoul_time(tstamp)
output += f"### {comp}\n"
output += f"- λ§μ§λ§ μ
λ°μ΄νΈ: {seoul_time}\n"
output += f"- μ μ₯λ κΈ°μ¬ μ: {count}건\n\n"
if analysis:
output += "#### λ΄μ€ κ°μ± λΆμ\n"
output += f"{analysis}\n\n"
output += "---\n\n"
return output
#########################################################
# μ 체 κ²μ (λ³λ ¬) / μ 체 μΆλ ₯ / μ 체 리ν¬νΈ
#########################################################
def search_all_companies():
overall_result = "# [μ 체 κ²μ κ²°κ³Ό]\n\n"
def do_search(comp):
return comp, search_company(comp)
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(do_search, c) for c in KOREAN_COMPANIES]
for future in as_completed(futures):
comp, res_text = future.result()
overall_result += f"## {comp}\n"
overall_result += res_text + "\n\n"
return overall_result
def load_all_companies():
overall_result = "# [μ 체 μΆλ ₯ κ²°κ³Ό]\n\n"
for comp in KOREAN_COMPANIES:
overall_result += f"## {comp}\n"
overall_result += load_company(comp)
overall_result += "\n"
return overall_result
def full_summary_report():
search_result_text = search_all_companies()
load_result_text = load_all_companies()
stats_text = show_stats()
combined_report = (
"# μ 체 λΆμ λ³΄κ³ μμ½\n\n"
"μλ μμλ‘ μ€νλμμ΅λλ€:\n"
"1. λͺ¨λ μ’
λͺ© κ²μ(λ³λ ¬) + λΆμ => 2. λͺ¨λ μ’
λͺ© DB κ²°κ³Ό μΆλ ₯ => 3. μ 체 κ°μ± λΆμ ν΅κ³\n\n"
f"{search_result_text}\n\n"
f"{load_result_text}\n\n"
"## [μ 체 κ°μ± λΆμ ν΅κ³]\n\n"
f"{stats_text}"
)
return combined_report
#########################################################
# (μΆκ°) μ¬μ©μ μμ κ²μ ν¨μ (λ λ²μ§Έ ν)
#########################################################
def search_custom(query, country):
"""
μ¬μ©μκ° μ
λ ₯ν (query, country)μ λν΄
1) κ²μ + λΆμ => DB μ μ₯
2) DB λ‘λ => κ²°κ³Ό(κΈ°μ¬ λͺ©λ‘ + λΆμ) μΆλ ₯
"""
error_message, articles = serphouse_search(query, country)
if error_message:
return f"μ€λ₯ λ°μ: {error_message}"
if not articles:
return "κ²μ κ²°κ³Όκ° μμ΅λλ€."
analysis = analyze_sentiment_batch(articles, client)
save_data = {
"articles": articles,
"analysis": analysis
}
save_to_db(query, country, save_data)
loaded_data, timestamp = load_from_db(query, country)
if not loaded_data:
return "DBμμ λ‘λ μ€ν¨"
arts = loaded_data.get("articles", [])
analy = loaded_data.get("analysis", "")
out = f"## [μ¬μ©μ μμ κ²μ κ²°κ³Ό]\n\n"
out += f"**ν€μλ**: {query}\n\n"
out += f"**κ΅κ°**: {country}\n\n"
out += f"**μ μ₯ μκ°**: {timestamp}\n\n"
out += display_results(arts)
out += f"### λ΄μ€ κ°μ± λΆμ\n{analy}\n"
return out
#########################################################
# (μΆκ°) νμ€ν 리 ν¨μ
#########################################################
def get_custom_search_history():
"""
KOREAN_COMPANIESμ μλ keywordλ‘ κ²μλ κΈ°λ‘λ§
(id, timestamp, keyword, country) ννλ‘ λ°ν
μ΅μ μ μ λ ¬
"""
# setμΌλ‘ λ§λ€μ΄μ λΉ λ₯΄κ² κ²μ
company_set = set(k.lower() for k in KOREAN_COMPANIES)
conn = sqlite3.connect("search_results.db")
c = conn.cursor()
c.execute("""SELECT id, keyword, country, timestamp
FROM searches
ORDER BY timestamp DESC""")
rows = c.fetchall()
conn.close()
history_list = []
for (sid, kw, cty, ts) in rows:
# KOREAN_COMPANIES μ μλ κ²½μ° -> μ¬μ©μ μμ κ²μ
if kw.lower() not in company_set:
# "id, μκ°, ν€μλ(κ΅κ°)" λ‘ νμν ν
μ€νΈ ꡬμ±
# μ: "12 | 2025-01-22 10:23:00 KST | Apple (United States)"
# μ€μ dropdown value λ sid (id) λ§ μ μ₯
display_time = convert_to_seoul_time(ts)
label = f"{sid} | {display_time} | {kw} ({cty})"
history_list.append((str(sid), label))
return history_list
def view_history_record(record_id):
"""
Dropdown μμ μ νλ record_id (λ¬Έμμ΄)λ‘λΆν°
ν΄λΉ κ²μ κ²°κ³Ό(κΈ°μ¬+λΆμ)μ Markdown ννλ‘ λ°ν
"""
if not record_id:
return "κΈ°λ‘μ΄ μμ΅λλ€."
data = load_by_id(int(record_id))
if not data:
return "ν΄λΉ IDμ κΈ°λ‘μ΄ μμ΅λλ€."
keyword = data["keyword"]
country = data["country"]
timestamp = data["timestamp"]
stored = data["data"] # { articles, analysis }
articles = stored.get("articles", [])
analysis = stored.get("analysis", "")
out = f"### [νμ€ν 리 κ²μ κ²°κ³Ό]\n\n"
out += f"- ID: {record_id}\n"
out += f"- ν€μλ: {keyword}\n"
out += f"- κ΅κ°: {country}\n"
out += f"- μ μ₯ μκ°: {timestamp}\n\n"
out += display_results(articles)
out += f"\n\n### λΆμ λ³΄κ³ \n{analysis}\n"
return out
#########################################################
# SerpHouse API
#########################################################
def is_english(text):
return all(ord(char) < 128 for char in text.replace(' ', '').replace('-', '').replace('_', ''))
@lru_cache(maxsize=100)
def translate_query(query, country):
try:
if is_english(query):
return query
if country in COUNTRY_LANGUAGES:
if country == "South Korea":
return query
target_lang = COUNTRY_LANGUAGES[country]
url = "https://translate.googleapis.com/translate_a/single"
params = {
"client": "gtx",
"sl": "auto",
"tl": target_lang,
"dt": "t",
"q": query
}
session = requests.Session()
retries = Retry(total=3, backoff_factor=0.5)
session.mount('https://', HTTPAdapter(max_retries=retries))
response = session.get(url, params=params, timeout=(5, 10))
translated_text = response.json()[0][0][0]
return translated_text
return query
except Exception as e:
print(f"λ²μ μ€λ₯: {str(e)}")
return query
def search_serphouse(query, country, page=1, num_result=10):
url = "https://api.serphouse.com/serp/live"
now = datetime.utcnow()
yesterday = now - timedelta(days=1)
date_range = f"{yesterday.strftime('%Y-%m-%d')},{now.strftime('%Y-%m-%d')}"
translated_query = translate_query(query, country)
payload = {
"data": {
"q": translated_query,
"domain": "google.com",
"loc": COUNTRY_LOCATIONS.get(country, "United States"),
"lang": COUNTRY_LANGUAGES.get(country, "en"),
"device": "desktop",
"serp_type": "news",
"page": str(page),
"num": "100",
"date_range": date_range,
"sort_by": "date"
}
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": f"Bearer {API_KEY}"
}
try:
session = requests.Session()
retries = Retry(
total=5,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504, 429],
allowed_methods=["POST"]
)
adapter = HTTPAdapter(max_retries=retries)
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.post(
url,
json=payload,
headers=headers,
timeout=(30, 30)
)
response.raise_for_status()
return {"results": response.json(), "translated_query": translated_query}
except requests.exceptions.Timeout:
return {
"error": "κ²μ μκ°μ΄ μ΄κ³Όλμμ΅λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ.",
"translated_query": query
}
except requests.exceptions.RequestException as e:
return {
"error": f"κ²μ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}",
"translated_query": query
}
except Exception as e:
return {
"error": f"μκΈ°μΉ μμ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}",
"translated_query": query
}
def format_results_from_raw(response_data):
if "error" in response_data:
return "Error: " + response_data["error"], []
try:
results = response_data["results"]
translated_query = response_data["translated_query"]
news_results = results.get('results', {}).get('results', {}).get('news', [])
if not news_results:
return "κ²μ κ²°κ³Όκ° μμ΅λλ€.", []
korean_domains = [
'.kr', 'korea', 'korean', 'yonhap', 'hankyung', 'chosun',
'donga', 'joins', 'hani', 'koreatimes', 'koreaherald'
]
korean_keywords = [
'korea', 'korean', 'seoul', 'busan', 'incheon', 'daegu',
'gwangju', 'daejeon', 'ulsan', 'sejong'
]
filtered_articles = []
for idx, result in enumerate(news_results, 1):
url = result.get("url", result.get("link", "")).lower()
title = result.get("title", "").lower()
channel = result.get("channel", result.get("source", "")).lower()
is_korean_content = (
any(domain in url or domain in channel for domain in korean_domains) or
any(keyword in title for keyword in korean_keywords)
)
if not is_korean_content:
filtered_articles.append({
"index": idx,
"title": result.get("title", "μ λͺ© μμ"),
"link": url,
"snippet": result.get("snippet", "λ΄μ© μμ"),
"channel": result.get("channel", result.get("source", "μ μ μμ")),
"time": result.get("time", result.get("date", "μ μ μλ μκ°")),
"image_url": result.get("img", result.get("thumbnail", "")),
"translated_query": translated_query
})
return "", filtered_articles
except Exception as e:
return f"κ²°κ³Ό μ²λ¦¬ μ€ μ€λ₯ λ°μ: {str(e)}", []
###################################
# νκ²½ λ³μ λ° CSS
###################################
ACCESS_TOKEN = os.getenv("HF_TOKEN")
if not ACCESS_TOKEN:
raise ValueError("HF_TOKEN environment variable is not set")
client = OpenAI(
base_url="https://api-inference.huggingface.co/v1/",
api_key=ACCESS_TOKEN,
)
API_KEY = os.getenv("SERPHOUSE_API_KEY")
COUNTRY_LANGUAGES = {
"United States": "en",
"KOREA": "ko",
"United Kingdom": "en",
"Taiwan": "zh-TW",
"Canada": "en",
"Australia": "en",
"Germany": "de",
"France": "fr",
"Japan": "ja",
"China": "zh",
"India": "hi",
"Brazil": "pt",
"Mexico": "es",
"Russia": "ru",
"Italy": "it",
"Spain": "es",
"Netherlands": "nl",
"Singapore": "en",
"Hong Kong": "zh-HK",
"Indonesia": "id",
"Malaysia": "ms",
"Philippines": "tl",
"Thailand": "th",
"Vietnam": "vi",
"Belgium": "nl",
"Denmark": "da",
"Finland": "fi",
"Ireland": "en",
"Norway": "no",
"Poland": "pl",
"Sweden": "sv",
"Switzerland": "de",
"Austria": "de",
"Czech Republic": "cs",
"Greece": "el",
"Hungary": "hu",
"Portugal": "pt",
"Romania": "ro",
"Turkey": "tr",
"Israel": "he",
"Saudi Arabia": "ar",
"United Arab Emirates": "ar",
"South Africa": "en",
"Argentina": "es",
"Chile": "es",
"Colombia": "es",
"Peru": "es",
"Venezuela": "es",
"New Zealand": "en",
"Bangladesh": "bn",
"Pakistan": "ur",
"Egypt": "ar",
"Morocco": "ar",
"Nigeria": "en",
"Kenya": "sw",
"Ukraine": "uk",
"Croatia": "hr",
"Slovakia": "sk",
"Bulgaria": "bg",
"Serbia": "sr",
"Estonia": "et",
"Latvia": "lv",
"Lithuania": "lt",
"Slovenia": "sl",
"Luxembourg": "Luxembourg",
"Malta": "Malta",
"Cyprus": "Cyprus",
"Iceland": "Iceland"
}
COUNTRY_LOCATIONS = {
"United States": "United States",
"KOREA": "kr",
"United Kingdom": "United Kingdom",
"Taiwan": "Taiwan",
"Canada": "Canada",
"Australia": "Australia",
"Germany": "Germany",
"France": "France",
"Japan": "Japan",
"China": "China",
"India": "India",
"Brazil": "Brazil",
"Mexico": "Mexico",
"Russia": "Russia",
"Italy": "Italy",
"Spain": "Spain",
"Netherlands": "Netherlands",
"Singapore": "Singapore",
"Hong Kong": "Hong Kong",
"Indonesia": "Indonesia",
"Malaysia": "Malaysia",
"Philippines": "Philippines",
"Thailand": "Thailand",
"Vietnam": "Vietnam",
"Belgium": "Belgium",
"Denmark": "Denmark",
"Finland": "Finland",
"Ireland": "Ireland",
"Norway": "Norway",
"Poland": "Poland",
"Sweden": "Sweden",
"Switzerland": "Switzerland",
"Austria": "Austria",
"Czech Republic": "Czech Republic",
"Greece": "Greece",
"Hungary": "Hungary",
"Portugal": "Portugal",
"Romania": "Romania",
"Turkey": "Turkey",
"Israel": "Israel",
"Saudi Arabia": "Saudi Arabia",
"United Arab Emirates": "United Arab Emirates",
"South Africa": "South Africa",
"Argentina": "Argentina",
"Chile": "Chile",
"Colombia": "Colombia",
"Peru": "Peru",
"Venezuela": "Venezuela",
"New Zealand": "New Zealand",
"Bangladesh": "Bangladesh",
"Pakistan": "Pakistan",
"Egypt": "Egypt",
"Morocco": "Morocco",
"Nigeria": "Nigeria",
"Kenya": "Kenya",
"Ukraine": "Ukraine",
"Croatia": "Croatia",
"Slovakia": "Slovakia",
"Bulgaria": "Bulgaria",
"Serbia": "Serbia",
"Estonia": "et",
"Latvia": "lv",
"Lithuania": "lt",
"Slovenia": "sl",
"Luxembourg": "Luxembourg",
"Malta": "Malta",
"Cyprus": "Cyprus",
"Iceland": "Iceland"
}
css = """
/* μ μ μ€νμΌ */
footer {visibility: hidden;}
/* λ μ΄μμ 컨ν
μ΄λ */
#status_area {
background: rgba(255, 255, 255, 0.9);
padding: 15px;
border-bottom: 1px solid #ddd;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
#results_area {
padding: 10px;
margin-top: 10px;
}
/* ν μ€νμΌ */
.tabs {
border-bottom: 2px solid #ddd !important;
margin-bottom: 20px !important;
}
.tab-nav {
border-bottom: none !important;
margin-bottom: 0 !important;
}
.tab-nav button {
font-weight: bold !important;
padding: 10px 20px !important;
}
.tab-nav button.selected {
border-bottom: 2px solid #1f77b4 !important;
color: #1f77b4 !important;
}
/* μν λ©μμ§ */
#status_area .markdown-text {
font-size: 1.1em;
color: #2c3e50;
padding: 10px 0;
}
/* κΈ°λ³Έ 컨ν
μ΄λ */
.group {
border: 1px solid #eee;
padding: 15px;
margin-bottom: 15px;
border-radius: 5px;
background: white;
}
/* λ²νΌ μ€νμΌ */
.primary-btn {
background: #1f77b4 !important;
border: none !important;
}
/* μ
λ ₯ νλ */
.textbox {
border: 1px solid #ddd !important;
border-radius: 4px !important;
}
/* νλ‘κ·Έλ μ€λ° 컨ν
μ΄λ */
.progress-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 6px;
background: #e0e0e0;
z-index: 1000;
}
/* νλ‘κ·Έλ μ€bar */
.progress-bar {
height: 100%;
background: linear-gradient(90deg, #2196F3, #00BCD4);
box-shadow: 0 0 10px rgba(33, 150, 243, 0.5);
transition: width 0.3s ease;
animation: progress-glow 1.5s ease-in-out infinite;
}
/* νλ‘κ·Έλ μ€ ν
μ€νΈ */
.progress-text {
position: fixed;
top: 8px;
left: 50%;
transform: translateX(-50%);
background: #333;
color: white;
padding: 4px 12px;
border-radius: 15px;
font-size: 14px;
z-index: 1001;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
/* νλ‘κ·Έλ μ€λ° μ λλ©μ΄μ
*/
@keyframes progress-glow {
0% {
box-shadow: 0 0 5px rgba(33, 150, 243, 0.5);
}
50% {
box-shadow: 0 0 20px rgba(33, 150, 243, 0.8);
}
100% {
box-shadow: 0 0 5px rgba(33, 150, 243, 0.5);
}
}
/* λ°μν λμμΈ */
@media (max-width: 768px) {
.group {
padding: 10px;
margin-bottom: 15px;
}
.progress-text {
font-size: 12px;
padding: 3px 10px;
}
}
/* λ‘λ© μν νμ κ°μ */
.loading {
opacity: 0.7;
pointer-events: none;
transition: opacity 0.3s ease;
}
/* κ²°κ³Ό 컨ν
μ΄λ μ λλ©μ΄μ
*/
.group {
transition: all 0.3s ease;
opacity: 0;
transform: translateY(20px);
}
.group.visible {
opacity: 1;
transform: translateY(0);
}
/* Examples μ€νμΌλ§ */
.examples-table {
margin-top: 10px !important;
margin-bottom: 20px !important;
}
.examples-table button {
background-color: #f0f0f0 !important;
border: 1px solid #ddd !important;
border-radius: 4px !important;
padding: 5px 10px !important;
margin: 2px !important;
transition: all 0.3s ease !important;
}
.examples-table button:hover {
background-color: #e0e0e0 !important;
transform: translateY(-1px) !important;
box-shadow: 0 2px 5px rgba(0,0,0,0.1) !important;
}
.examples-table .label {
font-weight: bold !important;
color: #444 !important;
margin-bottom: 5px !important;
}
"""
import gradio as gr
with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, title="NewsAI μλΉμ€") as iface:
init_db()
with gr.Tabs():
# 첫 λ²μ§Έ ν
with gr.Tab("Earnbot"):
gr.Markdown("## EarnBot: κΈλ‘λ² λΉ
ν
ν¬ κΈ°μ
λ° ν¬μ μ λ§ AI μλ λΆμ")
gr.Markdown(" - 'μ 체 λΆμ λ³΄κ³ μμ½' ν΄λ¦ μ μ 체 μλ λ³΄κ³ μμ±.\n - μλ κ°λ³ μ’
λͺ©μ 'κ²μ(DB μλ μ μ₯)'κ³Ό 'μΆλ ₯(DB μλ νΈμΆ)'λ κ°λ₯.\n - νλ¨ 'μλ κ²μ νμ€ν 리'μμ μ΄μ μ μλ μ
λ ₯ν κ²μμ΄ κΈ°λ‘ νμΈ κ°λ₯.")
# μ 체 λΆμ λ³΄κ³ μμ½
with gr.Row():
full_report_btn = gr.Button("μ 체 λΆμ λ³΄κ³ μμ½", variant="primary")
full_report_display = gr.Markdown()
full_report_btn.click(
fn=full_summary_report,
outputs=full_report_display
)
# μ§μ λ (KOREAN_COMPANIES) κΈ°μ
κ²μ/μΆλ ₯
with gr.Column():
for i in range(0, len(KOREAN_COMPANIES), 2):
with gr.Row():
# μΌμͺ½ μ΄
with gr.Column():
company = KOREAN_COMPANIES[i]
with gr.Group():
gr.Markdown(f"### {company}")
with gr.Row():
search_btn = gr.Button("κ²μ", variant="primary")
load_btn = gr.Button("μΆλ ₯", variant="secondary")
result_display = gr.Markdown()
search_btn.click(
fn=lambda c=company: search_company(c),
inputs=[],
outputs=result_display
)
load_btn.click(
fn=lambda c=company: load_company(c),
inputs=[],
outputs=result_display
)
# μ€λ₯Έμͺ½ μ΄
if i + 1 < len(KOREAN_COMPANIES):
with gr.Column():
company = KOREAN_COMPANIES[i + 1]
with gr.Group():
gr.Markdown(f"### {company}")
with gr.Row():
search_btn = gr.Button("κ²μ", variant="primary")
load_btn = gr.Button("μΆλ ₯", variant="secondary")
result_display = gr.Markdown()
search_btn.click(
fn=lambda c=company: search_company(c),
inputs=[],
outputs=result_display
)
load_btn.click(
fn=lambda c=company: load_company(c),
inputs=[],
outputs=result_display
)
# (μΆκ°) μλ κ²μ νμ€ν 리
gr.Markdown("---")
gr.Markdown("### μλ κ²μ νμ€ν 리")
with gr.Row():
refresh_hist_btn = gr.Button("νμ€ν 리 κ°±μ ", variant="secondary")
history_dropdown = gr.Dropdown(
label="κ²μ κΈ°λ‘ λͺ©λ‘",
choices=[], # μ΄ λΆλΆμ click μ΄λ²€νΈμμ λμ μΌλ‘ μ
λ°μ΄νΈ
value=None
)
hist_view_btn = gr.Button("보기", variant="primary")
hist_result_display = gr.Markdown()
# 1) νμ€ν 리 κ°±μ ν¨μ
def update_history_dropdown():
history_list = get_custom_search_history() # [(id, label), ...]
labels = [lbl for (id_val, lbl) in history_list]
values = [id_val for (id_val, lbl) in history_list]
# gr.Dropdown μ choices=[..., ...] ννλ‘ μ λ¬ν΄μΌ νλ―λ‘
# zip νμ¬ (value, label) μμ λ§λ¦
# Gradio 3.xμμλ choicesλ₯Ό listλ‘ μ£Όκ³ , label/value λΆλ¦¬ λΆκ°.
# -> workaround: "value|label" μ or just store label in "choices" and store value separate
# μ¬κΈ°μλ choices μ labelλ§ λ£κ³ , idλ label νμ± λ± ν΄μΌν¨.
# μ’ λ νΈνκ²: return a dictionary for "choices"
# λ°©λ²1) labelλ§ μ λ¬ -> user picks label -> then parse.
# κ°λ¨ν "value=label"μ΄ λλλ‘:
choice_list = []
for (id_val, label) in history_list:
choice_list.append(label)
return gr.update(choices=choice_list, value=None)
refresh_hist_btn.click(
fn=update_history_dropdown,
inputs=[],
outputs=history_dropdown
)
# 2) νμ€ν 리 보기 ν¨μ
def show_history_record(selected_label):
# selected_label μ΄ "id | time | keyword (country)" νμ
if not selected_label:
return "νμ€ν λ¦¬κ° μ νλμ§ μμμ΅λλ€."
# idλ κ°μ₯ μλΆλΆμ μ«μ
# μ: "12 | 2025-01-22 10:23:00 KST | Apple (United States)"
# -> id=12
splitted = selected_label.split("|")
if len(splitted) < 2:
return "νμ μ€λ₯"
record_id = splitted[0].strip() # "12"
return view_history_record(record_id)
hist_view_btn.click(
fn=show_history_record,
inputs=[history_dropdown],
outputs=hist_result_display
)
# λ λ²μ§Έ ν: "μ§μ μλ κ²μ/λΆμ"
with gr.Tab("μ§μ μλ κ²μ/λΆμ"):
gr.Markdown("## μ¬μ©μ μμ ν€μλ + κ΅κ° κ²μ/λΆμ")
gr.Markdown("κ²μ κ²°κ³Όκ° DBμ μ μ₯λλ©°, 첫 λ²μ§Έ νμ 'μλ κ²μ νμ€ν 리'μμ νμΈ κ°λ₯ν©λλ€.")
with gr.Row():
with gr.Column():
user_input = gr.Textbox(
label="κ²μμ΄ μ
λ ₯",
placeholder="μ) Apple, Samsung λ± μμ λ‘κ²"
)
with gr.Column():
country_selection = gr.Dropdown(
choices=list(COUNTRY_LOCATIONS.keys()),
value="United States",
label="κ΅κ° μ ν"
)
with gr.Column():
custom_search_btn = gr.Button("μ€ν", variant="primary")
custom_search_output = gr.Markdown()
custom_search_btn.click(
fn=search_custom,
inputs=[user_input, country_selection],
outputs=custom_search_output
)
iface.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
ssl_verify=False,
show_error=True
)
|