Nolist commited on
Commit
afbb50d
·
verified ·
1 Parent(s): 4066988

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -27
app.py CHANGED
@@ -3,13 +3,35 @@ import joblib
3
  import pandas as pd
4
  import re
5
  import nltk
6
- from nltk.corpus import stopwords
7
- from nltk.stem.porter import PorterStemmer
8
  import os
9
 
10
  # --- CẤU HÌNH TRANG STREAMLIT (PHẢI LÀ LỆNH STREAMLIT ĐẦU TIÊN) ---
11
  st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  # --- Cài đặt và tải tài nguyên NLTK (quan trọng cho môi trường Docker) ---
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)
@@ -22,35 +44,18 @@ except Exception as e:
22
  st.error(f"Lỗi khi tải NLTK stopwords: {e}")
23
  st.stop()
24
 
25
- # --- Định nghĩa hàm clean_text CHÍNH XÁC NHƯ TRONG CODE HUẤN LUYỆN ---
26
- def clean_text(series: pd.Series) -> pd.Series:
27
- return (
28
- series
29
- .str.replace(r'<[^>]+>', ' ', regex=True)
30
- .str.replace(r'http\S+|\S+@\S+', ' ', regex=True)
31
- .str.replace(r'[^A-Za-z0-9\s]', ' ', regex=True)
32
- .str.lower()
33
- .str.strip()
34
- )
35
 
36
  # --- Tải mô hình ---
37
  model = None
38
  try:
39
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
40
  model = joblib.load(model_path)
41
- # Không dùng st.success/st.error ở đây nữa, vì chúng phải được gọi sau set_page_config
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}. 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í.")
45
- st.stop() # Dừng ứng dụng nếu mô hình không tải được
46
-
47
- # Chỉ hiển thị thông báo tải thành công nếu không có lỗi nào trước đó
48
- if model is not None:
49
  st.success("Mô hình fake_news_model.pkl đã được tải thành công!")
50
-
 
 
51
 
52
  # --- Giao diện Streamlit ---
53
- # Các lệnh Streamlit khác sẽ bắt đầu từ đây trở đi
54
  st.title("📰 Phân biệt Tin tức Thật/Giả")
55
  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ả.")
56
 
@@ -77,12 +82,15 @@ if st.button("Phân tích"):
77
  prediction = model.predict(input_df)[0]
78
  prediction_proba = model.predict_proba(input_df)[0]
79
 
80
- if prediction == 0:
81
- result_label = "Tin tức GIẢ"
82
- color = "red"
83
- else:
84
  result_label = "Tin tức THẬT"
85
- color = "green"
 
 
 
86
 
87
  confidence = round(max(prediction_proba) * 100, 2)
88
 
 
3
  import pandas as pd
4
  import re
5
  import nltk
6
+ # from nltk.corpus import stopwords
7
+ # from nltk.stem.porter import PorterStemmer
8
  import os
9
 
10
  # --- CẤU HÌNH TRANG STREAMLIT (PHẢI LÀ LỆNH STREAMLIT ĐẦU TIÊN) ---
11
  st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
12
 
13
+ # --- Định nghĩa lớp Custom Transformer cho việc làm sạch văn bản ---
14
+ # PHẢI CHÍNH XÁC NHƯ LỚP BẠN ĐÃ DÙNG KHI HUẤN LUYỆN
15
+ from sklearn.base import BaseEstimator, TransformerMixin
16
+
17
+ class TextCleaner(BaseEstimator, TransformerMixin):
18
+ def fit(self, X, y=None):
19
+ return self
20
+
21
+ def transform(self, X: pd.Series, y=None):
22
+ if not isinstance(X, pd.Series):
23
+ X = pd.Series(X)
24
+
25
+ return (
26
+ X
27
+ .str.replace(r'<[^>]+>', ' ', regex=True)
28
+ .str.replace(r'http\S+|\S+@\S+', ' ', regex=True)
29
+ .str.replace(r'[^A-Za-z0-9\s]', ' ', regex=True)
30
+ .str.replace(r'\s+', ' ', regex=True)
31
+ .str.lower()
32
+ .str.strip()
33
+ )
34
+
35
  # --- Cài đặt và tải tài nguyên NLTK (quan trọng cho môi trường Docker) ---
36
  nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
37
  os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
 
44
  st.error(f"Lỗi khi tải NLTK stopwords: {e}")
45
  st.stop()
46
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # --- Tải mô hình ---
49
  model = None
50
  try:
51
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
52
  model = joblib.load(model_path)
 
 
 
 
 
 
 
 
53
  st.success("Mô hình fake_news_model.pkl đã được tải thành công!")
54
+ except Exception as e:
55
+ st.error(f"Lỗi khi tải mô hình: {e}. Vui lòng đảm bảo lớp TextCleaner đã được định nghĩa chính xác và file mô hình nằm đúng vị trí.")
56
+ st.stop()
57
 
58
  # --- Giao diện Streamlit ---
 
59
  st.title("📰 Phân biệt Tin tức Thật/Giả")
60
  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ả.")
61
 
 
82
  prediction = model.predict(input_df)[0]
83
  prediction_proba = model.predict_proba(input_df)[0]
84
 
85
+ # --- LOGIC NHÃN ĐÃ ĐƯỢC ĐIỀU CHỈNH ĐỂ KHỚP VỚI CÁCH BẠN TRAIN ---
86
+ # data_trues (tin thật) = 0
87
+ # data_fakes (tin giả) = 1
88
+ if prediction == 0: # Khi prediction là 0, đó là TRUE (Tin tức THẬT)
89
  result_label = "Tin tức THẬT"
90
+ color = "green" # Thường dùng màu xanh cho tin thật
91
+ else: # Khi prediction là 1, đó là FAKE (Tin tức GIẢ)
92
+ result_label = "Tin tức GIẢ"
93
+ color = "red" # Thường dùng màu đỏ cho tin giả
94
 
95
  confidence = round(max(prediction_proba) * 100, 2)
96