From 57ef57053957d0ff4575662c21deec6362c63656 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 28 Jun 2026 23:45:49 -0400 Subject: [PATCH] Add Django backend: users, admin, OTIO + scene persistence A Project (owner, OTIO file, fps, scene JSON) persists the timeline. Session API: list projects, GET/PUT scene, serve OTIO. Admin manages users/projects; seed_demo creates a project from the bundled one_two_three.otio. Co-Authored-By: Claude Opus 4.8 --- .gitignore | 7 ++ README.md | 37 +++++++ manage.py | 22 +++++ requirements.txt | 3 + scenes/__init__.py | 0 scenes/admin.py | 11 +++ scenes/apps.py | 5 + scenes/management/__init__.py | 0 scenes/management/commands/__init__.py | 0 scenes/management/commands/seed_demo.py | 31 ++++++ scenes/migrations/0001_initial.py | 33 +++++++ scenes/migrations/__init__.py | 0 scenes/models.py | 25 +++++ scenes/tests.py | 3 + scenes/urls.py | 9 ++ scenes/views.py | 56 +++++++++++ server/__init__.py | 0 server/asgi.py | 16 +++ server/settings.py | 124 ++++++++++++++++++++++++ server/urls.py | 8 ++ server/wsgi.py | 16 +++ 21 files changed, 406 insertions(+) create mode 100644 README.md create mode 100755 manage.py create mode 100644 requirements.txt create mode 100644 scenes/__init__.py create mode 100644 scenes/admin.py create mode 100644 scenes/apps.py create mode 100644 scenes/management/__init__.py create mode 100644 scenes/management/commands/__init__.py create mode 100644 scenes/management/commands/seed_demo.py create mode 100644 scenes/migrations/0001_initial.py create mode 100644 scenes/migrations/__init__.py create mode 100644 scenes/models.py create mode 100644 scenes/tests.py create mode 100644 scenes/urls.py create mode 100644 scenes/views.py create mode 100644 server/__init__.py create mode 100644 server/asgi.py create mode 100644 server/settings.py create mode 100644 server/urls.py create mode 100644 server/wsgi.py diff --git a/.gitignore b/.gitignore index 6359c7c..e170f0c 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,10 @@ node_modules/ .idea/ .vscode/ .DS_Store + +# Python / Django backend +.venv/ +__pycache__/ +*.pyc +db.sqlite3 +/media/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..e814017 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# scene_analysis + +- `tl/` — the lumet frontend (ClojureScript / reagent / re-frame). See `tl/`. +- Django backend (this folder) — users, admin, and persistence of OTIO + the + timeline scene. + +## Backend + +The backend stores one `Project` per editing session: the uploaded **OTIO** +source file, the playback **fps**, and the live **scene** (the `{:tracks +:groups}` mark-group map the frontend keeps in app-db) as a JSON dump. + +### Run + +```bash +python -m venv .venv && .venv/bin/pip install -r requirements.txt +.venv/bin/python manage.py migrate +DJANGO_SUPERUSER_PASSWORD=admin .venv/bin/python manage.py createsuperuser --noinput --username admin --email admin@example.com +.venv/bin/python manage.py seed_demo # demo project from tl/.../one_two_three.otio +.venv/bin/python manage.py runserver +``` + +Admin: (admin / admin). Upload OTIO and inspect +the scene JSON there. + +### API (session auth; 401 if not logged in) + +| Method | Path | Purpose | +| --- | --- | --- | +| GET | `/api/projects/` | the current user's projects | +| GET | `/api/projects//scene/` | `{fps, scene}` | +| PUT | `/api/projects//scene/` | replace `scene` and/or `fps` (JSON body) | +| GET | `/api/projects//otio/` | serve the uploaded OTIO file | + +The frontend currently loads `/one_two_three.otio` and persists annotations to +localStorage; pointing it at `/api/projects//otio/` and the scene endpoints +is the next wiring step (CORS/credentials needed across the dev ports). diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..8b46ee6 --- /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', 'server.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/requirements.txt b/requirements.txt new file mode 100644 index 0000000..df5f001 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +asgiref==3.11.1 +Django==6.0.6 +sqlparse==0.5.5 diff --git a/scenes/__init__.py b/scenes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scenes/admin.py b/scenes/admin.py new file mode 100644 index 0000000..49d3262 --- /dev/null +++ b/scenes/admin.py @@ -0,0 +1,11 @@ +from django.contrib import admin + +from .models import Project + + +@admin.register(Project) +class ProjectAdmin(admin.ModelAdmin): + list_display = ("name", "owner", "fps", "updated") + list_filter = ("owner",) + search_fields = ("name",) + readonly_fields = ("created", "updated") diff --git a/scenes/apps.py b/scenes/apps.py new file mode 100644 index 0000000..9ca11bb --- /dev/null +++ b/scenes/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class ScenesConfig(AppConfig): + name = 'scenes' diff --git a/scenes/management/__init__.py b/scenes/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scenes/management/commands/__init__.py b/scenes/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scenes/management/commands/seed_demo.py b/scenes/management/commands/seed_demo.py new file mode 100644 index 0000000..e7774a2 --- /dev/null +++ b/scenes/management/commands/seed_demo.py @@ -0,0 +1,31 @@ +"""Create a demo Project owned by `admin`, with the bundled OTIO attached.""" +from pathlib import Path + +from django.conf import settings +from django.contrib.auth import get_user_model +from django.core.files import File +from django.core.management.base import BaseCommand + +from scenes.models import Project + +OTIO = settings.BASE_DIR / "tl" / "resources" / "public" / "one_two_three.otio" + + +class Command(BaseCommand): + help = "Seed a demo project from the bundled OTIO file." + + def handle(self, *args, **opts): + User = get_user_model() + owner = User.objects.filter(username="admin").first() + if owner is None: + self.stderr.write("no 'admin' user — run createsuperuser first") + return + + project, created = Project.objects.get_or_create( + owner=owner, name="one two three", defaults={"scene": {}}) + if OTIO.exists() and not project.otio: + with OTIO.open("rb") as fh: + project.otio.save(Path(OTIO).name, File(fh), save=True) + + verb = "created" if created else "exists" + self.stdout.write(f"project #{project.pk} {verb}: {project.name} (otio={bool(project.otio)})") diff --git a/scenes/migrations/0001_initial.py b/scenes/migrations/0001_initial.py new file mode 100644 index 0000000..fc279ba --- /dev/null +++ b/scenes/migrations/0001_initial.py @@ -0,0 +1,33 @@ +# Generated by Django 6.0.6 on 2026-06-29 03:38 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Project', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=200)), + ('otio', models.FileField(blank=True, null=True, upload_to='otio/')), + ('fps', models.FloatField(default=23.976023976023978)), + ('scene', models.JSONField(blank=True, default=dict)), + ('created', models.DateTimeField(auto_now_add=True)), + ('updated', models.DateTimeField(auto_now=True)), + ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='projects', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'ordering': ['-updated'], + }, + ), + ] diff --git a/scenes/migrations/__init__.py b/scenes/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scenes/models.py b/scenes/models.py new file mode 100644 index 0000000..84a8d87 --- /dev/null +++ b/scenes/models.py @@ -0,0 +1,25 @@ +from django.conf import settings +from django.db import models + +NTSC_24 = 24000 / 1001 + + +class Project(models.Model): + """One editing project: an uploaded OTIO source + the live mark-group scene + (tl.scene) the frontend reads and writes. The scene is just a JSON dump for + now — the whole {:tracks :groups} map the client keeps in app-db.""" + + owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, + related_name="projects") + name = models.CharField(max_length=200) + otio = models.FileField(upload_to="otio/", blank=True, null=True) + fps = models.FloatField(default=NTSC_24) + scene = models.JSONField(default=dict, blank=True) + created = models.DateTimeField(auto_now_add=True) + updated = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ["-updated"] + + def __str__(self): + return f"{self.name} (#{self.pk})" diff --git a/scenes/tests.py b/scenes/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/scenes/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/scenes/urls.py b/scenes/urls.py new file mode 100644 index 0000000..553eba8 --- /dev/null +++ b/scenes/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from . import views + +urlpatterns = [ + path("projects/", views.projects), + path("projects//scene/", views.scene), + path("projects//otio/", views.otio), +] diff --git a/scenes/views.py b/scenes/views.py new file mode 100644 index 0000000..974903f --- /dev/null +++ b/scenes/views.py @@ -0,0 +1,56 @@ +import json + +from django.http import FileResponse, HttpResponseNotAllowed, JsonResponse +from django.shortcuts import get_object_or_404 +from django.views.decorators.csrf import csrf_exempt + +from .models import Project + + +def _auth(request): + """None if logged in, else a 401 JSON response (so fetch() doesn't get a + login redirect).""" + if not request.user.is_authenticated: + return JsonResponse({"detail": "authentication required"}, status=401) + return None + + +def _owned(request, pk): + return get_object_or_404(Project, pk=pk, owner=request.user) + + +def projects(request): + """GET /api/projects/ — the current user's projects.""" + if (resp := _auth(request)): + return resp + rows = Project.objects.filter(owner=request.user).values("id", "name", "fps", "updated") + return JsonResponse(list(rows), safe=False) + + +@csrf_exempt # dev convenience: session-auth API without a CSRF token round-trip +def scene(request, pk): + """GET/PUT /api/projects//scene/ — read or replace the timeline scene.""" + if (resp := _auth(request)): + return resp + project = _owned(request, pk) + if request.method == "GET": + return JsonResponse({"fps": project.fps, "scene": project.scene}) + if request.method == "PUT": + data = json.loads(request.body or "{}") + if "scene" in data: + project.scene = data["scene"] + if "fps" in data: + project.fps = data["fps"] + project.save(update_fields=["scene", "fps", "updated"]) + return JsonResponse({"ok": True, "updated": project.updated}) + return HttpResponseNotAllowed(["GET", "PUT"]) + + +def otio(request, pk): + """GET /api/projects//otio/ — serve the uploaded OTIO file.""" + if (resp := _auth(request)): + return resp + project = _owned(request, pk) + if not project.otio: + return JsonResponse({"detail": "no otio uploaded"}, status=404) + return FileResponse(project.otio.open("rb"), content_type="application/json") diff --git a/server/__init__.py b/server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/asgi.py b/server/asgi.py new file mode 100644 index 0000000..2c8b7fc --- /dev/null +++ b/server/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for server 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.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') + +application = get_asgi_application() diff --git a/server/settings.py b/server/settings.py new file mode 100644 index 0000000..ccd9ec6 --- /dev/null +++ b/server/settings.py @@ -0,0 +1,124 @@ +""" +Django settings for server project. + +Generated by 'django-admin startproject' using Django 6.0.6. + +For more information on this file, see +https://docs.djangoproject.com/en/6.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/6.0/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.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-it#u2wp)_qjx@cq61o*thw#*4_1*hk!%%lz#d+fww6^*l3j+zj' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'testserver'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'scenes', +] + +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 = 'server.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + '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 = 'server.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/6.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/6.0/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.0/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.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Uploaded OTIO files +MEDIA_URL = 'media/' +MEDIA_ROOT = BASE_DIR / 'media' + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/server/urls.py b/server/urls.py new file mode 100644 index 0000000..69fb2d6 --- /dev/null +++ b/server/urls.py @@ -0,0 +1,8 @@ +"""URL configuration for the scene_analysis backend.""" +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path("admin/", admin.site.urls), + path("api/", include("scenes.urls")), +] diff --git a/server/wsgi.py b/server/wsgi.py new file mode 100644 index 0000000..f8d1d2e --- /dev/null +++ b/server/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for server 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.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') + +application = get_wsgi_application()