"""参考图片编号必须与实际模型输入及稳定实体/形态引用对应。""" import copy from types import SimpleNamespace from unittest.mock import AsyncMock import pytest def referenced_spec(asset_ids): scene, entity, appearance = asset_ids return { "schema_version": 3, "scenes": [{"id": "2" * 32, "name": "Palace", "reference_asset_ids": [scene]}], "entities": [ { "id": "3" * 32, "name": "Mira", "description": "Silver-haired guard", "reference_asset_ids": [entity, scene], "forms": [{"id": "4" * 32, "name": "Battle form", "reference_asset_ids": [scene]}], "appearances": [ {"id": "5" * 32, "name": "Red cloak", "reference_asset_ids": [appearance]} ], }, { "id": "7" * 32, "name": "Mira", "description": "Unselected impostor", "reference_asset_ids": ["unused"], }, ], "shots": [ { "id": "1" * 32, "scene_id": "2" * 32, "cast": [ { "id": "6" * 32, "entity_id": "3" * 32, "form_id": "4" * 32, "appearance_id": "5" * 32, } ], "visual_prompt": "Mira stands near the gate.", } ], } def test_compiled_reference_bindings_number_unique_images_scene_first_and_keep_all_roles(): from app.domain.stories import compile_story assets = {id: {"sha256": id * 64} for id in "abc"} shot = compile_story(referenced_spec(list("abc")), assets)["shots"][0] lines = [line for line in shot["frame_prompt"].splitlines() if line.startswith("Picture ")] assert len(lines) == 3 assert ( lines[0] == 'Picture 1: scene "Scene 1 / Palace"; entity "Character 1 / Mira"; form "Character 1 / Mira / Battle form".' ) assert lines[1] == 'Picture 2: entity "Character 1 / Mira".' assert lines[2] == 'Picture 3: appearance "Character 1 / Mira / Red cloak".' assert [ref["asset_id"] for ref in shot["references"]] == ["a", "b", "a", "a", "c"] assert "Unselected impostor" not in shot["frame_prompt"] assert shot["errors"] == [] def test_reference_bindings_resolve_stable_cast_ids_after_entity_and_shot_reordering(): from app.domain.stories import compile_story spec = referenced_spec(list("abc")) spec["shots"].append({"id": "8" * 32, "visual_prompt": "Another shot"}) spec["scenes"].insert( 0, {"id": "9" * 32, "name": "Unselected scene", "reference_asset_ids": ["unused"]} ) spec["entities"][0]["forms"].insert( 0, {"id": "a" * 32, "name": "Unselected form", "reference_asset_ids": ["unused"]} ) spec["entities"][0]["appearances"].insert( 0, {"id": "b" * 32, "name": "Unselected appearance", "reference_asset_ids": ["unused"]} ) assets = {id: {"sha256": id * 64} for id in "abc"} before = compile_story(spec, assets)["shots"][0] changed = copy.deepcopy(spec) # @选择/按钮保存的是cast.entity_id,不能在同名实体或展示序号变化后改绑图片。 changed["entities"].reverse() changed["scenes"].reverse() changed["entities"][1]["forms"].reverse() changed["entities"][1]["appearances"].reverse() changed["shots"].reverse() after = next(s for s in compile_story(changed, assets)["shots"] if s["shot_id"] == "1" * 32) assert after["frame_prompt"] == before["frame_prompt"] assert after["context_hash"] == before["context_hash"] assert 'Picture 3: appearance "Character 1 / Mira / Red cloak".' in after["frame_prompt"] next(form for form in changed["entities"][1]["forms"] if form["id"] == "4" * 32)["name"] = ( "Wolf form" ) renamed = next(s for s in compile_story(changed, assets)["shots"] if s["shot_id"] == "1" * 32) assert 'form "Character 1 / Mira / Wolf form"' in renamed["frame_prompt"] assert renamed["context_hash"] != before["context_hash"] def test_no_reference_story_keeps_original_prompt_and_visual_hash(): from app.domain.stories import compile_story, digest spec = {"schema_version": 3, "shots": [{"id": "1" * 32, "visual_prompt": "A tree"}]} shot = compile_story(spec, {})["shots"][0] assert shot["frame_prompt"] == "A tree" assert shot["context_hash"] == digest( { "prompt": "A tree", "settings": { "era": "", "style": "", "palette": "", "lighting": "", "negative_prompt": "", }, "references": [], "profile": "landscape_1080_v1", } ) def test_same_named_cast_members_have_unique_aliases_for_description_position_and_picture_binding(): from app.domain.stories import compile_story spec = { "schema_version": 3, "entities": [ { "id": "3" * 32, "name": "Mira", "description": "Silver-haired guard", "reference_asset_ids": ["a"], }, { "id": "7" * 32, "name": "Mira", "description": "Dark-haired scholar", "reference_asset_ids": ["b"], }, { "id": "9" * 32, "name": "Mira", "description": "Unselected impostor", "reference_asset_ids": ["unused"], }, ], "shots": [ { "id": "1" * 32, "cast": [ { "id": "4" * 32, "entity_id": "3" * 32, "position": "on the left", "action": "holds a lantern", }, { "id": "8" * 32, "entity_id": "7" * 32, "position": "on the right", "action": "waves", }, ], "visual_prompt": "Both subjects face the camera.", } ], } for index, asset_id in enumerate("ab"): variant_id = asset_id * 32 spec["entities"][index]["forms"] = [ { "id": variant_id, "name": "Wolf", "description": "White fur" if index == 0 else "Black fur", "reference_asset_ids": [asset_id], } ] spec["shots"][0]["cast"][index]["form_id"] = variant_id assets = {id: {"sha256": id * 64} for id in "ab"} before = compile_story(spec, assets)["shots"][0] prompt = before["frame_prompt"] assert 'entity "Character 1 / Mira": Silver-haired guard' in prompt assert 'entity "Character 2 / Mira": Dark-haired scholar' in prompt assert '"Character 1 / Mira" position: on the left' in prompt assert '"Character 2 / Mira" position: on the right' in prompt assert '"Character 1 / Mira" action: holds a lantern' in prompt assert 'form "Character 1 / Mira / Wolf": White fur' in prompt assert 'form "Character 2 / Mira / Wolf": Black fur' in prompt assert 'Picture 1: entity "Character 1 / Mira"; form "Character 1 / Mira / Wolf".' in prompt assert 'Picture 2: entity "Character 2 / Mira"; form "Character 2 / Mira / Wolf".' in prompt assert "Unselected impostor" not in prompt reordered = copy.deepcopy(spec) reordered["entities"].reverse() reordered["entities"][0]["name"] = "Uncast renamed person" after = compile_story(reordered, assets)["shots"][0] assert after["frame_prompt"] == prompt and after["context_hash"] == before["context_hash"] renamed = copy.deepcopy(spec) renamed["entities"][1]["name"] = "Nora" changed = compile_story(renamed, assets)["shots"][0] assert ( 'Picture 2: entity "Character 2 / Nora"; form "Character 2 / Nora / Wolf".' in changed["frame_prompt"] ) assert changed["context_hash"] != before["context_hash"] def test_repeated_cast_of_same_entity_reuses_alias_and_variant_parent_binding(): from app.domain.stories import compile_story spec = referenced_spec(list("abc")) spec["shots"][0]["cast"].append( { "id": "d" * 32, "entity_id": "3" * 32, "form_id": "4" * 32, "position": "in the reflection", } ) prompt = compile_story(spec, {id: {"sha256": id * 64} for id in "abc"})["shots"][0][ "frame_prompt" ] assert "Character 2" not in prompt assert '"Character 1 / Mira" position: in the reflection' in prompt assert 'form "Character 1 / Mira / Battle form"' in prompt @pytest.mark.asyncio @pytest.mark.parametrize("reference_mode", ["reference", "text"]) async def test_candidate_prompt_binding_matches_preview_and_actual_provider_image_order( system, png_bytes, monkeypatch, reference_mode ): from app.adapters.provider.client import Provider from app.models import Asset, ShotCandidate c = system.client ids = [ ( await c.post("/api/assets", files={"file": (f"image-{i}.png", png_bytes, "image/png")}) ).json()["id"] for i in range(3) ] # 未出现实体的参考不属于此镜头,但仍须是可访问的故事基准素材。 spec = referenced_spec(ids) spec["entities"][1]["reference_asset_ids"] = [ids[2]] d = (await c.post("/api/stories", json={"name": "Picture bindings", "spec": spec})).json() path = f"/api/stories/{d['id']}" preview = (await c.get(path + "/preview")).json()["shots"][0] assert ( 'Picture 1: scene "Scene 1 / Palace"; entity "Character 1 / Mira"; form "Character 1 / Mira / Battle form".' in preview["frame_prompt"] ) assert 'Picture 3: appearance "Character 1 / Mira / Red cloak".' in preview["frame_prompt"] caps = { "reference_generation": { "available": True, "profile": system.settings.reference_generation_profile, "max_reference_images": 3, } } system.settings.reference_generation_enabled = True monkeypatch.setattr( system.provider, "upstream_capabilities", AsyncMock(return_value=caps), raising=False ) accepted = await c.post( path + "/candidates", headers={"Idempotency-Key": "bound"}, json={ "expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "reference_mode": reference_mode, }, ) assert accepted.status_code == 202, accepted.text candidate = accepted.json()["candidates"][0] expected_ids = ids if reference_mode == "reference" else [] assert candidate["context_hash"] == preview["context_hash"] assert candidate["input_summary"]["actual_reference_asset_ids"] == expected_ids async with system.app.state.db.session() as s: plan = (await s.get(ShotCandidate, candidate["id"])).plan_json assets = { id: system.settings.asset_root / (await s.get(Asset, id)).storage_key for id in ids } if reference_mode == "text": assert "Picture " not in plan["input"]["prompt"] assert "Silver-haired guard" in plan["input"]["prompt"] assert plan["input"].get("reference_asset_ids", []) == [] return assert plan["input"]["prompt"] == preview["frame_prompt"] assert plan["input"]["reference_asset_ids"] == ids real = Provider(system.settings) monkeypatch.setattr(real, "upstream_capabilities", AsyncMock(return_value=caps)) try: work = system.settings.job_work_root / "mapping-check" work.mkdir(parents=True) payload = await real.prepare_gpu_payload( plan["task_type"], plan["input"], plan["parameters"], assets, work, ) assert payload["input"]["prompt"] == preview["frame_prompt"] assert payload["input"]["image_paths"] == [str(assets[id]) for id in ids] finally: await real.aclose()