← Files Fitness LedgerARCHIVED FILE
skills/nutrition-ledger/scripts/contributions.py
799 Bytes · Oct 5, 2026 · 18:33 UTC
"""Nutrient contribution analysis over active entries."""
from __future__ import annotations
from collections import defaultdict
from typing import Any, Iterable, Mapping
def top_sources(rows: Iterable[Mapping[str, Any]], nutrient: str, limit: int = 5) -> list[dict[str, Any]]:
totals: dict[str, float] = defaultdict(float)
for row in rows:
if row.get("deleted_at") or row.get(nutrient) is None:
continue
label = str(row.get("food_product") or "Unknown food")
totals[label] += float(row[nutrient])
total = sum(totals.values())
return [{"food": food, "amount": round(amount, 4), "proportion": round(amount / total, 4) if total else 0.0} for food, amount in sorted(totals.items(), key=lambda item: (-item[1], item[0]))[:limit]]
SHA-256: 68f1f52cab7a1b5b5d04bfe8a7f8c3364b1571e4d08126494c7d815cf37b7d1b