feat: Update placeholder metadata and nutrition metrics
Deploy Development / deploy (push) Successful in 54s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 15s

- Adjusted the total number of placeholders from 116 to 114 across various documentation and code files to reflect the current state of the system.
- Enhanced TDEE calculation logic in `nutrition_metrics.py` to prioritize Mifflin–St Jeor BMR with PAL when demographic data is available, with a fallback to a weight-based estimate.
- Updated placeholder registrations to ensure consistency with the new metadata structure and improved data handling.
- Revised documentation to clarify the authoritative source of placeholder metadata and the implications of the changes on existing functionalities.

These updates improve the accuracy and consistency of the placeholder system and enhance the nutritional assessment capabilities within the application.
This commit is contained in:
Lars committed 2026-04-11 21:11:05 +02:00
1 parent 2ea5f905c4
commit 052ba195cc
11 files changed
+159 -77

No files matched your search

+111 -25
View File
@@ -25,14 +25,43 @@ from datetime import datetime, timedelta, date
from db import get_db, get_cursor, r2d
from data_layer.utils import calculate_confidence, safe_float, safe_int
# Single TDEE rule for placeholders, charts, and warnings (kcal/day = kg * factor).
# Replaces legacy fixed 2500 kcal so all consumers stay aligned.
# Fallback TDEE (kcal/day) when demographics for Mifflin–St Jeor are incomplete.
TDEE_KCAL_PER_KG_BODYWEIGHT = 32.5
# PAL applied to MSJ BMR when height, sex, dob and weight are available (moderate activity).
TDEE_PAL_MODERATE = 1.55
def _age_years_from_dob(dob) -> Optional[int]:
if dob is None:
return None
try:
if isinstance(dob, str):
birth = datetime.strptime(dob[:10], "%Y-%m-%d").date()
else:
birth = dob
today = date.today()
return today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
except Exception:
return None
def _mifflin_st_jeor_bmr_kcal(
weight_kg: float, height_cm: float, age_years: int, sex_is_male: bool
) -> float:
if sex_is_male:
return 10.0 * weight_kg + 6.25 * height_cm - 5.0 * age_years + 5.0
return 10.0 * weight_kg + 6.25 * height_cm - 5.0 * age_years - 161.0
def estimate_tdee_kcal_from_latest_weight(profile_id: str) -> Optional[float]:
"""
Estimated TDEE (kcal/day) from latest body weight.
Estimated TDEE (kcal/day).
Primary: Mifflin–St Jeor BMR × TDEE_PAL_MODERATE when latest weight plus
profiles.height, profiles.sex, profiles.dob are usable.
Fallback: latest weight (kg) × TDEE_KCAL_PER_KG_BODYWEIGHT (legacy heuristic).
Returns None if no weight on record.
"""
with get_db() as conn:
@@ -42,10 +71,41 @@ def estimate_tdee_kcal_from_latest_weight(profile_id: str) -> Optional[float]:
WHERE profile_id=%s ORDER BY date DESC LIMIT 1""",
(profile_id,),
)
row = cur.fetchone()
if not row or row["weight"] is None:
wrow = cur.fetchone()
if not wrow or wrow["weight"] is None:
return None
return float(row["weight"]) * TDEE_KCAL_PER_KG_BODYWEIGHT
weight_kg = float(wrow["weight"])
cur.execute(
"SELECT height, sex, dob FROM profiles WHERE id=%s",
(profile_id,),
)
prow = cur.fetchone()
if prow and prow.get("height") and prow.get("sex") is not None and prow.get("dob"):
height_cm = float(prow["height"])
age = _age_years_from_dob(prow["dob"])
if age is not None and 10 < age < 120 and height_cm > 50:
sex_raw = str(prow["sex"]).strip().lower()
sex_is_male = sex_raw in ("m", "male", "männlich", "mann")
bmr = _mifflin_st_jeor_bmr_kcal(weight_kg, height_cm, age, sex_is_male)
if bmr > 400:
return bmr * TDEE_PAL_MODERATE
return weight_kg * TDEE_KCAL_PER_KG_BODYWEIGHT
def _get_profile_goal_mode(profile_id: str) -> str:
"""Strategic goal_mode from profiles (Phase 0a); defaults to health."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT goal_mode FROM profiles WHERE id=%s", (profile_id,))
row = cur.fetchone()
if row and row.get("goal_mode"):
g = str(row["goal_mode"]).strip().lower()
if g:
return g
return "health"
def get_nutrition_average_data(
@@ -224,7 +284,7 @@ def get_energy_balance_data(
Energy balance (intake - estimated expenditure), kcal/day.
Intake: mean of daily total kcal (sum per calendar day).
TDEE: latest weight (kg) * TDEE_KCAL_PER_KG_BODYWEIGHT (same rule as placeholders).
TDEE: estimate_tdee_kcal_from_latest_weight (MSJ × PAL oder kg-Fallback).
"""
with get_db() as conn:
cur = get_cursor(conn)
@@ -834,32 +894,58 @@ def calculate_nutrition_score(profile_id: str, focus_weights: Optional[Dict] = N
def _score_calorie_adherence(profile_id: str) -> Optional[int]:
"""Score calorie target adherence (0-100)"""
# Check for energy balance goal
# For now, use energy balance calculation
"""Score calorie target adherence (0–100) using 7d balance vs profiles.goal_mode."""
balance = calculate_energy_balance_7d(profile_id)
if balance is None:
return None
# Score based on whether deficit/surplus aligns with goal
# Simplified: assume weight loss goal = deficit is good
# TODO: Check actual goal type
mode = _get_profile_goal_mode(profile_id)
b = float(balance)
abs_balance = abs(balance)
def _weight_loss(x: float) -> int:
if -550 <= x <= -250:
return 100
if x > 450:
return 38
if -750 <= x < -550 or -250 < x <= 120:
return 82
if x < -1200:
return 52
if -950 <= x < -750 or 120 < x <= 350:
return 68
return 58
# Moderate deficit/surplus = good
if 200 <= abs_balance <= 500:
return 100
elif 100 <= abs_balance <= 700:
return 85
elif abs_balance <= 900:
return 70
elif abs_balance <= 1200:
return 55
else:
def _surplus_friendly(x: float) -> int:
if 80 <= x <= 480:
return 100
if -120 <= x < 80 or 480 < x <= 700:
return 86
if -380 <= x < -120:
return 68
if x > 850:
return 54
if x < -650:
return 44
return 72
def _maintenance(x: float) -> int:
a = abs(x)
if a <= 200:
return 100
if a <= 400:
return 84
if a <= 650:
return 70
if a <= 900:
return 55
return 40
if mode == "weight_loss":
return _weight_loss(b)
if mode in ("strength", "recomposition"):
return _surplus_friendly(b)
return _maintenance(b)
def _score_macro_balance(profile_id: str) -> Optional[int]:
"""Score macro balance (0-100)"""