import streamlit as st import pandas as pd import numpy as np import neattext.functions as nfx from tensorflow.keras.models import load_model import pickle from textblob import TextBlob import os import nltk import plotly.graph_objects as go # --- NLTK / TEXTBLOB HATA ÇÖZÜCÜ --- @st.cache_resource def download_nltk_data(): try: nltk.download('punkt') nltk.download('wordnet') nltk.download('omw-1.4') nltk.download('punkt_tab') from textblob import download_corpora download_corpora.download_all() except Exception as e: st.error(f"Paket yükleme hatası: {e}") download_nltk_data() # --- PICKLE İÇİN GEREKLİ FONKSİYON --- def ekkok(title): try: return [word.lemmatize() for word in TextBlob(title).words] except: return title.split() # --- SAYFA AYARLARI --- st.set_page_config(page_title="News Classifier", layout="wide") # --- MODEL VE DOSYALARI YÜKLEME --- @st.cache_resource def load_assets(): model_path = "news_classification_model.h5" vect_path = "tfidf_vectorizer.pkl" le_path = "label_encoder.pkl" if not all(os.path.exists(p) for p in [model_path, vect_path, le_path]): st.error("⚠️ Model dosyaları bulunamadı!") st.stop() model = load_model(model_path) with open(vect_path, "rb") as f: vect = pickle.load(f) with open(le_path, "rb") as f: le = pickle.load(f) return model, vect, le model, vect, le = load_assets() # --- TAHMİN FONKSİYONU --- def predict_news(text): clean_text = nfx.clean_text(text.lower()) matrix = vect.transform([clean_text]).toarray() prediction = model.predict(matrix, verbose=0) class_index = np.argmax(prediction) prob = np.max(prediction) category = le.inverse_transform([class_index])[0] return category, prob, prediction[0] # --- SIDEBAR (SOL PANEL) --- st.sidebar.title("📌 Samples / Örnekler") all_examples = { "Science / Bilim": [ "NASA's Perseverance rover successfully collects high-priority rock samples from the Martian surface.", "The James Webb Space Telescope captures stunning new images of a distant star-forming nebula.", "Astronomers discover a new solar system with three potentially habitable planets." ], "Tech / Teknoloji": [ "Apple announces new AI-powered features for the upcoming iPhone 18 Pro series.", "OpenAI releases a new language model that can reason like a human expert.", "Scientists develop a new quantum computer that performs calculations in seconds." ], "Sports / Spor": [ "Manchester City secures a narrow victory against Arsenal in a thrilling Premier League match.", "The Olympic Committee announces the final list of cities bidding for the 2032 Games.", "Formula 1 introduces new sustainable fuel regulations to be implemented by 2026." ], "Business / Ekonomi": [ "Global stock markets rally as central banks signal potential interest rate cuts.", "The tech industry faces new regulations regarding data privacy and user security.", "Gold prices hit an all-time high amidst global economic uncertainty and inflation." ], "Health / Sağlık": [ "New clinical trials show a 90% success rate in a breakthrough cancer treatment.", "Doctors recommend daily exercise and a balanced diet to prevent heart disease.", "A new study reveals the long-term impact of sleep deprivation on mental health." ] } selected_cat = st.sidebar.selectbox("Select Category / Kategori Seçin:", [""] + list(all_examples.keys())) if selected_cat != "": st.sidebar.markdown(f"### {selected_cat} Samples / Örnekleri:") # İSTEDİĞİN DÜZELTME BURADA: st.sidebar.write("Click to copy / Kopyalamak üzere tıklayın:") for i, ex in enumerate(all_examples[selected_cat], 1): st.sidebar.info(f"Example / Örnek {i}:") st.sidebar.code(ex, language=None) # --- ANA SAYFA --- st.title("📰 Multidisciplinary News Classifier / Çok Disiplinli Haber Sınıflandırıcı") st.markdown("---") user_input = st.text_area("News Headline / Haber Başlığı:", height=150, placeholder="Copy an example from the left and paste it here... / Sol taraftan bir örnek kopyalayıp buraya yapıştırın...") if st.button("Predict / Tahmin Et"): if user_input.strip() != "": with st.spinner('Analiz ediliyor / Processing...'): category, confidence, all_probs = predict_news(user_input) try: translated = str(TextBlob(user_input).translate(from_lang='en', to='tr')) except: translated = "Çeviri şu an yapılamıyor / Translation failed." st.balloons() st.info(f"**Original / Orijinal:** {user_input}\n\n**Turkish Translation / Türkçe Çeviri:** *{translated}*") st.markdown("---") res_col1, res_col2 = st.columns(2) res_col1.success(f"**Predicted Category / Tahmin Edilen Kategori:**\n### {category}") res_col2.warning(f"**Confidence Score / Güven Oranı:**\n### %{confidence*100:.2f}") labels = le.classes_ fig = go.Figure(go.Bar( x=all_probs, y=labels, orientation='h', marker_color='#1F77B4', text=[f"%{p*100:.1f}" for p in all_probs], textposition='auto' )) fig.update_layout(title="Probability Graph / Olasılık Grafiği", height=350) st.plotly_chart(fig, use_container_width=True) else: st.warning("⚠️ Please enter a headline! / Lütfen bir haber başlığı girin!")