videogen/apps/api/app/services/context_passport.py
caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

118 lines
4.8 KiB
Python

"""Typed client for Railyard's Context Passport (locked brand identity).
Context Passport (``apps/context-passport`` in the Railyard repo, API surface
documented in that app's README) stores a versioned, LOCKABLE brand identity —
palette, typography, logo reference, voice/tone — content-addressed once
locked. This module is Menivor's real caller: it fetches a locked ``brand``
passport and turns its palette into a caption colour ReelForge can actually
burn into a video (see ``reelforge.py``'s ``stage_captions``).
Before this module existed, ReelForge's only brand-consistency mechanism was
the ad-hoc, local ``UserBrand`` row (logo + position + opacity — no colour or
typography at all); Context Passport's own README is explicit that it is a
separate, previously-unwired product. This client closes that gap for the one
real parameter ReelForge's caption pipeline can apply today: the locked
palette's primary colour becomes the karaoke emphasis colour.
The HTTP call itself goes through ``app.integrations.railyard.passport_client
.PassportClient`` — the typed client vendored from Railyard's real
``passport-sdk-python`` (not the hand-rolled ``requests`` call this module
used before), so a non-2xx response raises a typed ``PassportApiError``
carrying the server's stable error ``code`` instead of an opaque
``requests.HTTPError``.
Deliberately failure-tolerant, matching every other best-effort brand lookup
in this codebase (``reelforge._load_user_brand``, ``_resolve_watermark``): no
configured base URL/key, a network error, a ``PassportApiError`` of any kind,
an unlocked passport, or a non-``brand`` kind all yield ``None`` so a Context
Passport outage or misconfiguration can NEVER fail a render job.
"""
from __future__ import annotations
import os
from typing import Any
from loguru import logger
from app.integrations.railyard.passport_client import PassportApiError, PassportClient
__all__ = [
"fetch_locked_brand_assets",
"hex_to_ass_color",
]
_DEFAULT_TIMEOUT_S = 4.0
def _base_url() -> str:
return (os.getenv("CONTEXT_PASSPORT_BASE_URL") or "").strip().rstrip("/")
def _api_key() -> str:
return (os.getenv("CONTEXT_PASSPORT_API_KEY") or "").strip()
def fetch_locked_brand_assets(passport_id: str) -> dict[str, Any] | None:
"""Fetch a LOCKED ``brand`` Context Passport's assets via the typed client.
Calls ``GET {CONTEXT_PASSPORT_BASE_URL}/v1/passports/{passport_id}`` with
``X-API-Key: {CONTEXT_PASSPORT_API_KEY}`` (through ``PassportClient.get``)
and returns the head version's ``assets`` dict (``{kind, logo_ref,
palette, typography, watermark_ref, voice_tone}``) only when the head
version is actually locked and its kind is ``brand`` — an un-locked draft
or a mismatched kind both correctly yield ``None`` rather than letting an
in-progress edit silently leak into a live render.
Returns ``None`` on any missing config, invalid base URL, network error,
``PassportApiError`` (including the stable ``version_locked`` /
``not_found`` codes — there is nothing a best-effort brand lookup can do
about either), unlocked head, or non-brand kind. Never raises.
"""
base = _base_url()
key = _api_key()
if not base or not key or not passport_id:
return None
try:
client = PassportClient(base, key, timeout=_DEFAULT_TIMEOUT_S)
view = client.get(passport_id)
head = view.get("head") or {}
except PassportApiError as exc:
logger.warning(
f"context passport fetch failed for {passport_id!r} (non-fatal): "
f"HTTP {exc.status} ({exc.code})"
)
return None
except Exception as exc: # noqa: BLE001 - brand lookup is best-effort
logger.warning(f"context passport fetch failed for {passport_id!r} (non-fatal): {exc}")
return None
if head.get("status") != "locked":
logger.info(f"context passport {passport_id!r} head is not locked; skipping")
return None
assets = head.get("assets") or {}
if assets.get("kind") != "brand":
logger.warning(f"context passport {passport_id!r} is not a brand passport; skipping")
return None
return assets
def hex_to_ass_color(hex_color: str) -> str | None:
"""Convert a ``#RRGGBB`` hex colour to ASS ``&HBBGGRR&`` override form.
ASS stores colour as alpha-blue-green-red; the leading ``00`` alpha byte
makes it fully opaque, matching every other colour constant in
``app.services.captions.presets``. Returns ``None`` for anything that
isn't exactly 6 valid hex digits (optionally ``#``-prefixed) so a
malformed locked palette value never reaches ``write_ass``.
"""
digits = hex_color.strip().lstrip("#")
if len(digits) != 6:
return None
try:
r, g, b = digits[0:2], digits[2:4], digits[4:6]
int(digits, 16)
except ValueError:
return None
return f"&H00{b}{g}{r}".upper()