Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,83 +1,97 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import joblib
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
import nltk
|
|
|
|
| 5 |
import os
|
| 6 |
-
import
|
| 7 |
import google.generativeai as genai
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
|
|
|
| 11 |
|
| 12 |
-
#
|
|
|
|
|
|
|
|
|
|
| 13 |
nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
|
| 14 |
os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
|
| 15 |
nltk.data.path.append(nltk_data_path)
|
| 16 |
-
|
| 17 |
try:
|
| 18 |
if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
|
| 19 |
nltk.download('stopwords', download_dir=nltk_data_path)
|
| 20 |
except Exception as e:
|
| 21 |
-
st.error(f"
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
def clean_text(
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
#
|
|
|
|
| 32 |
try:
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
except Exception as e:
|
| 35 |
-
st.error(f"
|
| 36 |
st.stop()
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
st.title("📰 Phân biệt Tin tức Thật/Giả")
|
| 44 |
-
st.markdown("Nhập tiêu đề và nội dung để phân tích xem tin tức là thật hay giả.")
|
| 45 |
-
|
| 46 |
-
title_input = st.text_input("Tiêu đề:")
|
| 47 |
-
content_input = st.text_area("Nội dung:", height=200)
|
| 48 |
-
|
| 49 |
-
if st.button("Phân tích"):
|
| 50 |
if not title_input and not content_input:
|
| 51 |
-
st.warning("
|
| 52 |
else:
|
| 53 |
-
with st.spinner("
|
|
|
|
| 54 |
try:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
})
|
| 63 |
-
|
| 64 |
-
prediction = model.predict(df)[0]
|
| 65 |
-
label = "Tin tức THẬT" if prediction == 0 else "Tin tức GIẢ"
|
| 66 |
-
color = "green" if prediction == 0 else "red"
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
# --- PHÂN TÍCH BẰNG GEMINI ---
|
| 71 |
-
try:
|
| 72 |
-
prompt = f"""You are a fake news detection expert. Explain clearly and logically why this article is classified as '{label}'.
|
| 73 |
-
|
| 74 |
-
Title: {title_input}
|
| 75 |
-
Content: {content_input}
|
| 76 |
-
"""
|
| 77 |
-
response = g_model.generate_content(prompt)
|
| 78 |
-
st.markdown("🧠 **Phân tích chi tiết:**")
|
| 79 |
-
st.markdown(response.text)
|
| 80 |
-
except Exception as e:
|
| 81 |
-
st.warning(f"Không thể tạo giải thích từ Gemini: {e}")
|
| 82 |
except Exception as e:
|
| 83 |
-
st.error(f"
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import joblib
|
| 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
|
| 33 |
+
.str.replace(r'<[^>]+>', ' ', regex=True)
|
| 34 |
+
.str.replace(r'http\S+|\S+@\S+', ' ', regex=True)
|
| 35 |
+
.str.replace(r'[^A-Za-z0-9\s]', ' ', regex=True)
|
| 36 |
+
.str.lower()
|
| 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}
|
| 51 |
+
"""
|
| 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.")
|