Update app.py
Browse files
app.py
CHANGED
|
@@ -1,181 +1,147 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
-
import neattext.functions as nfx
|
| 5 |
-
from tensorflow.keras.models import load_model
|
| 6 |
-
import pickle
|
| 7 |
-
from textblob import TextBlob
|
| 8 |
-
import os
|
| 9 |
-
import nltk
|
| 10 |
-
import plotly.graph_objects as go
|
| 11 |
-
|
| 12 |
-
# --- NLTK
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
#
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
# ---
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
category = le.inverse_transform([class_index])[0]
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
"
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
"
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
"
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
#
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
st.
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
#
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
#
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
st.warning(f"**Confidence Score / Güven Oranı:**\n\n## %{confidence*100:.2f}")
|
| 149 |
-
|
| 150 |
-
# 6. Grafik Ekleme (Plotly ile Şık ve Renkli Görünüm)
|
| 151 |
-
st.markdown("#### Probability Distribution / Olasılık Dağılımı")
|
| 152 |
-
|
| 153 |
-
# Etiketler ve olasılıklar
|
| 154 |
-
labels = le.classes_
|
| 155 |
-
|
| 156 |
-
# --- GRAFİK RENGİ MAVİ OLSUN ---
|
| 157 |
-
fig = go.Figure(go.Bar(
|
| 158 |
-
x=all_probs,
|
| 159 |
-
y=labels,
|
| 160 |
-
orientation='h',
|
| 161 |
-
marker_color='#1F77B4', # Mazarine Blue / Mavi Renk Kodu
|
| 162 |
-
text=[f"%{p*100:.1f}" for p in all_probs],
|
| 163 |
-
textposition='auto'
|
| 164 |
-
))
|
| 165 |
-
|
| 166 |
-
fig.update_layout(
|
| 167 |
-
title="Category Probabilities / Kategori Olasılıkları",
|
| 168 |
-
xaxis_title="Confidence / Güven",
|
| 169 |
-
yaxis_title="Categories / Kategoriler",
|
| 170 |
-
height=400,
|
| 171 |
-
margin=dict(l=20, r=20, t=40, b=20)
|
| 172 |
-
)
|
| 173 |
-
|
| 174 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 175 |
-
|
| 176 |
-
else:
|
| 177 |
-
st.warning("⚠️ Lütfen bir haber başlığı girin! / Please enter a headline!")
|
| 178 |
-
|
| 179 |
-
# Footer / Alt Bilgi
|
| 180 |
-
st.markdown("---")
|
| 181 |
-
st.caption("Deep Learning News Classification Project - Powered by Mergen")
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import neattext.functions as nfx
|
| 5 |
+
from tensorflow.keras.models import load_model
|
| 6 |
+
import pickle
|
| 7 |
+
from textblob import TextBlob
|
| 8 |
+
import os
|
| 9 |
+
import nltk
|
| 10 |
+
import plotly.graph_objects as go
|
| 11 |
+
|
| 12 |
+
# --- NLTK / TEXTBLOB HATA ÇÖZÜCÜ (KRİTİK KISIM) ---
|
| 13 |
+
@st.cache_resource
|
| 14 |
+
def download_nltk_data():
|
| 15 |
+
try:
|
| 16 |
+
nltk.download('punkt')
|
| 17 |
+
nltk.download('wordnet')
|
| 18 |
+
nltk.download('omw-1.4')
|
| 19 |
+
nltk.download('punkt_tab')
|
| 20 |
+
# TextBlob'un içsel corpora'sını zorla yükle
|
| 21 |
+
from textblob import download_corpora
|
| 22 |
+
download_corpora.download_all()
|
| 23 |
+
except Exception as e:
|
| 24 |
+
st.error(f"Paket yükleme hatası: {e}")
|
| 25 |
+
|
| 26 |
+
download_nltk_data()
|
| 27 |
+
|
| 28 |
+
# --- PICKLE İÇİN GEREKLİ FONKSİYON ---
|
| 29 |
+
def ekkok(title):
|
| 30 |
+
try:
|
| 31 |
+
return [word.lemmatize() for word in TextBlob(title).words]
|
| 32 |
+
except:
|
| 33 |
+
return title.split()
|
| 34 |
+
|
| 35 |
+
# --- SAYFA AYARLARI ---
|
| 36 |
+
st.set_page_config(page_title="News Classifier", layout="wide")
|
| 37 |
+
|
| 38 |
+
# --- MODEL VE DOSYALARI YÜKLEME ---
|
| 39 |
+
@st.cache_resource
|
| 40 |
+
def load_assets():
|
| 41 |
+
model_path = "news_classification_model.h5"
|
| 42 |
+
vect_path = "tfidf_vectorizer.pkl"
|
| 43 |
+
le_path = "label_encoder.pkl"
|
| 44 |
+
|
| 45 |
+
if not all(os.path.exists(p) for p in [model_path, vect_path, le_path]):
|
| 46 |
+
st.error("⚠️ Model dosyaları bulunamadı!")
|
| 47 |
+
st.stop()
|
| 48 |
+
|
| 49 |
+
model = load_model(model_path)
|
| 50 |
+
with open(vect_path, "rb") as f:
|
| 51 |
+
vect = pickle.load(f)
|
| 52 |
+
with open(le_path, "rb") as f:
|
| 53 |
+
le = pickle.load(f)
|
| 54 |
+
return model, vect, le
|
| 55 |
+
|
| 56 |
+
model, vect, le = load_assets()
|
| 57 |
+
|
| 58 |
+
# --- TAHMİN FONKSİYONU ---
|
| 59 |
+
def predict_news(text):
|
| 60 |
+
clean_text = nfx.clean_text(text.lower())
|
| 61 |
+
matrix = vect.transform([clean_text]).toarray()
|
| 62 |
+
prediction = model.predict(matrix, verbose=0)
|
| 63 |
+
class_index = np.argmax(prediction)
|
| 64 |
+
prob = np.max(prediction)
|
| 65 |
+
category = le.inverse_transform([class_index])[0]
|
| 66 |
+
return category, prob, prediction[0]
|
| 67 |
+
|
| 68 |
+
# --- SIDEBAR (SOL PANEL) ---
|
| 69 |
+
st.sidebar.title("📌 Samples / Örnekler")
|
| 70 |
+
|
| 71 |
+
all_examples = {
|
| 72 |
+
"Science / Bilim": [
|
| 73 |
+
"NASA's Perseverance rover successfully collects high-priority rock samples from the Martian surface.",
|
| 74 |
+
"The James Webb Space Telescope captures stunning new images of a distant star-forming nebula.",
|
| 75 |
+
"Astronomers discover a new solar system with three potentially habitable planets."
|
| 76 |
+
],
|
| 77 |
+
"Tech / Teknoloji": [
|
| 78 |
+
"Apple announces new AI-powered features for the upcoming iPhone 18 Pro series.",
|
| 79 |
+
"OpenAI releases a new language model that can reason like a human expert.",
|
| 80 |
+
"Scientists develop a new quantum computer that performs calculations in seconds."
|
| 81 |
+
],
|
| 82 |
+
"Sports / Spor": [
|
| 83 |
+
"Manchester City secures a narrow victory against Arsenal in a thrilling Premier League match.",
|
| 84 |
+
"The Olympic Committee announces the final list of cities bidding for the 2032 Games.",
|
| 85 |
+
"Formula 1 introduces new sustainable fuel regulations to be implemented by 2026."
|
| 86 |
+
],
|
| 87 |
+
"Business / Ekonomi": [
|
| 88 |
+
"Global stock markets rally as central banks signal potential interest rate cuts.",
|
| 89 |
+
"The tech industry faces new regulations regarding data privacy and user security.",
|
| 90 |
+
"Gold prices hit an all-time high amidst global economic uncertainty and inflation."
|
| 91 |
+
],
|
| 92 |
+
"Health / Sağlık": [
|
| 93 |
+
"New clinical trials show a 90% success rate in a breakthrough cancer treatment.",
|
| 94 |
+
"Doctors recommend daily exercise and a balanced diet to prevent heart disease.",
|
| 95 |
+
"A new study reveals the long-term impact of sleep deprivation on mental health."
|
| 96 |
+
]
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
selected_cat = st.sidebar.selectbox("Select Category / Kategori Seçin:", [""] + list(all_examples.keys()))
|
| 100 |
+
|
| 101 |
+
if selected_cat != "":
|
| 102 |
+
st.sidebar.markdown(f"### {selected_cat} Örnekleri:")
|
| 103 |
+
st.sidebar.write("Kopyalamak için üzerine tıklayın:")
|
| 104 |
+
for i, ex in enumerate(all_examples[selected_cat], 1):
|
| 105 |
+
st.sidebar.info(f"Örnek {i}:")
|
| 106 |
+
st.sidebar.code(ex, language=None)
|
| 107 |
+
|
| 108 |
+
# --- ANA SAYFA ---
|
| 109 |
+
st.title("📰 Multidisciplinary News Classifier")
|
| 110 |
+
st.markdown("---")
|
| 111 |
+
|
| 112 |
+
user_input = st.text_area("News Headline / Haber Başlığı:", height=150, placeholder="Sol taraftan bir örnek kopyalayıp buraya yapıştırın...")
|
| 113 |
+
|
| 114 |
+
if st.button("Predict / Tahmin Et"):
|
| 115 |
+
if user_input.strip() != "":
|
| 116 |
+
with st.spinner('Analiz ediliyor...'):
|
| 117 |
+
# 1. Tahmin
|
| 118 |
+
category, confidence, all_probs = predict_news(user_input)
|
| 119 |
+
|
| 120 |
+
# 2. Çeviri (Hatasız Yöntem)
|
| 121 |
+
try:
|
| 122 |
+
translated = str(TextBlob(user_input).translate(from_lang='en', to='tr'))
|
| 123 |
+
except:
|
| 124 |
+
translated = "Çeviri şu an yapılamıyor (Bağlantı hatası)."
|
| 125 |
+
|
| 126 |
+
st.balloons()
|
| 127 |
+
|
| 128 |
+
# 3. Haber ve Çeviri Gösterimi
|
| 129 |
+
st.info(f"**Original:** {user_input}\n\n**Türkçe Çeviri:** *{translated}*")
|
| 130 |
+
st.markdown("---")
|
| 131 |
+
|
| 132 |
+
# 4. Sonuçlar
|
| 133 |
+
res_col1, res_col2 = st.columns(2)
|
| 134 |
+
res_col1.success(f"**Category / Kategori:**\n### {category}")
|
| 135 |
+
res_col2.warning(f"**Confidence / Güven:**\n### %{confidence*100:.2f}")
|
| 136 |
+
|
| 137 |
+
# 5. Mavi Grafik
|
| 138 |
+
labels = le.classes_
|
| 139 |
+
fig = go.Figure(go.Bar(
|
| 140 |
+
x=all_probs, y=labels, orientation='h',
|
| 141 |
+
marker_color='#1F77B4', # Mavi Renk
|
| 142 |
+
text=[f"%{p*100:.1f}" for p in all_probs], textposition='auto'
|
| 143 |
+
))
|
| 144 |
+
fig.update_layout(title="Probability Graph / Olasılık Grafiği", height=350)
|
| 145 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 146 |
+
else:
|
| 147 |
+
st.warning("⚠️ Lütfen bir haber başlığı girin!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|