From 66729f7d0834d87d77fce79394207227de75a7bc Mon Sep 17 00:00:00 2001 From: bjohnso2 Date: Fri, 20 Nov 2026 16:35:19 +0000 Subject: [PATCH] init --- .gitignore | 172 ++++++++++++++++++++++++ core/__init__.py | 0 core/base.py | 22 +++ core/llm_client.py | 40 ++++++ core/registry.py | 52 +++++++ core/urls.py | 8 ++ core/views.py | 27 ++++ dagda/__init__.py | 0 dagda/asgi.py | 16 +++ dagda/settings.py | 136 +++++++++++++++++++ dagda/urls.py | 23 ++++ dagda/wsgi.py | 16 +++ exercise_tracker/__init__.py | 0 exercise_tracker/migrations/__init__.py | 0 exercise_tracker/models.py | 40 ++++++ exercise_tracker/tasks.py | 72 ++++++++++ manage.py | 22 +++ meal_tracker/__init__.py | 0 meal_tracker/migrations/__init__.py | 0 meal_tracker/models.py | 120 +++++++++++++++++ meal_tracker/tasks.py | 57 ++++++++ requirements.txt | 3 + templates/core/base.html | 10 ++ templates/core/dashboard.html | 71 ++++++++++ 24 files changed, 907 insertions(+) create mode 100644 .gitignore create mode 100644 core/__init__.py create mode 100644 core/base.py create mode 100644 core/llm_client.py create mode 100644 core/registry.py create mode 100644 core/urls.py create mode 100644 core/views.py create mode 100644 dagda/__init__.py create mode 100644 dagda/asgi.py create mode 100644 dagda/settings.py create mode 100644 dagda/urls.py create mode 100644 dagda/wsgi.py create mode 100644 exercise_tracker/__init__.py create mode 100644 exercise_tracker/migrations/__init__.py create mode 100644 exercise_tracker/models.py create mode 100644 exercise_tracker/tasks.py create mode 100755 manage.py create mode 100644 meal_tracker/__init__.py create mode 100644 meal_tracker/migrations/__init__.py create mode 100644 meal_tracker/models.py create mode 100644 meal_tracker/tasks.py create mode 100644 requirements.txt create mode 100644 templates/core/base.html create mode 100644 templates/core/dashboard.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2d23794 --- /dev/null +++ b/.gitignore @@ -0,0 +1,172 @@ +### Example user template template +### Example user template + +# IntelliJ project files +.idea +*.iml +out +gen +### Python template +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/base.py b/core/base.py new file mode 100644 index 0000000..13f8d69 --- /dev/null +++ b/core/base.py @@ -0,0 +1,22 @@ +# core/base.py +from abc import ABC, abstractmethod +from typing import List, Dict, Any + + +class TaskModule(ABC): + MODULE_NAME = "" + DESCRIPTION = "" + + TOOLS = [] # Each module defines its tools + + @classmethod + def get_tools(cls) -> List[Dict[str, Any]]: + return cls.TOOLS + + @classmethod + def execute_tool(cls, tool_name: str, arguments: dict) -> Dict[str, Any]: + raise NotImplementedError("Modules must implement execute_tool()") + + @staticmethod + def get_system_prompt_fragment() -> str: + return "" diff --git a/core/llm_client.py b/core/llm_client.py new file mode 100644 index 0000000..ed75427 --- /dev/null +++ b/core/llm_client.py @@ -0,0 +1,40 @@ +# core/llm_client.py +import requests +import json +from django.conf import settings +from core.registry import TaskRegistry + +SYSTEM_PROMPT = f"""{TaskRegistry.build_system_prompt()} +Rules: +- ALWAYS use tools when appropriate. Never respond with text unless explicitly asked for a summary. +- If unsure which module handles a request, choose the most relevant one. +- Include a "final_response" field in every tool_call result for user display.""" + +def process_user_input(user_text: str): + tools = TaskRegistry.get_all_tools() + + payload = { + "model": "llama3.1", + "messages": [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": user_text} + ], + "tools": tools, + "tool_choice": "auto", + "temperature": 0.2 + } + + try: + resp = requests.post(settings.LLAMA_CPP_URL, json=payload, timeout=15) + data = resp.json() + + tool_calls = data["choices"][0]["message"].get("tool_calls", []) + if not tool_calls: + return {"status": "text", "message": data["choices"][0]["message"]["content"]} + + result = TaskRegistry.execute(tool_calls[0]["function"]["name"], + json.loads(tool_calls[0]["function"]["arguments"])) + return result + + except Exception as e: + return {"error": f"LLM processing failed: {str(e)}"} diff --git a/core/registry.py b/core/registry.py new file mode 100644 index 0000000..78a0850 --- /dev/null +++ b/core/registry.py @@ -0,0 +1,52 @@ +# core/registry.py +import importlib +from django.apps import apps +from core.base import TaskModule + + +class TaskRegistry: + MODULES = {} + + @classmethod + def discover_modules(cls): + for app_config in apps.get_app_configs(): + try: + module_path = f"{app_config.name}.tasks" + importlib.import_module(module_path) + + for obj_name in dir(apps.get_app_config(app_config.name).module): + obj = getattr(apps.get_app_config(app_config.name).module, obj_name) + if (isinstance(obj, type) and + issubclass(obj, TaskModule) and + obj.__name__ != 'TaskModule'): + cls.MODULES[obj.MODULE_NAME] = obj + except Exception: + continue + + @classmethod + def get_all_tools(cls) -> list: + tools = [] + for module in cls.MODULES.values(): + tools.extend(module.get_tools()) + return tools + + @classmethod + def execute(cls, tool_name: str, arguments: dict) -> dict: + for name, module in cls.MODULES.items(): + available_tools = [t["function"]["name"] for t in module.get_tools()] + if tool_name in available_tools: + return module.execute_tool(tool_name, arguments) + return {"status": "error", "message": f"Unknown tool: {tool_name}"} + + @classmethod + def build_system_prompt(cls) -> str: + fragments = [ + "You are an AI assistant with access to the following modules:", + *(f"- **{name.upper()}**: {mod.DESCRIPTION}" for name, mod in cls.MODULES.items()), + "\nOnly call tools that exist in your available tool list." + ] + return "\n".join(fragments) + + +# Auto-discover on first import +TaskRegistry.discover_modules() diff --git a/core/urls.py b/core/urls.py new file mode 100644 index 0000000..3d49d1b --- /dev/null +++ b/core/urls.py @@ -0,0 +1,8 @@ +# core/urls.py +from django.urls import path +from . import views + +urlpatterns = [ + path("", views.dashboard, name="dashboard"), + path("log/", views.agent_input, name="agent_input"), +] diff --git a/core/views.py b/core/views.py new file mode 100644 index 0000000..6f54fbe --- /dev/null +++ b/core/views.py @@ -0,0 +1,27 @@ +# core/views.py +from django.shortcuts import render, redirect +from django.contrib import messages +from core.llm_client import process_user_input + + +def dashboard(request): + return render(request, "core/dashboard.html") + + +def agent_input(request): + if request.method == "POST": + user_text = request.POST.get("input", "").strip() + if not user_text: + messages.warning(request, "Please enter a command.") + return redirect("dashboard") + + result = process_user_input(user_text) + + if result.get("error"): + messages.error(request, result["error"]) + elif result.get("status") == "success": + messages.success(request, result.get("message", "Task completed")) + else: + messages.info(request, result.get("message", "No action taken.")) + + return redirect("dashboard") diff --git a/dagda/__init__.py b/dagda/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dagda/asgi.py b/dagda/asgi.py new file mode 100644 index 0000000..92c8035 --- /dev/null +++ b/dagda/asgi.py @@ -0,0 +1,16 @@ +""" +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() diff --git a/dagda/settings.py b/dagda/settings.py new file mode 100644 index 0000000..2925716 --- /dev/null +++ b/dagda/settings.py @@ -0,0 +1,136 @@ +""" +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' diff --git a/dagda/urls.py b/dagda/urls.py new file mode 100644 index 0000000..38e3c06 --- /dev/null +++ b/dagda/urls.py @@ -0,0 +1,23 @@ +""" +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')), +] diff --git a/dagda/wsgi.py b/dagda/wsgi.py new file mode 100644 index 0000000..cca80c2 --- /dev/null +++ b/dagda/wsgi.py @@ -0,0 +1,16 @@ +""" +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() diff --git a/exercise_tracker/__init__.py b/exercise_tracker/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/exercise_tracker/migrations/__init__.py b/exercise_tracker/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/exercise_tracker/models.py b/exercise_tracker/models.py new file mode 100644 index 0000000..06b52bc --- /dev/null +++ b/exercise_tracker/models.py @@ -0,0 +1,40 @@ +# 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})" diff --git a/exercise_tracker/tasks.py b/exercise_tracker/tasks.py new file mode 100644 index 0000000..fcb9c22 --- /dev/null +++ b/exercise_tracker/tasks.py @@ -0,0 +1,72 @@ +# 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}") diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..a7b4961 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dagda.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/meal_tracker/__init__.py b/meal_tracker/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/meal_tracker/migrations/__init__.py b/meal_tracker/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/meal_tracker/models.py b/meal_tracker/models.py new file mode 100644 index 0000000..a1ac110 --- /dev/null +++ b/meal_tracker/models.py @@ -0,0 +1,120 @@ +# 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)" + diff --git a/meal_tracker/tasks.py b/meal_tracker/tasks.py new file mode 100644 index 0000000..bf16219 --- /dev/null +++ b/meal_tracker/tasks.py @@ -0,0 +1,57 @@ +# 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}") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..fa923cb --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +Django==5.1.4 +requests>=2.31.0 +psycopg2-binary>=2.9.9 # Use only if using PostgreSQL \ No newline at end of file diff --git a/templates/core/base.html b/templates/core/base.html new file mode 100644 index 0000000..566549b --- /dev/null +++ b/templates/core/base.html @@ -0,0 +1,10 @@ + + + + + Title + + + + + \ No newline at end of file diff --git a/templates/core/dashboard.html b/templates/core/dashboard.html new file mode 100644 index 0000000..435f983 --- /dev/null +++ b/templates/core/dashboard.html @@ -0,0 +1,71 @@ + + + + + + + AI Task Agent + + + + + +
+ +
+
+

Local AI Agent

+

Natural language interface for your tasks.

+
+
+ + +
+
+
+
+ {% csrf_token %} + + + +
+
+
+
+ + + {% if messages %} +
+
+ {% for message in messages %} + + {% endfor %} +
+
+ {% endif %} + + +
+
+
+ Meal Tracker + Exercise Tracker + Calendar +
+
+
+
+ + + + +