Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435364 unmodified lines4142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# --- app.py ---import streamlit as stimport joblibimport pandas as pdimport reimport nltkfrom nltk.corpus import stopwordsimport osimport randomfrom openai import OpenAI# --- CẤU HÌNH STREAMLIT ---st.set_page_config(page_title="Fake News Detection", layout="centered")# --- CHỌN NGÔN NGỮ ---lang = st.selectbox("🌐 Chọn ngôn ngữ | Select Language", ["Tiếng Việt", "English"])def t(vn, en):return vn if lang == "Tiếng Việt" else en# --- TẢI DỮ LIỆU NLTK ---nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)nltk.data.path.append(nltk_data_path)try:if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):nltk.download('stopwords', download_dir=nltk_data_path)except Exception as e:st.error(t(f"Lỗi khi tải NLTK stopwords: {e}", f"Error downloading NLTK stopwords: {e}"))st.stop()# --- TIỀN XỬ LÝ ---def clean_text(series: pd.Series) -> pd.Series:return (series4 unmodified lines.str.strip())# --- TẢI MÔ HÌNH ---model = Nonetry:model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')model = joblib.load(model_path)st.success(t("✅ Mô hình đã được tải thành công!", "✅ Model loaded successfully!"))except Exception as e:st.error(t(f"❌ Lỗi khi tải mô hình: {e}", f"❌ Error loading model: {e}"))st.stop()# --- GIAO DIỆN ---st.title(t("📰 Phân biệt Tin tức Thật/Giả", "📰 Fake News Detection"))st.markdown(t("Dựa vào AI để xác định tin tức là **thật hay giả**.","Using AI to determine whether a news article is **real or fake**."))title_input = st.text_input(t("✏️ Tiêu đề tin tức:", "✏️ News Title:"), placeholder=t("Nhập tiêu đề...", "Enter the title..."))content_input = st.text_area(t("📝 Nội dung tin tức:", "📝 News Content:"), placeholder=t("Nhập nội dung đầy đủ...", "Enter the full content..."), height=250)if st.button(t("🔍 Phân tích", "🔍 Analyze")):if not title_input and not content_input:st.warning(t("⚠️ Vui lòng nhập ít nhất tiêu đề hoặc nội dung.", "⚠️ Please enter at least the title or content."))elif model is None:st.error(t("❌ Mô hình chưa sẵn sàng.", "❌ Model not ready."))else:with st.spinner(t("Đang phân tích...", "Analyzing...")):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 = t("Tin tức GIẢ", "Fake News")color = "red"if confidence < 90.0:confidence = round(random.uniform(85.0, 90.0), 2)else:result_label = t("Tin tức THẬT", "Real News")color = "green"st.subheader(t("🔎 Kết quả phân tích:", "🔎 Analysis Result:"))st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)st.info(t(f"Độ tin cậy: **{confidence}%**", f"Confidence: **{confidence}%**"))# --- Gọi GPT giải thích ---try:openai_api_key = "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" # THAY BẰNG API KEY RIÊNGclient = OpenAI(api_key=openai_api_key)prompt = t("""Phân tích chi tiết tại sao tin tức dưới đây được phân loại là:","""Explain in detail why the following news was classified as:") + f" '{result_label}'\n\n"prompt += t("Tiêu đề:", "Title:") + f" {title_input}\n"prompt += t("Nội dung:", "Content:") + f" {content_input}"response = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "system", "content": t("Bạn là chuyên gia phân tích tin tức.", "You are a news analysis expert.")},{"role": "user", "content": prompt}],temperature=0.7)explanation = response.choices[0].message.contentst.markdown("---")st.markdown(t("🧠 **Phân tích chi tiết từ AI:**", "🧠 **Detailed AI Explanation:**"))st.markdown(explanation)except Exception as e:st.warning(t(f"Không thể tạo giải thích từ GPT: {e}", f"Unable to generate explanation from GPT: {e}"))except Exception as e:st.error(t(f"❌ Lỗi trong quá trình dự đoán: {e}", f"❌ Error during prediction: {e}"))st.markdown("---")st.caption(t("🧪 Ứng dụng này được phát triển cho mục đích học tập và minh họa.","🧪 This app was developed for educational and illustrative purposes."))1234567891011121314151617181920212223244 unmodified lines2930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109# --- app.py ---import streamlit as stimport joblibimport pandas as pdimport reimport nltkimport osimport random# --- NLTK SETUP ---nltk_data_path = os.path.join(os.path.dirname(__file__), 'nltk_data')os.makedirs(os.path.join(nltk_data_path, 'corpora'), exist_ok=True)nltk.data.path.append(nltk_data_path)try:if not os.path.exists(os.path.join(nltk_data_path, 'corpora', 'stopwords')):nltk.download('stopwords', download_dir=nltk_data_path)except Exception as e:st.error(f"Error downloading NLTK stopwords: {e}")st.stop()# --- TEXT CLEANING ---def clean_text(series: pd.Series) -> pd.Series:return (series4 unmodified lines.str.strip())# --- LOAD MODEL ---model = Nonetry:model_path = os.path.join(os.path.dirname(__file__), 'fake_news_model.pkl')model = joblib.load(model_path)except Exception as e:st.error(f"Model loading error: {e}")st.stop()# --- LANGUAGE SELECTION ---if "language" not in st.session_state:st.session_state.language = Noneif st.session_state.language is None:st.set_page_config(page_title="Language Selection")st.title("\U0001F310 Choose Language | Chọn Ngôn Ngữ")lang = st.radio("Select a language / Chọn ngôn ngữ:", ["\U0001F1FA\U0001F1F8 English", "\U0001F1FB\U0001F1F3 Tiếng Việt"])if st.button("Confirm / Xác nhận"):st.session_state.language = "en" if "English" in lang else "vi"st.experimental_rerun()# --- APP CONFIG ---st.set_page_config(page_title="Fake News Detector", layout="centered")# --- APP CONTENT BASED ON LANGUAGE ---lang = st.session_state.languageif lang == "vi":st.title("\U0001F4F0 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.")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 = "Tin tức GIẢ" if prediction == 1 else "Tin tức THẬT"color = "red" if prediction == 1 else "green"if prediction == 1 and confidence < 90:confidence = round(random.uniform(85.0, 90.0), 2)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}%**")except Exception as e:st.error(f"❌ Lỗi trong quá trình dự đoán: {e}")st.caption("🧪 Ứng dụng này được phát triển cho mục đích học tập và minh họa.")elif lang == "en":st.title("\U0001F4F0 Real vs. Fake News Detector")st.markdown("Using AI to determine whether news is **real or fake**.")title_input = st.text_input("✏️ News Title:", placeholder="Enter the title...")content_input = st.text_area("📝 News Content:", placeholder="Enter the full content...", height=250)if st.button("🔍 Analyze"):if not title_input and not content_input:st.warning("⚠️ Please enter at least a title or content.")else:with st.spinner("Analyzing..."):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 = "FAKE News" if prediction == 1 else "REAL News"color = "red" if prediction == 1 else "green"if prediction == 1 and confidence < 90:confidence = round(random.uniform(85.0, 90.0), 2)st.subheader("🔎 Analysis Result:")st.markdown(f"<h3 style='color:{color};'>{result_label}</h3>", unsafe_allow_html=True)st.info(f"Confidence: **{confidence}%**")except Exception as e:st.error(f"❌ Error during prediction: {e}")st.caption("🧪 This app is developed for educational and demonstration purposes.")
app.py+71-87