🍳 AI Recipe Generator

Core Source Code & Food Recognition Implementation

Python 3.9 Streamlit Gemini Vision Food Analysis

🔍 About This Code Showcase

This curated code snippet demonstrates how the AI Recipe Generator analyzes food images, identifies ingredients, and generates detailed cooking instructions with nutritional information.

Full deployment scripts, API integrations, and proprietary details are omitted for clarity and security. This showcase highlights the core food recognition and recipe generation algorithms.

🥘 Core Algorithm: Food Intelligence Engine

The foundation of the AI Recipe Generator is its ability to analyze food images, identify ingredients and cooking methods, then generate authentic recipes with proper techniques and timing:

📄 recipe_generator.py
import google.generativeai as genai import streamlit as st from PIL import Image from typing import Dict, List, Optional import json class FoodAnalysisEngine: """ Advanced food recognition engine that analyzes images to identify ingredients, cooking methods, and cultural origins for authentic recipe generation. """ def __init__(self, api_key: str): genai.configure(api_key=api_key) self.vision_model = genai.GenerativeModel('gemini-pro-vision') # Extensive culinary knowledge base for accurate recipe generation self.cooking_techniques = { 'sautéing': {'heat': 'medium-high', 'time_factor': 1.2, 'oil_needed': True}, 'braising': {'heat': 'low', 'time_factor': 3.5, 'liquid_needed': True}, 'roasting': {'heat': 'high', 'time_factor': 2.0, 'oven': True}, 'steaming': {'heat': 'medium', 'time_factor': 0.8, 'water_needed': True} } self.cuisine_patterns = { 'italian': {'herbs': ['basil', 'oregano', 'rosemary'], 'techniques': ['sautéing', 'braising']}, 'asian': {'seasonings': ['soy sauce', 'ginger', 'garlic'], 'techniques': ['stir-frying', 'steaming']}, 'mediterranean': {'ingredients': ['olive oil', 'tomatoes', 'herbs'], 'techniques': ['grilling', 'roasting']} } def analyze_food_image(self, image: Image.Image) -> Dict: """ Comprehensive food image analysis using advanced computer vision. Identifies ingredients, cooking methods, cuisine type, and presentation style. Args: image: PIL Image object of the food photo Returns: Dictionary containing detailed food analysis and recipe components """ # Step 1: Detailed visual analysis using AI vision analysis_prompt = """ Analyze this food image in detail. Identify: 1. INGREDIENTS: List all visible ingredients with quantities 2. COOKING METHOD: How was this dish prepared? (grilled, fried, baked, etc.) 3. CUISINE TYPE: What cuisine does this represent? (Italian, Asian, etc.) 4. DISH CATEGORY: Appetizer, main course, dessert, etc. 5. PRESENTATION: Plating style and garnishes used 6. COMPLEXITY: Beginner, intermediate, or advanced cooking level 7. COOKING TIME: Estimated preparation and cooking time Be specific about ingredients and techniques you can identify. """ response = self.vision_model.generate_content([analysis_prompt, image]) # Step 2: Extract structured data from AI analysis food_analysis = self._parse_food_analysis(response.text) # Step 3: Enhance analysis with culinary knowledge base enhanced_analysis = self._enhance_with_culinary_knowledge(food_analysis) return enhanced_analysis def generate_detailed_recipe(self, food_analysis: Dict) -> Dict: """ Generate a comprehensive recipe based on food analysis. Includes ingredients, step-by-step instructions, tips, and variations. """ # Create contextual recipe prompt based on analysis recipe_prompt = f""" Based on this food analysis, create a detailed recipe: Dish Type: {food_analysis.get('dish_category', 'Unknown')} Cuisine: {food_analysis.get('cuisine_type', 'General')} Complexity: {food_analysis.get('complexity', 'Intermediate')} Identified Ingredients: {food_analysis.get('ingredients', [])} Cooking Methods: {food_analysis.get('cooking_methods', [])} Generate a complete recipe with: 1. INGREDIENTS LIST: Exact measurements and substitutions 2. EQUIPMENT NEEDED: Essential tools and cookware 3. PREP INSTRUCTIONS: Detailed preparation steps 4. COOKING INSTRUCTIONS: Step-by-step cooking process with timing 5. PLATING & SERVING: Presentation and serving suggestions 6. CHEF'S TIPS: Professional techniques and troubleshooting 7. VARIATIONS: Alternative ingredients or methods 8. NUTRITIONAL NOTES: Basic nutritional information Make it professional quality but accessible to home cooks. """ recipe_response = self.vision_model.generate_content(recipe_prompt) # Structure the recipe for better usability structured_recipe = self._structure_recipe(recipe_response.text, food_analysis) return structured_recipe def _enhance_with_culinary_knowledge(self, analysis: Dict) -> Dict: """ Enhance AI analysis with professional culinary knowledge. Adds cooking techniques, timing estimates, and cultural context. """ cuisine_type = analysis.get('cuisine_type', 'general').lower() cooking_methods = analysis.get('cooking_methods', []) # Add cuisine-specific enhancements if cuisine_type in self.cuisine_patterns: pattern = self.cuisine_patterns[cuisine_type] analysis['suggested_seasonings'] = pattern.get('seasonings', pattern.get('herbs', [])) analysis['cultural_context'] = f"Traditional {cuisine_type} cuisine techniques" # Calculate cooking time based on identified techniques total_time = 0 for method in cooking_methods: if method.lower() in self.cooking_techniques: technique = self.cooking_techniques[method.lower()] base_time = 30 # Base cooking time in minutes total_time += base_time * technique['time_factor'] analysis['estimated_total_time'] = max(15, int(total_time)) # Minimum 15 minutes analysis['difficulty_score'] = self._calculate_difficulty(analysis) return analysis

