Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,30 +3,30 @@ import joblib
|
|
| 3 |
import pandas as pd
|
| 4 |
import re
|
| 5 |
import nltk
|
|
|
|
| 6 |
import os
|
| 7 |
import random
|
| 8 |
import google.generativeai as genai
|
| 9 |
-
from nltk.corpus import stopwords
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
st.set_page_config(page_title="
|
| 16 |
|
| 17 |
-
#
|
| 18 |
nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
|
| 19 |
os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
|
| 20 |
nltk.data.path.append(nltk_data_path)
|
| 21 |
-
|
| 22 |
try:
|
| 23 |
if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
|
| 24 |
nltk.download('stopwords', download_dir=nltk_data_path)
|
| 25 |
except Exception as e:
|
| 26 |
-
st.error(f"
|
| 27 |
st.stop()
|
| 28 |
|
| 29 |
-
#
|
| 30 |
def clean_text(series: pd.Series) -> pd.Series:
|
| 31 |
return (
|
| 32 |
series
|
|
@@ -37,13 +37,14 @@ def clean_text(series: pd.Series) -> pd.Series:
|
|
| 37 |
.str.strip()
|
| 38 |
)
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
def explain_with_gemini(title
|
| 42 |
try:
|
| 43 |
model = genai.GenerativeModel("gemini-pro")
|
| 44 |
-
chat = model.start_chat()
|
| 45 |
-
prompt = f"""
|
| 46 |
-
|
|
|
|
| 47 |
|
| 48 |
Title: {title}
|
| 49 |
Content: {content}
|
|
@@ -51,57 +52,46 @@ Content: {content}
|
|
| 51 |
response = chat.send_message(prompt)
|
| 52 |
return response.text
|
| 53 |
except Exception as e:
|
| 54 |
-
return f"
|
| 55 |
|
| 56 |
-
#
|
| 57 |
model = None
|
| 58 |
try:
|
| 59 |
model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
|
| 60 |
model = joblib.load(model_path)
|
| 61 |
-
st.success("
|
| 62 |
except Exception as e:
|
| 63 |
-
st.error(f"
|
| 64 |
st.stop()
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
st.title("📰
|
| 68 |
-
st.
|
|
|
|
| 69 |
|
| 70 |
-
|
| 71 |
-
content_input = st.text_area("🧾 Nội dung tin tức:", height=250)
|
| 72 |
-
|
| 73 |
-
if st.button("🔍 Phân tích"):
|
| 74 |
if not title_input and not content_input:
|
| 75 |
-
st.warning("
|
| 76 |
else:
|
| 77 |
-
with st.spinner("
|
| 78 |
-
input_df = pd.DataFrame({
|
| 79 |
-
'Feature_1': [title_input],
|
| 80 |
-
'Feature_2': [content_input]
|
| 81 |
-
})
|
| 82 |
-
|
| 83 |
try:
|
| 84 |
prediction = model.predict(input_df)[0]
|
| 85 |
prediction_proba = model.predict_proba(input_df)[0]
|
| 86 |
confidence = round(max(prediction_proba) * 100, 2)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
st.markdown("---")
|
| 92 |
-
st.subheader("📌 Kết quả:")
|
| 93 |
st.markdown(f"<h3 style='color:{color};'>{label}</h3>", unsafe_allow_html=True)
|
| 94 |
-
st.info(f"
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
st.subheader("🧠 Phân tích chi tiết:")
|
| 101 |
-
st.markdown(explanation)
|
| 102 |
|
| 103 |
except Exception as e:
|
| 104 |
-
st.error(f"
|
| 105 |
|
| 106 |
st.markdown("---")
|
| 107 |
-
st.
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import re
|
| 5 |
import nltk
|
| 6 |
+
from nltk.corpus import stopwords
|
| 7 |
import os
|
| 8 |
import random
|
| 9 |
import google.generativeai as genai
|
|
|
|
| 10 |
|
| 11 |
+
# Cấu hình Generative AI
|
| 12 |
+
GENAI_API_KEY = "AIzaSyDmXGLBoweYkqyXMDtWwSWOKZCo6Exd4Dk"
|
| 13 |
+
genai.configure(api_key=GENAI_API_KEY)
|
| 14 |
|
| 15 |
+
# Cấu hình Streamlit
|
| 16 |
+
st.set_page_config(page_title="Fake News Detector", layout="centered")
|
| 17 |
|
| 18 |
+
# Tải dữ liệu NLTK
|
| 19 |
nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
|
| 20 |
os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
|
| 21 |
nltk.data.path.append(nltk_data_path)
|
|
|
|
| 22 |
try:
|
| 23 |
if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
|
| 24 |
nltk.download('stopwords', download_dir=nltk_data_path)
|
| 25 |
except Exception as e:
|
| 26 |
+
st.error(f"NLTK error: {e}")
|
| 27 |
st.stop()
|
| 28 |
|
| 29 |
+
# Hàm xử lý văn bản
|
| 30 |
def clean_text(series: pd.Series) -> pd.Series:
|
| 31 |
return (
|
| 32 |
series
|
|
|
|
| 37 |
.str.strip()
|
| 38 |
)
|
| 39 |
|
| 40 |
+
# Hàm phân tích với Gemini
|
| 41 |
+
def explain_with_gemini(title, content, label):
|
| 42 |
try:
|
| 43 |
model = genai.GenerativeModel("gemini-pro")
|
| 44 |
+
chat = model.start_chat(history=[])
|
| 45 |
+
prompt = f"""
|
| 46 |
+
You are a news analysis expert.
|
| 47 |
+
Explain in detail why the following news article is classified as \"{label}\".
|
| 48 |
|
| 49 |
Title: {title}
|
| 50 |
Content: {content}
|
|
|
|
| 52 |
response = chat.send_message(prompt)
|
| 53 |
return response.text
|
| 54 |
except Exception as e:
|
| 55 |
+
return f"Could not generate explanation: {e}"
|
| 56 |
|
| 57 |
+
# Tải mô hình
|
| 58 |
model = None
|
| 59 |
try:
|
| 60 |
model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
|
| 61 |
model = joblib.load(model_path)
|
| 62 |
+
st.success("Model loaded successfully.")
|
| 63 |
except Exception as e:
|
| 64 |
+
st.error(f"Model loading error: {e}")
|
| 65 |
st.stop()
|
| 66 |
|
| 67 |
+
# Giao diện người dùng
|
| 68 |
+
st.title("📰 Fake News Detector")
|
| 69 |
+
title_input = st.text_input("News Title")
|
| 70 |
+
content_input = st.text_area("News Content", height=250)
|
| 71 |
|
| 72 |
+
if st.button("Analyze"):
|
|
|
|
|
|
|
|
|
|
| 73 |
if not title_input and not content_input:
|
| 74 |
+
st.warning("Please input a title or content.")
|
| 75 |
else:
|
| 76 |
+
with st.spinner("Analyzing..."):
|
| 77 |
+
input_df = pd.DataFrame({'Feature_1': [title_input], 'Feature_2': [content_input]})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
try:
|
| 79 |
prediction = model.predict(input_df)[0]
|
| 80 |
prediction_proba = model.predict_proba(input_df)[0]
|
| 81 |
confidence = round(max(prediction_proba) * 100, 2)
|
| 82 |
+
label = "REAL" if prediction == 0 else "FAKE"
|
| 83 |
+
color = "green" if label == "REAL" else "red"
|
| 84 |
+
st.subheader("Result:")
|
|
|
|
|
|
|
|
|
|
| 85 |
st.markdown(f"<h3 style='color:{color};'>{label}</h3>", unsafe_allow_html=True)
|
| 86 |
+
st.info(f"Confidence: {confidence}%")
|
| 87 |
|
| 88 |
+
explanation = explain_with_gemini(title_input, content_input, label)
|
| 89 |
+
st.markdown("---")
|
| 90 |
+
st.markdown("🧠 **Explanation:**")
|
| 91 |
+
st.markdown(explanation)
|
|
|
|
|
|
|
| 92 |
|
| 93 |
except Exception as e:
|
| 94 |
+
st.error(f"Prediction error: {e}")
|
| 95 |
|
| 96 |
st.markdown("---")
|
| 97 |
+
st.markdown("This app is for educational purposes only.")
|