Nolist commited on
Commit
b375876
·
verified ·
1 Parent(s): 30b8769

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -68
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 random
9
  import google.generativeai as genai
10
 
11
- # Cấu hình Generative AI
12
- GENAI_API_KEY = "AIzaSyDuX32-Rd6G23d8hUIg-lxFCYCOtfiNYVE"
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ử 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 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.")
 
 
 
 
 
 
 
 
 
 
 
 
 
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Ử ---
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}")