EmTpro01 commited on
Commit
0aa79e7
1 Parent(s): 668f6d9

Update app/services/recipe_generator.py

Browse files
Files changed (1) hide show
  1. 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 transformers import AutoTokenizer, AutoModelForCausalLM
3
- import torch
4
-
5
- class RecipeGenerator:
6
- def __init__(self):
7
- # Initialize your fine-tuned model and tokenizer
8
- self.tokenizer = AutoTokenizer.from_pretrained("flax-community/t5-recipe-generation")
9
- self.model = AutoModelForCausalLM.from_pretrained("flax-community/t5-recipe-generation")
10
-
11
- async def generate(self, ingredients: List[str]):
12
- # Format ingredients for input
13
- input_text = f"Generate a recipe using these ingredients: {', '.join(ingredients)}"
14
-
15
- # Tokenize and generate
16
- inputs = self.tokenizer(input_text, return_tensors="pt", padding=True)
17
- outputs = self.model.generate(
18
- inputs.input_ids,
19
- max_length=512,
20
- num_return_sequences=1,
21
- temperature=0.7,
22
- top_p=0.9,
23
- do_sample=True
24
- )
25
-
26
- # Decode and parse the generated recipe
27
- generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
28
-
29
- # Parse the generated text into structured format
30
- # This is a simple example - adjust based on your model's output format
31
- lines = generated_text.split('\n')
32
- title = lines[0]
33
- ingredients_list = []
34
- instructions_list = []
35
-
36
- # Simple parsing logic - adjust based on your model's output format
37
- current_section = None
38
- for line in lines[1:]:
39
- if "Ingredients:" in line:
40
- current_section = "ingredients"
41
- elif "Instructions:" in line:
42
- current_section = "instructions"
43
- elif line.strip():
44
- if current_section == "ingredients":
45
- ingredients_list.append(line.strip())
46
- elif current_section == "instructions":
47
- instructions_list.append(line.strip())
48
-
49
- return {
50
- "title": title,
51
- "ingredients": ingredients_list,
52
- "instructions": instructions_list
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
+ }