feat: Add personal reference values management in settings and API
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s

- Introduced new routes and API endpoints for managing personal reference values.
- Updated the SettingsPage to include a section for reference values with navigation to manage them.
- Enhanced the backend to support reference values in the data layer and versioning.
- Added necessary imports and UI components for a seamless user experience.
This commit is contained in:
Lars committed 2026-04-06 19:45:06 +02:00
1 parent e7dedd527f
commit f0e6fd04fb
23 files changed
+1719 -2

No files matched your search

@@ -0,0 +1,36 @@
"""
Training profile resolver (Layer 1 scaffold).
Template-driven multi-dimensional evaluation with built-in algorithms and
Focus Area contribution aggregation. Import explicitly from this package.
Public API:
- resolve_training_evaluation
- resolve_for_base_profile
- models: CalculationTemplate, TrainingEvaluationResult, ...
- registries: templates, profiles, algorithms
"""
from data_layer.training_profile.models import (
CalculationTemplate,
DimensionResult,
DimensionSpec,
FocusAreaMapping,
TrainingBaseProfile,
TrainingEvaluationResult,
)
from data_layer.training_profile.resolver import (
resolve_for_base_profile,
resolve_training_evaluation,
)
__all__ = [
"CalculationTemplate",
"DimensionResult",
"DimensionSpec",
"FocusAreaMapping",
"TrainingBaseProfile",
"TrainingEvaluationResult",
"resolve_for_base_profile",
"resolve_training_evaluation",
]
@@ -0,0 +1,13 @@
"""Built-in training evaluation algorithms (code-defined only)."""
from .registry import (
get_algorithm,
list_algorithm_ids,
register_algorithm,
)
__all__ = [
"get_algorithm",
"list_algorithm_ids",
"register_algorithm",
]
@@ -0,0 +1,23 @@
"""
Algorithm protocol: fixed implementations selected by id from declarative templates.
"""
from __future__ import annotations
from typing import Any, Dict, Mapping, Protocol
from data_layer.training_profile.models import AlgorithmRunResult
class TrainingAlgorithm(Protocol):
"""Built-in algorithm callable shape."""
id: str
def __call__(
self,
*,
inputs: Mapping[str, Any],
params: Mapping[str, Any],
) -> AlgorithmRunResult:
...
@@ -0,0 +1,6 @@
"""Example built-in algorithms (threshold bands, linear range mapping)."""
from .linear_range import linear_range_score
from .threshold_band import threshold_band_score
__all__ = ["linear_range_score", "threshold_band_score"]
@@ -0,0 +1,69 @@
"""
linear_range: map a value linearly from [min_value, max_value] to [0, 1], clamped.
params:
value_key: str
min_value: float
max_value: float
invert: bool (optional) — if True, high values map to 0
Missing value → score 0 and missing_inputs.
"""
from __future__ import annotations
from typing import Any, Mapping
from data_layer.training_profile.models import AlgorithmRunResult
from data_layer.utils import safe_float
ALGORITHM_ID = "linear_range"
def linear_range_score(
*,
inputs: Mapping[str, Any],
params: Mapping[str, Any],
) -> AlgorithmRunResult:
value_key = str(params.get("value_key", ""))
if not value_key:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=["__param_value_key__"],
detail={"error": "params.value_key required"},
)
if value_key not in inputs or inputs[value_key] is None:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=[value_key],
detail={"value_key": value_key},
)
raw = safe_float(inputs[value_key])
lo = safe_float(params.get("min_value"))
hi = safe_float(params.get("max_value"))
invert = bool(params.get("invert", False))
if hi <= lo:
return AlgorithmRunResult(
raw_score=raw,
normalized_score=0.0,
missing_inputs=[],
detail={"error": "max_value must be > min_value", "min": lo, "max": hi},
)
t = (raw - lo) / (hi - lo)
t = max(0.0, min(1.0, t))
if invert:
t = 1.0 - t
return AlgorithmRunResult(
raw_score=raw,
normalized_score=t,
missing_inputs=[],
detail={"value_key": value_key, "min": lo, "max": hi, "invert": invert},
)
@@ -0,0 +1,75 @@
"""
threshold_band: map a numeric value into a score using ordered upper bounds.
params:
value_key: str — key in inputs to read
bands: list of { "max": float | null, "score": float } — ascending max; null = +inf
Missing value_key → normalized_score 0, missing_inputs lists value_key.
"""
from __future__ import annotations
from typing import Any, List, Mapping
from data_layer.training_profile.models import AlgorithmRunResult
from data_layer.utils import safe_float
ALGORITHM_ID = "threshold_band"
def threshold_band_score(
*,
inputs: Mapping[str, Any],
params: Mapping[str, Any],
) -> AlgorithmRunResult:
value_key = str(params.get("value_key", ""))
if not value_key:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=["__param_value_key__"],
detail={"error": "params.value_key required"},
)
if value_key not in inputs or inputs[value_key] is None:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=[value_key],
detail={"value_key": value_key},
)
raw = safe_float(inputs[value_key])
bands = params.get("bands") or []
if not isinstance(bands, list) or not bands:
return AlgorithmRunResult(
raw_score=raw,
normalized_score=0.0,
missing_inputs=[],
detail={"error": "params.bands must be a non-empty list", "raw": raw},
)
score = 0.0
for band in bands:
if not isinstance(band, dict):
continue
max_v = band.get("max")
s = safe_float(band.get("score"))
if max_v is None:
score = s
break
if raw <= safe_float(max_v):
score = s
break
else:
score = safe_float(bands[-1].get("score")) if isinstance(bands[-1], dict) else 0.0
norm = max(0.0, min(1.0, score))
return AlgorithmRunResult(
raw_score=raw,
normalized_score=norm,
missing_inputs=[],
detail={"value_key": value_key, "bands_applied": True, "band_score": score},
)
@@ -0,0 +1,47 @@
"""
Registry for built-in algorithm ids → callables.
Only code registers algorithms; templates reference ids declared here.
"""
from __future__ import annotations
from typing import Any, Callable, Dict, Mapping
from data_layer.training_profile.algorithms.builtin.linear_range import (
ALGORITHM_ID as LINEAR_RANGE_ID,
linear_range_score,
)
from data_layer.training_profile.algorithms.builtin.threshold_band import (
ALGORITHM_ID as THRESHOLD_BAND_ID,
threshold_band_score,
)
from data_layer.training_profile.models import AlgorithmRunResult
AlgorithmFn = Callable[..., AlgorithmRunResult]
_REGISTRY: Dict[str, AlgorithmFn] = {}
def register_algorithm(algorithm_id: str, fn: AlgorithmFn) -> None:
if algorithm_id in _REGISTRY:
raise ValueError(f"Algorithm already registered: {algorithm_id}")
_REGISTRY[algorithm_id] = fn
def get_algorithm(algorithm_id: str) -> AlgorithmFn:
if algorithm_id not in _REGISTRY:
raise KeyError(f"Unknown algorithm_id: {algorithm_id}")
return _REGISTRY[algorithm_id]
def list_algorithm_ids() -> tuple[str, ...]:
return tuple(sorted(_REGISTRY.keys()))
def _register_defaults() -> None:
register_algorithm(THRESHOLD_BAND_ID, threshold_band_score)
register_algorithm(LINEAR_RANGE_ID, linear_range_score)
_register_defaults()
@@ -0,0 +1,121 @@
"""
Declarative schemas for template-based training evaluation (Layer 1 scaffold).
Templates select built-in algorithms by id and pass parameters; they do not embed
executable logic. See resolver and algorithm registry.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Mapping, Optional
@dataclass(frozen=True)
class FocusAreaMapping:
"""Maps a share of one dimension's score to a Focus Area (by stable key)."""
focus_area_key: str
weight: float
@dataclass(frozen=True)
class DimensionSpec:
"""
One evaluation dimension: algorithm + inputs + params + FA mapping.
inputs: names of keys expected in the flat activity_inputs dict passed to the resolver.
"""
key: str
algorithm_id: str
inputs: tuple[str, ...]
params: Mapping[str, Any]
maps_to: tuple[FocusAreaMapping, ...]
@dataclass(frozen=True)
class CalculationTemplate:
"""Declarative multi-dimensional calculation template (in-code registry)."""
id: str
version: str
label: str
dimensions: tuple[DimensionSpec, ...]
@dataclass(frozen=True)
class TrainingBaseProfile:
"""
Conceptual base profile: links a training context to a default template.
allowed_dimension_keys: if set, dimensions not listed are skipped at resolve time.
"""
key: str
label: str
default_template_id: str
allowed_dimension_keys: Optional[frozenset[str]] = None
@dataclass
class AlgorithmRunResult:
"""Output of a single built-in algorithm execution."""
raw_score: float
normalized_score: float
missing_inputs: List[str]
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class DimensionResult:
"""Per-dimension result after resolution."""
dimension_key: str
algorithm_id: str
raw_score: float
normalized_score: float
missing_inputs: List[str]
evidence: Dict[str, Any] = field(default_factory=dict)
@dataclass
class TrainingEvaluationResult:
"""
Stable structured result for Layer 2 (KI, charts, APIs, future persistence).
focus_area_contributions: aggregated contribution per focus_area key (additive).
"""
template_id: str
template_version: str
base_profile_key: Optional[str]
dimension_results: List[DimensionResult]
focus_area_contributions: Dict[str, float]
confidence: str
evidence: Dict[str, Any]
trace: Optional[Dict[str, Any]] = None
def to_serializable(self) -> Dict[str, Any]:
"""JSON-compatible dict (for APIs / storage)."""
return {
"template_id": self.template_id,
"template_version": self.template_version,
"base_profile_key": self.base_profile_key,
"dimension_results": [
{
"dimension_key": d.dimension_key,
"algorithm_id": d.algorithm_id,
"raw_score": d.raw_score,
"normalized_score": d.normalized_score,
"missing_inputs": d.missing_inputs,
"evidence": d.evidence,
}
for d in self.dimension_results
],
"focus_area_contributions": dict(self.focus_area_contributions),
"confidence": self.confidence,
"evidence": self.evidence,
"trace": self.trace,
}
@@ -0,0 +1,13 @@
"""Training base profile registrations (scaffold, in-code)."""
from .registry import (
get_training_base_profile,
list_training_base_profile_keys,
try_get_training_base_profile,
)
__all__ = [
"get_training_base_profile",
"list_training_base_profile_keys",
"try_get_training_base_profile",
]
@@ -0,0 +1,52 @@
"""
Example training base profiles — point to default templates and optional dimension filters.
Future: DB-backed training types may reference profile keys; this registry is code-only.
"""
from __future__ import annotations
from typing import Dict, Optional
from data_layer.training_profile.models import TrainingBaseProfile
_PROFILES: Dict[str, TrainingBaseProfile] = {}
def _register(p: TrainingBaseProfile) -> None:
if p.key in _PROFILES:
raise ValueError(f"Duplicate training base profile key: {p.key}")
_PROFILES[p.key] = p
def get_training_base_profile(key: str) -> TrainingBaseProfile:
if key not in _PROFILES:
raise KeyError(f"Unknown training base profile: {key}")
return _PROFILES[key]
def try_get_training_base_profile(key: str) -> Optional[TrainingBaseProfile]:
return _PROFILES.get(key)
def list_training_base_profile_keys() -> tuple[str, ...]:
return tuple(sorted(_PROFILES.keys()))
_register(
TrainingBaseProfile(
key="scaffold_aerobic_base",
label="Scaffold: aerobic base profile",
default_template_id="scaffold_example_aerobic_v1",
allowed_dimension_keys=None,
)
)
_register(
TrainingBaseProfile(
key="scaffold_strength_base",
label="Scaffold: strength base profile",
default_template_id="scaffold_example_strength_v1",
allowed_dimension_keys=frozenset({"effort"}),
)
)
@@ -0,0 +1,160 @@
"""
Layer 1 entry: resolve a multi-dimensional training evaluation from a template.
Pure calculation orchestration — no DB, no HTTP, no formatting for KI/charts.
"""
from __future__ import annotations
from collections import defaultdict
from typing import Any, Dict, List, Mapping, Optional
from data_layer.training_profile.algorithms.registry import get_algorithm
from data_layer.training_profile.models import (
CalculationTemplate,
DimensionResult,
DimensionSpec,
TrainingBaseProfile,
TrainingEvaluationResult,
)
def _required_inputs_present(
activity_inputs: Mapping[str, Any], keys: tuple[str, ...]
) -> tuple[bool, List[str]]:
missing: List[str] = []
for k in keys:
if k not in activity_inputs or activity_inputs[k] is None:
missing.append(k)
return (len(missing) == 0, missing)
def _confidence_level(total_dims: int, dims_with_any_missing: int) -> str:
if total_dims == 0:
return "insufficient"
if dims_with_any_missing == 0:
return "high"
if dims_with_any_missing >= total_dims:
return "insufficient"
if dims_with_any_missing == 1:
return "medium"
return "low"
def _filter_dimensions(
template: CalculationTemplate, base_profile: Optional[TrainingBaseProfile]
) -> tuple[DimensionSpec, ...]:
if base_profile is None or base_profile.allowed_dimension_keys is None:
return template.dimensions
allowed = base_profile.allowed_dimension_keys
return tuple(d for d in template.dimensions if d.key in allowed)
def resolve_training_evaluation(
*,
activity_inputs: Mapping[str, Any],
template: CalculationTemplate,
base_profile: Optional[TrainingBaseProfile] = None,
include_trace: bool = False,
) -> TrainingEvaluationResult:
"""
Run all template dimensions, aggregate Focus Area contributions, attach evidence.
activity_inputs: flat dict (e.g. avg_hr, duration_min, distance_km) supplied by caller.
"""
dimensions = _filter_dimensions(template, base_profile)
dimension_results: List[DimensionResult] = []
contributions: Dict[str, float] = defaultdict(float)
evidence: Dict[str, Any] = {
"dimensions_total": len(dimensions),
"inputs_keys": sorted(activity_inputs.keys()),
}
trace: Optional[Dict[str, Any]] = {} if include_trace else None
dims_with_missing = 0
for spec in dimensions:
ok, missing = _required_inputs_present(activity_inputs, spec.inputs)
if not ok:
dims_with_missing += 1
dimension_results.append(
DimensionResult(
dimension_key=spec.key,
algorithm_id=spec.algorithm_id,
raw_score=0.0,
normalized_score=0.0,
missing_inputs=list(missing),
evidence={"skipped": True, "reason": "required_inputs_missing"},
)
)
if trace is not None:
trace[spec.key] = {"skipped": True, "missing": missing}
continue
algo = get_algorithm(spec.algorithm_id)
slice_inputs = {k: activity_inputs[k] for k in spec.inputs}
run = algo(inputs=slice_inputs, params=dict(spec.params))
if run.missing_inputs:
dims_with_missing += 1
dimension_results.append(
DimensionResult(
dimension_key=spec.key,
algorithm_id=spec.algorithm_id,
raw_score=run.raw_score,
normalized_score=run.normalized_score,
missing_inputs=list(run.missing_inputs),
evidence={"algorithm_detail": run.detail},
)
)
for m in spec.maps_to:
contributions[m.focus_area_key] += run.normalized_score * m.weight
if trace is not None:
trace[spec.key] = {
"inputs": dict(slice_inputs),
"params": dict(spec.params),
"run": {
"raw_score": run.raw_score,
"normalized_score": run.normalized_score,
"missing_inputs": run.missing_inputs,
"detail": run.detail,
},
"maps_to": [(x.focus_area_key, x.weight) for x in spec.maps_to],
}
conf = _confidence_level(len(dimensions), dims_with_missing)
evidence["dimensions_with_missing_or_failed"] = dims_with_missing
return TrainingEvaluationResult(
template_id=template.id,
template_version=template.version,
base_profile_key=base_profile.key if base_profile else None,
dimension_results=dimension_results,
focus_area_contributions=dict(contributions),
confidence=conf,
evidence=evidence,
trace=trace,
)
def resolve_for_base_profile(
*,
activity_inputs: Mapping[str, Any],
base_profile_key: str,
include_trace: bool = False,
) -> TrainingEvaluationResult:
"""Convenience: load profile + default template from registries."""
from data_layer.training_profile.profiles.registry import get_training_base_profile
from data_layer.training_profile.templates.registry import get_calculation_template
profile = get_training_base_profile(base_profile_key)
template = get_calculation_template(profile.default_template_id)
return resolve_training_evaluation(
activity_inputs=activity_inputs,
template=template,
base_profile=profile,
include_trace=include_trace,
)
@@ -0,0 +1,5 @@
"""Declarative calculation templates (in-code registry, scaffold)."""
from .registry import get_calculation_template, list_calculation_template_ids
__all__ = ["get_calculation_template", "list_calculation_template_ids"]
@@ -0,0 +1,96 @@
"""
Example calculation templates — declarative only; algorithms are referenced by id.
These are scaffolding examples, not production coaching rules.
"""
from __future__ import annotations
from typing import Dict
from data_layer.training_profile.models import CalculationTemplate, DimensionSpec, FocusAreaMapping
_TEMPLATES: Dict[str, CalculationTemplate] = {}
def _register(t: CalculationTemplate) -> None:
if t.id in _TEMPLATES:
raise ValueError(f"Duplicate template id: {t.id}")
_TEMPLATES[t.id] = t
def get_calculation_template(template_id: str) -> CalculationTemplate:
if template_id not in _TEMPLATES:
raise KeyError(f"Unknown calculation template: {template_id}")
return _TEMPLATES[template_id]
def list_calculation_template_ids() -> tuple[str, ...]:
return tuple(sorted(_TEMPLATES.keys()))
# --- Example templates (illustrative) ---
_example_aerobic = CalculationTemplate(
id="scaffold_example_aerobic_v1",
version="1",
label="Scaffold: aerobic-style intensity + volume (example)",
dimensions=(
DimensionSpec(
key="intensity",
algorithm_id="threshold_band",
inputs=("avg_hr", "duration_min"),
params={
"value_key": "avg_hr",
"bands": [
{"max": 120, "score": 0.25},
{"max": 140, "score": 0.55},
{"max": 160, "score": 0.85},
{"max": None, "score": 1.0},
],
},
maps_to=(
FocusAreaMapping("aerobic_endurance", 0.7),
FocusAreaMapping("cardiovascular_health", 0.3),
),
),
DimensionSpec(
key="volume",
algorithm_id="linear_range",
inputs=("duration_min", "distance_km"),
params={
"value_key": "duration_min",
"min_value": 10.0,
"max_value": 90.0,
"invert": False,
},
maps_to=(FocusAreaMapping("aerobic_endurance", 0.8),),
),
),
)
_example_strength = CalculationTemplate(
id="scaffold_example_strength_v1",
version="1",
label="Scaffold: strength session load (example)",
dimensions=(
DimensionSpec(
key="effort",
algorithm_id="linear_range",
inputs=("duration_min",),
params={
"value_key": "duration_min",
"min_value": 20.0,
"max_value": 75.0,
"invert": False,
},
maps_to=(
FocusAreaMapping("strength", 0.9),
FocusAreaMapping("strength_endurance", 0.1),
),
),
),
)
_register(_example_aerobic)
_register(_example_strength)