astrbot_plugin_imagestudio/backend/services/profile_card_service.py

368 行
16 KiB
Python

"""Finalize the existing detailed workflow into an immutable profile card."""
from __future__ import annotations
from typing import Any
from uuid import uuid4
from backend.dto.common import ApiError, ErrorCode
from backend.dto.profile_card_dto import CharacterProfileCard, CharacterProfileCardAsset
from core.audit_service import AuditService
from core.identity import RequestContext
from database.repositories.image_repository import ImageRepository
from database.repositories.profile_card_repository import ProfileCardRepository
from database.repositories.profile_repository import ProfileRepository
from database.repositories.workflow_repository import WorkflowRepository
from engines.character_flow import canonical_gradual_node_key
PROFILE_CARD_ASSET_ROLES = ("avatar", "persona_image", "standing", "pv")
PROFILE_CARD_ROLE_STAGES: dict[str, frozenset[str]] = {
"avatar": frozenset({"headshot"}),
"persona_image": frozenset({"turnaround", "design_sheet"}),
"standing": frozenset({"full_body"}),
"pv": frozenset({"style_lock"}),
}
LEGACY_CARD_PREFIX = "legacy_card_"
class ProfileCardService:
def __init__(
self,
cards: ProfileCardRepository,
profiles: ProfileRepository,
workflows: WorkflowRepository,
images: ImageRepository,
audit_service: AuditService,
):
self.cards = cards
self.profiles = profiles
self.workflows = workflows
self.images = images
self.audit_service = audit_service
def finalize(self, workflow_id: str, payload: dict[str, Any], ctx: RequestContext) -> CharacterProfileCard:
idempotency_key = _required_text(payload.get("idempotency_key"), "idempotency_key")
existing = self.cards.get_by_idempotency_key(idempotency_key)
if existing is not None:
self._require_owner(existing.profile_id, ctx)
if existing.workflow_id != workflow_id:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"profile-card idempotency key belongs to another workflow",
{
"idempotency_key": idempotency_key,
"workflow_id": workflow_id,
"existing_workflow_id": existing.workflow_id,
},
)
return existing
workflow = self.workflows.get_workflow(workflow_id)
if workflow is None:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": workflow_id})
if workflow.workflow_type != "character_gradual":
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"only a detailed character workflow can create a profile card",
{"workflow_id": workflow_id, "workflow_type": workflow.workflow_type},
)
if workflow.status in {"cancelled", "archived"}:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"workflow cannot be finalized from its current status",
{"workflow_id": workflow_id, "status": workflow.status},
)
profile = self._require_owner(workflow.profile_id, ctx)
active_branch = workflow.current_branch or "main"
branch_nodes = sorted(
self.workflows.list_nodes(workflow_id, branch_name=active_branch),
key=lambda node: (node.sort_order, node.node_id),
)
profile_card_node = next(
(
node
for node in reversed(branch_nodes)
if canonical_gradual_node_key(node.node_key) == "profile_card"
),
None,
)
if profile_card_node is None:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"workflow does not contain a profile-card node",
{"workflow_id": workflow_id, "branch_name": active_branch},
)
incomplete = [
node.node_key
for node in branch_nodes
if node.sort_order < profile_card_node.sort_order
and node.status not in {"selected", "skipped", "completed"}
]
if incomplete:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"workflow stages must be completed before creating a profile card",
{"workflow_id": workflow_id, "incomplete_node_keys": incomplete},
)
persona_document = _required_text(payload.get("persona_document"), "persona_document")
assets_by_role = _normalize_assets(payload.get("assets"))
resolved_assets: list[dict[str, Any]] = []
avatar_image_id = ""
avatar_image_uri = ""
for role in PROFILE_CARD_ASSET_ROLES:
image_id = assets_by_role[role]
image = self.images.get(image_id)
if image is None or image.workflow_id != workflow_id:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"profile-card asset does not belong to this workflow",
{"asset_role": role, "image_id": image_id, "workflow_id": workflow_id},
)
if image.is_archived or _image_is_restricted(image.metadata):
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"profile-card asset is archived or restricted",
{"asset_role": role, "image_id": image_id},
)
source_node = self.workflows.get_node(image.node_id) if image.node_id else None
if (
source_node is None
or source_node.workflow_id != workflow_id
or source_node.branch_name != active_branch
):
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"profile-card asset has no valid node in the active branch",
{
"asset_role": role,
"image_id": image_id,
"node_id": image.node_id,
"active_branch": active_branch,
},
)
if not image.is_selected and source_node.selected_image_id != image.image_id:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"profile-card assets must be confirmed workflow candidates",
{"asset_role": role, "image_id": image_id, "node_key": source_node.node_key},
)
source_stage = _profile_card_stage_key(source_node.node_key)
allowed_stages = PROFILE_CARD_ROLE_STAGES[role]
if source_stage not in allowed_stages:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"profile-card asset comes from an incompatible workflow stage",
{
"asset_role": role,
"image_id": image_id,
"source_node_key": source_node.node_key,
"source_stage": source_stage,
"allowed_stages": sorted(allowed_stages),
},
)
resolved_assets.append(
{
"asset_id": f"cardasset_{uuid4().hex}",
"asset_role": role,
"image_id": image.image_id,
"image_uri": image.image_uri,
"metadata": {
"source_node_id": source_node.node_id,
"source_node_key": source_node.node_key,
"source_stage": source_stage,
"source_branch": source_node.branch_name,
"model_route": image.model_route,
"model_used": image.model_used,
},
}
)
if role == "avatar":
avatar_image_id = image.image_id
avatar_image_uri = image.image_uri
card_id = str(payload.get("card_id") or f"profilecard_{uuid4().hex}")
card = self.cards.finalize(
{
"card_id": card_id,
"profile_id": profile.profile_id,
"workflow_id": workflow.workflow_id,
"branch_name": active_branch,
"status": "sealed",
"persona_document": persona_document,
"idempotency_key": idempotency_key,
"metadata": {
**(payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}),
"schema_version": "character_profile_card_v1",
"source_workflow_status": workflow.status,
},
"assets": resolved_assets,
"avatar_image_id": avatar_image_id,
"avatar_image_uri": avatar_image_uri,
"profile_card_node_id": profile_card_node.node_id,
"history_id": f"hist_{uuid4().hex}",
"title_prefix": f"{profile.name} / 角色档案卡",
}
)
self.audit_service.record(
ctx=ctx,
action="finalize_profile_card",
target_type="character_profile_card",
target_id=card.card_id,
after_snapshot=card.to_dict(),
metadata={"workflow_id": workflow_id, "profile_id": profile.profile_id},
)
return card
def get(self, card_id: str, ctx: RequestContext) -> CharacterProfileCard:
card = self.cards.get(card_id)
if card is None and card_id.startswith(LEGACY_CARD_PREFIX):
workflow = self.workflows.get_workflow(card_id[len(LEGACY_CARD_PREFIX) :])
if workflow is not None:
self._require_owner(workflow.profile_id, ctx)
card = self._legacy_card(workflow)
if card is None:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile card not found", {"card_id": card_id})
self._require_owner(card.profile_id, ctx)
return card
def list_for_profile(self, profile_id: str, ctx: RequestContext) -> list[CharacterProfileCard]:
self._require_owner(profile_id, ctx)
cards = self.cards.list_by_profile(profile_id)
card_workflow_ids = {card.workflow_id for card in cards}
legacy_cards = [
card
for workflow in self.workflows.list_workflows(profile_id)
if workflow.workflow_id not in card_workflow_ids
if (card := self._legacy_card(workflow)) is not None
]
return [*cards, *legacy_cards]
def _legacy_card(self, workflow) -> CharacterProfileCard | None:
metadata = workflow.metadata if isinstance(workflow.metadata, dict) else {}
branch_states = metadata.get("branch_state") if isinstance(metadata.get("branch_state"), dict) else {}
branch_state = branch_states.get(workflow.current_branch or "main")
legacy_metadata = {
**metadata,
**(branch_state if isinstance(branch_state, dict) else {}),
}
image_ids = legacy_metadata.get("final_archive_image_ids")
if not isinstance(image_ids, list) or not image_ids:
return None
card_id = f"{LEGACY_CARD_PREFIX}{workflow.workflow_id}"
assets: list[CharacterProfileCardAsset] = []
used_roles: set[str] = set()
for index, image_id in enumerate(image_ids, start=1):
image = self.images.get(str(image_id))
if image is None or image.workflow_id != workflow.workflow_id:
continue
node = self.workflows.get_node(image.node_id) if image.node_id else None
canonical_key = _profile_card_stage_key(node.node_key) if node is not None else ""
preferred_role = {
"headshot": "avatar",
"full_body": "standing",
"turnaround": "persona_image",
"design_sheet": "persona_image",
"style_lock": "pv",
}.get(canonical_key)
role = preferred_role if preferred_role and preferred_role not in used_roles else f"legacy_asset_{index:02d}"
used_roles.add(role)
assets.append(
CharacterProfileCardAsset(
asset_id=f"legacy_asset_{image.image_id}",
card_id=card_id,
asset_role=role,
image_id=image.image_id,
image_uri=image.image_uri,
metadata={
"legacy": True,
"read_only": True,
"source_node_id": image.node_id,
"source_node_key": canonical_key or None,
},
created_at=image.created_at,
)
)
if not assets:
return None
profile = self.profiles.get(workflow.profile_id)
persona_document = "\n".join(
text
for text in (
getattr(profile, "description", None),
getattr(profile, "base_prompt", None),
getattr(profile, "appearance_prompt", None),
)
if str(text or "").strip()
)
timestamp = str(legacy_metadata.get("final_archive_completed_at") or workflow.updated_at)
return CharacterProfileCard(
card_id=card_id,
profile_id=workflow.profile_id,
workflow_id=workflow.workflow_id,
branch_name=workflow.current_branch or "main",
version=0,
status="legacy_read_only",
persona_document=persona_document,
idempotency_key=None,
metadata={
"legacy": True,
"read_only": True,
"schema_version": legacy_metadata.get("final_archive_schema_version"),
"history_id": legacy_metadata.get("final_archive_history_id"),
},
created_at=timestamp,
updated_at=timestamp,
assets=tuple(assets),
)
def _require_owner(self, profile_id: str, ctx: RequestContext):
profile = self.profiles.get(profile_id)
if profile is None or profile.status == "deleted":
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id})
if not (
ctx.has_permission("can_manage_all_profiles")
or ctx.has_permission("*")
or (ctx.actor_id and ctx.actor_id == profile.owner_user_id)
):
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id})
return profile
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
def _normalize_assets(value: Any) -> dict[str, str]:
if isinstance(value, dict):
result = {str(role): str(image_id or "").strip() for role, image_id in value.items()}
elif isinstance(value, list):
result = {
str(item.get("asset_role") or item.get("role") or "").strip(): str(item.get("image_id") or "").strip()
for item in value
if isinstance(item, dict)
}
else:
result = {}
missing = [role for role in PROFILE_CARD_ASSET_ROLES if not result.get(role)]
if missing:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"profile-card assets are incomplete",
{"required_roles": list(PROFILE_CARD_ASSET_ROLES), "missing_roles": missing},
)
return {role: result[role] for role in PROFILE_CARD_ASSET_ROLES}
def _profile_card_stage_key(node_key: str | None) -> str:
canonical = canonical_gradual_node_key(node_key)
return "style_lock" if canonical in {"style_lock", "hires_fix"} else canonical
def _image_is_restricted(metadata: Any) -> bool:
source = metadata if isinstance(metadata, dict) else {}
return bool(source.get("quarantined") or source.get("gallery_visibility") == "restricted")