mod-higgsfield / app /main.py
github-actions[bot]
Automated Deploy: 58555e752292dd34bbb1312f29d5942a18053eaa
9ec7973
Raw History Blame Contribute Delete
6.99 kB
"""Testing API behind one shared token. One process; its background worker pool runs inference."""
from contextlib import asynccontextmanager
import json
import logging
import secrets
import time
from fastapi import FastAPI, Header, HTTPException, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from app.catalog import Catalog
from app.characters import Characters
from app.core.body_limit import BodyLimit
from app.core.config import Settings
from app.db import Database
from app.jobs import Jobs, TEST_USER
from app.mcp import build_mcp
from app.schemas import GenerationRequest
from app.storage import Storage
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s %(message)s')
log = logging.getLogger('mod.api')
def create_app(settings=None, db=None, runtime=None):
settings = settings or Settings.from_env()
if settings.environment != 'testing':
raise ValueError('This application is for testing only')
storage = Storage(settings.storage_root)
database = db or Database(settings.database_url)
catalog = Catalog(settings.catalog_file, settings.environment)
characters = Characters(settings.characters_dir)
jobs = Jobs(database, catalog, settings, characters)
# The token is the access control, so the SDK's localhost-only Host check is turned off.
from mcp.server.transport_security import TransportSecuritySettings
mcp_server = build_mcp(jobs, characters, settings)
mcp_app = mcp_server.streamable_http_app(
stateless_http=True, json_response=True,
transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False))
if runtime is None and settings.worker_enabled:
from app.worker import LocalRuntime
runtime = LocalRuntime(database, storage, catalog, settings)
@asynccontextmanager
async def lifespan(app):
database.migrate()
if runtime:
runtime.start()
try:
async with mcp_server.session_manager.run():
yield
finally:
if runtime:
runtime.close()
app = FastAPI(title='Mod Motion · Influencer video', version='0.3.0', lifespan=lifespan)
app.state.jobs, app.state.storage = jobs, storage
def authorized(request):
path = request.url.path
# Artifact links are unguessable IDs so a <video> tag or a pasted link can play them.
if (not settings.api_token or request.method == 'OPTIONS' or path.startswith('/api/v1/artifacts/')
or not path.startswith(('/api/', '/mcp'))):
return True
return secrets.compare_digest(request.headers.get('authorization', '').encode(),
('Bearer ' + settings.api_token).encode())
@app.middleware('http')
async def headers(request, call_next):
request_id, started = secrets.token_hex(12), time.monotonic()
try:
response = (await call_next(request) if authorized(request)
else JSONResponse({'detail': 'A valid access token is required'}, status_code=401))
except Exception:
log.exception('request_failed id=%s', request_id)
response = JSONResponse({'detail': 'The service could not complete the request',
'request_id': request_id}, status_code=503)
response.headers.update({'X-Request-ID': request_id, 'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer', 'Cache-Control': 'no-store',
'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self'; media-src 'self'; base-uri 'self'; form-action 'self'"})
log.info('request id=%s method=%s status=%s ms=%.1f', request_id, request.method,
response.status_code, (time.monotonic()-started)*1000)
return response
# Added after the function middleware so CORS headers also reach 401 responses.
app.add_middleware(BodyLimit, limit=settings.body_limit)
# The frontend is hosted separately (Vercel) and calls this API cross-origin.
app.add_middleware(CORSMiddleware, allow_origins=list(settings.allowed_origins),
allow_methods=['GET', 'POST'],
allow_headers=['Content-Type', 'Idempotency-Key', 'Authorization'])
@app.post('/api/v1/generations/talking-video', status_code=202)
def talking_video(body: GenerationRequest, response: Response, idempotency_key: str = Header()):
result = jobs.submit(TEST_USER, body, 'talking_video', idempotency_key)
response.headers['Location'] = result['status_url']
return result
@app.get('/api/v1/generations/{job_id}')
def get_job(job_id: str):
return jobs.get(TEST_USER, job_id)
@app.post('/api/v1/generations/{job_id}/cancel')
def cancel(job_id: str):
return jobs.cancel(TEST_USER, job_id)
@app.get('/api/v1/artifacts/{asset_id}')
def artifact(asset_id: str, download: bool = False):
asset = jobs.asset(TEST_USER, asset_id)
path = storage.path(asset['storage_key'])
if asset['kind'] != 'video' or not path.is_file():
raise HTTPException(404, 'Video not found')
return FileResponse(path, media_type=json.loads(asset['metadata'])['content_type'],
filename=f'mod-motion-{asset_id}.mp4' if download else None,
content_disposition_type='attachment' if download else 'inline')
@app.get('/api/v1/characters')
def list_characters():
return {'characters': characters.public()}
@app.get('/api/v1/models')
def models():
return catalog.public()
@app.get('/api/v1/health/workers')
def workers():
rows = jobs.workers()
matching = [w for w in rows if w['online'] and w['details'].get('catalog_digest') == catalog.digest]
available = any(w['state'] in ('ready', 'busy') for w in matching)
counts = {state: sum(w['state'] == state for w in matching)
for state in ('ready', 'busy', 'starting', 'failed')}
state = next((state for state in ('ready', 'busy', 'starting', 'failed') if counts[state]), 'offline')
return {'available': available, 'state': state,
'concurrency': settings.worker_concurrency,
'ready_workers': counts['ready'], 'busy_workers': counts['busy']}
@app.get('/health/live')
def live():
return {'status': 'ok'}
@app.get('/health/ready')
def ready():
try:
with database.transaction() as c:
c.execute('SELECT id FROM jobs LIMIT 1')
storage.check()
except Exception:
return JSONResponse({'status': 'unavailable'}, status_code=503)
return {'status': 'ready'}
app.mount('/', mcp_app)
return app