github-actions[bot] commited on
Commit
fef0469
·
1 Parent(s): 49f1559

Automated Deploy: 85675fd6acc5dd57335e405ddab2d22ef803abe4

Browse files
.dockerignore ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv
2
+ .git
3
+ .env
4
+ .env.*
5
+ .aws
6
+ .agents
7
+ .codex
8
+ .DS_Store
9
+ secrets
10
+ data
11
+ models
12
+ vendor
13
+ __pycache__
14
+ **/__pycache__
15
+ *.pyc
16
+ .pytest_cache
17
+ benchmark-results
18
+ docs
19
+ tests
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Docker Space: backend + static frontend in one GPU container.
2
+ # README.md declares sdk: docker and app_port: 7860.
3
+ FROM pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime
4
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 \
5
+ STORAGE_ROOT=/home/mod/data HF_HOME=/home/mod/data/huggingface \
6
+ APP_ENV=testing GPU_MEMORY_BUDGET_GB=12
7
+ RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg && rm -rf /var/lib/apt/lists/*
8
+ WORKDIR /opt/mod
9
+ COPY requirements.txt requirements-gpu.txt ./
10
+ RUN pip install -r requirements-gpu.txt && pip check
11
+ RUN useradd -u 1000 -m mod && mkdir -p /home/mod/data && chown mod:mod /home/mod/data
12
+
13
+ # BE: FastAPI routes, background GPU worker and model configuration.
14
+ COPY --chown=mod:mod app app
15
+ COPY --chown=mod:mod config config
16
+ # FE: FastAPI serves index.html at / and these assets at /static.
17
+ # There is no Node build or second frontend server in this application.
18
+ COPY --chown=mod:mod web web
19
+
20
+ USER mod
21
+ EXPOSE 7860
22
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
23
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/health/ready', timeout=4)"
24
+ # Keep one process so multiple processes cannot load competing GPU models.
25
+ CMD ["uvicorn", "app.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "7860", "--workers", "1", "--no-access-log"]
README.md CHANGED
@@ -1,11 +1,97 @@
1
  ---
2
- title: Mod Higgsfield
3
- emoji: 🔥
4
- colorFrom: red
5
- colorTo: purple
6
  sdk: docker
7
- pinned: false
8
- license: mit
 
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Mod Motion
3
+ emoji: 🎬
4
+ colorFrom: green
5
+ colorTo: gray
6
  sdk: docker
7
+ app_port: 7860
8
+ suggested_hardware: t4-medium
9
+ startup_duration_timeout: 1h
10
  ---
11
 
12
+ # Mod Motion — text-to-video testing
13
+
14
+ Enter a prompt, wait for the loader, then play or download the generated video. **No login, image upload, image-to-video, or frontend settings.** This supersedes the earlier A14B/multi-user implementation for the current testing phase.
15
+
16
+ The model is **Wan 2.1 T2V 1.3B**, using a fixed official Diffusers snapshot. Output is 832 × 480, 81 frames at 16 fps (about five seconds), with 50 denoising steps. There is no paid inference API or prompt-enhancement LLM.
17
+
18
+ ## Deploy on your Hugging Face T4-medium
19
+
20
+ The root `Dockerfile` packages **both backend and frontend** into one Space. FastAPI serves the page at `/`, frontend assets at `/static`, and backend endpoints at `/api/v1`, all on port **7860**. There is no separate frontend deployment, API URL configuration, CORS setup or Node build required. This follows Hugging Face's [Docker Space configuration](https://huggingface.co/docs/hub/spaces-sdks-docker).
21
+
22
+ 1. Create or use a **Docker Space** and select **T4-medium** (16 GB GPU memory, 30 GB system RAM).
23
+ 2. Upload `README.md`, `Dockerfile`, `requirements.txt`, `requirements-gpu.txt`, and the `app/`, `config/`, and `web/` directories. Alternatively push this project to the Space repository, excluding `.venv`, `data`, credentials and local caches.
24
+ 3. Let the Space build. No application secrets, user file, PostgreSQL, Redis or Compose setup is required.
25
+ 4. Open the Space. It immediately serves the frontend while the worker downloads and loads the pinned model in the background. The Generate button becomes available when loading completes.
26
+ 5. Enter a prompt and generate. The loader shows the actual denoising step when available. Generation may take a long time on T4; timing is not benchmarked yet.
27
+
28
+ **The app intentionally has no access control.** Anyone who can reach it can submit work or retrieve a known job/video URL. For your own tests, Space visibility can restrict access without adding an app login. Nothing is automatically published or deployed by this repository.
29
+
30
+ Model files download at Space startup, not Docker build time. Downloads use the Hugging Face cache, and model objects are reused between jobs. Leave enough disk space for the model snapshot, container and outputs: approximately 50 GB of usable free runtime space is a planning allowance, not a measured requirement. Default storage is `/home/mod/data`; a Space restart/rebuild can discard ephemeral files and trigger another download.
31
+
32
+ If your Space has a persistent `/data` mount, set these Space variables:
33
+
34
+ ```text
35
+ STORAGE_ROOT=/data/mod-motion
36
+ HF_HOME=/data/huggingface
37
+ ```
38
+
39
+ Keep database, outputs and cache on the same persistent host storage. Without persistence, refresh recovery works only while the stored database/output files survive.
40
+
41
+ ## Memory and T4 configuration
42
+
43
+ The default `GPU_MEMORY_BUDGET_GB=12` caps **PyTorch allocator memory at 12 GiB**; CUDA driver/context allocations sit outside that cap. This is a limit, **not a measured guarantee that every generation fits**. An allocation exceeding it fails visibly instead of silently changing quality settings.
44
+
45
+ The T4 does not provide native BF16 GPU computation. The adapter therefore keeps the model's T5 text encoder in BF16 **on CPU**, encodes prompts there, and uses FP32 transformer/VAE computation on GPU. Sequential CPU offloading and tiled VAE decoding reduce GPU memory. This is conservative about numerical range but slower than higher-memory native BF16 hardware. The 30 GB system RAM on T4-medium is the target; peak RAM and speed still need measurement on the actual Space. CPU BF16 behavior also needs validation in that environment.
46
+
47
+ Only one inference runs at a time. Up to three active/queued jobs are allowed across the whole test app. No automatic resolution, duration or step reduction occurs after an OOM.
48
+
49
+ The official Wan repository reports 8.19 GB for its own optimized 1.3B inference configuration. That number is **not a measurement of this Diffusers/T4 implementation**. This smaller testing model has not been demonstrated to match Higgsfield quality.
50
+
51
+ ## Local interface/API tests on your Mac
52
+
53
+ ```sh
54
+ python3 -m venv .venv
55
+ .venv/bin/pip install -r requirements-dev.txt
56
+ .venv/bin/python -m pytest -q
57
+ WORKER_ENABLED=false .venv/bin/uvicorn app.main:create_app --factory --port 7860
58
+ ```
59
+
60
+ Open `http://localhost:7860`. With the GPU worker disabled, the page loads but generation is unavailable; there is no simulated model or fake video path in the application.
61
+
62
+ For an Ubuntu NVIDIA machine instead of Spaces, `docker compose up --build` uses the same container. Ensure UID 1000 can write the host `data` directory. Use only one Uvicorn process and one container per GPU/data directory.
63
+
64
+ ## Minimal API
65
+
66
+ | Endpoint | Behavior |
67
+ | --- | --- |
68
+ | POST `/api/v1/generations/text-to-video` | JSON `{"prompt":"A slow camera orbit around a ceramic vase"}`; requires an `Idempotency-Key` header; returns 202 and job ID immediately |
69
+ | GET `/api/v1/generations/{id}` | Current stage, success/failure and video URLs |
70
+ | POST `/api/v1/generations/{id}/cancel` | Cancel a queued job; running cancellation unsupported |
71
+ | GET `/api/v1/artifacts/{id}` | Stream MP4; add `?download=true` for download |
72
+ | GET `/api/v1/models` | The single model and fixed preset |
73
+ | GET `/api/v1/health/workers` | `starting`, `ready`, `busy`, `failed` or `offline` |
74
+ | GET `/health/live`, `/health/ready` | HTTP liveness and database/storage checks |
75
+
76
+ API mutations and artifacts require no token. There is no history-list endpoint. Browser local storage remembers its active job ID so refreshing can resume polling; it is not an authentication mechanism. Retrying a submission after a network error reuses its idempotency key.
77
+
78
+ ## Implementation
79
+
80
+ FastAPI serves the UI and small API. A dedicated background thread runs inference; SQLite stores the job queue and results durably on the local filesystem. Atomic job claims, an exclusive process lock and a serial executor prevent overlapping inference. An independent heartbeat thread keeps worker status current. Interrupted jobs are reconciled at restart; verified completed output can be published without generating it again. The two-hour execution timeout terminates the process to stop a stuck CUDA operation; restart the Space if its supervisor does not do so automatically.
81
+
82
+ The current unauthenticated build accepts only `APP_ENV=testing`. Archived exploration/planning documents describe the earlier broader platform and do not override these deployment instructions.
83
+
84
+ ## Verification and next step
85
+
86
+ CPU tests cover no-auth routes, prompt validation, idempotency, queue limits, durable execution/recovery and error handling. GPU builds and real video inference have not been tested on this Mac. The next check is one real generation on your T4-medium, recording startup time, wall time, peak VRAM/RAM, output quality and a second generation without restarting.
87
+
88
+ See [deployment acceptance](docs/deployment-acceptance.md) and [verification status](docs/implementation-status.md).
89
+
90
+ ## Sources and licenses
91
+
92
+ - [Official Wan 2.1 model card](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B-Diffusers): Apache-2.0; model revision `0fad780a534b6463e45facd96134c9f345acfa5b`.
93
+ - [Diffusers Wan implementation](https://github.com/huggingface/diffusers/blob/v0.35.1/src/diffusers/pipelines/wan/pipeline_wan.py): Apache-2.0; pinned to Diffusers 0.35.1.
94
+ - [Diffusers memory optimizations](https://huggingface.co/docs/diffusers/v0.35.1/optimization/memory).
95
+ - [Hugging Face Docker Spaces](https://huggingface.co/docs/hub/spaces-sdks-docker) and [GPU tiers](https://huggingface.co/docs/hub/spaces-gpus).
96
+
97
+ Retain upstream notices when distributing dependencies or weights. No code from the Higgsfield or AI Video Producer Skill repositories is needed by this build.
app/__init__.py ADDED
File without changes
app/catalog.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import json
3
+ from pathlib import Path
4
+
5
+
6
+ class Catalog:
7
+ def __init__(self, path, environment='staging'):
8
+ self.data = json.loads(Path(path).read_text())
9
+ self.environment = environment
10
+ self.digest = hashlib.sha256(json.dumps(self.data, sort_keys=True).encode()).hexdigest()
11
+ if not self.data.get('profiles'):
12
+ raise ValueError('Model catalog needs profiles')
13
+
14
+ def resolve(self, model_id, profile, mode):
15
+ model = self.data['models'].get(model_id)
16
+ preset = self.data['profiles'].get(profile)
17
+ if model is None or preset is None or mode not in model['capabilities']:
18
+ raise ValueError('Unsupported model, profile or generation mode')
19
+ if profile not in model['profiles']:
20
+ raise ValueError('Profile not available for this model')
21
+ if self.environment == 'production' and not model.get('quality_approved', False):
22
+ raise ValueError('Model has not passed production quality acceptance')
23
+ revision = model['revisions'][mode]
24
+ return dict(preset, profile=profile, model_id=model_id, mode=mode,
25
+ model_revision=revision, catalog_digest=self.digest,
26
+ runtime_revision=self.data['runtime_revision'])
27
+
28
+ def public(self):
29
+ return {'models': [dict(id=k, label=v['label'], capabilities=v['capabilities'],
30
+ profiles=v['profiles'], quality_approved=v.get('quality_approved', False))
31
+ for k, v in self.data['models'].items()],
32
+ 'profiles': self.data['profiles'], 'environment': self.environment}
app/core/__init__.py ADDED
File without changes
app/core/body_limit.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from starlette.responses import JSONResponse
2
+
3
+
4
+ class BodyLimit:
5
+ """Bound body consumption before multipart parsing, including chunked uploads."""
6
+ def __init__(self, app, limit):
7
+ self.app, self.limit = app, limit
8
+
9
+ async def __call__(self, scope, receive, send):
10
+ if scope['type'] != 'http' or scope['method'] not in ('POST', 'PUT', 'PATCH'):
11
+ return await self.app(scope, receive, send)
12
+ chunks, size = [], 0
13
+ while True:
14
+ message = await receive()
15
+ if message['type'] == 'http.disconnect':
16
+ return
17
+ body = message.get('body', b'')
18
+ size += len(body)
19
+ if size > self.limit:
20
+ return await JSONResponse({'detail': 'Request too large'}, status_code=413)(scope, receive, send)
21
+ chunks.append(body)
22
+ if not message.get('more_body', False):
23
+ break
24
+ consumed = False
25
+
26
+ async def bounded_receive():
27
+ nonlocal consumed
28
+ if not consumed:
29
+ consumed = True
30
+ return {'type': 'http.request', 'body': b''.join(chunks), 'more_body': False}
31
+ return await receive()
32
+
33
+ await self.app(scope, bounded_receive, send)
app/core/config.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-host, unauthenticated text-to-video testing configuration."""
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ import os
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Settings:
9
+ database_url: str
10
+ storage_root: Path
11
+ environment: str = 'testing'
12
+ catalog_file: Path = Path('config/models.json')
13
+ pending_limit: int = 3
14
+ backlog_limit: int = 3
15
+ body_limit: int = 16_384
16
+ worker_enabled: bool = True
17
+ job_timeout_seconds: int = 7200
18
+
19
+ @classmethod
20
+ def from_env(cls):
21
+ root = Path(os.environ.get('STORAGE_ROOT', './data')).resolve()
22
+ environment = os.environ.get('APP_ENV', 'testing')
23
+ if environment != 'testing':
24
+ raise ValueError('This unauthenticated build supports APP_ENV=testing only')
25
+ return cls('sqlite:///' + str(root / 'jobs.sqlite3'), root,
26
+ catalog_file=Path(os.environ.get('CATALOG_FILE', 'config/models.json')),
27
+ worker_enabled=os.environ.get('WORKER_ENABLED', 'true').lower() == 'true',
28
+ job_timeout_seconds=int(os.environ.get('JOB_TIMEOUT_SECONDS', '7200')))
app/db.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLite transactions for the single-host testing deployment."""
2
+ from contextlib import contextmanager
3
+ from pathlib import Path
4
+ import sqlite3
5
+
6
+
7
+ class Connection:
8
+ sqlite = True
9
+
10
+ def __init__(self, raw):
11
+ self.raw = raw
12
+
13
+ def execute(self, sql, args=()):
14
+ return self.raw.execute(sql.replace('%s', '?'), args)
15
+
16
+
17
+ class Database:
18
+ def __init__(self, url):
19
+ if not url.startswith('sqlite:///'):
20
+ raise ValueError('This testing deployment uses a local SQLite database')
21
+ self.path = Path(url.removeprefix('sqlite:///'))
22
+ self.path.parent.mkdir(parents=True, exist_ok=True)
23
+
24
+ @contextmanager
25
+ def transaction(self):
26
+ raw = sqlite3.connect(self.path, timeout=15)
27
+ raw.row_factory = sqlite3.Row
28
+ raw.execute('PRAGMA foreign_keys=ON')
29
+ raw.execute('BEGIN IMMEDIATE')
30
+ try:
31
+ yield Connection(raw)
32
+ raw.commit()
33
+ except BaseException:
34
+ raw.rollback()
35
+ raise
36
+ finally:
37
+ raw.close()
38
+
39
+ def migrate(self):
40
+ with sqlite3.connect(self.path) as raw:
41
+ raw.execute('PRAGMA journal_mode=WAL')
42
+ sql = Path(__file__).with_name('schema.sql').read_text()
43
+ with self.transaction() as c:
44
+ for statement in sql.split(';'):
45
+ if statement.strip():
46
+ c.execute(statement)
47
+
48
+ @staticmethod
49
+ def submission_lock(c):
50
+ # BEGIN IMMEDIATE already serializes the quota check and insert.
51
+ pass
app/jobs.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Job policy, persistence and state transitions in one small service."""
2
+ import hashlib
3
+ import json
4
+ import secrets
5
+ import time
6
+ import uuid
7
+ from dataclasses import dataclass
8
+
9
+ from fastapi import HTTPException
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class TestUser:
14
+ user_id: str = 'test'
15
+ company_id: str = 'mod-test'
16
+
17
+
18
+ TEST_USER = TestUser()
19
+
20
+
21
+ def identifier(prefix):
22
+ return prefix + '_' + uuid.uuid4().hex
23
+
24
+
25
+ def public_job(row):
26
+ job = dict(row)
27
+ result = {key: job[key] for key in ('id', 'mode', 'status', 'stage', 'created_at', 'updated_at', 'attempt', 'prompt')}
28
+ result['type'] = result.pop('mode')
29
+ result['effective_settings'] = json.loads(job['settings'])
30
+ result['input_image_id'] = job['input_id']
31
+ result['progress'] = 1.0 if job['status'] == 'succeeded' else None
32
+ result['can_cancel'] = job['status'] == 'queued'
33
+ result['error'] = json.loads(job['error']) if job['error'] else None
34
+ result['status_url'] = '/api/v1/generations/' + job['id']
35
+ result['output'] = None if not job['output_id'] else {
36
+ 'artifact_id': job['output_id'], 'content_type': 'video/mp4',
37
+ 'preview_url': '/api/v1/artifacts/' + job['output_id'],
38
+ 'download_url': '/api/v1/artifacts/' + job['output_id'] + '?download=true'}
39
+ return result
40
+
41
+
42
+ class Jobs:
43
+ def __init__(self, db, catalog, settings):
44
+ self.db, self.catalog, self.settings = db, catalog, settings
45
+
46
+ def add_asset(self, identity, key, metadata, checksum, kind='image'):
47
+ asset_id = identifier('img' if kind == 'image' else 'vid')
48
+ with self.db.transaction() as c:
49
+ c.execute('INSERT INTO assets VALUES (%s,%s,%s,%s,%s,%s,%s,%s)',
50
+ (asset_id, identity.user_id, identity.company_id, kind, key,
51
+ json.dumps(metadata), checksum, time.time()))
52
+ return asset_id
53
+
54
+ def asset(self, identity, asset_id):
55
+ with self.db.transaction() as c:
56
+ row = c.execute('SELECT * FROM assets WHERE id=%s AND owner_id=%s AND company_id=%s',
57
+ (asset_id, identity.user_id, identity.company_id)).fetchone()
58
+ if row is None:
59
+ raise HTTPException(404, 'Asset not found')
60
+ return dict(row)
61
+
62
+ def workers(self):
63
+ with self.db.transaction() as c:
64
+ rows = c.execute('SELECT * FROM workers ORDER BY id').fetchall()
65
+ return [dict(dict(r), details=json.loads(r['details']), online=r['heartbeat'] > time.time() - 45) for r in rows]
66
+
67
+ def submit(self, identity, request, mode, key):
68
+ if not key or len(key) > 128:
69
+ raise HTTPException(422, 'An Idempotency-Key of 1–128 characters is required')
70
+ prompt = request.prompt.strip()
71
+ if mode != 'text_to_video' or not prompt:
72
+ raise HTTPException(422, 'Only text-to-video with a nonempty prompt is supported')
73
+ fingerprint = hashlib.sha256(json.dumps({'mode': mode, **request.model_dump()}, sort_keys=True).encode()).hexdigest()
74
+ with self.db.transaction() as c:
75
+ self.db.submission_lock(c)
76
+ previous = c.execute('SELECT * FROM jobs WHERE owner_id=%s AND company_id=%s AND idempotency_key=%s',
77
+ (identity.user_id, identity.company_id, key)).fetchone()
78
+ if previous:
79
+ if previous['fingerprint'] != fingerprint:
80
+ raise HTTPException(409, 'Idempotency key was already used for a different request')
81
+ return public_job(previous)
82
+ try:
83
+ effective = self.catalog.resolve(request.model_id, request.settings.profile, mode)
84
+ except ValueError as exc:
85
+ raise HTTPException(422, str(exc)) from exc
86
+ ready = c.execute("SELECT details FROM workers WHERE heartbeat>%s AND state IN ('ready','busy')", (time.time() - 45,)).fetchall()
87
+ if not any(json.loads(w['details']).get('catalog_digest') == self.catalog.digest for w in ready):
88
+ raise HTTPException(503, 'The generation worker is unavailable. Please try again later.')
89
+ rows = c.execute("SELECT owner_id,company_id FROM jobs WHERE status IN ('queued','running')").fetchall()
90
+ own = sum(r['owner_id'] == identity.user_id and r['company_id'] == identity.company_id for r in rows)
91
+ if own >= self.settings.pending_limit or len(rows) >= self.settings.backlog_limit:
92
+ raise HTTPException(429, 'Generation queue is full. Wait for an existing job to finish.')
93
+ effective['seed'] = request.settings.seed if request.settings.seed is not None else secrets.randbelow(2**31)
94
+ job_id, now = identifier('gen'), time.time()
95
+ c.execute('''INSERT INTO jobs (id,owner_id,company_id,mode,input_id,prompt,settings,fingerprint,
96
+ idempotency_key,status,stage,created_at,updated_at)
97
+ VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued','queued',%s,%s)''',
98
+ (job_id, identity.user_id, identity.company_id, mode, None,
99
+ prompt, json.dumps(effective), fingerprint, key, now, now))
100
+ # The committed queued row is the durable queue for the local worker.
101
+ return public_job(c.execute('SELECT * FROM jobs WHERE id=%s', (job_id,)).fetchone())
102
+
103
+ def get(self, identity, job_id):
104
+ with self.db.transaction() as c:
105
+ row = c.execute('SELECT * FROM jobs WHERE id=%s AND owner_id=%s AND company_id=%s',
106
+ (job_id, identity.user_id, identity.company_id)).fetchone()
107
+ if not row:
108
+ raise HTTPException(404, 'Job not found')
109
+ return public_job(row)
110
+
111
+ def listing(self, identity, limit=20, cursor=None, status=None):
112
+ with self.db.transaction() as c:
113
+ sql = 'SELECT * FROM jobs WHERE owner_id=%s AND company_id=%s'
114
+ args = [identity.user_id, identity.company_id]
115
+ if status:
116
+ sql += ' AND status=%s'
117
+ args += [status]
118
+ if cursor:
119
+ anchor = c.execute('SELECT created_at,id FROM jobs WHERE id=%s AND owner_id=%s AND company_id=%s',
120
+ (cursor, identity.user_id, identity.company_id)).fetchone()
121
+ if not anchor:
122
+ raise HTTPException(422, 'Invalid cursor')
123
+ sql += ' AND (created_at<%s OR (created_at=%s AND id<%s))'
124
+ args += [anchor['created_at'], anchor['created_at'], anchor['id']]
125
+ rows = c.execute(sql + ' ORDER BY created_at DESC,id DESC LIMIT %s', (*args, limit + 1)).fetchall()
126
+ return {'items': [public_job(r) for r in rows[:limit]],
127
+ 'next_cursor': rows[limit-1]['id'] if len(rows) > limit else None}
128
+
129
+ def cancel(self, identity, job_id):
130
+ with self.db.transaction() as c:
131
+ row = c.execute("UPDATE jobs SET status='cancelled',stage='cancelled',updated_at=%s WHERE id=%s AND owner_id=%s AND company_id=%s AND status='queued' RETURNING *",
132
+ (time.time(), job_id, identity.user_id, identity.company_id)).fetchone()
133
+ if row:
134
+ return public_job(row)
135
+ current = self.get(identity, job_id)
136
+ if current['status'] == 'cancelled':
137
+ return current
138
+ raise HTTPException(409, 'Only queued jobs can be cancelled')
app/main.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """No-auth testing API. One process; its background worker serializes inference."""
2
+ from contextlib import asynccontextmanager
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ import secrets
7
+ import time
8
+
9
+ from fastapi import FastAPI, Header, HTTPException, Response
10
+ from fastapi.responses import FileResponse, JSONResponse
11
+ from fastapi.staticfiles import StaticFiles
12
+
13
+ from app.catalog import Catalog
14
+ from app.core.body_limit import BodyLimit
15
+ from app.core.config import Settings
16
+ from app.db import Database
17
+ from app.jobs import Jobs, TEST_USER
18
+ from app.schemas import GenerationRequest
19
+ from app.storage import Storage
20
+
21
+ log = logging.getLogger('mod.api')
22
+
23
+
24
+ def create_app(settings=None, db=None, runtime=None):
25
+ settings = settings or Settings.from_env()
26
+ if settings.environment != 'testing':
27
+ raise ValueError('No-auth application is for testing only')
28
+ storage = Storage(settings.storage_root)
29
+ database = db or Database(settings.database_url)
30
+ catalog = Catalog(settings.catalog_file, settings.environment)
31
+ jobs = Jobs(database, catalog, settings)
32
+ if runtime is None and settings.worker_enabled:
33
+ from app.worker import LocalRuntime
34
+ runtime = LocalRuntime(database, storage, catalog, settings)
35
+
36
+ @asynccontextmanager
37
+ async def lifespan(app):
38
+ database.migrate()
39
+ if runtime:
40
+ runtime.start()
41
+ try:
42
+ yield
43
+ finally:
44
+ if runtime:
45
+ runtime.close()
46
+
47
+ app = FastAPI(title='Mod Motion · Text-to-video test', version='0.2.0', lifespan=lifespan)
48
+ app.add_middleware(BodyLimit, limit=settings.body_limit)
49
+ app.state.jobs, app.state.storage = jobs, storage
50
+
51
+ @app.middleware('http')
52
+ async def headers(request, call_next):
53
+ request_id, started = secrets.token_hex(12), time.monotonic()
54
+ try:
55
+ response = await call_next(request)
56
+ except Exception:
57
+ log.exception('request_failed id=%s', request_id)
58
+ response = JSONResponse({'detail': 'The service could not complete the request',
59
+ 'request_id': request_id}, status_code=503)
60
+ response.headers.update({'X-Request-ID': request_id, 'X-Content-Type-Options': 'nosniff',
61
+ 'Referrer-Policy': 'no-referrer', 'Cache-Control': 'no-store',
62
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; media-src 'self'; base-uri 'self'; form-action 'self'"})
63
+ log.info('request id=%s method=%s status=%s ms=%.1f', request_id, request.method,
64
+ response.status_code, (time.monotonic()-started)*1000)
65
+ return response
66
+
67
+ @app.post('/api/v1/generations/text-to-video', status_code=202)
68
+ def t2v(body: GenerationRequest, response: Response, idempotency_key: str = Header()):
69
+ result = jobs.submit(TEST_USER, body, 'text_to_video', idempotency_key)
70
+ response.headers['Location'] = result['status_url']
71
+ return result
72
+
73
+ @app.get('/api/v1/generations/{job_id}')
74
+ def get_job(job_id: str):
75
+ return jobs.get(TEST_USER, job_id)
76
+
77
+ @app.post('/api/v1/generations/{job_id}/cancel')
78
+ def cancel(job_id: str):
79
+ return jobs.cancel(TEST_USER, job_id)
80
+
81
+ @app.get('/api/v1/artifacts/{asset_id}')
82
+ def artifact(asset_id: str, download: bool = False):
83
+ asset = jobs.asset(TEST_USER, asset_id)
84
+ path = storage.path(asset['storage_key'])
85
+ if asset['kind'] != 'video' or not path.is_file():
86
+ raise HTTPException(404, 'Video not found')
87
+ return FileResponse(path, media_type=json.loads(asset['metadata'])['content_type'],
88
+ filename=f'mod-motion-{asset_id}.mp4' if download else None,
89
+ content_disposition_type='attachment' if download else 'inline')
90
+
91
+ @app.get('/api/v1/models')
92
+ def models():
93
+ return catalog.public()
94
+
95
+ @app.get('/api/v1/health/workers')
96
+ def workers():
97
+ rows = jobs.workers()
98
+ matching = [w for w in rows if w['online'] and w['details'].get('catalog_digest') == catalog.digest]
99
+ available = any(w['state'] in ('ready', 'busy') for w in matching)
100
+ state = matching[0]['state'] if matching else 'offline'
101
+ return {'available': available, 'state': state}
102
+
103
+ @app.get('/health/live')
104
+ def live():
105
+ return {'status': 'ok'}
106
+
107
+ @app.get('/health/ready')
108
+ def ready():
109
+ try:
110
+ with database.transaction() as c:
111
+ c.execute('SELECT id FROM jobs LIMIT 1')
112
+ storage.check()
113
+ except Exception:
114
+ return JSONResponse({'status': 'unavailable'}, status_code=503)
115
+ return {'status': 'ready'}
116
+
117
+ web = Path(__file__).parent.parent / 'web'
118
+ app.mount('/static', StaticFiles(directory=web), name='static')
119
+
120
+ @app.get('/', include_in_schema=False)
121
+ def home():
122
+ return FileResponse(web / 'index.html')
123
+
124
+ return app
app/providers/__init__.py ADDED
File without changes
app/providers/wan.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wan 2.1 1.3B Diffusers adapter for a single T4. GPU imports stay in the worker."""
2
+ import gc
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import subprocess
8
+
9
+ def sha256_file(path):
10
+ digest = hashlib.sha256()
11
+ with Path(path).open('rb') as f:
12
+ for chunk in iter(lambda: f.read(1024 * 1024), b''):
13
+ digest.update(chunk)
14
+ return digest.hexdigest()
15
+
16
+
17
+ def verify_weights(directory, revision):
18
+ directory = Path(directory)
19
+ manifest = json.loads((directory / 'mod-manifest.json').read_text())
20
+ if manifest['revision'] != revision or not manifest['files']:
21
+ raise ValueError('Weight manifest does not match the approved catalog')
22
+ for filename, checksum in manifest['files'].items():
23
+ path = (directory / filename).resolve()
24
+ if not path.is_relative_to(directory.resolve()) or sha256_file(path) != checksum:
25
+ raise ValueError('Weight file integrity check failed')
26
+
27
+
28
+ class WanProvider:
29
+ def __init__(self, catalog):
30
+ self.catalog = catalog
31
+ self.pipeline = None
32
+ self.text_encoder = None
33
+ self.loaded_mode = None
34
+ self.resolved_revision = None
35
+
36
+ def preflight(self):
37
+ import torch
38
+ if not torch.cuda.is_available():
39
+ raise RuntimeError('CUDA GPU required. Select T4-medium in Space hardware settings.')
40
+ total = torch.cuda.get_device_properties(0).total_memory
41
+ budget = float(os.environ.get('GPU_MEMORY_BUDGET_GB', '12')) * 1024**3
42
+ if not 0 < budget <= total:
43
+ raise ValueError('GPU memory budget must be positive and fit the selected GPU')
44
+ # Bounds PyTorch allocations, not driver/context memory. OOM is reported, not hidden.
45
+ torch.cuda.set_per_process_memory_fraction(min(budget / total, 0.95), device=0)
46
+ self.load('text_to_video')
47
+
48
+ def load(self, mode):
49
+ if mode != 'text_to_video':
50
+ raise ValueError('This testing adapter supports text-to-video only')
51
+ if self.pipeline is not None:
52
+ return
53
+ import torch
54
+ from diffusers import WanPipeline, UniPCMultistepScheduler
55
+ from transformers import UMT5EncoderModel
56
+ from huggingface_hub import snapshot_download
57
+ model = self.catalog.data['models']['wan21-1.3b']
58
+ revision = model['revisions']['text_to_video']
59
+ self.reset()
60
+ # Download once at runtime, then reuse the Hugging Face cache. No custom remote code.
61
+ snapshot = snapshot_download(model['repository'], revision=revision,
62
+ allow_patterns=['*.json', '*.safetensors', '*.model', '*.txt'])
63
+ self.resolved_revision = Path(snapshot).name
64
+ # T4 lacks native BF16 GPU support. Keep T5 in BF16 on CPU, where PyTorch
65
+ # supports these ops, and run transformer/VAE in FP32 on GPU for numerical range.
66
+ self.text_encoder = UMT5EncoderModel.from_pretrained(
67
+ snapshot, subfolder='text_encoder', torch_dtype=torch.bfloat16,
68
+ low_cpu_mem_usage=True, local_files_only=True, use_safetensors=True).eval()
69
+ pipe = WanPipeline.from_pretrained(snapshot, text_encoder=None, torch_dtype=torch.float32,
70
+ low_cpu_mem_usage=True, local_files_only=True,
71
+ use_safetensors=True)
72
+ preset = self.catalog.data['profiles']['landscape-480p']
73
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config,
74
+ flow_shift=preset['flow_shift'])
75
+ pipe.vae.enable_tiling()
76
+ # Offload submodules; never move the full pipeline or T5 encoder onto the T4.
77
+ pipe.enable_sequential_cpu_offload(gpu_id=0)
78
+ self.pipeline, self.loaded_mode = pipe, mode
79
+
80
+ def reset(self):
81
+ self.pipeline, self.text_encoder, self.loaded_mode = None, None, None
82
+ gc.collect()
83
+ import torch
84
+ if torch.cuda.is_available():
85
+ torch.cuda.empty_cache()
86
+
87
+ def generate(self, job, image_path, output_path, stage):
88
+ import torch
89
+ from diffusers.utils import export_to_video
90
+ settings = job['effective_settings']
91
+ if image_path is not None or job['mode'] != 'text_to_video':
92
+ raise ValueError('Image conditioning is not supported')
93
+ if settings['catalog_digest'] != self.catalog.digest:
94
+ raise ValueError('Queued job uses a different model catalog')
95
+ stage('loading_model')
96
+ self.load('text_to_video')
97
+ pipe = self.pipeline
98
+ stage('encoding_prompt')
99
+ # Use Diffusers' tokenizer/prompt processing, but keep the encoder on CPU.
100
+ pipe.register_modules(text_encoder=self.text_encoder)
101
+ try:
102
+ with torch.inference_mode():
103
+ embeds, negative = pipe.encode_prompt(
104
+ prompt=job['prompt'], negative_prompt='blurry, distorted, low quality, subtitles, watermark',
105
+ device=torch.device('cpu'), do_classifier_free_guidance=True,
106
+ max_sequence_length=512)
107
+ finally:
108
+ pipe.register_modules(text_encoder=None)
109
+ stage('generating')
110
+ torch.cuda.reset_peak_memory_stats()
111
+ def step_callback(pipeline, step, timestep, callback_kwargs):
112
+ stage(f'generating_{step + 1}_of_{settings["steps"]}')
113
+ return callback_kwargs
114
+ with torch.inference_mode():
115
+ frames = pipe(prompt_embeds=embeds.to(device='cuda', dtype=torch.float32),
116
+ negative_prompt_embeds=negative.to(device='cuda', dtype=torch.float32),
117
+ height=settings['height'], width=settings['width'],
118
+ num_frames=settings['num_frames'], num_inference_steps=settings['steps'],
119
+ guidance_scale=settings['guidance_scale'],
120
+ generator=torch.Generator(device='cpu').manual_seed(settings['seed']),
121
+ callback_on_step_end=step_callback, output_type='np').frames[0]
122
+ import numpy as np
123
+ if len(frames) != settings['num_frames'] or not np.isfinite(frames).all():
124
+ raise RuntimeError('Model returned invalid video frames')
125
+ stage('encoding_video')
126
+ output_path.parent.mkdir(parents=True, exist_ok=True)
127
+ export_to_video(frames, str(output_path), fps=settings['fps'], quality=8, macro_block_size=1)
128
+ metadata = probe_video(output_path)
129
+ metadata.update(peak_vram_bytes=torch.cuda.max_memory_allocated(),
130
+ model_revision=self.resolved_revision, fps=settings['fps'])
131
+ return metadata
132
+
133
+
134
+ def probe_video(path):
135
+ result = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
136
+ '-show_entries', 'stream=width,height,nb_frames:format=duration',
137
+ '-of', 'json', str(path)], check=True, capture_output=True, text=True, timeout=30)
138
+ data = json.loads(result.stdout)
139
+ stream = data['streams'][0]
140
+ duration = float(data['format']['duration'])
141
+ if duration <= 0 or Path(path).stat().st_size == 0:
142
+ raise ValueError('Invalid video output')
143
+ return {'content_type': 'video/mp4', 'width': stream['width'], 'height': stream['height'],
144
+ 'duration_seconds': duration, 'size_bytes': Path(path).stat().st_size}
app/schema.sql ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CREATE TABLE IF NOT EXISTS assets (
2
+ id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, company_id TEXT NOT NULL,
3
+ kind TEXT NOT NULL CHECK (kind IN ('image','video')), storage_key TEXT NOT NULL UNIQUE,
4
+ metadata TEXT NOT NULL, checksum TEXT NOT NULL, created_at DOUBLE PRECISION NOT NULL
5
+ );
6
+ CREATE TABLE IF NOT EXISTS jobs (
7
+ id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, company_id TEXT NOT NULL,
8
+ mode TEXT NOT NULL CHECK (mode IN ('text_to_video','image_to_video')),
9
+ input_id TEXT REFERENCES assets(id), prompt TEXT NOT NULL, settings TEXT NOT NULL,
10
+ fingerprint TEXT NOT NULL, idempotency_key TEXT NOT NULL,
11
+ status TEXT NOT NULL CHECK (status IN ('queued','running','succeeded','failed','cancelled')),
12
+ stage TEXT NOT NULL, created_at DOUBLE PRECISION NOT NULL, updated_at DOUBLE PRECISION NOT NULL,
13
+ output_id TEXT REFERENCES assets(id), error TEXT, attempt INTEGER NOT NULL DEFAULT 0,
14
+ execution_token TEXT, worker_id TEXT,
15
+ UNIQUE (owner_id, company_id, idempotency_key)
16
+ );
17
+ CREATE INDEX IF NOT EXISTS job_owner_history ON jobs(company_id, owner_id, created_at, id);
18
+ CREATE INDEX IF NOT EXISTS job_status ON jobs(status);
19
+ CREATE TABLE IF NOT EXISTS attempts (
20
+ token TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id), worker_id TEXT NOT NULL,
21
+ started_at DOUBLE PRECISION NOT NULL, finished_at DOUBLE PRECISION, outcome TEXT, details TEXT
22
+ );
23
+ CREATE TABLE IF NOT EXISTS workers (
24
+ id TEXT PRIMARY KEY, heartbeat DOUBLE PRECISION NOT NULL,
25
+ state TEXT NOT NULL, loaded_model TEXT, details TEXT NOT NULL
26
+ );
app/schemas.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
2
+
3
+
4
+ class GenerationSettings(BaseModel):
5
+ model_config = ConfigDict(extra='forbid')
6
+ profile: str = 'landscape-480p'
7
+ seed: int | None = Field(default=None, ge=0, le=2**31 - 1)
8
+
9
+
10
+ class GenerationRequest(BaseModel):
11
+ model_config = ConfigDict(extra='forbid')
12
+ prompt: str = Field(min_length=1, max_length=2000)
13
+ model_id: str = 'wan21-1.3b'
14
+ settings: GenerationSettings = Field(default_factory=GenerationSettings)
15
+
16
+ @field_validator('prompt')
17
+ @classmethod
18
+ def nonblank(cls, value):
19
+ if not value.strip():
20
+ raise ValueError('Enter a prompt')
21
+ return value.strip()
app/storage.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import io
3
+ import os
4
+ from pathlib import Path
5
+ import secrets
6
+ import warnings
7
+
8
+ from PIL import Image, ImageOps, UnidentifiedImageError
9
+
10
+
11
+ class InvalidImage(ValueError):
12
+ pass
13
+
14
+
15
+ def normalize_image(content, pixel_limit=20_000_000):
16
+ try:
17
+ with warnings.catch_warnings():
18
+ warnings.simplefilter('error', Image.DecompressionBombWarning)
19
+ with Image.open(io.BytesIO(content)) as source:
20
+ if source.format not in ('JPEG', 'PNG', 'WEBP'):
21
+ raise InvalidImage('Use JPEG, PNG or static WebP')
22
+ if getattr(source, 'n_frames', 1) != 1:
23
+ raise InvalidImage('Animated images are not supported')
24
+ if source.width * source.height > pixel_limit or min(source.size) < 32:
25
+ raise InvalidImage('Image must be at least 32px per side and at most 20 megapixels')
26
+ source.load()
27
+ image = ImageOps.exif_transpose(source).convert('RGBA')
28
+ background = Image.new('RGBA', image.size, (255, 255, 255, 255))
29
+ background.alpha_composite(image)
30
+ clean = background.convert('RGB')
31
+ output = io.BytesIO()
32
+ clean.save(output, format='PNG')
33
+ return output.getvalue(), {'width': clean.width, 'height': clean.height,
34
+ 'content_type': 'image/png'}
35
+ except (UnidentifiedImageError, OSError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
36
+ raise InvalidImage('Image could not be safely decoded') from exc
37
+
38
+
39
+ class Storage:
40
+ def __init__(self, root):
41
+ self.root = Path(root).resolve()
42
+ self.root.mkdir(parents=True, exist_ok=True)
43
+
44
+ def path(self, key):
45
+ p = (self.root / key).resolve()
46
+ if not p.is_relative_to(self.root) or p == self.root:
47
+ raise ValueError('Invalid storage key')
48
+ return p
49
+
50
+ def write(self, key, data):
51
+ path = self.path(key)
52
+ path.parent.mkdir(parents=True, exist_ok=True)
53
+ temp = path.with_name(path.name + '.' + secrets.token_hex(8) + '.tmp')
54
+ try:
55
+ with temp.open('xb') as f:
56
+ f.write(data)
57
+ f.flush()
58
+ os.fsync(f.fileno())
59
+ os.replace(temp, path)
60
+ finally:
61
+ temp.unlink(missing_ok=True)
62
+ return hashlib.sha256(data).hexdigest()
63
+
64
+ def check(self):
65
+ key = '.health/' + secrets.token_hex(8)
66
+ self.write(key, b'ok')
67
+ self.path(key).unlink()
app/worker.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A persistent, serial GPU worker with explicit restart reconciliation."""
2
+ import fcntl
3
+ import json
4
+ import logging
5
+ import os
6
+ import threading
7
+ import time
8
+
9
+ from app.catalog import Catalog
10
+ from app.core.config import Settings
11
+ from app.db import Database
12
+ from app.jobs import identifier
13
+ from app.providers.wan import WanProvider, sha256_file
14
+ from app.storage import Storage
15
+
16
+ log = logging.getLogger('mod.worker')
17
+
18
+
19
+ class Worker:
20
+ def __init__(self, db, storage, catalog, provider, worker_id):
21
+ self.db, self.storage, self.catalog = db, storage, catalog
22
+ self.provider, self.worker_id = provider, worker_id
23
+ self.state, self.current, self.started = 'starting', None, None
24
+ self.lock = threading.Lock()
25
+
26
+ def heartbeat(self):
27
+ with self.db.transaction() as c:
28
+ c.execute('''INSERT INTO workers(id,heartbeat,state,loaded_model,details) VALUES(%s,%s,%s,%s,%s)
29
+ ON CONFLICT(id) DO UPDATE SET heartbeat=excluded.heartbeat,state=excluded.state,
30
+ loaded_model=excluded.loaded_model,details=excluded.details''',
31
+ (self.worker_id, time.time(), self.state, self.provider.loaded_mode,
32
+ json.dumps({'catalog_digest': self.catalog.digest, 'job_id': self.current})))
33
+
34
+ def stage(self, job_id, token, value):
35
+ with self.db.transaction() as c:
36
+ result = c.execute("UPDATE jobs SET stage=%s,updated_at=%s WHERE id=%s AND execution_token=%s AND status='running'",
37
+ (value, time.time(), job_id, token))
38
+ if result.rowcount != 1:
39
+ raise RuntimeError('Execution attempt no longer owns this job')
40
+
41
+ def fail(self, job_id, token, code, message):
42
+ with self.db.transaction() as c:
43
+ c.execute("UPDATE jobs SET status='failed',stage='failed',error=%s,updated_at=%s WHERE id=%s AND execution_token=%s AND status='running'",
44
+ (json.dumps({'code': code, 'message': message, 'retryable': False}), time.time(), job_id, token))
45
+ c.execute("UPDATE attempts SET finished_at=%s,outcome='failed',details=%s WHERE token=%s",
46
+ (time.time(), code, token))
47
+
48
+ def complete(self, job, token, key, metadata, checksum):
49
+ with self.db.transaction() as c:
50
+ # Lock the job before publishing; stale attempts may not create a public artifact.
51
+ row = c.execute('SELECT status,execution_token FROM jobs WHERE id=%s' + ('' if c.sqlite else ' FOR UPDATE'), (job['id'],)).fetchone()
52
+ if not row or row['status'] != 'running' or row['execution_token'] != token:
53
+ return
54
+ asset_id = identifier('vid')
55
+ c.execute('INSERT INTO assets VALUES(%s,%s,%s,%s,%s,%s,%s,%s)',
56
+ (asset_id, job['owner_id'], job['company_id'], 'video', key,
57
+ json.dumps(metadata), checksum, time.time()))
58
+ c.execute("UPDATE jobs SET status='succeeded',stage='completed',output_id=%s,updated_at=%s WHERE id=%s AND execution_token=%s",
59
+ (asset_id, time.time(), job['id'], token))
60
+ c.execute("UPDATE attempts SET finished_at=%s,outcome='succeeded',details=%s WHERE token=%s",
61
+ (time.time(), json.dumps(metadata), token))
62
+
63
+ def recover(self):
64
+ """Call only after acquiring exclusive deployment lock; old process must be stopped."""
65
+ with self.db.transaction() as c:
66
+ rows = c.execute("SELECT * FROM jobs WHERE worker_id=%s AND status='running'", (self.worker_id,)).fetchall()
67
+ for row in rows:
68
+ job = dict(row)
69
+ token = job['execution_token']
70
+ key = f"outputs/{job['id']}/{token}.mp4"
71
+ manifest = self.storage.path(key + '.json')
72
+ if manifest.exists():
73
+ try:
74
+ data = json.loads(manifest.read_text())
75
+ valid = data['token'] == token and sha256_file(self.storage.path(key)) == data['checksum']
76
+ except (OSError, ValueError, KeyError):
77
+ valid = False
78
+ if valid:
79
+ self.complete(job, token, key, data['metadata'], data['checksum'])
80
+ continue
81
+ self.fail(job['id'], token, 'WORKER_INTERRUPTED', 'The worker restarted before completion. Submit a new generation to retry.')
82
+
83
+ def execute(self, job_id):
84
+ with self.lock:
85
+ self._execute(job_id)
86
+
87
+ def _execute(self, job_id):
88
+ token = identifier('attempt')
89
+ with self.db.transaction() as c:
90
+ row = c.execute("UPDATE jobs SET status='running',stage='preparing',execution_token=%s,worker_id=%s,attempt=attempt+1,updated_at=%s WHERE id=%s AND status='queued' RETURNING *",
91
+ (token, self.worker_id, time.time(), job_id)).fetchone()
92
+ if not row:
93
+ return # Cancelled or already claimed; queue redelivery is harmless.
94
+ job = dict(row)
95
+ c.execute('INSERT INTO attempts(token,job_id,worker_id,started_at) VALUES(%s,%s,%s,%s)',
96
+ (token, job_id, self.worker_id, time.time()))
97
+ self.state, self.current, self.started = 'busy', job_id, time.monotonic()
98
+ job['effective_settings'] = json.loads(job['settings'])
99
+ try:
100
+ if job['effective_settings']['catalog_digest'] != self.catalog.digest:
101
+ raise ValueError('Catalog changed; resubmit under current settings')
102
+ image_path = None
103
+ if job['input_id']:
104
+ with self.db.transaction() as c:
105
+ asset = c.execute('SELECT * FROM assets WHERE id=%s AND owner_id=%s AND company_id=%s',
106
+ (job['input_id'], job['owner_id'], job['company_id'])).fetchone()
107
+ if asset is None:
108
+ raise ValueError('Input image missing')
109
+ image_path = self.storage.path(asset['storage_key'])
110
+ if sha256_file(image_path) != asset['checksum']:
111
+ raise ValueError('Input integrity failure')
112
+ key = f'outputs/{job_id}/{token}.mp4'
113
+ output = self.storage.path(key)
114
+ metadata = self.provider.generate(job, image_path, output, lambda s: self.stage(job_id, token, s))
115
+ self.stage(job_id, token, 'saving')
116
+ with output.open('rb') as f:
117
+ os.fsync(f.fileno())
118
+ checksum = sha256_file(output)
119
+ metadata['elapsed_seconds'] = time.monotonic() - self.started
120
+ manifest = json.dumps({'token': token, 'metadata': metadata, 'checksum': checksum}).encode()
121
+ # Bounded persistence retries reuse the video; never rerun expensive inference here.
122
+ for attempt in range(3):
123
+ try:
124
+ self.storage.write(key + '.json', manifest)
125
+ self.complete(job, token, key, metadata, checksum)
126
+ break
127
+ except Exception:
128
+ if attempt == 2:
129
+ raise
130
+ time.sleep(2 ** attempt)
131
+ log.info('generation_succeeded job=%s attempt=%s', job_id, token)
132
+ except Exception as exc:
133
+ log.exception('generation_failed job=%s attempt=%s', job_id, token)
134
+ oom = 'OutOfMemory' in type(exc).__name__ or 'out of memory' in str(exc).lower()
135
+ self.fail(job_id, token, 'GPU_OUT_OF_MEMORY' if oom else 'GENERATION_FAILED',
136
+ 'The worker exhausted GPU memory.' if oom else 'Generation failed. An operator can inspect the job diagnostics.')
137
+ if oom:
138
+ self.provider.reset()
139
+ finally:
140
+ self.current, self.started, self.state = None, None, 'ready'
141
+
142
+
143
+
144
+ class LocalRuntime:
145
+ """One background executor with a durable SQLite queue; no external broker."""
146
+ def __init__(self, db, storage, catalog, settings, provider=None):
147
+ self.db, self.storage, self.settings = db, storage, settings
148
+ self.worker = Worker(db, storage, catalog, provider or WanProvider(catalog), 'gpu-1')
149
+ self.stop = threading.Event()
150
+ self.lockfile = None
151
+ self.thread = None
152
+ self.monitor = None
153
+
154
+ def start(self):
155
+ path = self.storage.path('locks/gpu-0.lock')
156
+ path.parent.mkdir(parents=True, exist_ok=True)
157
+ self.lockfile = path.open('a')
158
+ try:
159
+ fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
160
+ except OSError:
161
+ self.lockfile.close()
162
+ raise RuntimeError('Only one application process may own this GPU/storage directory') from None
163
+ self.worker.recover()
164
+ self.worker.heartbeat()
165
+ self.monitor = threading.Thread(target=self._monitor, daemon=True, name='mod-heartbeat')
166
+ self.thread = threading.Thread(target=self._run, daemon=True, name='mod-inference')
167
+ self.monitor.start()
168
+ self.thread.start()
169
+
170
+ def _monitor(self):
171
+ while not self.stop.wait(5):
172
+ if (self.worker.started is not None and
173
+ time.monotonic() - self.worker.started > self.settings.job_timeout_seconds):
174
+ log.error('generation_timeout; terminating process for safe restart')
175
+ os._exit(70)
176
+ try:
177
+ self.worker.heartbeat()
178
+ except Exception:
179
+ log.exception('worker_heartbeat_failed')
180
+
181
+ def _run(self):
182
+ try:
183
+ self.worker.provider.preflight()
184
+ self.worker.state = 'ready'
185
+ self.worker.heartbeat()
186
+ while not self.stop.is_set():
187
+ with self.db.transaction() as c:
188
+ row = c.execute("SELECT id FROM jobs WHERE status='queued' ORDER BY created_at,id LIMIT 1").fetchone()
189
+ if row:
190
+ self.worker.execute(row['id'])
191
+ self.worker.heartbeat()
192
+ else:
193
+ self.stop.wait(0.5)
194
+ except Exception:
195
+ log.exception('worker_startup_or_queue_failed')
196
+ self.worker.state = 'failed'
197
+ try:
198
+ self.worker.heartbeat()
199
+ except Exception:
200
+ log.exception('worker_failure_status_unavailable')
201
+
202
+ def close(self):
203
+ self.stop.set()
204
+ if self.thread:
205
+ self.thread.join(timeout=5)
206
+ if self.monitor:
207
+ self.monitor.join(timeout=6)
208
+ # Never release ownership while a CUDA call remains active in a thread.
209
+ if self.thread and self.thread.is_alive():
210
+ log.warning('inference still running at shutdown; lock held until process exit')
211
+ return
212
+ self.worker.state = 'offline'
213
+ self.worker.heartbeat()
214
+ if self.lockfile:
215
+ self.lockfile.close()
config/models.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "runtime_revision": "diffusers-0.35.1",
3
+ "models": {
4
+ "wan21-1.3b": {
5
+ "label": "Wan 2.1 · 1.3B",
6
+ "repository": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
7
+ "capabilities": ["text_to_video"],
8
+ "profiles": ["landscape-480p"],
9
+ "quality_approved": false,
10
+ "revisions": {"text_to_video": "0fad780a534b6463e45facd96134c9f345acfa5b"}
11
+ }
12
+ },
13
+ "profiles": {
14
+ "landscape-480p": {
15
+ "label": "480p · approximately 5 seconds",
16
+ "width": 832, "height": 480, "num_frames": 81, "fps": 16,
17
+ "steps": 50, "guidance_scale": 5.0, "flow_shift": 3.0
18
+ }
19
+ }
20
+ }
requirements-gpu.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -r requirements.txt
2
+ torch==2.6.0
3
+ diffusers==0.35.1
4
+ transformers==4.51.3
5
+ accelerate==1.10.1
6
+ huggingface-hub==0.34.4
7
+ safetensors==0.6.2
8
+ sentencepiece==0.2.1
9
+ ftfy==6.3.1
10
+ numpy==1.26.4
11
+ imageio==2.37.0
12
+ imageio-ffmpeg==0.6.0
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi==0.135.3
2
+ uvicorn==0.41.0
3
+ pydantic==2.12.5
4
+ Pillow==12.3.0
web/app.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const $ = id => document.getElementById(id);
3
+ let jobId = null, pending = null, submitting = false, available = false;
4
+ const activeKey = 'mod-motion-active-job';
5
+ function saveJob(id) { try { if (id) localStorage.setItem(activeKey, id); else localStorage.removeItem(activeKey); } catch (_) {} }
6
+ function error(message) { $('error').textContent = message; $('error').hidden = !message; }
7
+ function loading(stage, detail) { $('loading').hidden = false; $('stage').textContent = stage; $('detail').textContent = detail; }
8
+ function controls() { $('submit').disabled = submitting || Boolean(jobId) || !available; }
9
+ async function api(path, options = {}) {
10
+ const response = await fetch('/api/v1' + path, {...options, signal: AbortSignal.timeout(20000), headers: {'Content-Type':'application/json', ...options.headers}});
11
+ const data = await response.json();
12
+ if (!response.ok) { const e = new Error(typeof data.detail === 'string' ? data.detail : 'Please check your prompt and try again.'); e.status = response.status; throw e; }
13
+ return data;
14
+ }
15
+ function display(job) {
16
+ if (job.status === 'succeeded') {
17
+ $('loading').hidden = true; $('result').hidden = false; $('video').src = job.output.preview_url;
18
+ $('download').href = job.output.download_url; jobId = null; saveJob(null); error('');
19
+ } else if (job.status === 'failed' || job.status === 'cancelled') {
20
+ $('loading').hidden = true; error(job.error?.message || 'Generation cancelled. You can try again.'); jobId = null; saveJob(null);
21
+ } else {
22
+ const match = /^generating_(\d+)_of_(\d+)$/.exec(job.stage);
23
+ const label = match ? `Generating your video · step ${match[1]} of ${match[2]}` : ({queued:'Your video is queued…',preparing:'Preparing your video…',loading_model:'Loading the video model…',encoding_prompt:'Reading your prompt…',generating:'Generating your video…',encoding_video:'Encoding your video…',saving:'Saving your video…'}[job.stage] || 'Working on your video…');
24
+ loading(label, 'Video generation can take several minutes. You can return to this page later.');
25
+ }
26
+ controls();
27
+ }
28
+ $('generate').onsubmit = async event => {
29
+ event.preventDefault(); if (submitting || jobId || !available) return;
30
+ const prompt = $('prompt').value.trim(); if (!prompt) return error('Enter a prompt first.');
31
+ const body = JSON.stringify({prompt});
32
+ if (!pending || pending.body !== body) pending = {body, key:crypto.randomUUID()};
33
+ submitting = true; controls(); error(''); $('result').hidden = true; $('video').pause();
34
+ loading('Submitting your prompt…', 'Your video will appear here when it is ready.');
35
+ try {
36
+ const job = await api('/generations/text-to-video', {method:'POST',headers:{'Idempotency-Key':pending.key},body});
37
+ jobId = job.id; saveJob(jobId); pending = null; display(job);
38
+ } catch(e) {
39
+ // Keep the key after uncertain network failures so a retry cannot create a duplicate.
40
+ if (e.status && e.status < 500) pending = null;
41
+ $('loading').hidden = true; error(e.message);
42
+ } finally { submitting = false; controls(); }
43
+ };
44
+ async function poll() {
45
+ try {
46
+ if (jobId) {
47
+ try { display(await api('/generations/' + jobId)); }
48
+ catch(e) { if (e.status === 404) { jobId = null; saveJob(null); $('loading').hidden = true; error('This generation is no longer available. You can generate another video.'); } else throw e; }
49
+ }
50
+ if (!jobId && !submitting) {
51
+ const health = await api('/health/workers'); available = health.available;
52
+ if (jobId || submitting) return;
53
+ if ($('error').textContent === 'Connection interrupted. Reconnecting automatically…') error('');
54
+ if (available) { $('loading').hidden = true; }
55
+ else if (health.state === 'failed') { $('loading').hidden = true; error('The model could not start. Check the Space logs, then restart the Space.'); }
56
+ else { loading('Preparing the generator…', 'The first startup downloads and loads the model. Please keep this page open.'); }
57
+ }
58
+ } catch(e) { error('Connection interrupted. Reconnecting automatically…'); }
59
+ finally { controls(); setTimeout(poll, 3000); }
60
+ }
61
+ try { jobId = localStorage.getItem(activeKey); } catch (_) {}
62
+ controls(); poll();
web/index.html ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Mod Motion</title><link rel="stylesheet" href="/static/style.css"><script src="/static/app.js" defer></script></head>
3
+ <body><header><a class="brand" href="/">mod<span>motion</span></a><span class="tag">TEXT TO VIDEO</span></header>
4
+ <main><div class="eyebrow">A MOD PRODUCT</div><h1>A thought.<br>A moving picture.</h1><p class="intro">Describe a scene. Watch it come to life.</p>
5
+ <section class="composer"><form id="generate"><label for="prompt">Your scene</label><textarea id="prompt" maxlength="2000" required placeholder="A slow camera move through a sunlit room. Linen curtains drift in the breeze…" rows="5"></textarea><div class="controls"><span class="hint">480p · approximately 5 seconds</span><button id="submit" type="submit" disabled>Generate video ↗</button></div></form></section>
6
+ <div id="loading" class="loading" role="status" aria-live="polite"><span class="spinner" aria-hidden="true"></span><div><p id="stage">Connecting to the generator…</p><small id="detail">The first startup downloads and loads the model.</small></div></div>
7
+ <p id="error" role="alert" hidden></p>
8
+ <section id="result" hidden aria-label="Generated video"><video id="video" controls playsinline></video><a id="download" class="button">Download video ↓</a></section>
9
+ </main><footer>MOD MOTION <span>Make room for imagination.</span></footer></body></html>
web/style.css ADDED
@@ -0,0 +1 @@
 
 
1
+ :root{color-scheme:dark;--bg:#131512;--panel:#1d201b;--line:#383e32;--text:#efeee5;--muted:#a4ad9b;--accent:#d4ed9a;font-family:Inter,ui-sans-serif,system-ui,sans-serif}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at 75% 5%,#293223 0,transparent 40%),var(--bg);color:var(--text);min-height:100vh}header,footer{display:flex;justify-content:space-between;align-items:center;padding:28px 6vw;border-bottom:1px solid var(--line)}a{color:inherit}.brand{text-decoration:none;font-size:30px;font-weight:800;letter-spacing:-2px}.brand span{font-size:20px;font-weight:400;letter-spacing:-.5px;margin-left:10px;color:var(--accent)}.tag,.eyebrow{font-size:10px;font-weight:700;letter-spacing:2.5px;color:var(--accent)}main{max-width:900px;margin:auto;padding:72px 24px 90px}h1{font-family:Georgia,serif;font-weight:400;font-size:clamp(48px,7vw,84px);letter-spacing:-3px;line-height:1.06;margin:22px 0}.intro{color:var(--muted);font-size:17px;margin-bottom:34px}.composer{border:1px solid var(--line);border-radius:20px;background:var(--panel);padding:26px;box-shadow:0 25px 70px #0003}label{display:block;font-size:12px;color:var(--muted)}textarea{display:block;resize:vertical;width:100%;background:transparent;border:0;color:var(--text);font:inherit;line-height:1.7;margin-top:12px;min-height:130px}textarea::placeholder{color:#89927f}textarea:focus{outline:none}button,.button{font:inherit;font-size:13px;cursor:pointer;border:0;border-radius:9px;padding:14px 20px;background:var(--accent);color:#1b2114;font-weight:650;text-decoration:none;display:inline-block}button:disabled{opacity:.5;cursor:wait}button:hover,.button:hover{filter:brightness(1.12)}:focus-visible{outline:2px solid var(--accent);outline-offset:4px}.controls{display:flex;gap:12px;align-items:center;justify-content:space-between;flex-wrap:wrap;border-top:1px solid var(--line);padding-top:18px}.hint{font-size:12px;color:var(--muted)}.loading{display:flex;align-items:center;gap:16px;padding:26px 4px}.loading p{margin:0 0 5px;color:var(--accent);font-size:14px}.loading small{color:var(--muted);font-size:12px}.spinner{width:24px;height:24px;flex-shrink:0;border:2px solid var(--line);border-top-color:var(--accent);border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}#error{color:#f5b4a6;background:#382520;border:1px solid #604034;border-radius:10px;padding:18px;font-size:14px;line-height:1.6}#result{margin-top:30px}video{width:100%;max-height:65vh;background:#000;border-radius:12px;display:block;margin-bottom:18px}footer{font-size:10px;letter-spacing:2px;border-top:1px solid var(--line);border-bottom:0;color:var(--muted)}[hidden]{display:none!important}@media(prefers-reduced-motion:reduce){.spinner{animation:none}}@media(max-width:600px){main{padding-top:45px}.composer{padding:18px}.controls button{width:100%}header{padding:20px}.tag,footer span{display:none}}