Spaces:
Running
Running
Update app/services/recipe_generator.py
Browse files- app/services/recipe_generator.py +75 -53
app/services/recipe_generator.py
CHANGED
@@ -1,53 +1,75 @@
|
|
1 |
-
# app/services/recipe_generator.py
|
2 |
-
from
|
3 |
-
import
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
#
|
13 |
-
|
14 |
-
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app/services/recipe_generator.py
|
2 |
+
from typing import List, Dict
|
3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
4 |
+
import torch
|
5 |
+
import os
|
6 |
+
|
7 |
+
class RecipeGenerator:
|
8 |
+
def __init__(self):
|
9 |
+
# Set cache directory to a writable location
|
10 |
+
os.environ['TRANSFORMERS_CACHE'] = '/tmp/huggingface'
|
11 |
+
|
12 |
+
# Create cache directory if it doesn't exist
|
13 |
+
os.makedirs('/tmp/huggingface', exist_ok=True)
|
14 |
+
|
15 |
+
# Initialize your fine-tuned model and tokenizer
|
16 |
+
try:
|
17 |
+
self.tokenizer = AutoTokenizer.from_pretrained("flax-community/t5-recipe-generation", cache_dir='/tmp/huggingface')
|
18 |
+
self.model = AutoModelForCausalLM.from_pretrained("flax-community/t5-recipe-generation", cache_dir='/tmp/huggingface')
|
19 |
+
except Exception as e:
|
20 |
+
print(f"Error loading model: {str(e)}")
|
21 |
+
# Provide a fallback or raise the error as needed
|
22 |
+
raise
|
23 |
+
|
24 |
+
async def generate(self, ingredients: List[str]) -> Dict[str, List[str]]:
|
25 |
+
try:
|
26 |
+
# Format ingredients for input
|
27 |
+
input_text = f"Generate a recipe using these ingredients: {', '.join(ingredients)}"
|
28 |
+
|
29 |
+
# Tokenize and generate
|
30 |
+
inputs = self.tokenizer(input_text, return_tensors="pt", padding=True)
|
31 |
+
outputs = self.model.generate(
|
32 |
+
inputs.input_ids,
|
33 |
+
max_length=512,
|
34 |
+
num_return_sequences=1,
|
35 |
+
temperature=0.7,
|
36 |
+
top_p=0.9,
|
37 |
+
do_sample=True
|
38 |
+
)
|
39 |
+
|
40 |
+
# Decode and parse the generated recipe
|
41 |
+
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
42 |
+
|
43 |
+
# Parse the generated text into structured format
|
44 |
+
lines = generated_text.split('\n')
|
45 |
+
title = lines[0] if lines else "Generated Recipe"
|
46 |
+
|
47 |
+
# Initialize lists
|
48 |
+
ingredients_list = []
|
49 |
+
instructions_list = []
|
50 |
+
|
51 |
+
# Simple parsing logic
|
52 |
+
current_section = None
|
53 |
+
for line in lines[1:]:
|
54 |
+
if "Ingredients:" in line:
|
55 |
+
current_section = "ingredients"
|
56 |
+
elif "Instructions:" in line:
|
57 |
+
current_section = "instructions"
|
58 |
+
elif line.strip():
|
59 |
+
if current_section == "ingredients":
|
60 |
+
ingredients_list.append(line.strip())
|
61 |
+
elif current_section == "instructions":
|
62 |
+
instructions_list.append(line.strip())
|
63 |
+
|
64 |
+
return {
|
65 |
+
"title": title,
|
66 |
+
"ingredients": ingredients_list or ["No ingredients generated"],
|
67 |
+
"instructions": instructions_list or ["No instructions generated"]
|
68 |
+
}
|
69 |
+
except Exception as e:
|
70 |
+
print(f"Error generating recipe: {str(e)}")
|
71 |
+
return {
|
72 |
+
"title": "Error Generating Recipe",
|
73 |
+
"ingredients": ["Error occurred while generating recipe"],
|
74 |
+
"instructions": ["Please try again later"]
|
75 |
+
}
|