import os import gradio as gr import requests # Get API keys from Secrets spoonacular_api_key = os.getenv('SPOONACULAR_API_KEY') # Spoonacular API key hf_api_key = os.getenv('HF_API_KEY') # Hugging Face API key # Translation function using Hugging Face def translate_text_hf(text): url = "https://api-inference.huggingface.co/models/Helsinki-NLP/opus-mt-et-en" headers = {"Authorization": f"Bearer {hf_api_key}"} payload = {"inputs": text} response = requests.post(url, headers=headers, json=payload) if response.status_code == 200: translation = response.json()[0]['translation_text'] print("Translated ingredients:", translation) # Debug: Print translation return translation else: print("Translation failed with status:", response.status_code) # Debug: Print failure return "Translation failed!" # Recipe search function using Spoonacular API def get_recipes(ingredients, max_calories=None, min_protein=None, max_fat=None, max_carbs=None): # Translate ingredients to English translated_ingredients = translate_text_hf(ingredients) url = "https://api.spoonacular.com/recipes/complexSearch" # Base parameters for the API request params = { "query": translated_ingredients, "apiKey": spoonacular_api_key, "number": 5 # Return up to 5 recipes } # Add optional parameters only if they are provided and not zero if max_calories and max_calories > 0: params["maxCalories"] = max_calories if min_protein and min_protein > 0: params["minProtein"] = min_protein if max_fat and max_fat > 0: params["maxFat"] = max_fat if max_carbs and max_carbs > 0: params["maxCarbs"] = max_carbs # Send the API request response = requests.get(url, params=params) # Check if the request was successful if response.status_code == 200: recipes = response.json().get('results', []) if recipes: # Format and return the list of recipes as HTML links html_links = "
".join( [f'{recipe["title"]}' for recipe in recipes] ) # Debug: Print each generated URL for the recipes for recipe in recipes: print(f"Generated URL: https://spoonacular.com/recipes/{recipe['title'].replace(' ', '-').lower()}-{recipe['id']}") return html_links else: return "No suitable recipes found." else: return f"Error fetching recipes: {response.status_code}" # Gradio Interface def recipe_app(ingredients, max_calories, min_protein, max_fat, max_carbs): return get_recipes(ingredients, max_calories, min_protein, max_fat, max_carbs) # Create Gradio interface interface = gr.Interface( fn=recipe_app, inputs=[ gr.Textbox(label="Sisesta koostisained"), gr.Number(label="Maksimaalne kalorikogus (valikuline)"), gr.Number(label="Minimaalne valk (g, valikuline)"), gr.Number(label="Maksimaalne rasvasisaldus (g, valikuline)"), gr.Number(label="Maksimaalne süsivesikute sisaldus (g, valikuline)"), ], outputs=gr.HTML(label="Recipes"), # Ensure output is HTML title="Retseptiotsija", description="Sisestage koostisosad eesti keeles ja määrake sobivate retseptide leidmiseks valikulised kalorite, valkude, rasvade ja süsivesikute piirangud." ) interface.launch()