Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -71,7 +71,7 @@ print("Loading generative model...")
|
|
| 71 |
generator = pipeline('text-generation', model='gpt2-medium')
|
| 72 |
|
| 73 |
def get_recommendations_and_generate(query_ingredients, k=3):
|
| 74 |
-
# 1. Get Recommendations
|
| 75 |
query_vector = embedding_model.encode([query_ingredients])
|
| 76 |
query_vector = np.array(query_vector, dtype=np.float32)
|
| 77 |
distances, indices = index.search(query_vector, k)
|
|
@@ -86,25 +86,35 @@ def get_recommendations_and_generate(query_ingredients, k=3):
|
|
| 86 |
}
|
| 87 |
results.append(recipe)
|
| 88 |
|
| 89 |
-
#
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
try:
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
lines = generated_text.split('\n')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
title = lines[0].strip() # The first line after the prompt is the title
|
| 106 |
-
|
| 107 |
-
# Find the start of ingredients and directions by looking for keywords
|
| 108 |
ing_index = -1
|
| 109 |
dir_index = -1
|
| 110 |
for i, line in enumerate(lines):
|
|
@@ -113,29 +123,28 @@ def get_recommendations_and_generate(query_ingredients, k=3):
|
|
| 113 |
if "directions" in line.lower() and dir_index == -1:
|
| 114 |
dir_index = i
|
| 115 |
|
| 116 |
-
# Extract the sections based on where the keywords were found
|
| 117 |
if ing_index != -1 and dir_index != -1:
|
| 118 |
ingredients = "\n".join(lines[ing_index+1:dir_index]).strip()
|
| 119 |
directions = "\n".join(lines[dir_index+1:]).strip()
|
| 120 |
-
elif ing_index != -1:
|
| 121 |
ingredients = "\n".join(lines[ing_index+1:]).strip()
|
| 122 |
-
|
|
|
|
| 123 |
directions = "\n".join(lines[dir_index+1:]).strip()
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
| 126 |
|
| 127 |
generated_recipe = {
|
| 128 |
"title": title,
|
| 129 |
"ingredients": ingredients,
|
| 130 |
"directions": directions
|
| 131 |
}
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
-
print(f"
|
| 134 |
-
generated_recipe
|
| 135 |
-
"title": "AI Generated Recipe (Parsing Error)",
|
| 136 |
-
"ingredients": "Could not determine ingredients.",
|
| 137 |
-
"directions": generated_text
|
| 138 |
-
}
|
| 139 |
|
| 140 |
return results[0], results[1], results[2], generated_recipe
|
| 141 |
|
|
|
|
| 71 |
generator = pipeline('text-generation', model='gpt2-medium')
|
| 72 |
|
| 73 |
def get_recommendations_and_generate(query_ingredients, k=3):
|
| 74 |
+
# --- 1. Get Recommendations ---
|
| 75 |
query_vector = embedding_model.encode([query_ingredients])
|
| 76 |
query_vector = np.array(query_vector, dtype=np.float32)
|
| 77 |
distances, indices = index.search(query_vector, k)
|
|
|
|
| 86 |
}
|
| 87 |
results.append(recipe)
|
| 88 |
|
| 89 |
+
# Defensive check: Ensure there are always 3 recommendations
|
| 90 |
+
while len(results) < 3:
|
| 91 |
+
results.append({"title": "No recipe found", "ingredients": "", "directions": ""})
|
| 92 |
+
|
| 93 |
+
# --- 2. Generate and Parse a New Recipe (with error handling) ---
|
| 94 |
+
generated_recipe = {
|
| 95 |
+
"title": "AI Recipe Generation Failed",
|
| 96 |
+
"ingredients": "The model could not generate a recipe for these ingredients.",
|
| 97 |
+
"directions": "Please try a different combination of ingredients."
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
try:
|
| 101 |
+
prompt = f"Create a simple and delicious recipe using the following ingredients: {query_ingredients}."
|
| 102 |
+
|
| 103 |
+
generated_outputs = generator(prompt, max_new_tokens=250, num_return_sequences=1, pad_token_id=50256)
|
| 104 |
+
|
| 105 |
+
# Check if the model returned a valid output
|
| 106 |
+
if not generated_outputs or 'generated_text' not in generated_outputs[0]:
|
| 107 |
+
raise ValueError("Model did not return generated_text.")
|
| 108 |
+
|
| 109 |
+
generated_text = generated_outputs[0]['generated_text'].replace(prompt, "").strip()
|
| 110 |
+
|
| 111 |
+
# Parsing logic
|
| 112 |
lines = generated_text.split('\n')
|
| 113 |
+
if not lines or lines[0] == "":
|
| 114 |
+
raise ValueError("Generated text is empty.")
|
| 115 |
+
|
| 116 |
+
title = lines[0].strip()
|
| 117 |
|
|
|
|
|
|
|
|
|
|
| 118 |
ing_index = -1
|
| 119 |
dir_index = -1
|
| 120 |
for i, line in enumerate(lines):
|
|
|
|
| 123 |
if "directions" in line.lower() and dir_index == -1:
|
| 124 |
dir_index = i
|
| 125 |
|
|
|
|
| 126 |
if ing_index != -1 and dir_index != -1:
|
| 127 |
ingredients = "\n".join(lines[ing_index+1:dir_index]).strip()
|
| 128 |
directions = "\n".join(lines[dir_index+1:]).strip()
|
| 129 |
+
elif ing_index != -1:
|
| 130 |
ingredients = "\n".join(lines[ing_index+1:]).strip()
|
| 131 |
+
directions = "Not provided."
|
| 132 |
+
elif dir_index != -1:
|
| 133 |
directions = "\n".join(lines[dir_index+1:]).strip()
|
| 134 |
+
ingredients = "Not provided."
|
| 135 |
+
else:
|
| 136 |
+
ingredients = "Not provided."
|
| 137 |
+
directions = "\n".join(lines[1:]).strip() if len(lines) > 1 else ""
|
| 138 |
|
| 139 |
generated_recipe = {
|
| 140 |
"title": title,
|
| 141 |
"ingredients": ingredients,
|
| 142 |
"directions": directions
|
| 143 |
}
|
| 144 |
+
|
| 145 |
except Exception as e:
|
| 146 |
+
print(f"An error occurred in get_recommendations_and_generate: {e}")
|
| 147 |
+
# The generated_recipe dictionary is already set to a default error message
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
return results[0], results[1], results[2], generated_recipe
|
| 150 |
|