evaliisah commited on
Commit
7d364db
·
verified ·
1 Parent(s): 5668b62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -42
app.py CHANGED
@@ -2,7 +2,6 @@ import gradio as gr
2
  import requests
3
  from transformers import pipeline
4
 
5
-
6
  # Initialize translation models
7
  translate_to_english = pipeline("translation", model="Helsinki-NLP/opus-mt-et-en")
8
  translate_to_estonian = pipeline("translation", model="Helsinki-NLP/opus-mt-en-et")
@@ -10,6 +9,8 @@ translate_to_estonian = pipeline("translation", model="Helsinki-NLP/opus-mt-en-e
10
  # Spoonacular API settings
11
  API_KEY = '0bf3de98d2654cb28f139df9fedb7db2'
12
  SPOONACULAR_URL = "https://api.spoonacular.com/recipes/findByIngredients"
 
 
13
 
14
  def translate_text(input_text, direction='et-en'):
15
  """Translate text between Estonian and English."""
@@ -19,7 +20,7 @@ def translate_text(input_text, direction='et-en'):
19
  result = translate_to_estonian(input_text)
20
  return result[0]['translation_text']
21
 
22
- def find_recipes(ingredient, calories, wheat_content):
23
  """Find recipes based on the ingredient and dietary preferences."""
24
  # Translate ingredient to English
25
  ingredient_en = translate_text(ingredient, direction='et-en')
@@ -29,50 +30,90 @@ def find_recipes(ingredient, calories, wheat_content):
29
  "Madal kalorsus": "Low",
30
  "Kõrge kalorsus": "High"
31
  }
32
- wheat_map = {
33
- "Sisaldab nisu": "Contains",
34
- "Nisuvaba": "Free of"
35
  }
36
 
37
- calories_en = calories_map.get(calories, "")
38
- wheat_en = wheat_map.get(wheat_content, "")
39
-
40
- params = {
41
- "ingredients": ingredient_en,
42
- "apiKey": API_KEY
43
  }
44
 
45
- response = requests.get(SPOONACULAR_URL, params=params)
 
 
 
 
46
 
47
  if response.status_code == 200:
48
- recipes = response.json()
49
 
50
  if not recipes:
51
  return "Ühtegi retsepti ei leitud.", ""
52
 
53
- # Select the first recipe for demonstration
54
- recipe = recipes[0]
55
-
56
- # Prepare recipe details
57
- recipe_name_en = recipe['title']
58
- recipe_name_et = translate_text(recipe_name_en, direction='en-et')
59
- recipe_link = f"https://spoonacular.com/recipes/{recipe['id']}-{recipe_name_en.replace(' ', '-')}"
60
-
61
- # Translate ingredients to Estonian
62
- missed_ingredients_en = ', '.join([ingredient['name'] for ingredient in recipe['missedIngredients']])
63
- missed_ingredients_et = translate_text(missed_ingredients_en, direction='en-et')
64
-
65
- # Create a recipe description
66
- recipe_description = (
67
- f"Retsept: {recipe_name_et}\n\n"
68
- f"Link: {recipe_link}\n\n"
69
- f"Koostisosad: {missed_ingredients_et}\n\n"
70
- f"Kalorsus: {calories}\n"
71
- f"Nisusisaldus: {wheat_content}\n\n"
72
- f"Valmistamise juhised: [Link to instructions]"
73
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- return recipe_description, recipe_link
 
76
  else:
77
  return "Viga retseptide toomisel.", ""
78
 
@@ -91,24 +132,24 @@ iface = gr.Interface(
91
  type="value"
92
  ),
93
  gr.Dropdown(
94
- choices=["Sisaldab nisu", "Nisuvaba"],
95
- label="Nisusisaldus",
96
  type="value"
97
  )
98
  ],
99
  outputs=[
100
- gr.Textbox(lines=15, label="Genereeritud Retsept"),
101
  gr.Textbox(lines=1, label="Retsepti Link")
102
  ],
103
  title="🍳 Nutikas Retsepti Generaator",
104
  description=(
105
- "Sisestage koostisosa, valige kalorsus ja nisusisaldus. "
106
  "Saate personaalse retsepti!"
107
  ),
108
  examples=[
109
- ["lõhe", "Madal kalorsus", "Nisuvaba"],
110
- ["šokolaadikook", "Kõrge kalorsus", "Sisaldab nisu"],
111
- ["kartul", "Madal kalorsus", "Nisuvaba"]
112
  ],
113
  theme="default"
114
  )
 
2
  import requests
3
  from transformers import pipeline
4
 
 
5
  # Initialize translation models
6
  translate_to_english = pipeline("translation", model="Helsinki-NLP/opus-mt-et-en")
7
  translate_to_estonian = pipeline("translation", model="Helsinki-NLP/opus-mt-en-et")
 
9
  # Spoonacular API settings
10
  API_KEY = '0bf3de98d2654cb28f139df9fedb7db2'
11
  SPOONACULAR_URL = "https://api.spoonacular.com/recipes/findByIngredients"
12
+ RECIPE_INFO_URL = "https://api.spoonacular.com/recipes/{}/information"
13
+ RECIPE_SEARCH_URL = "https://api.spoonacular.com/recipes/complexSearch"
14
 
15
  def translate_text(input_text, direction='et-en'):
16
  """Translate text between Estonian and English."""
 
20
  result = translate_to_estonian(input_text)
