Advertisement
pascallius

Untitled

Apr 9th, 2024
443
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.34 KB | None | 0 0
  1. import streamlit as st
  2. import requests
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5.  
  6. st.set_option('deprecation.showPyplotGlobalUse', False)
  7.  
  8. EDAMAM_APP_ID = 'b43bfd1e'
  9. EDAMAM_APP_KEY = '52c88b2f791a5ddecbecf76a970d8a13'
  10.  
  11. def get_recipe(food, calories):
  12.     url = f"https://api.edamam.com/search?q={food}&app_id={EDAMAM_APP_ID}&app_key={EDAMAM_APP_KEY}&calories=0-{calories}"
  13.     response = requests.get(url)
  14.     data = response.json()
  15.     return data['hits'][0]['recipe'] if data['hits'] else None
  16.  
  17. def plot_nutrition(recipe):
  18.     nutrients = recipe['totalNutrients']
  19.     nutrients_names = [nutrient['label'] for nutrient in nutrients.values()]
  20.     nutrients_values = [nutrient['quantity'] for nutrient in nutrients.values()]
  21.  
  22.     colors = ['#FFA07A', '#20B2AA']
  23.  
  24.     fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
  25.     plt.style.use('ggplot')
  26.  
  27.     y_pos = np.arange(len(nutrients_names))
  28.     bars = ax1.barh(y_pos, nutrients_values, align='center', color=colors[0])
  29.     ax1.set_yticks(y_pos)
  30.  
  31.     ax1.set_yticklabels(nutrients_names, fontweight='bold', fontsize=12, family='Arial', color='white')
  32.     ax1.set_xlabel('Quantity')
  33.     ax1.set_title('Nutrition Values', fontweight='bold', fontsize=16, color='white')
  34.     ax1.invert_yaxis()
  35.     ax1.spines['top'].set_visible(False)
  36.     ax1.spines['right'].set_visible(False)
  37.     ax1.spines['bottom'].set_visible(False)
  38.  
  39.     ax1.xaxis.set_tick_params(pad=20)
  40.  
  41.     for bar in bars:
  42.         width = bar.get_width()
  43.         ax1.text(width, bar.get_y() + bar.get_height() / 2, f'{width:.1f}', va='center', color='white',
  44.                  fontweight='bold', fontsize=12, family='Arial')
  45.  
  46.     ax1.tick_params(axis='y', which='major', pad=10)
  47.  
  48.     balance_score = np.mean(nutrients_values) / np.sum(nutrients_values)
  49.     labels = ['Balance', 'Total']
  50.     sizes = [balance_score, 1 - balance_score]
  51.     explode = (0.1, 0)
  52.     ax2.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',
  53.             shadow=True, startangle=90)
  54.     ax2.axis('equal')
  55.     ax2.set_title('Meal Balance', fontweight='bold', fontsize=16, color='white')
  56.  
  57.     plt.tight_layout()
  58.     st.pyplot(fig)
  59.  
  60. def main():
  61.     st.title("Welcome to DailyCalories!")
  62.     st.markdown(
  63.         """
  64.        <style>
  65.            body {
  66.                background-color: #f0f0f0;
  67.                color: #333333;
  68.                font-family: Arial, sans-serif;
  69.                line-height: 1.6;
  70.            }
  71.            .container {
  72.                max-width: 800px;
  73.                margin: 0 auto;
  74.                padding: 20px;
  75.            }
  76.            .header {
  77.                background-color: #007bff;
  78.                color: white;
  79.                padding: 20px;
  80.                border-radius: 5px;
  81.            }
  82.            .subheader {
  83.                font-size: 20px;
  84.                font-weight: bold;
  85.                margin-bottom: 20px;
  86.            }
  87.            .input {
  88.                margin-bottom: 20px;
  89.            }
  90.            .button {
  91.                background-color: #007bff;
  92.                color: white;
  93.                border: none;
  94.                padding: 10px 20px;
  95.                border-radius: 5px;
  96.                cursor: pointer;
  97.                font-size: 16px;
  98.            }
  99.            .button:hover {
  100.                background-color: #0056b3;
  101.            }
  102.            .image {
  103.                max-width: 100%;
  104.                margin-bottom: 20px;
  105.                border-radius: 5px;
  106.            }
  107.        </style>
  108.        """,
  109.         unsafe_allow_html=True
  110.     )
  111.  
  112.     st.write("""Irgend en wilkommens text hald""")
  113.  
  114.     food_type = st.text_input("Enter a Food Type:", "Chicken")
  115.     max_calories = st.number_input("Enter Maximum Calories:", min_value=0, step=100, value=500)
  116.  
  117.     if st.button("Find Recipe", key='find_recipe_button'):
  118.         recipe = get_recipe(food_type, max_calories)
  119.         if recipe:
  120.             st.subheader(recipe['label'])
  121.             st.markdown(f'<img src="{recipe["image"]}" class="image">', unsafe_allow_html=True)
  122.             st.subheader("Ingredients:")
  123.             for ingredient in recipe['ingredientLines']:
  124.                 st.write(ingredient)
  125.  
  126.             plot_nutrition(recipe)
  127.         else:
  128.             st.error("No recipe found. Please try different criteria.")
  129.  
  130. if __name__ == '__main__':
  131.     main()
  132.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement