sathwik2004's picture
update.py
4a16564 verified
raw
history blame
27 kB
import gradio as gr
import pandas as pd
import os
import requests
import json
from collections import defaultdict
import re
import urllib.parse
# Load the dataset
df = pd.read_csv("recipes_dataset.csv")
# Bria API Configuration
BRIA_API_KEY = os.getenv("BRIA_API_KEY", "3e0c700582c74fa58bb5c219b458da66") # Set your Bria API key as environment variable
BRIA_API_URL = "https://api.bria.ai/v1/text-to-image"
# Language translations dictionary
TRANSLATIONS = {
'English': {
'app_title': '🍳 Telugu Recipe App with AI Images',
'app_subtitle': 'Search for delicious Telugu recipes with AI-generated images and video tutorials!',
'search_recipe': 'Search Recipe',
'enter_recipe_name': 'Enter Recipe Name',
'recipe_placeholder': 'e.g., Chicken Curry, Fish Curry, Biryani...',
'search_button': '🔍 Search Recipe with Images',
'all_recipes': 'All Recipes',
'show_all_recipes': '📋 Show All Recipes',
'quick_recipes': 'Quick Recipes',
'maximum_time': 'Maximum Time (minutes)',
'find_quick_recipes': '⚡ Find Quick Recipes',
'categories': 'Categories',
'show_categories': '📊 Show Recipe Categories',
'cooking_time': 'Cooking Time',
'ingredients': 'Ingredients',
'no_recipe_found': 'No recipe found for',
'please_enter_recipe': 'Please enter a recipe name!',
'available_recipes': 'Available Recipes',
'recipes_under_time': 'Recipes under',
'minutes': 'minutes',
'no_recipes_under_time': 'No recipes found under',
'recipe_categories': 'Recipe Categories',
'curry_dishes': 'Curry Dishes',
'rice_dishes': 'Rice Dishes',
'egg_dishes': 'Egg Dishes',
'please_enter_valid_time': 'Please enter a valid time!',
'convert_to': 'Convert to',
'language_options': ['Telugu', 'Tamil', 'Hindi'],
'generated_image': 'AI Generated Recipe Image',
'video_tutorials': 'Recommended Video Tutorials',
'image_generation_failed': 'Failed to generate image',
'api_key_missing': 'Bria API key not configured',
'generating_image': 'Generating AI image...',
'searching_videos': 'Finding video tutorials...',
'visual_guide': 'Visual Guide & Tutorials'
},
'Telugu': {
'app_title': '🍳 తెలుగు వంటల యాప్ AI చిత్రాలతో',
'app_subtitle': 'AI చిత్రాలు మరియు వీడియో ట్యుటోరియల్స్‌తో రుచికరమైన తెలుగు వంటకాల కోసం వెతకండి!',
'search_recipe': 'వంటకం వెతుకు',
'enter_recipe_name': 'వంటకం పేరు ఎంటర్ చేయండి',
'recipe_placeholder': 'ఉదా., చికెన్ కూర, ఫిష్ కూర, బిర్యానీ...',
'search_button': '🔍 చిత్రాలతో వంటకం వెతుకు',
'all_recipes': 'అన్ని వంటకాలు',
'show_all_recipes': '📋 అన్ని వంటకాలు చూపించు',
'quick_recipes': 'త్వరగా చేసే వంటకాలు',
'maximum_time': 'గరిష్ట సమయం (నిమిషాలు)',
'find_quick_recipes': '⚡ త్వరగా చేసే వంటకాలు కనుగొనండి',
'categories': 'వర్గాలు',
'show_categories': '📊 వంటకాల వర్గాలు చూపించు',
'cooking_time': 'వంట సమయం',
'ingredients': 'పదార్థాలు',
'no_recipe_found': 'దొరకలేదు',
'please_enter_recipe': 'దయచేసి వంటకం పేరు ఎంటర్ చేయండి!',
'available_recipes': 'అందుబాటులో ఉన్న వంటకాలు',
'recipes_under_time': 'వంటకాలు',
'minutes': 'నిమిషాలలోపు',
'no_recipes_under_time': 'నిమిషాలలోపు వంటకాలు లేవు',
'recipe_categories': 'వంటకాల వర్గాలు',
'curry_dishes': 'కూర వంటకాలు',
'rice_dishes': 'అన్నం వంటకాలు',
'egg_dishes': 'గుడ్డు వంటకాలు',
'please_enter_valid_time': 'దయచేసి సరైన సమయం ఎంటర్ చేయండి!',
'convert_to': 'మార్చు',
'language_options': ['English', 'Tamil', 'Hindi'],
'generated_image': 'AI రూపొందించిన వంటకం చిత్రం',
'video_tutorials': 'సిఫార్సు చేయబడిన వీడియో ట్యుటోరియల్స్',
'image_generation_failed': 'చిత్రం రూపొందించడంలో విఫలమైంది',
'api_key_missing': 'Bria API కీ కాన్ఫిగర్ చేయబడలేదు',
'generating_image': 'AI చిత్రం రూపొందిస్తోంది...',
'searching_videos': 'వీడియో ట్యుటోరియల్స్ వెతుకుతోంది...',
'visual_guide': 'దృశ్య గైడ్ & ట్యుటోరియల్స్'
},
'Tamil': {
'app_title': '🍳 தெலுங்கு சமையல் பயன்பாடு AI படங்களுடன்',
'app_subtitle': 'AI படங்கள் மற்றும் வீடியோ டுடோரியல்களுடன் சுவையான தெலுங்கு சமையல் குறிப்புகளை தேடுங்கள்!',
'search_recipe': 'சமையல் தேடுக',
'enter_recipe_name': 'சமையல் பெயர் உள்ளிடவும்',
'recipe_placeholder': 'எ.கா., சிக்கன் கறி, மீன் கறி, பிரியாணி...',
'search_button': '🔍 படங்களுடன் சமையல் தேடுக',
'all_recipes': 'அனைத்து சமையல்',
'show_all_recipes': '📋 அனைத்து சமையல் காட்டுக',
'quick_recipes': 'விரைவு சமையல்',
'maximum_time': 'அதிகபட்ச நேரம் (நிமிடங்கள்)',
'find_quick_recipes': '⚡ விரைவு சமையல் கண்டுபிடிக்கவும்',
'categories': 'வகைகள்',
'show_categories': '📊 சமையல் வகைகள் காட்டுக',
'cooking_time': 'சமையல் நேரம்',
'ingredients': 'பொருட்கள்',
'no_recipe_found': 'கண்டுபிடிக்க முடியவில்லை',
'please_enter_recipe': 'தயவுசெய்து சமையல் பெயர் உள்ளிடவும்!',
'available_recipes': 'கிடைக்கும் சமையல்',
'recipes_under_time': 'சமையல்',
'minutes': 'நிமிடங்களுக்குள்',
'no_recipes_under_time': 'நிமிடங்களுக்குள் சமையல் இல்லை',
'recipe_categories': 'சமையல் வகைகள்',
'curry_dishes': 'கறி வகைகள்',
'rice_dishes': 'சாதம் வகைகள்',
'egg_dishes': 'முட்டை வகைகள்',
'please_enter_valid_time': 'தயவுசெய்து சரியான நேரம் உள்ளிடவும்!',
'convert_to': 'மாற்று',
'language_options': ['English', 'Telugu', 'Hindi'],
'generated_image': 'AI உருவாக்கிய சமையல் படம்',
'video_tutorials': 'பரிந்துரைக்கப்பட்ட வீடியோ டுடோரியல்கள்',
'image_generation_failed': 'படம் உருவாக்குவதில் தோல்வி',
'api_key_missing': 'Bria API கீ கட்டமைக்கப்படவில்லை',
'generating_image': 'AI படம் உருவாக்குகிறது...',
'searching_videos': 'வீடியோ டுடோரியல்களை தேடுகிறது...',
'visual_guide': 'காட்சி வழிகாட்டி & டுடோரியல்கள்'
},
'Hindi': {
'app_title': '🍳 तेलुगु रेसिपी ऐप AI चित्रों के साथ',
'app_subtitle': 'AI चित्रों और वीडियो ट्यूटोरियल के साथ स्वादिष्ट तेलुगु व्यंजनों की खोज करें!',
'search_recipe': 'रेसिपी खोजें',
'enter_recipe_name': 'रेसिपी का नाम दर्ज करें',
'recipe_placeholder': 'जैसे, चिकन करी, फिश करी, बिरयानी...',
'search_button': '🔍 चित्रों के साथ रेसिपी खोजें',
'all_recipes': 'सभी रेसिपी',
'show_all_recipes': '📋 सभी रेसिपी दिखाएं',
'quick_recipes': 'त्वरित रेसिपी',
'maximum_time': 'अधिकतम समय (मिनट)',
'find_quick_recipes': '⚡ त्वरित रेसिपी खोजें',
'categories': 'श्रेणियां',
'show_categories': '📊 रेसिपी श्रेणियां दिखाएं',
'cooking_time': 'खाना पकाने का समय',
'ingredients': 'सामग्री',
'no_recipe_found': 'नहीं मिली',
'please_enter_recipe': 'कृपया रेसिपी का नाम दर्ज करें!',
'available_recipes': 'उपलब्ध रेसिपी',
'recipes_under_time': 'रेसिपी',
'minutes': 'मिनट के अंदर',
'no_recipes_under_time': 'मिनट के अंदर कोई रेसिपी नहीं मिली',
'recipe_categories': 'रेसिपी श्रेणियां',
'curry_dishes': 'करी व्यंजन',
'rice_dishes': 'चावल व्यंजन',
'egg_dishes': 'अंडे के व्यंजन',
'please_enter_valid_time': 'कृपया वैध समय दर्ज करें!',
'convert_to': 'में बदलें',
'language_options': ['English', 'Telugu', 'Tamil'],
'generated_image': 'AI द्वारा बनाई गई रेसिपी तस्वीर',
'video_tutorials': 'सुझाए गए वीडियो ट्यूटोरियल',
'image_generation_failed': 'छवि बनाने में विफल',
'api_key_missing': 'Bria API कुंजी कॉन्फ़िगर नहीं है',
'generating_image': 'AI छवि बना रहा है...',
'searching_videos': 'वीडियो ट्यूटोरियल खोज रहा है...',
'visual_guide': 'दृश्य गाइड और ट्यूटोरियल'
}
}
def process_recipe_data():
"""Process the CSV data to group ingredients by recipe"""
recipes = defaultdict(lambda: {
'english_name': '',
'telugu_name': '',
'cooking_time_english': '',
'cooking_time_telugu': '',
'ingredients_english': [],
'ingredients_telugu': []
})
for _, row in df.iterrows():
recipe_name = row['English Name']
recipes[recipe_name]['english_name'] = row['English Name']
recipes[recipe_name]['telugu_name'] = row['Telugu Name']
recipes[recipe_name]['cooking_time_english'] = row['Cooking Time (English)']
recipes[recipe_name]['cooking_time_telugu'] = row['Cooking Time (Telugu)']
recipes[recipe_name]['ingredients_english'].append(row['Ingredient (English)'])
recipes[recipe_name]['ingredients_telugu'].append(row['Ingredient (Telugu)'])
return dict(recipes)
# Process the data
recipes_data = process_recipe_data()
def get_translation(key, language='English'):
"""Get translation for a given key and language"""
return TRANSLATIONS.get(language, TRANSLATIONS['English']).get(key, key)
def generate_recipe_image(recipe_name, ingredients_list):
"""Generate realistic recipe image using Bria API"""
if not BRIA_API_KEY:
return None, "API key not configured"
try:
# Create detailed prompt for realistic food photography
main_ingredients = ", ".join(ingredients_list[:5]) # Use first 5 ingredients
prompt = f"""Professional food photography of {recipe_name}, beautifully plated authentic Indian Telugu cuisine,
featuring {main_ingredients}, vibrant colors, traditional serving dish,
restaurant quality presentation, natural lighting, appetizing appearance,
high resolution, detailed textures, garnished appropriately,
traditional Indian food styling, warm ambient lighting"""
headers = {
"Authorization": f"Bearer {BRIA_API_KEY}",
"Content-Type": "application/json"
}
data = {
"prompt": prompt,
"num_results": 1,
"width": 512,
"height": 512,
"style_type": "photography",
"enhancement": True
}
response = requests.post(BRIA_API_URL, headers=headers, json=data, timeout=30)
if response.status_code == 200:
result = response.json()
if 'results' in result and len(result['results']) > 0:
return result['results'][0]['url'], None
else:
return None, "No image generated"
else:
return None, f"API Error: {response.status_code}"
except requests.exceptions.Timeout:
return None, "Request timeout"
except Exception as e:
return None, f"Error: {str(e)}"
def generate_youtube_links(recipe_name, telugu_name=""):
"""Generate relevant YouTube tutorial links for the recipe"""
search_queries = []
# Create multiple search variations for better results
base_recipe = recipe_name.replace(" ", "+")
search_queries.append(f"{base_recipe}+recipe+telugu")
search_queries.append(f"{base_recipe}+cooking+tutorial")
search_queries.append(f"how+to+make+{base_recipe}")
if telugu_name:
telugu_encoded = urllib.parse.quote(telugu_name)
search_queries.append(f"{telugu_encoded}+recipe")
# Add specific cooking channel searches
popular_channels = [
"Hebbars+Kitchen", "Vahrehvah", "Cook+with+Comali",
"Telugu+Cooking", "Andhra+Recipes", "South+Indian+Recipes"
]
video_links = []
for i, query in enumerate(search_queries[:3]): # Limit to 3 main searches
youtube_url = f"https://www.youtube.com/results?search_query={query}"
# Create more specific search URLs
video_links.append({
"title": f"🎥 {recipe_name} - Recipe Tutorial",
"url": youtube_url,
"description": f"Complete cooking tutorial for {recipe_name}"
})
# Add channel-specific searches
for channel in popular_channels[:2]:
channel_search = f"https://www.youtube.com/results?search_query={base_recipe}+{channel}"
video_links.append({
"title": f"🍳 {recipe_name} by {channel.replace('+', ' ')}",
"url": channel_search,
"description": f"Professional cooking tutorial from {channel.replace('+', ' ')}"
})
# Add general cooking tips search
tips_search = f"https://www.youtube.com/results?search_query={base_recipe}+tips+tricks+secrets"
video_links.append({
"title": f"💡 {recipe_name} - Tips & Secrets",
"url": tips_search,
"description": f"Professional cooking tips and secrets for perfect {recipe_name}"
})
return video_links
def format_video_links(video_links, current_language="English"):
"""Format video links for display"""
if not video_links:
return f"**{get_translation('video_tutorials', current_language)}:** No tutorials found"
formatted_links = f"**🎬 {get_translation('video_tutorials', current_language)}:**\n\n"
for i, video in enumerate(video_links, 1):
formatted_links += f"**{i}. [{video['title']}]({video['url']})**\n"
formatted_links += f" *{video['description']}*\n\n"
# Add helpful note
if current_language == "English":
formatted_links += "💡 **Note:** Click on any link above to search for detailed video tutorials on YouTube.\n"
formatted_links += "🔍 **Tip:** Use Telugu keywords in YouTube search for more authentic regional recipes."
elif current_language == "Telugu":
formatted_links += "💡 **గమనిక:** వివరణాత్మక వీడియో ట్యుటోరియల్స్ కోసం యూట్యూబ్‌లో వెతకడానికి ఎగువన ఉన్న ఏదైనా లింక్‌ను క్లిక్ చేయండి.\n"
formatted_links += "🔍 **చిట్కా:** మరింత అసలైన ప్రాంతీయ వంటకాల కోసం యూట్యూబ్ వెతుకులలో తెలుగు పదాలను ఉపయోగించండి."
return formatted_links
def assess_recipe_complexity(recipe_name, ingredients_list, cooking_time):
"""Assess if recipe needs video explanation based on complexity"""
complexity_score = 0
# Check for complex ingredients
complex_ingredients = ['paste', 'marinade', 'tempering', 'tadka', 'masala', 'curry leaves', 'ghee']
for ingredient in ingredients_list:
if any(complex_word in ingredient.lower() for complex_word in complex_ingredients):
complexity_score += 1
# Check cooking time
time_str = cooking_time.lower()
if 'hour' in time_str or 'hours' in time_str:
complexity_score += 2
elif any(num in time_str for num in ['45', '50', '60']) and 'minute' in time_str:
complexity_score += 1
# Check for complex cooking methods
complex_methods = ['biryani', 'curry', 'fry', 'roast', 'pickle', 'chutney']
if any(method in recipe_name.lower() for method in complex_methods):
complexity_score += 1
return complexity_score >= 2 # Recommend videos if complexity score is 2 or higher
def search_recipe(recipe_name, current_language="English"):
"""Search for a recipe and return details with AI image and video links"""
if not recipe_name.strip():
return get_translation('please_enter_recipe', current_language), "", "", "", None, ""
found_recipe = None
for recipe_key, recipe_info in recipes_data.items():
if (recipe_name.lower() in recipe_info['english_name'].lower() or
recipe_name in recipe_info['telugu_name'] or
recipe_name.lower() in recipe_key.lower()):
found_recipe = recipe_info
break
if not found_recipe:
return f"❌ {get_translation('no_recipe_found', current_language)} '{recipe_name}'", "", "", "", None, ""
# Basic recipe information
title = f"🍳 {found_recipe['english_name']}"
if current_language != 'English' and found_recipe['telugu_name']:
title += f" ({found_recipe['telugu_name']})"
time_info = f"⏰ **{get_translation('cooking_time', current_language)}:** {found_recipe['cooking_time_english']}"
ingredients_list = f"📋 **{get_translation('ingredients', current_language)}:**\n"
for i, ingredient in enumerate(found_recipe['ingredients_english'], 1):
ingredients_list += f"{i}. {ingredient}\n"
# Bilingual ingredients
bilingual_ingredients = f"📋 **{get_translation('ingredients', current_language)} (English + తెలుగు):**\n\n"
for i, (eng, tel) in enumerate(zip(found_recipe['ingredients_english'], found_recipe['ingredients_telugu']), 1):
bilingual_ingredients += f"{i}. **English:** {eng}\n **తెలుగు:** {tel}\n\n"
# Generate AI image
image_url = None
image_status = get_translation('generating_image', current_language)
try:
if BRIA_API_KEY:
image_url, error = generate_recipe_image(found_recipe['english_name'], found_recipe['ingredients_english'])
if error:
image_status = f"❌ {get_translation('image_generation_failed', current_language)}: {error}"
else:
image_status = f"✅ {get_translation('generated_image', current_language)}"
else:
image_status = f"⚠️ {get_translation('api_key_missing', current_language)}"
except Exception as e:
image_status = f"❌ {get_translation('image_generation_failed', current_language)}: {str(e)}"
# Generate YouTube video links
video_links = generate_youtube_links(found_recipe['english_name'], found_recipe['telugu_name'])
formatted_videos = format_video_links(video_links, current_language)
# Add complexity assessment
needs_video = assess_recipe_complexity(
found_recipe['english_name'],
found_recipe['ingredients_english'],
found_recipe['cooking_time_english']
)
if needs_video:
if current_language == "English":
formatted_videos = "🎯 **This recipe involves complex techniques - Video tutorials highly recommended!**\n\n" + formatted_videos
elif current_language == "Telugu":
formatted_videos = "🎯 **ఈ వంటకంలో సంక్లిష్ట పద్ధతులు ఉన్నాయి - వీడియో ట్యుటోరియల్స్ బాగా సిఫార్సు చేయబడుతున్నాయి!**\n\n" + formatted_videos
# Combine image status with video links
visual_content = f"## 🎬 {get_translation('visual_guide', current_language)}\n\n"
visual_content += f"**📸 {image_status}**\n\n"
visual_content += formatted_videos
return title, time_info, ingredients_list, bilingual_ingredients, image_url, visual_content
def get_all_recipes(current_language="English"):
"""Get all recipes list in the specified language"""
recipes_list = f"📚 **{get_translation('available_recipes', current_language)}:**\n\n"
for i, (recipe_key, recipe_info) in enumerate(recipes_data.items(), 1):
if current_language == 'English':
recipes_list += f"{i}. **{recipe_info['english_name']}**\n"
else:
recipes_list += f"{i}. **{recipe_info['english_name']}** | **{recipe_info['telugu_name']}**\n"
return recipes_list
def filter_by_time(max_time, current_language="English"):
"""Filter recipes by cooking time"""
if max_time <= 0:
return get_translation('please_enter_valid_time', current_language)
quick_recipes = []
for recipe_key, recipe_info in recipes_data.items():
time_str = recipe_info['cooking_time_english'].lower()
if 'hour' in time_str:
if '1 hour 15' in time_str:
total_minutes = 75
elif '1 hour' in time_str:
total_minutes = 60
else:
total_minutes = 60
else:
import re
minutes = re.findall(r'(\d+)', time_str)
total_minutes = int(minutes[0]) if minutes else 60
if total_minutes <= max_time:
quick_recipes.append((recipe_info['english_name'], recipe_info['telugu_name']))
if not quick_recipes:
return f"❌ {get_translation('no_recipes_under_time', current_language)} {max_time} {get_translation('minutes', current_language)}"
result = f"⚡ **{get_translation('recipes_under_time', current_language)} {max_time} {get_translation('minutes', current_language)}:**\n\n"
for i, (eng_name, tel_name) in enumerate(quick_recipes, 1):
if current_language == 'English':
result += f"{i}. **{eng_name}**\n"
else:
result += f"{i}. **{eng_name}** | **{tel_name}**\n"
return result
def get_recipe_by_category(current_language="English"):
"""Get recipes organized by category"""
categories = {
get_translation('curry_dishes', current_language): [],
get_translation('rice_dishes', current_language): [],
get_translation('egg_dishes', current_language): []
}
for recipe_key, recipe_info in recipes_data.items():
name_lower = recipe_info['english_name'].lower()
if 'curry' in name_lower:
categories[get_translation('curry_dishes', current_language)].append((recipe_info['english_name'], recipe_info['telugu_name']))
elif 'biryani' in name_lower:
categories[get_translation('rice_dishes', current_language)].append((recipe_info['english_name'], recipe_info['telugu_name']))
elif 'egg' in name_lower or 'omelette' in name_lower:
categories[get_translation('egg_dishes', current_language)].append((recipe_info['english_name'], recipe_info['telugu_name']))
result = f"🍽️ **{get_translation('recipe_categories', current_language)}:**\n\n"
for category, recipes in categories.items():
if recipes:
result += f"**{category}:**\n"
for i, (eng_name, tel_name) in enumerate(recipes, 1):
if current_language == 'English':
result += f" {i}. {eng_name}\n"
else:
result += f" {i}. {eng_name} | {tel_name}\n"
result += "\n"
return result
def change_language(new_language, current_search, current_time):
"""Change the interface language and update all content"""
new_translations = TRANSLATIONS[new_language]
# Update search results if there's current search
search_title = ""
search_time = ""
search_ingredients = ""
search_bilingual = ""
search_image =