21
  return result[0]['translation_text']
22
 
23
+ def find_recipes(ingredient, calories, gluten_content):
24
  """Find recipes based on the ingredient and dietary preferences."""
25
  # Translate ingredient to English
26
  ingredient_en = translate_text(ingredient, direction='et-en')
 
30
  "Madal kalorsus": "Low",
31
  "Kõrge kalorsus": "High"
32
  }
33
+ gluten_map = {
34
+ "Sisaldab gluteeni": "Contains",
35
+ "Gluteenivaba": "Free of"
36
  }
37
 
38
+ # Search for recipes that include the specific ingredient
39
+ search_params = {
40
+ "apiKey": API_KEY,
41
+ "query": ingredient_en,
42
+ "includeIngredients": ingredient_en,
43
+ "number": 5, # Fetch multiple recipes to increase chances
44
  }
45
 
46
+ # Add diet filters
47
+ if gluten_content == "Gluteenivaba":
48
+ search_params["intolerances"] = "Gluten"
49
+
50
+ response = requests.get(RECIPE_SEARCH_URL, params=search_params)
51
 
52
  if response.status_code == 200:
53
+ recipes = response.json().get('results', [])
54
 
55
  if not recipes:
56
  return "Ühtegi retsepti ei leitud.", ""
57
 
58
+ # Try to find a suitable recipe
59
+ for recipe in recipes:
60
+ # Get detailed recipe information
61
+ recipe_info_response = requests.get(
62
+ RECIPE_INFO_URL.format(recipe['id']),
63
+ params={
64
+ "apiKey": API_KEY,
65
+ "includeNutrition": True
66
+ }
67
+ )
68
+
69
+ if recipe_info_response.status_code == 200:
70
+ recipe_info = recipe_info_response.json()
71
+
72
+ # Verify ingredient is in the recipe
73
+ ingredients_list = recipe_info.get('extendedIngredients', [])
74
+ ingredient_names = [ing['name'].lower() for ing in ingredients_list]
75
+
76
+ # Check if the main ingredient is in the recipe
77
+ if any(ingredient_en.lower() in name for name in ingredient_names):
78
+ # Translate recipe title
79
+ recipe_name_en = recipe_info['title']
80
+ recipe_name_et = translate_text(recipe_name_en, direction='en-et')
81
+
82
+ # Create recipe link
83
+ recipe_link = recipe_info.get('sourceUrl', 'Link pole saadaval')
84
+
85
+ # Translate ingredients to Estonian
86
+ ingredients_list = [f"- {ingredient['original']}" for ingredient in ingredients_list]
87
+ ingredients_en = '\n'.join(ingredients_list)
88
+ ingredients_et = translate_text(ingredients_en, direction='en-et')
89
+
90
+ # Translate instructions
91
+ instructions_en = recipe_info.get('instructions', 'Instructions not available')
92
+ instructions_et = translate_text(instructions_en, direction='en-et')
93
+
94
+ # Calculate calories per serving
95
+ nutrition = recipe_info.get('nutrition', {})
96
+ calories_per_serving = nutrition.get('calories', 'N/A')
97
+
98
+ # Create a detailed recipe description
99
+ recipe_description = (
100
+ f"🍽️ RETSEPT: {recipe_name_et}\n\n"
101
+ f"🥘 Põhikoostisosa: {ingredient}\n\n"
102
+ f"⏲️ Valmistamisaeg: {recipe_info.get('readyInMinutes', 'N/A')} minutit\n"
103
+ f"👥 Portsjonite arv: {recipe_info.get('servings', 'N/A')}\n\n"
104
+ f"📝 KOOSTISOSAD:\n{ingredients_et}\n\n"
105
+ f"👩‍🍳 VALMISTAMISE JUHISED:\n{instructions_et}\n\n"
106
+ f"ℹ️ LISAINFO:\n"
107
+ f"Kalorsus: {calories}\n"
108
+ f"Gluteenisisaldus: {gluten_content}\n"
109
+ f"Kalorid portsjoni kohta: {calories_per_serving}\n\n"
110
+ f"🔗 Originaalretsept: {recipe_link}"
111
+ )
112
+
113
+ return recipe_description, recipe_link
114
 
115
+ # If no recipe found with the exact ingredient
116
+ return "Kahjuks ei leitud retsepti täpse koostisosaga.", ""
117
  else:
118
  return "Viga retseptide toomisel.", ""
119
 
 
132
  type="value"
133
  ),
134
  gr.Dropdown(
135
+ choices=["Sisaldab gluteeni", "Gluteenivaba"],
136
+ label="Gluteenisisaldus",
137
  type="value"
138
  )
139
  ],
140
  outputs=[
141
+ gr.Textbox(lines=20, label="Genereeritud Retsept"),
142
  gr.Textbox(lines=1, label="Retsepti Link")
143
  ],
144
  title="🍳 Nutikas Retsepti Generaator",
145
  description=(
146
+ "Sisestage koostisosa, valige kalorsus ja gluteenisisaldus. "
147
  "Saate personaalse retsepti!"
148
  ),
149
  examples=[
150
+ ["lõhe", "Madal kalorsus", "Gluteenivaba"],
151
+ ["šokolaadikook", "Kõrge kalorsus", "Sisaldab gluteeni"],
152
+ ["kartul", "Madal kalorsus", "Gluteenivaba"]
153
  ],
154
  theme="default"
155
  )