Files
journal/common.py

107 lines
2.8 KiB
Python

from pathlib import Path
from datetime import datetime
def parse_timestamp(timestamp):
return datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
def format_timestamp(timestamp):
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
def parse_foods_file():
path = Path.home() / 'projects' / 'open-journal' / 'foods'
text = path.read_text()
foods, recipes_str = text.split('---')
def parse_macro(macro):
if macro == '...':
return ('INVALID', 0.0)
name, value = macro.split()
value = float(value.removesuffix('g').removesuffix('kcal'))
return (name, value)
foods = {
macros[0]: dict(parse_macro(macro) for macro in macros[1:])
for macros in [food.split('\n') for food in foods.strip().split('\n\n')]
}
def combine_values(fst, snd):
result = fst.copy()
for k,v in snd.items():
if k in fst:
result[k] += v
else:
result[k] = v
return result
recipes = {}
def evaluate_ingredients(ingredients):
result = {}
total_weight = 0.0
for ingredient in ingredients:
k,v = parse_macro(ingredient)
if k == 'TOTAL':
result[k] = v
continue
else:
total_weight += v
food = foods.get(k)
total = 100.0
if not food:
food = recipes[k].copy()
total = food['TOTAL']
del food['TOTAL']
for kk,vv in food.items():
if kk not in result:
result[kk] = 0.0
result[kk] += vv * (v/total)
if 'TOTAL' not in result:
result['TOTAL'] = total_weight
return result
for ingredients in [recipe.split('\n') for recipe in recipes_str.strip().split('\n\n')]:
recipes[ingredients[0]] = evaluate_ingredients(ingredients[1:])
def get_calories_from_macros(mm):
calories = 0.0
for k,v in mm.items():
calories += v * {
'Carbs': 4,
'Fat': 9,
'Protein': 4
}.get(k, 0.0)
return calories
#for k,v in foods.items():
# print(round(v.get('Energy') - get_calories_from_macros(v)), k)
return foods, recipes
def evaluate_food_entry(foods, recipes, value, name):
if name in recipes:
food = recipes[name]
if value == 0.0:
value = food['TOTAL']
food = {k: v*(value/food['TOTAL']) for k,v in food.items()}
elif name in foods:
if value == 0.0:
value = 100
food = {k: v*(value/100.0) for k,v in foods[name].items()}
else:
breakpoint()
print(f'ERROR: Invalid diet entry: {content}')
return food