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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -87
app.py CHANGED
@@ -1,36 +1,24 @@
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="Fake News Detection", layout="centered")
15
-
16
- # --- CHỌN NGÔN NGỮ ---
17
- lang = st.selectbox("🌐 Chọn ngôn ngữ | Select Language", ["Tiếng Việt", "English"])
18
- def t(vn, en):
19
- return vn if lang == "Tiếng Việt" else en
20
 
21
- # --- TẢI DỮ LIỆU NLTK ---
22
  nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
23
  os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
24
  nltk.data.path.append(nltk_data_path)
25
-
26
  try:
27
  if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
28
  nltk.download('stopwords', download_dir=nltk_data_path)
29
  except Exception as e:
30
- st.error(t(f"Lỗi khi tải NLTK stopwords: {e}", f"Error downloading NLTK stopwords: {e}"))
31
  st.stop()
32
 
33
- # --- TIỀN XỬ LÝ ---
34
  def clean_text(series: pd.Series) -> pd.Series:
35
  return (
36
  series
@@ -41,85 +29,81 @@ def clean_text(series: pd.Series) -> pd.Series:
41
  .str.strip()
42
  )
43
 
44
- # --- TẢI MÔ HÌNH ---
45
  model = None
46
  try:
47
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
48
  model = joblib.load(model_path)
49
- st.success(t("✅ Mô hình đã được tải thành công!", "✅ Model loaded successfully!"))
50
  except Exception as e:
51
- st.error(t(f"❌ Lỗi khi tải mô hình: {e}", f"❌ Error loading model: {e}"))
52
  st.stop()
53
 
54
- # --- GIAO DIỆN ---
55
- st.title(t("📰 Phân biệt Tin tức Thật/Giả", "📰 Fake News Detection"))
56
-
57
- st.markdown(t(
58
- "Dựa vào AI để xác định tin tức là **thật hay giả**.",
59
- "Using AI to determine whether a news article is **real or fake**."
60
- ))
61
-
62
- title_input = st.text_input(t("✏️ Tiêu đề tin tức:", "✏️ News Title:"), placeholder=t("Nhập tiêu đề...", "Enter the title..."))
63
- content_input = st.text_area(t("📝 Nội dung tin tức:", "📝 News Content:"), placeholder=t("Nhập nội dung đầy đủ...", "Enter the full content..."), height=250)
64
-
65
- if st.button(t("🔍 Phân tích", "🔍 Analyze")):
66
- if not title_input and not content_input:
67
- st.warning(t("⚠️ Vui lòng nhập ít nhất tiêu đề hoặc nội dung.", "⚠️ Please enter at least the title or content."))
68
- elif model is None:
69
- st.error(t("❌ Mô hình chưa sẵn sàng.", "❌ Model not ready."))
70
- else:
71
- with st.spinner(t("Đang phân tích...", "Analyzing...")):
72
- input_df = pd.DataFrame({
73
- 'Feature_1': [title_input],
74
- 'Feature_2': [content_input]
75
- })
76
-
77
- try:
78
- prediction = model.predict(input_df)[0]
79
- prediction_proba = model.predict_proba(input_df)[0]
80
- confidence = round(max(prediction_proba) * 100, 2)
81
-
82
- if prediction == 1:
83
- result_label = t("Tin tức GIẢ", "Fake News")
84
- color = "red"
85
- if confidence < 90.0:
 
 
 
 
86
  confidence = round(random.uniform(85.0, 90.0), 2)
87
- else:
88
- result_label = t("Tin tức THẬT", "Real News")
89
- color = "green"
90
-
91
- st.subheader(t("🔎 Kết quả phân tích:", "🔎 Analysis Result:"))
92
- st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
93
- st.info(t(f"Độ tin cậy: **{confidence}%**", f"Confidence: **{confidence}%**"))
94
-
95
- # --- Gọi GPT giải thích ---
 
 
 
 
 
 
 
 
 
96
  try:
97
- openai_api_key = "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" # THAY BẰNG API KEY RIÊNG
98
- client = OpenAI(api_key=openai_api_key)
99
-
100
- prompt = t("""Phân tích chi tiết tại sao tin tức dưới đây được phân loại là:",
101
- """Explain in detail why the following news was classified as:") + f" '{result_label}'\n\n"
102
- prompt += t("Tiêu đề:", "Title:") + f" {title_input}\n"
103
- prompt += t("Nội dung:", "Content:") + f" {content_input}"
104
-
105
- response = client.chat.completions.create(
106
- model="gpt-3.5-turbo",
107
- messages=[
108
- {"role": "system", "content": t("Bạn là chuyên gia phân tích tin tức.", "You are a news analysis expert.")},
109
- {"role": "user", "content": prompt}
110
- ],
111
- temperature=0.7
112
- )
113
- explanation = response.choices[0].message.content
114
- st.markdown("---")
115
- st.markdown(t("🧠 **Phân tích chi tiết từ AI:**", "🧠 **Detailed AI Explanation:**"))
116
- st.markdown(explanation)
117
-
118
  except Exception as e:
119
- st.warning(t(f"Không thể tạo giải thích từ GPT: {e}", f"Unable to generate explanation from GPT: {e}"))
120
- except Exception as e:
121
- st.error(t(f"❌ Lỗi trong quá trình dự đoán: {e}", f"❌ Error during prediction: {e}"))
122
-
123
- st.markdown("---")
124
- st.caption(t("🧪 Ứng dụng này được phát triển cho mục đích học tập và minh họa.",
125
- "🧪 This app was developed for educational and illustrative purposes."))
 
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
  .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.")