Update app.py
Browse files
app.py
CHANGED
|
@@ -1,40 +1,18 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import requests
|
| 3 |
-
import matplotlib.pyplot as plt
|
| 4 |
-
import seaborn as sns
|
| 5 |
-
from transformers import pipeline
|
| 6 |
import openai
|
| 7 |
import os
|
| 8 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 9 |
from sklearn.linear_model import LogisticRegression
|
| 10 |
-
from sklearn.model_selection import train_test_split
|
| 11 |
from sklearn.metrics import accuracy_score
|
| 12 |
import joblib
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
st.set_page_config(page_title="์ ์น์ ๊ด์ ๋ถ์", page_icon="๐ฐ", layout="wide")
|
| 16 |
-
|
| 17 |
-
# OpenAI API ํค ์ค์ (ํ๊ฒฝ๋ณ์์์ ๊ฐ์ ธ์ค๋ ๋ฐฉ๋ฒ)
|
| 18 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
st.markdown(
|
| 22 |
-
"""
|
| 23 |
-
<style>
|
| 24 |
-
body {
|
| 25 |
-
font-family: 'Nanum Gothic', sans-serif;
|
| 26 |
-
}
|
| 27 |
-
</style>
|
| 28 |
-
""",
|
| 29 |
-
unsafe_allow_html=True
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
# matplotlib ํ๊ธ ํฐํธ ์ค์
|
| 33 |
-
import matplotlib
|
| 34 |
-
matplotlib.rcParams['font.family'] = 'NanumGothic' # ํ๊ธ ํฐํธ๋ฅผ ์ค์ ํฉ๋๋ค.
|
| 35 |
-
matplotlib.rcParams['axes.unicode_minus'] = False # ๋ง์ด๋์ค ๊ธฐํธ ๊นจ์ง ๋ฐฉ์ง
|
| 36 |
-
|
| 37 |
-
# ๋ค์ด๋ฒ ๋ด์ค API๋ฅผ ํตํด ์ค์ ๋ด์ค ๊ธฐ์ฌ ๊ฐ์ ธ์ค๊ธฐ
|
| 38 |
def fetch_naver_news(query, display=5):
|
| 39 |
client_id = "I_8koTJh3R5l4wLurQbG" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client ID
|
| 40 |
client_secret = "W5oWYlAgur" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client Secret
|
|
@@ -54,15 +32,14 @@ def fetch_naver_news(query, display=5):
|
|
| 54 |
response = requests.get(url, headers=headers, params=params)
|
| 55 |
if response.status_code == 200:
|
| 56 |
news_data = response.json()
|
| 57 |
-
return news_data['items']
|
| 58 |
else:
|
| 59 |
st.error("๋ด์ค ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ๋ฐ ์คํจํ์ต๋๋ค.")
|
| 60 |
return []
|
| 61 |
|
| 62 |
-
# ๋จธ์ ๋ฌ๋ ๋ชจ๋ธ
|
| 63 |
def train_ml_model():
|
| 64 |
-
#
|
| 65 |
-
# ์ค์ ๋ฐ์ดํฐ๋ฅผ ์ด์ฉํ ํ์ต ๊ณผ์ ์ด ํ์ํฉ๋๋ค.
|
| 66 |
data = [
|
| 67 |
("์ง๋ณด์ ์ธ ์ ๋ถ ์ ์ฑ
์ ๊ฐํํด์ผ ํ๋ค", "LEFT"),
|
| 68 |
("๋ณด์์ ์ธ ๊ฒฝ์ ์ ์ฑ
์ด ํ์ํ๋ค", "RIGHT"),
|
|
@@ -79,26 +56,34 @@ def train_ml_model():
|
|
| 79 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 80 |
|
| 81 |
# ๋ก์ง์คํฑ ํ๊ท ๋ชจ๋ธ ํ์ต
|
| 82 |
-
model = LogisticRegression()
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
# ๋ชจ๋ธ ์ฑ๋ฅ ํ๊ฐ
|
| 86 |
-
y_pred =
|
| 87 |
accuracy = accuracy_score(y_test, y_pred)
|
| 88 |
st.write(f"๋ชจ๋ธ ์ ํ๋: {accuracy:.2f}")
|
| 89 |
|
| 90 |
# ๋ชจ๋ธ ์ ์ฅ
|
| 91 |
-
joblib.dump(
|
| 92 |
joblib.dump(vectorizer, 'tfidf_vectorizer.pkl')
|
| 93 |
|
| 94 |
-
return
|
| 95 |
|
| 96 |
# ๋ก๋๋ ๋จธ์ ๋ฌ๋ ๋ชจ๋ธ๋ก ์ฑํฅ ๋ถ์
|
| 97 |
def analyze_article_sentiment_ml(text, model, vectorizer):
|
| 98 |
X = vectorizer.transform([text])
|
| 99 |
prediction = model.predict(X)[0]
|
| 100 |
|
| 101 |
-
# ์ฑํฅ์ ๋ฐ๋ฅธ ๋ ์ด๋ธ ๋ฐํ
|
| 102 |
if prediction == "LEFT":
|
| 103 |
return "์ง๋ณด"
|
| 104 |
elif prediction == "RIGHT":
|
|
@@ -109,41 +94,37 @@ def analyze_article_sentiment_ml(text, model, vectorizer):
|
|
| 109 |
# GPT-4๋ฅผ ์ด์ฉํด ๋ฐ๋ ๊ด์ ๊ธฐ์ฌ ์์ฑ
|
| 110 |
def generate_article_gpt4(prompt):
|
| 111 |
try:
|
| 112 |
-
# GPT-4 ๋ชจ๋ธ์ ์ด์ฉํด ๋ฐ๋ ๊ด์ ๊ธฐ์ฌ๋ฅผ ์์ฑ
|
| 113 |
response = openai.ChatCompletion.create(
|
| 114 |
-
model="gpt-4",
|
| 115 |
messages=[
|
| 116 |
{"role": "system", "content": "You are a helpful assistant that generates articles."},
|
| 117 |
-
{"role": "user", "content": prompt}
|
| 118 |
],
|
| 119 |
-
max_tokens=1024,
|
| 120 |
-
temperature=0.7
|
| 121 |
)
|
| 122 |
-
return response['choices'][0]['message']['content']
|
| 123 |
except Exception as e:
|
| 124 |
return f"Error generating text: {e}"
|
| 125 |
|
| 126 |
# ์ ์น์ ๊ด์ ๋น๊ต ๋ฐ ๋ฐ๋ ๊ด์ ์์ฑ
|
| 127 |
def analyze_news_political_viewpoint(query, model, vectorizer):
|
| 128 |
-
# ๋ด์ค ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
|
| 129 |
news_items = fetch_naver_news(query)
|
| 130 |
if not news_items:
|
| 131 |
return [], {}
|
| 132 |
|
| 133 |
results = []
|
| 134 |
-
sentiment_counts = {"์ง๋ณด": 0, "๋ณด์": 0, "์ค๋ฆฝ": 0}
|
| 135 |
|
| 136 |
for item in news_items:
|
| 137 |
title = item["title"]
|
| 138 |
description = item["description"]
|
| 139 |
-
link = item["link"]
|
| 140 |
combined_text = f"{title}. {description}"
|
| 141 |
|
| 142 |
-
# ๋จธ์ ๋ฌ๋ ๋ชจ๋ธ์ ์ด์ฉํ ์ฑํฅ ๋ถ์
|
| 143 |
sentiment = analyze_article_sentiment_ml(combined_text, model, vectorizer)
|
| 144 |
-
sentiment_counts[sentiment] += 1
|
| 145 |
|
| 146 |
-
# ๋ฐ๋ ๊ด์ ๊ธฐ์ฌ ์์ฑ
|
| 147 |
opposite_perspective = "๋ณด์์ " if sentiment == "์ง๋ณด" else "์ง๋ณด์ "
|
| 148 |
prompt = f"{combined_text}๋ฅผ ๊ธฐ๋ฐ์ผ๋ก {opposite_perspective} ๊ด์ ์ ๊ธฐ์ฌ๋ฅผ ์์ฑํด์ฃผ์ธ์."
|
| 149 |
opposite_article = generate_article_gpt4(prompt)
|
|
@@ -153,18 +134,20 @@ def analyze_news_political_viewpoint(query, model, vectorizer):
|
|
| 153 |
"์๋ณธ ๊ธฐ์ฌ": description,
|
| 154 |
"์ฑํฅ": sentiment,
|
| 155 |
"๋์กฐ ๊ด์ ๊ธฐ์ฌ": opposite_article,
|
| 156 |
-
"๋ด์ค ๋งํฌ": link
|
| 157 |
})
|
| 158 |
|
| 159 |
return results, sentiment_counts
|
| 160 |
|
| 161 |
-
# ์ฑํฅ ๋ถํฌ ์๊ฐํ
|
| 162 |
def visualize_sentiment_distribution(sentiment_counts):
|
|
|
|
|
|
|
|
|
|
| 163 |
fig, ax = plt.subplots(figsize=(8, 5))
|
| 164 |
labels = list(sentiment_counts.keys())
|
| 165 |
sizes = list(sentiment_counts.values())
|
| 166 |
|
| 167 |
-
# ์์ ์ค์ (๋ถ๋๋ฌ์ด ํ๋ ํธ)
|
| 168 |
color_palette = sns.color_palette("pastel")[0:len(sizes)]
|
| 169 |
|
| 170 |
ax.bar(labels, sizes, color=color_palette)
|
|
@@ -195,7 +178,6 @@ if st.button("๐ ๋ถ์ ์์"):
|
|
| 195 |
if analysis_results:
|
| 196 |
st.success("๋ด์ค ๋ถ์์ด ์๋ฃ๋์์ต๋๋ค.")
|
| 197 |
|
| 198 |
-
# ๋ด์ค ๊ธฐ์ฌ ๋ชฉ๋ก ํ์
|
| 199 |
for result in analysis_results:
|
| 200 |
st.subheader(result["์ ๋ชฉ"])
|
| 201 |
st.write(f"์ฑํฅ: {result['์ฑํฅ']}")
|
|
@@ -204,7 +186,6 @@ if st.button("๐ ๋ถ์ ์์"):
|
|
| 204 |
st.write(f"๋์กฐ ๊ด์ ๊ธฐ์ฌ: {result['๋์กฐ ๊ด์ ๊ธฐ์ฌ']}")
|
| 205 |
st.markdown("---")
|
| 206 |
|
| 207 |
-
# ์ฑํฅ ๋ถํฌ ์๊ฐํ
|
| 208 |
visualize_sentiment_distribution(sentiment_counts)
|
| 209 |
else:
|
| 210 |
st.warning("๊ฒ์๋ ๋ด์ค๊ฐ ์์ต๋๋ค.")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import requests
|
|
|
|
|
|
|
|
|
|
| 3 |
import openai
|
| 4 |
import os
|
| 5 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 6 |
from sklearn.linear_model import LogisticRegression
|
| 7 |
+
from sklearn.model_selection import train_test_split, cross_val_score
|
| 8 |
from sklearn.metrics import accuracy_score
|
| 9 |
import joblib
|
| 10 |
+
from sklearn.model_selection import GridSearchCV
|
| 11 |
|
| 12 |
+
# OpenAI API ํค ์ค์
|
|
|
|
|
|
|
|
|
|
| 13 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 14 |
|
| 15 |
+
# ๋ค์ด๋ฒ ๋ด์ค API๋ฅผ ํตํด ๋ด์ค ๊ธฐ์ฌ ๊ฐ์ ธ์ค๊ธฐ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def fetch_naver_news(query, display=5):
|
| 17 |
client_id = "I_8koTJh3R5l4wLurQbG" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client ID
|
| 18 |
client_secret = "W5oWYlAgur" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client Secret
|
|
|
|
| 32 |
response = requests.get(url, headers=headers, params=params)
|
| 33 |
if response.status_code == 200:
|
| 34 |
news_data = response.json()
|
| 35 |
+
return news_data['items']
|
| 36 |
else:
|
| 37 |
st.error("๋ด์ค ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ๋ฐ ์คํจํ์ต๋๋ค.")
|
| 38 |
return []
|
| 39 |
|
| 40 |
+
# ๋จธ์ ๋ฌ๋ ๋ชจ๋ธ ํ์ต ๋ฐ ๊ฐ์
|
| 41 |
def train_ml_model():
|
| 42 |
+
# ์์ ๋ฐ์ดํฐ
|
|
|
|
| 43 |
data = [
|
| 44 |
("์ง๋ณด์ ์ธ ์ ๋ถ ์ ์ฑ
์ ๊ฐํํด์ผ ํ๋ค", "LEFT"),
|
| 45 |
("๋ณด์์ ์ธ ๊ฒฝ์ ์ ์ฑ
์ด ํ์ํ๋ค", "RIGHT"),
|
|
|
|
| 56 |
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 57 |
|
| 58 |
# ๋ก์ง์คํฑ ํ๊ท ๋ชจ๋ธ ํ์ต
|
| 59 |
+
model = LogisticRegression(max_iter=1000, solver='liblinear') # ๋ ๋ง์ ๋ฐ๋ณต ํ์์ 'liblinear' solver ์ฌ์ฉ
|
| 60 |
+
|
| 61 |
+
# ํ์ดํผํ๋ผ๋ฏธํฐ ํ๋ (์ ๊ทํ ๊ฐ๋ C)
|
| 62 |
+
param_grid = {'C': [0.1, 1, 10, 100]}
|
| 63 |
+
grid_search = GridSearchCV(model, param_grid, cv=5)
|
| 64 |
+
grid_search.fit(X_train, y_train)
|
| 65 |
+
best_model = grid_search.best_estimator_
|
| 66 |
+
|
| 67 |
+
# ๊ต์ฐจ ๊ฒ์ฆ์ ํตํ ํ๊ฐ
|
| 68 |
+
cv_scores = cross_val_score(best_model, X, y, cv=5)
|
| 69 |
+
st.write(f"๊ต์ฐจ ๊ฒ์ฆ ํ๊ท ์ ํ๋: {cv_scores.mean():.2f}")
|
| 70 |
|
| 71 |
# ๋ชจ๋ธ ์ฑ๋ฅ ํ๊ฐ
|
| 72 |
+
y_pred = best_model.predict(X_test)
|
| 73 |
accuracy = accuracy_score(y_test, y_pred)
|
| 74 |
st.write(f"๋ชจ๋ธ ์ ํ๋: {accuracy:.2f}")
|
| 75 |
|
| 76 |
# ๋ชจ๋ธ ์ ์ฅ
|
| 77 |
+
joblib.dump(best_model, 'political_bias_model.pkl')
|
| 78 |
joblib.dump(vectorizer, 'tfidf_vectorizer.pkl')
|
| 79 |
|
| 80 |
+
return best_model, vectorizer
|
| 81 |
|
| 82 |
# ๋ก๋๋ ๋จธ์ ๋ฌ๋ ๋ชจ๋ธ๋ก ์ฑํฅ ๋ถ์
|
| 83 |
def analyze_article_sentiment_ml(text, model, vectorizer):
|
| 84 |
X = vectorizer.transform([text])
|
| 85 |
prediction = model.predict(X)[0]
|
| 86 |
|
|
|
|
| 87 |
if prediction == "LEFT":
|
| 88 |
return "์ง๋ณด"
|
| 89 |
elif prediction == "RIGHT":
|
|
|
|
| 94 |
# GPT-4๋ฅผ ์ด์ฉํด ๋ฐ๋ ๊ด์ ๊ธฐ์ฌ ์์ฑ
|
| 95 |
def generate_article_gpt4(prompt):
|
| 96 |
try:
|
|
|
|
| 97 |
response = openai.ChatCompletion.create(
|
| 98 |
+
model="gpt-4",
|
| 99 |
messages=[
|
| 100 |
{"role": "system", "content": "You are a helpful assistant that generates articles."},
|
| 101 |
+
{"role": "user", "content": prompt}
|
| 102 |
],
|
| 103 |
+
max_tokens=1024,
|
| 104 |
+
temperature=0.7
|
| 105 |
)
|
| 106 |
+
return response['choices'][0]['message']['content']
|
| 107 |
except Exception as e:
|
| 108 |
return f"Error generating text: {e}"
|
| 109 |
|
| 110 |
# ์ ์น์ ๊ด์ ๋น๊ต ๋ฐ ๋ฐ๋ ๊ด์ ์์ฑ
|
| 111 |
def analyze_news_political_viewpoint(query, model, vectorizer):
|
|
|
|
| 112 |
news_items = fetch_naver_news(query)
|
| 113 |
if not news_items:
|
| 114 |
return [], {}
|
| 115 |
|
| 116 |
results = []
|
| 117 |
+
sentiment_counts = {"์ง๋ณด": 0, "๋ณด์": 0, "์ค๋ฆฝ": 0}
|
| 118 |
|
| 119 |
for item in news_items:
|
| 120 |
title = item["title"]
|
| 121 |
description = item["description"]
|
| 122 |
+
link = item["link"]
|
| 123 |
combined_text = f"{title}. {description}"
|
| 124 |
|
|
|
|
| 125 |
sentiment = analyze_article_sentiment_ml(combined_text, model, vectorizer)
|
| 126 |
+
sentiment_counts[sentiment] += 1
|
| 127 |
|
|
|
|
| 128 |
opposite_perspective = "๋ณด์์ " if sentiment == "์ง๋ณด" else "์ง๋ณด์ "
|
| 129 |
prompt = f"{combined_text}๋ฅผ ๊ธฐ๋ฐ์ผ๋ก {opposite_perspective} ๊ด์ ์ ๊ธฐ์ฌ๋ฅผ ์์ฑํด์ฃผ์ธ์."
|
| 130 |
opposite_article = generate_article_gpt4(prompt)
|
|
|
|
| 134 |
"์๋ณธ ๊ธฐ์ฌ": description,
|
| 135 |
"์ฑํฅ": sentiment,
|
| 136 |
"๋์กฐ ๊ด์ ๊ธฐ์ฌ": opposite_article,
|
| 137 |
+
"๋ด์ค ๋งํฌ": link
|
| 138 |
})
|
| 139 |
|
| 140 |
return results, sentiment_counts
|
| 141 |
|
| 142 |
+
# ์ฑํฅ ๋ถํฌ ์๊ฐํ
|
| 143 |
def visualize_sentiment_distribution(sentiment_counts):
|
| 144 |
+
import matplotlib.pyplot as plt
|
| 145 |
+
import seaborn as sns
|
| 146 |
+
|
| 147 |
fig, ax = plt.subplots(figsize=(8, 5))
|
| 148 |
labels = list(sentiment_counts.keys())
|
| 149 |
sizes = list(sentiment_counts.values())
|
| 150 |
|
|
|
|
| 151 |
color_palette = sns.color_palette("pastel")[0:len(sizes)]
|
| 152 |
|
| 153 |
ax.bar(labels, sizes, color=color_palette)
|
|
|
|
| 178 |
if analysis_results:
|
| 179 |
st.success("๋ด์ค ๋ถ์์ด ์๋ฃ๋์์ต๋๋ค.")
|
| 180 |
|
|
|
|
| 181 |
for result in analysis_results:
|
| 182 |
st.subheader(result["์ ๋ชฉ"])
|
| 183 |
st.write(f"์ฑํฅ: {result['์ฑํฅ']}")
|
|
|
|
| 186 |
st.write(f"๋์กฐ ๊ด์ ๊ธฐ์ฌ: {result['๋์กฐ ๊ด์ ๊ธฐ์ฌ']}")
|
| 187 |
st.markdown("---")
|
| 188 |
|
|
|
|
| 189 |
visualize_sentiment_distribution(sentiment_counts)
|
| 190 |
else:
|
| 191 |
st.warning("๊ฒ์๋ ๋ด์ค๊ฐ ์์ต๋๋ค.")
|