eMulayim/Airline_Sentiment_Classification
0
1import streamlit as st2import pandas as pd3import joblib4import os5import re6import nltk7from nltk.stem.porter import PorterStemmer8 9# --- Page Config ---10st.set_page_config(11 page_title="Airline Sentiment Analysis",12 page_icon="✈️",13 layout="wide"14)15 16# --- 1. Tokenizer Fonksiyonu (Model Yükleme için ZORUNLU) ---17# Model bu fonksiyonla eğitildiği için, yüklerken bu fonksiyonun18# tanımlı olması gerekir.19stemmer = PorterStemmer()20 21def stemming_tokenizer(text):22 # Sadece harfleri al23 text = re.sub(r"[^a-zA-Z]", " ", str(text))24 # Kelimelere böl25 tokens = text.split()26 # Stemming uygula27 stems = [stemmer.stem(word) for word in tokens]28 return stems29 30# --- 2. Akıllı Yol Bulucu (Local vs Hugging Face) ---31def resolve_model_path(filename):32 """33 Model dosyasını scriptin bulunduğu konuma göre arar.34 En garantili yöntem budur.35 """36 # 1. Şu an çalışan dosyanın (streamlit_app.py) tam yolunu bul37 current_script_dir = os.path.dirname(os.path.abspath(__file__))38 39 possible_paths = [40 # Seçenek 1: Script ile aynı klasörde (Sizin durumunuz: src/best_model.pkl)41 os.path.join(current_script_dir, filename), 42 43 # Seçenek 2: Çalışma dizininde (Root'ta ise)44 filename,45 46 # Seçenek 3: Localde üst klasördeki models altında47 os.path.join(current_script_dir, "..", "models", filename),48 49 # Seçenek 4: Çalışma dizininde models/ altında50 os.path.join("models", filename),51 ]52 53 for path in possible_paths:54 if os.path.exists(path):55 return path56 return None57 58# --- 3. Modeli Yükle ---59@st.cache_resource60def load_model():61 # Model ismini buraya yazıyoruz62 model_filename = "best_model.pkl"63 model_path = resolve_model_path(model_filename)64 65 if model_path:66 try:67 model = joblib.load(model_path)68 return model69 except Exception as e:70 st.error(f"Model yüklenirken hata oluştu: {e}")71 return None72 else:73 st.error(f"Model dosyası ('{model_filename}') bulunamadı! Lütfen dosya yolunu kontrol edin.")74 return None75 76# --- Main App ---77def main():78 st.title("✈️ Airline Sentiment Classification")79 st.markdown("Bu uygulama, havayolu tweetlerinin duygu durumunu (Positive, Negative, Neutral) tahmin eder.")80 81 model = load_model()82 83 if model is None:84 st.warning("Model dosyası bulunamadığı için uygulama başlatılamadı.")85 st.info("İpucu: Eğer localde `src` klasöründeysen modelin `../models/` altında olduğundan emin ol.")86 return87 88 tab1, tab2 = st.tabs(["✍️ Manuel Giriş", "📂 Toplu Tahmin (CSV)"])89 90 # --- TAB 1: Manuel Giriş ---91 with tab1:92 st.subheader("Tekli Tahmin")93 user_input = st.text_area("Tweet Metni Girin:", "The flight was amazing and the crew was helpful!")94 95 if st.button("Analiz Et"):96 if user_input:97 try:98 # Model pipeline olduğu için doğrudan metni veriyoruz99 # (Tokenizer pipeline içinde çalışacak)100 prediction = model.predict([user_input])[0]101 102 st.divider()103 104 # Renklendirme105 if prediction == "positive":106 st.success(f"Tahmin: {prediction.upper()} 😃")107 elif prediction == "negative":108 st.error(f"Tahmin: {prediction.upper()} 😡")109 else:110 st.warning(f"Tahmin: {prediction.upper()} 😐")111 112 # Olasılık değerleri (Eğer model destekliyorsa)113 if hasattr(model, "predict_proba"):114 proba = model.predict_proba([user_input])[0]115 classes = model.classes_116 proba_df = pd.DataFrame([proba], columns=classes)117 st.bar_chart(proba_df.T)118 119 except Exception as e:120 st.error(f"Tahmin Hatası: {e}")121 else:122 st.warning("Lütfen bir metin girin.")123 124 # --- TAB 2: Toplu İşlem ---125 with tab2:126 st.subheader("CSV ile Toplu Tahmin")127 uploaded_file = st.file_uploader("CSV Dosyası Yükle", type=["csv"])128 129 if uploaded_file:130 try:131 df = pd.read_csv(uploaded_file)132 st.write("Yüklenen Veri (İlk 5 satır):")133 st.dataframe(df.head())134 135 # Text kolonunu otomatik bulmaya çalış veya kullanıcıya seçtir136 object_cols = list(df.select_dtypes(include=['object']).columns)137 text_col = st.selectbox("Analiz edilecek metin sütununu seçin:", object_cols)138 139 if st.button("Tahminleri Çalıştır"):140 with st.spinner('Tahmin yapılıyor...'):141 # Boş verileri doldur142 input_data = df[text_col].fillna('')143 144 # Tahmin145 df['sentiment_prediction'] = model.predict(input_data)146 147 st.success("Tamamlandı!")148 st.dataframe(df[[text_col, 'sentiment_prediction']].head())149 150 # İndirme Butonu151 csv = df.to_csv(index=False).encode('utf-8')152 st.download_button(153 label="Sonuçları İndir (CSV)",154 data=csv,155 file_name="tahmin_sonuclari.csv",156 mime="text/csv"157 )158 159 except Exception as e:160 st.error(f"Hata: {e}")161 162if __name__ == "__main__":163 main()