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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import base64
|
| 3 |
+
import requests
|
| 4 |
+
import io
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from together import Together
|
| 9 |
+
import tempfile
|
| 10 |
+
|
| 11 |
+
def encode_image_to_base64(image_path):
|
| 12 |
+
"""Convert image to base64 encoding"""
|
| 13 |
+
with open(image_path, "rb") as image_file:
|
| 14 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 15 |
+
|
| 16 |
+
def save_uploaded_image(image):
|
| 17 |
+
"""Save uploaded image to a temporary file and return the path"""
|
| 18 |
+
if image is None:
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_file:
|
| 22 |
+
if isinstance(image, dict) and "path" in image: # Gradio returns image as dict
|
| 23 |
+
# Copy the uploaded image to our temporary file
|
| 24 |
+
with open(image["path"], "rb") as img_file:
|
| 25 |
+
temp_file.write(img_file.read())
|
| 26 |
+
elif isinstance(image, Image.Image):
|
| 27 |
+
# If it's a PIL Image, save it
|
| 28 |
+
image.save(temp_file.name, format="JPEG")
|
| 29 |
+
else:
|
| 30 |
+
# Try to handle other formats
|
| 31 |
+
try:
|
| 32 |
+
Image.open(image).save(temp_file.name, format="JPEG")
|
| 33 |
+
except Exception:
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
return temp_file.name
|
| 37 |
+
|
| 38 |
+
def get_recipe_suggestions(api_key, image, num_recipes=3, dietary_restrictions="None"):
|
| 39 |
+
"""
|
| 40 |
+
Get recipe suggestions based on the uploaded image of ingredients
|
| 41 |
+
"""
|
| 42 |
+
if not api_key or not image:
|
| 43 |
+
return "Please provide both an API key and an image of ingredients."
|
| 44 |
+
|
| 45 |
+
# Save the uploaded image
|
| 46 |
+
image_path = save_uploaded_image(image)
|
| 47 |
+
if not image_path:
|
| 48 |
+
return "Failed to process the uploaded image."
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
# Initialize Together client with the provided API key
|
| 52 |
+
client = Together(api_key=api_key)
|
| 53 |
+
|
| 54 |
+
# Create the prompt for the model
|
| 55 |
+
system_prompt = """You are a culinary expert AI assistant that specializes in creating recipes based on available ingredients.
|
| 56 |
+
Analyze the provided image of ingredients and suggest creative, detailed recipes.
|
| 57 |
+
For each recipe suggestion, include:
|
| 58 |
+
1. Recipe name
|
| 59 |
+
2. Brief description of the dish
|
| 60 |
+
3. Complete ingredients list (including estimated quantities and any additional staple ingredients that might be needed)
|
| 61 |
+
4. Step-by-step cooking instructions
|
| 62 |
+
5. Approximate cooking time
|
| 63 |
+
6. Difficulty level (Easy, Medium, Advanced)
|
| 64 |
+
7. Nutritional highlights
|
| 65 |
+
|
| 66 |
+
Consider any dietary restrictions mentioned by the user."""
|
| 67 |
+
|
| 68 |
+
user_prompt = f"""Based on the ingredients shown in this image, suggest {num_recipes} creative and delicious recipes.
|
| 69 |
+
Dietary restrictions to consider: {dietary_restrictions}
|
| 70 |
+
Please be specific about what ingredients you can identify in the image and creative with your recipe suggestions."""
|
| 71 |
+
|
| 72 |
+
# Create message with image
|
| 73 |
+
response = client.chat.completions.create(
|
| 74 |
+
model="meta-llama/Llama-Vision-Free",
|
| 75 |
+
messages=[
|
| 76 |
+
{
|
| 77 |
+
"role": "system",
|
| 78 |
+
"content": system_prompt
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"role": "user",
|
| 82 |
+
"content": [
|
| 83 |
+
{
|
| 84 |
+
"type": "text",
|
| 85 |
+
"text": user_prompt
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"type": "image_url",
|
| 89 |
+
"image_url": {
|
| 90 |
+
"url": f"file://{image_path}"
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
]
|
| 94 |
+
}
|
| 95 |
+
],
|
| 96 |
+
max_tokens=2048,
|
| 97 |
+
temperature=0.7
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
# Clean up the temporary file
|
| 101 |
+
try:
|
| 102 |
+
os.unlink(image_path)
|
| 103 |
+
except:
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
return response.choices[0].message.content
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
# Clean up the temporary file in case of error
|
| 110 |
+
try:
|
| 111 |
+
os.unlink(image_path)
|
| 112 |
+
except:
|
| 113 |
+
pass
|
| 114 |
+
return f"Error: {str(e)}"
|
| 115 |
+
|
| 116 |
+
# Create the Gradio interface
|
| 117 |
+
with gr.Blocks(title="Visual Recipe Assistant") as app:
|
| 118 |
+
gr.Markdown("# 🍲 Visual Recipe Assistant")
|
| 119 |
+
gr.Markdown("Upload an image of ingredients you have, and get creative recipe suggestions!")
|
| 120 |
+
|
| 121 |
+
with gr.Row():
|
| 122 |
+
with gr.Column(scale=1):
|
| 123 |
+
api_key_input = gr.Textbox(
|
| 124 |
+
label="Together API Key",
|
| 125 |
+
placeholder="Enter your Together API key here...",
|
| 126 |
+
type="password"
|
| 127 |
+
)
|
| 128 |
+
image_input = gr.Image(
|
| 129 |
+
label="Upload Image of Ingredients",
|
| 130 |
+
type="filepath"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
with gr.Row():
|
| 134 |
+
num_recipes = gr.Slider(
|
| 135 |
+
minimum=1,
|
| 136 |
+
maximum=5,
|
| 137 |
+
value=3,
|
| 138 |
+
step=1,
|
| 139 |
+
label="Number of Recipe Suggestions"
|
| 140 |
+
)
|
| 141 |
+
dietary_restrictions = gr.Dropdown(
|
| 142 |
+
choices=["None", "Vegetarian", "Vegan", "Gluten-Free", "Dairy-Free", "Low-Carb", "Keto"],
|
| 143 |
+
value="None",
|
| 144 |
+
label="Dietary Restrictions"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
submit_button = gr.Button("Get Recipe Suggestions", variant="primary")
|
| 148 |
+
|
| 149 |
+
with gr.Column(scale=2):
|
| 150 |
+
output = gr.Markdown(label="Recipe Suggestions")
|
| 151 |
+
|
| 152 |
+
# Set up the submission action
|
| 153 |
+
submit_button.click(
|
| 154 |
+
fn=get_recipe_suggestions,
|
| 155 |
+
inputs=[api_key_input, image_input, num_recipes, dietary_restrictions],
|
| 156 |
+
outputs=output
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
gr.Markdown("""
|
| 160 |
+
## How to Use
|
| 161 |
+
1. Enter your Together API key
|
| 162 |
+
2. Upload an image of ingredients you have available
|
| 163 |
+
3. Adjust the number of recipes you'd like to receive
|
| 164 |
+
4. Select any dietary restrictions
|
| 165 |
+
5. Click "Get Recipe Suggestions"
|
| 166 |
+
|
| 167 |
+
## About
|
| 168 |
+
This app uses the Llama-Vision-Free multimodal model from Meta to analyze images of ingredients
|
| 169 |
+
and suggest creative recipes based on what it identifies.
|
| 170 |
+
""")
|
| 171 |
+
|
| 172 |
+
# Launch the app
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
app.launch()
|