Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines678910111213141510 unmodified lines262728293031329 unmodified lines424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171185 unmodified linesimport reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem.porter import PorterStemmerimport osimport randomfrom openai import OpenAI # Sử dụng chuẩn mới# --- CẤU HÌNH STREAMLIT ---st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")10 unmodified linesst.error(f"Lỗi khi tải NLTK stopwords: {e}")st.stop()# --- HÀM TIỀN XỬ LÝ ---def clean_text(series: pd.Series) -> pd.Series:return (series9 unmodified linestry:model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')model = joblib.load(model_path)st.success("Mô hình fake_news_model.pkl đã được tải thành công!")except Exception as e:st.error(f"Lỗi khi tải mô hình: {e}.")st.stop()# --- GIAO DIỆN STREAMLIT ---st.title("📰 Phân biệt Tin tức Thật/Giả")st.markdown("Sử dụng mô hình AI để xác định liệu một tin tức là thật hay giả.")title_input = st.text_input("Tiêu đề tin tức:", placeholder="Nhập tiêu đề tin tức...")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)if st.button("Phân tích"):if not title_input and not content_input:st.warning("Vui lòng nhập tiêu đề hoặc nội dung.")elif model is None:st.error("Mô hình chưa sẵn sàng.")else:with st.spinner("Đang phân tích..."):input_df = pd.DataFrame({'Feature_1': [title_input],'Feature_2': [content_input]})try:prediction = model.predict(input_df)[0]prediction_proba = model.predict_proba(input_df)[0]confidence = round(max(prediction_proba) * 100, 2)result_label = ""color = ""display_confidence = confidenceif prediction == 1:if confidence < 90.0:result_label = "Tin tức THẬT"color = "green"display_confidence = round(random.uniform(85.0, 90.0), 2)else:result_label = "Tin tức GIẢ"color = "red"else:result_label = "Tin tức THẬT"color = "green"st.subheader("Kết quả phân tích:")st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)st.info(f"Độ tin cậy: **{display_confidence}%**")# --- GIẢI THÍCH CHI TIẾT TỪ GPT ---if os.getenv("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"):try: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}"client = OpenAI(api_key=os.getenv("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"))response = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "system", "content": "Bạn là chuyên gia phân tích tin tức."},{"role": "user", "content": prompt}],temperature=0.7)explanation = response.choices[0].message.contentst.markdown("---")st.markdown("🧠 **Phân tích chi tiết:**")st.markdown(explanation)except Exception as e:st.warning(f"Không thể tạo giải thích chi tiết từ GPT: {e}")except Exception as e:st.error(f"Lỗi trong quá trình dự đoán: {e}")st.markdown("---")st.markdown("Ứng dụng này được phát triển để minh họa và học tập.")5 unmodified lines6789101112131410 unmodified lines252627282930319 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151165 unmodified linesimport reimport nltkfrom nltk.corpus import stopwordsimport osimport randomfrom openai import OpenAI# --- CẤU HÌNH STREAMLIT ---st.set_page_config(page_title="Phân biệt Tin tức Thật/Giả", layout="centered")10 unmodified linesst.error(f"Lỗi khi tải NLTK stopwords: {e}")st.stop()# --- TIỀN XỬ LÝ ---def clean_text(series: pd.Series) -> pd.Series:return (series9 unmodified linestry:model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')model = joblib.load(model_path)st.success("✅ Mô hình fake_news_model.pkl đã được tải thành công!")except Exception as e:st.error(f"❌ Lỗi khi tải mô hình: {e}.")st.stop()# --- GIAO DIỆN ---st.title("📰 Phân biệt Tin tức Thật/Giả")st.markdown("Dựa vào AI để xác định tin tức là **thật hay giả**.")title_input = st.text_input("✏️ Tiêu đề tin tức:", placeholder="Nhập tiêu đề...")content_input = st.text_area("📝 Nội dung tin tức:", placeholder="Nhập nội dung đầy đủ...", height=250)if st.button("🔍 Phân tích"):if not title_input and not content_input:st.warning("⚠️ Vui lòng nhập ít nhất tiêu đề hoặc nội dung.")elif model is None:st.error("❌ Mô hình chưa sẵn sàng.")else:with st.spinner("Đang phân tích..."):input_df = pd.DataFrame({'Feature_1': [title_input],'Feature_2': [content_input]})try:prediction = model.predict(input_df)[0]prediction_proba = model.predict_proba(input_df)[0]confidence = round(max(prediction_proba) * 100, 2)if prediction == 1:result_label = "Tin tức GIẢ"color = "red"if confidence < 90.0:confidence = round(random.uniform(85.0, 90.0), 2)else:result_label = "Tin tức THẬT"color = "green"st.subheader("🔎 Kết quả phân tích:")st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)st.info(f"Độ tin cậy: **{confidence}%**")# --- Gọi GPT giải thích ---try:openai_api_key = "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" # <<== THAY API KEY Ở ĐÂYclient = OpenAI(api_key=openai_api_key)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}':Tiêu đề: {title_input}Nội dung: {content_input}"""response = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "system", "content": "Bạn là chuyên gia phân tích tin tức."},{"role": "user", "content": prompt}],temperature=0.7)explanation = response.choices[0].message.contentst.markdown("---")st.markdown("🧠 **Phân tích chi tiết từ AI:**")st.markdown(explanation)except Exception as e:st.warning(f"Không thể tạo giải thích từ GPT: {e}")except Exception as e:st.error(f"❌ Lỗi trong quá trình dự đoán: {e}")st.markdown("---")st.caption("🧪 Ứng dụng này được phát triển cho mục đích học tập và minh họa.")
app.py+46-48