manuschyan.h commited on
Commit
b73366b
·
1 Parent(s): 981dd27

adding app

Browse files
Files changed (2) hide show
  1. app.py +28 -60
  2. movie_recommender.py +192 -0
app.py CHANGED
@@ -1,64 +1,32 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ from movie_recommender import MovieRecommender
3
+
4
+ # Initialize the recommender
5
+ recommender = MovieRecommender()
6
+
7
+ def get_recommendations(vibe_query):
8
+ """
9
+ This function takes a user's query, gets recommendations from the
10
+ MovieRecommender, and returns them as a formatted string.
11
+ """
12
+ if not vibe_query:
13
+ return "Please enter a vibe or movie description."
14
+ recommendations = recommender.recommend(vibe_query)
15
+ return recommendations
16
+
17
+ # Create the Gradio interface
18
+ iface = gr.Interface(
19
+ fn=get_recommendations,
20
+ inputs=gr.Textbox(lines=5, label="Describe the vibe of the movie you want to watch", placeholder="e.g., A scifi horror movie about a group of people who are trapped in a building and have to fight off an alien."),
21
+ outputs="text",
22
+ title="🎬 Movie Recommender",
23
+ description="Describe the kind of movie you're in the mood for, and I'll give you some recommendations based on the vibe.",
24
+ examples=[
25
+ ["A heartwarming story about a talking animal who goes on an adventure."],
26
+ ["A dark and gritty detective noir set in 1940s Los Angeles."],
27
+ ["A mind-bending psychological thriller with an unreliable narrator."]
28
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  )
30
 
 
31
  if __name__ == "__main__":
32
+ iface.launch()
movie_recommender.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_ollama.llms import OllamaLLM
2
+
3
+ from langchain.agents import AgentType
4
+ from langchain.agents import initialize_agent
5
+
6
+ from langchain.agents import Tool
7
+
8
+ from sentence_transformers import SentenceTransformer
9
+ from transformers import AutoTokenizer, AutoModel
10
+ import os
11
+ import glob
12
+ from tqdm import tqdm
13
+ import json
14
+ import faiss
15
+ import numpy as np
16
+
17
+
18
+ def safe_get(data, *keys, default=None):
19
+ """Safely get nested dictionary values with fallback to default."""
20
+ for key in keys:
21
+ try:
22
+ data = data[key]
23
+ except (KeyError, TypeError):
24
+ return default
25
+ return data
26
+
27
+ def get_movie_text(movie_json):
28
+ """Convert movie JSON to embedable text"""
29
+ title = safe_get(movie_json, 'titleText', 'text', default='Unknown')
30
+ year = safe_get(movie_json, 'releaseYear', 'year', default='Unknown')
31
+ plot = safe_get(movie_json, 'plot', 'plotText', 'plainText', default='No plot available')
32
+
33
+ genres = safe_get(movie_json, 'genres', 'genres', default=[])
34
+ genre_text = ', '.join([g.get('text', '') for g in genres]) if genres else 'Unknown genre'
35
+
36
+ keywords = safe_get(movie_json, 'keywords', 'edges', default=[])
37
+ keyword_text = ', '.join([kw['node']['text'] for kw in keywords[:10]]) if keywords else 'No keywords'
38
+
39
+ rating = safe_get(movie_json, 'ratingsSummary', 'aggregateRating', default='N/A')
40
+
41
+ movie_text = f"Title: {title}. Year: {year}. Genres: {genre_text}. Plot: {plot}. Keywords: {keyword_text}. Rating: {rating}"
42
+
43
+ return movie_text
44
+
45
+ class MovieRecommender:
46
+ def __init__(self,
47
+ model_name='intfloat/multilingual-e5-large-instruct',
48
+ index_path="movie_index.faiss",
49
+ texts_path="movie_texts.json",
50
+ data_path="archive/movie_dataset/movie_dataset/*.json"):
51
+
52
+ self.model = SentenceTransformer(model_name)
53
+ self.index_path = index_path
54
+ self.texts_path = texts_path
55
+ self.data_path = data_path
56
+ self.llm = OllamaLLM(model="huihui_ai/qwen3-abliterated")
57
+ self.all_movies_text = []
58
+ self.faiss_index = None
59
+
60
+ self._load_or_build_index()
61
+
62
+ def _load_movies(self):
63
+ movie_files = glob.glob(self.data_path)[:3]
64
+ print(f"Processing {len(movie_files)} movie files...")
65
+
66
+ all_movies_data = []
67
+ for file in tqdm(movie_files, desc="Loading movie files"):
68
+ try:
69
+ with open(file, "r") as f:
70
+ data = json.load(f)
71
+ all_movies_data.extend(data)
72
+ except Exception as e:
73
+ print(f"Error loading {file}: {e}")
74
+
75
+ print(f"Loaded data for {len(all_movies_data)} movies.")
76
+ self.all_movies_text = [get_movie_text(movie) for movie in tqdm(all_movies_data, desc="Extracting text from movies")]
77
+ print(f"Processed {len(self.all_movies_text)} movies total")
78
+
79
+ def _build_index(self, batch_size=10):
80
+ print(f"Embedding movies in batches of {batch_size}...")
81
+
82
+ self.faiss_index = faiss.IndexFlatL2(1024)
83
+
84
+ num_batches = (len(self.all_movies_text) + batch_size - 1) // batch_size
85
+
86
+ for i in tqdm(range(num_batches), desc="Embedding batches"):
87
+ batch_texts = self.all_movies_text[i*batch_size:(i+1)*batch_size]
88
+ if not batch_texts:
89
+ continue
90
+ document_embeddings = self.model.encode(batch_texts)
91
+ self.faiss_index.add(document_embeddings)
92
+
93
+ print(f"FAISS index built with {self.faiss_index.ntotal} vectors.")
94
+
95
+ print(f"Saving FAISS index to {self.index_path}")
96
+ faiss.write_index(self.faiss_index, self.index_path)
97
+
98
+ with open(self.texts_path, "w") as f:
99
+ json.dump(self.all_movies_text, f)
100
+ print(f"Saved movie texts to {self.texts_path}")
101
+
102
+ def _load_or_build_index(self):
103
+ if os.path.exists(self.index_path) and os.path.exists(self.texts_path):
104
+ print(f"Loading existing FAISS index from {self.index_path}")
105
+ self.faiss_index = faiss.read_index(self.index_path)
106
+
107
+ print(f"Loading movie texts from {self.texts_path}")
108
+ with open(self.texts_path, "r") as f:
109
+ self.all_movies_text = json.load(f)
110
+ print(f"Loaded {len(self.all_movies_text)} movie texts.")
111
+ else:
112
+ print("Building new FAISS index...")
113
+ self._load_movies()
114
+ self._build_index()
115
+
116
+ def search(self, query, k=50):
117
+ if self.faiss_index is None:
118
+ raise Exception("FAISS index is not built or loaded.")
119
+
120
+ query_embedding = self.model.encode([query], prompt_name="query")
121
+ distances, indices = self.faiss_index.search(query_embedding, k)
122
+
123
+ top_indices = indices[0]
124
+
125
+ extracted_topk_movies = [self.all_movies_text[i] for i in top_indices]
126
+
127
+ return extracted_topk_movies
128
+
129
+ def recommend(self, vibe_query):
130
+ print(f"Searching for movies with vibe: {vibe_query}")
131
+ candidate_movies = self.search(vibe_query)
132
+
133
+ prompt = f"""
134
+ You are a movie recommendation expert. I'm looking for movies with this vibe: "{vibe_query}"
135
+
136
+ Here are 50 candidate movies that were found using semantic similarity:
137
+
138
+ Create a vibe profile for each of these movies and then rank the movies based on the vibe profiles matching the requested vibe.
139
+
140
+ {''.join(candidate_movies)}
141
+
142
+ Please rank the TOP 10 movies that best match the requested vibe "{vibe_query}". For each movie, provide:
143
+
144
+ 1. **Movie Title and Year**
145
+ 2. **Rank Score** (1-10, where 10 is a perfect match)
146
+ 3. **Reason** (2-3 sentences explaining why this movie matches the vibe)
147
+ 4. **Description** (brief summary focusing on elements that match the vibe)
148
+ 5. **Hook** (1-2 hooky sentences that capture the essence of the movie)
149
+
150
+ Format your response exactly like this:
151
+
152
+ **TOP 10 MOVIE RECOMMENDATIONS:**
153
+
154
+ [Movie Title] ([Year])**
155
+ - **Rank Score:** [1-10]
156
+ - **Reason:** [2-3 sentences explaining the match]
157
+ - **Description:** [Brief summary highlighting vibe-matching elements]
158
+ - **Hook:** [1-2 hooky sentences that capture the essence of the movie]
159
+
160
+ **2. [Movie Title] ([Year])**
161
+ - **Rank Score:** [1-10]
162
+ - **Reason:** [2-3 sentences explaining the match]
163
+ - **Description:** [Brief summary highlighting vibe-matching elements]
164
+ - **Hook:** [1-2 hooky sentences that capture the essence of the movie]
165
+
166
+ **3. [Movie Title] ([Year])**
167
+ - **Rank Score:** [1-10]
168
+ - **Reason:** [2-3 sentences explaining the match]
169
+ - **Description:** [Brief summary highlighting vibe-matching elements]
170
+ - **Hook:** [1-2 hooky sentencess that capture the essence of the movie]
171
+
172
+ ...
173
+
174
+ **10. [Movie Title] ([Year])**
175
+ - **Rank Score:** [1-10]
176
+ - **Reason:** [2-3 sentences explaining the match]
177
+ - **Description:** [Brief summary highlighting vibe-matching elements]
178
+ - **Hook:** [1-2 hooky sentences that capture the essence of the movie]
179
+
180
+ Focus on how well each movie captures the specific vibe requested, not just general quality.
181
+ """
182
+
183
+ response = self.llm.invoke(prompt)
184
+ return response
185
+
186
+ if __name__ == "__main__":
187
+
188
+ recommender = MovieRecommender()
189
+
190
+ query = "A scifi horror movie about a group of people who are trapped in a building and have to fight off an alien."
191
+ recommendations = recommender.recommend(query)
192
+ print(recommendations)