Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +32 -9
src/streamlit_app.py
CHANGED
|
@@ -1,25 +1,43 @@
|
|
| 1 |
-
|
| 2 |
import streamlit as st
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
import tensorflow as tf
|
| 6 |
import joblib
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
@st.cache_resource
|
| 9 |
def load_model():
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
@st.cache_data
|
| 13 |
def load_assets():
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
return df_movies, user_map, movie_map
|
| 17 |
|
| 18 |
model = load_model()
|
| 19 |
movies_df, user2idx, movie2idx = load_assets()
|
| 20 |
reverse_movie_map = {v: k for k, v in movie2idx.items()}
|
| 21 |
|
| 22 |
-
st.title("TensorFlow Movie Recommender")
|
| 23 |
st.write("Select some movies you've liked to get recommendations:")
|
| 24 |
|
| 25 |
movie_titles = movies_df.set_index("movieId")["title"].to_dict()
|
|
@@ -28,14 +46,19 @@ selected_titles = st.multiselect("Liked movies", sorted(movie_choices))
|
|
| 28 |
|
| 29 |
user_ratings = {}
|
| 30 |
for title in selected_titles:
|
| 31 |
-
movie_id =
|
| 32 |
-
|
|
|
|
| 33 |
|
| 34 |
if st.button("Get Recommendations"):
|
| 35 |
if not user_ratings:
|
| 36 |
st.warning("Please select at least one movie.")
|
| 37 |
else:
|
| 38 |
liked_indices = [movie2idx[m] for m in user_ratings if m in movie2idx]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
avg_embedding = tf.reduce_mean(model.layers[2](tf.constant(liked_indices)), axis=0, keepdims=True)
|
| 40 |
all_movie_indices = tf.range(len(movie2idx))
|
| 41 |
movie_embeddings = model.layers[3](all_movie_indices)
|
|
@@ -44,12 +67,12 @@ if st.button("Get Recommendations"):
|
|
| 44 |
|
| 45 |
recommended = []
|
| 46 |
for idx in top_indices:
|
| 47 |
-
mid = reverse_movie_map
|
| 48 |
if mid not in user_ratings and mid in movie_titles:
|
| 49 |
recommended.append((movie_titles[mid], scores[idx]))
|
| 50 |
if len(recommended) >= 10:
|
| 51 |
break
|
| 52 |
|
| 53 |
-
st.subheader("Top Recommendations")
|
| 54 |
for title, score in recommended:
|
| 55 |
st.write(f"{title} — Score: {score:.3f}")
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import tensorflow as tf
|
| 5 |
import joblib
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# Define paths
|
| 9 |
+
BASE_DIR = os.path.dirname(__file__)
|
| 10 |
+
MODEL_PATH = os.path.join(BASE_DIR, "recommender_model.keras")
|
| 11 |
+
MOVIES_PATH = os.path.join(BASE_DIR, "movies.csv")
|
| 12 |
+
ENCODINGS_PATH = os.path.join(BASE_DIR, "encodings.pkl")
|
| 13 |
|
| 14 |
@st.cache_resource
|
| 15 |
def load_model():
|
| 16 |
+
try:
|
| 17 |
+
return tf.keras.models.load_model(MODEL_PATH)
|
| 18 |
+
except Exception as e:
|
| 19 |
+
st.error(f"Failed to load model: {e}")
|
| 20 |
+
st.stop()
|
| 21 |
|
| 22 |
@st.cache_data
|
| 23 |
def load_assets():
|
| 24 |
+
try:
|
| 25 |
+
df_movies = pd.read_csv(MOVIES_PATH)
|
| 26 |
+
except FileNotFoundError:
|
| 27 |
+
st.error("movies.csv not found.")
|
| 28 |
+
st.stop()
|
| 29 |
+
try:
|
| 30 |
+
user_map, movie_map = joblib.load(ENCODINGS_PATH)
|
| 31 |
+
except FileNotFoundError:
|
| 32 |
+
st.error("encodings.pkl not found.")
|
| 33 |
+
st.stop()
|
| 34 |
return df_movies, user_map, movie_map
|
| 35 |
|
| 36 |
model = load_model()
|
| 37 |
movies_df, user2idx, movie2idx = load_assets()
|
| 38 |
reverse_movie_map = {v: k for k, v in movie2idx.items()}
|
| 39 |
|
| 40 |
+
st.title("🎬 TensorFlow Movie Recommender")
|
| 41 |
st.write("Select some movies you've liked to get recommendations:")
|
| 42 |
|
| 43 |
movie_titles = movies_df.set_index("movieId")["title"].to_dict()
|
|
|
|
| 46 |
|
| 47 |
user_ratings = {}
|
| 48 |
for title in selected_titles:
|
| 49 |
+
movie_id = next((k for k, v in movie_titles.items() if v == title), None)
|
| 50 |
+
if movie_id:
|
| 51 |
+
user_ratings[movie_id] = 5.0
|
| 52 |
|
| 53 |
if st.button("Get Recommendations"):
|
| 54 |
if not user_ratings:
|
| 55 |
st.warning("Please select at least one movie.")
|
| 56 |
else:
|
| 57 |
liked_indices = [movie2idx[m] for m in user_ratings if m in movie2idx]
|
| 58 |
+
if not liked_indices:
|
| 59 |
+
st.error("No valid movie encodings found.")
|
| 60 |
+
st.stop()
|
| 61 |
+
|
| 62 |
avg_embedding = tf.reduce_mean(model.layers[2](tf.constant(liked_indices)), axis=0, keepdims=True)
|
| 63 |
all_movie_indices = tf.range(len(movie2idx))
|
| 64 |
movie_embeddings = model.layers[3](all_movie_indices)
|
|
|
|
| 67 |
|
| 68 |
recommended = []
|
| 69 |
for idx in top_indices:
|
| 70 |
+
mid = reverse_movie_map.get(idx)
|
| 71 |
if mid not in user_ratings and mid in movie_titles:
|
| 72 |
recommended.append((movie_titles[mid], scores[idx]))
|
| 73 |
if len(recommended) >= 10:
|
| 74 |
break
|
| 75 |
|
| 76 |
+
st.subheader("🎯 Top Recommendations")
|
| 77 |
for title, score in recommended:
|
| 78 |
st.write(f"{title} — Score: {score:.3f}")
|