Tesneem commited on
Commit
fe48904
·
verified ·
1 Parent(s): 3669869

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -143
app.py CHANGED
@@ -13,49 +13,49 @@ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base
13
  image_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
14
 
15
  def generate_input(input_type, image=None, text=None, response_amount=3):
16
- # Initialize the input variable
17
  combined_input = ""
18
 
19
- # Handle image input if chosen
20
  if input_type == "Image" and image:
21
- inputs = processor(images=image, return_tensors="pt")
22
- out = image_model.generate(**inputs)
23
- image_caption = processor.decode(out[0], skip_special_tokens=True)
24
- combined_input += image_caption # Add the image caption to input
25
 
26
- # Handle text input if chosen
27
  elif input_type == "Text" and text:
28
- combined_input += text # Add the text to input
29
 
30
- # Handle both text and image input if chosen
31
  elif input_type == "Both" and image and text:
32
  inputs = processor(images=image, return_tensors="pt")
33
  out = image_model.generate(**inputs)
34
- image_caption = processor.decode(out[0], skip_special_tokens=True)
35
- combined_input += image_caption + " and " + text # Combine image caption and text
36
 
37
- # If no input, fallback
38
  if not combined_input:
39
  combined_input = "No input provided."
40
  if response_amount is None:
41
  response_amount=3
42
 
43
- return vector_search(combined_input,response_amount)
44
 
45
- # Load embeddings and metadata
46
  embeddings = np.load("netflix_embeddings.npy") #created using sentence_transformers on kaggle
47
  metadata = pd.read_csv("netflix_metadata.csv") #created using sentence_transformers on kaggle
48
 
49
- # Vector search function
50
  def vector_search(query,top_n=3):
51
- query_embedding = sentence_model.encode(query)
52
- similarities = cosine_similarity([query_embedding], embeddings)[0]
53
  if top_n is None:
54
  top_n=3
55
- top_indices = similarities.argsort()[-top_n:][::-1]
56
- results = metadata.iloc[top_indices]
57
  result_text=""
58
- for index,row in results.iterrows():
59
  if index!=top_n-1:
60
  result_text+=f"Title: {row['title']} Description: {row['description']} Genre: {row['listed_in']}\n\n"
61
  else:
@@ -63,12 +63,12 @@ def vector_search(query,top_n=3):
63
  return result_text
64
 
65
 
66
- def set_response_amount(response_amount):
67
  if response_amount is None:
68
  return 3
69
  return response_amount
70
 
71
- # Based on the selected input type, make the appropriate input visible
72
  def update_inputs(input_type):
73
  if input_type == "Image":
74
  return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)
@@ -83,13 +83,13 @@ with gr.Blocks() as demo:
83
  input_type = gr.Radio(["Image", "Text", "Both"], label="Select Input Type", type="value")
84
  response_type=gr.Dropdown(choices=[3,5,10,25], type="value", label="Select Response Amount", visible=False)
85
  image_input = gr.Image(label="Upload Image", type="pil", visible=False) # Hidden initially
86
- text_input = gr.Textbox(label="Enter Text Query", placeholder="Enter a description or query here", visible=False) # Hidden initially
87
 
88
  input_type.change(fn=update_inputs, inputs=input_type, outputs=[image_input, text_input, response_type])
89
- # State variable to store the selected response amount
90
  selected_response_amount = gr.State()
91
 
92
- # Capture response amount immediately when dropdown changes
93
  response_type.change(fn=set_response_amount, inputs=response_type, outputs=selected_response_amount)
94
 
95
  submit_button = gr.Button("Submit")
@@ -99,121 +99,3 @@ with gr.Blocks() as demo:
99
 
100
  submit_button.click(fn=generate_input, inputs=[input_type,image_input, text_input,selected_response_amount], outputs=output)
101
  demo.launch()
