Slfagrouche commited on
Commit
dd71212
·
verified ·
1 Parent(s): 67b36d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -29
app.py CHANGED
@@ -15,6 +15,8 @@ MEALDB_BASE_URL = os.getenv('MEALDB_BASE_URL')
15
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
16
  youtube = build('youtube', 'v3', developerKey=YOUTUBE_DATA_API)
17
 
 
 
18
  # Function to convert image to base64
19
  def image_to_base64(image):
20
  buffered = io.BytesIO()
@@ -27,12 +29,9 @@ def perform_inference(image):
27
  image.save(buffered, format="JPEG")
28
  data = buffered.getvalue()
29
  model_url = "https://api-inference.huggingface.co/models/juliensimon/autotrain-food101-1471154053"
30
- try:
31
- response = requests.post(model_url, headers=headers, data=data)
32
- result = response.json()
33
- return result[0]['label']
34
- except Exception as e:
35
- return f"Error performing inference: {str(e)}"
36
 
37
  # Function to search YouTube videos based on a query
38
  def search_youtube_videos(query):
@@ -42,49 +41,63 @@ def search_youtube_videos(query):
42
  'maxResults': 5,
43
  'type': 'video',
44
  }
45
- try:
46
- search_response = youtube.search().list(**search_params).execute()
47
- video_ids = [item['id']['videoId'] for item in search_response['items']]
48
- return [f"https://www.youtube.com/embed/{video_id}" for video_id in video_ids]
49
- except Exception as e:
50
- return [f"Error searching YouTube: {str(e)}"]
51
 
52
  # Function to get recipe details from TheMealDB
53
  def get_recipe_details(query):
54
- try:
55
- response = requests.get(f"{MEALDB_BASE_URL}search.php?s={query}")
56
- data = response.json()
57
- meals = data.get('meals', [])
58
- if meals:
59
- meal_id = meals[0]['idMeal']
60
- details_response = requests.get(f"{MEALDB_BASE_URL}lookup.php?i={meal_id}")
61
- details_data = details_response.json()
62
- recipe = details_data['meals'][0]
63
- ingredients = "\n".join([f"{recipe[f'strIngredient{i}']}: {recipe[f'strMeasure{i}']}" for i in range(1, 21) if recipe[f'strIngredient{i}']])
64
- return f"{recipe['strMeal']} -\n\nSteps:\n{recipe['strInstructions']}\n\nIngredients:\n{ingredients}"
65
- else:
66
- return "Recipe details not found."
67
- except Exception as e:
68
- return f"Error fetching recipe details: {str(e)}"
69
 
70
  # Gradio interface function that handles image uploads and processes the data
 
71
  def gradio_interface(image):
72
  dish_name = perform_inference(image)
73
  youtube_links = search_youtube_videos(dish_name)
74
  recipe_details = get_recipe_details(dish_name)
75
- return dish_name, youtube_links, recipe_details
 
 
76
 
77
  iface = gr.Interface(
78
  fn=gradio_interface,
79
  inputs=gr.Image(type="pil", label="Upload an Image"),
80
  outputs=[
81
  gr.Textbox(label="Predicted Dish"),
82
- gr.Textbox(label="YouTube Recipe Videos"),
83
  gr.Textbox(label="Recipe Details")
84
  ],
85
  title="Dish Prediction, Recipe Videos, and Recipe Details",
86
  description="Upload an image of food, and the app will predict the dish, provide YouTube links for recipes, and fetch detailed recipe instructions."
87
  )
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  if __name__ == "__main__":
90
  iface.launch()
 
15
  headers = {"Authorization": f"Bearer {HF_API_KEY}"}
16
  youtube = build('youtube', 'v3', developerKey=YOUTUBE_DATA_API)
17
 
18
+
19
+
20
  # Function to convert image to base64
21
  def image_to_base64(image):
22
  buffered = io.BytesIO()
 
29
  image.save(buffered, format="JPEG")
30
  data = buffered.getvalue()
31
  model_url = "https://api-inference.huggingface.co/models/juliensimon/autotrain-food101-1471154053"
32
+ response = requests.post(model_url, headers=headers, data=data)
33
+ result = response.json()
34
+ return result[0]['label']
 
 
 
35
 
36
  # Function to search YouTube videos based on a query
37
  def search_youtube_videos(query):
 
41
  'maxResults': 5,
42
  'type': 'video',
43
  }
44
+ search_response = youtube.search().list(**search_params).execute()
45
+ video_ids = [item['id']['videoId'] for item in search_response['items']]
46
+ return [f"https://www.youtube.com/embed/{video_id}" for video_id in video_ids]
 
 
 
47
 
48
  # Function to get recipe details from TheMealDB
49
  def get_recipe_details(query):
50
+ response = requests.get(f"{mealdb_base_url}search.php?s={query}")
51
+ data = response.json()
52
+ meals = data.get('meals', [])
53
+ if meals:
54
+ meal_id = meals[0]['idMeal']
55
+ details_response = requests.get(f"{mealdb_base_url}lookup.php?i={meal_id}")
56
+ details_data = details_response.json()
57
+ recipe = details_data['meals'][0]
58
+ ingredients = "\n".join([f"{recipe[f'strIngredient{i}']}: {recipe[f'strMeasure{i}']}" for i in range(1, 21) if recipe[f'strIngredient{i}']])
59
+ return f"{recipe['strMeal']} -\n\nSteps:\n{recipe['strInstructions']}\n\nIngredients:\n{ingredients}"
60
+ return "Recipe details not found."
 
 
 
 
61
 
62
  # Gradio interface function that handles image uploads and processes the data
63
+
64
  def gradio_interface(image):
65
  dish_name = perform_inference(image)
66
  youtube_links = search_youtube_videos(dish_name)
67
  recipe_details = get_recipe_details(dish_name)
68
+ # Generate HTML content for embedding videos
69
+ youtube_html = generate_embed_html(youtube_links)
70
+ return dish_name, youtube_html, recipe_details
71
 
72
  iface = gr.Interface(
73
  fn=gradio_interface,
74
  inputs=gr.Image(type="pil", label="Upload an Image"),
75
  outputs=[
76
  gr.Textbox(label="Predicted Dish"),
77
+ gr.HTML(label="YouTube Recipe Videos"), # Changed to gr.HTML
78
  gr.Textbox(label="Recipe Details")
79
  ],
80
  title="Dish Prediction, Recipe Videos, and Recipe Details",
81
  description="Upload an image of food, and the app will predict the dish, provide YouTube links for recipes, and fetch detailed recipe instructions."
82
  )
83
 
84
+ def gradio_interface(image):
85
+ dish_name = perform_inference(image)
86
+ return dish_name, ""
87
+
88
+ def show_recipe(dish_name):
89
+ if dish_name:
90
+ return get_recipe_details(dish_name)
91
+ return "No dish predicted. Please upload an image and predict the dish first.", ""
92
+
93
+ def show_videos(dish_name):
94
+ if dish_name:
95
+ video_links = search_youtube_videos(dish_name)
96
+ return "", generate_embed_html(video_links)
97
+ return "", "No dish predicted. Please upload an image and predict the dish first."
98
+
99
+ iface = gr.Blocks()
100
+
101
+
102
  if __name__ == "__main__":
103
  iface.launch()