feat: implement nutrition history visualization bundle and related API endpoint
- Added a new `nutrition_interpretation.py` file to handle KPI tile generation for nutrition history. - Introduced `nutrition_viz.py` to create a visualization bundle for nutrition data, integrating metrics and historical analysis. - Implemented `get_nutrition_history_viz` endpoint in `charts.py` to serve the new visualization data. - Updated frontend components to fetch and display nutrition history data, enhancing user experience with detailed insights. - Refactored existing logic to streamline data handling and improve overall performance.
This commit is contained in:
1 parent
a8eafa8ba4
commit
b96b1931db
6 files changed
+774
-292
No files matched your search
+24
-128
@@ -32,12 +32,14 @@ from data_layer.body_metrics import (
|
||||
get_circumference_summary_data
|
||||
)
|
||||
from data_layer.body_viz import get_body_history_viz_bundle
|
||||
from data_layer.nutrition_viz import get_nutrition_history_viz_bundle
|
||||
from data_layer.nutrition_metrics import (
|
||||
get_nutrition_average_data,
|
||||
get_protein_targets_data,
|
||||
get_protein_adequacy_data,
|
||||
get_macro_consistency_data,
|
||||
get_energy_balance_data,
|
||||
get_weekly_macro_distribution_chart_data,
|
||||
)
|
||||
from data_layer.activity_metrics import (
|
||||
get_activity_summary_data,
|
||||
@@ -265,6 +267,26 @@ def get_body_history_viz(
|
||||
return serialize_dates(bundle)
|
||||
|
||||
|
||||
@router.get("/nutrition-history-viz")
|
||||
def get_nutrition_history_viz(
|
||||
days: int = Query(
|
||||
default=90,
|
||||
ge=7,
|
||||
le=9999,
|
||||
description="Analysefenster in Tagen (9999 = gesamte Historie)",
|
||||
),
|
||||
session: dict = Depends(require_auth),
|
||||
) -> Dict:
|
||||
"""
|
||||
Layer 2b: Ein Bundle für Verlauf «Ernährung» — Kennzahlen, Reihen, TDEE-Referenz, Wochen-Chart.
|
||||
|
||||
Alle Kennzahlen aus nutrition_metrics (gleiche Logik wie Platzhalter / Chart-Endpunkte).
|
||||
"""
|
||||
profile_id = session["profile_id"]
|
||||
bundle = get_nutrition_history_viz_bundle(profile_id, days)
|
||||
return serialize_dates(bundle)
|
||||
|
||||
|
||||
@router.get("/circumferences")
|
||||
def get_circumferences_chart(
|
||||
max_age_days: int = Query(default=90, ge=7, le=365),
|
||||
@@ -830,136 +852,10 @@ def get_weekly_macro_distribution_chart(
|
||||
Weekly macro distribution (E3) - Konzept-konform.
|
||||
|
||||
100%-gestapelter Wochenbalken statt Pie Chart.
|
||||
Shows macro consistency across weeks, not just overall average.
|
||||
|
||||
Args:
|
||||
weeks: Number of weeks to analyze (4-52, default 12)
|
||||
session: Auth session (injected)
|
||||
|
||||
Returns:
|
||||
Chart.js stacked bar chart with weekly macro percentages
|
||||
Datenberechnung: data_layer.nutrition_metrics.get_weekly_macro_distribution_chart_data
|
||||
"""
|
||||
profile_id = session['profile_id']
|
||||
|
||||
from db import get_db, get_cursor
|
||||
import statistics
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(weeks=weeks)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT date, protein_g, carbs_g, fat_g, kcal
|
||||
FROM nutrition_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
AND protein_g IS NOT NULL AND carbs_g IS NOT NULL
|
||||
AND fat_g IS NOT NULL AND kcal > 0
|
||||
ORDER BY date""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
if not rows or len(rows) < 7:
|
||||
return {
|
||||
"chart_type": "bar",
|
||||
"data": {
|
||||
"labels": [],
|
||||
"datasets": []
|
||||
},
|
||||
"metadata": {
|
||||
"confidence": "insufficient",
|
||||
"data_points": len(rows) if rows else 0,
|
||||
"message": "Nicht genug Daten für Wochen-Analyse (min. 7 Tage)"
|
||||
}
|
||||
}
|
||||
|
||||
# Group by ISO week
|
||||
weekly_data = {}
|
||||
for row in rows:
|
||||
date_obj = row['date'] if isinstance(row['date'], datetime) else datetime.fromisoformat(str(row['date']))
|
||||
iso_week = date_obj.strftime('%Y-W%V')
|
||||
|
||||
if iso_week not in weekly_data:
|
||||
weekly_data[iso_week] = {
|
||||
'protein': [],
|
||||
'carbs': [],
|
||||
'fat': [],
|
||||
'kcal': []
|
||||
}
|
||||
|
||||
weekly_data[iso_week]['protein'].append(safe_float(row['protein_g']))
|
||||
weekly_data[iso_week]['carbs'].append(safe_float(row['carbs_g']))
|
||||
weekly_data[iso_week]['fat'].append(safe_float(row['fat_g']))
|
||||
weekly_data[iso_week]['kcal'].append(safe_float(row['kcal']))
|
||||
|
||||
# Calculate weekly averages and percentages
|
||||
labels = []
|
||||
protein_pcts = []
|
||||
carbs_pcts = []
|
||||
fat_pcts = []
|
||||
|
||||
for iso_week in sorted(weekly_data.keys())[-weeks:]:
|
||||
data = weekly_data[iso_week]
|
||||
|
||||
avg_protein = sum(data['protein']) / len(data['protein']) if data['protein'] else 0
|
||||
avg_carbs = sum(data['carbs']) / len(data['carbs']) if data['carbs'] else 0
|
||||
avg_fat = sum(data['fat']) / len(data['fat']) if data['fat'] else 0
|
||||
|
||||
# Convert to kcal
|
||||
protein_kcal = avg_protein * 4
|
||||
carbs_kcal = avg_carbs * 4
|
||||
fat_kcal = avg_fat * 9
|
||||
|
||||
total_kcal = protein_kcal + carbs_kcal + fat_kcal
|
||||
|
||||
if total_kcal > 0:
|
||||
labels.append(f"KW {iso_week[-2:]}")
|
||||
protein_pcts.append(round((protein_kcal / total_kcal) * 100, 1))
|
||||
carbs_pcts.append(round((carbs_kcal / total_kcal) * 100, 1))
|
||||
fat_pcts.append(round((fat_kcal / total_kcal) * 100, 1))
|
||||
|
||||
# Calculate variation coefficient (Variationskoeffizient)
|
||||
protein_cv = statistics.stdev(protein_pcts) / statistics.mean(protein_pcts) * 100 if len(protein_pcts) > 1 and statistics.mean(protein_pcts) > 0 else 0
|
||||
carbs_cv = statistics.stdev(carbs_pcts) / statistics.mean(carbs_pcts) * 100 if len(carbs_pcts) > 1 and statistics.mean(carbs_pcts) > 0 else 0
|
||||
fat_cv = statistics.stdev(fat_pcts) / statistics.mean(fat_pcts) * 100 if len(fat_pcts) > 1 and statistics.mean(fat_pcts) > 0 else 0
|
||||
|
||||
return {
|
||||
"chart_type": "bar",
|
||||
"data": {
|
||||
"labels": labels,
|
||||
"datasets": [
|
||||
{
|
||||
"label": "Protein (%)",
|
||||
"data": protein_pcts,
|
||||
"backgroundColor": "#1D9E75",
|
||||
"stack": "macro"
|
||||
},
|
||||
{
|
||||
"label": "Kohlenhydrate (%)",
|
||||
"data": carbs_pcts,
|
||||
"backgroundColor": "#F59E0B",
|
||||
"stack": "macro"
|
||||
},
|
||||
{
|
||||
"label": "Fett (%)",
|
||||
"data": fat_pcts,
|
||||
"backgroundColor": "#EF4444",
|
||||
"stack": "macro"
|
||||
}
|
||||
]
|
||||
},
|
||||
"metadata": {
|
||||
"confidence": calculate_confidence(len(rows), weeks * 7, "general"),
|
||||
"data_points": len(rows),
|
||||
"weeks_analyzed": len(labels),
|
||||
"avg_protein_pct": round(statistics.mean(protein_pcts), 1) if protein_pcts else 0,
|
||||
"avg_carbs_pct": round(statistics.mean(carbs_pcts), 1) if carbs_pcts else 0,
|
||||
"avg_fat_pct": round(statistics.mean(fat_pcts), 1) if fat_pcts else 0,
|
||||
"protein_cv": round(protein_cv, 1),
|
||||
"carbs_cv": round(carbs_cv, 1),
|
||||
"fat_cv": round(fat_cv, 1)
|
||||
}
|
||||
}
|
||||
return get_weekly_macro_distribution_chart_data(profile_id, weeks)
|
||||
|
||||
|
||||
@router.get("/nutrition-adherence-score")
|
||||
|
||||
Reference in new issue
Block a user