Nolist commited on
Commit
d509064
·
verified ·
1 Parent(s): 1726379

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ 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ài đặt và tải tài nguyên NLTK (quan trọng cho môi trường Docker) ---
11
+ # Tải stopwords vào thư mục con 'nltk_data'
12
+ # Điều này giúp Dockerfile dễ dàng sao chép và NLTK tìm thấy chúng
13
+ nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
14
+
15
+ # Đảm bảo thư mục tồn tại
16
+ os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
17
+ # Thêm đường dẫn này để NLTK tìm kiếm
18
+ nltk.data.path.append(nltk_data_path)
19
+
20
+ # Cố gắng tải stopwords
21
+ 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() # Dừng ứng dụng nếu không tải được
27
+
28
+ # --- Tải mô hình ---
29
+ model = None
30
+ try:
31
+ model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
32
+ model = joblib.load(model_path)
33
+ st.success("Mô hình fake_news_model.pkl đã được tải thành công!")
34
+ except Exception as e:
35
+ st.error(f"Lỗi khi tải mô hình: {e}. Vui lòng đảm bảo file mô hình nằm cùng thư mục với app.py.")
36
+ st.stop() # Dừng ứng dụng nếu mô hình không tải được
37
+
38
+ # --- Khởi tạo Stemmer và Stopwords ---
39
+ ps = PorterStemmer()
40
+ # Đảm bảo NLTK tìm thấy stopwords từ đường dẫn đã chỉ định
41
+ try:
42
+ stop_words = set(stopwords.words('english'))
43
+ except Exception as e:
44
+ st.error(f"Lỗi khi tải stop words NLTK: {e}. Đảm bảo 'stopwords' đã được tải.")
45
+ st.stop()
46
+
47
+ # --- Hàm tiền xử lý văn bản (PHẢI GIỐNG VỚI LÚC TRAIN) ---
48
+ def preprocess_text(text):
49
+ if not isinstance(text, str):
50
+ return ""
51
+ text = text.lower()
52
+ text = re.sub('[^a-zA-Z]', ' ', text)
53
+ words = text.split()
54
+ words = [ps.stem(word) for word in words if word not in stop_words]
55
+ return ' '.join(words)
56
+
57
+ # --- Giao diện Streamlit ---
58
+ st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
59
+
60
+ st.title("📰 Phân biệt Tin tức Thật/Giả")
61
+ 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ả.")
62
+
63
+ # Ô nhập tiêu đề
64
+ title_input = st.text_input("Tiêu đề tin tức:", placeholder="Nhập tiêu đề tin tức...")
65
+
66
+ # Ô nhập nội dung
67
+ 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)
68
+
69
+ # Nút Analyze
70
+ if st.button("Phân tích"):
71
+ if not title_input and not content_input:
72
+ st.warning("Vui lòng nhập tiêu đề hoặc nội dung tin tức để phân tích.")
73
+ elif model is None:
74
+ 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.")
75
+ else:
76
+ with st.spinner("Đang phân tích tin tức..."):
77
+ combined_text = title_input + " " + content_input
78
+ processed_text = preprocess_text(combined_text)
79
+
80
+ try:
81
+ # Giả định mô hình của bạn đã được huấn luyện để nhận một danh sách các chuỗi đã tiền xử lý
82
+ # Nếu mô hình của bạn cần một TfidfVectorizer riêng, bạn cần tải nó và chuyển đổi processed_text
83
+ prediction = model.predict([processed_text])[0]
84
+ prediction_proba = model.predict_proba([processed_text])[0]
85
+
86
+ # === ĐIỀU CHỈNH LOGIC Ở ĐÂY DỰA TRÊN 1=FAKE, 0=TRUE ===
87
+ if prediction == 1: # Nếu prediction là 1, đó là TIN GIẢ
88
+ result_label = "Tin tức GIẢ"
89
+ color = "red"
90
+ else: # Nếu prediction là 0, đó là TIN THẬT
91
+ result_label = "Tin tức THẬT"
92
+ color = "green"
93
+ # =======================================================
94
+
95
+ # Lấy độ tin cậy của lớp được dự đoán
96
+ # Nếu prediction là 1 (FAKE), lấy xác suất của lớp 1
97
+ # Nếu prediction là 0 (TRUE), lấy xác suất của lớp 0
98
+ confidence = round(prediction_proba[prediction] * 100, 2)
99
+
100
+
101
+ st.subheader("Kết quả phân tích:")
102
+ st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
103
+ st.info(f"Độ tin cậy: **{confidence}%**")
104
+
105
+ except Exception as e:
106
+ st.error(f"Đã xảy ra lỗi trong quá trình dự đoán: {e}")
107
+
108
+ st.markdown("---")
109
+ st.markdown("Ứng dụng này được phát triển để mục đích minh họa và học tập.")