macflorek

project.py

Sep 12th, 2023
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.79 KB | None | 0 0
  1. import requests,sys,json
  2.  
  3. def get_leftover_ingredient():
  4.     while True:
  5.         ingredient=input("List ingredient you want to use-up and its amount separated by comma, with unit of measure at the end,separated by comma\nThe following units are accepted: piece,oz,lb,g,kg,cup,teaspoon,tablespoon,ml,l\nIngredient:").strip().split(",")
  6.         if len(ingredient)==3:
  7.             if check_ingredient_validity(ingredient[0])>0:
  8.                 if check_uom(ingredient[2])==True:
  9.                     return ingredient
  10.                     break
  11.  
  12.  
  13. def check_ingredient_validity(ingredient):
  14.     try:
  15.         r = requests.get('https://api.spoonacular.com/food/ingredients/search?apiKey=f017f95bd138484ea337209a60528299&query='+ingredient)
  16.         if next(iter(r.json().values()))!="failure":
  17.             if r.json()["totalResults"]==0:
  18.                 return False
  19.             else:
  20.                 id=(r.json()["results"][0]["id"])
  21.                 return id
  22.         else:
  23.             sys.exit("Access point limit exceeded. Aborting program. Try again later")
  24.     except requests.RequestException:
  25.         sys.exit("Connection to spoonacular.com error. Try again later")
  26.  
  27. def check_uom(uom):
  28.     if uom.strip().lower() not in ["piece","oz","lb","g","kg","cup","teaspoon","tablespoon","ml","l"]:
  29.         return False
  30.     else:
  31.         return True
  32.  
  33. def get_recipes_from_file(ingredient):
  34.     with open(r'recipes.json') as rec:
  35.         recipes = json.load(rec)
  36.         where_used=[recipe["Name"] for recipe in recipes if ingredient in recipe["Ingredients"]]
  37.         return where_used
  38.  
  39. def get_sugar_per_item(name,qty,uom):
  40.     try:
  41.         id=check_ingredient_validity(name)
  42.         if id=="Point limit exceeded":
  43.             sys.exit("Daily connection limit to spoonacular server exceeded. Aborting program. Try again later.")
  44.         else:
  45.             data = requests.get('https://api.spoonacular.com/food/ingredients/'+str(id)+'/information?apiKey=f017f95bd138484ea337209a60528299&amount='+qty+'&unit='+uom)
  46.             json_data=data.json()
  47.             amount = [nutrient['amount'] for nutrient in json_data["nutrition"]["nutrients"] if nutrient["name"] == "Sugar"]
  48.             return amount
  49.     except requests.RequestException:
  50.         sys.exit("Connection to spoonacular server error. Aborting program. Try again later.")
  51.  
  52. def get_sugar_per_recipe(recipe_name):
  53.     with open(r'recipes.json') as rec:
  54.         recipes = json.load(rec)
  55.         sugar_amount_matrix = [get_sugar_per_item(item,recipe["Ingredients"][item][0],recipe["Ingredients"][item][1]) for recipe in recipes for item in recipe['Ingredients'].keys() if recipe["Name"]==recipe_name]
  56.         sugar_amount_value=sum(y for x in sugar_amount_matrix for y in x)
  57.         return sugar_amount_value
  58.  
  59. def get_ingredient_balance_for_recipe(ingr,recipe):
  60.     with open(r'recipes.json') as rec:
  61.         recipes = json.load(rec)
  62.         for item in recipes:
  63.             for ingredient in item["Ingredients"].keys():
  64.                 if ingredient==ingr[0] and item["Name"]==recipe:
  65.                     if ingr[2]==item["Ingredients"][ingredient][1]:
  66.                         balance=[ingr[1]-item["Ingredients"][ingredient][0],"same uom",item["Ingredients"][ingredient][2]]
  67.                     else:
  68.                         balance=[item["Ingredients"][ingredient][0],"different uom",item["Ingredients"][ingredient][1]]
  69.     return balance
  70.  
  71. def print_recipe(recipe):
  72.     with open(r'recipes.json') as rec:
  73.         recipes = json.load(rec)
  74.         print("Recipe name:",recipe)
  75.         print("\nGrams of sugar in the recipe:",get_sugar_per_recipe(recipe),"\n\nIngredients:")
  76.         for item in recipes:
  77.             if item["Name"]==recipe:
  78.                 for ingredient in item["Ingredients"].keys():
  79.                     print("     ",ingredient,item["Ingredients"][ingredient][0],item["Ingredients"][ingredient][1])
  80.  
  81. def main():
  82.     ingredient=get_leftover_ingredient()
  83.     recipes=get_recipes_from_file(ingredient[0])
  84.     ingredient_balance= [get_ingredient_balance_for_recipe(ingredient,recipe) for recipe in recipes]
  85.     print("The ingredient is used in the following recipes:")
  86.     for recipe in recipes:
  87.         print(recipe)
  88.         balance=get_ingredient_balance_for_recipe(ingredient,recipe)
  89.         if balance[1]=="same uom":
  90.             if balance[0]>0:
  91.                 print("You'll have",balance[0],"of",ingredient[0],"left after preparing",recipe)
  92.             elif balance[1]<0:
  93.                 print("You'll need additional",-int[balance[1]],"of",ingredient[0],"for preparing",recipe)
  94.             else:
  95.                 print("You have exactly the needed amount of",ingredient[0],"for preparing",recipe)
  96.         else:
  97.             print("You have",ingredient[1],ingredient[2],"of",ingredient[0],"while",balance[0],balance[2],"is needed\n" )
  98.  
  99. main()
Advertisement
Add Comment
Please, Sign In to add comment