102
-
103
-
104
- # with gr.Blocks() as demo:
105
- # gr.Markdown("# Netflix Recommendation System")
106
- # gr.Markdown("Enter a query to receive Netflix show recommendations based on title, description, and genre.")
107
- # query = gr.Textbox(label="Enter your query")
108
- # output = gr.Textbox(label="Recommendations")
109
- # submit_button = gr.Button("Submit")
110
-
111
- # submit_button.click(fn=lambda q: vector_search(q, model), inputs=query, outputs=output)
112
- # import gradio as gr
113
-
114
- # # def greet(name):
115
- # # return "Hello " + name + "!!"
116
- # from sentence_transformers import SentenceTransformer
117
- # import numpy as np
118
- # from sklearn.metrics.pairwise import cosine_similarity
119
- # from datasets import load_dataset
120
- # # Load pre-trained SentenceTransformer model
121
- # embedding_model = SentenceTransformer("thenlper/gte-large")
122
-
123
- # # # Example dataset with genres (replace with your actual data)
124
- # # dataset = load_dataset("hugginglearners/netflix-shows")
125
- # # dataset = dataset.filter(lambda x: x['description'] is not None and x['listed_in'] is not None and x['title'] is not None)
126
- # # data = dataset['train'] # Accessing the 'train' split of the dataset
127
-
128
- # # # Convert the dataset to a list of dictionaries for easier indexing
129
- # # data_list = list[data]
130
- # # print(data_list)
131
- # # # Combine description and genre for embedding
132
- # # def combine_description_title_and_genre(description, listed_in, title):
133
- # # return f"{description} Genre: {listed_in} Title: {title}"
134
-
135
- # # # Generate embedding for the query
136
- # # def get_embedding(text):
137
- # # return embedding_model.encode(text)
138
-
139
- # # # Vector search function
140
- # # def vector_search(query):
141
- # # query_embedding = get_embedding(query)
142
-
143
- # # # Generate embeddings for the combined description and genre
144
- # # embeddings = np.array([get_embedding(combine_description_title_and_genre(item["description"], item["listed_in"],item["title"])) for item in data_list[0]])
145
-
146
- # # # Calculate cosine similarity between the query and all embeddings
147
- # # similarities = cosine_similarity([query_embedding], embeddings)
148
- # # Load dataset (using the correct dataset identifier for your case)
149
- # dataset = load_dataset("hugginglearners/netflix-shows")
150
-
151
- # # Combine description and genre for embedding
152
- # def combine_description_title_and_genre(description, listed_in, title):
153
- # return f"{description} Genre: {listed_in} Title: {title}"
154
-
155
- # # Generate embedding for the query
156
- # def get_embedding(text):
157
- # return embedding_model.encode(text)
158
-
159
- # # Vector search function
160
- # def vector_search(query):
161
- # query_embedding = get_embedding(query)
162
-
163
- # # Function to generate embeddings for each item in the dataset
164
- # def generate_embeddings(example):
165
- # return {
166
- # 'embedding': get_embedding(combine_description_title_and_genre(example["description"], example["listed_in"], example["title"]))
167
- # }
168
-
169
- # # Generate embeddings for the dataset using map
170
- # embeddings_dataset = dataset["train"].map(generate_embeddings)
171
-
172
- # # Extract embeddings
173
- # embeddings = np.array([embedding['embedding'] for embedding in embeddings_dataset])
174
-
175
- # # Calculate cosine similarity between the query and all embeddings
176
- # similarities = cosine_similarity([query_embedding], embeddings)
177
- # # # Adjust similarity scores based on ratings
178
- # # ratings = np.array([item["rating"] for item in data_list])
179
- # # adjusted_similarities = similarities * ratings.reshape(-1, 1)
180
-
181
- # # Get top N most similar items (e.g., top 3)
182
- # top_n = 3
183
- # top_indices = similarities[0].argsort()[-top_n:][::-1] # Get indices of the top N results
184
- # top_items = [dataset["train"][i] for i in top_indices]
185
-
186
- # # Format the output for display
187
- # search_result = ""
188
- # for item in top_items:
189
- # search_result += f"Title: {item['title']}, Description: {item['description']}, Genre: {item['listed_in']}\n"
190
-
191
- # return search_result
192
-
193
- # # Gradio Interface
194
- # def movie_search(query):
195
- # return vector_search(query)
196
- # with gr.Blocks() as demo:
197
- # gr.Markdown("# Netflix Recommendation System")
198
- # gr.Markdown("Enter a query to receive Netflix show recommendations based on title, description, and genre.")
199
- # query = gr.Textbox(label="Enter your query")
200
- # output = gr.Textbox(label="Recommendations")
201
- # submit_button = gr.Button("Submit")
202
-
203
- # submit_button.click(fn=movie_search, inputs=query, outputs=output)
204
-
205
- # demo.launch()
206
-
207
-
208
- # # iface = gr.Interface(fn=movie_search,
209
- # # inputs=gr.inputs.Textbox(label="Enter your query"),
210
- # # outputs="text",
211
- # # live=True,
212
- # # title="Netflix Recommendation System",
213
- # # description="Enter a query to get Netflix recommendations based on description and genre.")
214
-
215
- # # iface.launch()
216
-
217
-
218
- # # demo = gr.Interface(fn=greet, inputs="text", outputs="text")
219
- # # demo.launch()
 
