Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .streamlit/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[theme]
primaryColor = "#6C63FF"
backgroundColor = "#0E1117"
secondaryBackgroundColor = "#1F232B"
textColor = "#F5F7FA"
font = "sans serif"
52 changes: 51 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,51 @@
# -deepshekhardas.github.io
## Movie Recommendation System (Hybrid: SVD + Content)

An advanced, presentation-ready MovieLens recommender combining collaborative filtering (SVD) with content-based similarity (genres + tags). Built with Streamlit.

### Features
- Hybrid scoring: SVD CF + TF-IDF content similarity
- Cold-start support via likes/dislikes (content-based)
- Top-10 recommendations with posters, titles, genres, and scores
- Model evaluation (RMSE)
- Optional analytics (top genres, popular movies)

### Dataset
Automatically downloads MovieLens `ml-latest-small` (~100k ratings).

### Quick Start

```bash
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
streamlit run app.py
```

Optionally, pre-train and cache the SVD model:
```bash
python scripts/train.py
```

Set an API key for higher-quality posters (optional):
- OMDb: export `OMDB_API_KEY=your_key`
- or TMDb: export `TMDB_API_KEY=your_key`

Without a key, a placeholder image is shown.

### Project Structure
```
app.py
recommender/
__init__.py
data.py
content.py
cf.py
hybrid.py
posters.py
scripts/
train.py
```

### Notes
- First run will download the dataset and train the SVD model (cached).
- For unknown users, the app uses content similarity from likes/dislikes.
- For known users, the app combines SVD predictions with content similarity.
Binary file added __pycache__/app.cpython-313.pyc
Binary file not shown.
164 changes: 164 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import math
from typing import Optional, Tuple

import numpy as np
import pandas as pd
import streamlit as st
import plotly.express as px

from recommender import (
ensure_movielens_small,
load_datasets,
build_content_features,
load_or_train_svd,
hybrid_rank,
get_poster_url,
extract_title_year,
)


def _setup_page():
st.set_page_config(page_title="Hybrid Movie Recommender", page_icon="🎬", layout="wide")
CUSTOM_CSS = """
<style>
.card { background: #151a23; border-radius: 14px; padding: 12px; box-shadow: 0 6px 24px rgba(0,0,0,0.28); border: 1px solid rgba(255,255,255,0.06); }
.card h4 { margin: 8px 0 6px 0; font-size: 1.0rem; }
.badge { display: inline-block; padding: 2px 8px; border-radius: 999px; background: rgba(108,99,255,0.2); color: #c9c6ff; margin-right: 6px; font-size: 0.75rem; }
.score { font-weight: 600; color: #ffd166; }
</style>
"""
st.markdown(CUSTOM_CSS, unsafe_allow_html=True)


@st.cache_data(show_spinner=False)
def _load_data() -> Tuple[pd.DataFrame, pd.DataFrame, Optional[pd.DataFrame]]:
data_dir = ensure_movielens_small("data")
movies_df, ratings_df, tags_df = load_datasets(data_dir)
return movies_df, ratings_df, tags_df


@st.cache_resource(show_spinner=True)
def _prepare_models(ratings_df: pd.DataFrame):
model_bundle, rmse = load_or_train_svd(ratings_df, save_dir="models")
return model_bundle, rmse


@st.cache_resource(show_spinner=False)
def _prepare_content(movies_df: pd.DataFrame, tags_df: Optional[pd.DataFrame]):
return build_content_features(movies_df, tags_df)


def _render_cards(df: pd.DataFrame, title: str = "Recommendations"):
st.subheader(title)
if df.empty:
st.info("No recommendations available. Try different inputs.")
return
cols_per_row = 5
rows = math.ceil(len(df) / cols_per_row)
for r in range(rows):
cols = st.columns(cols_per_row)
for c in range(cols_per_row):
idx = r * cols_per_row + c
if idx >= len(df):
break
rec = df.iloc[idx]
with cols[c]:
with st.container():
st.markdown('<div class="card">', unsafe_allow_html=True)
poster_url = get_poster_url(rec["title"], rec.get("year"))
st.image(poster_url, use_column_width=True)
st.markdown(f"<h4>{rec['title']}</h4>", unsafe_allow_html=True)
genres = rec.get("genres", "").split("|") if isinstance(rec.get("genres"), str) else []
if genres:
st.markdown(" ".join([f"<span class='badge'>{g}</span>" for g in genres[:4]]), unsafe_allow_html=True)
score_val = rec.get("hybrid_score")
score_txt = f"{score_val:.3f}" if isinstance(score_val, (float, int)) else "-"
st.markdown(f"<div class='score'>Hybrid score: {score_txt}</div>", unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)


def main():
_setup_page()
st.title("🎬 Hybrid Movie Recommendation System")
st.caption("Collaborative Filtering (SVD) + Content-Based (Genres/Tags)")

with st.spinner("Loading data..."):
movies_df, ratings_df, tags_df = _load_data()

with st.spinner("Preparing models..."):
model_bundle, rmse = _prepare_models(ratings_df)
st.success(f"SVD RMSE: {rmse:.4f}")

