github-actions[bot] commited on
Commit ·
801f06c
1
Parent(s): e46bf3c
Automated Deploy: 49714823cd4f8e3e8f1382d391cfb3b9732cc60c
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +17 -0
- .gitattributes +5 -0
- .gitignore +32 -0
- Dockerfile +52 -0
- README.md +59 -5
- backend/app/__init__.py +0 -0
- backend/app/ai/__init__.py +0 -0
- backend/app/ai/chatterbox_provider.py +33 -0
- backend/app/ai/dialogue_provider.py +7 -0
- backend/app/ai/infinitetalk_provider.py +5 -0
- backend/app/ai/kokoro_provider.py +27 -0
- backend/app/ai/provider_factory.py +20 -0
- backend/app/ai/provider_readiness.py +32 -0
- backend/app/ai/qwen_provider.py +41 -0
- backend/app/ai/sadtalker_provider.py +9 -0
- backend/app/ai/speech_provider.py +8 -0
- backend/app/ai/video_http_provider.py +51 -0
- backend/app/ai/video_provider.py +10 -0
- backend/app/assets/__init__.py +0 -0
- backend/app/assets/asset_controller.py +84 -0
- backend/app/assets/asset_model.py +13 -0
- backend/app/bootstrap.py +127 -0
- backend/app/characters/__init__.py +0 -0
- backend/app/characters/character_controller.py +28 -0
- backend/app/characters/character_model.py +14 -0
- backend/app/characters/character_repository.py +6 -0
- backend/app/characters/character_schema.py +35 -0
- backend/app/characters/character_service.py +23 -0
- backend/app/config.py +27 -0
- backend/app/conversations/__init__.py +0 -0
- backend/app/conversations/conversation_controller.py +47 -0
- backend/app/conversations/conversation_model.py +11 -0
- backend/app/conversations/conversation_repository.py +6 -0
- backend/app/conversations/conversation_schema.py +29 -0
- backend/app/conversations/conversation_service.py +17 -0
- backend/app/database.py +29 -0
- backend/app/generations/__init__.py +0 -0
- backend/app/generations/generation_controller.py +75 -0
- backend/app/generations/generation_model.py +17 -0
- backend/app/generations/generation_repository.py +6 -0
- backend/app/generations/generation_schema.py +35 -0
- backend/app/generations/generation_service.py +120 -0
- backend/app/generations/generation_worker.py +220 -0
- backend/app/main.py +54 -0
- backend/app/scenes/__init__.py +0 -0
- backend/app/scenes/scene_controller.py +28 -0
- backend/app/scenes/scene_model.py +12 -0
- backend/app/scenes/scene_repository.py +6 -0
- backend/app/scenes/scene_schema.py +20 -0
- backend/app/scenes/scene_service.py +27 -0
.dockerignore
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.venv
|
| 3 |
+
node_modules
|
| 4 |
+
frontend/node_modules
|
| 5 |
+
frontend/dist
|
| 6 |
+
frontend/test-results
|
| 7 |
+
frontend/playwright-report
|
| 8 |
+
.env
|
| 9 |
+
.env.*
|
| 10 |
+
assets
|
| 11 |
+
data
|
| 12 |
+
model_weights
|
| 13 |
+
deliverables
|
| 14 |
+
__pycache__
|
| 15 |
+
**/__pycache__
|
| 16 |
+
.pytest_cache
|
| 17 |
+
.ruff_cache
|
.gitattributes
CHANGED
|
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
#Ignore vscode AI rules
|
| 4 |
+
.github/instructions/codacy.instructions.md
|
| 5 |
+
|
| 6 |
+
# Python and local settings
|
| 7 |
+
__pycache__/
|
| 8 |
+
*.py[cod]
|
| 9 |
+
.venv/
|
| 10 |
+
.pytest_cache/
|
| 11 |
+
.env
|
| 12 |
+
.env.*
|
| 13 |
+
!.env.example
|
| 14 |
+
|
| 15 |
+
# Generated assets and model weights
|
| 16 |
+
assets/**/*
|
| 17 |
+
!assets/**/
|
| 18 |
+
!assets/**/.gitkeep
|
| 19 |
+
model_weights/*
|
| 20 |
+
!model_weights/.gitkeep
|
| 21 |
+
data/*
|
| 22 |
+
!data/.gitkeep
|
| 23 |
+
|
| 24 |
+
# Monorepo build and test artifacts
|
| 25 |
+
node_modules/
|
| 26 |
+
frontend/dist/
|
| 27 |
+
frontend/test-results/
|
| 28 |
+
frontend/playwright-report/
|
| 29 |
+
*.tsbuildinfo
|
| 30 |
+
.ruff_cache/
|
| 31 |
+
worker-heartbeat.json
|
| 32 |
+
backend/.pytest_cache/
|
Dockerfile
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hugging Face Docker Space. Inference runs only on the assigned GPU at runtime.
|
| 2 |
+
FROM node:22-bookworm AS frontend
|
| 3 |
+
WORKDIR /workspace
|
| 4 |
+
COPY package.json package-lock.json ./
|
| 5 |
+
COPY frontend/package.json frontend/package.json
|
| 6 |
+
RUN npm ci
|
| 7 |
+
COPY frontend frontend
|
| 8 |
+
RUN npm run build
|
| 9 |
+
|
| 10 |
+
FROM python:3.10-slim-bookworm
|
| 11 |
+
WORKDIR /workspace
|
| 12 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 13 |
+
git wget ffmpeg espeak-ng libsndfile1 libgl1 libglib2.0-0 build-essential \
|
| 14 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
+
|
| 16 |
+
# SadTalker's older dependencies stay separate from Kokoro and FastAPI.
|
| 17 |
+
ARG SADTALKER_REF=cd4c0465ae0b54a6f85af57f5c65fec9fe23e7f8
|
| 18 |
+
RUN git clone https://github.com/OpenTalker/SadTalker.git /opt/SadTalker \
|
| 19 |
+
&& cd /opt/SadTalker && git checkout "$SADTALKER_REF"
|
| 20 |
+
COPY backend/model_services/requirements-sadtalker.txt /tmp/requirements-sadtalker.txt
|
| 21 |
+
RUN python -m venv /opt/sadtalker-venv \
|
| 22 |
+
&& /opt/sadtalker-venv/bin/pip install --no-cache-dir 'setuptools<70' wheel \
|
| 23 |
+
&& /opt/sadtalker-venv/bin/pip install --no-cache-dir \
|
| 24 |
+
torch==1.13.1+cu117 torchvision==0.14.1+cu117 \
|
| 25 |
+
--extra-index-url https://download.pytorch.org/whl/cu117 \
|
| 26 |
+
&& /opt/sadtalker-venv/bin/pip install --no-cache-dir --no-build-isolation -r /tmp/requirements-sadtalker.txt
|
| 27 |
+
RUN cd /opt/SadTalker && bash scripts/download_models.sh \
|
| 28 |
+
&& test -s checkpoints/SadTalker_V0.0.2_256.safetensors \
|
| 29 |
+
&& test -s checkpoints/mapping_00109-model.pth.tar
|
| 30 |
+
|
| 31 |
+
COPY backend/requirements.txt backend/requirements.txt
|
| 32 |
+
COPY backend/model_services/requirements-lightweight.txt backend/model_services/requirements-lightweight.txt
|
| 33 |
+
RUN pip install --no-cache-dir torch==2.6.0 --index-url https://download.pytorch.org/whl/cpu \
|
| 34 |
+
&& pip install --no-cache-dir -r backend/requirements.txt -r backend/model_services/requirements-lightweight.txt
|
| 35 |
+
RUN useradd -m -u 1000 studio
|
| 36 |
+
COPY --chown=studio:studio backend backend
|
| 37 |
+
COPY --chown=studio:studio scripts scripts
|
| 38 |
+
COPY --from=frontend --chown=studio:studio /workspace/frontend/dist frontend/dist
|
| 39 |
+
# /workspace itself must be writable: the worker heartbeat is written beside
|
| 40 |
+
# ASSETS_DIR, and /data is pre-created so persistent-storage overrides work.
|
| 41 |
+
RUN mkdir -p data assets /home/studio/.cache /data \
|
| 42 |
+
&& chown studio:studio /workspace /data \
|
| 43 |
+
&& chown -R studio:studio data assets /home/studio/.cache /opt/SadTalker
|
| 44 |
+
USER studio
|
| 45 |
+
ENV PYTHONUNBUFFERED=1 PYTHONPATH=/workspace/backend HOST=0.0.0.0 PORT=7860 \
|
| 46 |
+
DATABASE_URL=sqlite:////workspace/data/app.db ASSETS_DIR=/workspace/assets \
|
| 47 |
+
START_MODEL_SERVICE=true ENABLE_ANIMATED_RENDERS=true ENABLE_AI_DRAFTS=false \
|
| 48 |
+
SPEECH_PROVIDER=kokoro VIDEO_PROVIDER=sadtalker OLLAMA_URL="" \
|
| 49 |
+
SADTALKER_ROOT=/opt/SadTalker SADTALKER_PYTHON=/opt/sadtalker-venv/bin/python \
|
| 50 |
+
PROVIDER_TIMEOUT=14400 VIDEO_TIMEOUT=3600 HF_HOME=/home/studio/.cache/huggingface
|
| 51 |
+
EXPOSE 7860
|
| 52 |
+
CMD ["python", "scripts/start.py"]
|
README.md
CHANGED
|
@@ -1,11 +1,65 @@
|
|
| 1 |
---
|
| 2 |
title: Character Studio
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
-
license: mit
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Character Studio
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: pink
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Character Studio
|
| 12 |
+
|
| 13 |
+
A React/Vite + FastAPI MVP using two fixed fictional characters and the included generated image.
|
| 14 |
+
The UI is a single Studio page: write exact dialogue, save/approve it, create a preview and download the result.
|
| 15 |
+
Image uploads, character editing, Settings and Videos pages are not exposed.
|
| 16 |
+
|
| 17 |
+
## Current small-model pipeline
|
| 18 |
+
|
| 19 |
+
**Written dialogue → Kokoro-82M → SadTalker → FFmpeg.** No Ollama, voice recordings or external AI API keys are required.
|
| 20 |
+
R.Royale and Summer Breeze use different saved voice presets. Each portrait is animated independently and shown beside the other; natural shared reactions, body gestures and detailed dialect controls are not implemented.
|
| 21 |
+
|
| 22 |
+
The root Dockerfile prepares the frontend, backend and bundled model service for a Hugging Face NVIDIA GPU Space.
|
| 23 |
+
It does not run tests or inference at build time. The talking-video button requires model-service readiness.
|
| 24 |
+
**Remote Docker build and GPU output quality remain unverified.** See [deployment steps and limitations](docs/lightweight-mvp.md).
|
| 25 |
+
|
| 26 |
+
## Structure
|
| 27 |
+
|
| 28 |
+
```text
|
| 29 |
+
backend/app/
|
| 30 |
+
characters/ # saved character profiles, voice presets
|
| 31 |
+
conversations/ # creator-written dialogue; optional AI adapter
|
| 32 |
+
scenes/ # fixed cast and reference image
|
| 33 |
+
generations/ # immutable input snapshots, queue, worker
|
| 34 |
+
assets/ # asset records and downloads
|
| 35 |
+
ai/ # provider factory and replaceable model adapters
|
| 36 |
+
shared/ # storage, audio alignment, FFmpeg export
|
| 37 |
+
system/ # availability checks
|
| 38 |
+
backend/model_services/ # Kokoro/SadTalker service; legacy model adapters
|
| 39 |
+
backend/demo_assets/ # fixed generated scene
|
| 40 |
+
frontend/src/
|
| 41 |
+
app/ # app shell and styles
|
| 42 |
+
features/ # Studio, dialogue and scene components
|
| 43 |
+
shared/ # API client, types and common components
|
| 44 |
+
scripts/start.py # supervises API, worker and optional model service
|
| 45 |
+
docs/lightweight-mvp.md # deployment and current capability details
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
Backend modules use controller/service/repository/model/schema files. ML models use provider files.
|
| 49 |
+
The local SQLite database is created automatically; no separate database server is needed.
|
| 50 |
+
Attach persistent storage on Hugging Face if scripts and outputs must survive a rebuild.
|
| 51 |
+
|
| 52 |
+
## Frontend development
|
| 53 |
+
|
| 54 |
+
```sh
|
| 55 |
+
npm ci
|
| 56 |
+
npm run dev
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Vite proxies `/api` to the backend. Build with `npm run build`.
|
| 60 |
+
For backend-only development, install `backend/requirements.txt`, copy `.env.example` to `.env`,
|
| 61 |
+
and run `python scripts/start.py` with the backend virtual environment active.
|
| 62 |
+
Local defaults disable model inference; the GPU Docker deployment supplies its own defaults.
|
| 63 |
+
|
| 64 |
+
Legacy test files and heavier model adapters remain in the repository. Tests have not been updated or run for this simplified MVP.
|
| 65 |
+
The older [model-services document](docs/model-services.md) and [requirements coverage](docs/requirements-coverage.md) describe the previous heavier design; use the lightweight guide for the current implementation.
|
backend/app/__init__.py
ADDED
|
File without changes
|
backend/app/ai/__init__.py
ADDED
|
File without changes
|
backend/app/ai/chatterbox_provider.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import httpx
|
| 3 |
+
from app.config import settings
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ChatterboxProvider:
|
| 7 |
+
def synthesize(
|
| 8 |
+
self,
|
| 9 |
+
text: str,
|
| 10 |
+
voice_reference: Path,
|
| 11 |
+
output_path: Path,
|
| 12 |
+
profile: dict | None = None,
|
| 13 |
+
) -> Path:
|
| 14 |
+
if not settings.speech_url:
|
| 15 |
+
raise RuntimeError(
|
| 16 |
+
"Configure SPEECH_URL and start the Chatterbox model service"
|
| 17 |
+
)
|
| 18 |
+
with voice_reference.open("rb") as voice:
|
| 19 |
+
response = httpx.post(
|
| 20 |
+
settings.speech_url.rstrip("/") + "/synthesize",
|
| 21 |
+
files={"reference": ("voice.wav", voice, "audio/wav")},
|
| 22 |
+
data={
|
| 23 |
+
"text": text,
|
| 24 |
+
"expressiveness": str((profile or {}).get("expressiveness", 0.5)),
|
| 25 |
+
},
|
| 26 |
+
headers={"Authorization": f"Bearer {settings.provider_token}"},
|
| 27 |
+
timeout=settings.provider_timeout,
|
| 28 |
+
)
|
| 29 |
+
response.raise_for_status()
|
| 30 |
+
if len(response.content) > 50_000_000:
|
| 31 |
+
raise RuntimeError("Speech response exceeds size limit")
|
| 32 |
+
output_path.write_bytes(response.content)
|
| 33 |
+
return output_path
|
backend/app/ai/dialogue_provider.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Protocol
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class DialogueProvider(Protocol):
|
| 5 |
+
def generate(self, prompt: str, profiles: list[dict]) -> list[dict[str, str]]:
|
| 6 |
+
"""Return dialogue turns containing character_id and text."""
|
| 7 |
+
...
|
backend/app/ai/infinitetalk_provider.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.ai.video_http_provider import VideoHttpProvider
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class InfiniteTalkProvider(VideoHttpProvider):
|
| 5 |
+
"""Shared-scene video generation via the InfiniteTalk service."""
|
backend/app/ai/kokoro_provider.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import httpx
|
| 3 |
+
from app.config import settings
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class KokoroProvider:
|
| 7 |
+
def synthesize(
|
| 8 |
+
self,
|
| 9 |
+
text: str,
|
| 10 |
+
voice_reference: Path | None,
|
| 11 |
+
output_path: Path,
|
| 12 |
+
profile: dict | None = None,
|
| 13 |
+
) -> Path:
|
| 14 |
+
response = httpx.post(
|
| 15 |
+
settings.speech_url.rstrip("/") + "/synthesize",
|
| 16 |
+
data={
|
| 17 |
+
"text": text,
|
| 18 |
+
"voice": (profile or {}).get("voice_preset", "af_heart"),
|
| 19 |
+
},
|
| 20 |
+
headers={"Authorization": f"Bearer {settings.provider_token}"},
|
| 21 |
+
timeout=settings.provider_timeout,
|
| 22 |
+
)
|
| 23 |
+
response.raise_for_status()
|
| 24 |
+
if len(response.content) > 50_000_000:
|
| 25 |
+
raise RuntimeError("Speech response exceeds size limit")
|
| 26 |
+
output_path.write_bytes(response.content)
|
| 27 |
+
return output_path
|
backend/app/ai/provider_factory.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.ai.chatterbox_provider import ChatterboxProvider
|
| 2 |
+
from app.ai.kokoro_provider import KokoroProvider
|
| 3 |
+
from app.ai.infinitetalk_provider import InfiniteTalkProvider
|
| 4 |
+
from app.ai.sadtalker_provider import SadTalkerProvider
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def speech_provider(name):
|
| 8 |
+
if name == "kokoro":
|
| 9 |
+
return KokoroProvider()
|
| 10 |
+
if name == "chatterbox":
|
| 11 |
+
return ChatterboxProvider()
|
| 12 |
+
raise ValueError(f"Unsupported speech provider: {name}")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def video_provider(name):
|
| 16 |
+
if name == "sadtalker":
|
| 17 |
+
return SadTalkerProvider()
|
| 18 |
+
if name == "infinitetalk":
|
| 19 |
+
return InfiniteTalkProvider()
|
| 20 |
+
raise ValueError(f"Unsupported video provider: {name}")
|
backend/app/ai/provider_readiness.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import httpx
|
| 3 |
+
from app.config import settings
|
| 4 |
+
|
| 5 |
+
_cached_at = 0.0
|
| 6 |
+
_cached_ready = False
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def lightweight_ready():
|
| 10 |
+
"""Short readiness cache; configuration alone must not enable rendering."""
|
| 11 |
+
global _cached_at, _cached_ready
|
| 12 |
+
if time.monotonic() - _cached_at < 10:
|
| 13 |
+
return _cached_ready
|
| 14 |
+
_cached_ready = False
|
| 15 |
+
try:
|
| 16 |
+
for url in {settings.speech_url, settings.video_url}:
|
| 17 |
+
if not url:
|
| 18 |
+
return False
|
| 19 |
+
response = httpx.get(
|
| 20 |
+
url.rstrip("/") + "/health",
|
| 21 |
+
headers={"Authorization": f"Bearer {settings.provider_token}"},
|
| 22 |
+
timeout=5,
|
| 23 |
+
)
|
| 24 |
+
response.raise_for_status()
|
| 25 |
+
if response.json().get("model") != "kokoro+sadtalker":
|
| 26 |
+
return False
|
| 27 |
+
_cached_ready = True
|
| 28 |
+
except (httpx.HTTPError, ValueError):
|
| 29 |
+
pass
|
| 30 |
+
finally:
|
| 31 |
+
_cached_at = time.monotonic()
|
| 32 |
+
return _cached_ready
|
backend/app/ai/qwen_provider.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import httpx
|
| 3 |
+
from fastapi import HTTPException
|
| 4 |
+
from pydantic import ValidationError
|
| 5 |
+
from app.config import settings
|
| 6 |
+
from app.conversations.conversation_schema import DialogueTurn
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class QwenProvider:
|
| 10 |
+
def generate(self, prompt: str, profiles: list[dict]) -> list[dict]:
|
| 11 |
+
system = (
|
| 12 |
+
"Write an original approximately 120-word conversation. Return JSON {turns: [{character_id, text, direction, pause_after}]}. Use exactly the supplied character IDs and both characters. Honor each profile. Do not infer dialect from race. No impersonation. Profiles: "
|
| 13 |
+
+ json.dumps(profiles)
|
| 14 |
+
)
|
| 15 |
+
try:
|
| 16 |
+
response = httpx.post(
|
| 17 |
+
settings.ollama_url.rstrip("/") + "/api/chat",
|
| 18 |
+
json={
|
| 19 |
+
"model": settings.dialogue_model,
|
| 20 |
+
"stream": False,
|
| 21 |
+
"format": "json",
|
| 22 |
+
"messages": [
|
| 23 |
+
{"role": "system", "content": system},
|
| 24 |
+
{"role": "user", "content": prompt},
|
| 25 |
+
],
|
| 26 |
+
},
|
| 27 |
+
timeout=120,
|
| 28 |
+
)
|
| 29 |
+
response.raise_for_status()
|
| 30 |
+
turns = json.loads(response.json()["message"]["content"])["turns"]
|
| 31 |
+
if not 2 <= len(turns) <= 40:
|
| 32 |
+
raise ValueError("Invalid turn count")
|
| 33 |
+
result = [DialogueTurn.model_validate(t).model_dump() for t in turns]
|
| 34 |
+
if {t["character_id"] for t in result} != {p["id"] for p in profiles}:
|
| 35 |
+
raise ValueError("Invalid speaker IDs")
|
| 36 |
+
return result
|
| 37 |
+
except (httpx.HTTPError, KeyError, ValueError, ValidationError) as exc:
|
| 38 |
+
raise HTTPException(
|
| 39 |
+
503,
|
| 40 |
+
"Dialogue provider unavailable or returned an invalid draft. Start Ollama, install the configured Qwen model, or use creator-written dialogue.",
|
| 41 |
+
) from exc
|
backend/app/ai/sadtalker_provider.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.ai.video_http_provider import VideoHttpProvider
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class SadTalkerProvider(VideoHttpProvider):
|
| 5 |
+
"""Same multipart transport: fixed scene, two aligned WAVs, output MP4.
|
| 6 |
+
|
| 7 |
+
The service splits the scene, animates each portrait and composes the result.
|
| 8 |
+
Text performance directions are deliberately not interpreted by SadTalker.
|
| 9 |
+
"""
|
backend/app/ai/speech_provider.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Protocol
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class SpeechProvider(Protocol):
|
| 6 |
+
def synthesize(self, text: str, voice_reference: Path, output_path: Path) -> Path:
|
| 7 |
+
"""Generate speech using an authorized voice reference."""
|
| 8 |
+
...
|
backend/app/ai/video_http_provider.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from contextlib import ExitStack
|
| 3 |
+
import httpx
|
| 4 |
+
from app.config import settings
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class VideoHttpProvider:
|
| 8 |
+
def generate(
|
| 9 |
+
self,
|
| 10 |
+
scene_image: Path,
|
| 11 |
+
audio_tracks: list[Path],
|
| 12 |
+
output_path: Path,
|
| 13 |
+
prompt: str = "",
|
| 14 |
+
) -> Path:
|
| 15 |
+
if not settings.video_url:
|
| 16 |
+
raise RuntimeError(
|
| 17 |
+
"Configure VIDEO_URL and start the selected video model service"
|
| 18 |
+
)
|
| 19 |
+
with ExitStack() as stack:
|
| 20 |
+
files = {
|
| 21 |
+
"image": (
|
| 22 |
+
scene_image.name,
|
| 23 |
+
stack.enter_context(scene_image.open("rb")),
|
| 24 |
+
"image/png"
|
| 25 |
+
if scene_image.suffix.lower() == ".png"
|
| 26 |
+
else "image/jpeg",
|
| 27 |
+
)
|
| 28 |
+
}
|
| 29 |
+
for index, path in enumerate(audio_tracks):
|
| 30 |
+
files[f"audio{index + 1}"] = (
|
| 31 |
+
path.name,
|
| 32 |
+
stack.enter_context(path.open("rb")),
|
| 33 |
+
"audio/wav",
|
| 34 |
+
)
|
| 35 |
+
with httpx.stream(
|
| 36 |
+
"POST",
|
| 37 |
+
settings.video_url.rstrip("/") + "/generate",
|
| 38 |
+
files=files,
|
| 39 |
+
data={"prompt": prompt},
|
| 40 |
+
headers={"Authorization": f"Bearer {settings.provider_token}"},
|
| 41 |
+
timeout=settings.provider_timeout,
|
| 42 |
+
) as response:
|
| 43 |
+
response.raise_for_status()
|
| 44 |
+
with output_path.open("wb") as output:
|
| 45 |
+
size = 0
|
| 46 |
+
for chunk in response.iter_bytes():
|
| 47 |
+
size += len(chunk)
|
| 48 |
+
if size > 500_000_000:
|
| 49 |
+
raise RuntimeError("Video response exceeds size limit")
|
| 50 |
+
output.write(chunk)
|
| 51 |
+
return output_path
|
backend/app/ai/video_provider.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Protocol
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class VideoProvider(Protocol):
|
| 6 |
+
def generate(
|
| 7 |
+
self, scene_image: Path, audio_tracks: list[Path], output_path: Path
|
| 8 |
+
) -> Path:
|
| 9 |
+
"""Animate a shared scene using aligned, per-character audio tracks."""
|
| 10 |
+
...
|
backend/app/assets/__init__.py
ADDED
|
File without changes
|
backend/app/assets/asset_controller.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
| 2 |
+
from fastapi.responses import FileResponse
|
| 3 |
+
from sqlalchemy import select
|
| 4 |
+
from sqlalchemy.orm import Session
|
| 5 |
+
from app.database import get_session
|
| 6 |
+
from app.shared.storage_service import StorageService
|
| 7 |
+
from app.assets.asset_model import Asset
|
| 8 |
+
from app.config import settings
|
| 9 |
+
from app.generations.generation_model import Generation
|
| 10 |
+
|
| 11 |
+
router = APIRouter(prefix="/assets", tags=["assets"])
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def serialize(asset):
|
| 15 |
+
return {
|
| 16 |
+
"id": asset.id,
|
| 17 |
+
"kind": asset.kind,
|
| 18 |
+
"name": asset.original_name,
|
| 19 |
+
"rights": asset.rights,
|
| 20 |
+
"rights_note": asset.rights_note,
|
| 21 |
+
"url": f"/api/v1/assets/{asset.id}/file",
|
| 22 |
+
"revoked": asset.revoked,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@router.get("")
|
| 27 |
+
def list_assets(db: Session = Depends(get_session)):
|
| 28 |
+
return [
|
| 29 |
+
serialize(a) for a in db.scalars(select(Asset).where(Asset.revoked.is_(False)))
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@router.post("", status_code=201)
|
| 34 |
+
async def upload(
|
| 35 |
+
file: UploadFile = File(...),
|
| 36 |
+
kind: str = Form(...),
|
| 37 |
+
rights: str = Form(...),
|
| 38 |
+
rights_note: str = Form(...),
|
| 39 |
+
consent: bool = Form(...),
|
| 40 |
+
db: Session = Depends(get_session),
|
| 41 |
+
):
|
| 42 |
+
if settings.fixed_demo_mode and kind == "image":
|
| 43 |
+
raise HTTPException(403, "Image uploads are disabled for this MVP")
|
| 44 |
+
if not consent:
|
| 45 |
+
raise HTTPException(422, "Rights confirmation is required")
|
| 46 |
+
data = await file.read(20 * 1024 * 1024 + 1)
|
| 47 |
+
if len(data) > 20 * 1024 * 1024:
|
| 48 |
+
raise HTTPException(413, "Maximum upload is 20 MB")
|
| 49 |
+
return serialize(
|
| 50 |
+
StorageService(db).upload(
|
| 51 |
+
data, file.filename or "asset", kind, rights, rights_note
|
| 52 |
+
)
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@router.get("/{asset_id}/file")
|
| 57 |
+
def download(asset_id: str, db: Session = Depends(get_session)):
|
| 58 |
+
storage = StorageService(db)
|
| 59 |
+
asset = storage.get(asset_id)
|
| 60 |
+
if asset.kind == "video":
|
| 61 |
+
job = db.scalar(
|
| 62 |
+
select(Generation).where(Generation.output_asset_id == asset.id)
|
| 63 |
+
)
|
| 64 |
+
if job:
|
| 65 |
+
storage.get(job.settings["scene"]["image_asset_id"], "image")
|
| 66 |
+
if job.settings["kind"] == "animated":
|
| 67 |
+
for character in job.settings["characters"]:
|
| 68 |
+
storage.get(character["voice_asset_id"], "voice")
|
| 69 |
+
path = storage.path(asset)
|
| 70 |
+
if not path.is_file():
|
| 71 |
+
raise HTTPException(404, "Asset file is unavailable")
|
| 72 |
+
return FileResponse(
|
| 73 |
+
path, filename=asset.original_name, content_disposition_type="inline"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@router.post("/{asset_id}/revoke")
|
| 78 |
+
def revoke(asset_id: str, db: Session = Depends(get_session)):
|
| 79 |
+
if settings.fixed_demo_mode and asset_id == "mvp-scene-image":
|
| 80 |
+
raise HTTPException(403, "The built-in demo image cannot be removed")
|
| 81 |
+
asset = StorageService(db).get(asset_id)
|
| 82 |
+
asset.revoked = True
|
| 83 |
+
db.commit()
|
| 84 |
+
return {"revoked": True}
|
backend/app/assets/asset_model.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import String, Boolean
|
| 2 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 3 |
+
from app.shared.base_model import Record
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Asset(Record):
|
| 7 |
+
__tablename__ = "assets"
|
| 8 |
+
kind: Mapped[str] = mapped_column(String(30))
|
| 9 |
+
path: Mapped[str] = mapped_column(String(500))
|
| 10 |
+
original_name: Mapped[str] = mapped_column(String(300))
|
| 11 |
+
rights: Mapped[str] = mapped_column(String(30))
|
| 12 |
+
rights_note: Mapped[str] = mapped_column(String(2000))
|
| 13 |
+
revoked: Mapped[bool] = mapped_column(Boolean, default=False)
|
backend/app/bootstrap.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import shutil
|
| 3 |
+
from sqlalchemy.orm import Session
|
| 4 |
+
from app.database import Base, get_engine
|
| 5 |
+
from app.config import settings
|
| 6 |
+
from app.characters.character_model import Character
|
| 7 |
+
from app.assets.asset_model import Asset # noqa: F401
|
| 8 |
+
from app.conversations.conversation_model import Conversation # noqa: F401
|
| 9 |
+
from app.scenes.scene_model import Scene # noqa: F401
|
| 10 |
+
from app.generations.generation_model import Generation # noqa: F401
|
| 11 |
+
from app.characters.character_schema import CharacterProfile
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def initialize():
|
| 15 |
+
settings.assets_dir.mkdir(parents=True, exist_ok=True)
|
| 16 |
+
Base.metadata.create_all(get_engine())
|
| 17 |
+
if not settings.seed_characters and not settings.fixed_demo_mode:
|
| 18 |
+
return
|
| 19 |
+
with Session(get_engine()) as db:
|
| 20 |
+
profiles = [
|
| 21 |
+
(
|
| 22 |
+
"royale",
|
| 23 |
+
"R.Royale",
|
| 24 |
+
"Calm presence. A dry sense of humor.",
|
| 25 |
+
"#b9ace8",
|
| 26 |
+
"Calm, dry humor, thoughtful and controlled. An original fictional African-American woman.",
|
| 27 |
+
0.3,
|
| 28 |
+
"Small hand movements; attentive eye contact",
|
| 29 |
+
),
|
| 30 |
+
(
|
| 31 |
+
"summer",
|
| 32 |
+
"Summer Breeze",
|
| 33 |
+
"Big energy. A little sunshine.",
|
| 34 |
+
"#eac391",
|
| 35 |
+
"Warm, animated, expressive and outgoing. An original fictional African-American woman.",
|
| 36 |
+
0.75,
|
| 37 |
+
"Expressive hands; warm smiles; lively but natural reactions",
|
| 38 |
+
),
|
| 39 |
+
]
|
| 40 |
+
for (
|
| 41 |
+
identity,
|
| 42 |
+
name,
|
| 43 |
+
description,
|
| 44 |
+
color,
|
| 45 |
+
personality,
|
| 46 |
+
expression,
|
| 47 |
+
gestures,
|
| 48 |
+
) in profiles:
|
| 49 |
+
existing = db.get(Character, identity)
|
| 50 |
+
preset = "af_heart" if identity == "royale" else "af_bella"
|
| 51 |
+
if existing:
|
| 52 |
+
if "voice_preset" not in existing.profile:
|
| 53 |
+
existing.profile = {**existing.profile, "voice_preset": preset}
|
| 54 |
+
continue
|
| 55 |
+
profile = CharacterProfile(
|
| 56 |
+
personality=personality,
|
| 57 |
+
expressiveness=expression,
|
| 58 |
+
gestures=gestures,
|
| 59 |
+
voice_preset=preset,
|
| 60 |
+
).model_dump()
|
| 61 |
+
db.add(
|
| 62 |
+
Character(
|
| 63 |
+
id=identity,
|
| 64 |
+
name=name,
|
| 65 |
+
description=description,
|
| 66 |
+
color=color,
|
| 67 |
+
profile=profile,
|
| 68 |
+
)
|
| 69 |
+
)
|
| 70 |
+
db.commit()
|
| 71 |
+
|
| 72 |
+
demo = Path(__file__).resolve().parents[1] / "demo_assets" / "scene.png"
|
| 73 |
+
if demo.exists() and not db.get(Asset, "demo-scene-image"):
|
| 74 |
+
target = settings.assets_dir / "scenes" / "original-demo.png"
|
| 75 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
shutil.copyfile(demo, target)
|
| 77 |
+
asset = Asset(
|
| 78 |
+
id="demo-scene-image",
|
| 79 |
+
kind="image",
|
| 80 |
+
path="scenes/original-demo.png",
|
| 81 |
+
original_name="Original fictional scene.png",
|
| 82 |
+
rights="original",
|
| 83 |
+
rights_note="AI-generated fictional reference created for this prototype; creator approval pending",
|
| 84 |
+
)
|
| 85 |
+
db.add(asset)
|
| 86 |
+
db.add(
|
| 87 |
+
Scene(
|
| 88 |
+
id="demo-scene",
|
| 89 |
+
name="The living room",
|
| 90 |
+
image_asset_id=asset.id,
|
| 91 |
+
character_ids=["royale", "summer"],
|
| 92 |
+
prompt="Two women seated together in a warm living room. R.Royale on the left, Summer Breeze on the right. Natural eye contact, subtle gestures and attentive listening while the other speaks.",
|
| 93 |
+
approved=False,
|
| 94 |
+
)
|
| 95 |
+
)
|
| 96 |
+
db.commit()
|
| 97 |
+
|
| 98 |
+
if settings.fixed_demo_mode:
|
| 99 |
+
if not demo.is_file():
|
| 100 |
+
raise RuntimeError("The bundled MVP scene image is missing")
|
| 101 |
+
target = settings.assets_dir / "scenes" / "mvp-original.png"
|
| 102 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 103 |
+
if not target.exists():
|
| 104 |
+
shutil.copyfile(demo, target)
|
| 105 |
+
if not db.get(Asset, "mvp-scene-image"):
|
| 106 |
+
db.add(
|
| 107 |
+
Asset(
|
| 108 |
+
id="mvp-scene-image",
|
| 109 |
+
kind="image",
|
| 110 |
+
path="scenes/mvp-original.png",
|
| 111 |
+
original_name="R.Royale and Summer Breeze.png",
|
| 112 |
+
rights="original",
|
| 113 |
+
rights_note="AI-generated fictional scene selected by the creator for this fixed-image MVP",
|
| 114 |
+
)
|
| 115 |
+
)
|
| 116 |
+
if not db.get(Scene, "mvp-scene"):
|
| 117 |
+
db.add(
|
| 118 |
+
Scene(
|
| 119 |
+
id="mvp-scene",
|
| 120 |
+
name="The living room",
|
| 121 |
+
image_asset_id="mvp-scene-image",
|
| 122 |
+
character_ids=["royale", "summer"],
|
| 123 |
+
prompt="Two women seated together in a warm living room. R.Royale on the left, Summer Breeze on the right. Natural eye contact, subtle gestures and attentive listening while the other speaks.",
|
| 124 |
+
approved=True,
|
| 125 |
+
)
|
| 126 |
+
)
|
| 127 |
+
db.commit()
|
backend/app/characters/__init__.py
ADDED
|
File without changes
|
backend/app/characters/character_controller.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends
|
| 2 |
+
from sqlalchemy.orm import Session
|
| 3 |
+
from app.database import get_session
|
| 4 |
+
from app.characters.character_repository import CharacterRepository
|
| 5 |
+
from app.characters.character_service import CharacterService
|
| 6 |
+
from app.characters.character_schema import CharacterCreate, CharacterRead
|
| 7 |
+
|
| 8 |
+
router = APIRouter(prefix="/characters", tags=["characters"])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@router.get("", response_model=list[CharacterRead])
|
| 12 |
+
def list_records(db: Session = Depends(get_session)):
|
| 13 |
+
return CharacterRepository(db).list()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@router.post("", response_model=CharacterRead, status_code=201)
|
| 17 |
+
def create(data: CharacterCreate, db: Session = Depends(get_session)):
|
| 18 |
+
return CharacterService(CharacterRepository(db)).save(data)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@router.get("/{record_id}", response_model=CharacterRead)
|
| 22 |
+
def get(record_id: str, db: Session = Depends(get_session)):
|
| 23 |
+
return CharacterRepository(db).get(record_id)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@router.put("/{record_id}", response_model=CharacterRead)
|
| 27 |
+
def update(record_id: str, data: CharacterCreate, db: Session = Depends(get_session)):
|
| 28 |
+
return CharacterService(CharacterRepository(db)).save(data, record_id)
|
backend/app/characters/character_model.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import JSON, String, Boolean
|
| 2 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 3 |
+
from app.shared.base_model import Record
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Character(Record):
|
| 7 |
+
__tablename__ = "characters"
|
| 8 |
+
name: Mapped[str] = mapped_column(String(120))
|
| 9 |
+
description: Mapped[str] = mapped_column(String(2000), default="")
|
| 10 |
+
color: Mapped[str] = mapped_column(String(20), default="#a599e9")
|
| 11 |
+
profile: Mapped[dict] = mapped_column(JSON, default=dict)
|
| 12 |
+
image_asset_id: Mapped[str | None] = mapped_column(String(36), nullable=True)
|
| 13 |
+
voice_asset_id: Mapped[str | None] = mapped_column(String(36), nullable=True)
|
| 14 |
+
archived: Mapped[bool] = mapped_column(Boolean, default=False)
|
backend/app/characters/character_repository.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.shared.base_repository import Repository
|
| 2 |
+
from app.characters.character_model import Character
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class CharacterRepository(Repository):
|
| 6 |
+
model = Character
|
backend/app/characters/character_schema.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class CharacterProfile(BaseModel):
|
| 6 |
+
personality: str = Field(default="", max_length=2000)
|
| 7 |
+
region: str = Field(default="Creator defined", max_length=200)
|
| 8 |
+
vocabulary: str = Field(default="", max_length=2000)
|
| 9 |
+
aave: str = Field(default="Creator defined; no automatic dialect", max_length=1000)
|
| 10 |
+
slang: int = Field(default=0, ge=0, le=100)
|
| 11 |
+
pronunciation: str = Field(default="", max_length=2000)
|
| 12 |
+
cadence: str = Field(default="Natural", max_length=300)
|
| 13 |
+
code_switching: str = Field(default="Context dependent", max_length=1000)
|
| 14 |
+
expressiveness: float = Field(default=0.5, ge=0, le=1)
|
| 15 |
+
pace: float = Field(default=1, ge=0.8, le=1.2)
|
| 16 |
+
gestures: str = Field(default="Subtle conversational gestures", max_length=1000)
|
| 17 |
+
voice_notes: str = Field(default="", max_length=1000)
|
| 18 |
+
voice_preset: str = Field(default="af_heart", pattern=r"^af_[a-z]+$")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CharacterCreate(BaseModel):
|
| 22 |
+
name: str = Field(min_length=1, max_length=120)
|
| 23 |
+
description: str = Field(default="", max_length=2000)
|
| 24 |
+
color: str = Field(default="#a599e9", pattern=r"^#[0-9a-fA-F]{6}$")
|
| 25 |
+
profile: CharacterProfile = Field(default_factory=CharacterProfile)
|
| 26 |
+
image_asset_id: str | None = None
|
| 27 |
+
voice_asset_id: str | None = None
|
| 28 |
+
archived: bool = False
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class CharacterRead(CharacterCreate):
|
| 32 |
+
model_config = ConfigDict(from_attributes=True)
|
| 33 |
+
id: str
|
| 34 |
+
created_at: datetime
|
| 35 |
+
version: int
|
backend/app/characters/character_service.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import HTTPException
|
| 2 |
+
from app.config import settings
|
| 3 |
+
from app.shared.storage_service import StorageService
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class CharacterService:
|
| 7 |
+
def __init__(self, repository):
|
| 8 |
+
self.repository = repository
|
| 9 |
+
|
| 10 |
+
def save(self, data, character_id=None):
|
| 11 |
+
if settings.fixed_demo_mode:
|
| 12 |
+
raise HTTPException(
|
| 13 |
+
403,
|
| 14 |
+
"Character creation and editing are disabled for this fixed-cast MVP",
|
| 15 |
+
)
|
| 16 |
+
storage = StorageService(self.repository.session)
|
| 17 |
+
for field, kind in [("image_asset_id", "image"), ("voice_asset_id", "voice")]:
|
| 18 |
+
if value := getattr(data, field):
|
| 19 |
+
storage.get(value, kind)
|
| 20 |
+
values = data.model_dump()
|
| 21 |
+
if character_id:
|
| 22 |
+
return self.repository.update(self.repository.get(character_id), values)
|
| 23 |
+
return self.repository.create(values)
|
backend/app/config.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Literal
|
| 3 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Settings(BaseSettings):
|
| 7 |
+
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
| 8 |
+
app_name: str = "Character Studio"
|
| 9 |
+
database_url: str = "sqlite:///./data/app.db"
|
| 10 |
+
assets_dir: Path = Path("assets")
|
| 11 |
+
model_weights_dir: Path = Path("model_weights")
|
| 12 |
+
ollama_url: str = "http://127.0.0.1:11434"
|
| 13 |
+
dialogue_model: str = "qwen3:1.7b"
|
| 14 |
+
speech_provider: Literal["kokoro", "chatterbox"] = "kokoro"
|
| 15 |
+
video_provider: Literal["sadtalker", "infinitetalk"] = "sadtalker"
|
| 16 |
+
speech_url: str = ""
|
| 17 |
+
video_url: str = ""
|
| 18 |
+
provider_token: str = ""
|
| 19 |
+
provider_timeout: int = 1800
|
| 20 |
+
worker_poll_seconds: float = 2
|
| 21 |
+
seed_characters: bool = True
|
| 22 |
+
fixed_demo_mode: bool = True
|
| 23 |
+
enable_ai_drafts: bool = False
|
| 24 |
+
enable_animated_renders: bool = False
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
settings = Settings()
|
backend/app/conversations/__init__.py
ADDED
|
File without changes
|
backend/app/conversations/conversation_controller.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 2 |
+
from sqlalchemy.orm import Session
|
| 3 |
+
from app.database import get_session
|
| 4 |
+
from app.conversations.conversation_repository import ConversationRepository
|
| 5 |
+
from app.conversations.conversation_service import ConversationService
|
| 6 |
+
from app.conversations.conversation_schema import ConversationCreate, ConversationRead
|
| 7 |
+
from app.conversations.conversation_schema import DraftRequest
|
| 8 |
+
from app.characters.character_repository import CharacterRepository
|
| 9 |
+
from app.ai.qwen_provider import QwenProvider
|
| 10 |
+
from app.config import settings
|
| 11 |
+
|
| 12 |
+
router = APIRouter(prefix="/conversations", tags=["conversations"])
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@router.get("", response_model=list[ConversationRead])
|
| 16 |
+
def list_records(db: Session = Depends(get_session)):
|
| 17 |
+
return ConversationRepository(db).list()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@router.post("", response_model=ConversationRead, status_code=201)
|
| 21 |
+
def create(data: ConversationCreate, db: Session = Depends(get_session)):
|
| 22 |
+
return ConversationService(ConversationRepository(db)).save(data)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@router.post("/draft")
|
| 26 |
+
def draft(data: DraftRequest, db: Session = Depends(get_session)):
|
| 27 |
+
if not settings.enable_ai_drafts:
|
| 28 |
+
raise HTTPException(
|
| 29 |
+
503, "AI dialogue drafting is not functional at the moment for this MVP"
|
| 30 |
+
)
|
| 31 |
+
characters = [CharacterRepository(db).get(i) for i in data.character_ids]
|
| 32 |
+
if len(set(data.character_ids)) != 2 or any(c.archived for c in characters):
|
| 33 |
+
raise HTTPException(422, "Choose two distinct active characters")
|
| 34 |
+
profiles = [{"id": c.id, "name": c.name, "profile": c.profile} for c in characters]
|
| 35 |
+
return {"turns": QwenProvider().generate(data.topic, profiles), "approved": False}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@router.get("/{record_id}", response_model=ConversationRead)
|
| 39 |
+
def get(record_id: str, db: Session = Depends(get_session)):
|
| 40 |
+
return ConversationRepository(db).get(record_id)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@router.put("/{record_id}", response_model=ConversationRead)
|
| 44 |
+
def update(
|
| 45 |
+
record_id: str, data: ConversationCreate, db: Session = Depends(get_session)
|
| 46 |
+
):
|
| 47 |
+
return ConversationService(ConversationRepository(db)).save(data, record_id)
|
backend/app/conversations/conversation_model.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import JSON, String, Boolean
|
| 2 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 3 |
+
from app.shared.base_model import Record
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Conversation(Record):
|
| 7 |
+
__tablename__ = "conversations"
|
| 8 |
+
title: Mapped[str] = mapped_column(String(200))
|
| 9 |
+
mode: Mapped[str] = mapped_column(String(20), default="scripted")
|
| 10 |
+
turns: Mapped[list] = mapped_column(JSON, default=list)
|
| 11 |
+
approved: Mapped[bool] = mapped_column(Boolean, default=False)
|
backend/app/conversations/conversation_repository.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.shared.base_repository import Repository
|
| 2 |
+
from app.conversations.conversation_model import Conversation
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ConversationRepository(Repository):
|
| 6 |
+
model = Conversation
|
backend/app/conversations/conversation_schema.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from typing import Literal
|
| 3 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DialogueTurn(BaseModel):
|
| 7 |
+
character_id: str
|
| 8 |
+
text: str = Field(min_length=1, max_length=1500)
|
| 9 |
+
direction: str = Field(default="", max_length=500)
|
| 10 |
+
pause_after: float = Field(default=0.4, ge=0, le=5)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ConversationCreate(BaseModel):
|
| 14 |
+
title: str = Field(min_length=1, max_length=200)
|
| 15 |
+
mode: Literal["scripted", "generated"] = "scripted"
|
| 16 |
+
turns: list[DialogueTurn] = Field(min_length=1, max_length=40)
|
| 17 |
+
approved: bool = False
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ConversationRead(ConversationCreate):
|
| 21 |
+
model_config = ConfigDict(from_attributes=True)
|
| 22 |
+
id: str
|
| 23 |
+
created_at: datetime
|
| 24 |
+
version: int
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DraftRequest(BaseModel):
|
| 28 |
+
topic: str = Field(min_length=3, max_length=2000)
|
| 29 |
+
character_ids: list[str] = Field(min_length=2, max_length=2)
|
backend/app/conversations/conversation_service.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import HTTPException
|
| 2 |
+
from app.characters.character_repository import CharacterRepository
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ConversationService:
|
| 6 |
+
def __init__(self, repository):
|
| 7 |
+
self.repository = repository
|
| 8 |
+
|
| 9 |
+
def save(self, data, conversation_id=None):
|
| 10 |
+
characters = CharacterRepository(self.repository.session)
|
| 11 |
+
for turn in data.turns:
|
| 12 |
+
if characters.get(turn.character_id).archived:
|
| 13 |
+
raise HTTPException(422, "An archived character cannot be used")
|
| 14 |
+
values = data.model_dump()
|
| 15 |
+
if conversation_id:
|
| 16 |
+
return self.repository.update(self.repository.get(conversation_id), values)
|
| 17 |
+
return self.repository.create(values)
|
backend/app/database.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Generator
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from sqlalchemy import create_engine
|
| 6 |
+
from sqlalchemy.engine import Engine, make_url
|
| 7 |
+
from sqlalchemy.orm import DeclarativeBase, Session
|
| 8 |
+
|
| 9 |
+
from app.config import settings
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Base(DeclarativeBase):
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@lru_cache
|
| 17 |
+
def get_engine() -> Engine:
|
| 18 |
+
url = make_url(settings.database_url)
|
| 19 |
+
options = {}
|
| 20 |
+
if url.get_backend_name() == "sqlite":
|
| 21 |
+
options["check_same_thread"] = False
|
| 22 |
+
if url.database and url.database != ":memory:":
|
| 23 |
+
Path(url.database).parent.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
return create_engine(url, connect_args=options)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_session() -> Generator[Session, None, None]:
|
| 28 |
+
with Session(get_engine()) as session:
|
| 29 |
+
yield session
|
backend/app/generations/__init__.py
ADDED
|
File without changes
|
backend/app/generations/generation_controller.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 2 |
+
from sqlalchemy import update
|
| 3 |
+
from sqlalchemy.orm import Session
|
| 4 |
+
from app.database import get_session
|
| 5 |
+
from app.generations.generation_model import Generation
|
| 6 |
+
from app.generations.generation_repository import GenerationRepository
|
| 7 |
+
from app.generations.generation_service import GenerationService
|
| 8 |
+
from app.generations.generation_schema import (
|
| 9 |
+
GenerationCreate,
|
| 10 |
+
GenerationRead,
|
| 11 |
+
ReviewRequest,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
router = APIRouter(prefix="/generations", tags=["generations"])
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@router.get("", response_model=list[GenerationRead])
|
| 18 |
+
def list_jobs(db: Session = Depends(get_session)):
|
| 19 |
+
return GenerationRepository(db).list()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@router.post("", status_code=201, response_model=GenerationRead)
|
| 23 |
+
def create(data: GenerationCreate, db: Session = Depends(get_session)):
|
| 24 |
+
return GenerationService(GenerationRepository(db)).create(data)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@router.get("/{job_id}", response_model=GenerationRead)
|
| 28 |
+
def get(job_id: str, db: Session = Depends(get_session)):
|
| 29 |
+
return GenerationRepository(db).get(job_id)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@router.post("/{job_id}/retry", status_code=201, response_model=GenerationRead)
|
| 33 |
+
def retry(job_id: str, db: Session = Depends(get_session)):
|
| 34 |
+
repo = GenerationRepository(db)
|
| 35 |
+
return GenerationService(repo).retry(repo.get(job_id))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@router.post("/{job_id}/cancel")
|
| 39 |
+
def cancel(job_id: str, db: Session = Depends(get_session)):
|
| 40 |
+
GenerationRepository(db).get(job_id)
|
| 41 |
+
result = db.execute(
|
| 42 |
+
update(Generation)
|
| 43 |
+
.where(Generation.id == job_id, Generation.status == "queued")
|
| 44 |
+
.values(status="cancelled", stage="Cancelled")
|
| 45 |
+
)
|
| 46 |
+
db.commit()
|
| 47 |
+
if not result.rowcount:
|
| 48 |
+
raise HTTPException(
|
| 49 |
+
409, "Only queued jobs can be cancelled; running GPU calls must finish"
|
| 50 |
+
)
|
| 51 |
+
return {"status": "cancelled"}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@router.post("/{job_id}/review", response_model=GenerationRead)
|
| 55 |
+
def review(job_id: str, data: ReviewRequest, db: Session = Depends(get_session)):
|
| 56 |
+
repo = GenerationRepository(db)
|
| 57 |
+
job = repo.get(job_id)
|
| 58 |
+
if job.status != "completed" or job.settings["kind"] != "animated":
|
| 59 |
+
raise HTTPException(
|
| 60 |
+
409, "Only a completed animated render can receive final review"
|
| 61 |
+
)
|
| 62 |
+
return repo.update(job, {"review": data.model_dump()})
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@router.get("/{job_id}/manifest")
|
| 66 |
+
def manifest(job_id: str, db: Session = Depends(get_session)):
|
| 67 |
+
job = GenerationRepository(db).get(job_id)
|
| 68 |
+
return {
|
| 69 |
+
"id": job.id,
|
| 70 |
+
"status": job.status,
|
| 71 |
+
"inputs": job.settings,
|
| 72 |
+
"review": job.review,
|
| 73 |
+
"duration": job.duration,
|
| 74 |
+
"disclosure": "AI-generated fictional characters",
|
| 75 |
+
}
|
backend/app/generations/generation_model.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import JSON, String, Float, Integer
|
| 2 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 3 |
+
from app.shared.base_model import Record
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Generation(Record):
|
| 7 |
+
__tablename__ = "generations"
|
| 8 |
+
status: Mapped[str] = mapped_column(String(32), default="queued")
|
| 9 |
+
stage: Mapped[str] = mapped_column(String(100), default="Waiting for worker")
|
| 10 |
+
progress: Mapped[int] = mapped_column(Integer, default=0)
|
| 11 |
+
conversation_id: Mapped[str] = mapped_column(String(36))
|
| 12 |
+
scene_id: Mapped[str] = mapped_column(String(36))
|
| 13 |
+
settings: Mapped[dict] = mapped_column(JSON)
|
| 14 |
+
error: Mapped[str | None] = mapped_column(String(2000), nullable=True)
|
| 15 |
+
output_asset_id: Mapped[str | None] = mapped_column(String(36), nullable=True)
|
| 16 |
+
duration: Mapped[float | None] = mapped_column(Float, nullable=True)
|
| 17 |
+
review: Mapped[dict] = mapped_column(JSON, default=dict)
|
backend/app/generations/generation_repository.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.shared.base_repository import Repository
|
| 2 |
+
from app.generations.generation_model import Generation
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class GenerationRepository(Repository):
|
| 6 |
+
model = Generation
|
backend/app/generations/generation_schema.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from typing import Literal
|
| 3 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class GenerationCreate(BaseModel):
|
| 7 |
+
conversation_id: str
|
| 8 |
+
scene_id: str
|
| 9 |
+
kind: Literal["storyboard", "animated"] = "storyboard"
|
| 10 |
+
target_seconds: int = Field(default=60, ge=10, le=65)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class GenerationRead(BaseModel):
|
| 14 |
+
model_config = ConfigDict(from_attributes=True)
|
| 15 |
+
id: str
|
| 16 |
+
created_at: datetime
|
| 17 |
+
version: int
|
| 18 |
+
conversation_id: str
|
| 19 |
+
scene_id: str
|
| 20 |
+
status: str
|
| 21 |
+
stage: str
|
| 22 |
+
progress: int
|
| 23 |
+
settings: dict
|
| 24 |
+
error: str | None
|
| 25 |
+
output_asset_id: str | None
|
| 26 |
+
duration: float | None
|
| 27 |
+
review: dict
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ReviewRequest(BaseModel):
|
| 31 |
+
exact_words: bool
|
| 32 |
+
consistent_identity: bool
|
| 33 |
+
natural_reactions: bool
|
| 34 |
+
lip_sync: bool
|
| 35 |
+
notes: str = Field(default="", max_length=2000)
|
backend/app/generations/generation_service.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import HTTPException
|
| 2 |
+
from app.characters.character_repository import CharacterRepository
|
| 3 |
+
from app.characters.character_schema import CharacterRead
|
| 4 |
+
from app.conversations.conversation_repository import ConversationRepository
|
| 5 |
+
from app.conversations.conversation_schema import ConversationRead
|
| 6 |
+
from app.scenes.scene_repository import SceneRepository
|
| 7 |
+
from app.scenes.scene_schema import SceneRead
|
| 8 |
+
from app.shared.storage_service import StorageService
|
| 9 |
+
from app.config import settings
|
| 10 |
+
from app.ai.provider_readiness import lightweight_ready
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class GenerationService:
|
| 14 |
+
def __init__(self, repository):
|
| 15 |
+
self.repository = repository
|
| 16 |
+
|
| 17 |
+
def create(self, data):
|
| 18 |
+
self.check_feature(data.kind)
|
| 19 |
+
if settings.fixed_demo_mode and data.scene_id != "mvp-scene":
|
| 20 |
+
raise HTTPException(
|
| 21 |
+
403, "Only the built-in scene can be rendered in this MVP"
|
| 22 |
+
)
|
| 23 |
+
db = self.repository.session
|
| 24 |
+
conversation = ConversationRepository(db).get(data.conversation_id)
|
| 25 |
+
scene = SceneRepository(db).get(data.scene_id)
|
| 26 |
+
if not conversation.approved or not scene.approved:
|
| 27 |
+
raise HTTPException(
|
| 28 |
+
422, "Approve the dialogue and shared scene before rendering"
|
| 29 |
+
)
|
| 30 |
+
speakers = {t["character_id"] for t in conversation.turns}
|
| 31 |
+
if speakers != set(scene.character_ids):
|
| 32 |
+
raise HTTPException(
|
| 33 |
+
422, "The dialogue must use both scene characters and no other speakers"
|
| 34 |
+
)
|
| 35 |
+
storage = StorageService(db)
|
| 36 |
+
storage.get(scene.image_asset_id, "image")
|
| 37 |
+
characters = [CharacterRepository(db).get(i) for i in scene.character_ids]
|
| 38 |
+
for c in characters:
|
| 39 |
+
if c.archived:
|
| 40 |
+
raise HTTPException(422, "Restore archived characters before rendering")
|
| 41 |
+
if data.kind == "animated" and settings.speech_provider == "chatterbox":
|
| 42 |
+
if not c.voice_asset_id:
|
| 43 |
+
raise HTTPException(
|
| 44 |
+
422, f"Add an authorized voice reference for {c.name}"
|
| 45 |
+
)
|
| 46 |
+
storage.get(c.voice_asset_id, "voice")
|
| 47 |
+
if data.kind == "animated" and (
|
| 48 |
+
not settings.speech_url or not settings.video_url
|
| 49 |
+
):
|
| 50 |
+
raise HTTPException(
|
| 51 |
+
503,
|
| 52 |
+
"GPU services are not configured. Start the configured speech and video model services. A storyboard is available without GPU services.",
|
| 53 |
+
)
|
| 54 |
+
if (
|
| 55 |
+
data.kind == "animated"
|
| 56 |
+
and settings.speech_provider == "chatterbox"
|
| 57 |
+
and len({c.voice_asset_id for c in characters}) != 2
|
| 58 |
+
):
|
| 59 |
+
raise HTTPException(422, "Choose two distinct voice references")
|
| 60 |
+
snapshot = {
|
| 61 |
+
"kind": data.kind,
|
| 62 |
+
"target_seconds": data.target_seconds,
|
| 63 |
+
"conversation": ConversationRead.model_validate(conversation).model_dump(
|
| 64 |
+
mode="json"
|
| 65 |
+
),
|
| 66 |
+
"scene": SceneRead.model_validate(scene).model_dump(mode="json"),
|
| 67 |
+
"characters": [
|
| 68 |
+
CharacterRead.model_validate(c).model_dump(mode="json")
|
| 69 |
+
for c in characters
|
| 70 |
+
],
|
| 71 |
+
"providers": {
|
| 72 |
+
"speech": settings.speech_provider,
|
| 73 |
+
"video": settings.video_provider,
|
| 74 |
+
"dialogue": settings.dialogue_model,
|
| 75 |
+
},
|
| 76 |
+
}
|
| 77 |
+
return self.repository.create(
|
| 78 |
+
{
|
| 79 |
+
"conversation_id": conversation.id,
|
| 80 |
+
"scene_id": scene.id,
|
| 81 |
+
"settings": snapshot,
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def check_feature(kind):
|
| 87 |
+
if kind == "animated" and not settings.enable_animated_renders:
|
| 88 |
+
raise HTTPException(
|
| 89 |
+
503,
|
| 90 |
+
"Animated speech and lip-sync are not functional at the moment for this MVP",
|
| 91 |
+
)
|
| 92 |
+
if (
|
| 93 |
+
kind == "animated"
|
| 94 |
+
and settings.video_provider == "sadtalker"
|
| 95 |
+
and not lightweight_ready()
|
| 96 |
+
):
|
| 97 |
+
raise HTTPException(
|
| 98 |
+
503,
|
| 99 |
+
"Kokoro/SadTalker service is not ready. Check the GPU deployment logs.",
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def retry(self, job):
|
| 103 |
+
self.check_feature(job.settings["kind"])
|
| 104 |
+
if (
|
| 105 |
+
settings.fixed_demo_mode
|
| 106 |
+
and job.settings["scene"]["image_asset_id"] != "mvp-scene-image"
|
| 107 |
+
):
|
| 108 |
+
raise HTTPException(
|
| 109 |
+
403, "Older custom scenes cannot be re-rendered in this MVP"
|
| 110 |
+
)
|
| 111 |
+
if job.status not in {"failed", "cancelled"}:
|
| 112 |
+
raise HTTPException(409, "Only failed or cancelled jobs can be retried")
|
| 113 |
+
# Preserve the original versioned inputs, even after character edits.
|
| 114 |
+
return self.repository.create(
|
| 115 |
+
{
|
| 116 |
+
"conversation_id": job.conversation_id,
|
| 117 |
+
"scene_id": job.scene_id,
|
| 118 |
+
"settings": job.settings,
|
| 119 |
+
}
|
| 120 |
+
)
|
backend/app/generations/generation_worker.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import time
|
| 4 |
+
import threading
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
from sqlalchemy import select, update
|
| 7 |
+
from sqlalchemy.orm import Session
|
| 8 |
+
from app.database import get_engine
|
| 9 |
+
from app.config import settings
|
| 10 |
+
from app.generations.generation_model import Generation
|
| 11 |
+
from app.shared.storage_service import StorageService
|
| 12 |
+
from app.shared.audio_service import AudioService
|
| 13 |
+
from app.shared.video_service import VideoService
|
| 14 |
+
from app.ai.provider_factory import speech_provider, video_provider
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def claim_job():
|
| 20 |
+
with Session(get_engine()) as db:
|
| 21 |
+
job_id = db.scalar(
|
| 22 |
+
select(Generation.id)
|
| 23 |
+
.where(Generation.status == "queued")
|
| 24 |
+
.order_by(Generation.created_at)
|
| 25 |
+
.limit(1)
|
| 26 |
+
)
|
| 27 |
+
if job_id:
|
| 28 |
+
result = db.execute(
|
| 29 |
+
update(Generation)
|
| 30 |
+
.where(Generation.id == job_id, Generation.status == "queued")
|
| 31 |
+
.values(status="running", stage="Preparing inputs", progress=5)
|
| 32 |
+
)
|
| 33 |
+
db.commit()
|
| 34 |
+
if result.rowcount:
|
| 35 |
+
return job_id
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run_generation(job_id: str):
|
| 40 |
+
with Session(get_engine()) as db:
|
| 41 |
+
job = db.get(Generation, job_id)
|
| 42 |
+
if not job or job.status != "running":
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
def progress(stage, percent):
|
| 46 |
+
job.stage = stage
|
| 47 |
+
job.progress = percent
|
| 48 |
+
db.commit()
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
snapshot = job.settings
|
| 52 |
+
if (
|
| 53 |
+
settings.fixed_demo_mode
|
| 54 |
+
and snapshot["scene"]["image_asset_id"] != "mvp-scene-image"
|
| 55 |
+
):
|
| 56 |
+
raise ValueError("Only the built-in scene can be rendered in this MVP")
|
| 57 |
+
if snapshot["kind"] == "animated" and not settings.enable_animated_renders:
|
| 58 |
+
raise ValueError(
|
| 59 |
+
"Animated speech and lip-sync are not functional at the moment for this MVP"
|
| 60 |
+
)
|
| 61 |
+
storage = StorageService(db)
|
| 62 |
+
scene = snapshot["scene"]
|
| 63 |
+
image = storage.path(storage.get(scene["image_asset_id"], "image"))
|
| 64 |
+
folder = settings.assets_dir / "outputs" / job.id
|
| 65 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 66 |
+
output = folder / "conversation.mp4"
|
| 67 |
+
if snapshot["kind"] == "storyboard":
|
| 68 |
+
progress("Rendering silent storyboard", 40)
|
| 69 |
+
VideoService().storyboard(image, output, snapshot["target_seconds"])
|
| 70 |
+
duration = snapshot["target_seconds"]
|
| 71 |
+
else:
|
| 72 |
+
providers = snapshot["providers"]
|
| 73 |
+
if (
|
| 74 |
+
providers["speech"] != settings.speech_provider
|
| 75 |
+
or providers["video"] != settings.video_provider
|
| 76 |
+
):
|
| 77 |
+
raise ValueError(
|
| 78 |
+
"Providers changed since this job was saved. Create a new render."
|
| 79 |
+
)
|
| 80 |
+
speech = speech_provider(providers["speech"])
|
| 81 |
+
video = video_provider(providers["video"])
|
| 82 |
+
characters = {c["id"]: c for c in snapshot["characters"]}
|
| 83 |
+
turns = snapshot["conversation"]["turns"]
|
| 84 |
+
clips = []
|
| 85 |
+
audio = AudioService()
|
| 86 |
+
for index, turn in enumerate(turns):
|
| 87 |
+
c = characters[turn["character_id"]]
|
| 88 |
+
voice = (
|
| 89 |
+
storage.path(storage.get(c["voice_asset_id"], "voice"))
|
| 90 |
+
if providers["speech"] == "chatterbox"
|
| 91 |
+
else None
|
| 92 |
+
)
|
| 93 |
+
progress(
|
| 94 |
+
f"Generating voice {index + 1}/{len(turns)}",
|
| 95 |
+
10 + int(35 * index / len(turns)),
|
| 96 |
+
)
|
| 97 |
+
raw = speech.synthesize(
|
| 98 |
+
turn["text"], voice, folder / f"raw-{index}.wav", c["profile"]
|
| 99 |
+
)
|
| 100 |
+
clips.append(
|
| 101 |
+
audio.normalize(
|
| 102 |
+
raw,
|
| 103 |
+
folder / f"turn-{index}.wav",
|
| 104 |
+
c["profile"].get("pace", 1),
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
progress("Aligning two speaker tracks", 50)
|
| 108 |
+
tracks, timeline, duration = audio.align(
|
| 109 |
+
turns,
|
| 110 |
+
clips,
|
| 111 |
+
scene["character_ids"],
|
| 112 |
+
folder,
|
| 113 |
+
snapshot["target_seconds"],
|
| 114 |
+
)
|
| 115 |
+
(folder / "timeline.json").write_text(json.dumps(timeline, indent=2))
|
| 116 |
+
progress(
|
| 117 |
+
"Animating both portraits"
|
| 118 |
+
if providers["video"] == "sadtalker"
|
| 119 |
+
else "Animating the shared scene",
|
| 120 |
+
65,
|
| 121 |
+
)
|
| 122 |
+
prompt = (
|
| 123 |
+
scene["prompt"]
|
| 124 |
+
+ " Left-to-right character performance: "
|
| 125 |
+
+ json.dumps(
|
| 126 |
+
[
|
| 127 |
+
{
|
| 128 |
+
"name": c["name"],
|
| 129 |
+
"gestures": c["profile"].get("gestures", ""),
|
| 130 |
+
"personality": c["profile"].get("personality", ""),
|
| 131 |
+
}
|
| 132 |
+
for c in snapshot["characters"]
|
| 133 |
+
]
|
| 134 |
+
)
|
| 135 |
+
)
|
| 136 |
+
prompt += " Per-turn directions: " + json.dumps(
|
| 137 |
+
[
|
| 138 |
+
{
|
| 139 |
+
"character_id": t["character_id"],
|
| 140 |
+
"start": t["start"],
|
| 141 |
+
"end": t["end"],
|
| 142 |
+
"direction": t.get("direction", ""),
|
| 143 |
+
}
|
| 144 |
+
for t in timeline
|
| 145 |
+
]
|
| 146 |
+
)
|
| 147 |
+
raw_video = video.generate(image, tracks, folder / "raw.mp4", prompt)
|
| 148 |
+
progress("Mixing and exporting", 90)
|
| 149 |
+
VideoService().finalize(raw_video, folder / "mix.wav", output)
|
| 150 |
+
# Revocation during a long render prevents publishing its output.
|
| 151 |
+
db.expire_all()
|
| 152 |
+
storage.get(scene["image_asset_id"], "image")
|
| 153 |
+
if (
|
| 154 |
+
snapshot["kind"] == "animated"
|
| 155 |
+
and snapshot["providers"]["speech"] == "chatterbox"
|
| 156 |
+
):
|
| 157 |
+
for c in snapshot["characters"]:
|
| 158 |
+
storage.get(c["voice_asset_id"], "voice")
|
| 159 |
+
job.duration = duration
|
| 160 |
+
job.output_asset_id = storage.register(
|
| 161 |
+
output, "video", f"{snapshot['kind']}-{job.id[:8]}.mp4"
|
| 162 |
+
).id
|
| 163 |
+
job.status = "completed"
|
| 164 |
+
job.stage = (
|
| 165 |
+
"Ready for review"
|
| 166 |
+
if snapshot["kind"] == "animated"
|
| 167 |
+
else "Storyboard ready — no voice or animation"
|
| 168 |
+
)
|
| 169 |
+
job.progress = 100
|
| 170 |
+
db.commit()
|
| 171 |
+
except Exception as exc:
|
| 172 |
+
logger.exception("Generation %s failed", job_id)
|
| 173 |
+
db.rollback()
|
| 174 |
+
job = db.get(Generation, job_id)
|
| 175 |
+
job.status = "failed"
|
| 176 |
+
job.stage = "Needs attention"
|
| 177 |
+
job.error = (
|
| 178 |
+
str(getattr(exc, "detail", str(exc)))[:1800]
|
| 179 |
+
or "Generation failed; inspect worker logs"
|
| 180 |
+
)
|
| 181 |
+
db.commit()
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def main():
|
| 185 |
+
from app.bootstrap import initialize
|
| 186 |
+
|
| 187 |
+
initialize()
|
| 188 |
+
# The deployment runs one worker. Recover jobs interrupted by a process restart.
|
| 189 |
+
with Session(get_engine()) as db:
|
| 190 |
+
db.execute(
|
| 191 |
+
update(Generation)
|
| 192 |
+
.where(Generation.status == "running")
|
| 193 |
+
.values(
|
| 194 |
+
status="failed",
|
| 195 |
+
stage="Worker restarted",
|
| 196 |
+
error="Worker stopped during rendering. Retry this job.",
|
| 197 |
+
)
|
| 198 |
+
)
|
| 199 |
+
db.commit()
|
| 200 |
+
heartbeat = settings.assets_dir.parent / "worker-heartbeat.json"
|
| 201 |
+
|
| 202 |
+
def report_heartbeat():
|
| 203 |
+
while True:
|
| 204 |
+
heartbeat.parent.mkdir(parents=True, exist_ok=True)
|
| 205 |
+
heartbeat.write_text(
|
| 206 |
+
json.dumps({"updated_at": datetime.now(timezone.utc).isoformat()})
|
| 207 |
+
)
|
| 208 |
+
time.sleep(5)
|
| 209 |
+
|
| 210 |
+
threading.Thread(target=report_heartbeat, daemon=True).start()
|
| 211 |
+
while True:
|
| 212 |
+
job_id = claim_job()
|
| 213 |
+
if job_id:
|
| 214 |
+
run_generation(job_id)
|
| 215 |
+
else:
|
| 216 |
+
time.sleep(settings.worker_poll_seconds)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
if __name__ == "__main__":
|
| 220 |
+
main()
|
backend/app/main.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import asynccontextmanager
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from fastapi import FastAPI, HTTPException
|
| 4 |
+
from fastapi.responses import FileResponse
|
| 5 |
+
from app.config import settings
|
| 6 |
+
from app.bootstrap import initialize
|
| 7 |
+
from app.characters.character_controller import router as character_router
|
| 8 |
+
from app.conversations.conversation_controller import router as conversation_router
|
| 9 |
+
from app.scenes.scene_controller import router as scene_router
|
| 10 |
+
from app.generations.generation_controller import router as generation_router
|
| 11 |
+
from app.assets.asset_controller import router as asset_router
|
| 12 |
+
from app.system.system_controller import router as system_router
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@asynccontextmanager
|
| 16 |
+
async def lifespan(app):
|
| 17 |
+
initialize()
|
| 18 |
+
yield
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
app = FastAPI(title=settings.app_name, lifespan=lifespan)
|
| 22 |
+
for router in (
|
| 23 |
+
character_router,
|
| 24 |
+
conversation_router,
|
| 25 |
+
scene_router,
|
| 26 |
+
generation_router,
|
| 27 |
+
asset_router,
|
| 28 |
+
system_router,
|
| 29 |
+
):
|
| 30 |
+
app.include_router(router, prefix="/api/v1")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@app.get("/health", tags=["health"])
|
| 34 |
+
def health():
|
| 35 |
+
return {"status": "ok", "service": settings.app_name}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# The built Vite app and API use the same origin in the Docker deployment.
|
| 39 |
+
frontend = Path(__file__).resolve().parents[2] / "frontend" / "dist"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@app.get("/{path:path}", include_in_schema=False)
|
| 43 |
+
def frontend_app(path: str):
|
| 44 |
+
if path.startswith(("api/", "health/")):
|
| 45 |
+
raise HTTPException(404, "Route not found")
|
| 46 |
+
candidate = (frontend / path).resolve()
|
| 47 |
+
if candidate.is_relative_to(frontend.resolve()) and candidate.is_file():
|
| 48 |
+
return FileResponse(candidate)
|
| 49 |
+
index = frontend / "index.html"
|
| 50 |
+
if not index.is_file():
|
| 51 |
+
raise HTTPException(
|
| 52 |
+
404, "Build the frontend or start the Vite development server"
|
| 53 |
+
)
|
| 54 |
+
return FileResponse(index)
|
backend/app/scenes/__init__.py
ADDED
|
File without changes
|
backend/app/scenes/scene_controller.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends
|
| 2 |
+
from sqlalchemy.orm import Session
|
| 3 |
+
from app.database import get_session
|
| 4 |
+
from app.scenes.scene_repository import SceneRepository
|
| 5 |
+
from app.scenes.scene_service import SceneService
|
| 6 |
+
from app.scenes.scene_schema import SceneCreate, SceneRead
|
| 7 |
+
|
| 8 |
+
router = APIRouter(prefix="/scenes", tags=["scenes"])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@router.get("", response_model=list[SceneRead])
|
| 12 |
+
def list_records(db: Session = Depends(get_session)):
|
| 13 |
+
return SceneRepository(db).list()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@router.post("", response_model=SceneRead, status_code=201)
|
| 17 |
+
def create(data: SceneCreate, db: Session = Depends(get_session)):
|
| 18 |
+
return SceneService(SceneRepository(db)).save(data)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@router.get("/{record_id}", response_model=SceneRead)
|
| 22 |
+
def get(record_id: str, db: Session = Depends(get_session)):
|
| 23 |
+
return SceneRepository(db).get(record_id)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@router.put("/{record_id}", response_model=SceneRead)
|
| 27 |
+
def update(record_id: str, data: SceneCreate, db: Session = Depends(get_session)):
|
| 28 |
+
return SceneService(SceneRepository(db)).save(data, record_id)
|
backend/app/scenes/scene_model.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import JSON, String, Boolean
|
| 2 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 3 |
+
from app.shared.base_model import Record
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Scene(Record):
|
| 7 |
+
__tablename__ = "scenes"
|
| 8 |
+
name: Mapped[str] = mapped_column(String(120))
|
| 9 |
+
image_asset_id: Mapped[str] = mapped_column(String(36))
|
| 10 |
+
character_ids: Mapped[list] = mapped_column(JSON)
|
| 11 |
+
prompt: Mapped[str] = mapped_column(String(4000), default="")
|
| 12 |
+
approved: Mapped[bool] = mapped_column(Boolean, default=False)
|
backend/app/scenes/scene_repository.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.shared.base_repository import Repository
|
| 2 |
+
from app.scenes.scene_model import Scene
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class SceneRepository(Repository):
|
| 6 |
+
model = Scene
|
backend/app/scenes/scene_schema.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class SceneCreate(BaseModel):
|
| 6 |
+
name: str = Field(min_length=1, max_length=120)
|
| 7 |
+
image_asset_id: str
|
| 8 |
+
character_ids: list[str] = Field(min_length=2, max_length=2)
|
| 9 |
+
prompt: str = Field(
|
| 10 |
+
default="Two women in one scene, natural conversation and attentive listening.",
|
| 11 |
+
max_length=4000,
|
| 12 |
+
)
|
| 13 |
+
approved: bool = False
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SceneRead(SceneCreate):
|
| 17 |
+
model_config = ConfigDict(from_attributes=True)
|
| 18 |
+
id: str
|
| 19 |
+
created_at: datetime
|
| 20 |
+
version: int
|
backend/app/scenes/scene_service.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.config import settings
|
| 2 |
+
from fastapi import HTTPException
|
| 3 |
+
from app.characters.character_repository import CharacterRepository
|
| 4 |
+
from app.shared.storage_service import StorageService
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SceneService:
|
| 8 |
+
def __init__(self, repository):
|
| 9 |
+
self.repository = repository
|
| 10 |
+
|
| 11 |
+
def save(self, data, scene_id=None):
|
| 12 |
+
if settings.fixed_demo_mode:
|
| 13 |
+
raise HTTPException(
|
| 14 |
+
403, "This MVP uses the built-in scene; scene editing is disabled"
|
| 15 |
+
)
|
| 16 |
+
if len(set(data.character_ids)) != 2:
|
| 17 |
+
raise HTTPException(
|
| 18 |
+
422, "Choose two different characters, in left-to-right image order"
|
| 19 |
+
)
|
| 20 |
+
for character_id in data.character_ids:
|
| 21 |
+
if CharacterRepository(self.repository.session).get(character_id).archived:
|
| 22 |
+
raise HTTPException(422, "An archived character cannot be used")
|
| 23 |
+
StorageService(self.repository.session).get(data.image_asset_id, "image")
|
| 24 |
+
values = data.model_dump()
|
| 25 |
+
if scene_id:
|
| 26 |
+
return self.repository.update(self.repository.get(scene_id), values)
|
| 27 |
+
return self.repository.create(values)
|