Nolist commited on
Commit
123ead9
·
verified ·
1 Parent(s): 76904bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -47
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
- # --- CẤU HÌNH GEMINI ---
12
- genai.configure(api_key="AIzaSyDmXGLBoweYkqyXMDtWwSWOKZCo6Exd4Dk")
 
13
 
14
- # --- CẤU HÌNH STREAMLIT ---
15
- st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
16
 
17
- # --- TẢI DỮ LIỆU NLTK ---
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"Lỗi khi tải NLTK stopwords: {e}")
27
  st.stop()
28
 
29
- # --- TIỀN XỬ ---
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
- # --- PHÂN TÍCH CHI TIẾT BẰNG GEMINI ---
41
- def explain_with_gemini(title: str, content: str, label: str):
42
  try:
43
  model = genai.GenerativeModel("gemini-pro")
44
- chat = model.start_chat()
45
- prompt = f"""You are a news analysis expert.
46
- Explain in detail why the following news article is classified as "{label}".
 
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"⚠️ Could not generate explanation: {e}"
55
 
56
- # --- TẢI MÔ HÌNH PHÂN LOẠI ---
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(" hình đã được tải thành công!")
62
  except Exception as e:
63
- st.error(f" Lỗi khi tải mô hình: {e}")
64
  st.stop()
65
 
66
- # --- GIAO DIỆN NGƯỜI DÙNG ---
67
- st.title("📰 Phân biệt Tin tức Thật/Giả")
68
- st.markdown("Sử dụng AI để xác định xem một tin tức là **thật** hay **giả**.")
 
69
 
70
- title_input = st.text_input("📝 Tiêu đề tin tức:")
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("⚠️ Vui lòng nhập tiêu đề hoặc nội dung.")
76
  else:
77
- with st.spinner("Đang phân tích..."):
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
- label = "Tin tức GIẢ" if prediction == 1 else "Tin tức THẬT"
89
- color = "red" if prediction == 1 else "green"
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"Độ tin cậy: **{confidence}%**")
95
 
96
- # PHÂN TÍCH CHI TIẾT BẰNG GEMINI
97
- with st.spinner("Đang phân tích chi tiết bằng Gemini..."):
98
- explanation = explain_with_gemini(title_input, content_input, label)
99
- st.markdown("---")
100
- st.subheader("🧠 Phân tích chi tiết:")
101
- st.markdown(explanation)
102
 
103
  except Exception as e:
104
- st.error(f"Lỗi phân tích: {e}")
105
 
106
  st.markdown("---")
107
- st.caption("🌐 Ứng dụng demo cho mục đích học tập.")
 
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ử 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 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.")