ESMATUGBA commited on
Commit
288166c
·
verified ·
1 Parent(s): 7400974

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -94
app.py CHANGED
@@ -4,147 +4,95 @@ 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.")
 
4
  import plotly.express as px
5
  import os
6
 
7
+ # 1. Sayfa Ayarları (Hugging Face üzerinde düzgün görünmesi için)
8
  st.set_page_config(page_title="Movie Similarity Analysis", layout="wide")
9
 
10
+ # 2. Şık Arayüz Tasarımı (CSS)
11
  st.markdown("""
12
  <style>
13
+ .stApp { background-color: #111111; color: white; }
 
 
 
 
 
 
 
 
 
 
14
  .movie-card {
15
+ background-color: #1e1e1e; padding: 15px; border-radius: 10px;
16
+ border-top: 4px solid #e50914; height: 420px; margin-bottom: 20px;
 
 
 
 
17
  }
 
18
  .match-tag {
19
+ background-color: #e50914; color: white; text-align: center;
20
+ border-radius: 5px; padding: 3px; font-size: 12px; font-weight: bold;
 
 
 
 
 
 
21
  }
22
+ h1, h2, h3, h4 { color: #e50914 !important; }
23
  </style>
24
  """, unsafe_allow_html=True)
25
 
26
+ # 3. Bellek Dostu Veri Yükleme
27
  @st.cache_resource
28
+ def load_data():
29
  try:
30
  # Dosya yollarını kontrol et
31
  if not os.path.exists('netflix_titles.csv'):
32
+ return "csv_error", None, None
33
+
34
+ # CSV'yi sadece gerekli sütunlarla oku (RAM tasarrufu için)
35
+ df = pd.read_csv('netflix_titles.csv', usecols=['title', 'listed_in', 'description'])
36
 
37
+ # Model dosyalarını yükle
38
  with open('similarity.pkl', 'rb') as f:
39
  similarity = pickle.load(f)
 
40
  with open('indices.pkl', 'rb') as f:
41
  indices = pickle.load(f)
42
 
43
  return df, similarity, indices
44
  except Exception as e:
45
+ return str(e), None, None
 
 
 
 
 
 
 
46
 
47
+ df, similarity, indices = load_data()
 
 
 
48
 
49
+ # 4. Uygulama Arayüzü
50
+ if isinstance(df, pd.DataFrame):
51
+ st.title("🎬 Movie Similarity Analysis")
52
+ st.write("Film/Dizi Benzerlik Analizi ve Öneri Sistemi")
53
+ st.markdown("---")
54
 
55
+ # Seçim Kutusu
56
+ selected_movie = st.selectbox("Bir yapım seçin veya aratın:", df['title'].values)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ if st.button("ANALİZ ET VE BENZERLERİ GETİR"):
 
 
 
 
 
 
 
 
 
 
59
  try:
60
+ # Benzerlik hesaplama
61
  idx = indices[selected_movie]
 
62
  sim_scores = sorted(list(enumerate(similarity[idx])), key=lambda x: x[1], reverse=True)
63
 
64
+ # En yakın 5 film (kendisi hariç)
65
  top_indices = [i[0] for i in sim_scores[1:6]]
66
  top_scores = [i[1] for i in sim_scores[1:6]]
67
 
68
  recs = df.iloc[top_indices].copy()
69
  recs['Score'] = top_scores
70
 
71
+ # Grafik Çizimi
72
+ fig = px.bar(recs, x='Score', y='title', orientation='h',
73
+ color='Score', color_continuous_scale='Reds',
74
+ template="plotly_dark", title="Benzerlik Puanları")
75
  st.plotly_chart(fig, use_container_width=True)
76
 
77
+ # Film Kartları
78
+ st.write("### 🍿 Sizin İçin Öneriler")
79
  cols = st.columns(5)
80
  for i, col in enumerate(cols):
81
  with col:
82
  row = recs.iloc[i]
83
  st.markdown(f"""
84
  <div class="movie-card">
85
+ <h4>{row['title']}</h4>
86
+ <p style="font-size: 11px; color: #aaa;">{row['listed_in']}</p>
87
+ <hr style="border-color: #333;">
88
+ <p style="font-size: 11px;">{row['description'][:140]}...</p>
89
+ <div class="match-tag">%{int(row['Score']*100)} Benzerlik</div>
 
90
  </div>
91
  """, unsafe_allow_html=True)
92
  except Exception as e:
93
  st.error(f"Analiz sırasında bir hata oluştu: {e}")
94
+
95
+ elif df == "csv_error":
96
+ st.error("⚠️ 'netflix_titles.csv' dosyası bulunamadı! Lütfen Files sekmesinden bu dosyayı yükleyin.")
97
  else:
98
+ st.error(f"⚠️ Hata oluştu: {df}")