13
  image_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
14
 
15
  def generate_input(input_type, image=None, text=None, response_amount=3):
16
+ # initalize input variable
17
  combined_input = ""
18
 
19
+ # handle image input if chosen
20
  if input_type == "Image" and image:
21
+ inputs = processor(images=image, return_tensors="pt") #process image with BlipProcessor
22
+ out = image_model.generate(**inputs) #generate caption with BlipModel
23
+ image_caption = processor.decode(out[0], skip_special_tokens=True) #decode output w/ processor
24
+ combined_input += image_caption # add the image caption to input
25
 
26
+ # handle text input if chosen
27
  elif input_type == "Text" and text:
28
+ combined_input += text # add the text to input
29
 
30
+ # handle both text and image input if chosen
31
  elif input_type == "Both" and image and text:
32
  inputs = processor(images=image, return_tensors="pt")
33
  out = image_model.generate(**inputs)
34
+ image_caption = processor.decode(out[0], skip_special_tokens=True) #repeat image processing + caption generation and decoding
35
+ combined_input += image_caption + " and " + text # combine image caption and text
36
 
37
+ # if no input, fallback
38
  if not combined_input:
39
  combined_input = "No input provided."
40
  if response_amount is None:
41
  response_amount=3
42
 
43
+ return vector_search(combined_input,response_amount) #search through embedded document w/ input
44
 
45
+ # load embeddings and metadata
46
  embeddings = np.load("netflix_embeddings.npy") #created using sentence_transformers on kaggle
47
  metadata = pd.read_csv("netflix_metadata.csv") #created using sentence_transformers on kaggle
48
 
49
+ # vector search function
50
  def vector_search(query,top_n=3):
51
+ query_embedding = sentence_model.encode(query) #encode input w/ Sentence Transformers
52
+ similarities = cosine_similarity([query_embedding], embeddings)[0] #similarity function
53
  if top_n is None:
54
  top_n=3
55
+ top_indices = similarities.argsort()[-top_n:][::-1] #return top n indices based on chosen output amount
56
+ results = metadata.iloc[top_indices] #get metadata
57
  result_text=""
58
+ for index,row in results.iterrows(): #loop through results to get Title, Description, and Genre for top n outputs
59
  if index!=top_n-1:
60
  result_text+=f"Title: {row['title']} Description: {row['description']} Genre: {row['listed_in']}\n\n"
61
  else:
 
63
  return result_text
64
 
65
 
66
+ def set_response_amount(response_amount): #set response amount
67
  if response_amount is None:
68
  return 3
69
  return response_amount
70
 
71
+ # based on the selected input type, make the appropriate input visible
72
  def update_inputs(input_type):
73
  if input_type == "Image":
74
  return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)
 
83
  input_type = gr.Radio(["Image", "Text", "Both"], label="Select Input Type", type="value")
84
  response_type=gr.Dropdown(choices=[3,5,10,25], type="value", label="Select Response Amount", visible=False)
85
  image_input = gr.Image(label="Upload Image", type="pil", visible=False) # Hidden initially
86
+ text_input = gr.Textbox(label="Enter Text Query", placeholder="Enter a description or query here", visible=False) # hidden initially
87
 
88
  input_type.change(fn=update_inputs, inputs=input_type, outputs=[image_input, text_input, response_type])
89
+ # state variable to store the selected response amount
90
  selected_response_amount = gr.State()
91
 
92
+ # capture response amount immediately when dropdown changes
93
  response_type.change(fn=set_response_amount, inputs=response_type, outputs=selected_response_amount)
94
 
95
  submit_button = gr.Button("Submit")
 
99
 
100
  submit_button.click(fn=generate_input, inputs=[input_type,image_input, text_input,selected_response_amount], outputs=output)
101
  demo.launch()