feat: Phase 0c - Multi-Layer Data Architecture (Proof of Concept)
- Add data_layer/ module structure with utils.py + body_metrics.py - Migrate 3 functions: weight_trend, body_composition, circumference_summary - Refactor placeholders to use data layer - Add charts router with 3 Chart.js endpoints - Tests: Syntax ✅, Confidence logic ✅ Phase 0c PoC (3 functions): Foundation for 40+ remaining functions Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
255d1d61c5
commit
c79cc9eafb
6 files changed
+959
-82
No files matched your search
@@ -3,12 +3,22 @@ Placeholder Resolver for AI Prompts
|
||||
|
||||
Provides a registry of placeholder functions that resolve to actual user data.
|
||||
Used for prompt templates and preview functionality.
|
||||
|
||||
Phase 0c: Refactored to use data_layer for structured data.
|
||||
This module now focuses on FORMATTING for AI consumption.
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Optional, Callable
|
||||
from db import get_db, get_cursor, r2d
|
||||
|
||||
# Phase 0c: Import data layer
|
||||
from data_layer.body_metrics import (
|
||||
get_weight_trend_data,
|
||||
get_body_composition_data,
|
||||
get_circumference_summary_data
|
||||
)
|
||||
|
||||
|
||||
# ── Helper Functions ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -33,45 +43,41 @@ def get_latest_weight(profile_id: str) -> Optional[str]:
|
||||
|
||||
|
||||
def get_weight_trend(profile_id: str, days: int = 28) -> str:
|
||||
"""Calculate weight trend description."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
cur.execute(
|
||||
"""SELECT weight, date FROM weight_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
ORDER BY date""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
"""
|
||||
Calculate weight trend description.
|
||||
|
||||
if len(rows) < 2:
|
||||
return "nicht genug Daten"
|
||||
Phase 0c: Refactored to use data_layer.body_metrics.get_weight_trend_data()
|
||||
This function now only FORMATS the data for AI consumption.
|
||||
"""
|
||||
data = get_weight_trend_data(profile_id, days)
|
||||
|
||||
first = rows[0]['weight']
|
||||
last = rows[-1]['weight']
|
||||
delta = last - first
|
||||
if data['confidence'] == 'insufficient':
|
||||
return "nicht genug Daten"
|
||||
|
||||
if abs(delta) < 0.3:
|
||||
return "stabil"
|
||||
elif delta > 0:
|
||||
return f"steigend (+{delta:.1f} kg in {days} Tagen)"
|
||||
else:
|
||||
return f"sinkend ({delta:.1f} kg in {days} Tagen)"
|
||||
direction = data['direction']
|
||||
delta = data['delta']
|
||||
|
||||
if direction == "stable":
|
||||
return "stabil"
|
||||
elif direction == "increasing":
|
||||
return f"steigend (+{delta:.1f} kg in {days} Tagen)"
|
||||
else: # decreasing
|
||||
return f"sinkend ({delta:.1f} kg in {days} Tagen)"
|
||||
|
||||
|
||||
def get_latest_bf(profile_id: str) -> Optional[str]:
|
||||
"""Get latest body fat percentage from caliper."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""SELECT body_fat_pct FROM caliper_log
|
||||
WHERE profile_id=%s AND body_fat_pct IS NOT NULL
|
||||
ORDER BY date DESC LIMIT 1""",
|
||||
(profile_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return f"{row['body_fat_pct']:.1f}%" if row else "nicht verfügbar"
|
||||
"""
|
||||
Get latest body fat percentage from caliper.
|
||||
|
||||
Phase 0c: Refactored to use data_layer.body_metrics.get_body_composition_data()
|
||||
This function now only FORMATS the data for AI consumption.
|
||||
"""
|
||||
data = get_body_composition_data(profile_id)
|
||||
|
||||
if data['confidence'] == 'insufficient':
|
||||
return "nicht verfügbar"
|
||||
|
||||
return f"{data['body_fat_pct']:.1f}%"
|
||||
|
||||
|
||||
def get_nutrition_avg(profile_id: str, field: str, days: int = 30) -> str:
|
||||
@@ -123,62 +129,38 @@ def get_caliper_summary(profile_id: str) -> str:
|
||||
|
||||
|
||||
def get_circ_summary(profile_id: str) -> str:
|
||||
"""Get latest circumference measurements summary with age annotations.
|
||||
|
||||
For each measurement point, fetches the most recent value (even if from different dates).
|
||||
Annotates each value with measurement age for AI context.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
Get latest circumference measurements summary with age annotations.
|
||||
|
||||
# Define all circumference points with their labels
|
||||
fields = [
|
||||
('c_neck', 'Nacken'),
|
||||
('c_chest', 'Brust'),
|
||||
('c_waist', 'Taille'),
|
||||
('c_belly', 'Bauch'),
|
||||
('c_hip', 'Hüfte'),
|
||||
('c_thigh', 'Oberschenkel'),
|
||||
('c_calf', 'Wade'),
|
||||
('c_arm', 'Arm')
|
||||
]
|
||||
Phase 0c: Refactored to use data_layer.body_metrics.get_circumference_summary_data()
|
||||
This function now only FORMATS the data for AI consumption.
|
||||
"""
|
||||
data = get_circumference_summary_data(profile_id)
|
||||
|
||||
parts = []
|
||||
today = datetime.now().date()
|
||||
if data['confidence'] == 'insufficient':
|
||||
return "keine Umfangsmessungen"
|
||||
|
||||
# Get latest value for each field individually
|
||||
for field_name, label in fields:
|
||||
cur.execute(
|
||||
f"""SELECT {field_name}, date,
|
||||
CURRENT_DATE - date AS age_days
|
||||
FROM circumference_log
|
||||
WHERE profile_id=%s AND {field_name} IS NOT NULL
|
||||
ORDER BY date DESC LIMIT 1""",
|
||||
(profile_id,)
|
||||
)
|
||||
row = r2d(cur.fetchone()) if cur.rowcount > 0 else None
|
||||
parts = []
|
||||
for measurement in data['measurements']:
|
||||
age_days = measurement['age_days']
|
||||
|
||||
if row:
|
||||
value = row[field_name]
|
||||
age_days = row['age_days']
|
||||
# Format age annotation
|
||||
if age_days == 0:
|
||||
age_str = "heute"
|
||||
elif age_days == 1:
|
||||
age_str = "gestern"
|
||||
elif age_days <= 7:
|
||||
age_str = f"vor {age_days} Tagen"
|
||||
elif age_days <= 30:
|
||||
weeks = age_days // 7
|
||||
age_str = f"vor {weeks} Woche{'n' if weeks > 1 else ''}"
|
||||
else:
|
||||
months = age_days // 30
|
||||
age_str = f"vor {months} Monat{'en' if months > 1 else ''}"
|
||||
|
||||
# Format age annotation
|
||||
if age_days == 0:
|
||||
age_str = "heute"
|
||||
elif age_days == 1:
|
||||
age_str = "gestern"
|
||||
elif age_days <= 7:
|
||||
age_str = f"vor {age_days} Tagen"
|
||||
elif age_days <= 30:
|
||||
weeks = age_days // 7
|
||||
age_str = f"vor {weeks} Woche{'n' if weeks > 1 else ''}"
|
||||
else:
|
||||
months = age_days // 30
|
||||
age_str = f"vor {months} Monat{'en' if months > 1 else ''}"
|
||||
parts.append(f"{measurement['point']} {measurement['value']:.1f}cm ({age_str})")
|
||||
|
||||
parts.append(f"{label} {value:.1f}cm ({age_str})")
|
||||
|
||||
return ', '.join(parts) if parts else "keine Umfangsmessungen"
|
||||
return ', '.join(parts) if parts else "keine Umfangsmessungen"
|
||||
|
||||
|
||||
def get_goal_weight(profile_id: str) -> str:
|
||||
|
||||
Reference in new issue
Block a user