cmvr-visual/backend/tests/test_creation_editing.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

634 lines
22 KiB
Python

import pytest
from app.core.config import Settings
from app.adapters.provider.contracts import capabilities, validate_arguments
from app.domain.tasks import GPU_TYPES
from app.services.jobs import input_ids
def test_video_edit_registered_and_capabilities(tmp_path):
settings = Settings(
mode="test", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path
)
assert {"video.people.analyze", "video.replace"} <= GPU_TYPES
info = {row["task_type"]: row for row in capabilities(settings)}
assert info["video.replace"]["available"] is False
assert info["video.replace"]["defaults"]["preserve_audio"] is True
def test_reference_square_and_no_duplicates(tmp_path):
from app.domain.errors import MediaError
settings = Settings(
mode="test",
database_url="sqlite+aiosqlite:///:memory:",
workspace_root=tmp_path,
reference_generation_enabled=True,
)
validate_arguments(
"image.reference.generate",
{"prompt": "test", "reference_asset_ids": ["a"]},
{"width": 1024, "height": 1024},
settings,
)
with pytest.raises(MediaError):
validate_arguments(
"image.reference.generate",
{"prompt": "test", "reference_asset_ids": ["a", "a"]},
{},
settings,
)
def test_nested_references_protect_every_selected_actor():
assert input_ids(
{
"video_asset_id": "video",
"replacements": [
{"person_id": "p1", "reference_asset_id": "a"},
{"person_id": "p2", "reference_asset_id": "b"},
],
},
{},
) == ["video", "a", "b"]
@pytest.mark.asyncio
async def test_reference_four_candidates(system, png_bytes):
system.settings.reference_generation_enabled = True
response = await system.client.post(
"/api/assets", files={"file": ("ref.png", png_bytes, "image/png")}
)
assert response.status_code == 201, response.text
response = await system.client.post(
"/api/jobs",
json={
"task_type": "image.reference.generate",
"input": {"prompt": "edit", "reference_asset_ids": [response.json()["id"]]},
"parameters": {"width": 1024, "height": 1024},
"count": 4,
},
)
assert response.status_code == 202, response.text
assert [j["parameters"]["seed"] for j in response.json()["jobs"]] == [42, 43, 44, 45]
@pytest.fixture
async def video_setup(system, png_bytes, tmp_path):
from pathlib import Path
from app.adapters.media import run_process
from app.models import Job, Asset
tools = (
Path(__file__).resolve().parents[2]
/ ".local/tools/ffmpeg/ffmpeg-9.0.2-essentials_build/bin"
)
system.settings.ffmpeg_bin = str(tools / "ffmpeg.exe")
system.settings.ffprobe_bin = str(tools / "ffprobe.exe")
system.settings.video_edit_enabled = True
path = tmp_path / "video.mp4"
await run_process(
[
system.settings.ffmpeg_bin,
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=c=blue:s=64x48:r=24:d=1",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
str(path),
]
)
uploaded = await system.client.post(
"/api/assets", files={"file": ("source.mp4", path.read_bytes(), "video/mp4")}
)
assert uploaded.status_code == 201, uploaded.text
image = await system.client.post(
"/api/assets", files={"file": ("ref.png", png_bytes, "image/png")}
)
source_id, image_id = uploaded.json()["id"], image.json()["id"]
response = await system.client.post(
"/api/jobs",
json={"task_type": "video.people.analyze", "input": {"video_asset_id": source_id}},
)
assert response.status_code == 202, response.text
job_id = response.json()["jobs"][0]["id"]
runtime = system.app.state
async with runtime.db.session() as session:
source = await session.get(Asset, source_id)
job = await session.get(Job, job_id)
job.state, job.upstream_id = "succeeded", "a" * 32
job.result_json = {
"profile": "wan-animate-replace-v1",
"analysis_token": "b" * 64,
"source_sha256": source.sha256,
"video": {"width": 64, "height": 48, "frames": 24, "fps": 24, "duration_seconds": 1.0},
"poster_output_index": 0,
"people": [
{
"id": f"person_{i:04}",
"label": f"Person {i}",
"thumbnail_output_index": i,
"first_frame": 0,
"last_frame": 23,
"confidence": 0.9,
"samples": [
{"frame": frame, "bbox": [0.1, 0.1, 0.4, 0.9]} for frame in (0, 12, 23)
],
}
for i in (1, 2)
],
"warnings": [],
}
await session.commit()
return {
"task_type": "video.replace",
"input": {
"video_asset_id": source_id,
"analysis_job_id": job_id,
"prompt": "replace both",
"replacements": [
{"person_id": f"person_{i:04}", "reference_asset_id": image_id, "prompt": str(i)}
for i in (1, 2)
],
},
}
@pytest.mark.asyncio
async def test_replace_freezes_two_people_and_all_asset_refs(system, video_setup):
from sqlalchemy import select
from app.models import Job, JobAsset
response = await system.client.post("/api/jobs", json=video_setup)
assert response.status_code == 202, response.text
dto = response.json()["jobs"][0]
assert "_video_edit_binding" not in dto["parameters"]
async with system.app.state.db.session() as session:
job = await session.get(Job, dto["id"])
assert job.parameters["_video_edit_binding"]["analysis_id"] == "a" * 32
assert len(job.input_json["replacements"]) == 2
assert set(
(
await session.scalars(select(JobAsset.asset_id).where(JobAsset.job_id == job.id))
).all()
) == {
video_setup["input"]["video_asset_id"],
video_setup["input"]["replacements"][0]["reference_asset_id"],
}
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mutation",
[
"source",
"sha",
"deleted",
"failed",
"owner",
"unknown",
"duplicate",
"params",
"token",
"truncated",
],
)
async def test_replace_rejects_untrusted_analysis(system, other_client, video_setup, mutation):
from app.models import Job, utcnow
async with system.app.state.db.session() as session:
job = await session.get(Job, video_setup["input"]["analysis_job_id"])
if mutation == "source":
job.input_json = {"video_asset_id": "different"}
elif mutation == "sha":
job.result_json = job.result_json | {"source_sha256": "0" * 64}
elif mutation == "deleted":
job.deleted_at = utcnow()
elif mutation == "failed":
job.state = "failed"
elif mutation == "owner":
from sqlalchemy import select
from app.models import User
job.owner_id = await session.scalar(select(User.id).where(User.username == "alice"))
elif mutation == "unknown":
video_setup["input"]["replacements"][0]["person_id"] = "person_9999"
elif mutation == "duplicate":
video_setup["input"]["replacements"][1]["person_id"] = "person_0001"
elif mutation == "params":
video_setup["parameters"] = {"max_pixels": 921600}
elif mutation == "truncated":
video = job.result_json["video"] | {"frames": 12, "duration_seconds": 0.5}
people = [
p
| {
"last_frame": 11,
"samples": [{"frame": f, "bbox": [0.1, 0.1, 0.4, 0.9]} for f in (0, 5, 11)],
}
for p in job.result_json["people"]
]
job.result_json = job.result_json | {"video": video, "people": people}
elif mutation == "token":
video_setup["input"]["analysis_token"] = "forged"
await session.commit()
response = await system.client.post("/api/jobs", json=video_setup)
assert response.status_code in {400, 404, 422}, response.text
def test_analysis_rejects_missing_preview_and_drops_paths(tmp_path):
from app.domain.video_editing import safe_analysis
from app.domain.errors import MediaError
settings = Settings(
mode="test", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path
)
data = {
"profile": "wan-animate-replace-v1",
"analysis_token": "a" * 64,
"source_sha256": "b" * 64,
"video": {"width": 64, "height": 48, "fps": 24, "frames": 24, "duration_seconds": 1.0},
"poster_output_index": 2,
"people": [],
"warnings": [],
"manifest_path": "/private/secret",
}
assert "manifest_path" not in safe_analysis(data, settings, output_count=3)
with pytest.raises(MediaError):
safe_analysis(data, settings, output_count=2)
@pytest.mark.asyncio
async def test_real_provider_sends_both_actor_mappings(system, video_setup):
import httpx
from sqlalchemy import select
from app.models import Asset, Job
from app.adapters.provider.client import Provider
from app.domain.errors import MediaError
response = await system.client.post("/api/jobs", json=video_setup)
assert response.status_code == 202, response.text
async with system.app.state.db.session() as session:
job = await session.get(Job, response.json()["jobs"][0]["id"])
assets = (
await session.scalars(
select(Asset).where(
Asset.id.in_(
[
job.input_json["video_asset_id"],
job.input_json["replacements"][0]["reference_asset_id"],
]
)
)
)
).all()
paths = {a.id: system.settings.asset_root / a.storage_key for a in assets}
parameters = dict(job.parameters)
binding = parameters.pop("_video_edit_binding")
system.settings.inference_api_key_file = None
provider = Provider(system.settings)
await provider.client.aclose()
provider.client = httpx.AsyncClient(
transport=httpx.MockTransport(
lambda request: httpx.Response(
200,
json={
"video_edit": {
"available": True,
"profile": "wan-animate-replace-v1",
"max_seconds": 120,
"max_people": 12,
"max_pixels": 921600,
"fps": 24,
}
},
)
)
)
work = system.settings.job_work_root / "provider"
work.mkdir(parents=True)
try:
payload = await provider.prepare_gpu_payload(
"video.replace", job.input_json, parameters, paths, work, analysis_binding=binding
)
assert [r["person_id"] for r in payload["input"]["replacements"]] == [
"person_0001",
"person_0002",
]
assert [r["prompt"] for r in payload["input"]["replacements"]] == ["1", "2"]
assert payload["input"]["analysis_id"] == "a" * 32
assert "analysis_job_id" not in payload["input"]
with pytest.raises(MediaError):
await provider.prepare_gpu_payload(
"video.replace",
job.input_json,
parameters,
paths,
work,
analysis_binding=binding | {"source_sha256": "0" * 64},
)
finally:
await provider.aclose()
@pytest.mark.asyncio
async def test_decoded_output_type_frames_fps_audio_are_checked(system, video_setup):
from copy import deepcopy
from app.models import Job, Asset
from app.services.video_editing import validate_video_output, validate_result_metadata
response = await system.client.post("/api/jobs", json=video_setup)
async with system.app.state.db.session() as session:
job = await session.get(Job, response.json()["jobs"][0]["id"])
asset = await session.get(Asset, job.input_json["video_asset_id"])
source = system.settings.asset_root / asset.storage_key
job.upstream_result = {
"outputs": [{"path": "final.mp4"}],
"metadata": {
"profile": "wan-animate-replace-v1",
"person_ids": ["person_0001", "person_0002"],
"source_frames": 24,
"output_frames": 24,
"fps": 24,
"width": 64,
"height": 48,
"final_output_indices": [0],
"warnings": [],
},
}
await validate_video_output(job, source, system.settings)
original = deepcopy(job.upstream_result)
for key, bad in (
("person_ids", ["person_0002"]),
("output_frames", 12),
("fps", 12),
("final_output_indices", [5]),
):
job.upstream_result = deepcopy(original)
job.upstream_result["metadata"][key] = bad
with pytest.raises(ValueError):
validate_result_metadata(job, job.upstream_result["outputs"], system.settings)
job.upstream_result = original
job.parameters = job.parameters | {
"_video_edit_binding": job.parameters["_video_edit_binding"] | {"source_has_audio": True}
}
with pytest.raises(ValueError, match="audio"):
await validate_video_output(job, source, system.settings)
@pytest.mark.asyncio
async def test_analysis_requires_visible_start_middle_end_samples(system, video_setup):
from app.models import Job
from app.domain.errors import MediaError
from app.domain.video_editing import safe_analysis
async with system.app.state.db.session() as session:
job = await session.get(Job, video_setup["input"]["analysis_job_id"])
job.result_json["people"][0]["samples"] = job.result_json["people"][0]["samples"][:1]
with pytest.raises(MediaError):
safe_analysis(job.result_json, system.settings)
@pytest.mark.asyncio
async def test_nested_replacement_inputs_block_physical_deletion(system, video_setup):
response = await system.client.post("/api/jobs", json=video_setup)
assert response.status_code == 202, response.text
for asset_id in [
video_setup["input"]["video_asset_id"],
video_setup["input"]["replacements"][0]["reference_asset_id"],
]:
result = await system.client.delete(f"/api/assets/{asset_id}")
assert result.status_code == 409, result.text
@pytest.mark.asyncio
async def test_preserves_original_short_audio_duration(system, video_setup, tmp_path):
from app.models import Job
from app.adapters.media import run_process
from app.services.video_editing import validate_video_output
response = await system.client.post("/api/jobs", json=video_setup)
async with system.app.state.db.session() as session:
job = await session.get(Job, response.json()["jobs"][0]["id"])
output = system.settings.job_work_root / "short-audio.mp4"
await run_process(
[
system.settings.ffmpeg_bin,
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=c=blue:s=64x48:r=24:d=1",
"-f",
"lavfi",
"-i",
"sine=frequency=440:duration=0.5",
"-c:v",
"libx264",
"-c:a",
"aac",
"-pix_fmt",
"yuv420p",
str(output),
]
)
job.upstream_result = {
"outputs": [{"path": "final.mp4"}],
"metadata": {
"profile": "wan-animate-replace-v1",
"person_ids": ["person_0001", "person_0002"],
"source_frames": 24,
"output_frames": 24,
"fps": 24,
"width": 64,
"height": 48,
"final_output_indices": [0],
"warnings": [],
},
}
job.parameters = job.parameters | {
"_video_edit_binding": job.parameters["_video_edit_binding"]
| {"source_has_audio": True, "source_audio_duration": 0.5}
}
await validate_video_output(job, output, system.settings)
@pytest.mark.asyncio
async def test_video_timeline_ignores_longer_audio_tail(system, video_setup, tmp_path):
from hashlib import sha256
from app.adapters.media import run_process
from app.models import Asset, Job
from app.adapters.provider.client import Provider
import httpx
system.settings.video_edit_max_seconds = 1
rendered = tmp_path / "long-audio.mp4"
await run_process(
[
system.settings.ffmpeg_bin,
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=c=blue:s=64x48:r=24:d=1",
"-f",
"lavfi",
"-i",
"sine=frequency=440:duration=2",
"-c:v",
"libx264",
"-c:a",
"aac",
"-pix_fmt",
"yuv420p",
str(rendered),
]
)
async with system.app.state.db.session() as session:
asset = await session.get(Asset, video_setup["input"]["video_asset_id"])
source = system.settings.asset_root / asset.storage_key
source.write_bytes(rendered.read_bytes())
asset.sha256 = sha256(source.read_bytes()).hexdigest()
asset.duration_seconds = 2.0
analysis = await session.get(Job, video_setup["input"]["analysis_job_id"])
analysis.result_json = analysis.result_json | {"source_sha256": asset.sha256}
await session.commit()
response = await system.client.post("/api/jobs", json=video_setup)
assert response.status_code == 202, response.text
async with system.app.state.db.session() as session:
job = await session.get(Job, response.json()["jobs"][0]["id"])
binding = job.parameters["_video_edit_binding"]
assert binding["video"]["duration_seconds"] == 1.0
assert binding["source_audio_duration"] == pytest.approx(2, abs=0.05)
system.settings.inference_api_key_file = None
provider = Provider(system.settings)
await provider.client.aclose()
provider.client = httpx.AsyncClient(
transport=httpx.MockTransport(
lambda request: httpx.Response(
200,
json={
"video_edit": {
"available": True,
"profile": "wan-animate-replace-v1",
"max_seconds": 1,
"max_people": 12,
"max_pixels": 399360,
"fps": 24,
}
},
)
)
)
work = system.settings.job_work_root / "long-audio"
work.mkdir(parents=True)
try:
payload = await provider.prepare_gpu_payload(
"video.people.analyze", {"video_asset_id": asset.id}, {}, {asset.id: source}, work
)
assert payload["input"]["video_path"] == str(source)
finally:
await provider.aclose()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"change",
[{"prompt": ""}, {"prompt": " \n"}, {"mask_expand_pixels": 65}, {"mask_feather_pixels": 128}],
)
async def test_business_and_provider_share_raw_prompt_mask_contract(tmp_path, change):
from app.adapters.provider.client import Provider
from app.domain.errors import MediaError
settings = Settings(
mode="test",
database_url="sqlite+aiosqlite:///:memory:",
workspace_root=tmp_path,
video_edit_enabled=True,
)
inputs = {
"video_asset_id": "source",
"analysis_job_id": "analysis",
"prompt": "replace",
"replacements": [{"person_id": "person_0001", "reference_asset_id": "image"}],
}
parameters = {}
if "prompt" in change:
inputs.update(change)
else:
parameters.update(change)
with pytest.raises(MediaError, match="输入|参数|提示"):
validate_arguments("video.replace", inputs, parameters, settings)
provider = Provider(settings)
try:
with pytest.raises(MediaError):
await provider.prepare_gpu_payload("video.replace", inputs, parameters, {}, tmp_path)
finally:
await provider.aclose()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"local,remote,expected",
[(399360, 921600, 399360), (921600, 399360, 399360), (921600, 921600, 921600)],
)
async def test_effective_pixel_budget_is_shared_by_both_tasks(system, local, remote, expected):
from app.services.system import task_capabilities
system.settings.video_edit_enabled = True
system.settings.video_edit_max_pixels = local
async def capabilities():
return {
"video_edit": {
"available": True,
"profile": "wan-animate-replace-v1",
"max_seconds": 120,
"max_people": 12,
"max_pixels": remote,
"fps": 24,
}
}
system.provider.upstream_capabilities = capabilities
rows = {row["task_type"]: row for row in await task_capabilities(system.app.state)}
for task in ("video.people.analyze", "video.replace"):
assert rows[task]["available"] is True
assert rows[task]["constraints"]["max_pixels"] == expected
@pytest.mark.parametrize("pixels", [399360, 921600])
def test_video_pixel_budget_loads_from_environment(monkeypatch, tmp_path, pixels):
monkeypatch.setenv("CMVR_MODE", "test")
monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
monkeypatch.setenv("VIDEO_EDIT_MAX_PIXELS", str(pixels))
assert Settings.from_env().video_edit_max_pixels == pixels
def test_mask_upper_bound_matches_raw_protocol(tmp_path):
from app.domain.errors import MediaError
settings = Settings(
mode="test",
database_url="sqlite+aiosqlite:///:memory:",
workspace_root=tmp_path,
video_edit_enabled=True,
)
inputs = {
"video_asset_id": "source",
"analysis_job_id": "analysis",
"prompt": "replace",
"replacements": [{"person_id": "person_0001", "reference_asset_id": "image"}],
}
validate_arguments(
"video.replace", inputs, {"mask_expand_pixels": 64, "mask_feather_pixels": 64}, settings
)
with pytest.raises(MediaError):
validate_arguments("video.replace", inputs, {"max_pixels": 921600}, settings)