Nolist commited on
Commit
e2bdfc9
·
verified ·
1 Parent(s): ac15902

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -48
app.py CHANGED
@@ -6,10 +6,9 @@ import pandas as pd
6
  import re
7
  import nltk
8
  from nltk.corpus import stopwords
9
- from nltk.stem.porter import PorterStemmer
10
  import os
11
  import random
12
- from openai import OpenAI # Sử dụng chuẩn mới
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")
@@ -26,7 +25,7 @@ except Exception as e:
26
  st.error(f"Lỗi khi tải NLTK stopwords: {e}")
27
  st.stop()
28
 
29
- # --- HÀM TIỀN XỬ LÝ ---
30
  def clean_text(series: pd.Series) -> pd.Series:
31
  return (
32
  series
@@ -42,77 +41,76 @@ model = None
42
  try:
43
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
44
  model = joblib.load(model_path)
45
- st.success("Mô hình fake_news_model.pkl đã được tải thành công!")
46
  except Exception as e:
47
- st.error(f"Lỗi khi tải mô hình: {e}.")
48
  st.stop()
49
 
50
- # --- GIAO DIỆN STREAMLIT ---
51
  st.title("📰 Phân biệt Tin tức Thật/Giả")
52
- st.markdown("Sử dụng mô hình AI để xác định liệu một tin tức là thật hay giả.")
53
 
54
- title_input = st.text_input("Tiêu đề tin tức:", placeholder="Nhập tiêu đề tin tức...")
55
- content_input = st.text_area("Nội dung tin tức:", placeholder="Nhập toàn bộ nội dung tin tức...", height=250)
56
 
57
- if st.button("Phân tích"):
58
  if not title_input and not content_input:
59
- st.warning("Vui lòng nhập tiêu đề hoặc nội dung.")
60
  elif model is None:
61
- st.error("Mô hình chưa sẵn sàng.")
62
  else:
63
  with st.spinner("Đang phân tích..."):
64
  input_df = pd.DataFrame({
65
  'Feature_1': [title_input],
66
  'Feature_2': [content_input]
67
  })
 
68
  try:
69
  prediction = model.predict(input_df)[0]
70
  prediction_proba = model.predict_proba(input_df)[0]
71
-
72
  confidence = round(max(prediction_proba) * 100, 2)
73
 
74
- result_label = ""
75
- color = ""
76
- display_confidence = confidence
77
-
78
  if prediction == 1:
 
 
79
  if confidence < 90.0:
80
- result_label = "Tin tức THẬT"
81
- color = "green"
82
- display_confidence = round(random.uniform(85.0, 90.0), 2)
83
- else:
84
- result_label = "Tin tức GIẢ"
85
- color = "red"
86
  else:
87
  result_label = "Tin tức THẬT"
88
  color = "green"
89
 
90
- st.subheader("Kết quả phân tích:")
91
  st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
92
- st.info(f"Độ tin cậy: **{display_confidence}%**")
93
-
94
- # --- GIẢI THÍCH CHI TIẾT TỪ GPT ---
95
- if os.getenv("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"):
96
- try:
97
- prompt = f"Phân tích chi tiết lý do tại sao tin tức sau đây được phân loại là '{result_label}':\n\nTiêu đề: {title_input}\n\nNội dung: {content_input}"
98
- client = OpenAI(api_key=os.getenv("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"))
99
- response = client.chat.completions.create(
100
- model="gpt-3.5-turbo",
101
- messages=[
102
- {"role": "system", "content": "Bạn là chuyên gia phân tích tin tức."},
103
- {"role": "user", "content": prompt}
104
- ],
105
- temperature=0.7
106
- )
107
- explanation = response.choices[0].message.content
108
- st.markdown("---")
109
- st.markdown("🧠 **Phân tích chi tiết:**")
110
- st.markdown(explanation)
111
- except Exception as e:
112
- st.warning(f"Không thể tạo giải thích chi tiết từ GPT: {e}")
113
-
 
 
 
 
 
 
114
  except Exception as e:
115
- st.error(f"Lỗi trong quá trình dự đoán: {e}")
116
 
117
  st.markdown("---")
118
- st.markdown("Ứng dụng này được phát triển để minh họa và học tập.")
 
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")
 
25
  st.error(f"Lỗi khi tải NLTK stopwords: {e}")
26
  st.stop()
27
 
28
+ # --- TIỀN XỬ LÝ ---
29
  def clean_text(series: pd.Series) -> pd.Series:
30
  return (
31
  series
 
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
+
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.")