Spaces:
Sleeping
Sleeping
Download app.py from Pro-metheus/CineMatch: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/Pro-metheus/CineMatch/resolve/main/app.py
- Command line
-
hf download hf://spaces/Pro-metheus/CineMatch/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Pro-metheus/CineMatch/resolve/main/app.py
10.8 kB
| import gradio as gr | |
| import numpy as np | |
| import pandas as pd | |
| from surprise import Dataset, SVD, Reader | |
| from sklearn.metrics.pairwise import linear_kernel | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| def load_data(): | |
| # Load all necessary data files | |
| try: | |
| print("Loading data files...") | |
| movies_data = pd.read_csv("Data/NewMoviesMetadata.csv") | |
| movie_com = pd.read_csv("Data/MovieBasedRecommenderData.csv") | |
| ratings = pd.read_csv("Data/ratings_small.csv") | |
| links = pd.read_csv("Data/links.csv").dropna() | |
| links["tmdbId"] = links["tmdbId"].astype("int64") | |
| print("Data loaded successfully.") | |
| return movies_data, movie_com, ratings, links | |
| except FileNotFoundError as e: | |
| print(f"Error loading data files: {e}") | |
| print("Please make sure all required CSV files are in a 'data' directory.") | |
| return None, None, None, None | |
| def train_svd_model(ratings): | |
| # Train the SVD model for collaborative filtering | |
| if ratings is None: return None | |
| print("Training SVD model...") | |
| reader = Reader() | |
| data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader) | |
| trainset = data.build_full_trainset() | |
| svd = SVD() | |
| svd.fit(trainset) | |
| print("SVD model trained.") | |
| return svd | |
| def create_tfidf_matrix(movie_com): | |
| # Create TF-IDF matrix for content-based filtering | |
| if movie_com is None: return None | |
| print("Creating TF-IDF matrix...") | |
| movie_com["model_feature"] = movie_com["model_feature"].fillna("") | |
| tf = TfidfVectorizer( | |
| analyzer="word", | |
| ngram_range=(1, 2), | |
| min_df=1, | |
| stop_words="english" | |
| ) | |
| tfidf_matrix = tf.fit_transform(movie_com["model_feature"]) | |
| cosine_sim = linear_kernel(tfidf_matrix[:15000], tfidf_matrix) | |
| print("TF-IDF matrix created.") | |
| return cosine_sim | |
| # Load all data and models globally | |
| movies_data, movie_com, ratings, links = load_data() | |
| if movies_data is not None: | |
| svd = train_svd_model(ratings) | |
| cosine_sim = create_tfidf_matrix(movie_com) | |
| movie_titles = movies_data['title'].unique() | |
| else: | |
| # Handle case where data loading fails | |
| svd, cosine_sim, movie_titles = None, None, [] | |
| # Recomendation logic | |
| def hybrid_recommend(userId, title, svd, cosine_sim, movies_data, movie_com, links): | |
| # Hybrid recommendation function | |
| if svd is None or cosine_sim is None: | |
| return pd.DataFrame(columns=["title", "est", "id"]) | |
| indices = pd.Series(movies_data.index, index=movies_data['title']) | |
| try: | |
| idx = indices[title] | |
| if isinstance(idx, pd.Series): | |
| idx = idx.iloc[0] | |
| sim_scores = list(enumerate(cosine_sim[int(idx)])) | |
| sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)[1:21] | |
| movie_indices = [i[0] for i in sim_scores] | |
| movies = movie_com.iloc[movie_indices][["title", "id"]] | |
| tempLinks = links[links["tmdbId"].isin(movies["id"].tolist())] | |
| preds = [] | |
| for item in tempLinks["movieId"]: | |
| try: | |
| pred = svd.predict(userId, item).est | |
| preds.append(pred) | |
| except: | |
| preds.append(2.5) | |
| if len(preds) > 0: | |
| tempData = pd.DataFrame({ | |
| "title": movies["title"].iloc[:len(preds)], | |
| "est": preds, | |
| "id": movies["id"].iloc[:len(preds)] | |
| }) | |
| tempData = tempData.sort_values("est", ascending=False) | |
| tempData = tempData[tempData["est"] >= 2.5] | |
| return tempData.head(10) | |
| else: | |
| return pd.DataFrame(columns=["title", "est", "id"]) | |
| except Exception as e: | |
| print(f"Error in hybrid recommendation: {e}") | |
| return pd.DataFrame(columns=["title", "est", "id"]) | |
| def get_user_recommendations(userID, svd, cosine_sim, movies_data, movie_com, ratings, links): | |
| # Get recommendations for a specific user | |
| if svd is None or cosine_sim is None: | |
| return pd.DataFrame(columns=["title", "est", "id"]) | |
| tempRatings = ratings[ratings["userId"] == userID] | |
| tempRatings = tempRatings[tempRatings["rating"] >= 4] | |
| if tempRatings.empty: | |
| return pd.DataFrame(columns=["title", "est", "id"]) | |
| tempLinks = links[links["movieId"].isin(tempRatings["movieId"].tolist())] | |
| titlesData = movies_data[movies_data["id"].isin(tempLinks["tmdbId"])] | |
| resultDataFrame = pd.DataFrame() | |
| for title in titlesData["title"].head(5): | |
| try: | |
| recommendations = hybrid_recommend(userID, title, svd, cosine_sim, movies_data, movie_com, links) | |
| if not recommendations.empty: | |
| resultDataFrame = pd.concat([recommendations, resultDataFrame], ignore_index=True) | |
| except: | |
| continue | |
| if not resultDataFrame.empty: | |
| return resultDataFrame.sort_values("est", ascending=False).drop_duplicates(subset=["title"]).head(10) | |
| else: | |
| return pd.DataFrame(columns=["title", "est", "id"]) | |
| #Gradio | |
| def format_recommendations_html(df): | |
| # Converts a DataFrame of recommendations into a styled HTML string. | |
| if df.empty: | |
| return "<p style='color: #FF6347; text-align: center;'>No recommendations found. Try another selection!</p>" | |
| html = "" | |
| for idx, row in df.iterrows(): | |
| html += f""" | |
| <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 1rem; border-radius: 10px; margin: 0.5rem 0; box-shadow: 0 4px 6px rgba(0,0,0,0.1); color: white;"> | |
| <h3>{row['title']}</h3> | |
| <span style="background-color: #f39c12; color: white; padding: 0.3rem 0.6rem; border-radius: 15px; font-weight: bold; font-size: 0.9rem;"> | |
| Predicted Rating: {row['est']:.2f}/5 | |
| </span> | |
| </div> | |
| """ | |
| return html | |
| # controllers of some sort | |
| def movie_based_recommendation_app(user_id, movie_title): | |
| # UI function for movie-based recommendations | |
| if not movie_title: | |
| return "<p style='color: #FFCC00; text-align: center;'>Please select a movie first.</p>" | |
| recommendations = hybrid_recommend( | |
| user_id, movie_title, svd, cosine_sim, | |
| movies_data, movie_com, links | |
| ) | |
| return format_recommendations_html(recommendations) | |
| def user_based_recommendation_app(user_id): | |
| # Get user's liked movies | |
| user_ratings = ratings[(ratings["userId"] == user_id) & (ratings["rating"] >= 4)] | |
| liked_movies_html = "<p>No highly-rated movies found in your history.</p>" | |
| if not user_ratings.empty: | |
| user_movies = user_ratings.merge( | |
| links[["movieId", "tmdbId"]], on="movieId" | |
| ).merge( | |
| movies_data[["id", "title"]], left_on="tmdbId", right_on="id" | |
| ) | |
| liked_movies_html = "<ul>" | |
| for _, movie in user_movies.head(5).iterrows(): | |
| liked_movies_html += f"<li>β {movie['title']} (Your Rating: {movie['rating']}/5)</li>" | |
| liked_movies_html += "</ul>" | |
| # Get recommendations | |
| recommendations = get_user_recommendations( | |
| user_id, svd, cosine_sim, movies_data, | |
| movie_com, ratings, links | |
| ) | |
| recs_html = format_recommendations_html(recommendations) | |
| return liked_movies_html, recs_html | |
| # layout | |
| with gr.Blocks(theme=gr.themes.Soft(), css="footer {visibility: hidden}") as demo: | |
| gr.Markdown( | |
| """ | |
| <h1 style="font-size: 3rem; color: #e50914; text-align: center; margin-bottom: 1rem; font-weight: bold;"> | |
| π¬ Movie Recommendation System | |
| </h1> | |
| <h3 style="text-align: center; color: #555;">Discover your next favorite movie with our hybrid recommendation engine!</h3> | |
| """ | |
| ) | |
| with gr.Tabs(): | |
| with gr.TabItem("π Movie-based Recommendations"): | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| movie_input = gr.Dropdown( | |
| choices=list(movies_data['title'].head(100)), | |
| label="Select a movie you enjoyed:", | |
| info="Start typing to search for a movie." | |
| ) | |
| user_id_movie = gr.Slider( | |
| minimum=1, maximum=671, value=1, step=1, | |
| label="Enter your User ID:" | |
| ) | |
| btn_movie = gr.Button("π Get Recommendations", variant="primary") | |
| with gr.Column(scale=1): | |
| gr.Markdown( | |
| """ | |
| > **π‘ How it works:** | |
| > 1. Select a movie you liked. | |
| > 2. Choose your user ID. | |
| > 3. Get personalized recommendations! | |
| """ | |
| ) | |
| output_movie = gr.HTML(label="Recommended Movies") | |
| btn_movie.click( | |
| fn=movie_based_recommendation_app, | |
| inputs=[user_id_movie, movie_input], | |
| outputs=output_movie | |
| ) | |
| with gr.TabItem("π€ User-based Recommendations"): | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| user_id_user = gr.Slider( | |
| minimum=1, maximum=671, value=1, step=1, | |
| label="Enter your User ID:", | |
| info="This will analyze your rating history to suggest new movies." | |
| ) | |
| btn_user = gr.Button("π― Get My Recommendations", variant="primary") | |
| with gr.Column(scale=1): | |
| gr.Markdown( | |
| """ | |
| > **π‘ Profile-based recommendations:** | |
| > Based on your rating history, we'll find movies similar to ones you've enjoyed! | |
| """ | |
| ) | |
| with gr.Accordion("π Movies You've Enjoyed (from your profile)", open=False): | |
| output_user_liked = gr.HTML() | |
| output_user_recs = gr.HTML(label="π¬ Recommended For You") | |
| btn_user.click( | |
| fn=user_based_recommendation_app, | |
| inputs=[user_id_user], | |
| outputs=[output_user_liked, output_user_recs] | |
| ) | |
| gr.Markdown(""" | |
| <div style="text-align: center; color: #666; margin-top: 2rem;"> | |
| <p>π€ Powered by Hybrid Recommendation System | Collaborative Filtering + Content-Based Filtering</p> | |
| </div> | |
| """) | |
| if __name__ == "__main__": | |
| if movies_data is not None: | |
| demo.launch() | |
| else: | |
| print("Application cannot start due to data loading errors.") |