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 save_uploaded_image(image): """Save uploaded image to a temporary file and return the path""" if image is None: return None with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_file: if isinstance(image, dict) and "path" in image: with open(image["path"], "rb") as img_file: temp_file.write(img_file.read()) elif isinstance(image, Image.Image): image.save(temp_file.name, format="JPEG") else: try: Image.open(image).save(temp_file.name, format="JPEG") except Exception: return None return temp_file.name 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, images, 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 images or len(images) == 0 or all(img is None for img in images): return "Please upload at least one image of ingredients." valid_images = [img for img in images if img is not None] if len(valid_images) == 0: return "No valid images were uploaded. Please try again." image_paths = [] for img in valid_images: img_path = save_uploaded_image(img) if img_path: image_paths.append(img_path) if not image_paths: return "Failed to process the uploaded images." 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=2048, temperature=0.7 ) for img_path in image_paths: try: os.unlink(img_path) except: pass 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: for img_path in image_paths: try: os.unlink(img_path) except: pass return f"Error: {str(e)}" custom_css = """ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap'); :root { --primary-color: #E67E22; --primary-dark: #D35400; --secondary-color: #2ECC71; --accent-color: #F1C40F; --background-color: #FFFFFF; --text-color: #4A4A4A; --card-background: #F8F9FA; --border-radius: 10px; --font-family: 'Poppins', sans-serif; } 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: 40px 20px; text-align: center; border-radius: 0 0 20px 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); } .app-title { font-size: 2.5em; margin-bottom: 10px; font-weight: 700; } .app-subtitle { font-size: 1.2em; font-weight: 300; max-width: 600px; margin: 0 auto; } .input-section, .output-section { background-color: var(--card-background); border-radius: var(--border-radius); padding: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); margin-bottom: 30px; } .section-header { font-size: 1.5em; font-weight: 600; color: var(--text-color); margin-bottom: 20px; border-bottom: 2px solid var(--primary-color); padding-bottom: 10px; } .image-upload-container { border: 2px dashed var(--secondary-color); border-radius: var(--border-radius); padding: 40px; text-align: center; background-color: rgba(46, 204, 113, 0.05); transition: all 0.3s ease; } .image-upload-container:hover { border-color: var(--primary-color); background-color: rgba(230, 126, 34, 0.05); } button.primary-button { background-color: var(--primary-color); color: white; border: none; padding: 15px 30px; border-radius: 5px; font-size: 1.1em; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 2px 5px rgba(0,0,0,0.1); width: 100%; } button.primary-button:hover { background-color: var(--primary-dark); box-shadow: 0 4px 10px rgba(0,0,0,0.15); } .gallery-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; margin-top: 20px; } .gallery-item { border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.1); transition: transform 0.3s ease; } .gallery-item:hover { transform: scale(1.05); } .recipe-output { font-size: 1.1em; line-height: 1.6; color: var(--text-color); max-height: 600px; overflow-y: auto; padding-right: 10px; } .recipe-output h2 { color: var(--primary-color); margin-top: 30px; font-size: 1.8em; } .recipe-output h3 { color: var(--secondary-color); font-size: 1.4em; 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.2em; margin-top: 20px; } .footer { background-color: var(--card-background); padding: 40px 20px; text-align: center; color: var(--text-color); font-size: 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 = """