Spaces:
Sleeping
Sleeping
File size: 3,552 Bytes
64e5ecd 2f2356b 6893115 64e5ecd 2f2356b 64e5ecd 6893115 2f2356b e58c46d 6893115 2f2356b 64e5ecd e58c46d 64e5ecd 6893115 e58c46d 6893115 e58c46d 6893115 2f2356b e58c46d 2f2356b e58c46d 6893115 e58c46d 6893115 2f2356b 6893115 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
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) |