File size: 15,418 Bytes
30c01d5 1fde736 30c01d5 1fde736 30c01d5 81160e7 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 22148e0 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 1fde736 30c01d5 22148e0 30c01d5 22148e0 30c01d5 22148e0 30c01d5 22148e0 30c01d5 |
1 2 3 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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
import gradio as gr import base64 import requests import io from PIL import Image import json import os from together import Together import tempfile import uuid def encode_image_to_base64(image_path): """Convert image to base64 encoding""" with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8') def analyze_single_image(client, img_path): """Analyze a single image to identify ingredients""" system_prompt = """You are a culinary expert AI assistant that specializes in identifying ingredients in images. Your task is to analyze the provided image and list all the food ingredients you can identify. Be specific and detailed about what you see. Only list ingredients, don't suggest recipes yet.""" user_prompt = "Please identify all the food ingredients visible in this image. List each ingredient on a new line." try: with open(img_path, "rb") as image_file: base64_image = base64.b64encode(image_file.read()).decode('utf-8') content = [ {"type": "text", "text": user_prompt}, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{base64_image}" } } ] response = client.chat.completions.create( model="meta-llama/Llama-Vision-Free", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": content} ], max_tokens=500, temperature=0.2 ) return response.choices[0].message.content except Exception as e: return f"Error analyzing image: {str(e)}" def get_recipe_suggestions(api_key, image_paths, num_recipes=3, dietary_restrictions="None", cuisine_preference="Any"): """Get recipe suggestions based on the uploaded images of ingredients""" if not api_key: return "Please provide your Together API key." if not image_paths or len(image_paths) == 0: return "Please upload at least one image of ingredients." try: client = Together(api_key=api_key) all_ingredients = [] for img_path in image_paths: ingredients_text = analyze_single_image(client, img_path) all_ingredients.append(ingredients_text) combined_ingredients = "\n\n".join([f"Image {i+1} ingredients:\n{ingredients}" for i, ingredients in enumerate(all_ingredients)]) system_prompt = """You are a culinary expert AI assistant that specializes in creating recipes based on available ingredients. You will be provided with lists of ingredients identified from multiple images. Your task is to suggest creative, detailed recipes that use as many of the identified ingredients as possible. For each recipe suggestion, include: 1. Recipe name 2. Brief description of the dish 3. Complete ingredients list (including estimated quantities and any additional staple ingredients that might be needed) 4. Step-by-step cooking instructions 5. Approximate cooking time 6. Difficulty level (Easy, Medium, Advanced) 7. Nutritional highlights Consider any dietary restrictions and cuisine preferences mentioned by the user.""" user_prompt = f"""Based on the following ingredients identified from multiple images, suggest {num_recipes} creative and delicious recipes. {combined_ingredients} Dietary restrictions to consider: {dietary_restrictions} Cuisine preference: {cuisine_preference} Please be creative with your recipe suggestions and try to use ingredients from multiple images if possible.""" response = client.chat.completions.create( model="meta-llama/Llama-Vision-Free", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ], max_tokens=20000, #2048 temperature=0.7 ) result = "## π Ingredients Identified\n\n" result += combined_ingredients result += "\n\n---\n\n" result += "## π½οΈ Recipe Suggestions\n\n" result += response.choices[0].message.content return result except Exception as e: return f"Error: {str(e)}" def update_gallery(files): """Update the gallery with uploaded image paths""" if not files or len(files) == 0: return gr.update(visible=False) return gr.update(value=files, visible=True) def process_recipe_request(api_key, files, num_recipes, dietary_restrictions, cuisine_preference): """Process the recipe request with uploaded files""" if not files: return "Please upload at least one image of ingredients." return get_recipe_suggestions(api_key, files, num_recipes, dietary_restrictions, cuisine_preference) custom_css = """ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap'); :root { --primary-color: #FF6F61; /* Warm coral */ --secondary-color: #4BB543; /* Fresh green */ --accent-color: #F0A500; /* Golden yellow */ --background-color: #F4F4F9; /* Light grayish background */ --text-color: #333333; /* Dark gray text */ --card-background: #FFFFFF; /* White for cards */ --border-radius: 12px; --font-family: 'Poppins', sans-serif; --box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 20px; --hover-shadow: rgba(0, 0, 0, 0.15) 0px 8px 30px; } body { font-family: var(--font-family); background-color: var(--background-color); color: var(--text-color); margin: 0; padding: 0; } .container { max-width: 1200px; margin: 0 auto; padding: 20px; } .app-header { background-color: var(--primary-color); color: white; padding: 60px 20px; text-align: center; border-radius: 0 0 30px 30px; box-shadow: var(--box-shadow); } .app-title { font-size: 2.8em; font-weight: 700; margin-bottom: 10px; } .app-subtitle { font-size: 1.3em; font-weight: 300; max-width: 800px; margin: 0 auto; } .input-section, .output-section { background-color: var(--card-background); border-radius: var(--border-radius); padding: 30px; box-shadow: var(--box-shadow); margin-bottom: 30px; } .section-header { font-size: 1.6em; font-weight: 600; color: var(--text-color); margin-bottom: 20px; border-bottom: 2px solid var(--primary-color); padding-bottom: 10px; } .section-header2 { font-size: 1.6em; font-weight: 600; color: var(--text-color); border-bottom: 2px solid var(--primary-color); padding-bottom: 10px; } .image-upload-container { border: 2px dashed var(--secondary-color); padding: 40px; text-align: center; background-color: rgba(75, 181, 67, 0.1); transition: all 0.3s ease; } .image-upload-container:hover { border-color: var(--primary-color); background-color: rgba(255, 111, 97, 0.1); } button.primary-button { background-color: var(--primary-color); color: white; border: none; padding: 16px 32px; border-radius: 6px; font-size: 1.1em; cursor: pointer; transition: all 0.3s ease; width: 100%; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); } button.primary-button:hover { background-color: #E15F52; box-shadow: var(--hover-shadow); } .gallery-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin-top: 30px; } .gallery-item { border-radius: var(--border-radius); overflow: hidden; box-shadow: var(--box-shadow); transition: transform 0.3s ease; aspect-ratio: 1 / 1; object-fit: cover; } .gallery-item:hover { transform: scale(1.05); box-shadow: var(--hover-shadow); } .recipe-output { font-size: 1.2em; line-height: 1.7; color: var(--text-color); max-height: 600px; overflow-y: auto; padding-right: 15px; } .recipe-output h2 { color: var(--primary-color); margin-top: 30px; font-size: 2em; } .recipe-output h3 { color: var(--secondary-color); font-size: 1.5em; margin-top: 20px; } .loading-container { display: flex; flex-direction: column; justify-content: center; align-items: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; opacity: 0; visibility: hidden; transition: opacity 0.3s ease, visibility 0.3s ease; } .loading-container.visible { opacity: 1; visibility: visible; } .loading-spinner { border: 8px solid #f3f3f3; border-top: 8px solid var(--primary-color); border-radius: 50%; width: 60px; height: 60px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .loading-text { color: white; font-size: 1.3em; margin-top: 20px; } .footer { background-color: var(--card-background); padding: 40px 20px; text-align: center; color: var(--text-color); font-size: 1.1em; box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05); } .footer-content { max-width: 800px; margin: 0 auto; } .footer-brand { font-weight: 700; color: var(--primary-color); } .footer-links a { color: var(--secondary-color); text-decoration: none; margin: 0 15px; transition: color 0.3s ease; } .footer-links a:hover { color: var(--primary-color); } """ html_header = """ <div class="app-header"> <div class="app-title">π² Visual Recipe Assistant</div> <div class="app-subtitle">Upload images of ingredients you have on hand and get personalized recipe suggestions powered by AI</div> </div> <div id="loading-overlay" class="loading-container"> <div class="loading-spinner"></div> <div class="loading-text">Generating your recipes...</div> </div> <script> function showLoading() { document.getElementById('loading-overlay').classList.add('visible'); } function hideLoading() { document.getElementById('loading-overlay').classList.remove('visible'); } </script> """ html_footer = """ <div class="footer"> <div class="footer-content"> <p><span class="footer-brand">π² Visual Recipe Assistant</span></p> <p>Powered by Meta's Llama-Vision-Free Model & Together AI</p> <p>Upload multiple ingredient images for more creative recipe combinations</p> <div class="footer-links"> <a href="#" target="_blank">How It Works</a> <a href="#" target="_blank">Privacy Policy</a> <a href="#" target="_blank">Contact Us</a> </div> </div> </div> <script> document.addEventListener('DOMContentLoaded', function() { const submitBtn = document.querySelector('button.primary-button'); if (submitBtn) { submitBtn.addEventListener('click', function() { showLoading(); const output = document.querySelector('.recipe-output'); // Check every second for output content const checkInterval = setInterval(function() { if (output && output.textContent.trim().length > 0) { hideLoading(); clearInterval(checkInterval); clearTimeout(forceHideTimeout); } }, 60000); // Force hide after 120 seconds const forceHideTimeout = setTimeout(function() { hideLoading(); clearInterval(checkInterval); }, 120000); // 120000 milliseconds = 120 seconds }); } }); </script> """ with gr.Blocks(css=custom_css) as app: gr.HTML(html_header) with gr.Row(): with gr.Column(scale=1): with gr.Group(elem_classes="input-section"): gr.HTML('<h3 class="section-header">API Configuration</h3>') api_key_input = gr.Textbox( label="Together API Key", placeholder="Enter your Together API key here...", type="password", elem_classes="input-group" ) gr.HTML('<h3 class="section-header">Upload Ingredients</h3>') file_upload = gr.File( label="Upload images of ingredients", file_types=["image"], file_count="multiple", elem_classes="image-upload-container" ) image_input = gr.Gallery( label="Uploaded Ingredients", elem_id="ingredient-gallery", columns=3, rows=2, height="auto", visible=False ) gr.HTML('<h3 class="section-header2">Recipe Preferences</h3>') with gr.Row(): num_recipes = gr.Slider( minimum=1, maximum=5, value=3, step=1, label="Number of Recipe Suggestions", elem_classes="input-group" ) with gr.Row(): with gr.Column(): dietary_restrictions = gr.Dropdown( choices=["None", "Vegetarian", "Vegan", "Gluten-Free", "Dairy-Free", "Low-Carb", "Keto", "Paleo"], value="None", label="Dietary Restrictions", elem_classes="input-group" ) with gr.Column(): cuisine_preference = gr.Dropdown( choices=["Any", "Italian", "Asian", "Mexican", "Mediterranean", "Indian", "American", "French", "Middle Eastern"], value="Any", label="Cuisine Preference", elem_classes="input-group" ) submit_button = gr.Button("Get Recipe Suggestions", elem_classes="primary-button") with gr.Column(scale=1): with gr.Group(elem_classes="output-section"): gr.HTML('<h3 class="section-header">Your Personalized Recipes</h3>') output = gr.Markdown(elem_classes="recipe-output") gr.HTML(html_footer) file_upload.change(fn=update_gallery, inputs=file_upload, outputs=image_input) submit_button.click( fn=process_recipe_request, inputs=[api_key_input, file_upload, num_recipes, dietary_restrictions, cuisine_preference], outputs=output ) if __name__ == "__main__": app.launch() |