Update app.py
Browse files
app.py
CHANGED
|
@@ -2,17 +2,28 @@ 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# OpenAI API ํค ์ค์
|
| 13 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 14 |
|
| 15 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def fetch_naver_news(query, display=5):
|
| 17 |
client_id = "I_8koTJh3R5l4wLurQbG" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client ID
|
| 18 |
client_secret = "W5oWYlAgur" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client Secret
|
|
@@ -26,166 +37,93 @@ def fetch_naver_news(query, display=5):
|
|
| 26 |
"query": query,
|
| 27 |
"display": display,
|
| 28 |
"start": 1,
|
| 29 |
-
"sort": "date",
|
| 30 |
}
|
| 31 |
|
| 32 |
response = requests.get(url, headers=headers, params=params)
|
| 33 |
if response.status_code == 200:
|
| 34 |
-
|
| 35 |
-
return news_data['items']
|
| 36 |
else:
|
| 37 |
st.error("๋ด์ค ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ๋ฐ ์คํจํ์ต๋๋ค.")
|
| 38 |
return []
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
def
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
vectorizer = TfidfVectorizer(max_features=1000)
|
| 52 |
-
|
| 53 |
-
y =
|
| 54 |
-
|
| 55 |
-
|
| 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(
|
| 78 |
-
joblib.dump(vectorizer,
|
| 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":
|
| 90 |
-
return "๋ณด์"
|
| 91 |
-
else:
|
| 92 |
-
return "์ค๋ฆฝ"
|
| 93 |
|
| 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 |
-
|
| 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 |
-
ax.bar(labels, sizes, color=color_palette)
|
| 154 |
-
ax.set_xlabel('์ฑํฅ', fontsize=14)
|
| 155 |
-
ax.set_ylabel('๊ฑด์', fontsize=14)
|
| 156 |
-
ax.set_title('๋ด์ค ์ฑํฅ ๋ถํฌ', fontsize=16)
|
| 157 |
-
st.pyplot(fig)
|
| 158 |
-
|
| 159 |
-
# Streamlit ์ ํ๋ฆฌ์ผ์ด์
|
| 160 |
-
st.title("๐ฐ ์ ์น์ ๊ด์ ๋น๊ต ๋ถ์ ๋๊ตฌ")
|
| 161 |
-
st.markdown("๋ด์ค ๊ธฐ์ฌ์ ์ ์น ์ฑํฅ ๋ถ์๊ณผ ๋ฐ๋ ๊ด์ ๊ธฐ์ฌ๋ฅผ ์์ฑํ์ฌ ๋น๊ตํฉ๋๋ค.")
|
| 162 |
-
|
| 163 |
-
# ๋จธ์ ๋ฌ๋ ๋ชจ๋ธ ๋ก๋
|
| 164 |
-
if not os.path.exists('political_bias_model.pkl'):
|
| 165 |
-
model, vectorizer = train_ml_model()
|
| 166 |
-
else:
|
| 167 |
-
model = joblib.load('political_bias_model.pkl')
|
| 168 |
-
vectorizer = joblib.load('tfidf_vectorizer.pkl')
|
| 169 |
-
|
| 170 |
-
# ์ฌ์ฉ์๋ก๋ถํฐ ๊ฒ์์ด ์
๋ ฅ ๋ฐ๊ธฐ
|
| 171 |
-
query = st.text_input("๊ฒ์ ํค์๋๋ฅผ ์
๋ ฅํ์ธ์", value="์ ์น")
|
| 172 |
-
|
| 173 |
-
# ๋ถ์ ์์ ๋ฒํผ
|
| 174 |
-
if st.button("๐ ๋ถ์ ์์"):
|
| 175 |
-
with st.spinner("๋ถ์ ์ค..."):
|
| 176 |
-
analysis_results, sentiment_counts = analyze_news_political_viewpoint(query, model, vectorizer)
|
| 177 |
-
|
| 178 |
-
if analysis_results:
|
| 179 |
-
st.success("๋ด์ค ๋ถ์์ด ์๋ฃ๋์์ต๋๋ค.")
|
| 180 |
-
|
| 181 |
-
for result in analysis_results:
|
| 182 |
-
st.subheader(result["์ ๋ชฉ"])
|
| 183 |
-
st.write(f"์ฑํฅ: {result['์ฑํฅ']}")
|
| 184 |
-
st.write(f"๊ธฐ์ฌ: {result['์๋ณธ ๊ธฐ์ฌ']}")
|
| 185 |
-
st.write(f"[์๋ณธ ๊ธฐ์ฌ ๋ณด๊ธฐ]({result['๋ด์ค ๋งํฌ']})")
|
| 186 |
-
st.write(f"๋์กฐ ๊ด์ ๊ธฐ์ฌ: {result['๋์กฐ ๊ด์ ๊ธฐ์ฌ']}")
|
| 187 |
-
st.markdown("---")
|
| 188 |
-
|
| 189 |
-
visualize_sentiment_distribution(sentiment_counts)
|
| 190 |
-
else:
|
| 191 |
-
st.warning("๊ฒ์๋ ๋ด์ค๊ฐ ์์ต๋๋ค.")
|
|
|
|
| 2 |
import requests
|
| 3 |
import openai
|
| 4 |
import os
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 7 |
from sklearn.linear_model import LogisticRegression
|
| 8 |
from sklearn.model_selection import train_test_split, cross_val_score
|
| 9 |
+
from sklearn.metrics import classification_report, accuracy_score
|
| 10 |
import joblib
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import seaborn as sns
|
| 13 |
+
|
| 14 |
+
# Streamlit ํ์ด์ง ์ค์
|
| 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.cache_data
|
| 22 |
+
def load_huggingface_data():
|
| 23 |
+
dataset = load_dataset("jacobvs/PoliticalTweets")
|
| 24 |
+
return dataset
|
| 25 |
+
|
| 26 |
+
# ๋ค์ด๋ฒ ๋ด์ค API๋ฅผ ํตํด ๋ด์ค ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
|
| 27 |
def fetch_naver_news(query, display=5):
|
| 28 |
client_id = "I_8koTJh3R5l4wLurQbG" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client ID
|
| 29 |
client_secret = "W5oWYlAgur" # ๋ค์ด๋ฒ ๊ฐ๋ฐ์ ์ผํฐ์์ ๋ฐ๊ธ๋ฐ์ Client Secret
|
|
|
|
| 37 |
"query": query,
|
| 38 |
"display": display,
|
| 39 |
"start": 1,
|
| 40 |
+
"sort": "date",
|
| 41 |
}
|
| 42 |
|
| 43 |
response = requests.get(url, headers=headers, params=params)
|
| 44 |
if response.status_code == 200:
|
| 45 |
+
return response.json()['items']
|
|
|
|
| 46 |
else:
|
| 47 |
st.error("๋ด์ค ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ค๋ ๋ฐ ์คํจํ์ต๋๋ค.")
|
| 48 |
return []
|
| 49 |
|
| 50 |
+
# ํ๊น
ํ์ด์ค ๋ฐ์ดํฐ์ ๋ค์ด๋ฒ ๋ด์ค ๋ฐ์ดํฐ๋ฅผ ๊ฒฐํฉ
|
| 51 |
+
def combine_datasets(huggingface_data, naver_data):
|
| 52 |
+
additional_texts = [item['title'] + ". " + item['description'] for item in naver_data]
|
| 53 |
+
additional_labels = ["NEUTRAL"] * len(additional_texts) # ๊ธฐ๋ณธ์ ์ผ๋ก ์ค๋ฆฝ์ผ๋ก ๋ผ๋ฒจ๋ง
|
| 54 |
+
hf_texts = huggingface_data['train']['text']
|
| 55 |
+
hf_labels = huggingface_data['train']['party']
|
| 56 |
+
return hf_texts + additional_texts, hf_labels + additional_labels
|
| 57 |
+
|
| 58 |
+
# ๋จธ์ ๋ฌ๋ ๋ชจ๋ธ ํ์ต
|
| 59 |
+
@st.cache_data
|
| 60 |
+
def train_model(X, y):
|
| 61 |
+
vectorizer = TfidfVectorizer(max_features=1000, stop_words="english")
|
| 62 |
+
X_tfidf = vectorizer.fit_transform(X)
|
| 63 |
+
X_train, X_test, y_train, y_test = train_test_split(X_tfidf, y, test_size=0.2, random_state=42)
|
| 64 |
+
model = LogisticRegression(max_iter=1000)
|
| 65 |
+
model.fit(X_train, y_train)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# ๋ชจ๋ธ ์ ์ฅ
|
| 68 |
+
joblib.dump(model, "political_tweets_model.pkl")
|
| 69 |
+
joblib.dump(vectorizer, "tfidf_vectorizer.pkl")
|
| 70 |
+
return model, vectorizer, X_test, y_test
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
# GPT-4๋ฅผ ์ด์ฉํด ๋ฐ๋ ๊ด์ ๊ธฐ์ฌ ์์ฑ
|
| 73 |
def generate_article_gpt4(prompt):
|
| 74 |
try:
|
| 75 |
response = openai.ChatCompletion.create(
|
| 76 |
+
model="gpt-4",
|
| 77 |
+
messages=[
|
| 78 |
{"role": "system", "content": "You are a helpful assistant that generates articles."},
|
| 79 |
+
{"role": "user", "content": prompt}
|
| 80 |
],
|
| 81 |
+
max_tokens=1024,
|
| 82 |
+
temperature=0.7
|
| 83 |
)
|
| 84 |
return response['choices'][0]['message']['content']
|
| 85 |
except Exception as e:
|
| 86 |
return f"Error generating text: {e}"
|
| 87 |
|
| 88 |
+
# Streamlit ์ ํ๋ฆฌ์ผ์ด์
์์
|
| 89 |
+
st.title("๐ฐ ์ ์น์ ์ฑํฅ ๋ถ์ ๋ฐ ๋ด์ค ๋น๊ต ๋๊ตฌ")
|
| 90 |
+
st.markdown("ํ๊น
ํ์ด์ค์ `PoliticalTweets` ๋ฐ์ดํฐ์
๊ณผ ๋ค์ด๋ฒ ๋ด์ค API๋ฅผ ํ์ฉํ์ฌ ํ
์คํธ ์ฑํฅ์ ๋ถ์ํฉ๋๋ค.")
|
| 91 |
+
|
| 92 |
+
# ๋ฐ์ดํฐ ๋ก๋
|
| 93 |
+
huggingface_data = load_huggingface_data()
|
| 94 |
+
query = st.text_input("๋ค์ด๋ฒ ๋ด์ค์์ ๊ฒ์ํ ํค์๋๋ฅผ ์
๋ ฅํ์ธ์", value="์ ์น")
|
| 95 |
+
naver_data = fetch_naver_news(query)
|
| 96 |
+
|
| 97 |
+
if st.button("๋ฐ์ดํฐ ๊ฒฐํฉ ๋ฐ ํ์ต"):
|
| 98 |
+
texts, labels = combine_datasets(huggingface_data, naver_data)
|
| 99 |
+
label_mapping = {"Democrat": 0, "Republican": 1, "NEUTRAL": 2}
|
| 100 |
+
y = [label_mapping[label] for label in labels]
|
| 101 |
+
model, vectorizer, X_test, y_test = train_model(texts, y)
|
| 102 |
+
|
| 103 |
+
# ์ฑ๋ฅ ํ๊ฐ
|
| 104 |
+
y_pred = model.predict(X_test)
|
| 105 |
+
accuracy = accuracy_score(y_test, y_pred)
|
| 106 |
+
st.write(f"๋ชจ๋ธ ์ ํ๋: {accuracy:.2f}")
|
| 107 |
+
st.text("๋ถ๋ฅ ๋ฆฌํฌํธ:")
|
| 108 |
+
st.text(classification_report(y_test, y_pred, target_names=list(label_mapping.keys())))
|
| 109 |
+
|
| 110 |
+
# ์ฌ์ฉ์ ์
๋ ฅ ๋ฐ ์์ธก
|
| 111 |
+
st.subheader("ํธ์ ๋๋ ๋ด์ค ์ฑํฅ ์์ธก")
|
| 112 |
+
user_input = st.text_area("๋ถ์ํ ํ
์คํธ๋ฅผ ์
๋ ฅํ์ธ์", placeholder="์: The government should invest more in public health.")
|
| 113 |
+
|
| 114 |
+
if st.button("์ฑํฅ ๋ถ์"):
|
| 115 |
+
vectorizer = joblib.load("tfidf_vectorizer.pkl")
|
| 116 |
+
model = joblib.load("political_tweets_model.pkl")
|
| 117 |
+
user_tfidf = vectorizer.transform([user_input])
|
| 118 |
+
prediction = model.predict(user_tfidf)[0]
|
| 119 |
+
prediction_label = list(label_mapping.keys())[prediction]
|
| 120 |
+
st.write(f"์์ธก๋ ์ฑํฅ: {prediction_label}")
|
| 121 |
+
|
| 122 |
+
# ๋ด์ค ๋ฐ์ดํฐ ์๊ฐํ
|
| 123 |
+
if naver_data:
|
| 124 |
+
st.subheader("๋ค์ด๋ฒ ๋ด์ค ๋ฐ์ดํฐ")
|
| 125 |
+
for item in naver_data:
|
| 126 |
+
st.write(f"์ ๋ชฉ: {item['title']}")
|
| 127 |
+
st.write(f"๋ด์ฉ: {item['description']}")
|
| 128 |
+
st.write(f"[๊ธฐ์ฌ ๋งํฌ]({item['link']})")
|
| 129 |
+
st.markdown("---")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|