from pathlib import Path import json working_directory = Path(__file__).parent try: with open(str(working_directory / "settings.json"), "rt") as settings_file: settings = json.load(settings_file) checklist_file_path = settings.get("checklist_storage_path", str(working_directory / "json")) + "/checklists.json" ingredients_file_path = settings.get("meal_storage_path", str(working_directory / "json")) + "/ingredients.json" except Exception as e: print(e) with open(str(working_directory / "settings.json"), "w") as settings_file: settings = { "meal_storage_path": str(working_directory / "json"), "checklist_storage_path": str(working_directory / "json") } json.dump(settings, settings_file, indent=4) checklist_file_path = settings["checklist_storage_path"] + "/checklists.json" ingredients_file_path = settings["meal_storage_path"] + "/ingredients.json" def read_ingredient_json() -> dict: try: with open(ingredients_file_path, "rt") as file: return json.load(file) except: print("Could not find or read ingredients file.") return {} def read_json_file(filename: str) -> dict: try: with open(filename, "rt") as file: return json.load(file) except: print(f"Could not find or read file.\n{filename=}") return {} def update_json(meals: dict) -> None: try: with open(ingredients_file_path, "w") as file: json.dump(meals, file, indent=4) except Exception as e: print(f"Unable to write data to file. {e}") def update_file(filename: str, content: dict) -> None: try: with open(filename, "w") as file: json.dump(content, file, indent=4) except Exception as e: print(f"Unable to write data to file. {e}") def get_selected_meals(meals: dict) -> dict: meal_json = read_ingredient_json() selected_meals = {} if meal_json: for meal in meals: if meal in meal_json: selected_meals[meal] = meal_json[meal] return selected_meals def combine_ingredients(meals: dict) -> dict: combined_ingredients = {} for meal, ingredients in meals.items(): for ingredient, detail in ingredients.items(): if ingredient in combined_ingredients: combined_ingredients[ingredient]['quantity'] = str(float(combined_ingredients[ingredient]['quantity']) + float(detail['quantity'])) else: combined_ingredients[ingredient] = detail return combined_ingredients def write_checklist(data: dict) -> None: try: with open(checklist_file_path, 'w') as checklist: for ingredient, details in data.items(): s = ingredient + " - " + str(details['quantity']) if details['units'] != None: s += " " + details['units'] checklist.write(f"- [ ] {s}\n") except Exception as e: print(f"Unable to write data to file. {e}") if __name__ == "__main__": meals = read_ingredient_json() if meals: combined_ingredients = combine_ingredients(meals) write_checklist(combined_ingredients)