yigitcanozdemir
commited on
Commit
Β·
7453e74
1
Parent(s):
6c446ba
added country wise filtering and dynamic query prompt_title generation
Browse files- components/filters.py +75 -61
- components/gradio_ui.py +19 -19
- components/similarity.py +2 -2
- config.py +182 -9
- models/pydantic_schemas.py +12 -6
- models/recommendation_engine.py +68 -53
components/filters.py
CHANGED
|
@@ -4,13 +4,13 @@ from typing import List, Optional
|
|
| 4 |
import re
|
| 5 |
from config import QUALITY_LEVELS
|
| 6 |
|
|
|
|
| 7 |
class MovieFilter:
|
| 8 |
def __init__(self):
|
| 9 |
pass
|
| 10 |
|
| 11 |
def apply_filters(self, data: pd.DataFrame, features: Features) -> pd.DataFrame:
|
| 12 |
filtered_data = data.copy()
|
| 13 |
-
|
| 14 |
|
| 15 |
if features.movie_or_series != "both":
|
| 16 |
filtered_data = self._filter_by_type(
|
|
@@ -20,13 +20,11 @@ class MovieFilter:
|
|
| 20 |
if features.genres or features.negative_genres:
|
| 21 |
filtered_data["genreScore"] = filtered_data["genres"].apply(
|
| 22 |
lambda g: self.calculate_genre_score(
|
| 23 |
-
g,
|
| 24 |
-
features.genres or [],
|
| 25 |
-
features.negative_genres or []
|
| 26 |
)
|
| 27 |
)
|
| 28 |
else:
|
| 29 |
-
|
| 30 |
filtered_data["genreScore"] = 0.0
|
| 31 |
|
| 32 |
if features.date_range:
|
|
@@ -35,7 +33,9 @@ class MovieFilter:
|
|
| 35 |
)
|
| 36 |
|
| 37 |
if features.quality_level:
|
| 38 |
-
filtered_data = self._filter_by_quality(
|
|
|
|
|
|
|
| 39 |
|
| 40 |
if (
|
| 41 |
features.min_runtime_minutes is not None
|
|
@@ -46,7 +46,10 @@ class MovieFilter:
|
|
| 46 |
features.min_runtime_minutes,
|
| 47 |
features.max_runtime_minutes,
|
| 48 |
)
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
| 50 |
return filtered_data
|
| 51 |
|
| 52 |
def _filter_by_runtime(
|
|
@@ -78,66 +81,77 @@ class MovieFilter:
|
|
| 78 |
all_types = ["movie", "tvSeries", "tvMiniSeries", "tvMovie", "video"]
|
| 79 |
return data[data["titleType"].isin(all_types)]
|
| 80 |
|
| 81 |
-
def calculate_genre_score(
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
try:
|
| 88 |
-
row_genre_list = [g.strip().lower() for g in row_genres.split(",")]
|
| 89 |
-
target_genre_list = [g.lower() for g in target_genres]
|
| 90 |
-
negative_genre_list = [g.lower() for g in negative_genres]
|
| 91 |
-
|
| 92 |
-
positive_matches = sum(1 for g in row_genre_list if g in target_genre_list)
|
| 93 |
-
|
| 94 |
-
negative_matches = sum(1 for g in row_genre_list if g in negative_genre_list)
|
| 95 |
-
|
| 96 |
-
score = 0.0
|
| 97 |
-
if target_genres:
|
| 98 |
-
score = positive_matches / len(target_genre_list)
|
| 99 |
-
elif positive_matches > 0:
|
| 100 |
-
score = 1.0
|
| 101 |
-
|
| 102 |
-
score -= (negative_matches * 0.5)
|
| 103 |
-
return max(0.0, score)
|
| 104 |
-
except (AttributeError, TypeError):
|
| 105 |
-
return 0.0
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def _filter_by_genres(self, data: pd.DataFrame, genres: List[str]) -> pd.DataFrame:
|
| 109 |
-
if not genres:
|
| 110 |
-
return data
|
| 111 |
-
|
| 112 |
-
def count_genre_matches(row_genres, target_genres):
|
| 113 |
-
if pd.isna(row_genres):
|
| 114 |
-
return 0
|
| 115 |
|
|
|
|
| 116 |
row_genre_list = [g.strip().lower() for g in row_genres.split(",")]
|
| 117 |
target_genre_list = [g.lower() for g in target_genres]
|
|
|
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
)
|
| 124 |
-
return matches
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
|
|
|
|
|
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
|
| 140 |
-
|
|
|
|
| 141 |
|
| 142 |
def _filter_by_date_range(
|
| 143 |
self, data: pd.DataFrame, date_range: List[int]
|
|
@@ -158,13 +172,13 @@ class MovieFilter:
|
|
| 158 |
if config:
|
| 159 |
condition = pd.Series(True, index=data.index)
|
| 160 |
if "min_rating" in config:
|
| 161 |
-
condition &=
|
| 162 |
if "max_rating" in config:
|
| 163 |
-
condition &=
|
| 164 |
if "min_votes" in config:
|
| 165 |
-
condition &=
|
| 166 |
if "max_votes" in config:
|
| 167 |
-
condition &=
|
| 168 |
return data[condition]
|
| 169 |
|
| 170 |
return data
|
|
|
|
| 4 |
import re
|
| 5 |
from config import QUALITY_LEVELS
|
| 6 |
|
| 7 |
+
|
| 8 |
class MovieFilter:
|
| 9 |
def __init__(self):
|
| 10 |
pass
|
| 11 |
|
| 12 |
def apply_filters(self, data: pd.DataFrame, features: Features) -> pd.DataFrame:
|
| 13 |
filtered_data = data.copy()
|
|
|
|
| 14 |
|
| 15 |
if features.movie_or_series != "both":
|
| 16 |
filtered_data = self._filter_by_type(
|
|
|
|
| 20 |
if features.genres or features.negative_genres:
|
| 21 |
filtered_data["genreScore"] = filtered_data["genres"].apply(
|
| 22 |
lambda g: self.calculate_genre_score(
|
| 23 |
+
g, features.genres or [], features.negative_genres or []
|
|
|
|
|
|
|
| 24 |
)
|
| 25 |
)
|
| 26 |
else:
|
| 27 |
+
|
| 28 |
filtered_data["genreScore"] = 0.0
|
| 29 |
|
| 30 |
if features.date_range:
|
|
|
|
| 33 |
)
|
| 34 |
|
| 35 |
if features.quality_level:
|
| 36 |
+
filtered_data = self._filter_by_quality(
|
| 37 |
+
filtered_data, features.quality_level
|
| 38 |
+
)
|
| 39 |
|
| 40 |
if (
|
| 41 |
features.min_runtime_minutes is not None
|
|
|
|
| 46 |
features.min_runtime_minutes,
|
| 47 |
features.max_runtime_minutes,
|
| 48 |
)
|
| 49 |
+
if features.country_of_origin or features.dont_wanted_countrys:
|
| 50 |
+
filtered_data = self._filter_by_country_of_origin(
|
| 51 |
+
filtered_data, features.country_of_origin, features.dont_wanted_countrys
|
| 52 |
+
)
|
| 53 |
return filtered_data
|
| 54 |
|
| 55 |
def _filter_by_runtime(
|
|
|
|
| 81 |
all_types = ["movie", "tvSeries", "tvMiniSeries", "tvMovie", "video"]
|
| 82 |
return data[data["titleType"].isin(all_types)]
|
| 83 |
|
| 84 |
+
def calculate_genre_score(
|
| 85 |
+
self, row_genres: str, target_genres: List[str], negative_genres: List[str]
|
| 86 |
+
) -> float:
|
| 87 |
+
if not row_genres or pd.isna(row_genres):
|
| 88 |
+
return 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
try:
|
| 91 |
row_genre_list = [g.strip().lower() for g in row_genres.split(",")]
|
| 92 |
target_genre_list = [g.lower() for g in target_genres]
|
| 93 |
+
negative_genre_list = [g.lower() for g in negative_genres]
|
| 94 |
|
| 95 |
+
positive_matches = sum(1 for g in row_genre_list if g in target_genre_list)
|
| 96 |
+
|
| 97 |
+
negative_matches = sum(
|
| 98 |
+
1 for g in row_genre_list if g in negative_genre_list
|
| 99 |
)
|
|
|
|
| 100 |
|
| 101 |
+
score = 0.0
|
| 102 |
+
if target_genres:
|
| 103 |
+
score = positive_matches / len(target_genre_list)
|
| 104 |
+
elif positive_matches > 0:
|
| 105 |
+
score = 1.0
|
| 106 |
+
|
| 107 |
+
score -= negative_matches * 0.5
|
| 108 |
+
return score
|
| 109 |
+
except (AttributeError, TypeError):
|
| 110 |
+
return 0.0
|
| 111 |
+
|
| 112 |
+
def _filter_by_country_of_origin(
|
| 113 |
+
self,
|
| 114 |
+
data: pd.DataFrame,
|
| 115 |
+
country_of_origin: List[str],
|
| 116 |
+
dont_wanted_countrys: List[str] = None,
|
| 117 |
+
) -> pd.DataFrame:
|
| 118 |
+
if not country_of_origin and not dont_wanted_countrys:
|
| 119 |
+
return data
|
| 120 |
+
|
| 121 |
+
data_with_country = data.dropna(subset=["country_of_origin"])
|
| 122 |
|
| 123 |
+
def country_matches(row_countries: str) -> bool:
|
| 124 |
+
if not row_countries or pd.isna(row_countries):
|
| 125 |
+
return False
|
| 126 |
|
| 127 |
+
try:
|
| 128 |
+
row_country_list = [
|
| 129 |
+
country.strip() for country in row_countries.split(",")
|
| 130 |
+
]
|
| 131 |
+
|
| 132 |
+
if dont_wanted_countrys:
|
| 133 |
+
has_unwanted = any(
|
| 134 |
+
unwanted_country == row_country
|
| 135 |
+
for unwanted_country in dont_wanted_countrys
|
| 136 |
+
for row_country in row_country_list
|
| 137 |
+
)
|
| 138 |
+
if has_unwanted:
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
if country_of_origin:
|
| 142 |
+
return any(
|
| 143 |
+
target_country == row_country
|
| 144 |
+
for target_country in country_of_origin
|
| 145 |
+
for row_country in row_country_list
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return True
|
| 149 |
|
| 150 |
+
except (AttributeError, TypeError):
|
| 151 |
+
return False
|
| 152 |
|
| 153 |
+
mask = data_with_country["country_of_origin"].apply(country_matches)
|
| 154 |
+
return data_with_country[mask]
|
| 155 |
|
| 156 |
def _filter_by_date_range(
|
| 157 |
self, data: pd.DataFrame, date_range: List[int]
|
|
|
|
| 172 |
if config:
|
| 173 |
condition = pd.Series(True, index=data.index)
|
| 174 |
if "min_rating" in config:
|
| 175 |
+
condition &= data["averageRating"] >= config["min_rating"]
|
| 176 |
if "max_rating" in config:
|
| 177 |
+
condition &= data["averageRating"] <= config["max_rating"]
|
| 178 |
if "min_votes" in config:
|
| 179 |
+
condition &= data["numVotes"] >= config["min_votes"]
|
| 180 |
if "max_votes" in config:
|
| 181 |
+
condition &= data["numVotes"] <= config["max_votes"]
|
| 182 |
return data[condition]
|
| 183 |
|
| 184 |
return data
|
components/gradio_ui.py
CHANGED
|
@@ -15,25 +15,26 @@ def get_recommendations_api(message, engine):
|
|
| 15 |
df = result[1] if isinstance(result, tuple) and len(result) > 1 else None
|
| 16 |
if df is None or df.empty:
|
| 17 |
return []
|
| 18 |
-
|
| 19 |
recommendations = []
|
| 20 |
for idx, (_, row) in enumerate(df.iterrows()):
|
| 21 |
recommendations.append(
|
| 22 |
{
|
| 23 |
-
"imdb_id": row["
|
| 24 |
-
"title": row["
|
| 25 |
-
"year": row["
|
| 26 |
-
"type": row["
|
| 27 |
-
"rating": row["
|
| 28 |
-
"runtime_minutes": row["
|
| 29 |
-
"votes": row["
|
| 30 |
-
"genres": row["
|
| 31 |
-
"similarity": row["
|
| 32 |
-
"hybrid_score": row["
|
| 33 |
-
"overview": row["
|
| 34 |
-
"poster_url": row["
|
| 35 |
-
"final_score": row["
|
| 36 |
-
"genre_score": row["
|
|
|
|
| 37 |
}
|
| 38 |
)
|
| 39 |
|
|
@@ -51,7 +52,7 @@ def get_recommendations_api(message, engine):
|
|
| 51 |
titles = result_df["title"].tolist()
|
| 52 |
print(titles)
|
| 53 |
print(result_df)
|
| 54 |
-
return recommendations
|
| 55 |
except Exception as e:
|
| 56 |
print(f"Error getting recommendations: {e}")
|
| 57 |
return []
|
|
@@ -63,10 +64,9 @@ def create_interface(engine):
|
|
| 63 |
|
| 64 |
iface = gr.Interface(
|
| 65 |
fn=predict_wrapper,
|
| 66 |
-
inputs=gr.Textbox(lines=1, placeholder="Type your
|
| 67 |
outputs=gr.JSON(label="Recommendations"),
|
| 68 |
-
title="
|
| 69 |
-
description="Type a movie or genre, get recommendations with posters.",
|
| 70 |
api_name="predict",
|
| 71 |
)
|
| 72 |
return iface
|
|
|
|
| 15 |
df = result[1] if isinstance(result, tuple) and len(result) > 1 else None
|
| 16 |
if df is None or df.empty:
|
| 17 |
return []
|
| 18 |
+
prompt_title = result[0]
|
| 19 |
recommendations = []
|
| 20 |
for idx, (_, row) in enumerate(df.iterrows()):
|
| 21 |
recommendations.append(
|
| 22 |
{
|
| 23 |
+
"imdb_id": row["tconst"],
|
| 24 |
+
"title": row["title"],
|
| 25 |
+
"year": row["year"],
|
| 26 |
+
"type": row["type"],
|
| 27 |
+
"rating": row["rating"],
|
| 28 |
+
"runtime_minutes": row["runtimeMinutes"],
|
| 29 |
+
"votes": row["votes"],
|
| 30 |
+
"genres": row["genres"],
|
| 31 |
+
"similarity": row["similarity_score"],
|
| 32 |
+
"hybrid_score": row["hybrid_score"],
|
| 33 |
+
"overview": row["overview"],
|
| 34 |
+
"poster_url": row["poster_url"],
|
| 35 |
+
"final_score": row["final_score"],
|
| 36 |
+
"genre_score": row["genre_score"],
|
| 37 |
+
"country_of_origin": row["country_of_origin"],
|
| 38 |
}
|
| 39 |
)
|
| 40 |
|
|
|
|
| 52 |
titles = result_df["title"].tolist()
|
| 53 |
print(titles)
|
| 54 |
print(result_df)
|
| 55 |
+
return {"recommendations": recommendations, "prompt_title": prompt_title}
|
| 56 |
except Exception as e:
|
| 57 |
print(f"Error getting recommendations: {e}")
|
| 58 |
return []
|
|
|
|
| 64 |
|
| 65 |
iface = gr.Interface(
|
| 66 |
fn=predict_wrapper,
|
| 67 |
+
inputs=gr.Textbox(lines=1, placeholder="Type your query..."),
|
| 68 |
outputs=gr.JSON(label="Recommendations"),
|
| 69 |
+
title="Recommendation API",
|
|
|
|
| 70 |
api_name="predict",
|
| 71 |
)
|
| 72 |
return iface
|
components/similarity.py
CHANGED
|
@@ -97,7 +97,7 @@ class SimilarityCalculator:
|
|
| 97 |
filtered_data,
|
| 98 |
similarity_weight=1,
|
| 99 |
rating_weight=rating_weight,
|
| 100 |
-
genre_weight=0.
|
| 101 |
)
|
| 102 |
|
| 103 |
top_indices = (
|
|
@@ -105,7 +105,6 @@ class SimilarityCalculator:
|
|
| 105 |
.indices.cpu()
|
| 106 |
.numpy()
|
| 107 |
)
|
| 108 |
-
|
| 109 |
results = []
|
| 110 |
for idx in top_indices:
|
| 111 |
original_idx = filtered_data.iloc[idx].name
|
|
@@ -126,6 +125,7 @@ class SimilarityCalculator:
|
|
| 126 |
"final_score": row["finalScore"],
|
| 127 |
"genre_score": row["genreScore"],
|
| 128 |
"poster_url": row["poster_url"],
|
|
|
|
| 129 |
}
|
| 130 |
results.append(result)
|
| 131 |
|
|
|
|
| 97 |
filtered_data,
|
| 98 |
similarity_weight=1,
|
| 99 |
rating_weight=rating_weight,
|
| 100 |
+
genre_weight=0.3,
|
| 101 |
)
|
| 102 |
|
| 103 |
top_indices = (
|
|
|
|
| 105 |
.indices.cpu()
|
| 106 |
.numpy()
|
| 107 |
)
|
|
|
|
| 108 |
results = []
|
| 109 |
for idx in top_indices:
|
| 110 |
original_idx = filtered_data.iloc[idx].name
|
|
|
|
| 125 |
"final_score": row["finalScore"],
|
| 126 |
"genre_score": row["genreScore"],
|
| 127 |
"poster_url": row["poster_url"],
|
| 128 |
+
"country_of_origin": row["country_of_origin"],
|
| 129 |
}
|
| 130 |
results.append(result)
|
| 131 |
|
config.py
CHANGED
|
@@ -35,15 +35,188 @@ GENRE_LIST = Literal[
|
|
| 35 |
"Adult",
|
| 36 |
"Reality-TV",
|
| 37 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
QUALITY_LEVELS = {
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
| 47 |
|
| 48 |
class Config:
|
| 49 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
|
@@ -54,4 +227,4 @@ class Config:
|
|
| 54 |
DATA_FILE = "data/demo_data.parquet"
|
| 55 |
|
| 56 |
THEME = "soft"
|
| 57 |
-
TITLE = "π¬ AI Movie & TV Series Recommender"
|
|
|
|
| 35 |
"Adult",
|
| 36 |
"Reality-TV",
|
| 37 |
]
|
| 38 |
+
|
| 39 |
+
COUNTRY_LIST = Literal[
|
| 40 |
+
"Italy",
|
| 41 |
+
"France",
|
| 42 |
+
"Sweden",
|
| 43 |
+
"Germany",
|
| 44 |
+
"United States",
|
| 45 |
+
"Denmark",
|
| 46 |
+
"Soviet Union",
|
| 47 |
+
"United Kingdom",
|
| 48 |
+
"Australia",
|
| 49 |
+
"Austria",
|
| 50 |
+
"Switzerland",
|
| 51 |
+
"Japan",
|
| 52 |
+
"Canada",
|
| 53 |
+
"Isle of Man",
|
| 54 |
+
"Hungary",
|
| 55 |
+
"Brazil",
|
| 56 |
+
"Czechoslovakia",
|
| 57 |
+
"Portugal",
|
| 58 |
+
"Mexico",
|
| 59 |
+
"Norway",
|
| 60 |
+
"India",
|
| 61 |
+
"West Germany",
|
| 62 |
+
"Yugoslavia",
|
| 63 |
+
"Spain",
|
| 64 |
+
"Egypt",
|
| 65 |
+
"Finland",
|
| 66 |
+
"Albania",
|
| 67 |
+
"Poland",
|
| 68 |
+
"Greece",
|
| 69 |
+
"Hong Kong",
|
| 70 |
+
"East Germany",
|
| 71 |
+
"Venezuela",
|
| 72 |
+
"Ireland",
|
| 73 |
+
"Jamaica",
|
| 74 |
+
"Monaco",
|
| 75 |
+
"Turkey",
|
| 76 |
+
"Bulgaria",
|
| 77 |
+
"Romania",
|
| 78 |
+
"Israel",
|
| 79 |
+
"Cuba",
|
| 80 |
+
"Algeria",
|
| 81 |
+
"Bahamas",
|
| 82 |
+
"China",
|
| 83 |
+
"Taiwan",
|
| 84 |
+
"South Africa",
|
| 85 |
+
"Senegal",
|
| 86 |
+
"Belgium",
|
| 87 |
+
"Bermuda",
|
| 88 |
+
"Morocco",
|
| 89 |
+
"Argentina",
|
| 90 |
+
"Netherlands",
|
| 91 |
+
"Croatia",
|
| 92 |
+
"Chile",
|
| 93 |
+
"Iran",
|
| 94 |
+
"Estonia",
|
| 95 |
+
"Luxembourg",
|
| 96 |
+
"Peru",
|
| 97 |
+
"Colombia",
|
| 98 |
+
"Bangladesh",
|
| 99 |
+
"Thailand",
|
| 100 |
+
"Philippines",
|
| 101 |
+
"Lebanon",
|
| 102 |
+
"Libya",
|
| 103 |
+
"Kuwait",
|
| 104 |
+
"CΓ΄te d'Ivoire",
|
| 105 |
+
"Iceland",
|
| 106 |
+
"South Korea",
|
| 107 |
+
"Fiji",
|
| 108 |
+
"Botswana",
|
| 109 |
+
"New Zealand",
|
| 110 |
+
"Greenland",
|
| 111 |
+
"Martinique",
|
| 112 |
+
"Netherlands Antilles",
|
| 113 |
+
"Tunisia",
|
| 114 |
+
"Indonesia",
|
| 115 |
+
"Zimbabwe",
|
| 116 |
+
"Kenya",
|
| 117 |
+
"Mali",
|
| 118 |
+
"Burkina Faso",
|
| 119 |
+
"Cameroon",
|
| 120 |
+
"Ghana",
|
| 121 |
+
"North Korea",
|
| 122 |
+
"Macao",
|
| 123 |
+
"Jordan",
|
| 124 |
+
"Antarctica",
|
| 125 |
+
"Vietnam",
|
| 126 |
+
"Russia",
|
| 127 |
+
"Federal Republic of Yugoslavia",
|
| 128 |
+
"Uruguay",
|
| 129 |
+
"Malaysia",
|
| 130 |
+
"Armenia",
|
| 131 |
+
"Czech Republic",
|
| 132 |
+
"Liechtenstein",
|
| 133 |
+
"Georgia",
|
| 134 |
+
"North Macedonia",
|
| 135 |
+
"Bosnia and Herzegovina",
|
| 136 |
+
"Slovakia",
|
| 137 |
+
"Kazakhstan",
|
| 138 |
+
"Slovenia",
|
| 139 |
+
"Singapore",
|
| 140 |
+
"Cambodia",
|
| 141 |
+
"Aruba",
|
| 142 |
+
"Tajikistan",
|
| 143 |
+
"Latvia",
|
| 144 |
+
"Uzbekistan",
|
| 145 |
+
"Malta",
|
| 146 |
+
"Ukraine",
|
| 147 |
+
"Pakistan",
|
| 148 |
+
"Bhutan",
|
| 149 |
+
"Belarus",
|
| 150 |
+
"Cyprus",
|
| 151 |
+
"Nepal",
|
| 152 |
+
"Haiti",
|
| 153 |
+
"Lithuania",
|
| 154 |
+
"United Arab Emirates",
|
| 155 |
+
"Occupied Palestinian Territory",
|
| 156 |
+
"Serbia",
|
| 157 |
+
"Serbia and Montenegro",
|
| 158 |
+
"Afghanistan",
|
| 159 |
+
"Mongolia",
|
| 160 |
+
"Ecuador",
|
| 161 |
+
"Puerto Rico",
|
| 162 |
+
"Rwanda",
|
| 163 |
+
"Vatican",
|
| 164 |
+
"Guatemala",
|
| 165 |
+
"Iraq",
|
| 166 |
+
"Paraguay",
|
| 167 |
+
"Bahrain",
|
| 168 |
+
"Saudi Arabia",
|
| 169 |
+
"Qatar",
|
| 170 |
+
"Cayman Islands",
|
| 171 |
+
"Sudan",
|
| 172 |
+
"Dominican Republic",
|
| 173 |
+
"Sri Lanka",
|
| 174 |
+
"Liberia",
|
| 175 |
+
"Lesotho",
|
| 176 |
+
"Bolivia",
|
| 177 |
+
"Faroe Islands",
|
| 178 |
+
"Azerbaijan",
|
| 179 |
+
"New Caledonia",
|
| 180 |
+
"Costa Rica",
|
| 181 |
+
"Nigeria",
|
| 182 |
+
"Kosovo",
|
| 183 |
+
"French Polynesia",
|
| 184 |
+
"Syria",
|
| 185 |
+
"Papua New Guinea",
|
| 186 |
+
"Gambia",
|
| 187 |
+
"Chad",
|
| 188 |
+
"Panama",
|
| 189 |
+
"Moldova",
|
| 190 |
+
"Uganda",
|
| 191 |
+
"Montenegro",
|
| 192 |
+
"Laos",
|
| 193 |
+
"Mauritius",
|
| 194 |
+
"Ethiopia",
|
| 195 |
+
"Kyrgyzstan",
|
| 196 |
+
"Namibia",
|
| 197 |
+
"Benin",
|
| 198 |
+
"Mauritania",
|
| 199 |
+
"The Democratic Republic of Congo",
|
| 200 |
+
"Vanuatu",
|
| 201 |
+
"Myanmar",
|
| 202 |
+
"Tanzania",
|
| 203 |
+
"Marshall Islands",
|
| 204 |
+
"Zambia",
|
| 205 |
+
"Guadeloupe",
|
| 206 |
+
"Malawi",
|
| 207 |
+
"Yemen",
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
QUALITY_LEVELS = {
|
| 211 |
+
"legendary": {"min_rating": 8.0, "min_votes": 100000, "rating_weight": 0.2},
|
| 212 |
+
"classic": {"min_rating": 7.5, "min_votes": 50000, "rating_weight": 0.15},
|
| 213 |
+
"popular": {"min_rating": 6.5, "min_votes": 10000, "rating_weight": 0.15},
|
| 214 |
+
"niche": {"min_rating": 7.0, "max_votes": 50000, "rating_weight": -0.1},
|
| 215 |
+
"cult": {"min_rating": 6.0, "max_votes": 25000, "rating_weight": -0.15},
|
| 216 |
+
"mainstream": {"min_rating": 5.5, "min_votes": 10000, "rating_weight": 0.2},
|
| 217 |
+
"any": {"rating_weight": 0.1},
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
|
| 221 |
class Config:
|
| 222 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
|
|
|
| 227 |
DATA_FILE = "data/demo_data.parquet"
|
| 228 |
|
| 229 |
THEME = "soft"
|
| 230 |
+
TITLE = "π¬ AI Movie & TV Series Recommender"
|
models/pydantic_schemas.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from pydantic import BaseModel, Field
|
| 2 |
from typing import Literal, Optional
|
| 3 |
-
from config import GENRE_LIST
|
| 4 |
-
|
| 5 |
|
| 6 |
class Features(BaseModel):
|
| 7 |
movie_or_series: Literal["movie", "tvSeries", "both"] = Field(
|
|
@@ -15,11 +15,10 @@ class Features(BaseModel):
|
|
| 15 |
)
|
| 16 |
quality_level: str = Field(
|
| 17 |
default="any",
|
| 18 |
-
description="Quality expectation: legendary, classic, popular, niche, cult, mainstream, any"
|
| 19 |
)
|
| 20 |
-
positive_themes: str = Field(
|
| 21 |
-
|
| 22 |
-
description="Themes that should be present in the results"
|
| 23 |
)
|
| 24 |
negative_themes: Optional[str] = Field(
|
| 25 |
description="Themes that should be avoided in the results"
|
|
@@ -33,3 +32,10 @@ class Features(BaseModel):
|
|
| 33 |
max_runtime_minutes: Optional[int] = Field(
|
| 34 |
description="Preferred maximum runtimes as minutes", default=None
|
| 35 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from pydantic import BaseModel, Field
|
| 2 |
from typing import Literal, Optional
|
| 3 |
+
from config import GENRE_LIST, COUNTRY_LIST
|
| 4 |
+
|
| 5 |
|
| 6 |
class Features(BaseModel):
|
| 7 |
movie_or_series: Literal["movie", "tvSeries", "both"] = Field(
|
|
|
|
| 15 |
)
|
| 16 |
quality_level: str = Field(
|
| 17 |
default="any",
|
| 18 |
+
description="Quality expectation: legendary, classic, popular, niche, cult, mainstream, any",
|
| 19 |
)
|
| 20 |
+
positive_themes: Optional[str] = Field(
|
| 21 |
+
description="Themes that should be present in the results",
|
|
|
|
| 22 |
)
|
| 23 |
negative_themes: Optional[str] = Field(
|
| 24 |
description="Themes that should be avoided in the results"
|
|
|
|
| 32 |
max_runtime_minutes: Optional[int] = Field(
|
| 33 |
description="Preferred maximum runtimes as minutes", default=None
|
| 34 |
)
|
| 35 |
+
country_of_origin: list[COUNTRY_LIST] = Field(
|
| 36 |
+
description="Preferred country of production"
|
| 37 |
+
)
|
| 38 |
+
dont_wanted_countrys: list[COUNTRY_LIST] = Field(
|
| 39 |
+
description="Unwanted country of production"
|
| 40 |
+
)
|
| 41 |
+
prompt_title: str = Field(description="A short and meaningful title for the prompt")
|
models/recommendation_engine.py
CHANGED
|
@@ -72,11 +72,6 @@ class RecommendationEngine:
|
|
| 72 |
raise similarity_error
|
| 73 |
|
| 74 |
print(f"π Found {len(search_results['results'])} results.")
|
| 75 |
-
print("π Formatting results...")
|
| 76 |
-
start_time = time.time()
|
| 77 |
-
formatted_results = self._format_results(search_results)
|
| 78 |
-
format_time = time.time() - start_time
|
| 79 |
-
print(f"β
Results formatted in {format_time:.4f} seconds")
|
| 80 |
|
| 81 |
print("π Creating results dataframe...")
|
| 82 |
start_time = time.time()
|
|
@@ -85,7 +80,7 @@ class RecommendationEngine:
|
|
| 85 |
print(f"β
Dataframe created in {df_time:.4f} seconds")
|
| 86 |
|
| 87 |
print("π Recommendation process completed successfully!")
|
| 88 |
-
return
|
| 89 |
|
| 90 |
except Exception as e:
|
| 91 |
print(f"β Critical error in recommendation process: {str(e)}")
|
|
@@ -120,7 +115,7 @@ class RecommendationEngine:
|
|
| 120 |
---
|
| 121 |
|
| 122 |
### GENRES
|
| 123 |
-
- If the user mentions a specific movie/show, extract its ACTUAL genres (e.g., IMDb/TMDB genres).
|
| 124 |
- If unsure, infer 1β2 of the most likely/popular genres.
|
| 125 |
- If user directly mentions genres, match exactly from the allowed genre list.
|
| 126 |
- Prefer accuracy over guessing; leave empty if absolutely no genre can be inferred.
|
|
@@ -211,9 +206,10 @@ class RecommendationEngine:
|
|
| 211 |
β
GOOD THEMES EXAMPLES:
|
| 212 |
- βIn 1970s New York, a Mafia don must navigate betrayal and FBI pressure to hold his criminal empire together.β
|
| 213 |
- βA Mexican drug lord rises to power as DEA agents close in on his cross-border empire.β
|
| 214 |
-
-
|
| 215 |
-
-
|
| 216 |
-
-
|
|
|
|
| 217 |
β BAD THEMES TO AVOID:
|
| 218 |
- βA powerful family faces betrayal as they try to protect their empire.β βΆ Too vague and franchise-prone
|
| 219 |
|
|
@@ -255,11 +251,57 @@ class RecommendationEngine:
|
|
| 255 |
- Defaults to `[1900, 2025]` if not constrained.
|
| 256 |
- "recent", "modern" β prefer `[2010, 2025]`
|
| 257 |
- "classic", "old" β prefer `[1950, 1995]`
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
---
|
| 260 |
|
| 261 |
### LANGUAGE
|
| 262 |
If the query is not in English, **translate to English first**, then apply the above rules.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
---
|
| 265 |
|
|
@@ -290,34 +332,6 @@ class RecommendationEngine:
|
|
| 290 |
production_region=[],
|
| 291 |
)
|
| 292 |
|
| 293 |
-
def _format_results(self, search_results: dict) -> str:
|
| 294 |
-
if not search_results["results"]:
|
| 295 |
-
return search_results["status"]
|
| 296 |
-
|
| 297 |
-
output = []
|
| 298 |
-
output.append(f"π¬ {search_results['status']}")
|
| 299 |
-
output.append(
|
| 300 |
-
f"π Search completed in {search_results['search_time']:.4f} seconds"
|
| 301 |
-
)
|
| 302 |
-
output.append(
|
| 303 |
-
f"π Found {len(search_results['results'])} results from {search_results['total_candidates']} candidates"
|
| 304 |
-
)
|
| 305 |
-
output.append("=" * 50)
|
| 306 |
-
|
| 307 |
-
for i, result in enumerate(search_results["results"], 1):
|
| 308 |
-
output.append(f"{i}. **{result['title']}** ({result['year']})")
|
| 309 |
-
output.append(f" π Type: {result['type'].title()}")
|
| 310 |
-
output.append(
|
| 311 |
-
f" β Rating: {result['rating']}/10 ({result['votes']:,} votes)"
|
| 312 |
-
)
|
| 313 |
-
output.append(f" π Genres: {result['genres']}")
|
| 314 |
-
output.append(f" π Similarity: {result['similarity_score']:.4f}")
|
| 315 |
-
output.append(f" π Hybrid Score: {result['hybrid_score']:.4f}")
|
| 316 |
-
output.append(f" π {result['overview']}")
|
| 317 |
-
output.append("")
|
| 318 |
-
|
| 319 |
-
return "\n".join(output)
|
| 320 |
-
|
| 321 |
def _create_results_dataframe(self, search_results: dict) -> pd.DataFrame:
|
| 322 |
if not search_results["results"]:
|
| 323 |
return pd.DataFrame()
|
|
@@ -326,20 +340,21 @@ class RecommendationEngine:
|
|
| 326 |
for result in search_results["results"]:
|
| 327 |
df_data.append(
|
| 328 |
{
|
| 329 |
-
"
|
| 330 |
-
"
|
| 331 |
-
"
|
| 332 |
-
"
|
| 333 |
-
"
|
| 334 |
-
"
|
| 335 |
-
"
|
| 336 |
-
"
|
| 337 |
-
"
|
| 338 |
-
"
|
| 339 |
-
"
|
| 340 |
-
"
|
| 341 |
-
"
|
| 342 |
-
"
|
|
|
|
| 343 |
}
|
| 344 |
)
|
| 345 |
return pd.DataFrame(df_data)
|
|
|
|
| 72 |
raise similarity_error
|
| 73 |
|
| 74 |
print(f"π Found {len(search_results['results'])} results.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
print("π Creating results dataframe...")
|
| 77 |
start_time = time.time()
|
|
|
|
| 80 |
print(f"β
Dataframe created in {df_time:.4f} seconds")
|
| 81 |
|
| 82 |
print("π Recommendation process completed successfully!")
|
| 83 |
+
return features.prompt_title, results_df
|
| 84 |
|
| 85 |
except Exception as e:
|
| 86 |
print(f"β Critical error in recommendation process: {str(e)}")
|
|
|
|
| 115 |
---
|
| 116 |
|
| 117 |
### GENRES
|
| 118 |
+
- If the user mentions a specific movie/show, extract its ACTUAL genres (e.g., IMDb/TMDB genres). (Example if user wants anime, select animation etc.)
|
| 119 |
- If unsure, infer 1β2 of the most likely/popular genres.
|
| 120 |
- If user directly mentions genres, match exactly from the allowed genre list.
|
| 121 |
- Prefer accuracy over guessing; leave empty if absolutely no genre can be inferred.
|
|
|
|
| 206 |
β
GOOD THEMES EXAMPLES:
|
| 207 |
- βIn 1970s New York, a Mafia don must navigate betrayal and FBI pressure to hold his criminal empire together.β
|
| 208 |
- βA Mexican drug lord rises to power as DEA agents close in on his cross-border empire.β
|
| 209 |
+
- βNew Jersey mob boss Tony Soprano deals with personal and professional issues in his home and business life that affect his mental state, leading him to seek professional psychiatric counseling.β
|
| 210 |
+
- βIn an alternative version of 1969, the Soviet Union beats the United States to the Moon, and the space race continues on for decades with still grander challenges and goals.β
|
| 211 |
+
- βWhen Earth becomes uninhabitable in the future, a farmer and ex-NASA pilot, Joseph Cooper, is tasked to pilot a spacecraft, along with a team of researchers, to find a new planet for humansβ
|
| 212 |
+
- βAn astronaut becomes stranded on Mars after his team assume him dead, and must rely on his ingenuity to find a way to signal to Earth that he is alive and can survive until a potential rescue.β
|
| 213 |
β BAD THEMES TO AVOID:
|
| 214 |
- βA powerful family faces betrayal as they try to protect their empire.β βΆ Too vague and franchise-prone
|
| 215 |
|
|
|
|
| 251 |
- Defaults to `[1900, 2025]` if not constrained.
|
| 252 |
- "recent", "modern" β prefer `[2010, 2025]`
|
| 253 |
- "classic", "old" β prefer `[1950, 1995]`
|
| 254 |
+
|
| 255 |
+
---
|
| 256 |
+
|
| 257 |
+
### COUNTRY OF ORIGIN
|
| 258 |
+
Analyze the user's country of origin preference:
|
| 259 |
+
- "Turkish movies", "TΓΌrk filmi" β `["Turkey"]`
|
| 260 |
+
- "Hollywood films", "American movies" β `["United States"]`
|
| 261 |
+
- "Bollywood", "Indian cinema" β `["India"]`
|
| 262 |
+
- "French films", "French cinema" β `["France"]`
|
| 263 |
+
- "Korean movies", "K-drama" β `["South Korea"]`
|
| 264 |
+
- "Japanese anime", "Japanese films" β `["Japan"]`
|
| 265 |
+
- "British series", "UK shows" β `["United Kingdom"]`
|
| 266 |
+
- "German films", "German cinema" β `["Germany"]`
|
| 267 |
+
- "Italian movies", "Italian cinema" β `["Italy"]`
|
| 268 |
+
- "Spanish films", "Spanish series" β `["Spain"]`
|
| 269 |
+
- "Russian movies", "Russian cinema" β `["Russia"]`
|
| 270 |
+
- "Chinese films", "Chinese cinema" β `["China"]`
|
| 271 |
+
- "Brazilian movies", "Brazilian cinema" β `["Brazil"]`
|
| 272 |
+
- "Mexican series", "Mexican films" β `["Mexico"]`
|
| 273 |
+
- "Canadian films", "Canadian cinema" β `["Canada"]`
|
| 274 |
+
- "Australian movies", "Australian cinema" β `["Australia"]`
|
| 275 |
+
|
| 276 |
+
#### REGIONAL/CULTURAL CLUES:
|
| 277 |
+
- "Nordic noir", "Scandinavian" β `["Norway", "Sweden", "Denmark"]`
|
| 278 |
+
- "European cinema" β `["France", "Germany", "Italy", "Spain", "United Kingdom"]`
|
| 279 |
+
- "Asian cinema" β `["Japan", "South Korea", "China", "India"]`
|
| 280 |
+
- "Latin American" β `["Mexico", "Brazil", "Argentina", "Colombia"]`
|
| 281 |
+
- "Middle Eastern" β `["Turkey", "Iran", "Israel", "Lebanon"]`
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
#### PLATFORM/DISTRIBUTOR CLUES:
|
| 286 |
+
- "Netflix original" β Varies by platform, usually `["United States"]`
|
| 287 |
+
- "BBC series" β `["United Kingdom"]`
|
| 288 |
+
- "HBO series" β `["United States"]`
|
| 289 |
+
- "Amazon Prime" β Usually `["United States"]`
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
#### DEFAULT BEHAVIORS:
|
| 293 |
+
- No country specified: `[]` (empty list - all countries)
|
| 294 |
+
- Ambiguous expressions: `[]` (empty list)
|
| 295 |
+
- Multiple country preference: Return as list (e.g., `["United States", "United Kingdom"]`)
|
| 296 |
+
|
| 297 |
---
|
| 298 |
|
| 299 |
### LANGUAGE
|
| 300 |
If the query is not in English, **translate to English first**, then apply the above rules.
|
| 301 |
+
|
| 302 |
+
### PROMPT TITLE
|
| 303 |
+
Generate a short, clear, and meaningful title for users query.
|
| 304 |
+
***Critical: Always return title
|
| 305 |
|
| 306 |
---
|
| 307 |
|
|
|
|
| 332 |
production_region=[],
|
| 333 |
)
|
| 334 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
def _create_results_dataframe(self, search_results: dict) -> pd.DataFrame:
|
| 336 |
if not search_results["results"]:
|
| 337 |
return pd.DataFrame()
|
|
|
|
| 340 |
for result in search_results["results"]:
|
| 341 |
df_data.append(
|
| 342 |
{
|
| 343 |
+
"tconst": result["tconst"],
|
| 344 |
+
"title": result["title"],
|
| 345 |
+
"type": result["type"],
|
| 346 |
+
"year": result["year"],
|
| 347 |
+
"rating": result["rating"],
|
| 348 |
+
"runtimeMinutes": result["runtimeMinutes"],
|
| 349 |
+
"votes": result["votes"],
|
| 350 |
+
"genres": result["genres"],
|
| 351 |
+
"similarity_score": f"{result['similarity_score']:.4f}",
|
| 352 |
+
"hybrid_score": f"{result['hybrid_score']:.4f}",
|
| 353 |
+
"overview": result["overview"],
|
| 354 |
+
"final_score": f"{result['final_score']:.4f}",
|
| 355 |
+
"genre_score": f"{result['genre_score']:.4f}",
|
| 356 |
+
"poster_url": result["poster_url"],
|
| 357 |
+
"country_of_origin": result["country_of_origin"],
|
| 358 |
}
|
| 359 |
)
|
| 360 |
return pd.DataFrame(df_data)
|