1773 行
84 KiB
Python
1773 行
84 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import tempfile
|
|
import unittest
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
from backend.dto.common import ApiError
|
|
from backend.dto.job_dto import GenerationTask
|
|
from backend.dto.workflow_dto import WorkflowNode
|
|
from backend.services.advanced_material_service import AdvancedMaterialService
|
|
from backend.services.advanced_style_set_service import (
|
|
STYLE_REVIEW_DIMENSIONS,
|
|
_aggregate_style_review_feedback,
|
|
_detailed_style_negative_prompt,
|
|
_detailed_style_prompt,
|
|
_force_style_structures,
|
|
_is_reference_image_unsupported_error,
|
|
_consensus_source_analysis,
|
|
_normalize_artist_signature,
|
|
_normalize_style_deltas,
|
|
_normalize_style_dimension_scores,
|
|
_normalize_rendering_layer_scores,
|
|
_normalized_feature_evidence,
|
|
_scale_specific_style_prompt,
|
|
_scale_transfer_instruction,
|
|
_style_attempt_comparison,
|
|
_sanitize_validation_content,
|
|
_validation_cases,
|
|
_weighted_style_fidelity_score,
|
|
)
|
|
from backend.services.material_normalization_service import MaterialNormalizationService
|
|
from backend.services.prompt_governance_service import GenerationRouteService, PromptModerationService
|
|
from backend.services.queue_service import QueueService
|
|
from core.audit_service import AuditService
|
|
from core.config_service import ImageStudioConfig, StorageConfig
|
|
from core.identity import RequestContext
|
|
from core.model_route_chain import encode_model_route_chain
|
|
from core.storage import VfsStorage
|
|
from database.db_helper import Database, DatabaseSettings, SqliteSettings
|
|
from database.repositories.advanced_material_repository import AdvancedMaterialRepository
|
|
from database.repositories.job_repository import JobRepository
|
|
from database.repositories.material_repository import MaterialRepository
|
|
from engines.image_provider import (
|
|
GeneratedImagePayload,
|
|
ImageGenerationRequest,
|
|
ImageGenerationResult,
|
|
ImageProviderError,
|
|
)
|
|
from engines.single_flow import ONE_PIXEL_PNG, SingleFlowEngine
|
|
from engines.vision_provider import VisionProviderError, VisionRecognitionRequest, VisionRecognitionResult
|
|
|
|
|
|
PNG_DATA_URL = f"data:image/png;base64,{base64.b64encode(ONE_PIXEL_PNG).decode('ascii')}"
|
|
|
|
|
|
class _StaticConfigService:
|
|
def __init__(self, root: Path):
|
|
self.config = ImageStudioConfig(
|
|
storage=StorageConfig(
|
|
images_path=str(root / "images"),
|
|
thumbnails_path=str(root / "thumbnails"),
|
|
materials_path=str(root / "materials"),
|
|
advanced_materials_path=str(root / "advanced_materials"),
|
|
styles_path=str(root / "styles"),
|
|
archives_path=str(root / "archives"),
|
|
temp_path=str(root / "temp"),
|
|
)
|
|
)
|
|
|
|
def load(self) -> ImageStudioConfig:
|
|
return self.config
|
|
|
|
|
|
class _StyleVisionProvider:
|
|
provider_id = "style-vision"
|
|
|
|
def __init__(self) -> None:
|
|
self.requests: list[VisionRecognitionRequest] = []
|
|
self.fail_reviews = False
|
|
|
|
def recognize_material(self, request: VisionRecognitionRequest) -> VisionRecognitionResult:
|
|
self.requests.append(request)
|
|
if request.metadata.get("style_validation_review"):
|
|
if self.fail_reviews:
|
|
raise VisionProviderError(
|
|
"controlled automatic review failure",
|
|
provider_id=self.provider_id,
|
|
error_type="invalid_response",
|
|
)
|
|
return VisionRecognitionResult(
|
|
provider_id=self.provider_id,
|
|
model="style-vlm",
|
|
prompt="preserve fine ink linework, rounded stylized face proportions and two-band shadows",
|
|
negative_prompt="semi-realistic facial anatomy, thick generic outlines",
|
|
tags=["style-fidelity-review"],
|
|
confidence=0.88,
|
|
description="The transferred image preserves most structural and rendering traits.",
|
|
structured_data={
|
|
"prompt": "preserve fine ink linework, rounded stylized face proportions and two-band shadows",
|
|
"negative_prompt": "semi-realistic facial anatomy, thick generic outlines",
|
|
"fidelity_score": 0.88,
|
|
"dimension_scores": {"face_proportions": 0.84, "linework": 0.92, "shading": 0.89},
|
|
"matches": ["fine ink linework", "two-band shadows"],
|
|
"mismatches": ["face is slightly too realistic"],
|
|
"correction_prompt": "rounder stylized face, smaller simplified nose and mouth",
|
|
"negative_correction_prompt": "semi-realistic facial anatomy",
|
|
},
|
|
)
|
|
is_consensus = bool(request.image_uris) or bool(request.metadata.get("consensus_id"))
|
|
if not is_consensus:
|
|
sample_id = str(request.metadata.get("source_id") or len(self.requests))
|
|
prompt = f"sample style traits from {sample_id}"
|
|
return VisionRecognitionResult(
|
|
provider_id=self.provider_id,
|
|
model="style-vlm",
|
|
prompt=prompt,
|
|
negative_prompt="photorealism, watermark",
|
|
tags=["style", "ink", "cel-shading"],
|
|
confidence=0.94,
|
|
description="Observable line and coloring traits.",
|
|
structured_data=_style_structures(prompt),
|
|
)
|
|
|
|
payload = json.loads(str(request.prompt or "{}"))
|
|
reports = payload.get("source_reports") or [
|
|
{"source_id": source_id}
|
|
for source_id in payload.get("source_ids", [])
|
|
]
|
|
source_ids = [str(item["source_id"]) for item in reports]
|
|
instruction = str(request.metadata.get("recognition_instruction") or "")
|
|
adjustment = "cooler shadows" if "cooler shadows" in instruction else ""
|
|
prompt = "shared fine ink linework, flat cel colors, two-band shadows"
|
|
negative_prompt = "photorealism, source identity, watermark"
|
|
if adjustment:
|
|
prompt = f"{prompt}, {adjustment}"
|
|
if "颜色对比太过强烈" in instruction:
|
|
prompt = "intense color contrast, extreme color dynamics, luminous highly saturated palette"
|
|
negative_prompt = "low contrast, washed out, source identity, watermark"
|
|
structured = _style_structures(prompt)
|
|
structured.update(
|
|
{
|
|
"consensus_style": {"linework": "fine ink", "shading": "two-band cel"},
|
|
"variable_style_features": ["accent saturation"],
|
|
"source_content_features": ["sample identities and clothing"],
|
|
"content_leakage_exclusions": ["source identity", "source clothing", "source scene"],
|
|
"outlier_source_ids": [],
|
|
"representative_source_ids": source_ids[:3],
|
|
"consensus_confidence": 0.93,
|
|
"feature_evidence": [
|
|
{
|
|
"trait": "fine ink linework",
|
|
"supporting_source_ids": source_ids,
|
|
"support_ratio": 1.0,
|
|
"confidence": 0.95,
|
|
}
|
|
],
|
|
"validation_cases": [
|
|
{
|
|
"case_key": "portrait",
|
|
"content_prompt": "an elderly male instrument maker in a cool workshop, head portrait",
|
|
"aspect_ratio": "1:1",
|
|
},
|
|
{
|
|
"case_key": "fullbody",
|
|
"content_prompt": "a non-human courier robot in a rainy harbor, dynamic full body",
|
|
"aspect_ratio": "2:3",
|
|
},
|
|
{
|
|
"case_key": "novel_scene",
|
|
"content_prompt": "a child botanist on an alien meadow, wide environmental scene",
|
|
"aspect_ratio": "16:9",
|
|
},
|
|
],
|
|
}
|
|
)
|
|
return VisionRecognitionResult(
|
|
provider_id=self.provider_id,
|
|
model="style-vlm",
|
|
prompt=prompt,
|
|
negative_prompt=negative_prompt,
|
|
tags=["style", "ink", "cel-shading"],
|
|
confidence=0.93,
|
|
description="Cross-image transferable style consensus.",
|
|
structured_data=structured,
|
|
)
|
|
|
|
|
|
def _style_structures(prompt: str) -> dict[str, Any]:
|
|
capsules = {
|
|
tier: {
|
|
"prompt_parts": [f"{prompt} / {tier}"],
|
|
"negative_parts": ["photorealism", "watermark"],
|
|
}
|
|
for tier in ("compact", "standard", "detailed")
|
|
}
|
|
return {
|
|
"raw_analysis": {
|
|
"attributes": {
|
|
"linework": {
|
|
"value": "fine ink linework",
|
|
"confidence": 0.95,
|
|
"source_state": "observed",
|
|
}
|
|
}
|
|
},
|
|
"normalized_asset_profile": {
|
|
"category": "style",
|
|
"role": "style",
|
|
"body_slots": ["global_style"],
|
|
"must_preserve": ["fine ink linework", "two-band shadows"],
|
|
},
|
|
"generation_capsules": capsules,
|
|
}
|
|
|
|
|
|
class _StyleImageProvider:
|
|
provider_id = "style-image"
|
|
|
|
def __init__(self) -> None:
|
|
self.requests: list[ImageGenerationRequest] = []
|
|
self.fail_prompt_once: str | None = None
|
|
self._failed = False
|
|
|
|
def generate_image(self, request: ImageGenerationRequest) -> ImageGenerationResult:
|
|
self.requests.append(request)
|
|
if self.fail_prompt_once and self.fail_prompt_once in request.prompt and not self._failed:
|
|
self._failed = True
|
|
raise ImageProviderError(
|
|
"controlled style validation failure",
|
|
provider_id=self.provider_id,
|
|
error_type="timeout",
|
|
)
|
|
return ImageGenerationResult(
|
|
provider_id=self.provider_id,
|
|
model=request.model or "style-image-model",
|
|
images=[
|
|
GeneratedImagePayload(
|
|
b64_json=base64.b64encode(ONE_PIXEL_PNG).decode("ascii"),
|
|
revised_prompt=request.prompt,
|
|
)
|
|
],
|
|
usage={"images": 1},
|
|
raw_metadata={"provider_base_url": "https://style.invalid"},
|
|
)
|
|
|
|
|
|
class _Runtime:
|
|
def __init__(self, vision: _StyleVisionProvider, image: _StyleImageProvider) -> None:
|
|
self.vision = vision
|
|
self.image = image
|
|
self.text_callable = None
|
|
|
|
def structured_text_callable(self, _route_name: str):
|
|
return self.text_callable
|
|
|
|
def vision_provider_for_route(self, _route: dict[str, Any]) -> _StyleVisionProvider:
|
|
return self.vision
|
|
|
|
def image_provider_for_route(self, _route: dict[str, Any]) -> _StyleImageProvider:
|
|
return self.image
|
|
|
|
|
|
class _CapturingSingleFlowEngine(SingleFlowEngine):
|
|
def __init__(self, **kwargs: Any) -> None:
|
|
super().__init__(**kwargs)
|
|
self.requests: list[dict[str, Any]] = []
|
|
|
|
def generate(
|
|
self,
|
|
node: WorkflowNode,
|
|
task: GenerationTask,
|
|
request: dict[str, Any],
|
|
):
|
|
self.requests.append(dict(request))
|
|
return super().generate(node, task, request)
|
|
|
|
|
|
class _RouteService:
|
|
def resolve_route(self, route_name: str, *, modality: str | None = None) -> dict[str, Any]:
|
|
if modality != "image_generation":
|
|
raise AssertionError(f"unexpected modality: {modality}")
|
|
return {
|
|
"route_name": route_name,
|
|
"status": "resolved",
|
|
"provider_id": "style-image",
|
|
"model_id": "style-image-model",
|
|
"provider": {
|
|
"provider_id": "style-image",
|
|
"base_url": "https://style.invalid",
|
|
},
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class _Fixture:
|
|
database: Database
|
|
service: AdvancedMaterialService
|
|
queue: QueueService
|
|
materials: MaterialRepository
|
|
advanced: AdvancedMaterialRepository
|
|
storage_root: Path
|
|
vision: _StyleVisionProvider
|
|
image: _StyleImageProvider
|
|
engine: _CapturingSingleFlowEngine
|
|
style_category_id: str
|
|
other_category_id: str
|
|
|
|
|
|
def _fixture(root: Path) -> _Fixture:
|
|
database = Database(
|
|
DatabaseSettings(
|
|
backend="sqlite",
|
|
sqlite=SqliteSettings(path=str(root / "advanced-style-set.sqlite3")),
|
|
)
|
|
)
|
|
database.initialize()
|
|
audit = AuditService(database)
|
|
queue = QueueService(JobRepository(database), audit)
|
|
materials = MaterialRepository(database)
|
|
style = materials.create_category(
|
|
{
|
|
"category_id": "cat_test_style",
|
|
"name": "style",
|
|
"sort_order": 1,
|
|
"metadata": {"frontend_group": "style"},
|
|
}
|
|
)
|
|
other = materials.create_category(
|
|
{
|
|
"category_id": "cat_test_garment",
|
|
"name": "garment",
|
|
"sort_order": 2,
|
|
"metadata": {"frontend_group": "clothing"},
|
|
}
|
|
)
|
|
advanced = AdvancedMaterialRepository(database)
|
|
storage_root = root / "vfs"
|
|
storage = VfsStorage(_StaticConfigService(storage_root)) # type: ignore[arg-type]
|
|
vision = _StyleVisionProvider()
|
|
image = _StyleImageProvider()
|
|
runtime = _Runtime(vision, image)
|
|
engine = _CapturingSingleFlowEngine(
|
|
storage=storage,
|
|
image_provider_factory=runtime.image_provider_for_route,
|
|
allow_mock_fallback=False,
|
|
)
|
|
config = {
|
|
"model_assignments": {
|
|
"advanced_material_recognition": "style-vision-route",
|
|
"advanced_material_validation_generation": "style-image-route",
|
|
}
|
|
}
|
|
service = AdvancedMaterialService(
|
|
advanced,
|
|
materials,
|
|
queue,
|
|
audit,
|
|
_RouteService(), # type: ignore[arg-type]
|
|
runtime, # type: ignore[arg-type]
|
|
config=config,
|
|
storage=storage,
|
|
single_flow_engine=engine,
|
|
prompt_moderation_service=PromptModerationService({}),
|
|
generation_route_service=GenerationRouteService({}),
|
|
)
|
|
return _Fixture(
|
|
database=database,
|
|
service=service,
|
|
queue=queue,
|
|
materials=materials,
|
|
advanced=advanced,
|
|
storage_root=storage_root,
|
|
vision=vision,
|
|
image=image,
|
|
engine=engine,
|
|
style_category_id=style.category_id,
|
|
other_category_id=other.category_id,
|
|
)
|
|
|
|
|
|
def _images(count: int) -> list[dict[str, Any]]:
|
|
return [
|
|
{
|
|
"filename": f"style-{index + 1}.png",
|
|
"content_type": "image/png",
|
|
"image_data_url": PNG_DATA_URL,
|
|
"upload_source": "file",
|
|
}
|
|
for index in range(count)
|
|
]
|
|
|
|
|
|
def _upload(fixture: _Fixture, count: int = 3) -> dict[str, Any]:
|
|
return fixture.service.upload_style_set(
|
|
{
|
|
"display_name": "Parallel style set",
|
|
"category_id": fixture.style_category_id,
|
|
"images": _images(count),
|
|
},
|
|
RequestContext.system("advanced-style-test"),
|
|
)
|
|
|
|
|
|
def _execute_source_stage(fixture: _Fixture, count: int = 3) -> tuple[str, Any]:
|
|
uploaded = _upload(fixture, count)
|
|
for item in uploaded["tasks"]:
|
|
task = fixture.queue.get_job(item["task_id"])
|
|
fixture.service.execute_task(task, RequestContext.system("advanced-style-worker"))
|
|
import_id = uploaded["import"]["import_id"]
|
|
consensus = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
if consensus is None:
|
|
raise AssertionError("source barrier did not create a style consensus")
|
|
return import_id, consensus
|
|
|
|
|
|
def _execute_consensus(fixture: _Fixture, consensus: Any) -> tuple[Any, list[Any]]:
|
|
task = fixture.queue.get_job(consensus.task_id)
|
|
fixture.service.execute_task(task, RequestContext.system("advanced-style-worker"))
|
|
record = fixture.advanced.get_import(consensus.import_id)
|
|
if record is None or not record.current_attempt_id:
|
|
raise AssertionError("consensus did not create a validation batch")
|
|
attempt = fixture.advanced.get_attempt(record.current_attempt_id)
|
|
cases = fixture.advanced.list_style_validation_cases(record.current_attempt_id)
|
|
if attempt is None:
|
|
raise AssertionError("validation attempt is missing")
|
|
return attempt, cases
|
|
|
|
|
|
def _execute_validation_cases(fixture: _Fixture, cases: list[Any]) -> None:
|
|
for case in cases:
|
|
task = fixture.queue.get_job(case.task_id)
|
|
fixture.service.execute_task(task, RequestContext.system("advanced-style-worker"))
|
|
|
|
|
|
class AdvancedStyleSetWorkflowTests(unittest.TestCase):
|
|
def setUp(self) -> None:
|
|
self.temporary = tempfile.TemporaryDirectory(prefix="imagestudio-style-set-")
|
|
self.root = Path(self.temporary.name)
|
|
|
|
def tearDown(self) -> None:
|
|
self.temporary.cleanup()
|
|
|
|
def test_generic_reference_http_4xx_is_classified_for_pure_text_fallback(self) -> None:
|
|
error = ImageProviderError(
|
|
"image provider returned an HTTP error",
|
|
provider_id="style-image",
|
|
status_code=400,
|
|
error_type="http_error",
|
|
details={"body_preview": "invalid image parameter"},
|
|
)
|
|
self.assertTrue(_is_reference_image_unsupported_error(error))
|
|
|
|
server_error = ImageProviderError(
|
|
"image provider returned an HTTP error",
|
|
provider_id="style-image",
|
|
status_code=500,
|
|
error_type="http_error",
|
|
)
|
|
self.assertTrue(_is_reference_image_unsupported_error(server_error))
|
|
|
|
def test_style_only_boundaries_and_upload_creates_independent_source_tasks(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
ctx = RequestContext.system("advanced-style-boundaries")
|
|
|
|
with self.assertRaises(ApiError):
|
|
fixture.service.upload_style_set(
|
|
{
|
|
"display_name": "not style",
|
|
"category_id": fixture.other_category_id,
|
|
"images": _images(2),
|
|
},
|
|
ctx,
|
|
)
|
|
with self.assertRaises(ApiError):
|
|
fixture.service.upload_style_set(
|
|
{"display_name": "too few", "category_id": fixture.style_category_id, "images": _images(1)},
|
|
ctx,
|
|
)
|
|
with self.assertRaises(ApiError):
|
|
fixture.service.upload_style_set(
|
|
{"display_name": "too many", "category_id": fixture.style_category_id, "images": _images(9)},
|
|
ctx,
|
|
)
|
|
|
|
minimum = _upload(fixture, 2)
|
|
maximum = _upload(fixture, 8)
|
|
self.assertEqual(len(minimum["sources"]), 2)
|
|
self.assertEqual(len(maximum["sources"]), 8)
|
|
self.assertEqual(len(maximum["tasks"]), 8)
|
|
self.assertEqual(len({item["source_id"] for item in maximum["sources"]}), 8)
|
|
self.assertEqual(len({item["task_id"] for item in maximum["tasks"]}), 8)
|
|
self.assertTrue(all(item["task_type"] == "advanced_style_source_recognition" for item in maximum["tasks"]))
|
|
|
|
def test_consensus_reads_all_sources_and_creates_exactly_three_validation_cases_without_reference_by_default(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
|
|
source_requests = fixture.vision.requests[:3]
|
|
self.assertEqual(len(source_requests), 3)
|
|
self.assertTrue(all(len(item.image_uris) == 0 for item in source_requests))
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
|
|
with self.assertRaises(ApiError):
|
|
fixture.service.create_style_consensus(
|
|
import_id,
|
|
{},
|
|
RequestContext.system("advanced-style-overlap-guard"),
|
|
)
|
|
|
|
consensus_request = fixture.vision.requests[-1]
|
|
self.assertEqual(1 + len(consensus_request.image_uris), 3)
|
|
reports = json.loads(str(consensus_request.prompt))["source_reports"]
|
|
self.assertEqual({item["source_id"] for item in reports}, set(consensus.source_ids))
|
|
self.assertEqual(len(cases), 3)
|
|
self.assertEqual([item.case_key for item in cases], ["portrait", "fullbody", "novel_scene"])
|
|
self.assertEqual(len({item.task_id for item in cases}), 3)
|
|
self.assertTrue(all("source clothing" not in str(item.negative_prompt or "") for item in cases))
|
|
self.assertTrue(all(item.final_prompt.count("shared fine ink linework") == 1 for item in cases))
|
|
|
|
# Reference images are opt-in; default validation stays pure-text.
|
|
self.assertTrue(all(item.metadata.get("validation_reference_enabled") is False for item in cases))
|
|
self.assertTrue(all(not item.metadata.get("validation_reference_source_uri") for item in cases))
|
|
|
|
_execute_validation_cases(fixture, cases)
|
|
|
|
self.assertEqual(len(fixture.engine.requests), 3)
|
|
for request in fixture.engine.requests:
|
|
self.assertNotIn("image", request)
|
|
self.assertNotIn("input_images", request)
|
|
self.assertEqual(request["output_scope"]["kind"], "advanced_style_validation")
|
|
self.assertEqual(request["timeout_seconds"], 900)
|
|
self.assertEqual(len(fixture.image.requests), 3)
|
|
self.assertTrue(all(item.input_images == () for item in fixture.image.requests))
|
|
self.assertTrue(all(item.timeout_seconds == 900 for item in fixture.image.requests))
|
|
completed_for_ref = fixture.advanced.list_style_validation_cases(attempt.attempt_id)
|
|
self.assertTrue(all(item.metadata.get("reference_image_applied") is False for item in completed_for_ref))
|
|
self.assertTrue(all(int(item.to_dict().get("input_image_count") or 0) == 0 for item in completed_for_ref))
|
|
self.assertTrue(all("/ detailed" in item["expanded_prompt"] for item in fixture.engine.requests))
|
|
completed_cases = fixture.advanced.list_style_validation_cases(attempt.attempt_id)
|
|
self.assertTrue(
|
|
all(
|
|
str(item.validation_image_uri).startswith("storage://advanced_materials/style-validations/")
|
|
for item in completed_cases
|
|
)
|
|
)
|
|
self.assertTrue(all(0.0 <= float(item.fidelity_score or 0.0) <= 1.0 for item in completed_cases))
|
|
self.assertTrue(
|
|
all(item.style_review["score_calibration"]["source"] == "server_weighted_dimensions" for item in completed_cases)
|
|
)
|
|
self.assertTrue(all(item.style_review.get("status") == "succeeded" for item in completed_cases))
|
|
review_requests = [item for item in fixture.vision.requests if item.metadata.get("style_validation_review")]
|
|
self.assertEqual(len(review_requests), 3)
|
|
self.assertTrue(all(1 + len(item.image_uris) == 4 for item in review_requests))
|
|
reviewed_attempt = fixture.advanced.get_attempt(attempt.attempt_id)
|
|
expected_average = sum(float(item.fidelity_score or 0.0) for item in completed_cases) / len(completed_cases)
|
|
self.assertAlmostEqual(float(reviewed_attempt.fidelity_score or 0.0), expected_average)
|
|
self.assertFalse((fixture.storage_root / "images").exists())
|
|
self.assertFalse((fixture.storage_root / "thumbnails").exists())
|
|
record = fixture.advanced.get_import(import_id)
|
|
self.assertIsNotNone(record)
|
|
self.assertEqual(record.status, "awaiting_review")
|
|
|
|
def test_consensus_prefers_pure_text_cross_image_analysis(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
_import_id, consensus = _execute_source_stage(fixture, 8)
|
|
payloads: list[dict[str, Any]] = []
|
|
|
|
def complete(payload: dict[str, Any]) -> dict[str, Any]:
|
|
payloads.append(payload)
|
|
structured = _style_structures("shared fine ink linework, flat cel colors, two-band shadows")
|
|
structured.update(
|
|
{
|
|
"consensus_style": {"linework": "fine ink", "shading": "two-band cel"},
|
|
"representative_source_ids": payload["source_ids"][:3],
|
|
"validation_cases": [
|
|
{"case_key": "portrait", "content_prompt": "a portrait", "aspect_ratio": "1:1"},
|
|
{"case_key": "fullbody", "content_prompt": "a full body character", "aspect_ratio": "2:3"},
|
|
{"case_key": "novel_scene", "content_prompt": "a wide scene", "aspect_ratio": "16:9"},
|
|
],
|
|
}
|
|
)
|
|
return {
|
|
**structured,
|
|
"prompt": "shared fine ink linework, flat cel colors, two-band shadows",
|
|
"negative_prompt": "photorealism, source identity, watermark",
|
|
"tags": ["style", "ink", "cel-shading"],
|
|
"confidence": 0.93,
|
|
"description": "Text-only cross-image style consensus.",
|
|
}
|
|
|
|
fixture.service.model_provider_runtime.text_callable = complete
|
|
_execute_consensus(fixture, consensus)
|
|
|
|
self.assertEqual(len(payloads), 1)
|
|
self.assertEqual(len(payloads[0]["source_reports"]), 8)
|
|
self.assertEqual(len(fixture.vision.requests), 8)
|
|
completed = fixture.advanced.get_style_consensus_run(consensus.consensus_id)
|
|
self.assertIsNotNone(completed)
|
|
self.assertEqual(completed.result.get("analysis_strategy"), "text_only")
|
|
self.assertEqual(completed.result.get("image_manifest"), [])
|
|
record = fixture.advanced.get_import(consensus.import_id)
|
|
self.assertIsNotNone(record)
|
|
self.assertEqual(len(fixture.advanced.list_style_validation_cases(record.current_attempt_id)), 3)
|
|
def test_consensus_can_force_vision_assisted_analysis(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
_import_id, consensus = _execute_source_stage(fixture, 8)
|
|
updated = fixture.advanced.update_style_consensus_run(
|
|
consensus.consensus_id,
|
|
{"metadata": {**consensus.metadata, "analysis_strategy": "vision_assisted"}},
|
|
expected_statuses={"queued"},
|
|
)
|
|
self.assertIsNotNone(updated)
|
|
fixture.service.model_provider_runtime.text_callable = lambda _payload: (_ for _ in ()).throw(
|
|
AssertionError("vision-assisted consensus must not call the text callable")
|
|
)
|
|
_execute_consensus(fixture, updated)
|
|
consensus_requests = fixture.vision.requests[8:]
|
|
self.assertEqual(len(consensus_requests), 3)
|
|
self.assertEqual([1 + len(item.image_uris) for item in consensus_requests], [1, 1, 1])
|
|
def test_large_consensus_uses_grouped_two_stage_vision_requests(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
_import_id, consensus = _execute_source_stage(fixture, 8)
|
|
|
|
_execute_consensus(fixture, consensus)
|
|
|
|
consensus_requests = fixture.vision.requests[8:]
|
|
self.assertEqual(len(consensus_requests), 3)
|
|
self.assertEqual([1 + len(item.image_uris) for item in consensus_requests], [1, 1, 1])
|
|
self.assertEqual(
|
|
[json.loads(str(item.prompt)).get("analysis_mode") for item in consensus_requests],
|
|
["partial_style_consensus", "partial_style_consensus", "final_style_consensus"],
|
|
)
|
|
completed = fixture.advanced.get_style_consensus_run(consensus.consensus_id)
|
|
self.assertIsNotNone(completed)
|
|
self.assertEqual(completed.result.get("analysis_strategy"), "grouped_two_stage")
|
|
|
|
def test_style_normalization_preserves_profile_attributes_and_intact_capsule_phrases(self) -> None:
|
|
service = MaterialNormalizationService()
|
|
phrase = "highly glossy, sharp specular highlights on hair, skin, and eyes"
|
|
payload = {
|
|
"raw_analysis": {"style_extraction": {"medium": "clean digital illustration"}},
|
|
"normalized_asset_profile": {
|
|
"category": "style",
|
|
"role": "style",
|
|
"body_slots": ["global_style"],
|
|
"attributes": {
|
|
"face_proportions": {
|
|
"value": "rounded short face, large eye-to-face ratio, tiny simplified nose and mouth",
|
|
"confidence": 0.96,
|
|
"source": "consensus",
|
|
},
|
|
"linework": {
|
|
"value": "fine tapered locally colored lines",
|
|
"confidence": 0.95,
|
|
"source": "consensus",
|
|
},
|
|
},
|
|
},
|
|
"generation_capsules": {
|
|
tier: {"prompt_parts": [phrase], "negative_parts": ["semi-realistic facial anatomy"]}
|
|
for tier in ("compact", "standard", "detailed")
|
|
},
|
|
}
|
|
|
|
result = service.normalize_recognition(
|
|
payload,
|
|
prompt="specific stylized illustration grammar",
|
|
negative_prompt="semi-realistic facial anatomy",
|
|
tags=["style"],
|
|
confidence=0.96,
|
|
provider_id="test-vlm",
|
|
model="test-style-model",
|
|
route_name="test-style-route",
|
|
category_hint="style",
|
|
)
|
|
|
|
profile = result["normalized_asset_profile"]
|
|
self.assertIn("face_proportions", profile["attributes"])
|
|
self.assertIn("linework", profile["attributes"])
|
|
self.assertTrue(any("face proportions" in item for item in profile["must_preserve"]))
|
|
self.assertEqual(result["generation_capsules"]["detailed"]["prompt_parts"], [phrase])
|
|
|
|
def test_one_validation_case_failure_is_isolated_and_retryable(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
fixture.image.fail_prompt_once = "non-human courier robot"
|
|
|
|
failed_task_id = ""
|
|
for case in cases:
|
|
task = fixture.queue.get_job(case.task_id)
|
|
try:
|
|
fixture.service.execute_task(task, RequestContext.system("advanced-style-worker"))
|
|
except ImageProviderError as exc:
|
|
failed_task_id = task.task_id
|
|
fixture.service.handle_task_failure(task, exc, RequestContext.system("advanced-style-worker"))
|
|
|
|
self.assertTrue(failed_task_id)
|
|
current = fixture.advanced.list_style_validation_cases(attempt.attempt_id)
|
|
self.assertEqual([item.status for item in current].count("failed"), 1)
|
|
self.assertEqual([item.status for item in current].count("succeeded"), 2)
|
|
self.assertEqual(fixture.advanced.get_import(import_id).status, "validation_partial_failed")
|
|
failed = next(item for item in current if item.status == "failed")
|
|
|
|
fixture.queue.update_task(failed_task_id, {"status": "failed"}, RequestContext.system("advanced-style-mark-failed"))
|
|
retried = fixture.service.retry_style_validation_case(
|
|
import_id,
|
|
failed.case_id,
|
|
RequestContext.system("advanced-style-retry"),
|
|
)
|
|
self.assertNotEqual(retried["task"]["task_id"], failed_task_id)
|
|
self.assertEqual(retried["case"]["metadata"]["retry_count"], 1)
|
|
old_task = fixture.queue.get_job(failed_task_id)
|
|
self.assertEqual(old_task.status, "superseded")
|
|
self.assertEqual(old_task.metadata["superseded_by"], retried["task"]["task_id"])
|
|
fixture.service.handle_task_failure(
|
|
old_task,
|
|
RuntimeError("late failure from superseded validation task"),
|
|
RequestContext.system("advanced-style-stale-worker"),
|
|
)
|
|
still_retried = fixture.advanced.get_style_validation_case(failed.case_id)
|
|
self.assertEqual(still_retried.status, "queued")
|
|
self.assertEqual(still_retried.task_id, retried["task"]["task_id"])
|
|
retry_task = fixture.queue.get_job(retried["task"]["task_id"])
|
|
fixture.service.execute_task(retry_task, RequestContext.system("advanced-style-worker"))
|
|
|
|
self.assertEqual(fixture.advanced.get_import(import_id).status, "awaiting_review")
|
|
self.assertTrue(
|
|
all(item.status == "succeeded" for item in fixture.advanced.list_style_validation_cases(attempt.attempt_id))
|
|
)
|
|
|
|
def test_automatic_style_review_failure_never_discards_generated_validation_images(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
fixture.vision.fail_reviews = True
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
|
|
_execute_validation_cases(fixture, cases)
|
|
|
|
completed = fixture.advanced.list_style_validation_cases(attempt.attempt_id)
|
|
self.assertTrue(all(item.status == "succeeded" and item.validation_image_uri for item in completed))
|
|
self.assertTrue(all(item.style_review.get("status") == "review_failed" for item in completed))
|
|
self.assertTrue(all(item.fidelity_score is None for item in completed))
|
|
self.assertEqual(fixture.advanced.get_import(import_id).status, "awaiting_review")
|
|
|
|
def test_rejection_creates_new_consensus_revision_and_rebuilds_capsules(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
_execute_validation_cases(fixture, cases)
|
|
first_consensus = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
first_capsule = first_consensus.result["generation_capsules"]["detailed"]["prompt_parts"]
|
|
first_prompts = [item.content_prompt for item in cases]
|
|
|
|
rebuilt = fixture.service.reject_attempt(
|
|
import_id,
|
|
attempt.attempt_id,
|
|
{"style_adjustment_text": "use cooler shadows", "decision_notes": "shadows are too warm"},
|
|
RequestContext.system("advanced-style-reviewer"),
|
|
)
|
|
consensus_task = fixture.queue.get_job(rebuilt["task"]["task_id"])
|
|
fixture.service.execute_task(consensus_task, RequestContext.system("advanced-style-worker"))
|
|
|
|
latest = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
self.assertEqual(latest.revision, first_consensus.revision + 1)
|
|
self.assertIn("cooler shadows", latest.prompt)
|
|
second_capsule = latest.result["generation_capsules"]["detailed"]["prompt_parts"]
|
|
self.assertNotEqual(first_capsule, second_capsule)
|
|
self.assertTrue(any("cooler shadows" in item for item in second_capsule))
|
|
record = fixture.advanced.get_import(import_id)
|
|
next_cases = fixture.advanced.list_style_validation_cases(record.current_attempt_id)
|
|
self.assertEqual(len([item.content_prompt for item in next_cases]), len(first_prompts))
|
|
for before, after in zip(first_prompts, [item.content_prompt for item in next_cases]):
|
|
self.assertIn(before.split(",")[0], after)
|
|
self.assertEqual([item.seed for item in next_cases], [item.seed for item in cases])
|
|
self.assertEqual(fixture.advanced.get_attempt(attempt.attempt_id).status, "rejected")
|
|
|
|
def test_style_feedback_compares_previous_images_and_cannot_invert_decrease_direction(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
_execute_validation_cases(fixture, cases)
|
|
|
|
rebuilt = fixture.service.reject_attempt(
|
|
import_id,
|
|
attempt.attempt_id,
|
|
{"style_adjustment_text": "颜色对比太过强烈"},
|
|
RequestContext.system("advanced-style-direction-guard"),
|
|
)
|
|
consensus_task = fixture.queue.get_job(rebuilt["task"]["task_id"])
|
|
fixture.service.execute_task(consensus_task, RequestContext.system("advanced-style-worker"))
|
|
|
|
request = fixture.vision.requests[-1]
|
|
self.assertEqual(1 + len(request.image_uris), 6)
|
|
manifest = request.metadata["image_manifest"]
|
|
self.assertEqual([item["kind"] for item in manifest].count("source_reference"), 3)
|
|
self.assertEqual([item["kind"] for item in manifest].count("previous_validation"), 3)
|
|
request_payload = json.loads(str(request.prompt))
|
|
self.assertEqual(len(request_payload["previous_validation"]["validation_cases"]), 3)
|
|
self.assertEqual(request_payload["style_adjustment_plan"]["decrease"], ["color contrast"])
|
|
|
|
latest = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
self.assertIsNotNone(latest)
|
|
positive = str(latest.prompt or "").casefold()
|
|
negative = str(latest.negative_prompt or "").casefold()
|
|
self.assertNotIn("intense color contrast", positive)
|
|
self.assertNotIn("extreme color dynamics", positive)
|
|
self.assertNotIn("high contrast", positive)
|
|
self.assertIn("balanced moderate color contrast", positive)
|
|
self.assertIn("restrained color separation", positive)
|
|
self.assertNotIn("low contrast", negative)
|
|
self.assertNotIn("washed out", negative)
|
|
self.assertIn("excessive color contrast", negative)
|
|
self.assertEqual(latest.result["human_adjustments"]["style_adjustment_plan"]["decrease"], ["color contrast"])
|
|
self.assertTrue(latest.result["human_adjustments"]["guard"]["applied"])
|
|
self.assertEqual(len(latest.result["comparison_context"]["validation_cases"]), 3)
|
|
detailed = latest.result["generation_capsules"]["detailed"]
|
|
self.assertIn("balanced moderate color contrast", detailed["prompt_parts"])
|
|
self.assertIn("excessive color contrast", detailed["negative_parts"])
|
|
|
|
record = fixture.advanced.get_import(import_id)
|
|
next_cases = fixture.advanced.list_style_validation_cases(record.current_attempt_id)
|
|
self.assertTrue(all("balanced moderate color contrast" in item.final_prompt for item in next_cases))
|
|
start = len(fixture.engine.requests)
|
|
_execute_validation_cases(fixture, next_cases)
|
|
generated = fixture.engine.requests[start:]
|
|
self.assertEqual(len(generated), 3)
|
|
self.assertTrue(all("balanced moderate color contrast" in item["expanded_prompt"] for item in generated))
|
|
self.assertTrue(all("excessive color contrast" in item["expanded_negative_prompt"] for item in generated))
|
|
|
|
def test_validation_content_feedback_rebuilds_cases_and_changes_seeds(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
_execute_validation_cases(fixture, cases)
|
|
first_prompts = [item.content_prompt for item in cases]
|
|
first_seeds = [item.seed for item in cases]
|
|
instruction = "女性角色,全身,萌袖卫衣、泡泡袜和运动鞋,白发蓝瞳猫耳"
|
|
|
|
rebuilt = fixture.service.reject_attempt(
|
|
import_id,
|
|
attempt.attempt_id,
|
|
{"validation_instruction": instruction, "decision_notes": "第一轮角色差异过大"},
|
|
RequestContext.system("advanced-style-reviewer"),
|
|
)
|
|
consensus_task = fixture.queue.get_job(rebuilt["task"]["task_id"])
|
|
fixture.service.execute_task(consensus_task, RequestContext.system("advanced-style-worker"))
|
|
|
|
latest = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
self.assertEqual(latest.metadata["validation_instruction"], instruction)
|
|
record = fixture.advanced.get_import(import_id)
|
|
next_attempt = fixture.advanced.get_attempt(record.current_attempt_id)
|
|
next_cases = fixture.advanced.list_style_validation_cases(record.current_attempt_id)
|
|
self.assertNotEqual([item.content_prompt for item in next_cases], first_prompts)
|
|
self.assertNotEqual([item.seed for item in next_cases], first_seeds)
|
|
self.assertTrue(all(instruction in item.content_prompt for item in next_cases))
|
|
self.assertTrue(all(instruction in item.final_prompt for item in next_cases))
|
|
self.assertEqual(next_attempt.metadata["validation_instruction"], instruction)
|
|
self.assertIn("验证内容", next_attempt.adjustment_text)
|
|
request_count = len(fixture.engine.requests)
|
|
_execute_validation_cases(fixture, next_cases)
|
|
next_requests = fixture.engine.requests[request_count:]
|
|
self.assertEqual(len(next_requests), 3)
|
|
self.assertTrue(all(instruction in item["expanded_prompt"] for item in next_requests))
|
|
self.assertTrue(all(item["seed"] in {case.seed for case in next_cases} for item in next_requests))
|
|
|
|
|
|
def test_validation_reference_can_be_disabled_for_pure_text(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
uploaded = _upload(fixture, 3)
|
|
for item in uploaded["tasks"]:
|
|
task = fixture.queue.get_job(item["task_id"])
|
|
fixture.service.execute_task(task, RequestContext.system("advanced-style-worker"))
|
|
import_id = uploaded["import"]["import_id"]
|
|
latest = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
self.assertIsNotNone(latest)
|
|
if latest.status in {"queued", "running"}:
|
|
fixture.advanced.update_style_consensus_run(
|
|
latest.consensus_id,
|
|
{"status": "failed", "error": {"message": "replace with no-ref consensus"}},
|
|
expected_statuses={"queued", "running", "failed"},
|
|
)
|
|
created = fixture.service.create_style_consensus(
|
|
import_id,
|
|
{"validation_reference_enabled": False},
|
|
RequestContext.system("no-ref"),
|
|
)
|
|
consensus = fixture.advanced.get_style_consensus_run(created["consensus"]["consensus_id"])
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
self.assertTrue(all(item.metadata.get("validation_reference_enabled") is False for item in cases))
|
|
self.assertTrue(all(not item.metadata.get("validation_reference_source_uri") for item in cases))
|
|
_execute_validation_cases(fixture, cases)
|
|
self.assertTrue(all("input_images" not in item for item in fixture.engine.requests[-3:]))
|
|
self.assertTrue(all(item.input_images == () for item in fixture.image.requests[-3:]))
|
|
completed = fixture.advanced.list_style_validation_cases(attempt.attempt_id)
|
|
self.assertTrue(all(item.metadata.get("reference_image_applied") is False for item in completed))
|
|
self.assertTrue(all(int(item.to_dict().get("input_image_count") or 0) == 0 for item in completed))
|
|
|
|
def test_validation_reference_uses_user_selected_source(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
uploaded = _upload(fixture, 3)
|
|
for item in uploaded["tasks"]:
|
|
task = fixture.queue.get_job(item["task_id"])
|
|
fixture.service.execute_task(task, RequestContext.system("advanced-style-worker"))
|
|
import_id = uploaded["import"]["import_id"]
|
|
sources = fixture.advanced.list_style_sources(import_id, include_excluded=False)
|
|
chosen = sources[-1].source_id
|
|
latest = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
if latest is not None and latest.status in {"queued", "running"}:
|
|
fixture.advanced.update_style_consensus_run(
|
|
latest.consensus_id,
|
|
{"status": "failed", "error": {"message": "replace with selected-ref consensus"}},
|
|
expected_statuses={"queued", "running", "failed"},
|
|
)
|
|
created = fixture.service.create_style_consensus(
|
|
import_id,
|
|
{
|
|
"validation_reference_enabled": True,
|
|
"validation_reference_source_id": chosen,
|
|
},
|
|
RequestContext.system("selected-ref"),
|
|
)
|
|
consensus = fixture.advanced.get_style_consensus_run(created["consensus"]["consensus_id"])
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
self.assertEqual({item.metadata.get("validation_reference_source_id") for item in cases}, {chosen})
|
|
self.assertTrue(all(item.metadata.get("validation_reference_mode") == "user_selected" for item in cases))
|
|
_execute_validation_cases(fixture, cases)
|
|
self.assertTrue(all(len(item.input_images) == 1 for item in fixture.image.requests[-3:]))
|
|
completed = fixture.advanced.list_style_validation_cases(attempt.attempt_id)
|
|
self.assertTrue(all(item.metadata.get("validation_reference_source_id") == chosen for item in completed))
|
|
self.assertTrue(all(item.metadata.get("reference_image_applied") for item in completed))
|
|
|
|
def test_style_attempt_listing_includes_all_three_validation_images(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
_execute_validation_cases(fixture, cases)
|
|
|
|
listed = fixture.service.list_attempts(import_id)
|
|
current = next(item for item in listed if item["attempt_id"] == attempt.attempt_id)
|
|
self.assertEqual(len(current["validation_cases"]), 3)
|
|
self.assertTrue(all(item["validation_image_uri"] for item in current["validation_cases"]))
|
|
detail = fixture.service.get_import(import_id)
|
|
detail_attempt = next(item for item in detail["attempts"] if item["attempt_id"] == attempt.attempt_id)
|
|
self.assertEqual(len(detail_attempt["validation_cases"]), 3)
|
|
|
|
def test_legacy_adjustment_text_is_never_silently_discarded(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
_execute_validation_cases(fixture, cases)
|
|
legacy_text = "use a white-haired blue-eyed cat-eared woman in the next validation"
|
|
|
|
rebuilt = fixture.service.reject_attempt(
|
|
import_id,
|
|
attempt.attempt_id,
|
|
{"adjustment_text": legacy_text},
|
|
RequestContext.system("legacy-client"),
|
|
)
|
|
consensus_task = fixture.queue.get_job(rebuilt["task"]["task_id"])
|
|
fixture.service.execute_task(consensus_task, RequestContext.system("advanced-style-worker"))
|
|
|
|
latest = fixture.advanced.get_latest_style_consensus_run(import_id)
|
|
next_cases = fixture.advanced.list_style_validation_cases(fixture.advanced.get_import(import_id).current_attempt_id)
|
|
self.assertEqual(latest.metadata["style_adjustment_text"], legacy_text)
|
|
self.assertEqual(latest.metadata["validation_instruction"], legacy_text)
|
|
self.assertTrue(all(legacy_text in item.final_prompt for item in next_cases))
|
|
|
|
def test_three_successful_cases_seal_one_advanced_material_idempotently(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
import_id, consensus = _execute_source_stage(fixture, 3)
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
_execute_validation_cases(fixture, cases)
|
|
ctx = RequestContext.system("advanced-style-accept")
|
|
|
|
accepted = fixture.service.accept_attempt(
|
|
import_id,
|
|
attempt.attempt_id,
|
|
{"fidelity_score": 0.94, "decision_notes": "style transfers across all scenes"},
|
|
ctx,
|
|
)
|
|
replay = fixture.service.accept_attempt(import_id, attempt.attempt_id, {}, ctx)
|
|
|
|
self.assertEqual(accepted["material"]["material_id"], replay["material"]["material_id"])
|
|
self.assertTrue(accepted["material"]["material_id"].startswith("advmat_"))
|
|
self.assertEqual(accepted["material"]["priority"], 100)
|
|
self.assertEqual(len(accepted["material"]["metadata"]["style_set"]["source_ids"]), 3)
|
|
self.assertEqual(len(accepted["material"]["metadata"]["style_set"]["validation_cases"]), 3)
|
|
advanced_items, advanced_total = fixture.advanced.list_materials(page=1, page_size=10)
|
|
standard_items, standard_total = fixture.materials.list_materials(page=1, page_size=10)
|
|
self.assertEqual(advanced_total, 1)
|
|
self.assertEqual([item.material_id for item in advanced_items], [accepted["material"]["material_id"]])
|
|
self.assertEqual(standard_total, 0)
|
|
self.assertEqual(standard_items, [])
|
|
|
|
def test_queue_write_failures_leave_sources_and_validation_cases_retryable(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
original_create_task = fixture.queue.create_task
|
|
|
|
def reject_source_tasks(payload: dict[str, Any], ctx: RequestContext):
|
|
if payload.get("task_type") == "advanced_style_source_recognition":
|
|
raise RuntimeError("controlled source queue failure")
|
|
return original_create_task(payload, ctx)
|
|
|
|
fixture.queue.create_task = reject_source_tasks # type: ignore[method-assign]
|
|
uploaded = _upload(fixture, 2)
|
|
self.assertEqual(uploaded["tasks"], [])
|
|
self.assertEqual(uploaded["import"]["status"], "style_source_review_required")
|
|
self.assertTrue(all(item["status"] == "failed" for item in uploaded["sources"]))
|
|
|
|
validation_root = self.root / "validation-queue"
|
|
validation_root.mkdir(parents=True, exist_ok=True)
|
|
fixture = _fixture(validation_root)
|
|
import_id, consensus = _execute_source_stage(fixture, 2)
|
|
original_create_task = fixture.queue.create_task
|
|
|
|
def reject_validation_tasks(payload: dict[str, Any], ctx: RequestContext):
|
|
if payload.get("task_type") == "advanced_style_validation_generation":
|
|
raise RuntimeError("controlled validation queue failure")
|
|
return original_create_task(payload, ctx)
|
|
|
|
fixture.queue.create_task = reject_validation_tasks # type: ignore[method-assign]
|
|
attempt, cases = _execute_consensus(fixture, consensus)
|
|
self.assertEqual(attempt.status, "validation_partial_failed")
|
|
self.assertTrue(all(item.status == "failed" and item.task_id is None for item in cases))
|
|
self.assertEqual(fixture.advanced.get_import(import_id).status, "validation_partial_failed")
|
|
|
|
def test_retry_source_refreshes_obsolete_route_for_source_and_consensus(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
uploaded = _upload(fixture, 2)
|
|
import_id = uploaded["import"]["import_id"]
|
|
source_id = uploaded["sources"][0]["source_id"]
|
|
fixture.advanced.update_style_source(
|
|
source_id,
|
|
{"status": "failed", "task_id": None, "error": {"error_type": "route_unavailable"}},
|
|
)
|
|
repaired_route = encode_model_route_chain(
|
|
"plugin-vision-route",
|
|
"astrbot:vision-provider",
|
|
)
|
|
fixture.service.config["model_assignments"]["advanced_material_recognition"] = repaired_route
|
|
|
|
retried = fixture.service.retry_style_source(
|
|
import_id,
|
|
source_id,
|
|
RequestContext.system("advanced-style-route-repair"),
|
|
)
|
|
|
|
source = fixture.advanced.get_style_source(source_id)
|
|
record = fixture.advanced.get_import(import_id)
|
|
task = fixture.queue.get_job(retried["task"]["task_id"])
|
|
self.assertEqual(source.recognition_model_route, repaired_route)
|
|
self.assertEqual(record.recognition_model_route, repaired_route)
|
|
self.assertEqual(task.model_route, repaired_route)
|
|
|
|
def test_deleted_queue_row_is_reconciled_and_import_can_be_removed(self) -> None:
|
|
fixture = _fixture(self.root)
|
|
uploaded = _upload(fixture, 2)
|
|
import_id = uploaded["import"]["import_id"]
|
|
source_id = uploaded["sources"][0]["source_id"]
|
|
task_id = uploaded["tasks"][0]["task_id"]
|
|
source_before = fixture.advanced.get_style_source(source_id)
|
|
source_path = fixture.service.storage.ensure_file(source_before.source_image_uri)
|
|
self.assertTrue(source_path.exists())
|
|
|
|
fixture.queue.update_task(
|
|
task_id,
|
|
{"status": "failed", "error_message": "controlled queue failure"},
|
|
RequestContext.system("advanced-style-queue-failure"),
|
|
)
|
|
fixture.queue.delete_job(task_id, RequestContext.system("advanced-style-queue-delete"))
|
|
|
|
detail = fixture.service.get_import(import_id)
|
|
source_after = fixture.advanced.get_style_source(source_id)
|
|
self.assertEqual(source_after.status, "failed")
|
|
self.assertIsNone(source_after.task_id)
|
|
self.assertEqual(source_after.error["error_type"], "queue_task_missing")
|
|
self.assertEqual(detail["import"]["status"], "style_source_review_required")
|
|
|
|
deleted = fixture.service.delete_import(
|
|
import_id,
|
|
RequestContext.system("advanced-style-delete-import"),
|
|
)
|
|
self.assertTrue(deleted["deleted"])
|
|
self.assertIsNone(fixture.advanced.get_import(import_id))
|
|
self.assertIsNone(fixture.advanced.get_style_source(source_id))
|
|
self.assertFalse(source_path.exists())
|
|
|
|
def test_style_review_scores_are_server_weighted_with_fixed_dimensions(self) -> None:
|
|
normalized = _normalize_style_dimension_scores(
|
|
{
|
|
"face_proportions": 0.8,
|
|
"iris_construction": {"score": 0.8},
|
|
"line_art": 0.8,
|
|
"global_palette": 0.8,
|
|
"local_contrast": 0.8,
|
|
"shadow_rendering": 0.8,
|
|
"highlight_shape": 0.8,
|
|
"body_ratio": 0.8,
|
|
"hair_strands": 0.8,
|
|
"detail_density": 0.8,
|
|
"environment": 0.8,
|
|
}
|
|
)
|
|
self.assertEqual(set(normalized), set(STYLE_REVIEW_DIMENSIONS))
|
|
score, calibration = _weighted_style_fidelity_score("portrait", normalized, 0.99)
|
|
self.assertAlmostEqual(float(score or 0.0), 0.8)
|
|
self.assertEqual(calibration["source"], "server_weighted_dimensions")
|
|
self.assertEqual(calibration["dimension_coverage"], 1.0)
|
|
|
|
def test_style_prompt_compiler_rewrites_semantic_risks_and_keeps_scale_overrides(self) -> None:
|
|
payload = {
|
|
"normalized_asset_profile": {
|
|
"must_preserve": ["fine colored linework", "segmented ring halo highlight across the hair"],
|
|
},
|
|
"generation_capsules": {
|
|
"detailed": {
|
|
"prompt_parts": [
|
|
"fine colored linework with tapered ends",
|
|
"fine colored linework",
|
|
"soft two-band cel shading",
|
|
],
|
|
"negative_parts": ["photorealism"],
|
|
}
|
|
},
|
|
"prompt_priority_groups": {
|
|
"core": ["rounded stylized facial structure"],
|
|
"structural": ["large layered irises"],
|
|
"rendering": ["pastel global palette with crisp local separation"],
|
|
},
|
|
"semantic_risk_audit": [
|
|
{
|
|
"original_phrase": "segmented ring halo highlight across the hair",
|
|
"safe_rewrite": "segmented satin sheen painted directly on the curved hair surface",
|
|
"negative_guard": "floating luminous object detached from the styled surface",
|
|
}
|
|
],
|
|
"scale_capsules": {
|
|
"fullbody": {"prompt_parts": ["readable colored silhouette lines at full-body scale"]}
|
|
},
|
|
}
|
|
prompt = _detailed_style_prompt(payload, "fallback")
|
|
negative = _detailed_style_negative_prompt(payload, "")
|
|
self.assertNotIn("ring halo", prompt)
|
|
self.assertIn("painted directly on the curved hair surface", prompt)
|
|
self.assertEqual(prompt.count("fine colored linework"), 1)
|
|
self.assertIn("detached from the styled surface", negative)
|
|
self.assertIn("full-body scale", _scale_specific_style_prompt(payload, "fullbody"))
|
|
|
|
def test_review_aggregation_separates_recurrent_and_scale_specific_failures(self) -> None:
|
|
def case(case_key: str, case_id: str, scores: dict[str, float]) -> SimpleNamespace:
|
|
return SimpleNamespace(
|
|
case_key=case_key,
|
|
case_id=case_id,
|
|
fidelity_score=0.6,
|
|
style_review={
|
|
"status": "succeeded",
|
|
"fidelity_score": 0.6,
|
|
"dimension_scores": scores,
|
|
"style_deltas": [],
|
|
"prompt_patch": {},
|
|
"semantic_risks": [],
|
|
},
|
|
)
|
|
|
|
feedback = _aggregate_style_review_feedback(
|
|
[
|
|
case("portrait", "p", {"linework": 0.5, "eye_design": 0.5}),
|
|
case("fullbody", "f", {"linework": 0.6, "anatomy_scale": 0.5}),
|
|
case("novel_scene", "n", {"linework": 0.55, "background_rendering": 0.5}),
|
|
]
|
|
)
|
|
self.assertEqual(feedback["recurrent_weak_dimensions"], ["linework"])
|
|
self.assertEqual(feedback["scale_specific_weak_dimensions"]["portrait"], ["eye_design"])
|
|
self.assertEqual(feedback["scale_specific_weak_dimensions"]["fullbody"], ["anatomy_scale"])
|
|
self.assertEqual(feedback["scale_specific_weak_dimensions"]["novel_scene"], ["background_rendering"])
|
|
|
|
def test_style_age_terms_are_not_compiled_into_transfer_prompts(self) -> None:
|
|
payload = {
|
|
"normalized_asset_profile": {
|
|
"attributes": {
|
|
"apparent_age": {
|
|
"value": "pre-adolescent to early adolescent bishoujo style",
|
|
"eligible_for_generation": True,
|
|
},
|
|
"linework": {"value": "thin colored lineart", "eligible_for_generation": True},
|
|
},
|
|
"must_preserve": [
|
|
"pre-adolescent to early adolescent bishoujo style",
|
|
"thin colored lineart",
|
|
],
|
|
},
|
|
"generation_capsules": {
|
|
"detailed": {
|
|
"prompt_parts": [
|
|
"highly stylized youthful moe aesthetic, pre-adolescent character proportions",
|
|
"thin colored lineart",
|
|
],
|
|
"negative_parts": [],
|
|
}
|
|
},
|
|
"feature_evidence": [
|
|
{"trait": "thin colored lineart", "support_ratio": 1.0, "confidence": 0.95}
|
|
],
|
|
}
|
|
forced = _force_style_structures(payload)
|
|
prompt = _detailed_style_prompt(forced, "fallback")
|
|
self.assertNotIn("pre-adolescent", prompt.casefold())
|
|
self.assertNotIn("early adolescent", prompt.casefold())
|
|
self.assertNotIn("child proportions", prompt.casefold())
|
|
self.assertNotIn("mature adult", prompt.casefold())
|
|
self.assertNotIn("explicitly adult", prompt.casefold())
|
|
self.assertFalse(forced["normalized_asset_profile"]["attributes"]["apparent_age"]["eligible_for_generation"])
|
|
fullbody = _scale_transfer_instruction("fullbody").casefold()
|
|
self.assertTrue("5-7" in fullbody or "5 to 7" in fullbody or "heads tall" in fullbody)
|
|
self.assertIn("chibi", fullbody)
|
|
self.assertNotIn("explicitly adult", fullbody)
|
|
# "mature adult-woman body canon" may appear as a forbidden phrase; that is intentional.
|
|
self.assertIn("not force", fullbody)
|
|
|
|
def test_review_score_penalizes_mismatches_patches_risks_and_text_severity(self) -> None:
|
|
normalized = {key: 1.0 for key in STYLE_REVIEW_DIMENSIONS}
|
|
deltas = _normalize_style_deltas(
|
|
[
|
|
{
|
|
"dimension": "highlights",
|
|
"scope": "local",
|
|
"severity": "moderate",
|
|
"observed": "solid white bar",
|
|
}
|
|
],
|
|
case_key="portrait",
|
|
)
|
|
self.assertEqual(deltas[0]["severity"], 0.5)
|
|
score, calibration = _weighted_style_fidelity_score(
|
|
"portrait",
|
|
normalized,
|
|
0.94,
|
|
mismatches=["hair highlight became a solid bar"],
|
|
deltas=deltas,
|
|
prompt_patch={"positive_additions": ["surface-bound satin sheen"]},
|
|
semantic_risks=[{"original_phrase": "horizontal band highlight"}],
|
|
)
|
|
self.assertLess(float(score or 1.0), 0.90)
|
|
self.assertTrue(calibration["review_inconsistent"])
|
|
self.assertGreater(calibration["consistency_penalty"], 0.0)
|
|
self.assertLessEqual(float(score or 1.0), 0.94)
|
|
|
|
def test_prompt_compiler_requires_evidence_for_core_background_and_palette_traits(self) -> None:
|
|
payload = {
|
|
"normalized_asset_profile": {
|
|
"must_preserve": [
|
|
"thin colored lineart matching local fills",
|
|
"soft-focus background with circular bokeh",
|
|
"high-key pastel-dominated color palette",
|
|
]
|
|
},
|
|
"generation_capsules": {
|
|
"detailed": {
|
|
"prompt_parts": [
|
|
"thin colored lineart matching local fills",
|
|
"soft-focus background with circular bokeh",
|
|
"high-key pastel-dominated color palette",
|
|
],
|
|
"negative_parts": [],
|
|
}
|
|
},
|
|
"prompt_priority_groups": {
|
|
"core": [
|
|
"thin colored lineart matching local fills",
|
|
"soft-focus background with circular bokeh",
|
|
"high-key pastel-dominated color palette",
|
|
]
|
|
},
|
|
"feature_evidence": [
|
|
{
|
|
"trait": "thin colored lineart matching local fills",
|
|
"support_ratio": 1.0,
|
|
"confidence": 0.95,
|
|
}
|
|
],
|
|
}
|
|
prompt = _detailed_style_prompt(payload, "fallback").casefold()
|
|
self.assertIn("thin colored lineart", prompt)
|
|
self.assertNotIn("circular bokeh", prompt)
|
|
# Palette is a transferable style trait even when the provider paraphrases its evidence; literal scene effects still require evidence.
|
|
|
|
def test_semantic_second_pass_rewrites_provider_safe_band_and_adds_literal_shape_guards(self) -> None:
|
|
payload = {
|
|
"normalized_asset_profile": {
|
|
"must_preserve": ["bright horizontal band highlight across the hair crown"]
|
|
},
|
|
"generation_capsules": {
|
|
"detailed": {
|
|
"prompt_parts": ["bright horizontal band highlight across the hair crown"],
|
|
"negative_parts": [],
|
|
}
|
|
},
|
|
"feature_evidence": [
|
|
{
|
|
"trait": "bright horizontal highlight across the hair crown",
|
|
"support_ratio": 0.875,
|
|
"confidence": 0.95,
|
|
}
|
|
],
|
|
"semantic_risk_audit": [
|
|
{
|
|
"original_phrase": "angel ring highlight",
|
|
"safe_rewrite": "bright horizontal band highlight across the hair crown",
|
|
"negative_guard": "floating halo",
|
|
}
|
|
],
|
|
}
|
|
prompt = _detailed_style_prompt(payload, "fallback").casefold()
|
|
negative = _detailed_style_negative_prompt(payload, "").casefold()
|
|
self.assertNotIn("band highlight", prompt)
|
|
self.assertNotIn("angel ring", prompt)
|
|
self.assertIn("semi-transparent satin sheen", prompt)
|
|
self.assertIn("curved hair volume", prompt)
|
|
self.assertIn("solid white stripe", negative)
|
|
self.assertIn("geometric zigzag bar", negative)
|
|
|
|
def test_scale_capsule_excludes_common_traits_and_keeps_scale_only_constraints(self) -> None:
|
|
payload = {
|
|
"scale_capsules": {
|
|
"fullbody": (
|
|
"thin colored lineart matching local fills, layered irises with multiple catchlights, "
|
|
"source head-to-body ratio around 1:6 with slender limbs"
|
|
)
|
|
},
|
|
"feature_evidence": [
|
|
{"trait": "thin colored lineart matching local fills", "support_ratio": 1.0, "confidence": 0.95},
|
|
{"trait": "layered irises with multiple catchlights", "support_ratio": 1.0, "confidence": 0.95},
|
|
],
|
|
}
|
|
scale = _scale_specific_style_prompt(
|
|
payload,
|
|
"fullbody",
|
|
"thin colored lineart matching local fills, layered irises with multiple catchlights",
|
|
).casefold()
|
|
self.assertNotIn("thin colored lineart", scale)
|
|
self.assertNotIn("layered irises", scale)
|
|
self.assertIn("head-to-body", scale)
|
|
self.assertIn("1:6", scale)
|
|
|
|
def test_validation_cases_keep_age_band_open_and_neutral_scene_lighting(self) -> None:
|
|
cases = _validation_cases(
|
|
[
|
|
{
|
|
"case_key": "portrait",
|
|
"content_prompt": "a young heroine portrait with circular bokeh and neon rim light",
|
|
},
|
|
{
|
|
"case_key": "fullbody",
|
|
"content_prompt": "the same heroine, youthful full body proportions",
|
|
},
|
|
{
|
|
"case_key": "novel_scene",
|
|
"content_prompt": "the same heroine on a rooftop at dawn with sunset lens flare and bokeh",
|
|
},
|
|
],
|
|
None,
|
|
)
|
|
portrait, fullbody, novel = [item["content_prompt"].casefold() for item in cases]
|
|
self.assertNotIn("mature adult", portrait)
|
|
self.assertNotIn("the depicted character is an adult", portrait)
|
|
self.assertNotIn("neon", portrait)
|
|
self.assertNotIn("bokeh", portrait)
|
|
self.assertNotIn("mature adult limb", fullbody)
|
|
self.assertTrue("heads tall" in fullbody or "head-to-body" in fullbody)
|
|
self.assertIn("chibi", fullbody)
|
|
self.assertNotIn("dawn", novel)
|
|
self.assertNotIn("sunset", novel)
|
|
self.assertNotIn("lens flare", novel)
|
|
self.assertNotIn("bokeh", novel)
|
|
self.assertIn("overcast", novel)
|
|
|
|
|
|
def test_source_body_ratio_preserved_and_mature_override_stripped(self) -> None:
|
|
payload = {
|
|
"normalized_asset_profile": {
|
|
"attributes": {
|
|
"facial_age_stylization": {
|
|
"value": "Pronounced neotenic abstraction featuring an exaggerated eye-to-face ratio",
|
|
"eligible_for_generation": True,
|
|
},
|
|
"body_maturity_proportions": {
|
|
"value": (
|
|
"The source illustrations feature a slightly stylized head-to-body ratio of approximately "
|
|
"1:5.5 to 1:6 with slender limbs, but style preservation must adapt to a natural 6.5 to 7.5 "
|
|
"heads-tall mature adult proportion during full-body generation."
|
|
),
|
|
"eligible_for_generation": True,
|
|
},
|
|
"actual_age_evidence": {
|
|
"value": "None. The style abstracts features structurally.",
|
|
"eligible_for_generation": True,
|
|
},
|
|
},
|
|
"must_preserve": [
|
|
"thin continuous lineart tinted in local color families",
|
|
"large eyes with multi-layered gradient irises",
|
|
],
|
|
},
|
|
"generation_capsules": {
|
|
"detailed": {
|
|
"prompt_parts": [
|
|
"thin continuous lineart tinted in local color families",
|
|
"large eyes with multi-layered gradient irises",
|
|
],
|
|
"must_preserve": [
|
|
"thin continuous lineart tinted in local color families",
|
|
"large eyes with multi-layered gradient irises",
|
|
],
|
|
}
|
|
},
|
|
"feature_evidence": [
|
|
{"trait": "thin continuous lineart tinted in local color families", "support_ratio": 1.0, "confidence": 0.95},
|
|
{"trait": "large eyes with multi-layered gradient irises", "support_ratio": 1.0, "confidence": 0.95},
|
|
],
|
|
}
|
|
forced = _force_style_structures(payload)
|
|
prompt = _detailed_style_prompt(forced, "fallback").casefold()
|
|
self.assertIn("neotenic", prompt)
|
|
self.assertIn("head-to-body", prompt)
|
|
self.assertTrue("1:5.5" in prompt or "1:5.5" in prompt.replace(" ", ""))
|
|
self.assertNotIn("mature adult", prompt)
|
|
self.assertNotIn("6.5", prompt)
|
|
self.assertNotIn("7.5", prompt)
|
|
attrs = forced["normalized_asset_profile"]["attributes"]
|
|
self.assertEqual(attrs["facial_age_stylization"]["transfer_role"], "style_structure")
|
|
self.assertEqual(attrs["body_maturity_proportions"]["transfer_role"], "style_structure")
|
|
self.assertEqual(attrs["actual_age_evidence"]["transfer_role"], "reference_only")
|
|
fullbody = _sanitize_validation_content(
|
|
"fullbody",
|
|
"the same heroine, youthful full body proportions with mature adult limb lengths between 6.5 and 7.5 heads tall",
|
|
).casefold()
|
|
self.assertNotIn("mature adult limb", fullbody)
|
|
# Soft anatomy band uses 5.5-6.5 by default; that is intentional and different from mature 6.5-7.5 lock.
|
|
self.assertIn("5.5", fullbody)
|
|
self.assertIn("not chibi", fullbody)
|
|
self.assertNotIn("between 6.5 and 7.5", fullbody)
|
|
|
|
|
|
def test_fullbody_soft_anatomy_band_clamps_chibi_and_keeps_source_ratio(self) -> None:
|
|
from backend.services.advanced_style_set_service import (
|
|
_anatomy_soft_band_phrase,
|
|
_clamp_head_ratio_range,
|
|
_extract_head_ratio_range,
|
|
_source_anatomy_range_from_style_result,
|
|
)
|
|
self.assertEqual(_extract_head_ratio_range("head-to-body ratio of approximately 1:5.5 to 1:6"), (5.5, 6.0))
|
|
self.assertEqual(_clamp_head_ratio_range((3.0, 4.0)), (5.0, 5.0)) # chibi clamped up to soft min
|
|
self.assertEqual(_clamp_head_ratio_range((8.0, 9.0))[1], 7.0) # overly tall clamped down
|
|
phrase = _anatomy_soft_band_phrase((5.5, 6.0)).casefold()
|
|
self.assertIn("5.5", phrase)
|
|
self.assertIn("6.0", phrase)
|
|
self.assertIn("not chibi", phrase)
|
|
payload = {
|
|
"normalized_asset_profile": {
|
|
"attributes": {
|
|
"body_maturity_proportions": {
|
|
"value": "stylized head-to-body ratio of approximately 1:5.5 to 1:6 with slender limbs",
|
|
"transfer_role": "style_structure",
|
|
}
|
|
}
|
|
}
|
|
}
|
|
self.assertEqual(_source_anatomy_range_from_style_result(payload), (5.5, 6.0))
|
|
|
|
|
|
def test_validation_prompt_removes_explicit_youth_and_chibi_age_terms(self) -> None:
|
|
sanitized = _sanitize_validation_content(
|
|
"fullbody",
|
|
"moe-style juvenile face with toddler proportions, 2 heads tall, 3 heads tall, 4 heads tall",
|
|
).casefold()
|
|
self.assertNotIn("juvenile", sanitized)
|
|
self.assertNotIn("toddler", sanitized)
|
|
self.assertNotIn("2 heads tall", sanitized)
|
|
self.assertNotIn("3 heads tall", sanitized)
|
|
self.assertNotIn("4 heads tall", sanitized)
|
|
self.assertIn("neotenic", sanitized)
|
|
self.assertIn("not chibi", sanitized)
|
|
|
|
def test_provider_failure_keeps_status_and_safe_response_summary(self) -> None:
|
|
from backend.services.advanced_style_set_service import _safe_failure
|
|
|
|
failure = _safe_failure(
|
|
ImageProviderError(
|
|
"image provider returned an HTTP error",
|
|
provider_id="wy-gpt-image-2",
|
|
status_code=502,
|
|
error_type="provider_error",
|
|
details={"body_preview": '{"error":{"message":"gateway timeout"}}'},
|
|
)
|
|
)
|
|
self.assertEqual(failure["status_code"], 502)
|
|
self.assertEqual(failure["provider_id"], "wy-gpt-image-2")
|
|
self.assertIn("gateway timeout", failure["details"]["body_preview"])
|
|
def test_reference_image_502_is_eligible_for_pure_text_fallback(self) -> None:
|
|
from backend.services.advanced_style_set_service import _is_reference_image_unsupported_error
|
|
|
|
for status_code in (400, 422, 500, 502, 503, 504):
|
|
self.assertTrue(
|
|
_is_reference_image_unsupported_error(
|
|
ImageProviderError(
|
|
"image provider returned an HTTP error",
|
|
provider_id="wy-gpt-image-2",
|
|
status_code=status_code,
|
|
error_type="http_error",
|
|
)
|
|
)
|
|
)
|
|
for status_code in (401, 403, 429):
|
|
self.assertFalse(
|
|
_is_reference_image_unsupported_error(
|
|
ImageProviderError(
|
|
"image provider returned an HTTP error",
|
|
provider_id="wy-gpt-image-2",
|
|
status_code=status_code,
|
|
error_type="http_error",
|
|
)
|
|
)
|
|
)
|
|
def test_portrait_transfer_locks_face_contour_without_changing_other_scales(self) -> None:
|
|
portrait = _scale_transfer_instruction("portrait").casefold()
|
|
fullbody = _scale_transfer_instruction("fullbody").casefold()
|
|
self.assertIn("width-to-length ratio", portrait)
|
|
self.assertIn("jawline", portrait)
|
|
self.assertIn("chin silhouette", portrait)
|
|
self.assertIn("do not redesign", portrait)
|
|
self.assertNotIn("width-to-length ratio", fullbody)
|
|
|
|
def test_artist_signature_traits_survive_prompt_compilation(self) -> None:
|
|
prompt = _detailed_style_prompt(
|
|
{
|
|
"artist_signature": [
|
|
{"phrase": "dual-tone emerald-to-gold iris gradient with crisp star catchlights", "support_ratio": 0.75},
|
|
{"phrase": "generic anime style", "support_ratio": 1.0},
|
|
{"phrase": "warm rose-sepia linework matching local fill values", "support_ratio": 0.8},
|
|
],
|
|
"generation_capsules": {"detailed": {"prompt_parts": []}},
|
|
},
|
|
"fallback",
|
|
).casefold()
|
|
self.assertIn("emerald-to-gold iris gradient", prompt)
|
|
self.assertIn("rose-sepia linework", prompt)
|
|
self.assertNotIn("generic anime style", prompt)
|
|
def test_artist_signature_fallback_balances_dimensions_and_uses_source_attributes(self) -> None:
|
|
sources = [
|
|
SimpleNamespace(
|
|
source_id="source-a",
|
|
recognition_result={
|
|
"normalized_asset_profile": {
|
|
"must_preserve": [
|
|
"warm rose-sepia contour lines with tapered variable pressure",
|
|
"layered iris rings with a small diamond catchlight",
|
|
],
|
|
"attributes": {
|
|
"hair_rendering": {
|
|
"value": "grouped hair strands with segmented surface-bound highlights",
|
|
"transfer_role": "style_rendering",
|
|
}
|
|
},
|
|
},
|
|
"generation_capsules": {"detailed": {"must_preserve": ["soft violet shadows with firm two-band edges"]}},
|
|
},
|
|
),
|
|
SimpleNamespace(
|
|
source_id="source-b",
|
|
recognition_result={
|
|
"normalized_asset_profile": {
|
|
"must_preserve": [
|
|
"warm rose-sepia contour lines with tapered variable pressure",
|
|
"layered iris rings with a small diamond catchlight",
|
|
],
|
|
"attributes": {
|
|
"palette": {
|
|
"value": "restrained cream, rose and teal palette with local color separation",
|
|
"transfer_role": "style_rendering",
|
|
}
|
|
},
|
|
},
|
|
"generation_capsules": {"detailed": {"must_preserve": ["soft violet shadows with firm two-band edges"]}},
|
|
},
|
|
),
|
|
]
|
|
signature = _normalize_artist_signature(None, sources)
|
|
dimensions = {item["dimension"] for item in signature}
|
|
self.assertTrue({"eye_design", "linework", "shading", "palette", "hair_rendering"} <= dimensions)
|
|
linework = next(item for item in signature if item["dimension"] == "linework")
|
|
self.assertEqual(linework["support_ratio"], 1.0)
|
|
self.assertNotIn("generic anime style", " ".join(item["phrase"] for item in signature).casefold())
|
|
|
|
def test_artist_signature_provider_dimensions_are_preserved_in_prompt(self) -> None:
|
|
prompt = _detailed_style_prompt(
|
|
{
|
|
"artist_signature": [
|
|
{
|
|
"dimension": "palette",
|
|
"phrase": "restrained cream, rose and teal palette with local color separation",
|
|
"supporting_source_ids": ["a", "b"],
|
|
"support_ratio": 1.0,
|
|
"confidence": 0.95,
|
|
},
|
|
{
|
|
"dimension": "eye_design",
|
|
"phrase": "layered iris rings with a small diamond catchlight",
|
|
"supporting_source_ids": ["a", "b"],
|
|
"support_ratio": 1.0,
|
|
"confidence": 0.9,
|
|
},
|
|
],
|
|
"generation_capsules": {"detailed": {"prompt_parts": []}},
|
|
},
|
|
"fallback",
|
|
).casefold()
|
|
self.assertIn("artist-specific palette signature", prompt)
|
|
self.assertIn("artist-specific eye design signature", prompt)
|
|
self.assertIn("local color separation", prompt)
|
|
self.assertIn("diamond catchlight", prompt)
|
|
|
|
def test_style_kernel_preserves_high_specificity_traits_over_generic_summary(self) -> None:
|
|
prompt = _detailed_style_prompt(
|
|
{
|
|
"feature_evidence": [
|
|
{"trait": "High-key pastel color palette"},
|
|
{"trait": "Oversized layered glossy eyes"},
|
|
{"trait": "Broad white gloss streaks on hair"},
|
|
{"trait": "Thin tapered colored linework"},
|
|
{"trait": "Diffuse pink skin blush"},
|
|
{"trait": "Cool translucent cel-shadow bands"},
|
|
],
|
|
"normalized_asset_profile": {
|
|
"must_preserve": [
|
|
"Short rounded face, tiny chin, oversized eyes",
|
|
"Bright airy background with soft floating particles",
|
|
]
|
|
},
|
|
"generation_capsules": {"detailed": {"prompt_parts": []}},
|
|
},
|
|
"fallback",
|
|
).casefold()
|
|
self.assertIn("short broad rounded facial geometry", prompt)
|
|
self.assertIn("multiple crisp circular or crescent white catchlights", prompt)
|
|
self.assertIn("opaque elongated pearlescent white sheen bands", prompt)
|
|
self.assertIn("local lavender, plum, rose, or blue", prompt)
|
|
self.assertIn("peach-pink cheek blush", prompt)
|
|
self.assertNotIn("floating particles", prompt)
|
|
|
|
def test_style_negative_prompt_rewrites_mature_face_wording(self) -> None:
|
|
negative = _detailed_style_negative_prompt(
|
|
{
|
|
"generation_capsules": {
|
|
"detailed": {
|
|
"negative_parts": ["mature angular facial proportions", "photorealistic rendering"]
|
|
}
|
|
}
|
|
},
|
|
"",
|
|
).casefold()
|
|
self.assertIn("overly angular realistic facial proportions", negative)
|
|
self.assertNotIn("mature angular facial proportions", negative)
|
|
|
|
def test_scale_style_kernels_split_portrait_fullbody_and_scene(self) -> None:
|
|
payload = {
|
|
"scale_capsules": {
|
|
"portrait": {"prompt_parts": ["face details"]},
|
|
"fullbody": {"prompt_parts": ["body details"]},
|
|
"novel_scene": {"prompt_parts": ["scene details"]},
|
|
}
|
|
}
|
|
self.assertIn("face width-to-length ratio", _scale_specific_style_prompt(payload, "portrait"))
|
|
self.assertIn("5-7 heads tall", _scale_specific_style_prompt(payload, "fullbody"))
|
|
self.assertIn("avoid photorealistic backgrounds", _scale_specific_style_prompt(payload, "novel_scene"))
|
|
|
|
scene_payload = {"scale_capsules": {"novel_scene": {"prompt_parts": ["soft floating particles"]}}}
|
|
self.assertNotIn("floating particles", _scale_specific_style_prompt(scene_payload, "novel_scene"))
|
|
|
|
def test_consensus_source_analysis_removes_textual_style_anchors(self) -> None:
|
|
cleaned = _consensus_source_analysis(
|
|
{
|
|
"prompt": "style of named artist, pastel colors",
|
|
"negative_prompt": "avoid realism",
|
|
"tags": ["named artist", "anime"],
|
|
"raw_analysis": {"artist_name": "named artist", "linework": "thin colored lines"},
|
|
"generation_capsules": {
|
|
"detailed": {
|
|
"prompt_parts": ["style of named artist", "thin colored lineart"],
|
|
"must_preserve": ["thin colored lineart"],
|
|
}
|
|
},
|
|
}
|
|
)
|
|
self.assertNotIn("prompt", cleaned)
|
|
self.assertNotIn("negative_prompt", cleaned)
|
|
self.assertNotIn("tags", cleaned)
|
|
self.assertNotIn("artist_name", cleaned["raw_analysis"])
|
|
self.assertNotIn("style of named artist", cleaned["generation_capsules"]["detailed"]["prompt_parts"])
|
|
self.assertIn("thin colored lineart", cleaned["generation_capsules"]["detailed"]["prompt_parts"])
|
|
|
|
def test_artist_signature_rejects_low_support_summary_traits(self) -> None:
|
|
signature = _normalize_artist_signature(
|
|
[
|
|
{
|
|
"dimension": "hair_rendering",
|
|
"phrase": "digital illustration in a soft high-key pastel style, characterized by light blue and pale pink hues, delicate colored lineart, expressive eyes, soft shading and glossy hair",
|
|
"support_ratio": 0.25,
|
|
"confidence": 0.7,
|
|
},
|
|
{
|
|
"dimension": "linework",
|
|
"phrase": "thin clean colored lineart with tapered local hue matching",
|
|
"support_ratio": 1.0,
|
|
"confidence": 0.95,
|
|
},
|
|
],
|
|
[],
|
|
)
|
|
self.assertEqual([item["dimension"] for item in signature], ["linework"])
|
|
|
|
def test_core_evidence_requires_cross_context_support_when_declared(self) -> None:
|
|
evidence = _normalized_feature_evidence([
|
|
{
|
|
"trait": "distinct lavender shadow bands",
|
|
"support_ratio": 1.0,
|
|
"confidence": 0.95,
|
|
"cross_role_support": True,
|
|
"cross_scene_support": False,
|
|
"cross_palette_support": True,
|
|
}
|
|
])
|
|
self.assertFalse(evidence[0]["supported"])
|
|
self.assertFalse(evidence[0]["cross_context_supported"])
|
|
|
|
def test_review_layer_scores_are_normalized_separately_from_global_palette(self) -> None:
|
|
layers = _normalize_rendering_layer_scores({
|
|
"character_linework": 0.9,
|
|
"figure_coloring": 0.7,
|
|
"background_palette": 0.4,
|
|
"effect_interference": 0.2,
|
|
})
|
|
self.assertEqual(layers["character_linework"], 0.9)
|
|
self.assertEqual(layers["character_coloring"], 0.7)
|
|
self.assertEqual(layers["background_color"], 0.4)
|
|
self.assertEqual(layers["optical_effect_interference"], 0.2)
|
|
|
|
def test_regressed_case_blocks_automatic_candidate_adoption(self) -> None:
|
|
def case(key: str, score: float) -> SimpleNamespace:
|
|
return SimpleNamespace(
|
|
case_id=key,
|
|
case_key=key,
|
|
fidelity_score=score,
|
|
style_review={"status": "succeeded", "fidelity_score": score, "dimension_scores": {}},
|
|
)
|
|
current = SimpleNamespace(attempt_id="new", fidelity_score=0.82)
|
|
previous = SimpleNamespace(attempt_id="old", fidelity_score=0.80)
|
|
comparison = _style_attempt_comparison(
|
|
current_attempt=current,
|
|
current_cases=[case("portrait", 0.85), case("fullbody", 0.70), case("novel_scene", 0.91)],
|
|
previous_attempt=previous,
|
|
previous_cases=[case("portrait", 0.80), case("fullbody", 0.80), case("novel_scene", 0.80)],
|
|
)
|
|
self.assertEqual(comparison["recommendation"], "keep_previous_candidate")
|
|
self.assertIn("fullbody", comparison["scenario_regressions"])
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|