408 lines
15 KiB
Python
408 lines
15 KiB
Python
|
|
"""Keep candidate jobs and assessments under one frozen parent workflow."""
|
|||
|
|
|
|||
|
|
from copy import deepcopy
|
|||
|
|
import json
|
|||
|
|
|
|||
|
|
from sqlalchemy import func, select
|
|||
|
|
|
|||
|
|
from app.core.errors import fail
|
|||
|
|
from app.models import Asset, WorkflowStep
|
|||
|
|
from app.models.workflows import WorkflowVariant, QualityAssessment
|
|||
|
|
from app.services.workflows import digest, verified_output
|
|||
|
|
|
|||
|
|
|
|||
|
|
def enabled(manifest):
|
|||
|
|
return manifest.get("schema_version") == 2 and manifest["spec"].get("schema_version") == 4
|
|||
|
|
|
|||
|
|
|
|||
|
|
def quality_action(verdict, ordinal, used, policy, locked):
|
|||
|
|
if verdict == "pass":
|
|||
|
|
return "accept"
|
|||
|
|
if (
|
|||
|
|
verdict == "reject"
|
|||
|
|
and not locked
|
|||
|
|
and ordinal < min(2, policy.get("max_repairs_per_shot", 2))
|
|||
|
|
and used < min(12, policy.get("max_total_repairs", 12))
|
|||
|
|
):
|
|||
|
|
return "repair"
|
|||
|
|
return "blocked"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def location(run, step):
|
|||
|
|
manifest = run.result_manifest
|
|||
|
|
sid = step.recipe_json["unit_id"]
|
|||
|
|
index = manifest["shot_ids"].index(sid)
|
|||
|
|
return manifest["spec"]["shots"][index], index
|
|||
|
|
|
|||
|
|
|
|||
|
|
def inspection(run, step, candidate):
|
|||
|
|
shot, index = location(run, step)
|
|||
|
|
edge = shot["continuity"]
|
|||
|
|
timing = run.prepared_plan["timing"]["shots"][index]
|
|||
|
|
expected = {k: edge[k] for k in ("state_in", "state_out", "expected_motion", "transition")}
|
|||
|
|
expected["fps"] = 24
|
|||
|
|
expected["dedup_frames"] = timing["dedup_frames"]
|
|||
|
|
expected.update({k: timing[k] for k in ("source_start_frame", "source_end_frame")})
|
|||
|
|
ids = [candidate["asset_id"]]
|
|||
|
|
hashes = {ids[0]: candidate["sha256"]}
|
|||
|
|
inputs = dict(video_asset_id=ids[0], asset_ids=ids, expected=expected)
|
|||
|
|
if edge["transition"] == "continue":
|
|||
|
|
previous = run.result_manifest["shot_ids"][index - 1]
|
|||
|
|
binding = run.result_manifest["bindings"]["video:" + previous]
|
|||
|
|
inputs["previous_video_asset_id"] = binding["asset_id"]
|
|||
|
|
expected["previous_start_frame"] = run.prepared_plan["timing"]["shots"][index - 1][
|
|||
|
|
"source_start_frame"
|
|||
|
|
]
|
|||
|
|
expected["previous_end_frame"] = run.prepared_plan["timing"]["shots"][index - 1][
|
|||
|
|
"source_end_frame"
|
|||
|
|
]
|
|||
|
|
if binding["asset_id"] not in ids:
|
|||
|
|
ids.append(binding["asset_id"])
|
|||
|
|
hashes[binding["asset_id"]] = binding["sha256"]
|
|||
|
|
return dict(
|
|||
|
|
task_type="video.continuity.inspect", input=inputs, parameters={}, input_sha256=hashes
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def model_hash(resolved):
|
|||
|
|
# QA can re-extract byte-identical anchors under new asset IDs.
|
|||
|
|
inputs = deepcopy(resolved["input"])
|
|||
|
|
for k in ("image_asset_id", "first_frame_asset_id", "last_frame_asset_id"):
|
|||
|
|
if k in inputs:
|
|||
|
|
inputs[k] = resolved["input_sha256"][inputs[k]]
|
|||
|
|
return digest({"input": inputs, "parameters": resolved["parameters"]})
|
|||
|
|
|
|||
|
|
|
|||
|
|
def generated_candidate(binding, actual, base, requested_parameters):
|
|||
|
|
# 实际输入用于复现;作者请求摘要用于复用。force/repair换seed不能伪装成作者改了配置。
|
|||
|
|
requested = deepcopy(base)
|
|||
|
|
if "seed" in requested_parameters:
|
|||
|
|
requested["parameters"]["seed"] = requested_parameters["seed"]
|
|||
|
|
return {
|
|||
|
|
**deepcopy(binding),
|
|||
|
|
"context_hash": model_hash(actual),
|
|||
|
|
"provenance": {
|
|||
|
|
**(binding.get("provenance") or {}),
|
|||
|
|
"requested_context_hash": model_hash(requested),
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def matches_request(candidate, resolved):
|
|||
|
|
provenance = candidate.get("provenance") or {}
|
|||
|
|
expected = provenance.get("requested_context_hash", candidate.get("context_hash"))
|
|||
|
|
return expected == model_hash(resolved)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def latest(session, run, step):
|
|||
|
|
return await session.scalar(
|
|||
|
|
select(WorkflowVariant)
|
|||
|
|
.where(WorkflowVariant.run_id == run.id, WorkflowVariant.step_key == step.step_key)
|
|||
|
|
.order_by(WorkflowVariant.ordinal.desc())
|
|||
|
|
.limit(1)
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def freeze_prepared_plan(session, run):
|
|||
|
|
from app.domain.continuity import compile_story_timing
|
|||
|
|
|
|||
|
|
if run.prepared_plan is not None:
|
|||
|
|
return
|
|||
|
|
author = deepcopy(run.plan_snapshot["manifest"])
|
|||
|
|
author["spec"] = deepcopy(run.result_manifest["spec"])
|
|||
|
|
author["audio"] = deepcopy(run.result_manifest.get("audio", {}))
|
|||
|
|
author["bindings"].update(
|
|||
|
|
{
|
|||
|
|
key: deepcopy(value)
|
|||
|
|
for key, value in run.result_manifest["bindings"].items()
|
|||
|
|
if key.startswith("audio:")
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
frozen = {
|
|||
|
|
"timing": compile_story_timing(author["spec"]),
|
|||
|
|
"manifest": author,
|
|||
|
|
"plan_hash": run.plan_snapshot["plan_hash"],
|
|||
|
|
}
|
|||
|
|
prepared = (
|
|||
|
|
await session.scalars(
|
|||
|
|
select(WorkflowStep)
|
|||
|
|
.where(
|
|||
|
|
WorkflowStep.run_id == run.id,
|
|||
|
|
WorkflowStep.kind.in_(
|
|||
|
|
[
|
|||
|
|
"audio.mix",
|
|||
|
|
"audio.normalize",
|
|||
|
|
"audio.speech",
|
|||
|
|
"text.script.generate",
|
|||
|
|
"text.story.plan",
|
|||
|
|
]
|
|||
|
|
),
|
|||
|
|
)
|
|||
|
|
.order_by(WorkflowStep.step_key)
|
|||
|
|
)
|
|||
|
|
).all()
|
|||
|
|
if any(row.state != "succeeded" for row in prepared):
|
|||
|
|
fail(409, "preparation_incomplete", "等待准备步骤完成")
|
|||
|
|
plan = {
|
|||
|
|
**frozen,
|
|||
|
|
"recipes": deepcopy(run.plan_snapshot["steps"]),
|
|||
|
|
"preparation": {
|
|||
|
|
row.step_key: {
|
|||
|
|
"resolved_input": deepcopy(row.resolved_input_json),
|
|||
|
|
"result": deepcopy(row.result_json),
|
|||
|
|
}
|
|||
|
|
for row in prepared
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
run.prepared_plan = {**plan, "prepared_hash": digest(plan)}
|
|||
|
|
run.phase = "production"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def endpoint_trim_conflict(run, step, parameters):
|
|||
|
|
if parameters.get("conditioning_mode") != "first_last_frame":
|
|||
|
|
return False
|
|||
|
|
shot, _ = location(run, step)
|
|||
|
|
edit = shot["edit"]
|
|||
|
|
return edit["start_frame"] != 0 or edit["duration_frames"] != parameters["num_frames"]
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def prepare(session, run, step, settings):
|
|||
|
|
from .editor_engine import _resolve
|
|||
|
|
|
|||
|
|
await freeze_prepared_plan(session, run)
|
|||
|
|
current = await latest(session, run, step)
|
|||
|
|
if current is None:
|
|||
|
|
candidate = step.recipe_json.get("candidate")
|
|||
|
|
if candidate and candidate.get("source") == "manual":
|
|||
|
|
resolved = inspection(run, step, candidate)
|
|||
|
|
else:
|
|||
|
|
resolved = await _resolve(session, run, step, settings)
|
|||
|
|
if candidate and not matches_request(candidate, resolved):
|
|||
|
|
if candidate.get("locked"):
|
|||
|
|
fail(409, "locked_dependency_changed", "已锁定的视频与当前首尾帧或生成意图不符")
|
|||
|
|
candidate = None
|
|||
|
|
current = WorkflowVariant(
|
|||
|
|
run_id=run.id,
|
|||
|
|
step_key=step.step_key,
|
|||
|
|
ordinal=0,
|
|||
|
|
resolved_input=resolved,
|
|||
|
|
candidate=candidate,
|
|||
|
|
state="assessing" if candidate else "generating",
|
|||
|
|
)
|
|||
|
|
session.add(current)
|
|||
|
|
await session.flush()
|
|||
|
|
if current.state == "generating" and endpoint_trim_conflict(
|
|||
|
|
run, step, current.resolved_input["parameters"]
|
|||
|
|
):
|
|||
|
|
fail(409, "endpoint_trim_conflict", "新生成的首尾帧视频必须选用完整原生帧区间")
|
|||
|
|
if current.state not in ("generating", "assessing"):
|
|||
|
|
fail(409, "quality_decision_final", "此候选已有质量判定")
|
|||
|
|
step.resolved_input_json = (
|
|||
|
|
inspection(run, step, current.candidate)
|
|||
|
|
if current.state == "assessing"
|
|||
|
|
else deepcopy(current.resolved_input)
|
|||
|
|
)
|
|||
|
|
if current.model_input_hash is None:
|
|||
|
|
current.model_input_hash = (
|
|||
|
|
digest(current.resolved_input)
|
|||
|
|
if current.resolved_input.get("task_type")
|
|||
|
|
else model_hash(current.resolved_input)
|
|||
|
|
)
|
|||
|
|
current.provenance_hash = digest(
|
|||
|
|
{
|
|||
|
|
"plan": run.prepared_plan["prepared_hash"],
|
|||
|
|
"source_edges": step.recipe_json.get("source_edges", {}),
|
|||
|
|
"resolved": current.resolved_input,
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
step.semantic_input_hash = digest(step.resolved_input_json)
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def collect(session, run, step, job, settings):
|
|||
|
|
from .editor_engine import _collect, _add_ref, _resolve
|
|||
|
|
|
|||
|
|
variant = await latest(session, run, step)
|
|||
|
|
if job.task_type == "video.generate":
|
|||
|
|
before = deepcopy(run.result_manifest)
|
|||
|
|
await _collect(session, run, step, job, settings)
|
|||
|
|
base = await _resolve(session, run, step, settings)
|
|||
|
|
variant.candidate = generated_candidate(
|
|||
|
|
step.result_json,
|
|||
|
|
variant.resolved_input,
|
|||
|
|
base,
|
|||
|
|
step.recipe_json.get("requested_parameters", {}),
|
|||
|
|
)
|
|||
|
|
variant.generation_job_id = job.id
|
|||
|
|
run.result_manifest = before
|
|||
|
|
variant.state = "assessing"
|
|||
|
|
else:
|
|||
|
|
evidence = deepcopy(job.result_json or {})
|
|||
|
|
verdict = (
|
|||
|
|
evidence.get("verdict")
|
|||
|
|
if isinstance(evidence.get("reason"), str) and evidence["reason"].strip()
|
|||
|
|
else "indeterminate"
|
|||
|
|
)
|
|||
|
|
if verdict not in ("pass", "reject", "indeterminate"):
|
|||
|
|
verdict = "indeterminate"
|
|||
|
|
expected = (step.resolved_input_json or {}).get("input", {}).get("expected", {})
|
|||
|
|
if evidence.get("dedup_verified") is False:
|
|||
|
|
verdict = "reject"
|
|||
|
|
elif (
|
|||
|
|
verdict == "pass"
|
|||
|
|
and expected.get("dedup_frames")
|
|||
|
|
and evidence.get("dedup_verified") is not True
|
|||
|
|
):
|
|||
|
|
verdict = "indeterminate"
|
|||
|
|
evidence["boundary_hash"] = digest(step.resolved_input_json)
|
|||
|
|
session.add(
|
|||
|
|
QualityAssessment(
|
|||
|
|
variant_id=variant.id, job_id=job.id, verdict=verdict, evidence=evidence
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
used = await session.scalar(
|
|||
|
|
select(func.count())
|
|||
|
|
.select_from(WorkflowVariant)
|
|||
|
|
.where(WorkflowVariant.run_id == run.id, WorkflowVariant.ordinal > 0)
|
|||
|
|
)
|
|||
|
|
action = quality_action(
|
|||
|
|
verdict,
|
|||
|
|
variant.ordinal,
|
|||
|
|
used,
|
|||
|
|
run.result_manifest.get("production", {}),
|
|||
|
|
variant.candidate.get("locked", False),
|
|||
|
|
)
|
|||
|
|
variant.state = verdict
|
|||
|
|
sid = step.recipe_json["unit_id"]
|
|||
|
|
if action == "accept":
|
|||
|
|
anchor = await session.scalar(
|
|||
|
|
select(Asset).where(
|
|||
|
|
Asset.source_job_id == job.id,
|
|||
|
|
Asset.owner_id == run.owner_id,
|
|||
|
|
Asset.kind == "image",
|
|||
|
|
Asset.ready.is_(True),
|
|||
|
|
Asset.deleted_at.is_(None),
|
|||
|
|
Asset.library_scope == "private",
|
|||
|
|
Asset.source_output_index == 0,
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if not anchor or not await verified_output(anchor, settings):
|
|||
|
|
fail(409, "invalid_output", "质量检查缺少实际末帧")
|
|||
|
|
manifest = deepcopy(run.result_manifest)
|
|||
|
|
manifest["bindings"]["video:" + sid] = variant.candidate
|
|||
|
|
manifest["bindings"]["join_anchor:" + sid] = dict(
|
|||
|
|
asset_id=anchor.id,
|
|||
|
|
sha256=anchor.sha256,
|
|||
|
|
kind="image",
|
|||
|
|
source="generated",
|
|||
|
|
source_job_id=job.id,
|
|||
|
|
source_run_id=run.id,
|
|||
|
|
context_hash=digest(step.resolved_input_json),
|
|||
|
|
)
|
|||
|
|
await _add_ref(session, run, anchor)
|
|||
|
|
run.result_manifest = manifest
|
|||
|
|
step.result_json = variant.candidate
|
|||
|
|
step.state = "succeeded"
|
|||
|
|
step.version += 1
|
|||
|
|
return
|
|||
|
|
blocked_code = "quality_" + verdict
|
|||
|
|
if evidence.get("dedup_verified") is False:
|
|||
|
|
blocked_code = "dedup_mismatch"
|
|||
|
|
action = "blocked"
|
|||
|
|
if action == "repair" and endpoint_trim_conflict(run, step, step.recipe_json["parameters"]):
|
|||
|
|
blocked_code = "endpoint_trim_conflict"
|
|||
|
|
action = "blocked"
|
|||
|
|
if action == "blocked":
|
|||
|
|
step.state = "blocked"
|
|||
|
|
step.selected_job_id = None
|
|||
|
|
step.version += 1
|
|||
|
|
run.error_json = dict(
|
|||
|
|
code=blocked_code, step_key=step.step_key, ordinal=variant.ordinal
|
|||
|
|
)
|
|||
|
|
return
|
|||
|
|
resolved = await _resolve(session, run, step, settings)
|
|||
|
|
prompt = resolved["input"].get("prompt", "")
|
|||
|
|
repair_note = (
|
|||
|
|
"\n保持原定剧情、主体与镜头约束。修正前次画面问题:" + evidence["reason"].strip()[:800]
|
|||
|
|
)
|
|||
|
|
if len(prompt) + 40 > 8000:
|
|||
|
|
step.state = "blocked"
|
|||
|
|
step.selected_job_id = None
|
|||
|
|
step.version += 1
|
|||
|
|
run.error_json = {"code": "repair_prompt_too_long", "step_key": step.step_key}
|
|||
|
|
return
|
|||
|
|
resolved["input"]["prompt"] = prompt + repair_note[: 8000 - len(prompt)]
|
|||
|
|
resolved["parameters"]["seed"] = (
|
|||
|
|
resolved["parameters"]["seed"] + variant.ordinal + 1
|
|||
|
|
) % 2**32
|
|||
|
|
session.add(
|
|||
|
|
WorkflowVariant(
|
|||
|
|
run_id=run.id,
|
|||
|
|
step_key=step.step_key,
|
|||
|
|
ordinal=variant.ordinal + 1,
|
|||
|
|
resolved_input=resolved,
|
|||
|
|
state="generating",
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
await session.flush()
|
|||
|
|
step.selected_job_id = None
|
|||
|
|
step.resolved_input_json = None
|
|||
|
|
step.result_json = None
|
|||
|
|
step.state = "waiting"
|
|||
|
|
step.version += 1
|
|||
|
|
|
|||
|
|
|
|||
|
|
def validate_story_plan(author, updated):
|
|||
|
|
from app.domain.stories import parse_story_spec
|
|||
|
|
|
|||
|
|
if not isinstance(updated, dict) or updated.get("schema_version") != 4:
|
|||
|
|
raise ValueError("Invalid story plan")
|
|||
|
|
spec = parse_story_spec(updated).model_dump(mode="json")
|
|||
|
|
original = parse_story_spec(author).model_dump(mode="json")
|
|||
|
|
allowed = deepcopy(original)
|
|||
|
|
for shot, new in zip(allowed["shots"], spec["shots"], strict=True):
|
|||
|
|
before, after = shot["continuity"], new["continuity"]
|
|||
|
|
for key in ("state_in", "state_out"):
|
|||
|
|
for field, value in after[key].items():
|
|||
|
|
if field == "entities":
|
|||
|
|
for entity, state in value.items():
|
|||
|
|
before[key][field].setdefault(entity, state)
|
|||
|
|
elif not before[key][field]:
|
|||
|
|
before[key][field] = value
|
|||
|
|
if not before[key]["summary"].strip():
|
|||
|
|
raise ValueError("Missing prepared state summary")
|
|||
|
|
if not before["end_prompt"]:
|
|||
|
|
before["end_prompt"] = after["end_prompt"]
|
|||
|
|
if allowed != spec:
|
|||
|
|
raise ValueError("Story planner modified an authored field")
|
|||
|
|
return spec
|
|||
|
|
|
|||
|
|
|
|||
|
|
def planned_prompt(manifest, recipe, sha_by_asset):
|
|||
|
|
from app.domain.stories import compile_story
|
|||
|
|
|
|||
|
|
sid = recipe["unit_id"]
|
|||
|
|
spec = manifest["spec"]
|
|||
|
|
index = manifest["shot_ids"].index(sid)
|
|||
|
|
shot = spec["shots"][index]
|
|||
|
|
edge = shot["continuity"]
|
|||
|
|
if recipe["kind"] == "video.generate":
|
|||
|
|
prompt = recipe["input"]["prompt"]
|
|||
|
|
fields = ("state_in", "state_out")
|
|||
|
|
else:
|
|||
|
|
assets = {aid: {"sha256": sha} for aid, sha in sha_by_asset.items()}
|
|||
|
|
compiled = compile_story(spec, assets)["shots"][index]
|
|||
|
|
if compiled["errors"]:
|
|||
|
|
raise ValueError("Invalid compiled shot")
|
|||
|
|
prompt = compiled["frame_prompt"]
|
|||
|
|
if not recipe["key"].startswith("end_"):
|
|||
|
|
return prompt
|
|||
|
|
prompt += "\nEnd frame: " + edge["end_prompt"]
|
|||
|
|
fields = ("state_out",)
|
|||
|
|
for key in fields:
|
|||
|
|
state = {k: v for k, v in edge[key].items() if v}
|
|||
|
|
if state:
|
|||
|
|
prompt += "\n" + key + ": " + json.dumps(state, ensure_ascii=False, sort_keys=True)
|
|||
|
|
if len(prompt) > 8000:
|
|||
|
|
raise ValueError("Prepared prompt too long")
|
|||
|
|
return prompt
|