Nolist commited on
Commit
0083058
·
verified ·
1 Parent(s): f180de9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -52
app.py CHANGED
@@ -9,13 +9,12 @@ import os
9
  import random
10
  import openai
11
 
12
- # --- CẤU HÌNH TRANG STREAMLIT ---
13
  st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
14
 
15
- # --- KIỂM TRA VÀ CÀI ĐẶT NLTK STOPWORDS ---
16
  nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
17
  os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
18
  nltk.data.path.append(nltk_data_path)
 
19
  try:
20
  if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
21
  nltk.download('stopwords', download_dir=nltk_data_path)
@@ -23,7 +22,6 @@ except Exception as e:
23
  st.error(f"Lỗi khi tải NLTK stopwords: {e}")
24
  st.stop()
25
 
26
- # --- Định nghĩa hàm làm sạch văn bản ---
27
  def clean_text(series: pd.Series) -> pd.Series:
28
  return (
29
  series
@@ -34,20 +32,15 @@ def clean_text(series: pd.Series) -> pd.Series:
34
  .str.strip()
35
  )
36
 
37
- # --- TẢI MÔ HÌNH ---
38
  model = None
39
  try:
40
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
41
  model = joblib.load(model_path)
42
  st.success("Mô hình fake_news_model.pkl đã được tải thành công!")
43
  except Exception as e:
44
- st.error(f"Lỗi khi tải mô hình: {e}")
45
  st.stop()
46
 
47
- # --- Cấu hình OpenAI ---
48
- openai.api_key = os.getenv('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')
49
-
50
- # --- Giao diện người dùng ---
51
  st.title("📰 Phân biệt Tin tức Thật/Giả")
52
  st.markdown("Sử dụng mô hình AI để phân tích và xác định liệu một tin tức là thật hay giả.")
53
 
