Add FastAPI web service for video transcoding management

Implements a complete video transcoding web service with:
- FastAPI framework for REST API
- SQLAlchemy ORM with SQLite database
- API key authentication using SHA256 hashing
- Per-user resource isolation for all assets and jobs
- S3-compatible file upload/download/delete/list interface
- YAML-based API for transcode job requests
- Transcode profile management (stored and inline)
- Database models for Users, APIKeys, Assets, Jobs, and Profiles
- CLI entry point for database initialization and server startup
- Comprehensive integration tests with 100% pass rate
- Deployment documentation with examples

New files:
- privatestudio/web/: Web service package
- privatestudio/web/models.py: SQLAlchemy ORM models
- privatestudio/web/auth.py: API key authentication
- privatestudio/web/database.py: Database configuration
- privatestudio/web/app.py: FastAPI application
- privatestudio/web/s3_interface.py: File storage backend
- privatestudio/web/cli.py: CLI commands
- privatestudio/web/routes/: API endpoint handlers
- tests/test_web.py: Integration tests
- DEPLOYMENT.md: Deployment guide

Updated files:
- pyproject.toml: Added dependencies and CLI entry point

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Shaun Kruger
2026-11-22 15:28:25 -07:00
co-authored by Copilot
parent 72b4fcc107
commit 057d6bed5c
17 changed files with 1664 additions and 0 deletions
+181
View File
@@ -0,0 +1,181 @@
"""YAML-based transcode job request endpoints."""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel
import yaml
from privatestudio.web.database import get_db
from privatestudio.web.models import User, TranscodeJob, UploadedAsset, TranscodeProfile
from privatestudio.web.auth import get_current_user
router = APIRouter()
class TranscodeJobResponse(BaseModel):
"""Response model for transcode job."""
id: int
asset_id: int
profile_id: int | None
status: str
requested_at: str
class Config:
from_attributes = True
@router.post("/transcode")
def request_transcode(
body: str, # Raw YAML body
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""
Request a transcode job with YAML definition.
The request body should contain YAML like:
```yaml
asset: "video.mp4" # Asset name or ID
profile: "hd-profile" # Profile name, or inline profile definition
```
Or with inline profile:
```yaml
asset: "video.mp4"
profile:
profiles:
hd:
resolution: "1280x720"
bitrate: "2500k"
```
"""
# Parse YAML
try:
request_data = yaml.safe_load(body)
if not isinstance(request_data, dict):
raise ValueError("Request must be a YAML mapping")
except yaml.YAMLError as e:
raise HTTPException(status_code=400, detail=f"Invalid YAML: {e}")
# Get asset
asset_ref = request_data.get("asset")
if not asset_ref:
raise HTTPException(status_code=400, detail="Request must specify 'asset'")
# Try to find asset by name or ID
asset = None
try:
asset_id = int(asset_ref)
asset = db.query(UploadedAsset).filter(
UploadedAsset.id == asset_id,
UploadedAsset.user_id == current_user.id,
).first()
except ValueError:
# Not an ID, try as filename
asset = db.query(UploadedAsset).filter(
UploadedAsset.filename == asset_ref,
UploadedAsset.user_id == current_user.id,
).first()
if not asset:
raise HTTPException(status_code=404, detail=f"Asset '{asset_ref}' not found")
# Get or validate profile
profile_ref = request_data.get("profile")
if not profile_ref:
raise HTTPException(status_code=400, detail="Request must specify 'profile'")
profile_id = None
profile_definition = None
if isinstance(profile_ref, str):
# Profile name reference
profile = db.query(TranscodeProfile).filter(
TranscodeProfile.name == profile_ref,
TranscodeProfile.user_id == current_user.id,
).first()
if not profile:
raise HTTPException(status_code=404, detail=f"Profile '{profile_ref}' not found")
profile_id = profile.id
profile_definition = profile.profile_definition
elif isinstance(profile_ref, dict):
# Inline profile definition
try:
# Validate it has a 'profiles' section
if "profiles" not in profile_ref:
raise ValueError("Inline profile must contain a 'profiles' section")
profile_definition = yaml.dump(profile_ref)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid profile definition: {e}")
else:
raise HTTPException(status_code=400, detail="Profile must be a string (name) or object (definition)")
# Create transcode job
job = TranscodeJob(
user_id=current_user.id,
asset_id=asset.id,
profile_id=profile_id,
status="pending",
)
db.add(job)
db.commit()
db.refresh(job)
return TranscodeJobResponse(
id=job.id,
asset_id=job.asset_id,
profile_id=job.profile_id,
status=job.status,
requested_at=job.requested_at.isoformat(),
)
@router.get("/transcode/{job_id}", response_model=TranscodeJobResponse)
def get_transcode_job(
job_id: int,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Get status of a transcode job."""
job = db.query(TranscodeJob).filter(
TranscodeJob.id == job_id,
TranscodeJob.user_id == current_user.id,
).first()
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return TranscodeJobResponse(
id=job.id,
asset_id=job.asset_id,
profile_id=job.profile_id,
status=job.status,
requested_at=job.requested_at.isoformat(),
)
@router.get("/transcode", response_model=list[TranscodeJobResponse])
def list_transcode_jobs(
status: str | None = None,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""List transcode jobs for the current user."""
query = db.query(TranscodeJob).filter(TranscodeJob.user_id == current_user.id)
if status:
query = query.filter(TranscodeJob.status == status)
jobs = query.all()
return [
TranscodeJobResponse(
id=job.id,
asset_id=job.asset_id,
profile_id=job.profile_id,
status=job.status,
requested_at=job.requested_at.isoformat(),
)
for job in jobs
]