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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -50
app.py CHANGED
@@ -1,5 +1,3 @@
1
- # --- app.py ---
2
-
3
  import streamlit as st
4
  import joblib
5
  import pandas as pd
@@ -8,12 +6,13 @@ 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")
15
 
16
- # --- TẢI DỮ LIỆU NLTK ---
17
  nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')
18
  os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)
19
  nltk.data.path.append(nltk_data_path)
@@ -25,7 +24,7 @@ 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Ý ---
29
  def clean_text(series: pd.Series) -> pd.Series:
30
  return (
31
  series
@@ -36,81 +35,91 @@ def clean_text(series: pd.Series) -> pd.Series:
36
  .str.strip()
37
  )
38
 
39
- # --- TẢI MÔ HÌNH ---
40
  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]
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.")
 
 
 
1
  import streamlit as st
2
  import joblib
3
  import pandas as pd
 
6
  from nltk.corpus import stopwords
7
  import os
8
  import random
 
9
 
10
+ from transformers import pipeline
11
+
12
+ # CẤU HÌNH STREAMLIT
13
  st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")
14
 
15
+ # TẢI 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)
 
24
  st.error(f"Lỗi khi tải NLTK stopwords: {e}")
25
  st.stop()
26
 
27
+ # TIỀN XỬ LÝ
28
  def clean_text(series: pd.Series) -> pd.Series:
29
  return (
30
  series
 
35
  .str.strip()
36
  )
37
 
38
+ # TẢI MÔ HÌNH DỰ ĐOÁN FAKE/REAL
39
  model = None
40
  try:
41
  model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')
42
  model = joblib.load(model_path)
43
+ st.success("Mô hình fake_news_model.pkl đã được tải thành công!")
44
  except Exception as e:
45
+ st.error(f"Lỗi khi tải mô hình: {e}")
46
  st.stop()
47
 
48
+ # TẢI MÔ HÌNH LLaMA 3 TỪ HUGGING FACE
49
+ @st.cache_resource
50
+ def load_llama_pipeline():
51
+ try:
52
+ return pipeline(
53
+ "text-generation",
54
+ model="meta-llama/Meta-Llama-3-8B-Instruct",
55
+ device=0 if torch.cuda.is_available() else -1,
56
+ max_new_tokens=200,
57
+ temperature=0.7
58
+ )
59
+ except Exception as e:
60
+ st.warning(f"Lỗi khi tải mô hình LLaMA: {e}")
61
+ return None
62
+
63
+ llama = load_llama_pipeline()
64
+
65
+ # GIAO DIỆN STREAMLIT
66
  st.title("📰 Phân biệt Tin tức Thật/Giả")
67
+ st.markdown("Sử dụng AI để xác định liệu một tin tức là thật hay giả.")
68
 
69
+ title_input = st.text_input("Tiêu đề tin tức:", placeholder="Nhập tiêu đề tin tức...")
70
+ 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)
71
 
72
+ if st.button("Phân tích"):
73
  if not title_input and not content_input:
74
+ st.warning("Vui lòng nhập tiêu đề hoặc nội dung.")
75
  elif model is None:
76
+ st.error("Mô hình chưa sẵn sàng.")
77
  else:
78
  with st.spinner("Đang phân tích..."):
79
  input_df = pd.DataFrame({
80
  'Feature_1': [title_input],
81
  'Feature_2': [content_input]
82
  })
 
83
  try:
84
  prediction = model.predict(input_df)[0]
85
  prediction_proba = model.predict_proba(input_df)[0]
86
+
87
  confidence = round(max(prediction_proba) * 100, 2)
88
 
89
  if prediction == 1:
90
+ result_label = "Tin tức GIẢ" if confidence >= 90 else "Tin tức THẬT"
91
+ color = "red" if result_label == "Tin tức GIẢ" else "green"
 
 
92
  else:
93
  result_label = "Tin tức THẬT"
94
  color = "green"
95
 
96
+ st.subheader("Kết quả phân tích:")
97
  st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)
98
  st.info(f"Độ tin cậy: **{confidence}%**")
99
 
100
+ # TẠO GIẢI THÍCH CHI TIẾT
101
+ if llama:
102
+ with st.spinner("Đang tạo giải thích từ AI..."):
103
+ prompt = f"""You are a news analysis assistant. Explain why the following news article is considered '{result_label}'.
104
+
105
+ Title: {title_input}
106
+
107
+ Content: {content_input}
108
+
109
+ Answer:"""
110
+ try:
111
+ response = llama(prompt)[0]["generated_text"]
112
+ explanation = response.replace(prompt, "").strip()
113
+ st.markdown("---")
114
+ st.markdown("🧠 **Phân tích chi tiết:**")
115
+ st.markdown(explanation)
116
+ except Exception as e:
117
+ st.warning(f"Không thể tạo giải thích chi tiết từ LLaMA: {e}")
118
+ else:
119
+ st.warning("Mô hình LLaMA chưa sẵn sàng hoặc bị lỗi.")
120
+
 
 
 
 
 
121
  except Exception as e:
122
+ st.error(f"Lỗi trong quá trình dự đoán: {e}")
123
 
124
  st.markdown("---")
125
+ st.markdown("Ứng dụng này được phát triển phục vụ học tập và minh họa mô hình AI.")