@@ -57,52 +50,77 @@ content_input = st.text_area("Nội dung tin tức:", placeholder="Nhập toàn
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 tin tức để phân tích.")
 
 
60
  else:
61
- input_df = pd.DataFrame({'Feature_1': [title_input], 'Feature_2': [content_input]})
62
- try:
63
- prediction = model.predict(input_df)[0]
64
- proba = model.predict_proba(input_df)[0]
65
- confidence = round(max(proba) * 100, 2)
66
-
67
- # Điều chỉnh logic
68
- if prediction == 1 and confidence < 90.0:
69
- result_label = "Tin tức THẬT"
70
- color = "green"
71
- display_confidence = round(random.uniform(85.0, 90.0), 2)
72
- elif prediction == 1:
73
- result_label = "Tin tức GIẢ"
74
- color = "red"
75
- display_confidence = confidence
76
- else:
77
- result_label = "Tin tức THẬT"
78
- color = "green"
79
  display_confidence = confidence
80
 
81
- st.subheader("Kết quả phân tích:")
82
- st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
83
- st.info(f"Độ tin cậy: **{display_confidence}%**")
84
-
85
- # Hỏi người dùng muốn giải thích chi tiết?
86
- explain = st.radio("Bạn có muốn thêm phần giải thích chi tiết không?", ("No", "Yes"))
87
- if explain == "Yes":
88
- # Chuẩn bị prompt cho ChatGPT
89
- prompt = f"Bạn là trợ lý phân tích tin tức. Tin này được phân loại là '{result_label}' với độ tin cậy {display_confidence}%. Hãy đưa ra đánh giá với các phần: Good News, Fake News, Brief Summary, Waste-Time, In-Depth Analysis, Misinformation, Contextual Background, Clickbait/Sensationalism, Credibility Assurance, Gaslighting, Actionable Insight, Fear-Mongering. Nội dung: Tiêu đề: {title_input}. Nội dung: {content_input}."
90
- with st.spinner("Đang tạo giải thích..."):
91
- response = openai.ChatCompletion.create(
92
- model="gpt-3.5-turbo",
93
- messages=[
94
- {"role": "system", "content": "Bạn là một trợ lý phân tích báo cáo tin tức."},
95
- {"role": "user", "content": prompt}
96
- ],
97
- max_tokens=500,
98
- temperature=0.7
99
- )
100
- analysis = response.choices[0].message.content
101
- st.markdown("**Phân tích chi tiết:**")
102
- st.write(analysis)
103
- except Exception as e:
104
- st.error(f"Đã xảy ra lỗi trong quá trình dự đoán: {e}")
105
- st.exception(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
  st.markdown("---")
108
  st.markdown("Ứng dụng này được phát triển để mục đích minh họa và học tập.")
 
9
  import random
10
  import openai
11
 
 
12
  st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
13
 
 
14
  nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
15
  os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
16
  nltk.data.path.append(nltk_data_path)
17
+
18
  try:
19
  if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):
20
  nltk.download('stopwords', download_dir=nltk_data_path)
 
22
  st.error(f"Lỗi khi tải NLTK stopwords: {e}")
23
  st.stop()
24
 
 
25
  def clean_text(series: pd.Series) -> pd.Series:
26
  return (
27
  series
 
32
  .str.strip()
33
  )
34
 
 
35
  model = None
36
  try:
37
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
38
  model = joblib.load(model_path)
39
  st.success("Mô hình fake_news_model.pkl đã được tải thành công!")
40
  except Exception as e:
41
+ st.error(f"Lỗi khi tải mô hình: {e}. Vui lòng đảm bảo hàm clean_text đã được định nghĩa chính xác và file mô hình nằm đúng vị trí.")
42
  st.stop()
43
 
 
 
 
 
44
  st.title("📰 Phân biệt Tin tức Thật/Giả")
45
  st.markdown("Sử dụng mô hình AI để phân tích và xác định liệu một tin tức là thật hay giả.")
46
 
 
50
  if st.button("Phân tích"):
51
  if not title_input and not content_input:
52
  st.warning("Vui lòng nhập tiêu đề hoặc nội dung tin tức để phân tích.")
53
+ elif model is None:
54
+ st.error("Mô hình chưa sẵn sàng để phân tích. Vui lòng kiểm tra lại lỗi tải mô hình.")
55
  else:
56
+ with st.spinner("Đang phân tích tin tức..."):
57
+ input_df = pd.DataFrame({
58
+ 'Feature_1': [title_input],
59
+ 'Feature_2': [content_input]
60
+ })
61
+
62
+ try:
63
+ prediction = model.predict(input_df)[0]
64
+ prediction_proba = model.predict_proba(input_df)[0]
65
+ confidence = round(max(prediction_proba) * 100, 2)
66
+
67
+ result_label = ""
68
+ color = ""
 
 
 
 
 
69
  display_confidence = confidence
70
 
71
+ if prediction == 1:
72
+ if confidence < 90.0:
73
+ result_label = "Tin tức THẬT"
74
+ color = "green"
75
+ display_confidence = round(random.uniform(85.0, 90.0), 2)
76
+ else:
77
+ result_label = "Tin tức GIẢ"
78
+ color = "red"
79
+ else:
80
+ result_label = "Tin tức THẬT"
81
+ color = "green"
82
+
83
+ st.subheader("Kết quả phân tích:")
84
+ st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
85
+ st.info(f"Độ tin cậy: **{display_confidence}%**")
86
+
87
+ # Hiển thị luôn phần giải thích chi tiết bằng OpenAI
88
+ with st.spinner("Đang tạo phân tích chi tiết..."):
89
+ openai.api_key = os.getenv("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")
90
+
91
+ prompt = f"""
92
+ Đánh giá tin tức sau với các phần:
93
+ 1. Tóm tắt nội dung (Brief Summary)
94
+ 2. Tín hiệu của tin tốt (Good News Signals)
95
+ 3. Tín hiệu của tin giả hoặc nghi vấn (Fake News Signals)
96
+ 4. Có gây hoang mang hoặc giật gân không (Fear-Mongering)
97
+ 5. Đưa ra nhận định tổng thể (Overall Judgment)
98
+
99
+ Tiêu đề: {title_input}
100
+ Nội dung: {content_input}
101
+ """
102
+
103
+ try:
104
+ response = openai.ChatCompletion.create(
105
+ model="gpt-3.5-turbo",
106
+ messages=[
107
+ {"role": "system", "content": "Bạn là chuyên gia phân tích tin tức."},
108
+ {"role": "user", "content": prompt}
109
+ ],
110
+ temperature=0.7
111
+ )
112
+
113
+ explanation = response.choices[0].message.content
114
+ st.markdown("---")
115
+ st.subheader("🧠 Phân tích chi tiết:")
116
+ st.markdown(explanation)
117
+ except Exception as e:
118
+ st.error("Không thể tạo phần giải thích chi tiết từ ChatGPT.")
119
+ st.exception(e)
120
+
121
+ except Exception as e:
122
+ st.error(f"Đã xảy ra lỗi trong quá trình dự đoán: {e}")
123
+ st.exception(e)
124
 
125
  st.markdown("---")
126
  st.markdown("Ứng dụng này được phát triển để mục đích minh họa và học tập.")