"""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"} 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}) running_workflow = workflow if workflow.status != "running": running_workflow = self.workflow_service.update_workflow(workflow_id, {"status": "running"}, ctx) completed_nodes: list[WorkflowNode] = [] prompt_context: list[str] = [] for node in active_nodes: prompt = _node_prompt(profile, node, running_workflow, prompt_context) negative_prompt = _negative_prompt(profile, node) completed = self.workflow_service.update_node( node.node_id, { "status": "completed", "prompt": prompt, "negative_prompt": negative_prompt, "metadata": { **node.metadata, "execution": { "executor": "character_workflow", "workflow_type": workflow.workflow_type, "context_prompts": len(prompt_context), }, }, }, ctx, ) completed_nodes.append(completed) prompt_context.append(prompt) completed_workflow = self.workflow_service.update_workflow( workflow_id, { "status": "completed", "current_node_id": completed_nodes[-1].node_id, "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], }, }, }, ctx, ) return { "workflow": completed_workflow.to_dict(), "nodes": [node.to_dict() for node in completed_nodes], "completed_node_ids": [node.node_id for node in completed_nodes], } 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: 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", "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", } table = fast if workflow_type == "character_fast" else gradual 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