Nolist commited on
Commit
dea6186
·
verified ·
1 Parent(s): 33b331c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -71
app.py CHANGED
@@ -1,24 +1,31 @@
1
  # --- app.py ---
 
2
  import streamlit as st
3
  import joblib
4
  import pandas as pd
5
  import re
6
  import nltk
 
7
  import os
8
  import random
 
 
 
 
9
 
10
- # --- NLTK SETUP ---
11
  nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
12
  os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
13
  nltk.data.path.append(nltk_data_path)
 
14
  try:
15
  if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
16
  nltk.download('stopwords', download_dir=nltk_data_path)
17
  except Exception as e:
18
- st.error(f"Error downloading NLTK stopwords: {e}")
19
  st.stop()
20
 
21
- # --- TEXT CLEANING ---
22
  def clean_text(series: pd.Series) -> pd.Series:
23
  return (
24
  series
@@ -29,81 +36,80 @@ def clean_text(series: pd.Series) -> pd.Series:
29
  .str.strip()
30
  )
31
 
32
- # --- LOAD MODEL ---
33
  model = None
34
  try:
35
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
36
  model = joblib.load(model_path)
 
37
  except Exception as e:
38
- st.error(f"Model loading error: {e}")
39
  st.stop()
40
 
41
- # --- LANGUAGE SELECTION ---
42
- if "language" not in st.session_state:
43
- st.session_state.language = None
44
-
45
- if st.session_state.language is None:
46
- st.set_page_config(page_title="Language Selection")
47
- st.title("\U0001F310 Choose Language | Chọn Ngôn Ngữ")
48
- lang = st.radio("Select a language / Chọn ngôn ngữ:", ["\U0001F1FA\U0001F1F8 English", "\U0001F1FB\U0001F1F3 Tiếng Việt"])
49
- if st.button("Confirm / Xác nhận"):
50
- st.session_state.language = "en" if "English" in lang else "vi"
51
- st.experimental_rerun()
52
-
53
- # --- APP CONFIG ---
54
- st.set_page_config(page_title="Fake News Detector", layout="centered")
55
-
56
- # --- APP CONTENT BASED ON LANGUAGE ---
57
- lang = st.session_state.language
58
-
59
- if lang == "vi":
60
- st.title("\U0001F4F0 Phân biệt Tin tức Thật/Giả")
61
- st.markdown("Dựa vào AI để xác định tin tức là **thật hay giả**.")
62
- title_input = st.text_input("✏️ Tiêu đề tin tức:", placeholder="Nhập tiêu đề...")
63
- content_input = st.text_area("📝 Nội dung tin tức:", placeholder="Nhập nội dung đầy đủ...", height=250)
64
- if st.button("🔍 Phân tích"):
65
- if not title_input and not content_input:
66
- st.warning("⚠️ Vui lòng nhập ít nhất tiêu đề hoặc nội dung.")
67
- else:
68
- with st.spinner("Đang phân tích..."):
69
- input_df = pd.DataFrame({'Feature_1': [title_input], 'Feature_2': [content_input]})
70
- try:
71
- prediction = model.predict(input_df)[0]
72
- prediction_proba = model.predict_proba(input_df)[0]
73
- confidence = round(max(prediction_proba) * 100, 2)
74
- result_label = "Tin tức GIẢ" if prediction == 1 else "Tin tức THẬT"
75
- color = "red" if prediction == 1 else "green"
76
- if prediction == 1 and confidence < 90:
77
  confidence = round(random.uniform(85.0, 90.0), 2)
78
- st.subheader("🔎 Kết quả phân tích:")
79
- st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
80
- st.info(f"Độ tin cậy: **{confidence}%**")
81
- except Exception as e:
82
- st.error(f" Lỗi trong quá trình dự đoán: {e}")
83
- st.caption("🧪 Ứng dụng này được phát triển cho mục đích học tập và minh họa.")
84
-
85
- elif lang == "en":
86
- st.title("\U0001F4F0 Real vs. Fake News Detector")
87
- st.markdown("Using AI to determine whether news is **real or fake**.")
88
- title_input = st.text_input("✏️ News Title:", placeholder="Enter the title...")
89
- content_input = st.text_area("📝 News Content:", placeholder="Enter the full content...", height=250)
90
- if st.button("🔍 Analyze"):
91
- if not title_input and not content_input:
92
- st.warning("⚠️ Please enter at least a title or content.")
93
- else:
94
- with st.spinner("Analyzing..."):
95
- input_df = pd.DataFrame({'Feature_1': [title_input], 'Feature_2': [content_input]})
96
  try:
97
- prediction = model.predict(input_df)[0]
98
- prediction_proba = model.predict_proba(input_df)[0]
99
- confidence = round(max(prediction_proba) * 100, 2)
100
- result_label = "FAKE News" if prediction == 1 else "REAL News"
101
- color = "red" if prediction == 1 else "green"
102
- if prediction == 1 and confidence < 90:
103
- confidence = round(random.uniform(85.0, 90.0), 2)
104
- st.subheader("🔎 Analysis Result:")
105
- st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
106
- st.info(f"Confidence: **{confidence}%**")
 
 
 
 
 
 
 
 
 
 
 
107
  except Exception as e:
108
- st.error(f" Error during prediction: {e}")
109
- st.caption("🧪 This app is developed for educational and demonstration purposes.")
 
 
 
 
 
1
  # --- app.py ---
2
+
3
  import streamlit as st
4
  import joblib
5
  import pandas as pd
6
  import re
7
  import nltk
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("✅ Mô 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
+ Nội dung: {content_input}"""
95
+
96
+ response = client.chat.completions.create(
97
+ model="gpt-3.5-turbo",
98
+ messages=[
99
+ {"role": "system", "content": "Bạn là chuyên gia phân tích tin tức."},
100
+ {"role": "user", "content": prompt}
101
+ ],
102
+ temperature=0.7
103
+ )
104
+ explanation = response.choices[0].message.content
105
+ st.markdown("---")
106
+ st.markdown("🧠 **Phân tích chi tiết từ AI:**")
107
+ st.markdown(explanation)
108
+
109
  except Exception as e:
110
+ st.warning(f"Không thể tạo giải thích từ GPT: {e}")
111
+ except Exception as e:
112
+ st.error(f"❌ Lỗi trong quá trình dự đoán: {e}")
113
+
114
+ st.markdown("---")
115
+ st.caption("🧪 Ứng dụng này được phát triển cho mục đích học tập và minh họa.")