Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from datasets import load_dataset
|
| 4 |
+
|
| 5 |
+
# 1. Load MovieLens 100K from the Hub
|
| 6 |
+
ml = load_dataset("movielens", "100k") # train + test splits
|
| 7 |
+
df = pd.concat([
|
| 8 |
+
ml["train"].to_pandas(),
|
| 9 |
+
ml["test"].to_pandas()
|
| 10 |
+
], ignore_index=True)
|
| 11 |
+
|
| 12 |
+
# 2. Extract year and prepare genres
|
| 13 |
+
df["year"] = pd.to_datetime(df["timestamp"], unit="s").dt.year
|
| 14 |
+
# movieId → title/genres mapping is in the "movies" config
|
| 15 |
+
movies = load_dataset("movielens", "100k", split="train") \
|
| 16 |
+
.to_pandas()[["movieId","title","genres"]].drop_duplicates()
|
| 17 |
+
df = df.merge(movies, on="movieId", how="left")
|
| 18 |
+
|
| 19 |
+
# 3. Deduplicate for metadata
|
| 20 |
+
metadata = df[["title","genres","year"]].drop_duplicates()
|
| 21 |
+
|
| 22 |
+
def recommend_by_genre_year(genre, year, top_k=5):
|
| 23 |
+
mask_genre = metadata["genres"].str.lower().str.contains(genre.lower())
|
| 24 |
+
mask_year = metadata["year"] >= year
|
| 25 |
+
candidates = metadata[mask_genre & mask_year]
|
| 26 |
+
if candidates.empty:
|
| 27 |
+
return f"No {genre.title()} movies found from {year} onward."
|
| 28 |
+
picks = candidates.sample(min(top_k, len(candidates)))
|
| 29 |
+
return "\n".join(f"• {row.title} ({row.year})" for _, row in picks.iterrows())
|
| 30 |
+
|
| 31 |
+
iface = gr.Interface(
|
| 32 |
+
fn=recommend_by_genre_year,
|
| 33 |
+
inputs=[
|
| 34 |
+
gr.Textbox(label="Genre", placeholder="e.g. Action, Romance"),
|
| 35 |
+
gr.Number(label="Release Year (≥)", value=2010),
|
| 36 |
+
gr.Slider(1, 10, step=1, label="Number of Recommendations", value=5)
|
| 37 |
+
],
|
| 38 |
+
outputs="text",
|
| 39 |
+
title="🎬 Online MovieLens Recommender",
|
| 40 |
+
description="""
|
| 41 |
+
Pulls MovieLens 100K live from Hugging Face Datasets—no local files needed.
|
| 42 |
+
Filters by genre substring and release year (inferred from timestamp).
|
| 43 |
+
"""
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if __name__ == "__main__":
|
| 47 |
+
iface.launch()
|