Spaces:
Sleeping
Sleeping
File size: 56,307 Bytes
83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 35745e0 83ac6e8 |
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 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
import streamlit as st
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re
import time
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from collections import Counter
import json
import os
from datetime import datetime, timedelta
from openai import OpenAI # μ΅μ λ°©μ import
from dotenv import load_dotenv
import traceback
import plotly.graph_objects as go
import schedule
import threading
import matplotlib.pyplot as plt
# μλν΄λΌμ°λ μΆκ°
try:
from wordcloud import WordCloud
except ImportError:
st.error("wordcloud ν¨ν€μ§λ₯Ό μ€μΉν΄μ£ΌμΈμ: pip install wordcloud")
WordCloud = None
# μ€μΌμ€λ¬ μν ν΄λμ€ μΆκ°
class SchedulerState:
def __init__(self):
self.is_running = False
self.thread = None
self.last_run = None
self.next_run = None
self.scheduled_jobs = []
self.scheduled_results = []
# μ μ μ€μΌμ€λ¬ μν κ°μ²΄ μμ±
global_scheduler_state = SchedulerState()
# API ν€ κ΄λ¦¬λ₯Ό μν μΈμ
μν μ΄κΈ°ν
if 'openai_api_key' not in st.session_state:
st.session_state.openai_api_key = None
st.session_state.openai_client = None
# μ¬λ¬ λ°©λ²μΌλ‘ API ν€ λ‘λ μλ
load_dotenv() # .env νμΌμμ λ‘λ μλ
# 1. νκ²½ λ³μμμ API ν€ νμΈ
if os.environ.get('OPENAI_API_KEY'):
st.session_state.openai_api_key = os.environ.get('OPENAI_API_KEY')
try:
# proxies μΈμ μμ΄ ν΄λΌμ΄μΈνΈ μμ±
st.session_state.openai_client = OpenAI(api_key=st.session_state.openai_api_key)
except Exception as e:
st.error(f"OpenAI ν΄λΌμ΄μΈνΈ μ΄κΈ°ν μ€λ₯: {str(e)}")
# 2. Streamlit secretsμμ API ν€ νμΈ (try-exceptλ‘ μ€λ₯ λ°©μ§)
if not st.session_state.openai_api_key:
try:
if 'OPENAI_API_KEY' in st.secrets:
st.session_state.openai_api_key = st.secrets['OPENAI_API_KEY']
try:
st.session_state.openai_client = OpenAI(api_key=st.session_state.openai_api_key)
except Exception as e:
st.error(f"OpenAI ν΄λΌμ΄μΈνΈ μ΄κΈ°ν μ€λ₯: {str(e)}")
except Exception as e:
pass # secrets νμΌμ΄ μμ΄λ μ€λ₯ λ°μνμ§ μμ
# μμ λλ ν 리λ₯Ό μ¬μ©νλλ‘ NLTK λ°μ΄ν° κ²½λ‘ μ€μ
nltk_data_dir = '/tmp/nltk_data'
os.makedirs(nltk_data_dir, exist_ok=True)
nltk.data.path.insert(0, nltk_data_dir) # μ΄ κ²½λ‘λ₯Ό μ°μ κ²μνλλ‘ μ€μ
# νμν NLTK λ°μ΄ν° λ€μ΄λ‘λ
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt', download_dir=nltk_data_dir)
try:
nltk.data.find('corpora/stopwords')
except LookupError:
nltk.download('stopwords', download_dir=nltk_data_dir)
# νμ΄μ§ μ€μ
st.set_page_config(page_title="λ΄μ€ κΈ°μ¬ λꡬ", page_icon="π°", layout="wide")
# μ¬μ΄λλ°μ API ν€ μ
λ ₯ νλ μΆκ°
with st.sidebar:
st.title("λ΄μ€ κΈ°μ¬ λꡬ")
menu = st.radio(
"λ©λ΄ μ ν",
["λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§", "κΈ°μ¬ λΆμνκΈ°", "μ κΈ°μ¬ μμ±νκΈ°", "λ΄μ€ κΈ°μ¬ μμ½νκΈ°"]
)
st.divider()
api_key = st.text_input("OpenAI API ν€ μ
λ ₯", type="password")
if api_key:
st.session_state.openai_api_key = api_key
try:
# proxies μΈμ μμ΄ ν΄λΌμ΄μΈνΈ μμ±
st.session_state.openai_client = OpenAI(api_key=api_key)
st.success("API ν€κ° μ€μ λμμ΅λλ€!")
except Exception as e:
st.error(f"OpenAI ν΄λΌμ΄μΈνΈ μ΄κΈ°ν μ€λ₯: {str(e)}")
# μ μ₯λ κΈ°μ¬λ₯Ό λΆλ¬μ€λ ν¨μ
def load_saved_articles():
if os.path.exists('/tmp/saved_articles/articles.json'):
with open('/tmp/saved_articles/articles.json', 'r', encoding='utf-8') as f:
return json.load(f)
return []
# κΈ°μ¬λ₯Ό μ μ₯νλ ν¨μ
def save_articles(articles):
os.makedirs('/tmp/saved_articles', exist_ok=True)
with open('/tmp/saved_articles/articles.json', 'w', encoding='utf-8') as f:
json.dump(articles, f, ensure_ascii=False, indent=2)
@st.cache_data
def crawl_naver_news(keyword, num_articles=5):
"""
λ€μ΄λ² λ΄μ€ κΈ°μ¬λ₯Ό μμ§νλ ν¨μ
"""
url = f"https://search.naver.com/search.naver?where=news&query={keyword}"
results = []
try:
# νμ΄μ§ μμ²
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# λ΄μ€ μμ΄ν
μ°ΎκΈ°
news_items = soup.select('div.sds-comps-base-layout.sds-comps-full-layout')
# κ° λ΄μ€ μμ΄ν
μμ μ 보 μΆμΆ
for i, item in enumerate(news_items):
if i >= num_articles:
break
try:
# μ λͺ©κ³Ό λ§ν¬ μΆμΆ
title_element = item.select_one('a.X0fMYp2dHd0TCUS2hjww span')
if not title_element:
continue
title = title_element.text.strip()
link_element = item.select_one('a.X0fMYp2dHd0TCUS2hjww')
link = link_element['href'] if link_element else ""
# μΈλ‘ μ¬ μΆμΆ
press_element = item.select_one('div.sds-comps-profile-info-title span.sds-comps-text-type-body2')
source = press_element.text.strip() if press_element else "μ μ μμ"
# λ μ§ μΆμΆ
date_element = item.select_one('span.r0VOr')
date = date_element.text.strip() if date_element else "μ μ μμ"
# 미리보기 λ΄μ© μΆμΆ
desc_element = item.select_one('a.X0fMYp2dHd0TCUS2hjww.IaKmSOGPdofdPwPE6cyU > span')
description = desc_element.text.strip() if desc_element else "λ΄μ© μμ"
results.append({
'title': title,
'link': link,
'description': description,
'source': source,
'date': date,
'content': "" # λμ€μ μλ¬Έ λ΄μ©μ μ μ₯ν νλ
})
except Exception as e:
st.error(f"κΈ°μ¬ μ 보 μΆμΆ μ€ μ€λ₯ λ°μ: {str(e)}")
continue
except Exception as e:
st.error(f"νμ΄μ§ μμ² μ€ μ€λ₯ λ°μ: {str(e)}")
return results
# κΈ°μ¬ μλ¬Έ κ°μ Έμ€κΈ°
def get_article_content(url):
try:
response = requests.get(url, timeout=5)
soup = BeautifulSoup(response.text, 'html.parser')
# λ€μ΄λ² λ΄μ€ λ³Έλ¬Έ μ°ΎκΈ°
content = soup.select_one('#dic_area')
if content:
text = content.text.strip()
text = re.sub(r'\s+', ' ', text) # μ¬λ¬ 곡백 μ κ±°
return text
# λ€λ₯Έ λ΄μ€ μ¬μ΄νΈ λ³Έλ¬Έ μ°ΎκΈ° (μ¬λ¬ μ¬μ΄νΈ λμ νμ)
content = soup.select_one('.article_body, .article-body, .article-content, .news-content-inner')
if content:
text = content.text.strip()
text = re.sub(r'\s+', ' ', text)
return text
return "λ³Έλ¬Έμ κ°μ Έμ¬ μ μμ΅λλ€."
except Exception as e:
return f"μ€λ₯ λ°μ: {str(e)}"
# NLTKλ₯Ό μ΄μ©ν ν€μλ λΆμ
def analyze_keywords(text, top_n=10):
# νκ΅μ΄ λΆμ©μ΄ λͺ©λ‘ (μ§μ μ μν΄μΌ ν©λλ€)
korean_stopwords = ['μ΄', 'κ·Έ', 'μ ', 'κ²', 'λ°', 'λ±', 'λ₯Ό', 'μ', 'μ', 'μμ', 'μ', 'μΌλ‘', 'λ‘']
tokens = word_tokenize(text)
tokens = [word for word in tokens if word.isalnum() and len(word) > 1 and word not in korean_stopwords]
word_count = Counter(tokens)
top_keywords = word_count.most_common(top_n)
return top_keywords
#μλ ν΄λΌμ°λμ© λΆμ
def extract_keywords_for_wordcloud(text, top_n=50):
if not text or len(text.strip()) < 10:
return {}
try:
try:
tokens = word_tokenize(text.lower())
except Exception as e:
st.warning(f"{str(e)} μ€λ₯λ°μ")
tokens = text.lower().split()
stop_words = set()
try:
stop_words = set(stopwords.words('english'))
except Exception:
pass
korea_stop_words = {
'λ°', 'λ±', 'λ₯Ό', 'μ΄', 'μ', 'κ°', 'μ', 'λ', 'μΌλ‘', 'μμ', 'κ·Έ', 'λ', 'λλ', 'νλ', 'ν ', 'νκ³ ',
'μλ€', 'μ΄λ€', 'μν΄', 'κ²μ΄λ€', 'κ²μ', 'λν', 'λλ¬Έ', 'κ·Έλ¦¬κ³ ', 'νμ§λ§', 'κ·Έλ¬λ', 'κ·Έλμ',
'μ
λλ€', 'ν©λλ€', 'μ΅λλ€', 'μ', 'μ£ ', 'κ³ ', 'κ³Ό', 'μ', 'λ', 'μ', 'μ', 'κ²', 'λ€', 'μ ', 'μ ',
'λ
', 'μ', 'μΌ', 'μ', 'λΆ', 'μ΄', 'μ§λ', 'μ¬ν΄', 'λ΄λ
', 'μ΅κ·Ό', 'νμ¬', 'μ€λ', 'λ΄μΌ', 'μ΄μ ',
'μ€μ ', 'μ€ν', 'λΆν°', 'κΉμ§', 'μκ²', 'κ»μ', 'μ΄λΌκ³ ', 'λΌκ³ ', 'νλ©°', 'νλ©΄μ', 'λ°λΌ', 'ν΅ν΄',
'κ΄λ ¨', 'ννΈ', 'νΉν', 'κ°μ₯', 'λ§€μ°', 'λ', 'λ', 'λ§μ΄', 'μ‘°κΈ', 'νμ', 'μμ£Ό', 'κ°λ', 'κ±°μ',
'μ ν', 'λ°λ‘', 'μ λ§', 'λ§μ½', 'λΉλ‘―ν', 'λ±μ', 'λ±μ΄', 'λ±μ', 'λ±κ³Ό', 'λ±λ', 'λ±μ', 'λ±μμ',
'κΈ°μ', 'λ΄μ€', 'μ¬μ§', 'μ°ν©λ΄μ€', 'λ΄μμ€', 'μ 곡', '무λ¨', 'μ μ¬', 'μ¬λ°°ν¬', 'κΈμ§', 'μ΅μ»€', 'λ©νΈ',
'μΌλ³΄', 'λ°μΌλ¦¬', 'κ²½μ ', 'μ¬ν', 'μ μΉ', 'μΈκ³', 'κ³Όν', 'μμ΄ν°', 'λ·μ»΄', 'μ¨λ·', 'λΈλ‘ν°', 'μ μμ λ¬Έ'
}
stop_words.update(korea_stop_words)
# 1κΈμ μ΄μμ΄κ³ λΆμ©μ΄κ° μλ ν ν°λ§ νν°λ§
filtered_tokens = [word for word in tokens if len(word) > 1 and word not in stop_words]
# λ¨μ΄ λΉλ κ³μ°
word_freq = {}
for word in filtered_tokens:
if word.isalnum(): # μνλ²³κ³Ό μ«μλ§ ν¬ν¨λ λ¨μ΄λ§ νμ©
word_freq[word] = word_freq.get(word, 0) + 1
# λΉλμμΌλ‘ μ λ ¬νμ¬ μμ nκ° λ°ν
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
if not sorted_words:
return {"data": 1, "analysis": 1, "news": 1}
return dict(sorted_words[:top_n])
except Exception as e:
st.error(f"μ€λ₯λ°μ {str(e)}")
return {"data": 1, "analysis": 1, "news": 1}
# μλ ν΄λΌμ°λ μμ± ν¨μ
def generate_wordcloud(keywords_dict):
if not WordCloud:
st.warning("μλν΄λΌμ°λ μ€μΉμλμ΄ μμ΅λλ€.")
return None
try:
wc= WordCloud(
width=800,
height=400,
background_color = 'white',
colormap = 'viridis',
max_font_size=150,
random_state=42
).generate_from_frequencies(keywords_dict)
try:
possible_font_paths=["NanumGothic.ttf", "μ΄λ¦"]
font_path = None
for path in possible_font_paths:
if os.path.exists(path):
font_path = path
break
if font_path:
wc= WordCloud(
font_path=font_path,
width=800,
height=400,
background_color = 'white',
colormap = 'viridis',
max_font_size=150,
random_state=42
).generate_from_frequencies(keywords_dict)
except Exception as e:
print(f"μ€λ₯λ°μ {str(e)}")
return wc
except Exception as e:
st.error(f"μ€λ₯λ°μ {str(e)}")
return None
# λ΄μ€ λΆμ ν¨μ
def analyze_news_content(news_df):
if news_df.empty:
return "λ°μ΄ν°κ° μμ΅λλ€"
results = {}
#μΉ΄ν
κ³ λ¦¬λ³
if 'source' in news_df.columns:
results['source_counts'] = news_df['source'].value_counts().to_dict()
#μΉ΄ν
κ³ λ¦¬λ³
if 'date' in news_df.columns:
results['date_counts'] = news_df['date'].value_counts().to_dict()
#ν€μλλΆμ
all_text = " ".join(news_df['title'].fillna('') + " " + news_df['content'].fillna(''))
if len(all_text.strip()) > 0:
results['top_keywords_for_wordcloud']= extract_keywords_for_wordcloud(all_text, top_n=50)
results['top_keywords'] = analyze_keywords(all_text)
else:
results['top_keywords_for_wordcloud']={}
results['top_keywords'] = []
return results
# OpenAI APIλ₯Ό μ΄μ©ν μ κΈ°μ¬ μμ± (μ΅μ λ°©μ)
def generate_article(original_content, prompt_text):
try:
if not st.session_state.openai_client:
return "OpenAI API ν€κ° μ€μ λμ§ μμμ΅λλ€."
response = st.session_state.openai_client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "λΉμ μ μ λ¬Έμ μΈ λ΄μ€ κΈ°μμ
λλ€. μ£Όμ΄μ§ λ΄μ©μ λ°νμΌλ‘ μλ‘μ΄ κΈ°μ¬λ₯Ό μμ±ν΄μ£ΌμΈμ."},
{"role": "user", "content": f"λ€μ λ΄μ©μ λ°νμΌλ‘ {prompt_text}\n\n{original_content[:1000]}"}
],
max_tokens=2000
)
return response.choices[0].message.content
except Exception as e:
return f"κΈ°μ¬ μμ± μ€λ₯: {str(e)}"
# OpenAI APIλ₯Ό μ΄μ©ν μ΄λ―Έμ§ μμ± (μ΅μ λ°©μ)
def generate_image(prompt):
try:
if not st.session_state.openai_client:
return "OpenAI API ν€κ° μ€μ λμ§ μμμ΅λλ€."
response = st.session_state.openai_client.images.generate(
model="dall-e-3", # λλ μ¬μ© κ°λ₯ν λͺ¨λΈ
prompt=prompt,
n=1,
size="1024x1024"
)
return response.data[0].url # μ΅μ APIλ URLλ§ λ°ν
except Exception as e:
return f"μ΄λ―Έμ§ μμ± μ€λ₯: {str(e)}"
# μ€μΌμ€λ¬ κ΄λ ¨ ν¨μλ€
def get_next_run_time(hour, minute):
now = datetime.now()
next_run = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
if next_run <= now:
next_run += timedelta(days=1)
return next_run
def run_scheduled_task():
try:
while global_scheduler_state.is_running:
schedule.run_pending()
time.sleep(1)
except Exception as e:
print(f"μ€μΌμ€λ¬ μλ¬ λ°μ: {e}")
traceback.print_exc()
def perform_news_task(task_type, keyword, num_articles, file_prefix):
try:
articles = crawl_naver_news(keyword, num_articles)
# κΈ°μ¬ λ΄μ© κ°μ Έμ€κΈ°
for article in articles:
article['content'] = get_article_content(article['link'])
time.sleep(0.5) # μλ² λΆν λ°©μ§
# κ²°κ³Ό μ μ₯
os.makedirs('/tmp/scheduled_news', exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"/tmp/scheduled_news/{file_prefix}_{task_type}_{timestamp}.json"
with open(filename, 'w', encoding='utf-8') as f:
json.dump(articles, f, ensure_ascii=False, indent=2)
global_scheduler_state.last_run = datetime.now()
print(f"{datetime.now()} - {task_type} λ΄μ€ κΈ°μ¬ μμ§ μλ£: {keyword}")
# μ μ μνμ μμ§ κ²°κ³Όλ₯Ό μ μ₯ (UI μ
λ°μ΄νΈμ©)
result_item = {
'task_type': task_type,
'keyword': keyword,
'timestamp': timestamp,
'num_articles': len(articles),
'filename': filename
}
global_scheduler_state.scheduled_results.append(result_item)
except Exception as e:
print(f"μμ
μ€ν μ€ μ€λ₯ λ°μ: {e}")
traceback.print_exc()
def start_scheduler(daily_tasks, interval_tasks):
if not global_scheduler_state.is_running:
schedule.clear()
global_scheduler_state.scheduled_jobs = []
# μΌλ³ νμ€ν¬ λ±λ‘
for task in daily_tasks:
hour = task['hour']
minute = task['minute']
keyword = task['keyword']
num_articles = task['num_articles']
job_id = f"daily_{keyword}_{hour}_{minute}"
schedule.every().day.at(f"{hour:02d}:{minute:02d}").do(
perform_news_task, "daily", keyword, num_articles, job_id
).tag(job_id)
global_scheduler_state.scheduled_jobs.append({
'id': job_id,
'type': 'daily',
'time': f"{hour:02d}:{minute:02d}",
'keyword': keyword,
'num_articles': num_articles
})
# μκ° κ°κ²© νμ€ν¬ λ±λ‘
for task in interval_tasks:
interval_minutes = task['interval_minutes']
keyword = task['keyword']
num_articles = task['num_articles']
run_immediately = task['run_immediately']
job_id = f"interval_{keyword}_{interval_minutes}"
if run_immediately:
# μ¦μ μ€ν
perform_news_task("interval", keyword, num_articles, job_id)
# λΆ κ°κ²©μΌλ‘ μμ½
schedule.every(interval_minutes).minutes.do(
perform_news_task, "interval", keyword, num_articles, job_id
).tag(job_id)
global_scheduler_state.scheduled_jobs.append({
'id': job_id,
'type': 'interval',
'interval': f"{interval_minutes}λΆλ§λ€",
'keyword': keyword,
'num_articles': num_articles,
'run_immediately': run_immediately
})
# λ€μ μ€ν μκ° κ³μ°
next_run = schedule.next_run()
if next_run:
global_scheduler_state.next_run = next_run
# μ€μΌμ€λ¬ μ°λ λ μμ
global_scheduler_state.is_running = True
global_scheduler_state.thread = threading.Thread(
target=run_scheduled_task, daemon=True
)
global_scheduler_state.thread.start()
# μνλ₯Ό μΈμ
μνλ‘λ λ³΅μ¬ (UI νμμ©)
if 'scheduler_status' not in st.session_state:
st.session_state.scheduler_status = {}
st.session_state.scheduler_status = {
'is_running': global_scheduler_state.is_running,
'last_run': global_scheduler_state.last_run,
'next_run': global_scheduler_state.next_run,
'jobs_count': len(global_scheduler_state.scheduled_jobs)
}
def stop_scheduler():
if global_scheduler_state.is_running:
global_scheduler_state.is_running = False
schedule.clear()
if global_scheduler_state.thread:
global_scheduler_state.thread.join(timeout=1)
global_scheduler_state.next_run = None
global_scheduler_state.scheduled_jobs = []
# UI μν μ
λ°μ΄νΈ
if 'scheduler_status' in st.session_state:
st.session_state.scheduler_status['is_running'] = False
# λ©λ΄μ λ°λ₯Έ νλ©΄ νμ
if menu == "λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§":
st.header("λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§")
keyword = st.text_input("κ²μμ΄ μ
λ ₯", "μΈκ³΅μ§λ₯")
num_articles = st.slider("κ°μ Έμ¬ κΈ°μ¬ μ", min_value=1, max_value=20, value=5)
if st.button("κΈ°μ¬ κ°μ Έμ€κΈ°"):
with st.spinner("κΈ°μ¬λ₯Ό μμ§ μ€μ
λλ€..."):
articles = crawl_naver_news(keyword, num_articles)
# κΈ°μ¬ λ΄μ© κ°μ Έμ€κΈ°
for i, article in enumerate(articles):
st.progress((i + 1) / len(articles))
article['content'] = get_article_content(article['link'])
time.sleep(0.5) # μλ² λΆν λ°©μ§
# κ²°κ³Ό μ μ₯ λ° νμ
save_articles(articles)
st.success(f"{len(articles)}κ°μ κΈ°μ¬λ₯Ό μμ§νμ΅λλ€!")
# μμ§ν κΈ°μ¬ νμ
for article in articles:
with st.expander(f"{article['title']} - {article['source']}"):
st.write(f"**μΆμ²:** {article['source']}")
st.write(f"**λ μ§:** {article['date']}")
st.write(f"**μμ½:** {article['description']}")
st.write(f"**λ§ν¬:** {article['link']}")
st.write("**본문 미리보기:**")
st.write(article['content'][:300] + "..." if len(article['content']) > 300 else article['content'])
elif menu == "κΈ°μ¬ λΆμνκΈ°":
st.header("κΈ°μ¬ λΆμνκΈ°")
articles = load_saved_articles()
if not articles:
st.warning("μ μ₯λ κΈ°μ¬κ° μμ΅λλ€. λ¨Όμ 'λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§' λ©λ΄μμ κΈ°μ¬λ₯Ό μμ§ν΄μ£ΌμΈμ.")
else:
# κΈ°μ¬ μ ν
titles = [article['title'] for article in articles]
selected_title = st.selectbox("λΆμν κΈ°μ¬ μ ν", titles)
selected_article = next((a for a in articles if a['title'] == selected_title), None)
if selected_article:
st.write(f"**μ λͺ©:** {selected_article['title']}")
st.write(f"**μΆμ²:** {selected_article['source']}")
# λ³Έλ¬Έ νμ
with st.expander("κΈ°μ¬ λ³Έλ¬Έ 보기"):
st.write(selected_article['content'])
# λΆμ λ°©λ² μ ν
analysis_type = st.radio(
"λΆμ λ°©λ²",
["ν€μλ λΆμ", "κ°μ λΆμ", "ν
μ€νΈ ν΅κ³"]
)
if analysis_type == "ν€μλ λΆμ":
if st.button("ν€μλ λΆμνκΈ°"):
with st.spinner("ν€μλλ₯Ό λΆμ μ€μ
λλ€..."):
keyword_tab1, keyword_tab2 = st.tabs(["ν€μλ λΉλ", "μλν΄λΌμ°λ"])
with keyword_tab1:
keywords = analyze_keywords(selected_article['content'])
# μκ°ν
df = pd.DataFrame(keywords, columns=['λ¨μ΄', 'λΉλμ'])
st.bar_chart(df.set_index('λ¨μ΄'))
st.write("**μ£Όμ ν€μλ:**")
for word, count in keywords:
st.write(f"- {word}: {count}ν")
with keyword_tab2:
keyword_dict = extract_keywords_for_wordcloud(selected_article['content'])
wc = generate_wordcloud(keyword_dict)
if wc:
fig, ax = plt.subplots(figsize=(10, 5))
ax.imshow(wc, interpolation='bilinear')
ax.axis('off')
st.pyplot(fig)
# ν€μλ μμ 20κ° νμ
st.write("**μμ 20κ° ν€μλ:**")
top_keywords = sorted(keyword_dict.items(), key=lambda x: x[1], reverse=True)[:20]
keyword_df = pd.DataFrame(top_keywords, columns=['ν€μλ', 'λΉλ'])
st.dataframe(keyword_df)
else:
st.error("μλν΄λΌμ°λλ₯Ό μμ±ν μ μμ΅λλ€.")
elif analysis_type == "ν
μ€νΈ ν΅κ³":
if st.button("ν
μ€νΈ ν΅κ³ λΆμ"):
content = selected_article['content']
# ν
μ€νΈ ν΅κ³ κ³μ°
word_count = len(re.findall(r'\b\w+\b', content))
char_count = len(content)
sentence_count = len(re.split(r'[.!?]+', content))
avg_word_length = sum(len(word) for word in re.findall(r'\b\w+\b', content)) / word_count if word_count > 0 else 0
avg_sentence_length = word_count / sentence_count if sentence_count > 0 else 0
# ν΅κ³ νμ
st.subheader("ν
μ€νΈ ν΅κ³")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("λ¨μ΄ μ", f"{word_count:,}")
with col2:
st.metric("λ¬Έμ μ", f"{char_count:,}")
with col3:
st.metric("λ¬Έμ₯ μ", f"{sentence_count:,}")
col1, col2 = st.columns(2)
with col1:
st.metric("νκ· λ¨μ΄ κΈΈμ΄", f"{avg_word_length:.1f}μ")
with col2:
st.metric("νκ· λ¬Έμ₯ κΈΈμ΄", f"{avg_sentence_length:.1f}λ¨μ΄")
# ν
μ€νΈ 볡μ‘μ± μ μ (κ°λ¨ν μμ)
complexity_score = min(10, (avg_sentence_length / 10) * 5 + (avg_word_length / 5) * 5)
st.progress(complexity_score / 10)
st.write(f"ν
μ€νΈ 볡μ‘μ± μ μ: {complexity_score:.1f}/10")
# μΆν λΉλ λ§λ κ·Έλν
st.subheader("νμ¬λ³ λΆν¬ (νκ΅μ΄/μμ΄ μ§μ)")
try:
# KoNLPy μ€μΉ νμΈ
try:
from konlpy.tag import Okt
konlpy_installed = True
except ImportError:
konlpy_installed = False
st.warning("νκ΅μ΄ ννμ λΆμμ μν΄ KoNLPyλ₯Ό μ€μΉν΄μ£ΌμΈμ: pip install konlpy")
# μμ΄ POS tagger μ€λΉ
from nltk import pos_tag
try:
nltk.data.find('taggers/averaged_perceptron_tagger')
except LookupError:
nltk.download('averaged_perceptron_tagger', download_dir=nltk_data_dir)
# μΈμ΄ κ°μ§ (κ°λ¨ν λ°©μ)
is_korean = bool(re.search(r'[κ°-ν£]', content))
if is_korean and konlpy_installed:
# νκ΅μ΄ ννμ λΆμ
okt = Okt()
tagged = okt.pos(content)
# νκ΅μ΄ νμ¬ λ§€ν
pos_dict = {
'Noun': 'λͺ
μ¬', 'NNG': 'λͺ
μ¬', 'NNP': 'κ³ μ λͺ
μ¬',
'Verb': 'λμ¬', 'VV': 'λμ¬', 'VA': 'νμ©μ¬',
'Adjective': 'νμ©μ¬',
'Adverb': 'λΆμ¬',
'Josa': 'μ‘°μ¬', 'Punctuation': 'ꡬλμ ',
'Determiner': 'κ΄νμ¬', 'Exclamation': 'κ°νμ¬'
}
pos_counts = {'λͺ
μ¬': 0, 'λμ¬': 0, 'νμ©μ¬': 0, 'λΆμ¬': 0, 'μ‘°μ¬': 0, 'ꡬλμ ': 0, 'κ΄νμ¬': 0, 'κ°νμ¬': 0, 'κΈ°ν': 0}
for _, pos in tagged:
if pos in pos_dict:
pos_counts[pos_dict[pos]] += 1
elif pos.startswith('N'): # κΈ°ν λͺ
μ¬λ₯
pos_counts['λͺ
μ¬'] += 1
elif pos.startswith('V'): # κΈ°ν λμ¬λ₯
pos_counts['λμ¬'] += 1
else:
pos_counts['κΈ°ν'] += 1
else:
# μμ΄ POS νκΉ
tokens = word_tokenize(content.lower())
tagged = pos_tag(tokens)
# μμ΄ νμ¬ λ§€ν
pos_dict = {
'NN': 'λͺ
μ¬', 'NNS': 'λͺ
μ¬', 'NNP': 'κ³ μ λͺ
μ¬', 'NNPS': 'κ³ μ λͺ
μ¬',
'VB': 'λμ¬', 'VBD': 'λμ¬', 'VBG': 'λμ¬', 'VBN': 'λμ¬', 'VBP': 'λμ¬', 'VBZ': 'λμ¬',
'JJ': 'νμ©μ¬', 'JJR': 'νμ©μ¬', 'JJS': 'νμ©μ¬',
'RB': 'λΆμ¬', 'RBR': 'λΆμ¬', 'RBS': 'λΆμ¬'
}
pos_counts = {'λͺ
μ¬': 0, 'λμ¬': 0, 'νμ©μ¬': 0, 'λΆμ¬': 0, 'κΈ°ν': 0}
for _, pos in tagged:
if pos in pos_dict:
pos_counts[pos_dict[pos]] += 1
else:
pos_counts['κΈ°ν'] += 1
# κ²°κ³Ό μκ°ν
pos_df = pd.DataFrame({
'νμ¬': list(pos_counts.keys()),
'λΉλ': list(pos_counts.values())
})
st.bar_chart(pos_df.set_index('νμ¬'))
if is_korean:
st.info("νκ΅μ΄ ν
μ€νΈκ° κ°μ§λμμ΅λλ€.")
else:
st.info("μμ΄ ν
μ€νΈκ° κ°μ§λμμ΅λλ€.")
except Exception as e:
st.error(f"νμ¬ λΆμ μ€ μ€λ₯ λ°μ: {str(e)}")
st.error(traceback.format_exc())
elif analysis_type == "κ°μ λΆμ":
if st.button("κ°μ λΆμνκΈ°"):
if st.session_state.openai_client:
with st.spinner("κΈ°μ¬μ κ°μ μ λΆμ μ€μ
λλ€..."):
try:
# κ°μ λΆμ ν둬ννΈ μ€μ (μ΅μ λ°©μ)
response = st.session_state.openai_client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "λΉμ μ ν
μ€νΈμ κ°μ κ³Ό λ
Όμ‘°λ₯Ό λΆμνλ μ λ¬Έκ°μ
λλ€. λ€μ λ΄μ€ κΈ°μ¬μ κ°μ κ³Ό λ
Όμ‘°λ₯Ό λΆμνκ³ , 'κΈμ μ ', 'λΆμ μ ', 'μ€λ¦½μ ' μ€ νλλ‘ λΆλ₯ν΄ μ£ΌμΈμ. λν κΈ°μ¬μμ λλ¬λλ ν΅μ¬ κ°μ ν€μλλ₯Ό 5κ° μΆμΆνκ³ , κ° ν€μλλ³λ‘ 1-10 μ¬μ΄μ κ°λ μ μλ₯Ό 맀겨주μΈμ. JSON νμμΌλ‘ λ€μκ³Ό κ°μ΄ μλ΅ν΄μ£ΌμΈμ: {'sentiment': 'κΈμ μ /λΆμ μ /μ€λ¦½μ ', 'reason': 'μ΄μ μ€λͺ
...', 'keywords': [{'word': 'ν€μλ1', 'score': 8}, {'word': 'ν€μλ2', 'score': 7}, ...]}"},
{"role": "user", "content": f"λ€μ λ΄μ€ κΈ°μ¬λ₯Ό λΆμν΄ μ£ΌμΈμ:\n\nμ λͺ©: {selected_article['title']}\n\nλ΄μ©: {selected_article['content'][:1500]}"}
],
max_tokens=800,
response_format={"type": "json_object"}
)
# JSON νμ± (μ΅μ λ°©μ)
analysis_result = json.loads(response.choices[0].message.content)
# κ²°κ³Ό μκ°ν
st.subheader("κ°μ λΆμ κ²°κ³Ό")
# 1. κ°μ νμ
μ λ°λ₯Έ μκ°μ νν
sentiment_type = analysis_result.get('sentiment', 'μ€λ¦½μ ')
col1, col2, col3 = st.columns([1, 3, 1])
with col2:
if sentiment_type == "κΈμ μ ":
st.markdown(f"""
<div style="background-color:#DCEDC8; padding:20px; border-radius:10px; text-align:center;">
<h1 style="color:#388E3C; font-size:28px;">π κΈμ μ λ
Όμ‘° π</h1>
<p style="font-size:16px;">κ°μ κ°λ: λμ</p>
</div>
""", unsafe_allow_html=True)
elif sentiment_type == "λΆμ μ ":
st.markdown(f"""
<div style="background-color:#FFCDD2; padding:20px; border-radius:10px; text-align:center;">
<h1 style="color:#D32F2F; font-size:28px;">π λΆμ μ λ
Όμ‘° π</h1>
<p style="font-size:16px;">κ°μ κ°λ: λμ</p>
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div style="background-color:#E0E0E0; padding:20px; border-radius:10px; text-align:center;">
<h1 style="color:#616161; font-size:28px;">π μ€λ¦½μ λ
Όμ‘° π</h1>
<p style="font-size:16px;">κ°μ κ°λ: μ€κ°</p>
</div>
""", unsafe_allow_html=True)
# 2. μ΄μ μ€λͺ
st.markdown("### λΆμ κ·Όκ±°")
st.markdown(f"<div style='background-color:#F5F5F5; padding:15px; border-radius:5px;'>{analysis_result.get('reason', '')}</div>", unsafe_allow_html=True)
# 3. κ°μ ν€μλ μκ°ν
st.markdown("### ν΅μ¬ κ°μ ν€μλ")
# ν€μλ λ°μ΄ν° μ€λΉ
keywords = analysis_result.get('keywords', [])
if keywords:
# λ§λ μ°¨νΈμ© λ°μ΄ν°
keyword_names = [item.get('word', '') for item in keywords]
keyword_scores = [item.get('score', 0) for item in keywords]
# λ μ΄λ μ°¨νΈ μμ±
fig = go.Figure()
# μμ μ€μ
if sentiment_type == "κΈμ μ ":
fill_color = 'rgba(76, 175, 80, 0.3)' # μ°ν μ΄λ‘μ
line_color = 'rgba(76, 175, 80, 1)' # μ§ν μ΄λ‘μ
elif sentiment_type == "λΆμ μ ":
fill_color = 'rgba(244, 67, 54, 0.3)' # μ°ν λΉ¨κ°μ
line_color = 'rgba(244, 67, 54, 1)' # μ§ν λΉ¨κ°μ
else:
fill_color = 'rgba(158, 158, 158, 0.3)' # μ°ν νμ
line_color = 'rgba(158, 158, 158, 1)' # μ§ν νμ
# λ μ΄λ μ°¨νΈ λ°μ΄ν° μ€λΉ - λ§μ§λ§ μ μ΄ μ²« μ κ³Ό μ°κ²°λλλ‘ λ°μ΄ν° μΆκ°
radar_keywords = keyword_names.copy()
radar_scores = keyword_scores.copy()
# λ μ΄λ μ°¨νΈ μμ±
fig.add_trace(go.Scatterpolar(
r=radar_scores,
theta=radar_keywords,
fill='toself',
fillcolor=fill_color,
line=dict(color=line_color, width=2),
name='κ°μ ν€μλ'
))
# λ μ΄λ μ°¨νΈ λ μ΄μμ μ€μ
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 10],
tickmode='linear',
tick0=0,
dtick=2
)
),
showlegend=False,
title={
'text': 'κ°μ ν€μλ λ μ΄λ λΆμ',
'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'
},
height=500,
width=500,
margin=dict(l=80, r=80, t=80, b=80)
)
# μ°¨νΈ μ€μμ νμ
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.plotly_chart(fig)
# ν€μλ μΉ΄λλ‘ νμ
st.markdown("#### ν€μλ μΈλΆ μ€λͺ
")
cols = st.columns(min(len(keywords), 5))
for i, keyword in enumerate(keywords):
with cols[i % len(cols)]:
word = keyword.get('word', '')
score = keyword.get('score', 0)
# μ μμ λ°λ₯Έ μμ κ³μ°
r, g, b = 0, 0, 0
if sentiment_type == "κΈμ μ ":
g = min(200 + score * 5, 255)
r = max(255 - score * 20, 100)
elif sentiment_type == "λΆμ μ ":
r = min(200 + score * 5, 255)
g = max(255 - score * 20, 100)
else:
r = g = b = 128
# μΉ΄λ μμ±
st.markdown(f"""
<div style="background-color:rgba({r},{g},{b},0.2); padding:10px; border-radius:5px; text-align:center; margin:5px;">
<h3 style="margin:0;">{word}</h3>
<div style="background-color:#E0E0E0; border-radius:3px; margin-top:5px;">
<div style="width:{score*10}%; background-color:rgba({r},{g},{b},0.8); height:10px; border-radius:3px;"></div>
</div>
<p style="margin:2px; font-size:12px;">κ°λ: {score}/10</p>
</div>
""", unsafe_allow_html=True)
else:
st.info("ν€μλλ₯Ό μΆμΆνμ§ λͺ»νμ΅λλ€.")
# 4. μμ½ ν΅κ³
st.markdown("### μ£Όμ ν΅κ³")
col1, col2, col3 = st.columns(3)
with col1:
st.metric(label="κΈμ /λΆμ μ μ", value=f"{7 if sentiment_type == 'κΈμ μ ' else 3 if sentiment_type == 'λΆμ μ ' else 5}/10")
with col2:
st.metric(label="ν€μλ μ", value=len(keywords))
with col3:
avg_score = sum(keyword_scores) / len(keyword_scores) if keyword_scores else 0
st.metric(label="νκ· κ°λ", value=f"{avg_score:.1f}/10")
except Exception as e:
st.error(f"κ°μ λΆμ μ€λ₯: {str(e)}")
st.code(traceback.format_exc())
else:
st.warning("OpenAI API ν€κ° μ€μ λμ΄ μμ§ μμ΅λλ€. μ¬μ΄λλ°μμ API ν€λ₯Ό μ€μ ν΄μ£ΌμΈμ.")
elif menu == "μ κΈ°μ¬ μμ±νκΈ°":
st.header("μ κΈ°μ¬ μμ±νκΈ°")
articles = load_saved_articles()
if not articles:
st.warning("μ μ₯λ κΈ°μ¬κ° μμ΅λλ€. λ¨Όμ 'λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§' λ©λ΄μμ κΈ°μ¬λ₯Ό μμ§ν΄μ£ΌμΈμ.")
else:
# κΈ°μ¬ μ ν
titles = [article['title'] for article in articles]
selected_title = st.selectbox("μλ³Έ κΈ°μ¬ μ ν", titles)
selected_article = next((a for a in articles if a['title'] == selected_title), None)
if selected_article:
st.write(f"**μλ³Έ μ λͺ©:** {selected_article['title']}")
with st.expander("μλ³Έ κΈ°μ¬ λ΄μ©"):
st.write(selected_article['content'])
prompt_text ="""λ€μ κΈ°μ¬ μμμ λ°λΌμ λ€μ μμ±ν΄μ€.
μν : λΉμ μ μ λ¬Έμ¬μ κΈ°μμ
λλ€.
μμ
: μ΅κ·Ό μΌμ΄λ μ¬κ±΄μ λν 보λμλ£λ₯Ό μμ±ν΄μΌ ν©λλ€. μλ£λ μ¬μ€μ κΈ°λ°μΌλ‘ νλ©°, κ°κ΄μ μ΄κ³ μ νν΄μΌ ν©λλ€.
μ§μΉ¨:
μ 곡λ μ 보λ₯Ό λ°νμΌλ‘ μ λ¬Έ 보λμλ£ νμμ λ§μΆ° κΈ°μ¬λ₯Ό μμ±νμΈμ.
κΈ°μ¬ μ λͺ©μ μ£Όμ λ₯Ό λͺ
νν λ°μνκ³ λ
μμ κ΄μ¬μ λ μ μλλ‘ μμ±ν©λλ€.
κΈ°μ¬ λ΄μ©μ μ ννκ³ κ°κ²°νλ©° μ€λλ ₯ μλ λ¬Έμ₯μΌλ‘ ꡬμ±ν©λλ€.
κ΄λ ¨μμ μΈν°λ·°λ₯Ό μΈμ© ννλ‘ λ£μ΄μ£ΌμΈμ.
μμ μ 보μ μ§μΉ¨μ μ°Έκ³ νμ¬ μ λ¬Έ 보λμλ£ νμμ κΈ°μ¬λ₯Ό μμ±ν΄ μ£ΌμΈμ"""
# μ΄λ―Έμ§ μμ± μ¬λΆ μ ν μ΅μ
μΆκ°
generate_image_too = st.checkbox("κΈ°μ¬ μμ± ν μ΄λ―Έμ§λ ν¨κ» μμ±νκΈ°", value=True)
if st.button("μ κΈ°μ¬ μμ±νκΈ°"):
if st.session_state.openai_client:
with st.spinner("κΈ°μ¬λ₯Ό μμ± μ€μ
λλ€..."):
new_article = generate_article(selected_article['content'], prompt_text)
st.write("**μμ±λ κΈ°μ¬:**")
st.write(new_article)
# μ΄λ―Έμ§ μμ±νκΈ° (μ΅μ
μ΄ μ νλ κ²½μ°)
if generate_image_too:
with st.spinner("κΈ°μ¬ κ΄λ ¨ μ΄λ―Έμ§λ₯Ό μμ± μ€μ
λλ€..."):
# μ΄λ―Έμ§ μμ± ν둬ννΈ μ€λΉ
image_prompt = f"""μ λ¬ΈκΈ°μ¬ μ λͺ© "{selected_article['title']}" μ λ³΄κ³ μ΄λ―Έμ§λ₯Ό λ§λ€μ΄μ€
μ΄λ―Έμ§μλ λ€μ μμκ° ν¬ν¨λμ΄μΌ ν©λλ€:
- κΈ°μ¬λ₯Ό μ΄ν΄ν μ μλ λμ
- κΈ°μ¬ λ΄μ©κ³Ό κ΄λ ¨λ ν
μ€νΈ
- μ¬ννκ² μ²λ¦¬
"""
# μ΄λ―Έμ§ μμ±
image_url = generate_image(image_prompt)
if image_url and not image_url.startswith("μ΄λ―Έμ§ μμ± μ€λ₯"):
st.subheader("μμ±λ μ΄λ―Έμ§:")
st.image(image_url)
else:
st.error(image_url)
# μμ±λ κΈ°μ¬ μ μ₯ μ΅μ
if st.button("μμ±λ κΈ°μ¬ μ μ₯"):
new_article_data = {
'title': f"[μμ±λ¨] {selected_article['title']}",
'source': f"AI μμ± (μλ³Έ: {selected_article['source']})",
'date': datetime.now().strftime("%Y-%m-%d %H:%M"),
'description': new_article[:100] + "...",
'link': "",
'content': new_article
}
articles.append(new_article_data)
save_articles(articles)
st.success("μμ±λ κΈ°μ¬κ° μ μ₯λμμ΅λλ€!")
else:
st.warning("OpenAI API ν€λ₯Ό μ¬μ΄λλ°μμ μ€μ ν΄μ£ΌμΈμ.")
elif menu == "λ΄μ€ κΈ°μ¬ μμ½νκΈ°":
st.header("λ΄μ€ κΈ°μ¬ μμ½νκΈ°")
# ν μμ±
tab1, tab2, tab3 = st.tabs(["μΌλ³ μμ½", "μκ° κ°κ²© μμ½", "μ€μΌμ€λ¬ μν"])
# μΌλ³ μμ½ ν
with tab1:
st.subheader("λ§€μΌ μ ν΄μ§ μκ°μ κΈ°μ¬ μμ§νκΈ°")
# ν€μλ μ
λ ₯
daily_keyword = st.text_input("κ²μ ν€μλ", value="μΈκ³΅μ§λ₯", key="daily_keyword")
daily_num_articles = st.slider("μμ§ν κΈ°μ¬ μ", min_value=1, max_value=20, value=5, key="daily_num_articles")
# μκ° μ€μ
daily_col1, daily_col2 = st.columns(2)
with daily_col1:
daily_hour = st.selectbox("μ", range(24), format_func=lambda x: f"{x:02d}μ", key="daily_hour")
with daily_col2:
daily_minute = st.selectbox("λΆ", range(0, 60, 5), format_func=lambda x: f"{x:02d}λΆ", key="daily_minute")
# μΌλ³ μμ½ λ¦¬μ€νΈ
if 'daily_tasks' not in st.session_state:
st.session_state.daily_tasks = []
if st.button("μΌλ³ μμ½ μΆκ°"):
st.session_state.daily_tasks.append({
'hour': daily_hour,
'minute': daily_minute,
'keyword': daily_keyword,
'num_articles': daily_num_articles
})
st.success(f"μΌλ³ μμ½μ΄ μΆκ°λμμ΅λλ€: λ§€μΌ {daily_hour:02d}:{daily_minute:02d} - '{daily_keyword}'")
# μμ½ λͺ©λ‘ νμ
if st.session_state.daily_tasks:
st.subheader("μΌλ³ μμ½ λͺ©λ‘")
for i, task in enumerate(st.session_state.daily_tasks):
st.write(f"{i+1}. λ§€μΌ {task['hour']:02d}:{task['minute']:02d} - '{task['keyword']}' ({task['num_articles']}κ°)")
if st.button("μΌλ³ μμ½ μ΄κΈ°ν"):
st.session_state.daily_tasks = []
st.warning("μΌλ³ μμ½μ΄ λͺ¨λ μ΄κΈ°νλμμ΅λλ€.")
# μκ° κ°κ²© μμ½ ν
with tab2:
st.subheader("μκ° κ°κ²©μΌλ‘ κΈ°μ¬ μμ§νκΈ°")
# ν€μλ μ
λ ₯
interval_keyword = st.text_input("κ²μ ν€μλ", value="λΉ
λ°μ΄ν°", key="interval_keyword")
interval_num_articles = st.slider("μμ§ν κΈ°μ¬ μ", min_value=1, max_value=20, value=5, key="interval_num_articles")
# μκ° κ°κ²© μ€μ
interval_minutes = st.number_input("μ€ν κ°κ²©(λΆ)", min_value=1, max_value=60*24, value=30, key="interval_minutes")
# μ¦μ μ€ν μ¬λΆ
run_immediately = st.checkbox("μ¦μ μ€ν", value=True, help="체ν¬νλ©΄ μ€μΌμ€λ¬ μμ μ μ¦μ μ€νν©λλ€.")
# μκ° κ°κ²© μμ½ λ¦¬μ€νΈ
if 'interval_tasks' not in st.session_state:
st.session_state.interval_tasks = []
if st.button("μκ° κ°κ²© μμ½ μΆκ°"):
st.session_state.interval_tasks.append({
'interval_minutes': interval_minutes,
'keyword': interval_keyword,
'num_articles': interval_num_articles,
'run_immediately': run_immediately
})
st.success(f"μκ° κ°κ²© μμ½μ΄ μΆκ°λμμ΅λλ€: {interval_minutes}λΆλ§λ€ - '{interval_keyword}'")
# μμ½ λͺ©λ‘ νμ
if st.session_state.interval_tasks:
st.subheader("μκ° κ°κ²© μμ½ λͺ©λ‘")
for i, task in enumerate(st.session_state.interval_tasks):
immediate_text = "μ¦μ μ€ν ν " if task['run_immediately'] else ""
st.write(f"{i+1}. {immediate_text}{task['interval_minutes']}λΆλ§λ€ - '{task['keyword']}' ({task['num_articles']}κ°)")
if st.button("μκ° κ°κ²© μμ½ μ΄κΈ°ν"):
st.session_state.interval_tasks = []
st.warning("μκ° κ°κ²© μμ½μ΄ λͺ¨λ μ΄κΈ°νλμμ΅λλ€.")
# μ€μΌμ€λ¬ μν ν
with tab3:
st.subheader("μ€μΌμ€λ¬ μ μ΄ λ° μν")
col1, col2 = st.columns(2)
with col1:
# μ€μΌμ€λ¬ μμ/μ€μ§ λ²νΌ
if not global_scheduler_state.is_running:
if st.button("μ€μΌμ€λ¬ μμ"):
if not st.session_state.daily_tasks and not st.session_state.interval_tasks:
st.error("μμ½λ μμ
μ΄ μμ΅λλ€. λ¨Όμ μΌλ³ μμ½ λλ μκ° κ°κ²© μμ½μ μΆκ°ν΄μ£ΌμΈμ.")
else:
start_scheduler(st.session_state.daily_tasks, st.session_state.interval_tasks)
st.success("μ€μΌμ€λ¬κ° μμλμμ΅λλ€.")
else:
if st.button("μ€μΌμ€λ¬ μ€μ§"):
stop_scheduler()
st.warning("μ€μΌμ€λ¬κ° μ€μ§λμμ΅λλ€.")
with col2:
# μ€μΌμ€λ¬ μν νμ
if 'scheduler_status' in st.session_state:
st.write(f"μν: {'μ€νμ€' if global_scheduler_state.is_running else 'μ€μ§'}")
if global_scheduler_state.last_run:
st.write(f"λ§μ§λ§ μ€ν: {global_scheduler_state.last_run.strftime('%Y-%m-%d %H:%M:%S')}")
if global_scheduler_state.next_run and global_scheduler_state.is_running:
st.write(f"λ€μ μ€ν: {global_scheduler_state.next_run.strftime('%Y-%m-%d %H:%M:%S')}")
else:
st.write("μν: μ€μ§")
# μμ½λ μμ
λͺ©λ‘
if global_scheduler_state.scheduled_jobs:
st.subheader("νμ¬ μ€ν μ€μΈ μμ½ μμ
")
for i, job in enumerate(global_scheduler_state.scheduled_jobs):
if job['type'] == 'daily':
st.write(f"{i+1}. [μΌλ³] λ§€μΌ {job['time']} - '{job['keyword']}' ({job['num_articles']}κ°)")
else:
immediate_text = "[μ¦μ μ€ν ν] " if job.get('run_immediately', False) else ""
st.write(f"{i+1}. [κ°κ²©] {immediate_text}{job['interval']} - '{job['keyword']}' ({job['num_articles']}κ°)")
# μ€μΌμ€λ¬ μ€ν κ²°κ³Ό
if global_scheduler_state.scheduled_results:
st.subheader("μ€μΌμ€λ¬ μ€ν κ²°κ³Ό")
# κ²°κ³Όλ₯Ό UIμ νμνκΈ° μ μ 볡μ¬
results_for_display = global_scheduler_state.scheduled_results.copy()
if results_for_display:
result_df = pd.DataFrame(results_for_display)
result_df['μ€νμκ°'] = result_df['timestamp'].apply(lambda x: datetime.strptime(x, "%Y%m%d_%H%M%S").strftime("%Y-%m-%d %H:%M:%S"))
result_df = result_df.rename(columns={
'task_type': 'μμ
μ ν',
'keyword': 'ν€μλ',
'num_articles': 'κΈ°μ¬μ',
'filename': 'νμΌλͺ
'
})
result_df['μμ
μ ν'] = result_df['μμ
μ ν'].apply(lambda x: 'μΌλ³' if x == 'daily' else 'μκ°κ°κ²©')
st.dataframe(
result_df[['μμ
μ ν', 'ν€μλ', 'κΈ°μ¬μ', 'μ€νμκ°', 'νμΌλͺ
']],
hide_index=True
)
# μμ§λ νμΌ λ³΄κΈ°
if os.path.exists('/tmp/scheduled_news'):
files = [f for f in os.listdir('/tmp/scheduled_news') if f.endswith('.json')]
if files:
st.subheader("μμ§λ νμΌ μ΄κΈ°")
selected_file = st.selectbox("νμΌ μ ν", files, index=len(files)-1)
if selected_file and st.button("νμΌ λ΄μ© 보기"):
with open(os.path.join('/tmp/scheduled_news', selected_file), 'r', encoding='utf-8') as f:
articles = json.load(f)
st.write(f"**νμΌλͺ
:** {selected_file}")
st.write(f"**μμ§ κΈ°μ¬ μ:** {len(articles)}κ°")
for article in articles:
with st.expander(f"{article['title']} - {article['source']}"):
st.write(f"**μΆμ²:** {article['source']}")
st.write(f"**λ μ§:** {article['date']}")
st.write(f"**λ§ν¬:** {article['link']}")
st.write("**λ³Έλ¬Έ:**")
st.write(article['content'][:500] + "..." if len(article['content']) > 500 else article['content'])
# νΈν°
st.markdown("---")
st.markdown("Β© λ΄μ€ κΈ°μ¬ λꡬ @conanssam") |