tfidf_matrix, movie_index, index_to_movie, vocab = _prepare_content(movies_df, tags_df)

tabs = st.tabs(["Recommend", "Analytics"])

with tabs[0]:
st.sidebar.header("Controls")
mode = st.sidebar.radio("Mode", ["Existing user", "Likes/Dislikes"], index=0)
weight_cf = st.sidebar.slider("CF weight (vs Content)", 0.0, 1.0, 0.65, 0.05)
top_n = st.sidebar.slider("Top N", 5, 30, 10, 1)

if mode == "Existing user":
trainset = model_bundle["trainset"]
try:
known_user_ids = [int(trainset.to_raw_uid(i)) for i in range(trainset.n_users)]
except Exception:
known_user_ids = list(sorted(ratings_df["userId"].unique().tolist()))
default_uid = int(known_user_ids[0]) if known_user_ids else 1
user_id = st.number_input("User ID", min_value=1, value=default_uid, step=1)
if st.button("Recommend for user"):
recs = hybrid_rank(
mode="by_user",
user_id=int(user_id),
movies_df=movies_df,
ratings_df=ratings_df,
tfidf_matrix=tfidf_matrix,
movie_index=movie_index,
index_to_movie=index_to_movie,
svd_bundle=model_bundle,
weight_cf=weight_cf,
top_n=top_n,
)
_render_cards(recs)
else:
st.write("Pick a few movies you liked and disliked to shape recommendations.")
all_options = movies_df["title"].tolist()
liked_titles = st.multiselect("Liked movies", all_options[:2000], max_selections=20)
disliked_titles = st.multiselect("Disliked movies (optional)", all_options[:2000], max_selections=10)
liked_ids = movies_df[movies_df["title"].isin(liked_titles)]["movieId"].tolist()
disliked_ids = movies_df[movies_df["title"].isin(disliked_titles)]["movieId"].tolist()
if st.button("Recommend from likes/dislikes"):
recs = hybrid_rank(
mode="by_likes",
liked_movie_ids=liked_ids,
disliked_movie_ids=disliked_ids,
movies_df=movies_df,
ratings_df=ratings_df,
tfidf_matrix=tfidf_matrix,
movie_index=movie_index,
index_to_movie=index_to_movie,
svd_bundle=model_bundle,
weight_cf=weight_cf,
top_n=top_n,
)
_render_cards(recs)

with tabs[1]:
st.subheader("Dataset Analytics")
genres_exp = (
movies_df.assign(genre_list=movies_df["genres"].str.split("|")).explode("genre_list")
)
genre_counts = genres_exp["genre_list"].value_counts().head(15).reset_index()
genre_counts.columns = ["genre", "count"]
fig1 = px.bar(genre_counts, x="genre", y="count", title="Top Genres")
st.plotly_chart(fig1, use_container_width=True)

pop = ratings_df.groupby("movieId").agg(count=("rating", "count"), avg_rating=("rating", "mean")).reset_index()
pop = pop.merge(movies_df[["movieId", "title"]], on="movieId", how="left").sort_values("count", ascending=False).head(20)
fig2 = px.bar(pop, x="title", y="count", title="Most Rated Movies")
st.plotly_chart(fig2, use_container_width=True)


if __name__ == "__main__":
main()
Binary file added data/ml-latest-small.zip
Binary file not shown.
153 changes: 153 additions & 0 deletions data/ml-latest-small/README.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
Summary
=======