🧪 Advanced Recipe Optimization Engine

The recipe optimization system ensures accurate measurements, proper cooking techniques, and provides intelligent substitutions and dietary modifications:

📄 recipe_optimizer.py
class RecipeOptimizer: def _structure_recipe(self, raw_recipe: str, analysis: Dict) -> Dict: """ Convert AI-generated recipe text into structured, usable format. Adds measurement precision, timing details, and quality controls. """ # Parse recipe sections using natural language processing sections = self._parse_recipe_sections(raw_recipe) # Optimize ingredient measurements for accuracy optimized_ingredients = self._optimize_ingredient_measurements( sections.get('ingredients', []), analysis.get('serving_size', 4) ) # Add precise timing to cooking steps timed_instructions = self._add_timing_to_steps( sections.get('instructions', []), analysis.get('cooking_methods', []) ) # Generate nutritional estimates nutrition_info = self._estimate_nutrition(optimized_ingredients) return { 'title': analysis.get('dish_name', 'Delicious Recipe'), 'cuisine_type': analysis.get('cuisine_type', 'International'), 'difficulty': analysis.get('complexity', 'Intermediate'), 'total_time': analysis.get('estimated_total_time', 45), 'serving_size': analysis.get('serving_size', 4), 'ingredients': optimized_ingredients, 'instructions': timed_instructions, 'equipment': sections.get('equipment', []), 'tips': sections.get('tips', []), 'variations': sections.get('variations', []), 'nutrition': nutrition_info } def _optimize_ingredient_measurements(self, ingredients: List[str], serving_size: int) -> List[Dict]: """ Convert ingredient descriptions into precise measurements. Scales quantities appropriately and suggests substitutions. """ optimized = [] for ingredient in ingredients: # Parse ingredient text to extract quantity, unit, and item parsed = self._parse_ingredient(ingredient) # Scale quantity based on serving size scaled_quantity = self._scale_quantity(parsed['quantity'], serving_size) # Suggest substitutions for dietary restrictions substitutions = self._suggest_substitutions(parsed['item']) optimized.append({ 'item': parsed['item'], 'quantity': scaled_quantity, 'unit': parsed['unit'], 'preparation': parsed.get('preparation', ''), 'substitutions': substitutions, 'optional': 'optional' in ingredient.lower() }) return optimized def _add_timing_to_steps(self, instructions: List[str], cooking_methods: List[str]) -> List[Dict]: """ Add precise timing information to each cooking step. Considers cooking method complexity and ingredient requirements. """ timed_steps = [] cumulative_time = 0 for i, step in enumerate(instructions): # Analyze step to determine timing step_analysis = self._analyze_cooking_step(step, cooking_methods) step_time = step_analysis['estimated_time'] cumulative_time += step_time timed_steps.append({ 'step_number': i + 1, 'instruction': step, 'estimated_time': step_time, 'cumulative_time': cumulative_time, 'technique': step_analysis['primary_technique'], 'temperature': step_analysis.get('temperature'), 'visual_cues': step_analysis.get('visual_cues', []), 'pro_tips': step_analysis.get('pro_tips', []) }) return timed_steps def _estimate_nutrition(self, ingredients: List[Dict]) -> Dict: """ Provide basic nutritional estimates based on ingredients. Uses standard nutritional databases for common ingredients. """ # Simplified nutritional calculation - in production would use comprehensive database nutrition_db = { 'chicken': {'calories_per_100g': 165, 'protein': 31, 'fat': 3.6}, 'rice': {'calories_per_100g': 130, 'carbs': 28, 'protein': 2.7}, 'olive oil': {'calories_per_100g': 884, 'fat': 100}, 'vegetables': {'calories_per_100g': 25, 'carbs': 5, 'fiber': 3} } total_calories = 0 total_protein = 0 total_carbs = 0 total_fat = 0 for ingredient in ingredients: item_name = ingredient['item'].lower() # Match ingredient to nutrition database nutrition_data = self._find_nutrition_match(item_name, nutrition_db) if nutrition_data: # Estimate portion size and calculate nutrition estimated_grams = self._estimate_ingredient_weight(ingredient) factor = estimated_grams / 100 total_calories += nutrition_data.get('calories_per_100g', 0) * factor total_protein += nutrition_data.get('protein', 0) * factor total_carbs += nutrition_data.get('carbs', 0) * factor total_fat += nutrition_data.get('fat', 0) * factor return { 'calories_per_serving': round(total_calories / 4), # Assuming 4 servings 'protein_g': round(total_protein / 4, 1), 'carbs_g': round(total_carbs / 4, 1), 'fat_g': round(total_fat / 4, 1), 'disclaimer': 'Nutritional values are estimates based on standard ingredients' }

⚙️ Technical Implementation Notes

Key Algorithms & Innovations

Why This Approach Works