Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,97 +1,79 @@
|
|
| 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
|
| 9 |
import google.generativeai as genai
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
genai.configure(api_key=GENAI_API_KEY)
|
| 14 |
|
| 15 |
-
#
|
| 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
|
| 27 |
st.stop()
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
def clean_text(
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 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 |
-
#
|
| 58 |
-
model = None
|
| 59 |
try:
|
| 60 |
-
|
| 61 |
-
model = joblib.load(model_path)
|
| 62 |
-
st.success("Model loaded successfully.")
|
| 63 |
except Exception as e:
|
| 64 |
-
st.error(f"
|
| 65 |
st.stop()
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
content_input = st.text_area("News Content", height=250)
|
| 71 |
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
if not title_input and not content_input:
|
| 74 |
-
st.warning("
|
| 75 |
else:
|
| 76 |
-
with st.spinner("
|
| 77 |
-
input_df = pd.DataFrame({'Feature_1': [title_input], 'Feature_2': [content_input]})
|
| 78 |
try:
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 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 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
st.markdown(explanation)
|
| 92 |
|
| 93 |
-
|
| 94 |
-
st.error(f"Prediction error: {e}")
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import joblib
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
import nltk
|
|
|
|
| 5 |
import os
|
| 6 |
+
import re
|
| 7 |
import google.generativeai as genai
|
| 8 |
|
| 9 |
+
# --- CẤU HÌNH ---
|
| 10 |
+
st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
|
|
|
|
| 11 |
|
| 12 |
+
# --- TẢI STOPWORDS ---
|
|
|
|
|
|
|
|
|
|
| 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"Lỗi tải NLTK stopwords: {e}")
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
+
# --- TIỀN XỬ LÝ ---
|
| 25 |
+
def clean_text(text):
|
| 26 |
+
text = re.sub(r'<[^>]+>', ' ', text)
|
| 27 |
+
text = re.sub(r'http\S+|\S+@\S+', ' ', text)
|
| 28 |
+
text = re.sub(r'[^A-Za-z0-9\s]', ' ', text)
|
| 29 |
+
return text.lower().strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# --- TẢI MÔ HÌNH ---
|
|
|
|
| 32 |
try:
|
| 33 |
+
model = joblib.load("fake_news_model.pkl")
|
|
|
|
|
|
|
| 34 |
except Exception as e:
|
| 35 |
+
st.error(f"Lỗi tải mô hình: {e}")
|
| 36 |
st.stop()
|
| 37 |
|
| 38 |
+
# --- CẤU HÌNH GEMINI ---
|
| 39 |
+
genai.configure(api_key="AIzaSyDuX32-Rd6G23d8hUIg-lxFCYCOtfiNYVE")
|
| 40 |
+
g_model = genai.GenerativeModel("gemini-pro")
|
|
|
|
| 41 |
|
| 42 |
+
# --- GIAO DIỆN ---
|
| 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("Vui lòng nhập tiêu đề hoặc nội dung.")
|
| 52 |
else:
|
| 53 |
+
with st.spinner("Đang phân tích..."):
|
|
|
|
| 54 |
try:
|
| 55 |
+
df = pd.DataFrame({
|
| 56 |
+
"Feature_1": [title_input],
|
| 57 |
+
"Feature_2": [content_input]
|
| 58 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
prediction = model.predict(df)[0]
|
| 61 |
+
label = "Tin tức THẬT" if prediction == 0 else "Tin tức GIẢ"
|
| 62 |
+
color = "green" if prediction == 0 else "red"
|
|
|
|
| 63 |
|
| 64 |
+
st.markdown(f"<h3 style='color:{color}'>{label}</h3>", unsafe_allow_html=True)
|
|
|
|
| 65 |
|
| 66 |
+
# --- PHÂN TÍCH BẰNG GEMINI ---
|
| 67 |
+
try:
|
| 68 |
+
prompt = f"""You are a fake news detection expert. Explain clearly and logically why this article is classified as '{label}'.
|
| 69 |
+
|
| 70 |
+
Title: {title_input}
|
| 71 |
+
Content: {content_input}
|
| 72 |
+
"""
|
| 73 |
+
response = g_model.generate_content(prompt)
|
| 74 |
+
st.markdown("🧠 **Phân tích chi tiết:**")
|
| 75 |
+
st.markdown(response.text)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
st.warning(f"Không thể tạo giải thích từ Gemini: {e}")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
st.error(f"Lỗi khi dự đoán: {e}")
|