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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -27
app.py CHANGED
@@ -11,7 +11,12 @@ 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')
@@ -22,7 +27,7 @@ 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Ử LÝ ---
@@ -41,25 +46,29 @@ 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]
@@ -71,46 +80,46 @@ if st.button("🔍 Phân tích"):
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.")
 
 
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')
 
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Ý ---
 
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]
 
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."))