303 行
11 KiB
Python
303 行
11 KiB
Python
"""Prompt expansion service for generation requests."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from backend.dto.profile_dto import CharacterProfile
|
|
from backend.dto.workflow_dto import WorkflowNode
|
|
from backend.services.node_injection_template_service import (
|
|
build_node_injection_contract,
|
|
injection_payload_from_generation_request,
|
|
)
|
|
from engines.character_flow import canonical_gradual_node_key
|
|
from core.prompt_pipeline import merge_prompt_sections
|
|
|
|
|
|
class PromptExpansionService:
|
|
def expand_payload(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
sections = payload.get("sections")
|
|
if not isinstance(sections, list):
|
|
sections = [payload]
|
|
result = merge_prompt_sections(*[section for section in sections if isinstance(section, dict)])
|
|
return {
|
|
**result.to_dict(),
|
|
"source": "payload",
|
|
}
|
|
|
|
def expand_for_node(
|
|
self,
|
|
profile: CharacterProfile,
|
|
node: WorkflowNode,
|
|
payload: dict[str, Any],
|
|
) -> dict[str, Any]:
|
|
dependency_context = payload.get("dependency_context") if isinstance(payload.get("dependency_context"), dict) else {}
|
|
prompt_plan = dependency_context.get("prompt_plan") if isinstance(dependency_context.get("prompt_plan"), dict) else {}
|
|
prompt_plan_generation = (
|
|
prompt_plan.get("generation_params") if isinstance(prompt_plan.get("generation_params"), dict) else {}
|
|
)
|
|
variables = {
|
|
"profile_name": profile.name,
|
|
"node_title": node.title,
|
|
**(profile.metadata.get("prompt_variables") if isinstance(profile.metadata.get("prompt_variables"), dict) else {}),
|
|
**(payload.get("variables") if isinstance(payload.get("variables"), dict) else {}),
|
|
}
|
|
injection_payload = injection_payload_from_generation_request(payload)
|
|
dependency_injection = (
|
|
dependency_context.get("injection_template")
|
|
if isinstance(dependency_context.get("injection_template"), dict)
|
|
else {}
|
|
)
|
|
material_bindings = (
|
|
injection_payload["material_bindings"]
|
|
or dependency_context.get("material_bindings")
|
|
or dependency_injection.get("material_bindings")
|
|
or []
|
|
)
|
|
stage_inputs = (
|
|
injection_payload["stage_inputs"]
|
|
or dependency_context.get("stage_inputs")
|
|
or dependency_injection.get("stage_inputs")
|
|
or {}
|
|
)
|
|
selected_draft_image_ids = (
|
|
injection_payload["selected_draft_image_ids"]
|
|
or dependency_context.get("selected_draft_image_ids")
|
|
or dependency_injection.get("selected_draft_image_ids")
|
|
or []
|
|
)
|
|
context_prompt_parts = _unique_prompt_parts(
|
|
[
|
|
*_prompt_values(dependency_context.get("prompt_context")),
|
|
*_material_prompt_parts(material_bindings),
|
|
]
|
|
)
|
|
result = merge_prompt_sections(
|
|
{
|
|
"parts": [profile.base_prompt, profile.appearance_prompt, profile.style_prompt],
|
|
"negative_parts": [profile.negative_prompt],
|
|
"variables": variables,
|
|
},
|
|
{
|
|
"parts": [node.prompt],
|
|
"negative_parts": [node.negative_prompt],
|
|
"variables": variables,
|
|
},
|
|
{
|
|
"parts": _as_list(prompt_plan_generation.get("prompt_patch")),
|
|
"negative_parts": _as_list(prompt_plan_generation.get("negative_patch")),
|
|
"variables": variables,
|
|
},
|
|
{
|
|
"parts": context_prompt_parts,
|
|
"variables": variables,
|
|
},
|
|
{
|
|
"parts": _payload_parts(payload),
|
|
"negative_parts": _payload_negative_parts(payload),
|
|
"variables": variables,
|
|
},
|
|
)
|
|
node_injection = build_node_injection_contract(
|
|
node,
|
|
requested_kind=injection_payload["requested_kind"],
|
|
user_instruction=injection_payload["user_instruction"],
|
|
dependency_context=dependency_context,
|
|
material_bindings=material_bindings,
|
|
prompt_plan=prompt_plan or dependency_injection.get("prompt_plan") or {},
|
|
stage_inputs=stage_inputs,
|
|
selected_draft_image_ids=_string_list(selected_draft_image_ids),
|
|
ui_context=injection_payload["ui_context"],
|
|
)
|
|
prompt_result = result.to_dict()
|
|
prompt_result = _apply_character_stage_prompt_guard(prompt_result, node)
|
|
return {
|
|
**prompt_result,
|
|
"source": "profile_node",
|
|
"profile_id": profile.profile_id,
|
|
"node_id": node.node_id,
|
|
"node_injection": node_injection,
|
|
}
|
|
|
|
|
|
def _apply_character_stage_prompt_guard(result: dict[str, Any], node: WorkflowNode) -> dict[str, Any]:
|
|
if canonical_gradual_node_key(getattr(node, "node_key", None)) != "headshot":
|
|
return result
|
|
positive_guard = (
|
|
"headshot avatar portrait only, close-up head and face, head and shoulders crop, "
|
|
"face fills the frame, centered single character, one person"
|
|
)
|
|
negative_guard = (
|
|
"full body, upper body composition, lower body, standing pose, wide shot, distant character, "
|
|
"character design sheet, turnaround, multiple views, expression sheet, outfit callouts, "
|
|
"multiple characters, tiny face, full scene"
|
|
)
|
|
return {
|
|
**result,
|
|
"prompt": _join_prompt_parts(result.get("prompt"), positive_guard),
|
|
"negative_prompt": _join_prompt_parts(result.get("negative_prompt"), negative_guard),
|
|
"stage_prompt_guard": {
|
|
"stage": "headshot",
|
|
"positive": positive_guard,
|
|
"negative": negative_guard,
|
|
"aspect_ratio": "1:1",
|
|
},
|
|
}
|
|
|
|
|
|
def _join_prompt_parts(*values: Any) -> str:
|
|
result: list[str] = []
|
|
seen: set[str] = set()
|
|
for value in values:
|
|
text = str(value or "").strip()
|
|
key = text.casefold()
|
|
if text and key not in seen:
|
|
result.append(text)
|
|
seen.add(key)
|
|
return ", ".join(result)
|
|
|
|
|
|
def _payload_parts(payload: dict[str, Any]) -> list[Any]:
|
|
parts: list[Any] = []
|
|
parts.extend(_as_list(payload.get("prompt_parts")))
|
|
for key in ("prompt_patch", "extra_prompt", "style_prompt"):
|
|
value = payload.get(key)
|
|
if value:
|
|
parts.append(value)
|
|
return parts
|
|
|
|
|
|
def _payload_negative_parts(payload: dict[str, Any]) -> list[Any]:
|
|
parts: list[Any] = []
|
|
parts.extend(_as_list(payload.get("negative_parts")))
|
|
for key in ("negative_prompt", "negative_prompt_patch"):
|
|
value = payload.get(key)
|
|
if value:
|
|
parts.append(value)
|
|
return parts
|
|
|
|
|
|
def _as_list(value: Any) -> list[Any]:
|
|
if value is None:
|
|
return []
|
|
if isinstance(value, list):
|
|
return value
|
|
return [value]
|
|
|
|
|
|
def _material_prompt_parts(material_bindings: Any) -> list[str]:
|
|
if not isinstance(material_bindings, (dict, list, tuple)):
|
|
return []
|
|
|
|
structured: list[str] = []
|
|
contexts: list[str] = []
|
|
if isinstance(material_bindings, dict):
|
|
composition = material_bindings.get("composition") if isinstance(material_bindings.get("composition"), dict) else {}
|
|
composition_prompt = str(composition.get("prompt") or "").strip()
|
|
if composition_prompt:
|
|
return _split_prompt_text(composition_prompt)
|
|
structured.extend(_prompt_values(material_bindings.get("material_prompts")))
|
|
structured.extend(_prompt_values(material_bindings.get("reference_prompts")))
|
|
generation_params = material_bindings.get("generation_params")
|
|
if isinstance(generation_params, dict):
|
|
structured.extend(_prompt_values(generation_params.get("reference_prompts")))
|
|
structured.extend(_raw_material_prompt_values(material_bindings.get("active_bindings")))
|
|
structured.extend(_raw_material_prompt_values(material_bindings.get("rules")))
|
|
contexts.extend(_prompt_values(material_bindings.get("prompt_context")))
|
|
else:
|
|
structured.extend(_raw_material_prompt_values(material_bindings))
|
|
|
|
return _unique_prompt_parts([*structured, *contexts])
|
|
|
|
|
|
def _raw_material_prompt_values(value: Any) -> list[str]:
|
|
if not isinstance(value, (list, tuple)):
|
|
return []
|
|
result: list[str] = []
|
|
for item in value:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
result.extend(_prompt_values(item.get("material_prompt")))
|
|
material = item.get("material")
|
|
if isinstance(material, dict):
|
|
result.extend(_prompt_values(material.get("prompt")))
|
|
return result
|
|
|
|
|
|
def _prompt_values(value: Any) -> list[str]:
|
|
if value is None:
|
|
return []
|
|
if isinstance(value, str):
|
|
text = value.strip()
|
|
return _split_prompt_text(text) if text else []
|
|
if isinstance(value, (list, tuple)):
|
|
result: list[str] = []
|
|
for item in value:
|
|
result.extend(_prompt_values(item))
|
|
return result
|
|
if isinstance(value, dict):
|
|
for key in ("prompt", "text"):
|
|
if key in value:
|
|
return _prompt_values(value.get(key))
|
|
return []
|
|
|
|
|
|
def _unique_prompt_parts(values: list[str]) -> list[str]:
|
|
result: list[str] = []
|
|
seen: set[str] = set()
|
|
for value in values:
|
|
text = str(value or "").strip()
|
|
key = text.casefold()
|
|
if text and key not in seen:
|
|
result.append(text)
|
|
seen.add(key)
|
|
return result
|
|
|
|
|
|
def _string_list(value: Any) -> list[str]:
|
|
if isinstance(value, str):
|
|
return [value] if value.strip() else []
|
|
if not isinstance(value, (list, tuple)):
|
|
return []
|
|
return _unique_prompt_parts([str(item) for item in value if str(item or "").strip()])
|
|
|
|
|
|
def _split_prompt_text(text: str) -> list[str]:
|
|
parts: list[str] = []
|
|
current: list[str] = []
|
|
depth = 0
|
|
quote: str | None = None
|
|
escaped = False
|
|
for character in text:
|
|
if escaped:
|
|
current.append(character)
|
|
escaped = False
|
|
continue
|
|
if character == "\\":
|
|
current.append(character)
|
|
escaped = True
|
|
continue
|
|
if quote:
|
|
current.append(character)
|
|
if character == quote:
|
|
quote = None
|
|
continue
|
|
if character in {'"', "'"}:
|
|
current.append(character)
|
|
quote = character
|
|
continue
|
|
if character in "([{":
|
|
depth += 1
|
|
elif character in ")]}":
|
|
depth = max(depth - 1, 0)
|
|
if character == "," and depth == 0:
|
|
part = "".join(current).strip()
|
|
if part:
|
|
parts.append(part)
|
|
current = []
|
|
continue
|
|
current.append(character)
|
|
part = "".join(current).strip()
|
|
if part:
|
|
parts.append(part)
|
|
return parts
|