Spaces:
Sleeping
Sleeping
import streamlit as st | |
from surprise import Dataset, Reader, SVD | |
from surprise.model_selection import train_test_split | |
import pandas as pd | |
import numpy as np | |
import json | |
import os | |
# Path to the JSON file to persist movie ratings | |
RATINGS_FILE = 'movie_ratings.json' | |
# Initialize sample user-item rating data | |
data = { | |
'user_id': [1, 1, 1, 2, 2, 3, 3, 4, 4], | |
'item_id': [1, 2, 3, 1, 4, 2, 3, 1, 4], | |
'rating': [5, 3, 4, 4, 5, 5, 2, 4, 4] | |
} | |
df = pd.DataFrame(data) | |
reader = Reader(rating_scale=(1, 5)) | |
dataset = Dataset.load_from_df(df[['user_id', 'item_id', 'rating']], reader) | |
trainset, testset = train_test_split(dataset, test_size=0.25) | |
algo = SVD() | |
algo.fit(trainset) | |
# Function to load ratings from a JSON file | |
def load_ratings(): | |
if os.path.exists(RATINGS_FILE): | |
with open(RATINGS_FILE, 'r') as file: | |
return json.load(file) | |
else: | |
return {movie: [] for movie in ['Die Hard', 'Mad Max', 'The Shawshank Redemption', 'Forrest Gump', | |
'Superbad', 'Step Brothers', 'Inception', 'Interstellar']} | |
# Function to save ratings to a JSON file | |
def save_ratings(ratings): | |
with open(RATINGS_FILE, 'w') as file: | |
json.dump(ratings, file) | |
# Load ratings from file | |
movie_ratings = load_ratings() | |
def update_ratings(movie, rating): | |
movie_ratings[movie].append(rating) | |
save_ratings(movie_ratings) | |
# UI Elements | |
st.title("π Personalized Entertainment Recommendations") | |
# Input for user genre preference | |
user_genre = st.selectbox( | |
"Choose your favorite genre", | |
["Action π¬", "Drama π", "Comedy π", "Sci-Fi π"] | |
) | |
# Define genre mapping | |
genre_mapping = { | |
"Action π¬": 1, | |
"Drama π": 2, | |
"Comedy π": 3, | |
"Sci-Fi π": 4 | |
} | |
# Example mapping of genre to item_id | |
recommendations = { | |
1: ["Die Hard", "Mad Max"], | |
2: ["The Shawshank Redemption", "Forrest Gump"], | |
3: ["Superbad", "Step Brothers"], | |
4: ["Inception", "Interstellar"] | |
} | |
# Provide recommendation based on collaborative filtering | |
selected_genre_id = genre_mapping[user_genre] | |
# Predict ratings for the selected genre items | |
predicted_ratings = [(id, algo.predict(5, id).est) for id in [1, 2, 3, 4] if id == selected_genre_id] | |
# Sort recommendations by predicted ratings | |
predicted_ratings.sort(key=lambda x: x[1], reverse=True) | |
st.subheader("π― Recommendations for you:") | |
# Collect average scores | |
all_movies = [] | |
for item_id, rating in predicted_ratings: | |
for rec in recommendations[item_id]: | |
current_ratings = movie_ratings[rec] | |
avg_score = np.mean(current_ratings) if current_ratings else rating | |
vote_count = len(current_ratings) | |
st.write(f"{rec} - Average Score: {avg_score:.2f} β (Votes: {vote_count})") | |
# Rating slider from 1 to 10 | |
user_rating = st.slider(f"Rate {rec}", 1, 10, 5, key=f"slider_{rec}") | |
if st.button(f"Submit Rating for {rec}", key=f"button_{rec}"): | |
update_ratings(rec, user_rating) | |
st.experimental_rerun() # Rerun to immediately reflect the rating submission | |
all_movies.append((rec, avg_score, vote_count)) | |
# Sort movies by average score in descending order | |
sorted_movies = sorted(all_movies, key=lambda x: x[1], reverse=True) | |
# Display scoreboard | |
st.subheader("π Scoreboard:") | |
for movie, avg_score, vote_count in sorted_movies: | |
st.write(f"{movie}: {avg_score:.2f} β (Votes: {vote_count})") | |
# Display current session state (for debugging purposes) | |
# st.write("Session State (User Ratings):", movie_ratings) |