This dataset (ml-latest-small) describes 5-star rating and free-text tagging activity from [MovieLens](http://movielens.org), a movie recommendation service. It contains 100836 ratings and 3683 tag applications across 9742 movies. These data were created by 610 users between March 29, 1996 and September 24, 2018. This dataset was generated on September 26, 2018.

Users were selected at random for inclusion. All selected users had rated at least 20 movies. No demographic information is included. Each user is represented by an id, and no other information is provided.

The data are contained in the files `links.csv`, `movies.csv`, `ratings.csv` and `tags.csv`. More details about the contents and use of all these files follows.

This is a *development* dataset. As such, it may change over time and is not an appropriate dataset for shared research results. See available *benchmark* datasets if that is your intent.

This and other GroupLens data sets are publicly available for download at <http://grouplens.org/datasets/>.


Usage License
=============

Neither the University of Minnesota nor any of the researchers involved can guarantee the correctness of the data, its suitability for any particular purpose, or the validity of results based on the use of the data set. The data set may be used for any research purposes under the following conditions:

* The user may not state or imply any endorsement from the University of Minnesota or the GroupLens Research Group.
* The user must acknowledge the use of the data set in publications resulting from the use of the data set (see below for citation information).
* The user may redistribute the data set, including transformations, so long as it is distributed under these same license conditions.
* The user may not use this information for any commercial or revenue-bearing purposes without first obtaining permission from a faculty member of the GroupLens Research Project at the University of Minnesota.
* The executable software scripts are provided "as is" without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of them is with you. Should the program prove defective, you assume the cost of all necessary servicing, repair or correction.

In no event shall the University of Minnesota, its affiliates or employees be liable to you for any damages arising out of the use or inability to use these programs (including but not limited to loss of data or data being rendered inaccurate).

If you have any further questions or comments, please email <grouplens-info@umn.edu>


Citation
========

To acknowledge use of the dataset in publications, please cite the following paper:

> F. Maxwell Harper and Joseph A. Konstan. 2015. The MovieLens Datasets: History and Context. ACM Transactions on Interactive Intelligent Systems (TiiS) 5, 4: 19:1–19:19. <https://doi.org/10.1145/2827872>


Further Information About GroupLens
===================================

GroupLens is a research group in the Department of Computer Science and Engineering at the University of Minnesota. Since its inception in 1992, GroupLens's research projects have explored a variety of fields including:

* recommender systems
* online communities
* mobile and ubiquitious technologies
* digital libraries
* local geographic information systems

GroupLens Research operates a movie recommender based on collaborative filtering, MovieLens, which is the source of these data. We encourage you to visit <http://movielens.org> to try it out! If you have exciting ideas for experimental work to conduct on MovieLens, send us an email at <grouplens-info@cs.umn.edu> - we are always interested in working with external collaborators.


Content and Use of Files
========================

Formatting and Encoding
-----------------------

The dataset files are written as [comma-separated values](http://en.wikipedia.org/wiki/Comma-separated_values) files with a single header row. Columns that contain commas (`,`) are escaped using double-quotes (`"`). These files are encoded as UTF-8. If accented characters in movie titles or tag values (e.g. Misérables, Les (1995)) display incorrectly, make sure that any program reading the data, such as a text editor, terminal, or script, is configured for UTF-8.


User Ids
--------

MovieLens users were selected at random for inclusion. Their ids have been anonymized. User ids are consistent between `ratings.csv` and `tags.csv` (i.e., the same id refers to the same user across the two files).


Movie Ids
---------

Only movies with at least one rating or tag are included in the dataset. These movie ids are consistent with those used on the MovieLens web site (e.g., id `1` corresponds to the URL <https://movielens.org/movies/1>). Movie ids are consistent between `ratings.csv`, `tags.csv`, `movies.csv`, and `links.csv` (i.e., the same id refers to the same movie across these four data files).


Ratings Data File Structure (ratings.csv)
-----------------------------------------

All ratings are contained in the file `ratings.csv`. Each line of this file after the header row represents one rating of one movie by one user, and has the following format:

userId,movieId,rating,timestamp

The lines within this file are ordered first by userId, then, within user, by movieId.

Ratings are made on a 5-star scale, with half-star increments (0.5 stars - 5.0 stars).

Timestamps represent seconds since midnight Coordinated Universal Time (UTC) of January 1, 1970.


Tags Data File Structure (tags.csv)
-----------------------------------

All tags are contained in the file `tags.csv`. Each line of this file after the header row represents one tag applied to one movie by one user, and has the following format:

userId,movieId,tag,timestamp

The lines within this file are ordered first by userId, then, within user, by movieId.

Tags are user-generated metadata about movies. Each tag is typically a single word or short phrase. The meaning, value, and purpose of a particular tag is determined by each user.

Timestamps represent seconds since midnight Coordinated Universal Time (UTC) of January 1, 1970.


Movies Data File Structure (movies.csv)
---------------------------------------

Movie information is contained in the file `movies.csv`. Each line of this file after the header row represents one movie, and has the following format:

movieId,title,genres

Movie titles are entered manually or imported from <https://www.themoviedb.org/>, and include the year of release in parentheses. Errors and inconsistencies may exist in these titles.

Genres are a pipe-separated list, and are selected from the following:

* Action
* Adventure
* Animation
* Children's
* Comedy
* Crime
* Documentary
* Drama
* Fantasy
* Film-Noir
* Horror
* Musical
* Mystery
* Romance
* Sci-Fi
* Thriller
* War
* Western
* (no genres listed)


Links Data File Structure (links.csv)
---------------------------------------

Identifiers that can be used to link to other sources of movie data are contained in the file `links.csv`. Each line of this file after the header row represents one movie, and has the following format:

movieId,imdbId,tmdbId

movieId is an identifier for movies used by <https://movielens.org>. E.g., the movie Toy Story has the link <https://movielens.org/movies/1>.

imdbId is an identifier for movies used by <http://www.imdb.com>. E.g., the movie Toy Story has the link <http://www.imdb.com/title/tt0114709/>.

tmdbId is an identifier for movies used by <https://www.themoviedb.org>. E.g., the movie Toy Story has the link <https://www.themoviedb.org/movie/862>.

Use of the resources listed above is subject to the terms of each provider.


Cross-Validation
----------------

Prior versions of the MovieLens dataset included either pre-computed cross-folds or scripts to perform this computation. We no longer bundle either of these features with the dataset, since most modern toolkits provide this as a built-in feature. If you wish to learn about standard approaches to cross-fold computation in the context of recommender systems evaluation, see [LensKit](http://lenskit.org) for tools, documentation, and open-source code examples.
Loading