diff --git a/allfiles.txt b/allfiles.txt new file mode 100644 index 0000000..30927e8 --- /dev/null +++ b/allfiles.txt @@ -0,0 +1,779 @@ +File ./exercise_tracker/models.py +# exercise_tracker/models.py +from django.db import models + + +class Session(models.Model): + name = models.CharField(max_length=100, blank=True) + date = models.DateField() + location = models.CharField(max_length=100, blank=True) + + def __str__(self): + return f"{self.name or 'Workout'} ({self.date})" + + +class Exercise(models.Model): + session = models.ForeignKey(Session, related_name='exercises', on_delete=models.CASCADE) + name = models.CharField(max_length=255) + + def __str__(self): + return f"{self.name} in {self.session.name or 'Workout'}" + + +class Set(models.Model): + exercise = models.ForeignKey(Exercise, related_name='sets', on_delete=models.CASCADE) + + reps = models.IntegerField(null=True, blank=True) + weight_kg = models.FloatField(null=True, blank=True) + + distance_meters = models.FloatField(null=True, blank=True) + duration_seconds = models.IntegerField(null=True, blank=True) + + is_personal_record = models.BooleanField(default=False) + + def __str__(self): + if self.distance_meters is not None: + mins = self.duration_seconds // 60 if self.duration_seconds else 0 + secs = self.duration_seconds % 60 if self.duration_seconds else 0 + return f"Cardio: {self.exercise.name} ({mins}m {secs}s, {self.distance_meters / 1000:.2f}km)" + reps_str = self.reps or "∞" + weight_str = f"{self.weight_kg:.1f}" if self.weight_kg is not None else "" + return f"{reps_str}x{weight_str}kg ({self.exercise.name})" +----------------------------------------------------------------------------- +File ./exercise_tracker/migrations/__init__.py +----------------------------------------------------------------------------- +File ./exercise_tracker/tasks.py +# exercise_tracker/tasks.py +from core.base import TaskModule +from .models import Session, Exercise, Set + + +class ExerciseTracker(TaskModule): + MODULE_NAME = "exercise_tracker" + DESCRIPTION = "Log workouts, exercises, and training sets (strength & cardio)" + + TOOLS = [ + { + "type": "function", + "function": { + "name": "log_workout", + "description": "Record a complete workout session with exercises and sets", + "parameters": { + "type": "object", + "properties": { + "session_name": {"type": "string"}, + "date": {"type": "string", "format": "date"}, + "exercises": { + "type": "array", + "items": { + "type": "object", + "properties": { + "exercise_name": {"type": "string"}, + "sets": { + "type": "array", + "items": { + "type": "object", + "properties": { + # Strength options + "reps": {"type": "integer"}, + "weight_kg": {"type": "number"}, + + # Cardio options + "duration_seconds": {"type": "integer"}, + "distance_meters": {"type": "number"} + } + } + } + }, + "required": ["exercise_name"] + } + } + }, + "required": ["session_name", "date", "exercises"] + } + } + } + ] + + @classmethod + def execute_tool(cls, tool_name: str, arguments: dict) -> dict: + if tool_name == "log_workout": + session = Session.objects.create(name=arguments["session_name"], date=arguments["date"]) + + for ex_data in arguments.get("exercises", []): + exercise = Exercise.objects.create(session=session, name=ex_data["exercise_name"]) + + for set_data in ex_data.get("sets", []): + Set.objects.create( + exercise=exercise, + reps=set_data.get("reps"), + weight_kg=set_data.get("weight_kg"), + duration_seconds=set_data.get("duration_seconds"), + distance_meters=set_data.get("distance_meters") + ) + + return {"status": "success", "message": f"Logged workout: {session.name}"} + + raise ValueError(f"Unknown tool: {tool_name}") +----------------------------------------------------------------------------- +File ./exercise_tracker/__init__.py +----------------------------------------------------------------------------- +File ./dagda/settings.py +""" +Django settings for dagda project. + +Generated by 'django-admin startproject' using Django 6.1.3. + +For more information on this file, see +https://docs.djangoproject.com/en/6.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/6.1/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-jby^z#toz(p!$z=gr7+p8^d(qq1-yvb)8#+7ousf+)=&k-5zx^' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'core', + 'meal_tracker', + 'exercise_tracker', + 'calendar', + + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'dagda.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [BASE_DIR / 'templates'] + , + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'dagda.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/6.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/6.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/6.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/6.1/howto/static-files/ + +STATIC_URL = 'static/' + + +# Email +# https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration + +MAILERS = { + 'default': { + 'BACKEND': 'django.core.mail.backends.console.EmailBackend', + }, +} + +LLAMA_CPP_URL = "http://brigit.lan:8080/v1/chat/completions" +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' +----------------------------------------------------------------------------- +File ./dagda/asgi.py +""" +ASGI config for dagda project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/6.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dagda.settings') + +application = get_asgi_application() +----------------------------------------------------------------------------- +File ./dagda/urls.py +""" +URL configuration for dagda project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/6.1/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), + path('', include('core.urls')), +] +----------------------------------------------------------------------------- +File ./dagda/wsgi.py +""" +WSGI config for dagda project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/6.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dagda.settings') + +application = get_wsgi_application() +----------------------------------------------------------------------------- +File ./dagda/__init__.py +----------------------------------------------------------------------------- +File ./meal_tracker/models.py +# meal_tracker/models.py +from django.db import models + + +class Ingredient(models.Model): + name = models.CharField(max_length=255, db_index=True) + calories_per_100g = models.FloatField() + protein_per_100g = models.FloatField() + fat_per_100g = models.FloatField() + carbs_per_100g = models.FloatField() + + class Meta: + verbose_name_plural = "Ingredients" + + def __str__(self): + return self.name + + +class Food(models.Model): + name = models.CharField(max_length=255, unique=True) + estimated_calories = models.IntegerField(null=True, blank=True) + estimated_protein = models.FloatField(null=True, blank=True) + estimated_fat = models.FloatField(null=True, blank=True) + estimated_carbs = models.FloatField(null=True, blank=True) + + ingredients = models.ManyToManyField('Ingredient', through='FoodComponent') + + @property + def total_calories(self): + if self.estimated_calories: + return self.estimated_calories + return sum(c.get_component_calories() for c in self.ingredients.all()) + + def __str__(self): + return self.name + + +class FoodComponent(models.Model): + food = models.ForeignKey(Food, related_name='components', on_delete=models.CASCADE) + ingredient = models.ForeignKey(Ingredient, related_name='foods_used_in', on_delete=models.CASCADE) + amount_grams = models.FloatField() + calories = models.IntegerField(default=0) + protein = models.FloatField(default=0) + fat = models.FloatField(default=0) + carbs = models.FloatField(default=0) + + def save(self, *args, **kwargs): + if self.ingredient: + factor = self.amount_grams / 100.0 + self.calories = int(self.ingredient.calories_per_100g * factor) + self.protein = self.ingredient.protein_per_100g * factor + self.fat = self.ingredient.fat_per_100g * factor + self.carbs = self.ingredient.carbs_per_100g * factor + super().save(*args, **kwargs) + + def __str__(self): + return f"{self.food.name} component" + + +class Meal(models.Model): + date = models.DateField() + created_at = models.DateTimeField(auto_now_add=True) + + def get_total_macros(self): + totals = {'calories': 0, 'protein': 0, 'fat': 0, 'carbs': 0} + for item in self.items.all(): + totals['calories'] += item.get_food_calories() + totals['protein'] += item.get_food_protein() + totals['fat'] += item.get_food_fat() + totals['carbs'] += item.get_food_carbs() + return totals + + def __str__(self): + return f"Meal on {self.date}" + + +class MealItem(models.Model): + meal = models.ForeignKey(Meal, related_name='items', on_delete=models.CASCADE) + food = models.ForeignKey(Food, related_name='meals_contained', on_delete=models.PROTECT) + quantity_grams = models.FloatField() + + def get_food_calories(self): + if self.food.estimated_calories: + return int(self.food.estimated_calories) + total = 0 + for comp in self.food.components.all(): + factor = self.quantity_grams / comp.amount_grams + total += int(comp.calories * factor) + return total + + def get_food_protein(self): + if self.food.estimated_protein is not None: + return self.food.estimated_protein + total = 0 + for comp in self.food.components.all(): + factor = self.quantity_grams / comp.amount_grams + total += comp.protein * factor + return total + + def get_food_fat(self): + if self.food.estimated_fat is not None: + return self.food.estimated_fat + total = 0 + for comp in self.food.components.all(): + factor = self.quantity_grams / comp.amount_grams + total += comp.fat * factor + return total + + def get_food_carbs(self): + if self.food.estimated_carbs is not None: + return self.food.estimated_carbs + total = 0 + for comp in self.food.components.all(): + factor = self.quantity_grams / comp.amount_grams + total += comp.carbs * factor + return total + + def __str__(self): + return f"{self.food.name} ({self.quantity_grams}g)" + +----------------------------------------------------------------------------- +File ./meal_tracker/migrations/__init__.py +----------------------------------------------------------------------------- +File ./meal_tracker/tasks.py +# meal_tracker/tasks.py +from core.base import TaskModule +from .models import Meal, MealItem, Food + + +class MealTracker(TaskModule): + MODULE_NAME = "meal_tracker" + DESCRIPTION = "Log meals with food items and nutritional tracking" + + TOOLS = [ + { + "type": "function", + "function": { + "name": "log_meal", + "description": "Log a meal entry with food, quantity, and macros", + "parameters": { + "type": "object", + "properties": { + "date": {"type": "string", "format": "date"}, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "food_name": {"type": "string"}, + "quantity_grams": {"type": "integer"}, + "estimated_calories": {"type": "integer"}, + "estimated_protein": {"type": "number"}, + "estimated_fat": {"type": "number"}, + "estimated_carbs": {"type": "number"} + }, + "required": ["food_name", "quantity_grams"] + } + } + }, + "required": ["date", "items"] + } + } + } + ] + + @classmethod + def execute_tool(cls, tool_name: str, arguments: dict) -> dict: + if tool_name == "log_meal": + meal = Meal.objects.create(date=arguments["date"]) + for item_data in arguments["items"]: + food = Food.objects.create( + name=item_data["food_name"], + estimated_calories=item_data.get("estimated_calories"), + estimated_protein=item_data.get("estimated_protein"), + estimated_fat=item_data.get("estimated_fat"), + estimated_carbs=item_data.get("estimated_carbs") + ) + MealItem.objects.create(meal=meal, food=food, quantity_grams=item_data["quantity_grams"]) + return {"status": "success", + "message": f"Logged {len(arguments['items'])} food items for {arguments['date']}"} + raise ValueError(f"Unknown tool: {tool_name}") +----------------------------------------------------------------------------- +File ./meal_tracker/__init__.py +----------------------------------------------------------------------------- +File ./templates/core/base.html + + +
+ +Natural language interface for your tasks.
+