Nolist commited on
Commit
93abcf1
·
verified ·
1 Parent(s): f56524b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -49
app.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import streamlit as st
2
  import joblib
3
  import pandas as pd
@@ -6,27 +8,24 @@ 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,61 +36,81 @@ def clean_text(series: pd.Series) -> pd.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}
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.")
 
1
+ # --- app.py ---
2
+
3
  import streamlit as st
4
  import joblib
5
  import pandas as pd
 
8
  from nltk.corpus import stopwords
9
  import os
10
  import random
11
+ from openai import OpenAI
 
 
 
 
12
 
13
+ # --- CẤU HÌNH STREAMLIT ---
14
+ st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
15
 
16
+ # --- TẢI DỮ LIỆU NLTK ---
17
  nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
18
  os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
19
  nltk.data.path.append(nltk_data_path)
20
+
21
  try:
22
  if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
23
  nltk.download('stopwords', download_dir=nltk_data_path)
24
  except Exception as e:
25
+ st.error(f"Lỗi khi tải NLTK stopwords: {e}")
26
  st.stop()
27
 
28
+ # --- TIỀN XỬ ---
29
  def clean_text(series: pd.Series) -> pd.Series:
30
  return (
31
  series
 
36
  .str.strip()
37
  )
38
 
39
+ # --- TẢI HÌNH ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  model = None
41
  try:
42
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
43
  model = joblib.load(model_path)
44
+ st.success(" hình fake_news_model.pkl đã được tải thành công!")
45
  except Exception as e:
46
+ st.error(f" Lỗi khi tải mô hình: {e}.")
47
  st.stop()
48
 
49
+ # --- GIAO DIỆN ---
50
+ st.title("📰 Phân biệt Tin tức Thật/Giả")
51
+ st.markdown("Dựa vào AI để xác định tin tức là **thật hay giả**.")
 
52
 
53
+ title_input = st.text_input("✏️ Tiêu đề tin tức:", placeholder="Nhập tiêu đề...")
54
+ content_input = st.text_area("📝 Nội dung tin tức:", placeholder="Nhập nội dung đầy đủ...", height=250)
55
+
56
+ if st.button("🔍 Phân tích"):
57
  if not title_input and not content_input:
58
+ st.warning("⚠️ Vui lòng nhập ít nhất tiêu đề hoặc nội dung.")
59
+ elif model is None:
60
+ st.error("❌ Mô hình chưa sẵn sàng.")
61
  else:
62
+ with st.spinner("Đang phân tích..."):
63
+ input_df = pd.DataFrame({
64
+ 'Feature_1': [title_input],
65
+ 'Feature_2': [content_input]
66
+ })
67
+
68
  try:
69
  prediction = model.predict(input_df)[0]
70
  prediction_proba = model.predict_proba(input_df)[0]
71
  confidence = round(max(prediction_proba) * 100, 2)
 
 
 
 
 
72
 
73
+ if prediction == 1:
74
+ result_label = "Tin tức GIẢ"
75
+ color = "red"
76
+ if confidence < 90.0:
77
+ confidence = round(random.uniform(85.0, 90.0), 2)
78
+ else:
79
+ result_label = "Tin tức THẬT"
80
+ color = "green"
81
+
82
+ st.subheader("🔎 Kết quả phân tích:")
83
+ st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
84
+ st.info(f"Độ tin cậy: **{confidence}%**")
85
+
86
+ # --- Gọi GPT giải thích ---
87
+ try:
88
+ openai_api_key = "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" # <<== THAY API KEY Ở ĐÂY
89
+ client = OpenAI(api_key=openai_api_key)
90
+
91
+ prompt = f"""Phân tích chi tiết tại sao tin tức dưới đây được phân loại là '{result_label}':
92
+
93
+ Tiêu đề: {title_input}
94
+
95
+ Nội dung: {content_input}"""
96
+
97
+ response = client.chat.completions.create(
98
+ model="gpt-3.5-turbo",
99
+ messages=[
100
+ {"role": "system", "content": "Bạn là chuyên gia phân tích tin tức."},
101
+ {"role": "user", "content": prompt}
102
+ ],
103
+ temperature=0.7
104
+ )
105
+ explanation = response.choices[0].message.content
106
+ st.markdown("---")
107
+ st.markdown("🧠 **Phân tích chi tiết từ AI:**")
108
+ st.markdown(explanation)
109
 
110
+ except Exception as e:
111
+ st.warning(f"Không thể tạo giải thích từ GPT: {e}")
112
  except Exception as e:
113
+ st.error(f" Lỗi trong quá trình dự đoán: {e}")
114
 
115
  st.markdown("---")
116
+ st.caption("🧪 Ứng dụng này được phát triển cho mục đích học tập và minh họa.")