ESMATUGBA commited on
Commit
33f777d
·
verified ·
1 Parent(s): 4596e81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -156
app.py CHANGED
@@ -1,156 +1,150 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import pickle
4
- import plotly.express as px
5
-
6
- # 1. Sayfa Ayarları
7
- st.set_page_config(page_title="Movie Recommender AI", layout="wide")
8
-
9
- # 2. Şık Görsel Stil (CSS) - Netflix ibaresi kaldırıldı, renkler düzenlendi
10
- st.markdown("""
11
- <style>
12
- .stApp { background-color: #141414; color: white; }
13
- .stButton>button {
14
- width: 100%;
15
- background-color: #333333;
16
- color: white;
17
- font-weight: bold;
18
- border: 1px solid #555;
19
- border-radius: 5px;
20
- height: 3em;
21
- }
22
- .stButton>button:hover { background-color: #e50914; border: 1px solid #e50914; color: white; }
23
- .stSelectbox label { color: white !important; font-size: 16px !important; }
24
- .movie-card {
25
- background-color: #262730;
26
- padding: 20px;
27
- border-radius: 10px;
28
- border-top: 5px solid #e50914;
29
- height: 520px;
30
- margin-bottom: 20px;
31
- }
32
- h1, h2, h3, h4, p, span { color: white !important; }
33
- .match-tag {
34
- background-color: #e50914;
35
- color: white;
36
- text-align: center;
37
- border-radius: 5px;
38
- padding: 5px;
39
- font-size: 14px;
40
- font-weight: bold;
41
- margin-top: 10px;
42
- }
43
- </style>
44
- """, unsafe_allow_html=True)
45
-
46
- # 3. Veri ve Model Yükleme
47
- @st.cache_resource
48
- def load_assets():
49
- try:
50
- df = pd.read_csv('netflix_titles.csv')
51
- with open('similarity.pkl', 'rb') as f:
52
- similarity = pickle.load(f)
53
- with open('indices.pkl', 'rb') as f:
54
- indices = pickle.load(f)
55
- return df, similarity, indices
56
- except:
57
- return None, None, None
58
-
59
- df, similarity, indices = load_assets()
60
-
61
- # Türkçe Çeviri Simülasyonu Fonksiyonu
62
- def get_turkish_desc(text):
63
- # Veri setindeki İngilizce özetleri Türkçeleştirme başlığı altında sunar
64
- return f"Bu yapım genel olarak şunu konu almaktadır: {text[:100]}..."
65
-
66
- if df is not None:
67
- # --- YENİ BAŞLIK ---
68
- st.title("🎬 Movie Recommendation System / Film Öneri Sistemi")
69
- st.write("---")
70
-
71
- col_left, col_main = st.columns([1.5, 3])
72
-
73
- # --- SOL TARAF: ÖRNEKLER (İKİŞERLİ YAN YANA GRID) ---
74
- with col_left:
75
- st.subheader("💡 Suggestions / Örnekler")
76
- samples = [
77
- ("Kota Factory", "Eğitim"), ("Ganglands", "Aksiyon"),
78
- ("Midnight Mass", "Korku"), ("Squid Game", "Gerilim"),
79
- ("The Witcher", "Fantastik"), ("Peaky Blinders", "Dram"),
80
- ("Dark", "Gizem"), ("Lucifer", "Suç")
81
- ]
82
-
83
- # 2'li Izgara Yapısı
84
- for i in range(0, len(samples), 2):
85
- c1, c2 = st.columns(2)
86
- with c1:
87
- st.button(samples[i][0], key=f"btn_{samples[i][0]}")
88
- st.caption(f"({samples[i][1]})")
89
- with c2:
90
- if i+1 < len(samples):
91
- st.button(samples[i+1][0], key=f"btn_{samples[i+1][0]}")
92
- st.caption(f"({samples[i+1][1]})")
93
-
94
- st.markdown("""
95
- <div style="background-color: #1c1c1c; padding: 15px; border-radius: 8px; border: 1px solid #444; margin-top: 25px;">
96
- <p style="font-size:14px; margin:0; color: #ddd !important;">
97
- <b>İpucu:</b> Beğendiğiniz bir filmi sağdaki listeden seçebilir veya ismini yazarak aratabilirsiniz.
98
- </p>
99
- </div>
100
- """, unsafe_allow_html=True)
101
-
102
- # --- SAĞ TARAF: ANALİZ VE SEÇİM ---
103
- with col_main:
104
- # Film seçerken yanında kategorisi de görünsün
105
- df['display_name'] = df['title'] + " (" + df['listed_in'] + ")"
106
-
107
- selected_display = st.selectbox(
108
- "Bir Film veya Dizi Seçin / Select a Movie or TV Show:",
109
- df['display_name'].values
110
- )
111
- # Seçilen isimden orijinal başlığı ayıkla
112
- selected_movie = selected_display.split(" (")[0]
113
-
114
- process_btn = st.button('ÖNERİLERİ ANALİZ ET VE GETİR / ANALYZE')
115
-
116
- # --- ANALİZ SONUÇLARI ---
117
- if process_btn:
118
- idx = indices[selected_movie]
119
- sim_scores = sorted(list(enumerate(similarity[idx])), key=lambda x: x[1], reverse=True)
120
-
121
- # En benzer 5 film
122
- top_indices = [i[0] for i in sim_scores[1:6]]
123
- top_scores = [i[1] for i in sim_scores[1:6]]
124
-
125
- recs = df.iloc[top_indices].copy()
126
- recs['Score'] = top_scores
127
-
128
- # BENZERLİK GRAFİĞİ
129
- st.subheader("📊 Benzerlik Oranları / Similarity Analysis")
130
- fig = px.bar(recs, x='Score', y='title', orientation='h', color='Score',
131
- color_continuous_scale='Reds', template="plotly_dark", height=300)
132
- fig.update_layout(yaxis={'categoryorder':'total ascending'})
133
- st.plotly_chart(fig, use_container_width=True)
134
-
135
- st.write("---")
136
-
137
- # FİLM KARTLARI
138
- st.subheader("Tavsiye Edilen Yapımlar / Recommendations")
139
- cols = st.columns(5)
140
- for i, col in enumerate(cols):
141
- with col:
142
- row = recs.iloc[i]
143
- st.markdown(f"""
144
- <div class="movie-card">
145
- <h4 style="color: #e50914; font-size: 16px; margin-bottom: 2px;">{row['title']}</h4>
146
- <p style="font-size: 11px; color: #aaa !important;">{row['listed_in']}</p>
147
- <hr style="border-color: #444; margin: 10px 0;">
148
- <p style="font-size: 12px; color: white !important;"><b>🇬🇧 Summary:</b><br>{row['description'][:60]}...</p>
149
- <p style="font-size: 12px; color: #ffcc00 !important;"><b>🇹🇷 Özet:</b><br>{get_turkish_desc(row['description'])}</p>
150
- <div class="match-tag">
151
- %{int(row['Score']*100)} Match
152
- </div>
153
- </div>
154
- """, unsafe_allow_html=True)
155
- else:
156
- st.error("Dosyalar yüklenemedi! 'netflix_titles.csv', 'similarity.pkl' ve 'indices.pkl' dosyalarını kontrol edin.")
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import pickle
4
+ import plotly.express as px
5
+ import os
6
+
7
+ # 1. Sayfa Ayarları
8
+ st.set_page_config(page_title="Movie Similarity Analysis", layout="wide")
9
+
10
+ # 2. Şık Görsel Stil (CSS)
11
+ st.markdown("""
12
+ <style>
13
+ .stApp { background-color: #141414; color: white; }
14
+ .stButton>button {
15
+ width: 100%;
16
+ background-color: #333333;
17
+ color: white;
18
+ font-weight: bold;
19
+ border: 1px solid #555;
20
+ border-radius: 5px;
21
+ height: 3em;
22
+ }
23
+ .stButton>button:hover { background-color: #e50914; border: 1px solid #e50914; color: white; }
24
+ .movie-card {
25
+ background-color: #262730;
26
+ padding: 20px;
27
+ border-radius: 10px;
28
+ border-top: 5px solid #e50914;
29
+ height: 450px;
30
+ margin-bottom: 20px;
31
+ }
32
+ h1, h2, h3, h4, p, span { color: white !important; }
33
+ .match-tag {
34
+ background-color: #e50914;
35
+ color: white;
36
+ text-align: center;
37
+ border-radius: 5px;
38
+ padding: 5px;
39
+ font-size: 14px;
40
+ font-weight: bold;
41
+ margin-top: 10px;
42
+ }
43
+ </style>
44
+ """, unsafe_allow_html=True)
45
+
46
+ # 3. Veri ve Model Yükleme Fonksiyonu
47
+ @st.cache_resource
48
+ def load_assets():
49
+ try:
50
+ # Dosya yollarını kontrol et
51
+ if not os.path.exists('netflix_titles.csv'):
52
+ st.error("Hata: 'netflix_titles.csv' dosyası bulunamadı. Lütfen yükleyin.")
53
+ return None, None, None
54
+
55
+ df = pd.read_csv('netflix_titles.csv')
56
+
57
+ with open('similarity.pkl', 'rb') as f:
58
+ similarity = pickle.load(f)
59
+
60
+ with open('indices.pkl', 'rb') as f:
61
+ indices = pickle.load(f)
62
+
63
+ return df, similarity, indices
64
+ except Exception as e:
65
+ st.error(f"Dosyalar yüklenirken bir hata oluştu: {e}")
66
+ return None, None, None
67
+
68
+ df, similarity, indices = load_assets()
69
+
70
+ # Türkçe Özet Simülasyonu
71
+ def get_turkish_desc(text):
72
+ return f"Bu yapım genel olarak şunu konu almaktadır: {text[:80]}..."
73
+
74
+ if df is not None:
75
+ st.title("🎬 Movie Similarity Analysis / Film Benzerliği Analizi")
76
+ st.write("Veri Seti: Netflix Movies & TV Shows (8800+ Yapım)")
77
+ st.write("---")
78
+
79
+ col_left, col_main = st.columns([1.5, 3])
80
+
81
+ # --- SOL TARAF: ÖRNEKLER ---
82
+ with col_left:
83
+ st.subheader("💡 Suggestions / Örnekler")
84
+ samples = ["Kota Factory", "Ganglands", "Midnight Mass", "Squid Game", "The Witcher", "Dark"]
85
+
86
+ for sample in samples:
87
+ if st.button(sample, key=f"btn_{sample}"):
88
+ st.session_state.selected_movie_input = sample
89
+
90
+ # --- SAĞ TARAF: SEÇİM VE ANALİZ ---
91
+ with col_main:
92
+ df['display_name'] = df['title'] + " (" + df['listed_in'].str[:30] + "...)"
93
+
94
+ # Session state ile buton tıklamasını yakala
95
+ default_idx = 0
96
+ if 'selected_movie_input' in st.session_state:
97
+ try:
98
+ default_idx = list(df['title']).index(st.session_state.selected_movie_input)
99
+ except:
100
+ default_idx = 0
101
+
102
+ selected_display = st.selectbox(
103
+ "Bir Film seçin veya yazın:",
104
+ df['display_name'].values,
105
+ index=default_idx
106
+ )
107
+
108
+ selected_movie = selected_display.split(" (")[0]
109
+ process_btn = st.button('BENZERLİKLERİ ANALİZ ET / ANALYZE')
110
+
111
+ # --- ANALİZ SONUÇLARI ---
112
+ if process_btn:
113
+ try:
114
+ idx = indices[selected_movie]
115
+ # Benzerlik skorlarını al
116
+ sim_scores = sorted(list(enumerate(similarity[idx])), key=lambda x: x[1], reverse=True)
117
+
118
+ # En benzer 5 film (kendisi hariç)
119
+ top_indices = [i[0] for i in sim_scores[1:6]]
120
+ top_scores = [i[1] for i in sim_scores[1:6]]
121
+
122
+ recs = df.iloc[top_indices].copy()
123
+ recs['Score'] = top_scores
124
+
125
+ # GRAFİK
126
+ st.subheader("📊 Similarity Scores / Benzerlik Puanları")
127
+ fig = px.bar(recs, x='Score', y='title', orientation='h', color='Score',
128
+ color_continuous_scale='Reds', template="plotly_dark", height=300)
129
+ st.plotly_chart(fig, use_container_width=True)
130
+
131
+ # KARTLAR
132
+ st.subheader("🔍 Recommended for You / Sizin İçin Önerilenler")
133
+ cols = st.columns(5)
134
+ for i, col in enumerate(cols):
135
+ with col:
136
+ row = recs.iloc[i]
137
+ st.markdown(f"""
138
+ <div class="movie-card">
139
+ <h4 style="color: #e50914; font-size: 15px;">{row['title']}</h4>
140
+ <p style="font-size: 10px; color: #aaa;">{row['listed_in']}</p>
141
+ <hr style="border-color: #444;">
142
+ <p style="font-size: 11px;"><b>🇬🇧 Summary:</b> {row['description'][:50]}...</p>
143
+ <p style="font-size: 11px; color: #ffcc00;"><b>🇹🇷 Özet:</b> {get_turkish_desc(row['description'])}</p>
144
+ <div class="match-tag">%{int(row['Score']*100)} Match</div>
145
+ </div>
146
+ """, unsafe_allow_html=True)
147
+ except Exception as e:
148
+ st.error(f"Analiz sırasında bir hata oluştu: {e}")
149
+ else:
150
+ st.warning("⚠️ Lütfen sistemin çalışması için 'netflix_titles.csv' dosyasını yüklediğinizden emin olun.")