File size: 4,331 Bytes
763d0a5
 
1cf44ab
 
 
 
763d0a5
 
d9c142b
 
 
763d0a5
 
 
 
 
 
 
 
 
 
 
611b765
763d0a5
d9c142b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763d0a5
 
 
 
 
b467447
763d0a5
 
 
d9c142b
763d0a5
 
 
 
 
 
 
 
 
 
 
 
 
 
d9c142b
763d0a5
 
d9c142b
611b765
 
763d0a5
 
 
 
 
d9c142b
763d0a5
 
 
 
 
 
 
b467447
763d0a5
 
b467447
763d0a5
 
b467447
763d0a5
 
d9c142b
 
 
 
763d0a5
 
b467447
763d0a5
611b765
763d0a5
 
b467447
763d0a5
 
 
 
 
b467447
763d0a5
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
import streamlit as st
import requests
import os

spoonacular_api_key = os.getenv('SP_KEY')  # Spoonacular API key
hf_api_key = os.getenv('HF_KEY')  # Hugging Face API key

# Translation function
def translate_from_estonian(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()
        return translation[0]['translation_text']
    else:
        print(f"Error: {response.status_code} - {response.text}")
        return None

# Function to get recipes from Spoonacular API
def get_recipes(ingredients, calorie_limit, protein_limit, fat_limit):
    # Construct the API URL
    translated_ingredients = translate_from_estonian(ingredients)
    url = "https://api.spoonacular.com/recipes/complexSearch"

    params = {
        "query": translated_ingredients,
        "apiKey": spoonacular_api_key,
        "number": 10  # Return up to 10 recipes
    }

    if calorie_limit and calorie_limit > 0:
        params["maxCalories"] = calorie_limit
    if protein_limit and protein_limit > 0:
        params["minProtein"] = protein_limit
    if fat_limit and fat_limit > 0:
        params["maxFat"] = fat_limit
            
    # Make the API request
    response = requests.get(url)
    
    # Check if the request was successful
    if response.status_code != 200:
        st.error("Ebaõnnestumine. Proovi uuesti!")
        return []
    
    # Parse the JSON response
    recipes = response.json().get('results', [])
    
    # Filter recipes based on nutritional information
    filtered_recipes = []
    for recipe in recipes:
        recipe_id = recipe['id']
        
        # Fetch detailed information for each recipe
        detail_url = f"https://api.spoonacular.com/recipes/{recipe_id}/information?apiKey={api_key_spoonacular}"
        detail_response = requests.get(detail_url)
        
        if detail_response.status_code == 200:
            recipe_detail = detail_response.json()
            calories = recipe_detail['nutrition']['nutrients'][0]['amount']  # Get calories
            protein = recipe_detail['nutrition']['nutrients'][1]['amount']   # Get protein
            fat = recipe_detail['nutrition']['nutrients'][1]['amount']   # Get fat
            
            # Check if it meets the nutritional criteria
            if calories <= calorie_limit and protein >= protein_limit and fat<=fat_limit:
                translated_title = translate_to_estonian(recipe_detail['title'])
                translated_instructions = translate_to_estonian(recipe_detail['instructions'])
                
                filtered_recipes.append({
                    'name': translated_title if translated_title else recipe_detail['title'],
                    'calories': calories,
                    'protein': protein,
                    'fat':fat,
                    'instructions': translated_instructions if translated_instructions else recipe_detail['instructions'],
                    'image': recipe_detail['image']
                })

    return filtered_recipes

# Title of the app
st.title("Retseptide generaator")

# Input for ingredients
ingredients = st.text_input("Lisa koostisosad:")

# Slider for calorie limit
calorie_limit = st.slider("Vali maksmimaalne kaloraaž:", min_value=100, max_value=1000, value=500)

# Slider for minimum protein limit
protein_limit = st.slider("Vali minimaalne proteiini kogus (g):", min_value=0, max_value=100, value=10)

# Slider for maximum fat limit limit
fat_limit = st.slider("Vali maksimaalne rasva kogus (g):", min_value=0, max_value=500, value=50)

# Button to generate recipes
if st.button("Palun retseptisoovitust"):
    if ingredients:
        recipes = get_recipes(ingredients, calorie_limit, protein_limit, fat_limit)
        
        # Display the recipes
        st.subheader("Genereerime retsepte:")
        for recipe in recipes:
            st.write(f"**{recipe['name']}** - Calories: {recipe['calories']}, Protein: {recipe['protein']}g")
            st.image(recipe['image'])
            st.write(recipe['instructions'])
    else:
        st.error("Palun sisesta vähemalt üks koostisosa.")