astrbot_plugin_imagestudio/backend/services/character_workflow_service.py

202 行
8.8 KiB
Python

2026-07-06 03:00:03 +08:00
"""Deterministic execution helpers for character workflows."""
from __future__ import annotations
from typing import Any
from backend.dto.common import ApiError, ErrorCode
from backend.dto.profile_dto import CharacterProfile
from backend.dto.workflow_dto import ProfileWorkflow, WorkflowNode
from backend.services.workflow_service import WorkflowService
from core.identity import RequestContext
CHARACTER_WORKFLOW_TYPES = {"character_fast", "character_gradual", "quick_profile"}
GENERATION_NODE_TYPES = {"generation", "single_image"}
EDITABLE_PREPARATION_NODE_TYPES = {"planning", "reference_binding"}
2026-07-06 03:00:03 +08:00
class CharacterWorkflowService:
def __init__(self, workflow_service: WorkflowService):
self.workflow_service = workflow_service
def execute_workflow(self, workflow_id: str, ctx: RequestContext) -> dict[str, Any]:
detail = self.workflow_service.get_workflow(workflow_id)
workflow = detail.workflow
if workflow.workflow_type not in CHARACTER_WORKFLOW_TYPES:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"workflow is not a character workflow",
{"workflow_id": workflow_id, "workflow_type": workflow.workflow_type},
)
profile = self.workflow_service.profile_repository.get(workflow.profile_id)
if profile is None:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": workflow.profile_id})
active_nodes = [
node
for node in sorted(detail.nodes, key=lambda item: item.sort_order)
if node.branch_name == workflow.current_branch
]
if not active_nodes:
raise ApiError(ErrorCode.VALIDATION_FAILED, "workflow has no executable nodes", {"workflow_id": workflow_id})
if workflow.status == "completed":
return {
"workflow": workflow.to_dict(),
"nodes": [node.to_dict() for node in active_nodes],
"completed_node_ids": [
node.node_id for node in active_nodes if node.status in {"completed", "selected"}
],
"queued_node_ids": [node.node_id for node in active_nodes if node.status == "queued"],
"prepared_node_ids": [],
"idempotent_replay": True,
}
previous_execution = workflow.metadata.get("character_execution")
if workflow.status == "running" and isinstance(previous_execution, dict):
completed_node_ids = [node.node_id for node in active_nodes if node.status == "completed"]
queued_node_ids = [node.node_id for node in active_nodes if node.status == "queued"]
prepared_node_ids = [
node.node_id
for node in active_nodes
if node.node_type in EDITABLE_PREPARATION_NODE_TYPES and node.status == "draft"
]
return {
"workflow": workflow.to_dict(),
"nodes": [node.to_dict() for node in active_nodes],
"completed_node_ids": completed_node_ids,
"queued_node_ids": queued_node_ids,
"prepared_node_ids": prepared_node_ids,
"idempotent_replay": True,
}
2026-07-06 03:00:03 +08:00
running_workflow = workflow
if workflow.status not in {"running", "completed"}:
2026-07-06 03:00:03 +08:00
running_workflow = self.workflow_service.update_workflow(workflow_id, {"status": "running"}, ctx)
prepared_nodes: list[WorkflowNode] = []
2026-07-06 03:00:03 +08:00
prompt_context: list[str] = []
for node in active_nodes:
prompt = _node_prompt(profile, node, running_workflow, prompt_context)
negative_prompt = _negative_prompt(profile, node)
if node.node_type in GENERATION_NODE_TYPES:
target_status = "queued"
elif node.node_type in EDITABLE_PREPARATION_NODE_TYPES:
target_status = node.status
else:
target_status = "completed"
prepared = self.workflow_service.update_node(
2026-07-06 03:00:03 +08:00
node.node_id,
{
"status": target_status,
2026-07-06 03:00:03 +08:00
"prompt": prompt,
"negative_prompt": negative_prompt,
"metadata": {
**node.metadata,
"execution": {
"executor": "character_workflow",
"workflow_type": workflow.workflow_type,
"context_prompts": len(prompt_context),
"prepared_only": target_status in {"queued", "draft"},
2026-07-06 03:00:03 +08:00
},
},
},
ctx,
)
prepared_nodes.append(prepared)
2026-07-06 03:00:03 +08:00
prompt_context.append(prompt)
queued_nodes = [node for node in prepared_nodes if node.status == "queued"]
completed_nodes = [node for node in prepared_nodes if node.status == "completed"]
editable_nodes = [
node
for node in prepared_nodes
if node.node_type in EDITABLE_PREPARATION_NODE_TYPES and node.status == "draft"
]
workflow_status = "running" if queued_nodes or editable_nodes else "completed"
updated_workflow = self.workflow_service.update_workflow(
2026-07-06 03:00:03 +08:00
workflow_id,
{
"status": workflow_status,
"current_node_id": (queued_nodes[0] if queued_nodes else prepared_nodes[-1]).node_id,
2026-07-06 03:00:03 +08:00
"metadata": {
**running_workflow.metadata,
"character_execution": {
"executor": "character_workflow",
"workflow_type": workflow.workflow_type,
"completed_node_ids": [node.node_id for node in completed_nodes],
"queued_node_ids": [node.node_id for node in queued_nodes],
"prepared_node_ids": [node.node_id for node in editable_nodes],
2026-07-06 03:00:03 +08:00
},
},
},
ctx,
)
return {
"workflow": updated_workflow.to_dict(),
"nodes": [node.to_dict() for node in prepared_nodes],
2026-07-06 03:00:03 +08:00
"completed_node_ids": [node.node_id for node in completed_nodes],
"queued_node_ids": [node.node_id for node in queued_nodes],
"prepared_node_ids": [node.node_id for node in editable_nodes],
2026-07-06 03:00:03 +08:00
}
def _node_prompt(
profile: CharacterProfile,
node: WorkflowNode,
workflow: ProfileWorkflow,
prompt_context: list[str],
) -> str:
parts = [
profile.name,
profile.base_prompt,
profile.appearance_prompt,
profile.style_prompt,
_step_instruction(workflow.workflow_type, node.node_key),
node.prompt,
]
if prompt_context:
parts.append(f"consistency reference: {prompt_context[-1]}")
return ", ".join(_unique_text(parts))
def _negative_prompt(profile: CharacterProfile, node: WorkflowNode) -> str:
return ", ".join(_unique_text([profile.negative_prompt, node.negative_prompt, "low quality, blurry"]))
def _step_instruction(workflow_type: str, node_key: str) -> str:
quick_profile = {
"questionnaire": "normalized questionnaire and quick profile archive input",
"preview": "saved quick profile prompts ready for structured setting split",
}
2026-07-06 03:00:03 +08:00
fast = {
"fast_profile": "condensed character design brief",
"fast_candidates": "candidate batch, varied composition, keep identity consistent",
"fast_final": "final selected character illustration, production ready",
}
gradual = {
"profile_brief": "core identity and visual anchors",
"prompt_plan": "prompt matrix for portrait, half body, full body, and design sheet nodes",
"material_bind": "reference material binding rules for style, composition, clothing, shoes, and accessories",
2026-07-06 03:00:03 +08:00
"headshot": "headshot, face, hair, eyes, expression",
"half_body": "half body, upper outfit, posture and silhouette",
"full_body": "full body, complete outfit and proportions",
"expression_sheet": "expression sheet with reusable emotions",
"pose_sheet": "pose sheet with action variants",
"style_lock": "style consistency lock and final rendering rules",
"final_pack": "final character pack, accepted images and reusable metadata",
}
tables = {
"character_fast": fast,
"character_gradual": gradual,
"quick_profile": quick_profile,
}
table = tables.get(workflow_type, {})
2026-07-06 03:00:03 +08:00
return table.get(node_key, node_key.replace("_", " "))
def _unique_text(values: list[Any]) -> list[str]:
result: list[str] = []
seen: set[str] = set()
for value in values:
text = str(value or "").strip()
if text and text not in seen:
result.append(text)
seen.add(text)
return result