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

340 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""状态与能力的业务读取;不持有 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,
H3_NATIVE_AV_PROFILES,
)
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:
from app.adapters.provider.native_av import (
certified as native_certified,
enabled as native_enabled,
select_evidence as native_evidence,
CERTIFICATION_REASON as NATIVE_REASON,
)
runtime.settings._native_av_upstream = upstream_snapshot
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"] in H3_NATIVE_AV_PROFILES:
selected = profile["profile"]
evidence = native_evidence(upstream_snapshot, selected)
ready = native_enabled(runtime.settings, selected) and native_certified(
evidence, selected
)
profile.update(
available=ready,
reason=None if ready else NATIVE_REASON,
canvases=[list(c) for c in evidence["canvases"]] if ready else [],
)
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 row["defaults"].get("profile") in H3_NATIVE_AV_PROFILES:
selected = next(
p for p in row["video_profiles"] if p["profile"] == row["defaults"]["profile"]
)
row.update(available=selected["available"], reason=selected["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"])
from app.adapters.provider.dialogue_gpu import KEYS, certified, select_evidence
dialogue = upstream_snapshot.get("dialogue", {})
dialogue = dialogue if isinstance(dialogue, dict) else {}
runtime.settings._dialogue_upstream = dialogue
for row in items:
if row["task_type"] not in KEYS:
continue
evidence = select_evidence(dialogue, row["task_type"])
row["available"] = row["available"] is True and certified(row["task_type"], evidence)
row["reason"] = None if row["available"] else "对白模型或对应处理阶段尚未通过部署认证。"
if row["available"]:
row["constraints"]["max_people"] = evidence["max_people"]
from app.adapters.provider.native_av import alignment_enabled, ALIGNMENT_REASON
alignment_ready = alignment_enabled(runtime.settings, upstream_snapshot)
for row in items:
if row["task_type"] == "audio.dialogue.inspect":
row["native_alignment"] = dict(
available=alignment_ready, reason=None if alignment_ready else ALIGNMENT_REASON
)
if alignment_ready:
row.update(available=True, reason=None)
return items
async def refresh_dialogue_capabilities(runtime):
"""只读协商结果;私有证据不由浏览器提交,超时保持关闭。"""
try:
upstream = await asyncio.wait_for(runtime.provider.upstream_capabilities(), 3)
result = upstream.get("dialogue", {}) if isinstance(upstream, dict) else {}
runtime.settings._native_av_upstream = upstream if isinstance(upstream, dict) else {}
except Exception:
result = {}
runtime.settings._native_av_upstream = {}
runtime.settings._dialogue_upstream = result if isinstance(result, dict) else {}
return runtime.settings._dialogue_upstream
async def capabilities(runtime):
policy = read_runtime_policy(runtime.settings)
items = await task_capabilities(runtime)
by_task = {item["task_type"]: item for item in items}
dialogue = dict(authoring_available=True)
generation = by_task.get("video.generate", {})
native_profiles = [
p for p in generation.get("video_profiles", []) if p["profile"] in H3_NATIVE_AV_PROFILES
]
alignment_ready = (
by_task.get("audio.dialogue.inspect", {}).get("native_alignment", {}).get("available")
is True
)
generation_ready = any(p.get("available") is True for p in native_profiles)
visual_review_ready = by_task.get("video.dialogue.review", {}).get("available") is True
native_ready = generation_ready and alignment_ready and visual_review_ready
from app.adapters.provider.native_av import (
TURN_CERTIFICATION_REASON,
turn_evidence,
turn_certificate,
CERTIFICATION_REASON as NATIVE_REASON,
ALIGNMENT_REASON,
)
native_reason = (
NATIVE_REASON
if not generation_ready
else ALIGNMENT_REASON
if not alignment_ready
else "原生对白画面质检尚未就绪,请配置Qwen并完成视觉评审认证。"
if not visual_review_ready
else None
)
snapshot = getattr(runtime.settings, "_native_av_upstream", {})
proof = turn_evidence(snapshot)
turn_ready = bool(native_ready and turn_certificate(snapshot,proof) and any(p["profile"]==proof.get("profile") and p.get("available") for p in native_profiles))
dialogue["native_av"] = dict(
available=native_ready,
production_available=native_ready,
profiles=[p["profile"] for p in native_profiles],
profile_options=native_profiles,
languages=["Chinese"],
readiness=dict(
generation=generation_ready,
word_alignment=alignment_ready,
visual_review=visual_review_ready,
),
two_person_turns=dict(
supported=True,
available=turn_ready,
reason=None if turn_ready else TURN_CERTIFICATION_REASON,
profile=proof.get("profile") if turn_ready else None,
num_frames=proof.get("num_frames") if turn_ready else None,
),
supports_single_face=native_ready,
supports_two_faces=turn_ready,
max_visible_speakers=2 if turn_ready else 1,
language="Chinese",
reason=native_reason,
)
dialogue.update(
available=native_ready,
production_available=native_ready,
supports_single_face=native_ready,
supports_two_faces=turn_ready,
max_visible_speakers=2 if turn_ready else 1,
reason=native_reason,
)
return {
"dialogue": dialogue,
"editable_production": {
"schema_version": 1,
"supported_schema_versions": [1, 2, 3, 4],
"preferred_schema_version": 3,
"story_schema_versions": [3, 4, 5, 6],
"dialogue": dialogue,
"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": items,
"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),
}