Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +1118 -38
src/streamlit_app.py
CHANGED
@@ -1,40 +1,1120 @@
|
|
1 |
-
import altair as alt
|
2 |
-
import numpy as np
|
3 |
-
import pandas as pd
|
4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
11 |
-
forums](https://discuss.streamlit.io).
|
12 |
-
|
13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
14 |
-
"""
|
15 |
-
|
16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
18 |
-
|
19 |
-
indices = np.linspace(0, 1, num_points)
|
20 |
-
theta = 2 * np.pi * num_turns * indices
|
21 |
-
radius = indices
|
22 |
-
|
23 |
-
x = radius * np.cos(theta)
|
24 |
-
y = radius * np.sin(theta)
|
25 |
-
|
26 |
-
df = pd.DataFrame({
|
27 |
-
"x": x,
|
28 |
-
"y": y,
|
29 |
-
"idx": indices,
|
30 |
-
"rand": np.random.randn(num_points),
|
31 |
-
})
|
32 |
-
|
33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
34 |
-
.mark_point(filled=True)
|
35 |
-
.encode(
|
36 |
-
x=alt.X("x", axis=None),
|
37 |
-
y=alt.Y("y", axis=None),
|
38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
40 |
-
))
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import requests
|
4 |
+
from bs4 import BeautifulSoup
|
5 |
+
import re
|
6 |
+
import time
|
7 |
+
import nltk
|
8 |
+
from nltk.tokenize import word_tokenize
|
9 |
+
from nltk.corpus import stopwords
|
10 |
+
from collections import Counter
|
11 |
+
import json
|
12 |
+
import os
|
13 |
+
from datetime import datetime, timedelta
|
14 |
+
import openai
|
15 |
+
from dotenv import load_dotenv
|
16 |
+
import traceback
|
17 |
+
import plotly.graph_objects as go
|
18 |
+
import schedule
|
19 |
+
import threading
|
20 |
+
import matplotlib.pyplot as plt
|
21 |
+
|
22 |
+
# μλν΄λΌμ°λ μΆκ°
|
23 |
+
try:
|
24 |
+
from wordcloud import WordCloud
|
25 |
+
except ImportError:
|
26 |
+
st.error("wordcloud ν¨ν€μ§λ₯Ό μ€μΉν΄μ£ΌμΈμ: pip install wordcloud")
|
27 |
+
WordCloud = None
|
28 |
+
|
29 |
+
# μ€μΌμ€λ¬ μν ν΄λμ€ μΆκ°
|
30 |
+
class SchedulerState:
|
31 |
+
def __init__(self):
|
32 |
+
self.is_running = False
|
33 |
+
self.thread = None
|
34 |
+
self.last_run = None
|
35 |
+
self.next_run = None
|
36 |
+
self.scheduled_jobs = []
|
37 |
+
self.scheduled_results = []
|
38 |
+
|
39 |
+
# μ μ μ€μΌμ€λ¬ μν κ°μ²΄ μμ± (μ€λ λ μμμ μ¬μ©)
|
40 |
+
global_scheduler_state = SchedulerState()
|
41 |
+
|
42 |
+
# API ν€ κ΄λ¦¬λ₯Ό μν μΈμ
μν μ΄κΈ°ν
|
43 |
+
if 'openai_api_key' not in st.session_state:
|
44 |
+
st.session_state.openai_api_key = None
|
45 |
+
|
46 |
+
# νκ²½ λ³μμμ API ν€ λ‘λ μλ
|
47 |
+
load_dotenv()
|
48 |
+
if os.getenv('OPENAI_API_KEY'):
|
49 |
+
st.session_state.openai_api_key = os.getenv('OPENAI_API_KEY')
|
50 |
+
elif 'OPENAI_API_KEY' in st.secrets:
|
51 |
+
st.session_state.openai_api_key = st.secrets['OPENAI_API_KEY']
|
52 |
+
|
53 |
+
# νμν NLTK λ°μ΄ν° λ€μ΄λ‘λ
|
54 |
+
try:
|
55 |
+
nltk.data.find('tokenizers/punkt')
|
56 |
+
except LookupError:
|
57 |
+
nltk.download('punkt')
|
58 |
+
|
59 |
+
try:
|
60 |
+
nltk.data.find('tokenizers/punkt_tab')
|
61 |
+
except LookupError:
|
62 |
+
nltk.download('punkt_tab')
|
63 |
+
|
64 |
+
try:
|
65 |
+
nltk.data.find('corpora/stopwords')
|
66 |
+
except LookupError:
|
67 |
+
nltk.download('stopwords')
|
68 |
+
|
69 |
+
# OpenAI API ν€ μ€μ (μ€μ μ¬μ© μ νκ²½ λ³μλ Streamlit secretsμμ κ°μ Έμ€λ κ²μ΄ μ’μ΅λλ€)
|
70 |
+
if 'OPENAI_API_KEY' in os.environ:
|
71 |
+
openai.api_key = os.environ['OPENAI_API_KEY']
|
72 |
+
elif 'OPENAI_API_KEY' in st.secrets:
|
73 |
+
openai.api_key = st.secrets['OPENAI_API_KEY']
|
74 |
+
elif os.getenv('OPENAI_API_KEY'):
|
75 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
76 |
+
|
77 |
+
# νμ΄μ§ μ€μ
|
78 |
+
st.set_page_config(page_title="λ΄μ€ κΈ°μ¬ λꡬ", page_icon="π°", layout="wide")
|
79 |
+
|
80 |
+
# μ¬μ΄λλ° λ©λ΄ μ€μ
|
81 |
+
st.sidebar.title("λ΄μ€ κΈ°μ¬ λꡬ")
|
82 |
+
menu = st.sidebar.radio(
|
83 |
+
"λ©λ΄ μ ν",
|
84 |
+
["λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§", "κΈ°μ¬ λΆμνκΈ°", "μ κΈ°μ¬ μμ±νκΈ°", "λ΄μ€ κΈ°μ¬ μμ½νκΈ°"]
|
85 |
+
)
|
86 |
+
|
87 |
+
# μ μ₯λ κΈ°μ¬λ₯Ό λΆλ¬μ€λ ν¨μ
|
88 |
+
def load_saved_articles():
|
89 |
+
if os.path.exists('saved_articles/articles.json'):
|
90 |
+
with open('saved_articles/articles.json', 'r', encoding='utf-8') as f:
|
91 |
+
return json.load(f)
|
92 |
+
return []
|
93 |
+
|
94 |
+
# κΈ°μ¬λ₯Ό μ μ₯νλ ν¨μ
|
95 |
+
def save_articles(articles):
|
96 |
+
os.makedirs('saved_articles', exist_ok=True)
|
97 |
+
with open('saved_articles/articles.json', 'w', encoding='utf-8') as f:
|
98 |
+
json.dump(articles, f, ensure_ascii=False, indent=2)
|
99 |
+
|
100 |
+
@st.cache_data
|
101 |
+
def crawl_naver_news(keyword, num_articles=5):
|
102 |
+
"""
|
103 |
+
λ€μ΄λ² λ΄μ€ κΈ°μ¬λ₯Ό μμ§νλ ν¨μ
|
104 |
+
"""
|
105 |
+
url = f"https://search.naver.com/search.naver?where=news&query={keyword}"
|
106 |
+
results = []
|
107 |
+
|
108 |
+
try:
|
109 |
+
# νμ΄μ§ μμ²
|
110 |
+
response = requests.get(url)
|
111 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
112 |
+
|
113 |
+
# λ΄μ€ μμ΄ν
μ°ΎκΈ°
|
114 |
+
news_items = soup.select('div.sds-comps-base-layout.sds-comps-full-layout')
|
115 |
+
|
116 |
+
# κ° λ΄μ€ μμ΄ν
μμ μ 보 μΆμΆ
|
117 |
+
for i, item in enumerate(news_items):
|
118 |
+
if i >= num_articles:
|
119 |
+
break
|
120 |
+
|
121 |
+
try:
|
122 |
+
# μ λͺ©κ³Ό λ§ν¬ μΆμΆ
|
123 |
+
title_element = item.select_one('a.X0fMYp2dHd0TCUS2hjww span')
|
124 |
+
if not title_element:
|
125 |
+
continue
|
126 |
+
|
127 |
+
title = title_element.text.strip()
|
128 |
+
link_element = item.select_one('a.X0fMYp2dHd0TCUS2hjww')
|
129 |
+
link = link_element['href'] if link_element else ""
|
130 |
+
|
131 |
+
# μΈλ‘ μ¬ μΆμΆ
|
132 |
+
press_element = item.select_one('div.sds-comps-profile-info-title span.sds-comps-text-type-body2')
|
133 |
+
source = press_element.text.strip() if press_element else "μ μ μμ"
|
134 |
+
|
135 |
+
# λ μ§ μΆμΆ
|
136 |
+
date_element = item.select_one('span.r0VOr')
|
137 |
+
date = date_element.text.strip() if date_element else "μ μ μμ"
|
138 |
+
|
139 |
+
# 미리보기 λ΄μ© μΆμΆ
|
140 |
+
desc_element = item.select_one('a.X0fMYp2dHd0TCUS2hjww.IaKmSOGPdofdPwPE6cyU > span')
|
141 |
+
description = desc_element.text.strip() if desc_element else "λ΄μ© μμ"
|
142 |
+
|
143 |
+
results.append({
|
144 |
+
'title': title,
|
145 |
+
'link': link,
|
146 |
+
'description': description,
|
147 |
+
'source': source,
|
148 |
+
'date': date,
|
149 |
+
'content': "" # λμ€μ μλ¬Έ λ΄μ©μ μ μ₯ν νλ
|
150 |
+
})
|
151 |
+
|
152 |
+
except Exception as e:
|
153 |
+
st.error(f"κΈ°μ¬ μ 보 μΆμΆ μ€ μ€λ₯ λ°μ: {str(e)}")
|
154 |
+
continue
|
155 |
+
|
156 |
+
except Exception as e:
|
157 |
+
st.error(f"νμ΄μ§ μμ² μ€ μ€λ₯ λ°μ: {str(e)}")
|
158 |
+
|
159 |
+
return results
|
160 |
+
|
161 |
+
# κΈ°μ¬ μλ¬Έ κ°μ Έμ€κΈ°
|
162 |
+
def get_article_content(url):
|
163 |
+
try:
|
164 |
+
response = requests.get(url, timeout=5)
|
165 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
166 |
+
|
167 |
+
# λ€μ΄λ² λ΄μ€ λ³Έλ¬Έ μ°ΎκΈ°
|
168 |
+
content = soup.select_one('#dic_area')
|
169 |
+
if content:
|
170 |
+
text = content.text.strip()
|
171 |
+
text = re.sub(r'\s+', ' ', text) # μ¬λ¬ 곡백 μ κ±°
|
172 |
+
return text
|
173 |
+
|
174 |
+
# λ€λ₯Έ λ΄μ€ μ¬μ΄νΈ λ³Έλ¬Έ μ°ΎκΈ° (μ¬λ¬ μ¬μ΄νΈ λμ νμ)
|
175 |
+
content = soup.select_one('.article_body, .article-body, .article-content, .news-content-inner')
|
176 |
+
if content:
|
177 |
+
text = content.text.strip()
|
178 |
+
text = re.sub(r'\s+', ' ', text)
|
179 |
+
return text
|
180 |
+
|
181 |
+
return "λ³Έλ¬Έμ κ°μ Έμ¬ μ μμ΅λλ€."
|
182 |
+
except Exception as e:
|
183 |
+
return f"μ€λ₯ λ°μ: {str(e)}"
|
184 |
+
|
185 |
+
# NLTKλ₯Ό μ΄μ©ν ν€μλ λΆμ
|
186 |
+
def analyze_keywords(text, top_n=10):
|
187 |
+
# νκ΅μ΄ λΆμ©μ΄ λͺ©λ‘ (μ§μ μ μν΄μΌ ν©λλ€)
|
188 |
+
korean_stopwords = ['μ΄', 'κ·Έ', 'μ ', 'κ²', 'λ°', 'λ±', 'λ₯Ό', 'μ', 'μ', 'μμ', 'μ', 'μΌλ‘', 'λ‘']
|
189 |
+
|
190 |
+
tokens = word_tokenize(text)
|
191 |
+
tokens = [word for word in tokens if word.isalnum() and len(word) > 1 and word not in korean_stopwords]
|
192 |
+
|
193 |
+
word_count = Counter(tokens)
|
194 |
+
top_keywords = word_count.most_common(top_n)
|
195 |
+
|
196 |
+
return top_keywords
|
197 |
+
|
198 |
+
#μλ ν΄λΌμ°λμ© λΆμ
|
199 |
+
def extract_keywords_for_wordcloud(text, top_n=50):
|
200 |
+
if not text or len(text.strip()) < 10:
|
201 |
+
return {}
|
202 |
+
|
203 |
+
try:
|
204 |
+
try:
|
205 |
+
tokens = word_tokenize(text.lower())
|
206 |
+
except Exception as e:
|
207 |
+
st.warning(f"{str(e)} μ€λ₯λ°μ")
|
208 |
+
tokens = text.lower().split()
|
209 |
+
|
210 |
+
stop_words = set()
|
211 |
+
try:
|
212 |
+
stop_words = set(stopwords.words('english'))
|
213 |
+
except Exception:
|
214 |
+
pass
|
215 |
+
|
216 |
+
korea_stop_words = {
|
217 |
+
'λ°', 'λ±', 'λ₯Ό', 'μ΄', 'μ', 'κ°', 'μ', 'λ', 'μΌλ‘', 'μμ', 'κ·Έ', 'λ', 'λλ', 'νλ', 'ν ', 'νκ³ ',
|
218 |
+
'μλ€', 'μ΄λ€', 'μν΄', 'κ²μ΄λ€', 'κ²μ', 'λν', 'λλ¬Έ', 'κ·Έλ¦¬κ³ ', 'νμ§λ§', 'κ·Έλ¬λ', 'κ·Έλμ',
|
219 |
+
'μ
λλ€', 'ν©λλ€', 'μ΅λλ€', 'μ', 'μ£ ', 'κ³ ', 'κ³Ό', 'μ', 'λ', 'μ', 'μ', 'κ²', 'λ€', 'μ ', 'μ ',
|
220 |
+
'λ
', 'μ', 'μΌ', 'μ', 'λΆ', 'μ΄', 'μ§λ', 'μ¬ν΄', 'λ΄λ
', 'μ΅κ·Ό', 'νμ¬', 'μ€λ', 'λ΄μΌ', 'μ΄μ ',
|
221 |
+
'μ€μ ', 'μ€ν', 'λΆν°', 'κΉμ§', 'μκ²', 'κ»μ', 'μ΄λΌκ³ ', 'λΌκ³ ', 'νλ©°', 'νλ©΄μ', 'λ°λΌ', 'ν΅ν΄',
|
222 |
+
'κ΄λ ¨', 'ννΈ', 'νΉν', 'κ°μ₯', 'λ§€μ°', 'λ', 'λ', 'λ§μ΄', 'μ‘°κΈ', 'νμ', 'μμ£Ό', 'κ°λ', 'κ±°μ',
|
223 |
+
'μ ν', 'λ°λ‘', 'μ λ§', 'λ§μ½', 'λΉλ‘―ν', 'λ±μ', 'λ±μ΄', 'λ±μ', 'λ±κ³Ό', 'λ±λ', 'λ±μ', 'λ±μμ',
|
224 |
+
'κΈ°μ', 'λ΄μ€', 'μ¬μ§', 'μ°ν©λ΄μ€', 'λ΄μμ€', 'μ 곡', '무λ¨', 'μ μ¬', 'μ¬λ°°ν¬', 'κΈμ§', 'μ΅μ»€', 'λ©νΈ',
|
225 |
+
'μΌλ³΄', 'λ°μΌλ¦¬', 'κ²½μ ', 'μ¬ν', 'μ μΉ', 'μΈκ³', 'κ³Όν', 'μμ΄ν°', 'λ·μ»΄', 'μ¨λ·', 'λΈλ‘ν°', 'μ μμ λ¬Έ'
|
226 |
+
}
|
227 |
+
stop_words.update(korea_stop_words)
|
228 |
+
|
229 |
+
# 1κΈμ μ΄μμ΄κ³ λΆμ©μ΄κ° μλ ν ν°λ§ νν°λ§
|
230 |
+
filtered_tokens = [word for word in tokens if len(word) > 1 and word not in stop_words]
|
231 |
+
|
232 |
+
# λ¨μ΄ λΉλ κ³μ°
|
233 |
+
word_freq = {}
|
234 |
+
for word in filtered_tokens:
|
235 |
+
if word.isalnum(): # μνλ²³κ³Ό μ«μλ§ ν¬ν¨λ λ¨μ΄λ§ νμ©
|
236 |
+
word_freq[word] = word_freq.get(word, 0) + 1
|
237 |
+
|
238 |
+
# λΉλμμΌλ‘ μ λ ¬νμ¬ μμ nκ° λ°ν
|
239 |
+
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
|
240 |
+
|
241 |
+
if not sorted_words:
|
242 |
+
return {"data": 1, "analysis": 1, "news": 1}
|
243 |
+
|
244 |
+
return dict(sorted_words[:top_n])
|
245 |
+
|
246 |
+
except Exception as e:
|
247 |
+
st.error(f"μ€λ₯λ°μ {str(e)}")
|
248 |
+
return {"data": 1, "analysis": 1, "news": 1}
|
249 |
+
|
250 |
+
|
251 |
+
# μλ ν΄λΌμ°λ μμ± ν¨μ
|
252 |
+
|
253 |
+
def generate_wordcloud(keywords_dict):
|
254 |
+
if not WordCloud:
|
255 |
+
st.warning("μλν΄λΌμ°λ μ€μΉμλμ΄ μμ΅λλ€.")
|
256 |
+
return None
|
257 |
+
try:
|
258 |
+
wc= WordCloud(
|
259 |
+
width=800,
|
260 |
+
height=400,
|
261 |
+
background_color = 'white',
|
262 |
+
colormap = 'viridis',
|
263 |
+
max_font_size=150,
|
264 |
+
random_state=42
|
265 |
+
).generate_from_frequencies(keywords_dict)
|
266 |
+
|
267 |
+
try:
|
268 |
+
possible_font_paths=["NanumGothic.ttf", "μ΄λ¦"]
|
269 |
+
|
270 |
+
font_path = None
|
271 |
+
for path in possible_font_paths:
|
272 |
+
if os.path.exists(path):
|
273 |
+
font_path = path
|
274 |
+
break
|
275 |
+
|
276 |
+
if font_path:
|
277 |
+
wc= WordCloud(
|
278 |
+
font_path=font_path,
|
279 |
+
width=800,
|
280 |
+
height=400,
|
281 |
+
background_color = 'white',
|
282 |
+
colormap = 'viridis',
|
283 |
+
max_font_size=150,
|
284 |
+
random_state=42
|
285 |
+
).generate_from_frequencies(keywords_dict)
|
286 |
+
except Exception as e:
|
287 |
+
print(f"μ€λ₯λ°μ {str(e)}")
|
288 |
+
|
289 |
+
return wc
|
290 |
+
|
291 |
+
except Exception as e:
|
292 |
+
st.error(f"μ€λ₯λ°μ {str(e)}")
|
293 |
+
return None
|
294 |
+
|
295 |
+
# λ΄μ€ λΆμ ν¨μ
|
296 |
+
def analyze_news_content(news_df):
|
297 |
+
if news_df.empty:
|
298 |
+
return "λ°μ΄ν°κ° μμ΅λλ€"
|
299 |
+
|
300 |
+
results = {}
|
301 |
+
#μΉ΄ν
κ³ λ¦¬λ³
|
302 |
+
if 'source' in news_df.columns:
|
303 |
+
results['source_counts'] = news_df['source'].value_counts().to_dict()
|
304 |
+
#μΉ΄ν
κ³ λ¦¬λ³
|
305 |
+
if 'date' in news_df.columns:
|
306 |
+
results['date_counts'] = news_df['date'].value_counts().to_dict()
|
307 |
+
|
308 |
+
#ν€μλλΆμ
|
309 |
+
all_text = " ".join(news_df['title'].fillna('') + " " + news_df['content'].fillna(''))
|
310 |
+
|
311 |
+
if len(all_text.strip()) > 0:
|
312 |
+
results['top_keywords_for_wordcloud']= extract_keywords_for_wordcloud(all_text, top_n=50)
|
313 |
+
results['top_keywords'] = analyze_keywords(all_text)
|
314 |
+
else:
|
315 |
+
results['top_keywords_for_wordcloud']={}
|
316 |
+
results['top_keywords'] = []
|
317 |
+
return results
|
318 |
+
|
319 |
+
# OpenAI APIλ₯Ό μ΄μ©ν μ κΈ°μ¬ μμ±
|
320 |
+
def generate_article(original_content, prompt_text):
|
321 |
+
try:
|
322 |
+
response = openai.chat.completions.create(
|
323 |
+
model="gpt-4.1-mini",
|
324 |
+
messages=[
|
325 |
+
{"role": "system", "content": "λΉμ μ μ λ¬Έμ μΈ λ΄μ€ κΈ°μμ
λλ€. μ£Όμ΄μ§ λ΄μ©μ λ°νμΌλ‘ μλ‘μ΄ κΈ°μ¬λ₯Ό μμ±ν΄μ£ΌμΈμ."},
|
326 |
+
{"role": "user", "content": f"λ€μ λ΄μ©μ λ°νμΌλ‘ {prompt_text}\n\n{original_content[:1000]}"}
|
327 |
+
],
|
328 |
+
max_tokens=2000
|
329 |
+
)
|
330 |
+
return response.choices[0].message.content
|
331 |
+
except Exception as e:
|
332 |
+
return f"κΈ°μ¬ μμ± μ€λ₯: {str(e)}"
|
333 |
+
|
334 |
+
# OpenAI APIλ₯Ό μ΄μ©ν μ΄λ―Έμ§ μμ±
|
335 |
+
def generate_image(prompt):
|
336 |
+
try:
|
337 |
+
response = openai.images.generate(
|
338 |
+
model="gpt-image-1",
|
339 |
+
prompt=prompt
|
340 |
+
)
|
341 |
+
image_base64=response.data[0].b64_json
|
342 |
+
return f"data:image/png;base64,{image_base64}"
|
343 |
+
except Exception as e:
|
344 |
+
return f"μ΄λ―Έμ§ μμ± μ€λ₯: {str(e)}"
|
345 |
+
|
346 |
+
# μ€μΌμ€λ¬ κ΄λ ¨ ν¨μλ€
|
347 |
+
def get_next_run_time(hour, minute):
|
348 |
+
now = datetime.now()
|
349 |
+
next_run = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
350 |
+
if next_run <= now:
|
351 |
+
next_run += timedelta(days=1)
|
352 |
+
return next_run
|
353 |
+
|
354 |
+
def run_scheduled_task():
|
355 |
+
try:
|
356 |
+
while global_scheduler_state.is_running:
|
357 |
+
schedule.run_pending()
|
358 |
+
time.sleep(1)
|
359 |
+
except Exception as e:
|
360 |
+
print(f"μ€μΌμ€λ¬ μλ¬ λ°μ: {e}")
|
361 |
+
traceback.print_exc()
|
362 |
+
|
363 |
+
def perform_news_task(task_type, keyword, num_articles, file_prefix):
|
364 |
+
try:
|
365 |
+
articles = crawl_naver_news(keyword, num_articles)
|
366 |
+
|
367 |
+
# κΈ°μ¬ λ΄μ© κ°μ Έμ€κΈ°
|
368 |
+
for article in articles:
|
369 |
+
article['content'] = get_article_content(article['link'])
|
370 |
+
time.sleep(0.5) # μλ² λΆν λ°©μ§
|
371 |
+
|
372 |
+
# κ²°κ³Ό μ μ₯
|
373 |
+
os.makedirs('scheduled_news', exist_ok=True)
|
374 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
375 |
+
filename = f"scheduled_news/{file_prefix}_{task_type}_{timestamp}.json"
|
376 |
+
|
377 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
378 |
+
json.dump(articles, f, ensure_ascii=False, indent=2)
|
379 |
+
|
380 |
+
global_scheduler_state.last_run = datetime.now()
|
381 |
+
print(f"{datetime.now()} - {task_type} λ΄μ€ κΈ°μ¬ μμ§ μλ£: {keyword}")
|
382 |
+
|
383 |
+
# μ μ μνμ μμ§ κ²°κ³Όλ₯Ό μ μ₯ (UI μ
λ°μ΄νΈμ©)
|
384 |
+
result_item = {
|
385 |
+
'task_type': task_type,
|
386 |
+
'keyword': keyword,
|
387 |
+
'timestamp': timestamp,
|
388 |
+
'num_articles': len(articles),
|
389 |
+
'filename': filename
|
390 |
+
}
|
391 |
+
global_scheduler_state.scheduled_results.append(result_item)
|
392 |
+
|
393 |
+
except Exception as e:
|
394 |
+
print(f"μμ
μ€ν μ€ μ€λ₯ λ°μ: {e}")
|
395 |
+
traceback.print_exc()
|
396 |
+
|
397 |
+
def start_scheduler(daily_tasks, interval_tasks):
|
398 |
+
if not global_scheduler_state.is_running:
|
399 |
+
schedule.clear()
|
400 |
+
global_scheduler_state.scheduled_jobs = []
|
401 |
+
|
402 |
+
# μΌλ³ νμ€ν¬ λ±λ‘
|
403 |
+
for task in daily_tasks:
|
404 |
+
hour = task['hour']
|
405 |
+
minute = task['minute']
|
406 |
+
keyword = task['keyword']
|
407 |
+
num_articles = task['num_articles']
|
408 |
+
|
409 |
+
job_id = f"daily_{keyword}_{hour}_{minute}"
|
410 |
+
schedule.every().day.at(f"{hour:02d}:{minute:02d}").do(
|
411 |
+
perform_news_task, "daily", keyword, num_articles, job_id
|
412 |
+
).tag(job_id)
|
413 |
+
|
414 |
+
global_scheduler_state.scheduled_jobs.append({
|
415 |
+
'id': job_id,
|
416 |
+
'type': 'daily',
|
417 |
+
'time': f"{hour:02d}:{minute:02d}",
|
418 |
+
'keyword': keyword,
|
419 |
+
'num_articles': num_articles
|
420 |
+
})
|
421 |
+
|
422 |
+
# μκ° κ°κ²© νμ€ν¬ λ±λ‘
|
423 |
+
for task in interval_tasks:
|
424 |
+
interval_minutes = task['interval_minutes']
|
425 |
+
keyword = task['keyword']
|
426 |
+
num_articles = task['num_articles']
|
427 |
+
run_immediately = task['run_immediately']
|
428 |
+
|
429 |
+
job_id = f"interval_{keyword}_{interval_minutes}"
|
430 |
+
|
431 |
+
if run_immediately:
|
432 |
+
# μ¦μ μ€ν
|
433 |
+
perform_news_task("interval", keyword, num_articles, job_id)
|
434 |
+
|
435 |
+
# λΆ κ°κ²©μΌλ‘ μμ½
|
436 |
+
schedule.every(interval_minutes).minutes.do(
|
437 |
+
perform_news_task, "interval", keyword, num_articles, job_id
|
438 |
+
).tag(job_id)
|
439 |
+
|
440 |
+
global_scheduler_state.scheduled_jobs.append({
|
441 |
+
'id': job_id,
|
442 |
+
'type': 'interval',
|
443 |
+
'interval': f"{interval_minutes}λΆλ§λ€",
|
444 |
+
'keyword': keyword,
|
445 |
+
'num_articles': num_articles,
|
446 |
+
'run_immediately': run_immediately
|
447 |
+
})
|
448 |
+
|
449 |
+
# λ€μ μ€ν μκ° κ³μ°
|
450 |
+
next_run = schedule.next_run()
|
451 |
+
if next_run:
|
452 |
+
global_scheduler_state.next_run = next_run
|
453 |
+
|
454 |
+
# μ€μΌμ€λ¬ μ°λ λ μμ
|
455 |
+
global_scheduler_state.is_running = True
|
456 |
+
global_scheduler_state.thread = threading.Thread(
|
457 |
+
target=run_scheduled_task, daemon=True
|
458 |
+
)
|
459 |
+
global_scheduler_state.thread.start()
|
460 |
+
|
461 |
+
# μνλ₯Ό μΈμ
μνλ‘λ λ³΅μ¬ (UI νμμ©)
|
462 |
+
if 'scheduler_status' not in st.session_state:
|
463 |
+
st.session_state.scheduler_status = {}
|
464 |
+
|
465 |
+
st.session_state.scheduler_status = {
|
466 |
+
'is_running': global_scheduler_state.is_running,
|
467 |
+
'last_run': global_scheduler_state.last_run,
|
468 |
+
'next_run': global_scheduler_state.next_run,
|
469 |
+
'jobs_count': len(global_scheduler_state.scheduled_jobs)
|
470 |
+
}
|
471 |
+
|
472 |
+
def stop_scheduler():
|
473 |
+
if global_scheduler_state.is_running:
|
474 |
+
global_scheduler_state.is_running = False
|
475 |
+
schedule.clear()
|
476 |
+
if global_scheduler_state.thread:
|
477 |
+
global_scheduler_state.thread.join(timeout=1)
|
478 |
+
global_scheduler_state.next_run = None
|
479 |
+
global_scheduler_state.scheduled_jobs = []
|
480 |
+
|
481 |
+
# UI μν μ
λ°μ΄νΈ
|
482 |
+
if 'scheduler_status' in st.session_state:
|
483 |
+
st.session_state.scheduler_status['is_running'] = False
|
484 |
+
|
485 |
+
# λ©λ΄μ λ°λ₯Έ νλ©΄ νμ
|
486 |
+
if menu == "λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§":
|
487 |
+
st.header("λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§")
|
488 |
+
|
489 |
+
keyword = st.text_input("κ²μμ΄ μ
λ ₯", "μΈκ³΅μ§λ₯")
|
490 |
+
num_articles = st.slider("κ°μ Έμ¬ κΈ°μ¬ μ", min_value=1, max_value=20, value=5)
|
491 |
+
|
492 |
+
if st.button("κΈ°μ¬ κ°μ Έμ€κΈ°"):
|
493 |
+
with st.spinner("κΈ°μ¬λ₯Ό μμ§ μ€μ
λλ€..."):
|
494 |
+
articles = crawl_naver_news(keyword, num_articles)
|
495 |
+
|
496 |
+
# κΈ°μ¬ λ΄μ© κ°μ Έμ€κΈ°
|
497 |
+
for i, article in enumerate(articles):
|
498 |
+
st.progress((i + 1) / len(articles))
|
499 |
+
article['content'] = get_article_content(article['link'])
|
500 |
+
time.sleep(0.5) # μλ² λΆν λ°©μ§
|
501 |
+
|
502 |
+
# κ²°κ³Ό μ μ₯ λ° νμ
|
503 |
+
save_articles(articles)
|
504 |
+
st.success(f"{len(articles)}κ°μ κΈ°μ¬λ₯Ό μμ§νμ΅λλ€!")
|
505 |
+
|
506 |
+
# μμ§ν κΈ°μ¬ νμ
|
507 |
+
for article in articles:
|
508 |
+
with st.expander(f"{article['title']} - {article['source']}"):
|
509 |
+
st.write(f"**μΆμ²:** {article['source']}")
|
510 |
+
st.write(f"**λ μ§:** {article['date']}")
|
511 |
+
st.write(f"**μμ½:** {article['description']}")
|
512 |
+
st.write(f"**λ§ν¬:** {article['link']}")
|
513 |
+
st.write("**본문 미리보기:**")
|
514 |
+
st.write(article['content'][:300] + "...")
|
515 |
+
|
516 |
+
elif menu == "κΈ°μ¬ λΆμνκΈ°":
|
517 |
+
st.header("κΈ°μ¬ λΆμνκΈ°")
|
518 |
+
|
519 |
+
articles = load_saved_articles()
|
520 |
+
if not articles:
|
521 |
+
st.warning("μ μ₯λ κΈ°μ¬κ° μμ΅λλ€. λ¨Όμ 'λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§' λ©λ΄μμ κΈ°μ¬λ₯Ό μμ§ν΄μ£ΌμΈμ.")
|
522 |
+
else:
|
523 |
+
# κΈ°μ¬ μ ν
|
524 |
+
titles = [article['title'] for article in articles]
|
525 |
+
selected_title = st.selectbox("λΆμν κΈ°μ¬ μ ν", titles)
|
526 |
+
|
527 |
+
selected_article = next((a for a in articles if a['title'] == selected_title), None)
|
528 |
+
|
529 |
+
if selected_article:
|
530 |
+
st.write(f"**μ λͺ©:** {selected_article['title']}")
|
531 |
+
st.write(f"**μΆμ²:** {selected_article['source']}")
|
532 |
+
|
533 |
+
# λ³Έλ¬Έ νμ
|
534 |
+
with st.expander("κΈ°μ¬ λ³Έλ¬Έ 보기"):
|
535 |
+
st.write(selected_article['content'])
|
536 |
+
|
537 |
+
# λΆμ λ°©λ² μ ν
|
538 |
+
analysis_type = st.radio(
|
539 |
+
"λΆμ λ°©λ²",
|
540 |
+
["ν€μλ λΆμ", "κ°μ λΆμ", "ν
μ€νΈ ν΅κ³"]
|
541 |
+
)
|
542 |
+
|
543 |
+
if analysis_type == "ν€μλ λΆμ":
|
544 |
+
if st.button("ν€μλ λΆμνκΈ°"):
|
545 |
+
with st.spinner("ν€μλλ₯Ό λΆμ μ€μ
λλ€..."):
|
546 |
+
keyword_tab1, keyword_tab2 = st.tabs(["ν€μλ λΉλ", "μλν΄λΌμ°λ"])
|
547 |
+
|
548 |
+
with keyword_tab1:
|
549 |
+
|
550 |
+
keywords = analyze_keywords(selected_article['content'])
|
551 |
+
|
552 |
+
# μκ°ν
|
553 |
+
df = pd.DataFrame(keywords, columns=['λ¨μ΄', 'λΉλμ'])
|
554 |
+
st.bar_chart(df.set_index('λ¨μ΄'))
|
555 |
+
|
556 |
+
st.write("**μ£Όμ ν€μλ:**")
|
557 |
+
for word, count in keywords:
|
558 |
+
st.write(f"- {word}: {count}ν")
|
559 |
+
with keyword_tab2:
|
560 |
+
keyword_dict = extract_keywords_for_wordcloud(selected_article['content'])
|
561 |
+
wc = generate_wordcloud(keyword_dict)
|
562 |
+
|
563 |
+
if wc:
|
564 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
565 |
+
ax.imshow(wc, interpolation='bilinear')
|
566 |
+
ax.axis('off')
|
567 |
+
st.pyplot(fig)
|
568 |
+
|
569 |
+
# ν€μλ μμ 20κ° νμ
|
570 |
+
st.write("**μμ 20κ° ν€μλ:**")
|
571 |
+
top_keywords = sorted(keyword_dict.items(), key=lambda x: x[1], reverse=True)[:20]
|
572 |
+
keyword_df = pd.DataFrame(top_keywords, columns=['ν€μλ', 'λΉλ'])
|
573 |
+
st.dataframe(keyword_df)
|
574 |
+
else:
|
575 |
+
st.error("μλν΄λΌμ°λλ₯Ό μμ±ν μ μμ΅λλ€.")
|
576 |
+
|
577 |
+
elif analysis_type == "ν
μ€νΈ ν΅κ³":
|
578 |
+
if st.button("ν
μ€νΈ ν΅κ³ λΆμ"):
|
579 |
+
content = selected_article['content']
|
580 |
+
|
581 |
+
# ν
μ€νΈ ν΅κ³ κ³μ°
|
582 |
+
word_count = len(re.findall(r'\b\w+\b', content))
|
583 |
+
char_count = len(content)
|
584 |
+
sentence_count = len(re.split(r'[.!?]+', content))
|
585 |
+
avg_word_length = sum(len(word) for word in re.findall(r'\b\w+\b', content)) / word_count if word_count > 0 else 0
|
586 |
+
avg_sentence_length = word_count / sentence_count if sentence_count > 0 else 0
|
587 |
+
|
588 |
+
# ν΅κ³ νμ
|
589 |
+
st.subheader("ν
μ€νΈ ν΅κ³")
|
590 |
+
col1, col2, col3 = st.columns(3)
|
591 |
+
with col1:
|
592 |
+
st.metric("λ¨μ΄ μ", f"{word_count:,}")
|
593 |
+
with col2:
|
594 |
+
st.metric("λ¬Έμ μ", f"{char_count:,}")
|
595 |
+
with col3:
|
596 |
+
st.metric("λ¬Έμ₯ μ", f"{sentence_count:,}")
|
597 |
+
|
598 |
+
col1, col2 = st.columns(2)
|
599 |
+
with col1:
|
600 |
+
st.metric("νκ· λ¨μ΄ κΈΈμ΄", f"{avg_word_length:.1f}μ")
|
601 |
+
with col2:
|
602 |
+
st.metric("νκ· λ¬Έμ₯ κΈΈμ΄", f"{avg_sentence_length:.1f}λ¨μ΄")
|
603 |
+
|
604 |
+
# ν
μ€νΈ 볡μ‘μ± μ μ (κ°λ¨ν μμ)
|
605 |
+
complexity_score = min(10, (avg_sentence_length / 10) * 5 + (avg_word_length / 5) * 5)
|
606 |
+
st.progress(complexity_score / 10)
|
607 |
+
st.write(f"ν
μ€νΈ 볡μ‘μ± μ μ: {complexity_score:.1f}/10")
|
608 |
+
|
609 |
+
# μΆν λΉλ λ§λ κ·Έλν
|
610 |
+
st.subheader("νμ¬λ³ λΆν¬ (νκ΅μ΄/μμ΄ μ§μ)")
|
611 |
+
try:
|
612 |
+
# KoNLPy μ€μΉ νμΈ
|
613 |
+
try:
|
614 |
+
from konlpy.tag import Okt
|
615 |
+
konlpy_installed = True
|
616 |
+
except ImportError:
|
617 |
+
konlpy_installed = False
|
618 |
+
st.warning("νκ΅μ΄ ννμ λΆμμ μν΄ KoNLPyλ₯Ό μ€μΉν΄μ£ΌμΈμ: pip install konlpy")
|
619 |
+
|
620 |
+
# μμ΄ POS tagger μ€λΉ
|
621 |
+
from nltk import pos_tag
|
622 |
+
try:
|
623 |
+
nltk.data.find('taggers/averaged_perceptron_tagger')
|
624 |
+
except LookupError:
|
625 |
+
nltk.download('averaged_perceptron_tagger')
|
626 |
+
|
627 |
+
# Try using the correct resource name as shown in the error message
|
628 |
+
try:
|
629 |
+
nltk.data.find('averaged_perceptron_tagger_eng')
|
630 |
+
except LookupError:
|
631 |
+
nltk.download('averaged_perceptron_tagger_eng')
|
632 |
+
|
633 |
+
# μΈμ΄ κ°μ§ (κ°λ¨ν λ°©μ)
|
634 |
+
is_korean = bool(re.search(r'[κ°-ν£]', content))
|
635 |
+
|
636 |
+
if is_korean and konlpy_installed:
|
637 |
+
# νκ΅μ΄ ννμ λΆμ
|
638 |
+
okt = Okt()
|
639 |
+
tagged = okt.pos(content)
|
640 |
+
|
641 |
+
# νκ΅μ΄ νμ¬ λ§€ν
|
642 |
+
pos_dict = {
|
643 |
+
'Noun': 'λͺ
μ¬', 'NNG': 'λͺ
μ¬', 'NNP': 'κ³ μ λͺ
μ¬',
|
644 |
+
'Verb': 'λμ¬', 'VV': 'λμ¬', 'VA': 'νμ©μ¬',
|
645 |
+
'Adjective': 'νμ©μ¬',
|
646 |
+
'Adverb': 'λΆμ¬',
|
647 |
+
'Josa': 'μ‘°μ¬', 'Punctuation': 'ꡬλμ ',
|
648 |
+
'Determiner': 'κ΄νμ¬', 'Exclamation': 'κ°νμ¬'
|
649 |
+
}
|
650 |
+
|
651 |
+
pos_counts = {'λͺ
μ¬': 0, 'λμ¬': 0, 'νμ©μ¬': 0, 'λΆμ¬': 0, 'μ‘°μ¬': 0, 'ꡬλμ ': 0, 'κ΄νμ¬': 0, 'κ°νμ¬': 0, 'κΈ°ν': 0}
|
652 |
+
|
653 |
+
for _, pos in tagged:
|
654 |
+
if pos in pos_dict:
|
655 |
+
pos_counts[pos_dict[pos]] += 1
|
656 |
+
elif pos.startswith('N'): # κΈ°ν λͺ
μ¬λ₯
|
657 |
+
pos_counts['λͺ
μ¬'] += 1
|
658 |
+
elif pos.startswith('V'): # κΈ°ν λμ¬λ₯
|
659 |
+
pos_counts['λμ¬'] += 1
|
660 |
+
else:
|
661 |
+
pos_counts['κΈ°ν'] += 1
|
662 |
+
|
663 |
+
else:
|
664 |
+
# μμ΄ POS νκΉ
|
665 |
+
tokens = word_tokenize(content.lower())
|
666 |
+
tagged = pos_tag(tokens)
|
667 |
+
|
668 |
+
# μμ΄ νμ¬ λ§€ν
|
669 |
+
pos_dict = {
|
670 |
+
'NN': 'λͺ
μ¬', 'NNS': 'λͺ
μ¬', 'NNP': 'κ³ μ λͺ
μ¬', 'NNPS': 'κ³ μ λͺ
μ¬',
|
671 |
+
'VB': 'λμ¬', 'VBD': 'λμ¬', 'VBG': 'λμ¬', 'VBN': 'λμ¬', 'VBP': 'λμ¬', 'VBZ': 'λμ¬',
|
672 |
+
'JJ': 'νμ©μ¬', 'JJR': 'νμ©μ¬', 'JJS': 'νμ©μ¬',
|
673 |
+
'RB': 'λΆμ¬', 'RBR': 'λΆμ¬', 'RBS': 'λΆμ¬'
|
674 |
+
}
|
675 |
+
|
676 |
+
pos_counts = {'λͺ
μ¬': 0, 'λμ¬': 0, 'νμ©μ¬': 0, 'λΆμ¬': 0, 'κΈ°ν': 0}
|
677 |
+
|
678 |
+
for _, pos in tagged:
|
679 |
+
if pos in pos_dict:
|
680 |
+
pos_counts[pos_dict[pos]] += 1
|
681 |
+
else:
|
682 |
+
pos_counts['κΈ°ν'] += 1
|
683 |
+
|
684 |
+
# κ²°κ³Ό μκ°ν
|
685 |
+
pos_df = pd.DataFrame({
|
686 |
+
'νμ¬': list(pos_counts.keys()),
|
687 |
+
'λΉλ': list(pos_counts.values())
|
688 |
+
})
|
689 |
+
|
690 |
+
st.bar_chart(pos_df.set_index('νμ¬'))
|
691 |
+
|
692 |
+
if is_korean:
|
693 |
+
st.info("νκ΅μ΄ ν
μ€νΈκ° κ°μ§λμμ΅λλ€.")
|
694 |
+
else:
|
695 |
+
st.info("μμ΄ ν
μ€νΈκ° κ°μ§λμμ΅λλ€.")
|
696 |
+
except Exception as e:
|
697 |
+
st.error(f"νμ¬ λΆμ μ€ μ€λ₯ λ°μ: {str(e)}")
|
698 |
+
st.error(traceback.format_exc())
|
699 |
+
|
700 |
+
elif analysis_type == "κ°μ λΆμ":
|
701 |
+
if st.button("κ°μ λΆμνκΈ°"):
|
702 |
+
if st.session_state.openai_api_key:
|
703 |
+
with st.spinner("κΈ°μ¬μ κ°μ μ λΆμ μ€μ
λλ€..."):
|
704 |
+
try:
|
705 |
+
openai.api_key = st.session_state.openai_api_key
|
706 |
+
|
707 |
+
# κ°μ λΆμ ν둬ννΈ μ€μ
|
708 |
+
response = openai.chat.completions.create(
|
709 |
+
model="gpt-4.1-mini",
|
710 |
+
messages=[
|
711 |
+
{"role": "system", "content": "λΉμ μ ν
μ€νΈμ κ°μ κ³Ό λ
Όμ‘°λ₯Ό λΆμνλ μ λ¬Έκ°μ
λλ€. λ€μ λ΄μ€ κΈ°μ¬μ κ°μ κ³Ό λ
Όμ‘°λ₯Ό λΆμνκ³ , 'κΈμ μ ', 'λΆμ μ ', 'μ€λ¦½μ ' μ€ νλλ‘ λΆλ₯ν΄ μ£ΌμΈμ. λν κΈ°μ¬μμ λλ¬λλ ν΅μ¬ κ°μ ν€μλλ₯Ό 5κ° μΆμΆνκ³ , κ° ν€μλλ³λ‘ 1-10 μ¬μ΄μ κ°λ μ μλ₯Ό 맀겨주μΈμ. JSON νμμΌλ‘ λ€μκ³Ό κ°μ΄ μλ΅ν΄μ£ΌμΈμ: {'sentiment': 'κΈμ μ /λΆμ μ /μ€λ¦½μ ', 'reason': 'μ΄μ μ€λͺ
...', 'keywords': [{'word': 'ν€μλ1', 'score': 8}, {'word': 'ν€μλ2', 'score': 7}, ...]}"},
|
712 |
+
{"role": "user", "content": f"λ€μ λ΄μ€ κΈ°μ¬λ₯Ό λΆμν΄ μ£ΌμΈμ:\n\nμ λͺ©: {selected_article['title']}\n\nλ΄μ©: {selected_article['content'][:1500]}"}
|
713 |
+
],
|
714 |
+
max_tokens=800,
|
715 |
+
response_format={"type": "json_object"}
|
716 |
+
)
|
717 |
+
|
718 |
+
# JSON νμ±
|
719 |
+
analysis_result = json.loads(response.choices[0].message.content)
|
720 |
+
|
721 |
+
# κ²°κ³Ό μκ°ν
|
722 |
+
st.subheader("κ°μ λΆμ κ²°κ³Ό")
|
723 |
+
|
724 |
+
# 1. κ°μ νμ
μ λ°λ₯Έ μκ°μ νν
|
725 |
+
sentiment_type = analysis_result.get('sentiment', 'μ€λ¦½μ ')
|
726 |
+
col1, col2, col3 = st.columns([1, 3, 1])
|
727 |
+
|
728 |
+
with col2:
|
729 |
+
if sentiment_type == "κΈμ μ ":
|
730 |
+
st.markdown(f"""
|
731 |
+
<div style="background-color:#DCEDC8; padding:20px; border-radius:10px; text-align:center;">
|
732 |
+
<h1 style="color:#388E3C; font-size:28px;">π κΈμ μ λ
Όμ‘° π</h1>
|
733 |
+
<p style="font-size:16px;">κ°μ κ°λ: λμ</p>
|
734 |
+
</div>
|
735 |
+
""", unsafe_allow_html=True)
|
736 |
+
elif sentiment_type == "λΆμ μ ":
|
737 |
+
st.markdown(f"""
|
738 |
+
<div style="background-color:#FFCDD2; padding:20px; border-radius:10px; text-align:center;">
|
739 |
+
<h1 style="color:#D32F2F; font-size:28px;">π λΆμ μ λ
Όμ‘° π</h1>
|
740 |
+
<p style="font-size:16px;">κ°μ κ°λ: λμ</p>
|
741 |
+
</div>
|
742 |
+
""", unsafe_allow_html=True)
|
743 |
+
else:
|
744 |
+
st.markdown(f"""
|
745 |
+
<div style="background-color:#E0E0E0; padding:20px; border-radius:10px; text-align:center;">
|
746 |
+
<h1 style="color:#616161; font-size:28px;">π μ€λ¦½μ λ
Όμ‘° π</h1>
|
747 |
+
<p style="font-size:16px;">κ°μ κ°λ: μ€κ°</p>
|
748 |
+
</div>
|
749 |
+
""", unsafe_allow_html=True)
|
750 |
+
|
751 |
+
# 2. μ΄μ μ€λͺ
|
752 |
+
st.markdown("### λΆμ κ·Όκ±°")
|
753 |
+
st.markdown(f"<div style='background-color:#F5F5F5; padding:15px; border-radius:5px;'>{analysis_result.get('reason', '')}</div>", unsafe_allow_html=True)
|
754 |
+
|
755 |
+
# 3. κ°μ ν€μλ μκ°ν
|
756 |
+
st.markdown("### ν΅μ¬ κ°μ ν€μλ")
|
757 |
+
|
758 |
+
# ν€μλ λ°μ΄ν° μ€λΉ
|
759 |
+
keywords = analysis_result.get('keywords', [])
|
760 |
+
if keywords:
|
761 |
+
# λ§λ μ°¨νΈμ© λ°μ΄ν°
|
762 |
+
keyword_names = [item.get('word', '') for item in keywords]
|
763 |
+
keyword_scores = [item.get('score', 0) for item in keywords]
|
764 |
+
|
765 |
+
# λ μ΄λ μ°¨νΈ μμ±
|
766 |
+
fig = go.Figure()
|
767 |
+
|
768 |
+
# μμ μ€μ
|
769 |
+
if sentiment_type == "κΈμ μ ":
|
770 |
+
fill_color = 'rgba(76, 175, 80, 0.3)' # μ°ν μ΄λ‘μ
|
771 |
+
line_color = 'rgba(76, 175, 80, 1)' # μ§ν μ΄λ‘μ
|
772 |
+
elif sentiment_type == "λΆμ μ ":
|
773 |
+
fill_color = 'rgba(244, 67, 54, 0.3)' # μ°ν λΉ¨κ°μ
|
774 |
+
line_color = 'rgba(244, 67, 54, 1)' # μ§ν λΉ¨κ°μ
|
775 |
+
else:
|
776 |
+
fill_color = 'rgba(158, 158, 158, 0.3)' # μ°ν νμ
|
777 |
+
line_color = 'rgba(158, 158, 158, 1)' # μ§ν νμ
|
778 |
+
|
779 |
+
# λ μ΄λ μ°¨νΈ λ°μ΄ν° μ€λΉ - λ§μ§λ§ μ μ΄ μ²« μ κ³Ό μ°κ²°λλλ‘ λ°μ΄ν° μΆκ°
|
780 |
+
radar_keywords = keyword_names.copy()
|
781 |
+
radar_scores = keyword_scores.copy()
|
782 |
+
|
783 |
+
# λ μ΄λ μ°¨νΈ μμ±
|
784 |
+
fig.add_trace(go.Scatterpolar(
|
785 |
+
r=radar_scores,
|
786 |
+
theta=radar_keywords,
|
787 |
+
fill='toself',
|
788 |
+
fillcolor=fill_color,
|
789 |
+
line=dict(color=line_color, width=2),
|
790 |
+
name='κ°μ ν€μλ'
|
791 |
+
))
|
792 |
+
|
793 |
+
# λ μ΄λ μ°¨νΈ λ μ΄μμ μ€μ
|
794 |
+
fig.update_layout(
|
795 |
+
polar=dict(
|
796 |
+
radialaxis=dict(
|
797 |
+
visible=True,
|
798 |
+
range=[0, 10],
|
799 |
+
tickmode='linear',
|
800 |
+
tick0=0,
|
801 |
+
dtick=2
|
802 |
+
)
|
803 |
+
),
|
804 |
+
showlegend=False,
|
805 |
+
title={
|
806 |
+
'text': 'κ°μ ν€μλ λ μ΄λ λΆμ',
|
807 |
+
'y':0.95,
|
808 |
+
'x':0.5,
|
809 |
+
'xanchor': 'center',
|
810 |
+
'yanchor': 'top'
|
811 |
+
},
|
812 |
+
height=500,
|
813 |
+
width=500,
|
814 |
+
margin=dict(l=80, r=80, t=80, b=80)
|
815 |
+
)
|
816 |
+
|
817 |
+
# μ°¨νΈ μ€μμ νμ
|
818 |
+
col1, col2, col3 = st.columns([1, 2, 1])
|
819 |
+
with col2:
|
820 |
+
st.plotly_chart(fig)
|
821 |
+
|
822 |
+
# ν€μλ μΉ΄λλ‘ νμ
|
823 |
+
st.markdown("#### ν€μλ μΈλΆ μ€λͺ
")
|
824 |
+
cols = st.columns(min(len(keywords), 5))
|
825 |
+
for i, keyword in enumerate(keywords):
|
826 |
+
with cols[i % len(cols)]:
|
827 |
+
word = keyword.get('word', '')
|
828 |
+
score = keyword.get('score', 0)
|
829 |
+
|
830 |
+
# μ μμ λ°λ₯Έ μμ κ³μ°
|
831 |
+
r, g, b = 0, 0, 0
|
832 |
+
if sentiment_type == "κΈμ μ ":
|
833 |
+
g = min(200 + score * 5, 255)
|
834 |
+
r = max(255 - score * 20, 100)
|
835 |
+
elif sentiment_type == "λΆμ μ ":
|
836 |
+
r = min(200 + score * 5, 255)
|
837 |
+
g = max(255 - score * 20, 100)
|
838 |
+
else:
|
839 |
+
r = g = b = 128
|
840 |
+
|
841 |
+
# μΉ΄λ μμ±
|
842 |
+
st.markdown(f"""
|
843 |
+
<div style="background-color:rgba({r},{g},{b},0.2); padding:10px; border-radius:5px; text-align:center; margin:5px;">
|
844 |
+
<h3 style="margin:0;">{word}</h3>
|
845 |
+
<div style="background-color:#E0E0E0; border-radius:3px; margin-top:5px;">
|
846 |
+
<div style="width:{score*10}%; background-color:rgba({r},{g},{b},0.8); height:10px; border-radius:3px;"></div>
|
847 |
+
</div>
|
848 |
+
<p style="margin:2px; font-size:12px;">κ°λ: {score}/10</p>
|
849 |
+
</div>
|
850 |
+
""", unsafe_allow_html=True)
|
851 |
+
|
852 |
+
else:
|
853 |
+
st.info("ν€μλλ₯Ό μΆμΆνμ§ λͺ»νμ΅λλ€.")
|
854 |
+
|
855 |
+
# 4. μμ½ ν΅κ³
|
856 |
+
st.markdown("### μ£Όμ ν΅κ³")
|
857 |
+
col1, col2, col3 = st.columns(3)
|
858 |
+
with col1:
|
859 |
+
st.metric(label="κΈμ /λΆμ μ μ", value=f"{7 if sentiment_type == 'κΈμ μ ' else 3 if sentiment_type == 'λΆμ μ ' else 5}/10")
|
860 |
+
with col2:
|
861 |
+
st.metric(label="ν€μλ μ", value=len(keywords))
|
862 |
+
with col3:
|
863 |
+
avg_score = sum(keyword_scores) / len(keyword_scores) if keyword_scores else 0
|
864 |
+
st.metric(label="νκ· κ°λ", value=f"{avg_score:.1f}/10")
|
865 |
+
|
866 |
+
except Exception as e:
|
867 |
+
st.error(f"κ°μ λΆμ μ€λ₯: {str(e)}")
|
868 |
+
st.code(traceback.format_exc())
|
869 |
+
else:
|
870 |
+
st.warning("OpenAI API ν€κ° μ€μ λμ΄ μμ§ μμ΅λλ€. μ¬μ΄λλ°μμ API ν€λ₯Ό μ€μ ν΄μ£ΌμΈμ.")
|
871 |
+
|
872 |
+
elif menu == "μ κΈ°μ¬ μμ±νκΈ°":
|
873 |
+
st.header("μ κΈ°μ¬ μμ±νκΈ°")
|
874 |
+
|
875 |
+
articles = load_saved_articles()
|
876 |
+
if not articles:
|
877 |
+
st.warning("μ μ₯λ κΈ°μ¬κ° μμ΅λλ€. λ¨Όμ 'λ΄μ€ κΈ°μ¬ ν¬λ‘€λ§' λ©λ΄μμ κΈ°μ¬λ₯Ό μμ§ν΄μ£ΌμΈμ.")
|
878 |
+
else:
|
879 |
+
# κΈ°μ¬ μ ν
|
880 |
+
titles = [article['title'] for article in articles]
|
881 |
+
selected_title = st.selectbox("μλ³Έ κΈ°μ¬ μ ν", titles)
|
882 |
+
|
883 |
+
selected_article = next((a for a in articles if a['title'] == selected_title), None)
|
884 |
+
|
885 |
+
if selected_article:
|
886 |
+
st.write(f"**μλ³Έ μ λͺ©:** {selected_article['title']}")
|
887 |
+
|
888 |
+
with st.expander("μλ³Έ κΈ°μ¬ λ΄μ©"):
|
889 |
+
st.write(selected_article['content'])
|
890 |
+
|
891 |
+
prompt_text ="""λ€μ κΈ°μ¬ μμμ λ°λΌμ λ€μ μμ±ν΄μ€.
|
892 |
+
μν : λΉμ μ μ λ¬Έμ¬μ κΈ°μμ
λλ€.
|
893 |
+
μμ
: μ΅κ·Ό μΌμ΄λ μ¬κ±΄μ λν 보λμλ£λ₯Ό μμ±ν΄μΌ ν©λλ€. μλ£λ μ¬μ€μ κΈ°λ°μΌλ‘ νλ©°, κ°κ΄μ μ΄κ³ μ νν΄μΌ ν©λλ€.
|
894 |
+
μ§μΉ¨:
|
895 |
+
μ 곡λ μ 보λ₯Ό λ°νμΌλ‘ μ λ¬Έ 보λμλ£ νμμ λ§μΆ° κΈ°μ¬λ₯Ό μμ±νμΈμ.
|
896 |
+
κΈ°μ¬ μ λͺ©μ μ£Όμ λ₯Ό λͺ
νν λ°μνκ³ λ
μμ κ΄μ¬μ λ μ μλλ‘ μμ±ν©λλ€.
|
897 |
+
κΈ°μ¬ λ΄μ©μ μ ννκ³ κ°κ²°νλ©° μ€λλ ₯ μλ λ¬Έμ₯μΌλ‘ ꡬμ±ν©λλ€.
|
898 |
+
κ΄λ ¨μμ μΈν°λ·°λ₯Ό μΈμ© ννλ‘ λ£μ΄μ£ΌμΈμ.
|
899 |
+
μμ μ 보μ μ§μΉ¨μ μ°Έκ³ νμ¬ μ λ¬Έ 보λμλ£ νμμ κΈ°μ¬λ₯Ό μμ±ν΄ μ£ΌμΈμ"""
|
900 |
+
|
901 |
+
# μ΄λ―Έμ§ μμ± μ¬λΆ μ ν μ΅μ
μΆκ°
|
902 |
+
generate_image_too = st.checkbox("κΈ°μ¬ μμ± ν μ΄λ―Έμ§λ ν¨κ» μμ±νκΈ°", value=True)
|
903 |
+
|
904 |
+
if st.button("μ κΈ°μ¬ μμ±νκΈ°"):
|
905 |
+
if st.session_state.openai_api_key:
|
906 |
+
openai.api_key = st.session_state.openai_api_key
|
907 |
+
with st.spinner("κΈ°μ¬λ₯Ό μμ± μ€μ
λλ€..."):
|
908 |
+
new_article = generate_article(selected_article['content'], prompt_text)
|
909 |
+
|
910 |
+
st.write("**μμ±λ κΈ°μ¬:**")
|
911 |
+
st.write(new_article)
|
912 |
+
|
913 |
+
# μ΄λ―Έμ§ μμ±νκΈ° (μ΅μ
μ΄ μ νλ κ²½μ°)
|
914 |
+
if generate_image_too:
|
915 |
+
with st.spinner("κΈ°μ¬ κ΄λ ¨ μ΄λ―Έμ§λ₯Ό μμ± μ€μ
λλ€..."):
|
916 |
+
# μ΄λ―Έμ§ μμ± ν둬ννΈ μ€λΉ
|
917 |
+
image_prompt = f"""μ λ¬ΈκΈ°μ¬ μ λͺ© "{selected_article['title']}" μ λ³΄κ³ μ΄λ―Έμ§λ₯Ό λ§λ€μ΄μ€
|
918 |
+
μ΄λ―Έμ§μλ λ€μ μμκ° ν¬ν¨λμ΄μΌ ν©λλ€:
|
919 |
+
- κΈ°μ¬λ₯Ό μ΄ν΄ν μ μλ λμ
|
920 |
+
- κΈ°μ¬ λ΄μ©κ³Ό κ΄λ ¨λ ν
μ€νΈ
|
921 |
+
- μ¬ννκ² μ²λ¦¬
|
922 |
+
"""
|
923 |
+
|
924 |
+
# μ΄λ―Έμ§ μμ±
|
925 |
+
image_url = generate_image(image_prompt)
|
926 |
+
|
927 |
+
if image_url and not image_url.startswith("μ΄οΏ½οΏ½μ§ μμ± μ€λ₯"):
|
928 |
+
st.subheader("μμ±λ μ΄λ―Έμ§:")
|
929 |
+
st.image(image_url)
|
930 |
+
else:
|
931 |
+
st.error(image_url)
|
932 |
+
|
933 |
+
# μμ±λ κΈ°μ¬ μ μ₯ μ΅μ
|
934 |
+
if st.button("μμ±λ κΈ°μ¬ μ μ₯"):
|
935 |
+
new_article_data = {
|
936 |
+
'title': f"[μμ±λ¨] {selected_article['title']}",
|
937 |
+
'source': f"AI μμ± (μλ³Έ: {selected_article['source']})",
|
938 |
+
'date': datetime.now().strftime("%Y-%m-%d %H:%M"),
|
939 |
+
'description': new_article[:100] + "...",
|
940 |
+
'link': "",
|
941 |
+
'content': new_article
|
942 |
+
}
|
943 |
+
articles.append(new_article_data)
|
944 |
+
save_articles(articles)
|
945 |
+
st.success("μμ±λ κΈ°μ¬κ° μ μ₯λμμ΅λλ€!")
|
946 |
+
else:
|
947 |
+
st.warning("OpenAI API ν€λ₯Ό μ¬μ΄λλ°μμ μ€μ ν΄μ£ΌμΈμ.")
|
948 |
+
|
949 |
+
|
950 |
+
|
951 |
+
elif menu == "λ΄μ€ κΈ°μ¬ μμ½νκΈ°":
|
952 |
+
st.header("λ΄μ€ κΈ°μ¬ μμ½νκΈ°")
|
953 |
+
|
954 |
+
# ν μμ±
|
955 |
+
tab1, tab2, tab3 = st.tabs(["μΌλ³ μμ½", "μκ° κ°κ²© μμ½", "μ€μΌμ€λ¬ μν"])
|
956 |
+
|
957 |
+
# μΌλ³ μμ½ ν
|
958 |
+
with tab1:
|
959 |
+
st.subheader("λ§€μΌ μ ν΄μ§ μκ°μ κΈ°μ¬ μμ§νκΈ°")
|
960 |
+
|
961 |
+
# ν€μλ μ
λ ₯
|
962 |
+
daily_keyword = st.text_input("κ²μ ν€μλ", value="μΈκ³΅μ§λ₯", key="daily_keyword")
|
963 |
+
daily_num_articles = st.slider("μμ§ν κΈ°μ¬ μ", min_value=1, max_value=20, value=5, key="daily_num_articles")
|
964 |
+
|
965 |
+
# μκ° μ€μ
|
966 |
+
daily_col1, daily_col2 = st.columns(2)
|
967 |
+
with daily_col1:
|
968 |
+
daily_hour = st.selectbox("μ", range(24), format_func=lambda x: f"{x:02d}μ", key="daily_hour")
|
969 |
+
with daily_col2:
|
970 |
+
daily_minute = st.selectbox("λΆ", range(0, 60, 5), format_func=lambda x: f"{x:02d}λΆ", key="daily_minute")
|
971 |
+
|
972 |
+
# μΌλ³ μμ½ λ¦¬μ€νΈ
|
973 |
+
if 'daily_tasks' not in st.session_state:
|
974 |
+
st.session_state.daily_tasks = []
|
975 |
+
|
976 |
+
if st.button("μΌλ³ μμ½ μΆκ°"):
|
977 |
+
st.session_state.daily_tasks.append({
|
978 |
+
'hour': daily_hour,
|
979 |
+
'minute': daily_minute,
|
980 |
+
'keyword': daily_keyword,
|
981 |
+
'num_articles': daily_num_articles
|
982 |
+
})
|
983 |
+
st.success(f"μΌλ³ μμ½μ΄ μΆκ°λμμ΅λλ€: λ§€μΌ {daily_hour:02d}:{daily_minute:02d} - '{daily_keyword}'")
|
984 |
+
|
985 |
+
# μμ½ λͺ©λ‘ νμ
|
986 |
+
if st.session_state.daily_tasks:
|
987 |
+
st.subheader("μΌλ³ μμ½ λͺ©λ‘")
|
988 |
+
for i, task in enumerate(st.session_state.daily_tasks):
|
989 |
+
st.write(f"{i+1}. λ§€μΌ {task['hour']:02d}:{task['minute']:02d} - '{task['keyword']}' ({task['num_articles']}κ°)")
|
990 |
+
|
991 |
+
if st.button("μΌλ³ μμ½ μ΄κΈ°ν"):
|
992 |
+
st.session_state.daily_tasks = []
|
993 |
+
st.warning("μΌλ³ μμ½μ΄ λͺ¨λ μ΄κΈ°νλμμ΅λλ€.")
|
994 |
+
|
995 |
+
# μκ° κ°κ²© μμ½ ν
|
996 |
+
with tab2:
|
997 |
+
st.subheader("μκ° κ°κ²©μΌλ‘ κΈ°μ¬ μμ§νκΈ°")
|
998 |
+
|
999 |
+
# ν€μλ μ
λ ₯
|
1000 |
+
interval_keyword = st.text_input("κ²μ ν€μλ", value="λΉ
λ°μ΄ν°", key="interval_keyword")
|
1001 |
+
interval_num_articles = st.slider("μμ§ν κΈ°μ¬ μ", min_value=1, max_value=20, value=5, key="interval_num_articles")
|
1002 |
+
|
1003 |
+
# μκ° κ°κ²© μ€μ
|
1004 |
+
interval_minutes = st.number_input("μ€ν κ°κ²©(λΆ)", min_value=1, max_value=60*24, value=30, key="interval_minutes")
|
1005 |
+
|
1006 |
+
# μ¦μ μ€ν μ¬λΆ
|
1007 |
+
run_immediately = st.checkbox("μ¦μ μ€ν", value=True, help="체ν¬νλ©΄ μ€μΌμ€λ¬ μμ μ μ¦μ μ€νν©λλ€.")
|
1008 |
+
|
1009 |
+
# μκ° κ°κ²© μμ½ λ¦¬μ€νΈ
|
1010 |
+
if 'interval_tasks' not in st.session_state:
|
1011 |
+
st.session_state.interval_tasks = []
|
1012 |
+
|
1013 |
+
if st.button("μκ° κ°κ²© μμ½ μΆκ°"):
|
1014 |
+
st.session_state.interval_tasks.append({
|
1015 |
+
'interval_minutes': interval_minutes,
|
1016 |
+
'keyword': interval_keyword,
|
1017 |
+
'num_articles': interval_num_articles,
|
1018 |
+
'run_immediately': run_immediately
|
1019 |
+
})
|
1020 |
+
st.success(f"μκ° κ°κ²© μμ½μ΄ μΆκ°λμμ΅λλ€: {interval_minutes}λΆλ§λ€ - '{interval_keyword}'")
|
1021 |
+
|
1022 |
+
# μμ½ λͺ©λ‘ νμ
|
1023 |
+
if st.session_state.interval_tasks:
|
1024 |
+
st.subheader("μκ° κ°κ²© μμ½ λͺ©λ‘")
|
1025 |
+
for i, task in enumerate(st.session_state.interval_tasks):
|
1026 |
+
immediate_text = "μ¦μ μ€ν ν " if task['run_immediately'] else ""
|
1027 |
+
st.write(f"{i+1}. {immediate_text}{task['interval_minutes']}λΆλ§λ€ - '{task['keyword']}' ({task['num_articles']}κ°)")
|
1028 |
+
|
1029 |
+
if st.button("μκ° κ°κ²© μμ½ μ΄κΈ°ν"):
|
1030 |
+
st.session_state.interval_tasks = []
|
1031 |
+
st.warning("μκ° κ°κ²© μμ½μ΄ λͺ¨λ μ΄κΈ°νλμμ΅λλ€.")
|
1032 |
+
|
1033 |
+
# μ€μΌμ€λ¬ μν ν
|
1034 |
+
with tab3:
|
1035 |
+
st.subheader("μ€μΌμ€λ¬ μ μ΄ λ° μν")
|
1036 |
+
|
1037 |
+
col1, col2 = st.columns(2)
|
1038 |
+
|
1039 |
+
with col1:
|
1040 |
+
# μ€μΌμ€λ¬ μμ/μ€μ§ λ²νΌ
|
1041 |
+
if not global_scheduler_state.is_running:
|
1042 |
+
if st.button("μ€μΌμ€λ¬ μμ"):
|
1043 |
+
if not st.session_state.daily_tasks and not st.session_state.interval_tasks:
|
1044 |
+
st.error("μμ½λ μμ
μ΄ μμ΅λλ€. λ¨Όμ μΌλ³ μμ½ λλ μκ° κ°κ²© μμ½μ μΆκ°ν΄μ£ΌμΈμ.")
|
1045 |
+
else:
|
1046 |
+
start_scheduler(st.session_state.daily_tasks, st.session_state.interval_tasks)
|
1047 |
+
st.success("μ€μΌμ€λ¬κ° μμλμμ΅λλ€.")
|
1048 |
+
else:
|
1049 |
+
if st.button("μ€μΌμ€λ¬ μ€μ§"):
|
1050 |
+
stop_scheduler()
|
1051 |
+
st.warning("μ€μΌμ€λ¬κ° μ€μ§λμμ΅λλ€.")
|
1052 |
+
|
1053 |
+
with col2:
|
1054 |
+
# μ€μΌμ€λ¬ μν νμ
|
1055 |
+
if 'scheduler_status' in st.session_state:
|
1056 |
+
st.write(f"μν: {'μ€νμ€' if global_scheduler_state.is_running else 'μ€μ§'}")
|
1057 |
+
if global_scheduler_state.last_run:
|
1058 |
+
st.write(f"λ§μ§λ§ μ€ν: {global_scheduler_state.last_run.strftime('%Y-%m-%d %H:%M:%S')}")
|
1059 |
+
if global_scheduler_state.next_run and global_scheduler_state.is_running:
|
1060 |
+
st.write(f"λ€μ μ€ν: {global_scheduler_state.next_run.strftime('%Y-%m-%d %H:%M:%S')}")
|
1061 |
+
else:
|
1062 |
+
st.write("μν: μ€μ§")
|
1063 |
+
|
1064 |
+
# μμ½λ μμ
λͺ©λ‘
|
1065 |
+
if global_scheduler_state.scheduled_jobs:
|
1066 |
+
st.subheader("νμ¬ μ€ν μ€μΈ μμ½ μμ
")
|
1067 |
+
for i, job in enumerate(global_scheduler_state.scheduled_jobs):
|
1068 |
+
if job['type'] == 'daily':
|
1069 |
+
st.write(f"{i+1}. [μΌλ³] λ§€μΌ {job['time']} - '{job['keyword']}' ({job['num_articles']}κ°)")
|
1070 |
+
else:
|
1071 |
+
immediate_text = "[μ¦μ μ€ν ν] " if job.get('run_immediately', False) else ""
|
1072 |
+
st.write(f"{i+1}. [κ°κ²©] {immediate_text}{job['interval']} - '{job['keyword']}' ({job['num_articles']}κ°)")
|
1073 |
+
|
1074 |
+
# μ€μΌμ€λ¬ μ€ν κ²°κ³Ό
|
1075 |
+
if global_scheduler_state.scheduled_results:
|
1076 |
+
st.subheader("μ€μΌμ€λ¬ μ€ν κ²°κ³Ό")
|
1077 |
+
|
1078 |
+
# κ²°κ³Όλ₯Ό UIμ νμνκΈ° μ μ 볡μ¬
|
1079 |
+
results_for_display = global_scheduler_state.scheduled_results.copy()
|
1080 |
+
|
1081 |
+
if results_for_display:
|
1082 |
+
result_df = pd.DataFrame(results_for_display)
|
1083 |
+
result_df['μ€νμκ°'] = result_df['timestamp'].apply(lambda x: datetime.strptime(x, "%Y%m%d_%H%M%S").strftime("%Y-%m-%d %H:%M:%S"))
|
1084 |
+
result_df = result_df.rename(columns={
|
1085 |
+
'task_type': 'μμ
μ ν',
|
1086 |
+
'keyword': 'ν€μλ',
|
1087 |
+
'num_articles': 'κΈ°μ¬μ',
|
1088 |
+
'filename': 'νμΌλͺ
'
|
1089 |
+
})
|
1090 |
+
result_df['μμ
μ ν'] = result_df['μμ
μ ν'].apply(lambda x: 'μΌλ³' if x == 'daily' else 'μκ°κ°κ²©')
|
1091 |
+
|
1092 |
+
st.dataframe(
|
1093 |
+
result_df[['μμ
μ ν', 'ν€μλ', 'κΈ°μ¬μ', 'μ€νμκ°', 'νμΌλͺ
']],
|
1094 |
+
hide_index=True
|
1095 |
+
)
|
1096 |
+
|
1097 |
+
# μμ§λ νμΌ λ³΄κΈ°
|
1098 |
+
if os.path.exists('scheduled_news'):
|
1099 |
+
files = [f for f in os.listdir('scheduled_news') if f.endswith('.json')]
|
1100 |
+
if files:
|
1101 |
+
st.subheader("μμ§λ νμΌ μ΄κΈ°")
|
1102 |
+
selected_file = st.selectbox("νμΌ μ ν", files, index=len(files)-1)
|
1103 |
+
if selected_file and st.button("νμΌ λ΄μ© 보기"):
|
1104 |
+
with open(os.path.join('scheduled_news', selected_file), 'r', encoding='utf-8') as f:
|
1105 |
+
articles = json.load(f)
|
1106 |
+
|
1107 |
+
st.write(f"**νμΌλͺ
:** {selected_file}")
|
1108 |
+
st.write(f"**μμ§ κΈ°μ¬ μ:** {len(articles)}κ°")
|
1109 |
+
|
1110 |
+
for article in articles:
|
1111 |
+
with st.expander(f"{article['title']} - {article['source']}"):
|
1112 |
+
st.write(f"**μΆμ²:** {article['source']}")
|
1113 |
+
st.write(f"**λ μ§:** {article['date']}")
|
1114 |
+
st.write(f"**λ§ν¬:** {article['link']}")
|
1115 |
+
st.write("**λ³Έλ¬Έ:**")
|
1116 |
+
st.write(article['content'][:500] + "..." if len(article['content']) > 500 else article['content'])
|
1117 |
|
1118 |
+
# νΈν°
|
1119 |
+
st.markdown("---")
|
1120 |
+
st.markdown("Β© λ΄μ€ κΈ°μ¬ λꡬ @conanssam")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|