cmvr-visual/backend/app/services/system.py

206 lines
8.6 KiB
Python
Raw Normal View History

"""状态与能力的业务读取;不持有 HTTP Request。"""
import asyncio
import time
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from app.adapters.provider.client import capabilities as provider_capabilities
from app.adapters.provider.contracts import (
H3_CERTIFIED_REVISION,
H3_CERTIFICATION_REASON,
H3_TP2_CERTIFICATION_REASON,
h3_tp2_certified,
)
from app.core.maintenance import maintenance_active
from app.core.runtime_policy import read_runtime_policy
from app.domain.video_generation import H3_PROFILE, H3_V2_PROFILE, H3_TP2_PROFILE
from app.services.orchestration.resource_policy import execution_policy
from app.domain.timeline import (
DEFAULT_SOURCE_FRAMES,
MAX_SOURCE_FRAMES,
DEFAULT_CLIP_FRAMES,
MAX_CLIP_FRAMES,
)
def workflow_limits(policy):
return {
"max_shots": policy["workflow_max_shots"],
"source_frames": DEFAULT_SOURCE_FRAMES,
"default_source_frames": DEFAULT_SOURCE_FRAMES,
"max_source_frames": MAX_SOURCE_FRAMES,
"default_clip_frames": DEFAULT_CLIP_FRAMES,
"max_clip_frames": MAX_CLIP_FRAMES,
"fps": 24,
}
async def health(runtime):
async with runtime.db.session() as session:
await session.execute(text("SELECT 1"))
return {"status": "ok", "database": runtime.settings.sqlalchemy_url.get_backend_name()}
async def readiness(runtime):
checks = {
"database": False,
"coordinator": True,
"upstream_protocol": False,
"accepting": not runtime.draining and (not maintenance_active(runtime.settings)),
}
try:
async with runtime.db.session() as session:
await session.execute(text("SELECT 1"))
checks["database"] = True
except SQLAlchemyError:
pass
coordinator = runtime.coordinator
if runtime.settings.run_coordinator:
heartbeat = getattr(coordinator, "last_tick_success", None)
checks["coordinator"] = bool(
coordinator._task
and (not coordinator._task.done())
and (heartbeat is not None)
and (time.monotonic() - heartbeat < 90)
)
try:
caps = await asyncio.wait_for(runtime.provider.upstream_capabilities(), 3)
checks["upstream_protocol"] = caps.get("protocol_version", 0) >= 2 and bool(
caps.get("admission_policy")
)
except (Exception, asyncio.TimeoutError):
pass
return checks
async def task_capabilities(runtime):
items = provider_capabilities(runtime.settings)
generation = [row for row in items if row["task_type"] == "video.generate"]
video = [row for row in items if row["task_type"] in {"video.people.analyze", "video.replace"}]
generation_configured = bool(generation and getattr(runtime.settings, "inference_base_url", ""))
upstream_snapshot = {}
if generation_configured or any(row["available"] for row in video):
try:
upstream_snapshot = await runtime.provider.upstream_capabilities()
except Exception:
pass
if not isinstance(upstream_snapshot, dict):
upstream_snapshot = {}
if generation_configured:
upstream = upstream_snapshot.get("video_generation", {})
# PoC模式不能在业务界面声明H3已就绪;地址、真值字符串或旧证书都不构成正式认证。
certified = (
isinstance(upstream, dict)
and upstream.get("available") is True
and upstream.get("profile") == H3_PROFILE
and upstream.get("revision") == H3_CERTIFIED_REVISION
)
v2 = upstream.get("v2") if isinstance(upstream, dict) else None
v2_ready = (
isinstance(v2, dict)
and v2.get("available") is True
and v2.get("profile") == H3_V2_PROFILE
and v2.get("revision") == H3_CERTIFIED_REVISION
and v2.get("adapter_contract_version") == "h3-fl2va-v2"
and v2.get("input_modes") == ["first_frame", "first_last_frame"]
and v2.get("output_policy") == "full_native"
and v2.get("native_frame_counts") == list(range(124, 346, 17))
and v2.get("fps") == 24
and v2.get("canvases") == [[1344, 768], [768, 1344]]
)
tp2_ready = h3_tp2_certified(upstream.get("tp2") if isinstance(upstream, dict) else None)
for row in generation:
for profile in row.get("video_profiles", []):
if profile["profile"] == H3_TP2_PROFILE:
profile.update(
available=tp2_ready,
reason=None if tp2_ready else H3_TP2_CERTIFICATION_REASON,
)
if profile["profile"] == H3_V2_PROFILE:
profile.update(
available=v2_ready, reason=None if v2_ready else H3_CERTIFICATION_REASON
)
if profile["profile"] == H3_PROFILE:
profile["available"] = certified
profile["reason"] = None if certified else H3_CERTIFICATION_REASON
if not certified:
profile["description"] = H3_CERTIFICATION_REASON
if row["defaults"].get("profile") == H3_TP2_PROFILE:
row.update(
available=tp2_ready, reason=None if tp2_ready else H3_TP2_CERTIFICATION_REASON
)
if not tp2_ready:
row["description"] = H3_TP2_CERTIFICATION_REASON
if row["defaults"].get("profile") == H3_V2_PROFILE:
row.update(available=v2_ready, reason=None if v2_ready else H3_CERTIFICATION_REASON)
if row["defaults"].get("profile") == H3_PROFILE:
row["available"] = certified
row["reason"] = None if certified else H3_CERTIFICATION_REASON
if not certified:
row["description"] = H3_CERTIFICATION_REASON
if any(row["available"] for row in video):
upstream = upstream_snapshot.get("video_edit", {})
if not isinstance(upstream, dict):
upstream = {}
for row in video:
if (
upstream.get("available") is not True
or upstream.get("profile") != row["defaults"]["profile"]
or upstream.get("fps") != 24
):
row["available"] = False
row["reason"] = row["description"] = "上游视频编辑未完成认证或模型版本不匹配。"
else:
for key in ("max_seconds", "max_people", "max_pixels"):
value = upstream.get(key)
if type(value) is not int or value < 1:
row["available"] = False
row["reason"] = row["description"] = "上游视频编辑能力合同无效。"
else:
row["constraints"][key] = min(row["constraints"][key], value)
for row in video:
row.setdefault("reason", None if row["available"] else row["description"])
return items
async def capabilities(runtime):
policy = read_runtime_policy(runtime.settings)
return {
"editable_production": {
"schema_version": 1,
"supported_schema_versions": [1, 2],
"preferred_schema_version": 2,
"story_schema_versions": [3, 4],
"continuity": {
"available": bool(getattr(runtime.settings, "continuity_quality_certified", False)),
"reason": None
if getattr(runtime.settings, "continuity_quality_certified", False)
else "连续性质检尚未完成真实样例认证,可先编辑和规划。",
"max_shots": 60,
"max_total_frames": 7200,
"max_mix_segments": 128,
},
},
"items": await task_capabilities(runtime),
"scheduler": await runtime.provider.scheduler_status(),
"execution_policy": execution_policy(settings=runtime.settings),
"workflow_limits": workflow_limits(policy),
}
async def status(runtime):
policy = read_runtime_policy(runtime.settings)
online, scheduler = await asyncio.gather(
runtime.provider.health(), runtime.provider.scheduler_status()
)
return {
"inference_online": online,
"scheduler": scheduler,
"models": await task_capabilities(runtime),
"environment": runtime.settings.mode,
"database_backend": runtime.settings.sqlalchemy_url.get_backend_name(),
"execution_policy": execution_policy(settings=runtime.settings),
"workflow_limits": workflow_limits(policy),
"public_access": getattr(runtime.settings, "public_access", False),
}