feat: learnable activity type mapping system (DB-based, auto-learning)
Replaces hardcoded mappings with database-driven, self-learning system. Backend: - Migration 007: activity_type_mappings table - Supports global and user-specific mappings - Seeded with 40+ default mappings (German + English) - Unique constraint: (activity_type, profile_id) - Refactored: get_training_type_for_activity() queries DB - Priority: user-specific → global → NULL - Bulk categorization now saves mapping automatically - Source: 'bulk' for learned mappings - admin_activity_mappings.py: Full CRUD endpoints - List, Get, Create, Update, Delete - Coverage stats endpoint - CSV import uses DB mappings (no hardcoded logic) Frontend: - AdminActivityMappingsPage: Full mapping management UI - Coverage stats (% mapped, unmapped count) - Filter: All / Global - Create/Edit/Delete mappings - Tip: System learns from bulk categorization - Added route + admin link - API methods: adminList/Get/Create/Update/DeleteActivityMapping Benefits: - No code changes needed for new activity types - System learns from user bulk categorizations - User-specific mappings override global defaults - Admin can manage all mappings via UI - Migration pre-populates 40+ common German/English types Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
a4bd738e6f
commit
829edecbdc
8 files changed
+772
-67
No files matched your search
+48
-66
@@ -113,80 +113,44 @@ def activity_stats(x_profile_id: Optional[str]=Header(default=None), session: di
|
||||
return {"count":len(rows),"total_kcal":round(total_kcal),"total_min":round(total_min),"by_type":by_type}
|
||||
|
||||
|
||||
def get_training_type_for_apple_health(workout_type: str):
|
||||
def get_training_type_for_activity(activity_type: str, profile_id: str = None):
|
||||
"""
|
||||
Map Apple Health workout type to training_type_id + category + subcategory.
|
||||
Map activity_type to training_type_id using database mappings.
|
||||
|
||||
Priority:
|
||||
1. User-specific mapping (profile_id)
|
||||
2. Global mapping (profile_id = NULL)
|
||||
3. No mapping found → returns (None, None, None)
|
||||
|
||||
Returns: (training_type_id, category, subcategory) or (None, None, None)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Mapping: Apple Health Workout Type → training_type subcategory
|
||||
# Supports English and German workout names
|
||||
mapping = {
|
||||
# English
|
||||
'running': 'running',
|
||||
'walking': 'walk',
|
||||
'hiking': 'walk',
|
||||
'cycling': 'cycling',
|
||||
'swimming': 'swimming',
|
||||
'traditional strength training': 'hypertrophy',
|
||||
'functional strength training': 'functional',
|
||||
'high intensity interval training': 'hiit',
|
||||
'yoga': 'yoga',
|
||||
'martial arts': 'technique',
|
||||
'boxing': 'sparring',
|
||||
'rowing': 'rowing',
|
||||
'dance': 'dance',
|
||||
'core training': 'functional',
|
||||
'flexibility': 'static',
|
||||
'cooldown': 'regeneration',
|
||||
'meditation': 'meditation',
|
||||
'mindfulness': 'mindfulness',
|
||||
# Try user-specific mapping first
|
||||
if profile_id:
|
||||
cur.execute("""
|
||||
SELECT m.training_type_id, t.category, t.subcategory
|
||||
FROM activity_type_mappings m
|
||||
JOIN training_types t ON m.training_type_id = t.id
|
||||
WHERE m.activity_type = %s AND m.profile_id = %s
|
||||
LIMIT 1
|
||||
""", (activity_type, profile_id))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
return (row['training_type_id'], row['category'], row['subcategory'])
|
||||
|
||||
# German (Deutsch)
|
||||
'laufen': 'running',
|
||||
'gehen': 'walk',
|
||||
'wandern': 'walk',
|
||||
'outdoor spaziergang': 'walk',
|
||||
'innenräume spaziergang': 'walk',
|
||||
'spaziergang': 'walk',
|
||||
'radfahren': 'cycling',
|
||||
'schwimmen': 'swimming',
|
||||
'traditionelles krafttraining': 'hypertrophy',
|
||||
'funktionelles krafttraining': 'functional',
|
||||
'hochintensives intervalltraining': 'hiit',
|
||||
'yoga': 'yoga',
|
||||
'kampfsport': 'technique',
|
||||
'matrial arts': 'technique', # Common typo in Apple Health
|
||||
'boxen': 'sparring',
|
||||
'rudern': 'rowing',
|
||||
'tanzen': 'dance',
|
||||
'cardio dance': 'dance',
|
||||
'core training': 'functional',
|
||||
'flexibilität': 'static',
|
||||
'abwärmen': 'regeneration',
|
||||
'cooldown': 'regeneration',
|
||||
'meditation': 'meditation',
|
||||
'achtsamkeit': 'mindfulness',
|
||||
'geist & körper': 'yoga', # Mind & Body → Yoga category
|
||||
}
|
||||
|
||||
subcategory = mapping.get(workout_type.lower())
|
||||
if not subcategory:
|
||||
return (None, None, None)
|
||||
|
||||
# Find training_type_id by subcategory
|
||||
# Try global mapping
|
||||
cur.execute("""
|
||||
SELECT id, category, subcategory
|
||||
FROM training_types
|
||||
WHERE LOWER(subcategory) = %s
|
||||
SELECT m.training_type_id, t.category, t.subcategory
|
||||
FROM activity_type_mappings m
|
||||
JOIN training_types t ON m.training_type_id = t.id
|
||||
WHERE m.activity_type = %s AND m.profile_id IS NULL
|
||||
LIMIT 1
|
||||
""", (subcategory,))
|
||||
""", (activity_type,))
|
||||
row = cur.fetchone()
|
||||
|
||||
if row:
|
||||
return (row['id'], row['category'], row['subcategory'])
|
||||
return (row['training_type_id'], row['category'], row['subcategory'])
|
||||
|
||||
return (None, None, None)
|
||||
|
||||
@@ -216,6 +180,9 @@ def bulk_categorize_activities(
|
||||
):
|
||||
"""
|
||||
Bulk update training type for activities.
|
||||
|
||||
Also saves the mapping to activity_type_mappings for future imports.
|
||||
|
||||
Body: {
|
||||
"activity_type": "Running",
|
||||
"training_type_id": 1,
|
||||
@@ -234,6 +201,8 @@ def bulk_categorize_activities(
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Update existing activities
|
||||
cur.execute("""
|
||||
UPDATE activity_log
|
||||
SET training_type_id = %s,
|
||||
@@ -245,7 +214,20 @@ def bulk_categorize_activities(
|
||||
""", (training_type_id, training_category, training_subcategory, pid, activity_type))
|
||||
updated_count = cur.rowcount
|
||||
|
||||
return {"updated": updated_count, "activity_type": activity_type}
|
||||
# Save mapping for future imports (upsert)
|
||||
cur.execute("""
|
||||
INSERT INTO activity_type_mappings (activity_type, training_type_id, profile_id, source, updated_at)
|
||||
VALUES (%s, %s, %s, 'bulk', CURRENT_TIMESTAMP)
|
||||
ON CONFLICT (activity_type, profile_id)
|
||||
DO UPDATE SET
|
||||
training_type_id = EXCLUDED.training_type_id,
|
||||
source = 'bulk',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""", (activity_type, training_type_id, pid))
|
||||
|
||||
logger.info(f"[MAPPING] Saved bulk mapping: {activity_type} → training_type_id {training_type_id} (profile {pid})")
|
||||
|
||||
return {"updated": updated_count, "activity_type": activity_type, "mapping_saved": True}
|
||||
|
||||
|
||||
@router.post("/import-csv")
|
||||
@@ -280,8 +262,8 @@ async def import_activity_csv(file: UploadFile=File(...), x_profile_id: Optional
|
||||
def tf(v):
|
||||
try: return round(float(v),1) if v else None
|
||||
except: return None
|
||||
# Map Apple Health workout type to training_type_id
|
||||
training_type_id, training_category, training_subcategory = get_training_type_for_apple_health(wtype)
|
||||
# Map activity_type to training_type_id using database mappings
|
||||
training_type_id, training_category, training_subcategory = get_training_type_for_activity(wtype, pid)
|
||||
|
||||
try:
|
||||
# Check if entry already exists (duplicate detection by date + start_time)
|
||||
|
||||
Reference in new issue
Block a user