270 行
11 KiB
Python
270 行
11 KiB
Python
"""Plan generation-based cross review with distinct image-generation models."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from backend.dto.common import ApiError, ErrorCode
|
|
from backend.services.model_provider_service import ModelProviderService
|
|
|
|
|
|
GENERATION_CROSS_REVIEW_VERSION = "2026-07-15.generation-cross-review.v2"
|
|
|
|
|
|
class GenerationCrossReviewPlanner:
|
|
"""Validate routes and produce a deterministic candidate-generation plan.
|
|
|
|
This is intentionally separate from ``CrossReviewService``, which performs
|
|
VLM visual quality inspection. The planner never calls a provider; it only
|
|
proves that every secondary route resolves to a distinct image model.
|
|
"""
|
|
|
|
def __init__(self, model_providers: ModelProviderService):
|
|
self.model_providers = model_providers
|
|
|
|
def plan(
|
|
self,
|
|
*,
|
|
primary_route: str,
|
|
configured_routes: list[str] | tuple[str, ...],
|
|
source_candidate_id: str,
|
|
source_image_id: str,
|
|
selected_for_regeneration: list[str] | tuple[str, ...] | None = None,
|
|
) -> dict[str, Any]:
|
|
primary_name = _required_text(primary_route, "primary_route")
|
|
source_candidate = _required_text(source_candidate_id, "source_candidate_id")
|
|
source_image = _required_text(source_image_id, "source_image_id")
|
|
primary = self._resolve_image_route(primary_name)
|
|
|
|
ordered_names = _unique_routes(configured_routes)
|
|
if primary_name not in ordered_names:
|
|
ordered_names.insert(0, primary_name)
|
|
resolved_routes = [self._resolve_image_route(route_name) for route_name in ordered_names]
|
|
primary_identity = _route_identity(primary)
|
|
distinct: list[dict[str, Any]] = []
|
|
seen_identities = {primary_identity}
|
|
duplicate_routes: list[str] = []
|
|
for route in resolved_routes:
|
|
identity = _route_identity(route)
|
|
if route["route_name"] == primary_name:
|
|
continue
|
|
if identity in seen_identities:
|
|
duplicate_routes.append(str(route["route_name"]))
|
|
continue
|
|
seen_identities.add(identity)
|
|
distinct.append(route)
|
|
if not distinct:
|
|
raise ApiError(
|
|
ErrorCode.MODEL_CAPABILITY_UNCONFIRMED,
|
|
"cross review requires at least one different image-generation model",
|
|
{
|
|
"primary_route": primary_name,
|
|
"configured_routes": ordered_names,
|
|
"duplicate_routes": duplicate_routes,
|
|
"required_modality": "image_generation",
|
|
"required_action": "configure_distinct_generation_cross_review_routes",
|
|
},
|
|
)
|
|
|
|
regenerate_ids = {
|
|
str(item).strip()
|
|
for item in (selected_for_regeneration or [])
|
|
if str(item).strip()
|
|
}
|
|
candidates: list[dict[str, Any]] = [
|
|
{
|
|
"candidate_index": 1,
|
|
"role": "primary_preserved",
|
|
"source_candidate_id": source_candidate,
|
|
"source_image_id": source_image,
|
|
"model_route": primary_name,
|
|
"provider_id": primary["provider_id"],
|
|
"provider_name": _route_summary(primary).get("provider_name"),
|
|
"model_id": primary["model_id"],
|
|
"generate": source_candidate in regenerate_ids,
|
|
"preserve_when_not_selected": True,
|
|
}
|
|
]
|
|
for index, route in enumerate(distinct, start=2):
|
|
candidates.append(
|
|
{
|
|
"candidate_index": index,
|
|
"role": "cross_review_model",
|
|
"source_candidate_id": source_candidate,
|
|
"source_image_id": source_image,
|
|
"model_route": route["route_name"],
|
|
"provider_id": route["provider_id"],
|
|
"provider_name": _route_summary(route).get("provider_name"),
|
|
"model_id": route["model_id"],
|
|
"generate": True,
|
|
"preserve_when_not_selected": True,
|
|
}
|
|
)
|
|
return {
|
|
"schema_version": GENERATION_CROSS_REVIEW_VERSION,
|
|
"round_kind": "cross_review",
|
|
"primary_route": _route_summary(primary),
|
|
"secondary_routes": [_route_summary(item) for item in distinct],
|
|
"candidates": candidates,
|
|
"duplicate_routes_ignored": duplicate_routes,
|
|
}
|
|
|
|
def plan_followup(
|
|
self,
|
|
*,
|
|
candidates: list[dict[str, Any]] | tuple[dict[str, Any], ...],
|
|
selected_for_regeneration: list[str] | tuple[str, ...],
|
|
) -> dict[str, Any]:
|
|
"""Plan a review child round without silently replacing candidates.
|
|
|
|
Every prior slot is copied into the child round. Only explicitly
|
|
selected candidate IDs are regenerated, using the same image route as
|
|
that slot. This keeps candidate 01 as the primary-model slot and makes
|
|
later TXSC rounds directly comparable with their parent.
|
|
"""
|
|
|
|
selected = {
|
|
str(value).strip()
|
|
for value in selected_for_regeneration
|
|
if str(value).strip()
|
|
}
|
|
if not selected:
|
|
raise ApiError(
|
|
ErrorCode.VALIDATION_FAILED,
|
|
"select at least one cross-review candidate to regenerate",
|
|
{
|
|
"field": "candidate_ids",
|
|
"minimum": 1,
|
|
"required_action": "select_review_candidates",
|
|
},
|
|
)
|
|
|
|
normalized: list[dict[str, Any]] = []
|
|
known_ids: set[str] = set()
|
|
resolved_identities: dict[tuple[str, str], str] = {}
|
|
for ordinal, raw in enumerate(candidates, start=1):
|
|
candidate_id = _required_text(raw.get("candidate_id"), "candidate_id")
|
|
if candidate_id in known_ids:
|
|
raise ApiError(
|
|
ErrorCode.VALIDATION_FAILED,
|
|
"cross-review candidate list contains duplicate IDs",
|
|
{"candidate_id": candidate_id},
|
|
)
|
|
known_ids.add(candidate_id)
|
|
image_id = _required_text(raw.get("image_id"), "image_id")
|
|
route_name = _required_text(raw.get("model_route"), "model_route")
|
|
route = self._resolve_image_route(route_name)
|
|
identity = _route_identity(route)
|
|
duplicate_candidate = resolved_identities.get(identity)
|
|
if duplicate_candidate:
|
|
raise ApiError(
|
|
ErrorCode.MODEL_CAPABILITY_UNCONFIRMED,
|
|
"cross-review candidate slots must use different image-generation models",
|
|
{
|
|
"candidate_id": candidate_id,
|
|
"duplicate_candidate_id": duplicate_candidate,
|
|
"model_route": route_name,
|
|
"provider_id": route.get("provider_id"),
|
|
"model_id": route.get("model_id"),
|
|
"required_action": "configure_distinct_generation_cross_review_routes",
|
|
},
|
|
)
|
|
resolved_identities[identity] = candidate_id
|
|
try:
|
|
candidate_index = int(raw.get("candidate_index") or ordinal)
|
|
except (TypeError, ValueError) as exc:
|
|
raise ApiError(
|
|
ErrorCode.VALIDATION_FAILED,
|
|
"cross-review candidate index must be an integer",
|
|
{"candidate_id": candidate_id},
|
|
) from exc
|
|
normalized.append(
|
|
{
|
|
"candidate_index": candidate_index,
|
|
"role": "primary_preserved" if candidate_index == 1 else "cross_review_model",
|
|
"source_candidate_id": candidate_id,
|
|
"source_image_id": image_id,
|
|
"model_route": route_name,
|
|
"provider_id": route["provider_id"],
|
|
"model_id": route["model_id"],
|
|
"provider_name": _route_summary(route).get("provider_name"),
|
|
"generate": candidate_id in selected,
|
|
"preserve_when_not_selected": True,
|
|
}
|
|
)
|
|
|
|
unknown = sorted(selected - known_ids)
|
|
if unknown:
|
|
raise ApiError(
|
|
ErrorCode.VALIDATION_FAILED,
|
|
"selected cross-review candidate does not belong to the parent round",
|
|
{
|
|
"unknown_candidate_ids": unknown,
|
|
"allowed_candidate_ids": sorted(known_ids),
|
|
},
|
|
)
|
|
if len(resolved_identities) < 2:
|
|
raise ApiError(
|
|
ErrorCode.MODEL_CAPABILITY_UNCONFIRMED,
|
|
"cross review requires at least two different image-generation models",
|
|
{
|
|
"candidate_count": len(normalized),
|
|
"required_action": "configure_distinct_generation_cross_review_routes",
|
|
},
|
|
)
|
|
normalized.sort(key=lambda item: (int(item["candidate_index"]), str(item["source_candidate_id"])))
|
|
return {
|
|
"schema_version": GENERATION_CROSS_REVIEW_VERSION,
|
|
"round_kind": "cross_review",
|
|
"followup": True,
|
|
"selected_for_regeneration": sorted(selected),
|
|
"candidates": normalized,
|
|
}
|
|
|
|
def _resolve_image_route(self, route_name: str) -> dict[str, Any]:
|
|
resolved = self.model_providers.resolve_route(route_name, modality="image_generation")
|
|
if not resolved:
|
|
raise ApiError(
|
|
ErrorCode.MODEL_CAPABILITY_UNCONFIRMED,
|
|
"cross-review route is missing or is not an image-generation route",
|
|
{
|
|
"route_name": route_name,
|
|
"required_modality": "image_generation",
|
|
"required_action": "configure_image_generation_route",
|
|
},
|
|
)
|
|
return resolved
|
|
|
|
|
|
def _route_identity(route: dict[str, Any]) -> tuple[str, str]:
|
|
return (str(route.get("provider_id") or ""), str(route.get("model_id") or ""))
|
|
|
|
|
|
def _route_summary(route: dict[str, Any]) -> dict[str, Any]:
|
|
provider = route.get("provider") if isinstance(route.get("provider"), dict) else {}
|
|
return {
|
|
"route_name": route.get("route_name"),
|
|
"route_id": route.get("route_id"),
|
|
"provider_id": route.get("provider_id"),
|
|
"provider_name": provider.get("display_name"),
|
|
"provider_type": provider.get("provider_type"),
|
|
"model_id": route.get("model_id"),
|
|
"modality": route.get("modality"),
|
|
"status": "resolved",
|
|
}
|
|
|
|
|
|
def _unique_routes(values: list[str] | tuple[str, ...]) -> list[str]:
|
|
result: list[str] = []
|
|
for value in values:
|
|
text = str(value or "").strip()
|
|
if text and text not in result:
|
|
result.append(text)
|
|
return result
|
|
|
|
|
|
def _required_text(value: Any, field: str) -> str:
|
|
text = str(value or "").strip()
|
|
if not text:
|
|
raise ApiError(ErrorCode.VALIDATION_FAILED, f"{field} is required", {"field": field})
|
|
return text
|