astrbot_plugin_imagestudio/backend/services/quick_profile_service.py

222 行
8.8 KiB
Python

2026-07-05 00:20:59 +08:00
"""Quick profile draft service.
P0 uses a deterministic draft builder. A later text-model adapter can replace
the prompt expansion internals without changing the API contract.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
2026-07-05 00:20:59 +08:00
from uuid import uuid4
from backend.dto.common import ApiError, ErrorCode
2026-07-06 02:55:19 +08:00
from backend.services.profile_service import ProfileService
from core.identity import RequestContext
2026-07-05 00:20:59 +08:00
if TYPE_CHECKING:
from backend.services.workflow_service import WorkflowService
2026-07-05 00:20:59 +08:00
class QuickProfileService:
def create_draft(self, payload: dict[str, Any]) -> dict[str, Any]:
questionnaire = payload.get("questionnaire")
if not isinstance(questionnaire, dict):
raise ApiError(
ErrorCode.VALIDATION_FAILED,
2026-07-05 13:33:49 +08:00
"\u7f3a\u5c11\u5feb\u901f\u4eba\u8bbe\u95ee\u5377",
2026-07-05 00:20:59 +08:00
{"field": "questionnaire"},
)
name = str(questionnaire.get("name") or "").strip()
if not name:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
2026-07-05 13:33:49 +08:00
"\u89d2\u8272\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a",
2026-07-05 00:20:59 +08:00
{"field": "questionnaire.name"},
)
identity = _text(questionnaire.get("identity"))
gender_presentation = _text(questionnaire.get("gender_presentation"))
age_stage = _first_text(questionnaire, "age_stage", "age_group")
species = _text(questionnaire.get("species"))
2026-07-05 00:20:59 +08:00
personality = _join(questionnaire.get("personality"))
body_type = _first_text(questionnaire, "body_type", "height_build")
distinctive_features = _first_text(questionnaire, "distinctive_features", "body_features")
2026-07-05 00:20:59 +08:00
hair_color = _text(questionnaire.get("hair_color"))
hairstyle = _text(questionnaire.get("hairstyle"))
eye_color = _text(questionnaire.get("eye_color"))
style = _text(questionnaire.get("style"))
clothing = _join(questionnaire.get("clothing_keywords"))
base_parts = [name]
if identity:
base_parts.append(identity)
if gender_presentation:
base_parts.append(f"gender presentation: {gender_presentation}")
if age_stage:
base_parts.append(f"age stage: {age_stage}")
if species:
base_parts.append(f"species: {species}")
2026-07-05 00:20:59 +08:00
if personality:
base_parts.append(f"personality: {personality}")
appearance_parts = []
if body_type:
appearance_parts.append(f"body type: {body_type}")
if distinctive_features:
appearance_parts.append(f"distinctive features: {distinctive_features}")
2026-07-05 00:20:59 +08:00
if hair_color:
appearance_parts.append(f"{hair_color} hair")
if hairstyle:
appearance_parts.append(hairstyle)
if eye_color:
appearance_parts.append(f"{eye_color} eyes")
if clothing:
appearance_parts.append(clothing)
return {
"draft_id": f"draft_{uuid4().hex}",
"profile_preview": {
"name": name,
"base_prompt": ", ".join(base_parts),
"appearance_prompt": ", ".join(appearance_parts),
"style_prompt": style,
"negative_prompt": "low quality, blurry, bad anatomy, extra fingers",
},
}
2026-07-06 02:55:19 +08:00
def save_draft(
self,
payload: dict[str, Any],
profile_service: ProfileService,
ctx: RequestContext,
workflow_service: "WorkflowService | None" = None,
2026-07-06 02:55:19 +08:00
) -> dict[str, Any]:
draft = payload.get("draft") if isinstance(payload.get("draft"), dict) else {}
preview = payload.get("profile_preview") if isinstance(payload.get("profile_preview"), dict) else None
preview = preview or (draft.get("profile_preview") if isinstance(draft.get("profile_preview"), dict) else None)
if not preview:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"\u7f3a\u5c11\u5feb\u901f\u4eba\u8bbe\u9884\u89c8",
{"field": "profile_preview"},
)
name = _text(preview.get("name"))
if not name:
raise ApiError(ErrorCode.VALIDATION_FAILED, "\u89d2\u8272\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a", {"field": "name"})
draft_id = _text(payload.get("draft_id") or draft.get("draft_id"))
questionnaire = _normalize_questionnaire(
payload.get("questionnaire") if isinstance(payload.get("questionnaire"), dict) else {}
)
metadata = _build_profile_metadata(payload.get("metadata"), questionnaire, draft_id)
2026-07-06 02:55:19 +08:00
profile = profile_service.create_profile(
{
"name": name,
"description": payload.get("description"),
"base_prompt": preview.get("base_prompt"),
"appearance_prompt": preview.get("appearance_prompt"),
"style_prompt": preview.get("style_prompt"),
"negative_prompt": preview.get("negative_prompt"),
"default_model_route": payload.get("default_model_route") or preview.get("default_model_route"),
"avatar_image_uri": payload.get("avatar_image_uri") or preview.get("avatar_image_uri"),
"metadata": metadata,
2026-07-06 02:55:19 +08:00
},
ctx,
)
result = {
2026-07-06 02:55:19 +08:00
"draft_id": draft_id or None,
"profile": profile.to_dict(),
}
should_create_workflow = bool(payload.get("create_workflow", workflow_service is not None))
if should_create_workflow:
if workflow_service is None:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"\u7f3a\u5c11\u5feb\u901f\u89d2\u8272\u5de5\u4f5c\u6d41\u670d\u52a1",
{"field": "workflow_service"},
)
workflow_detail = workflow_service.create_workflow(
profile.profile_id,
{
"workflow_type": "quick_profile",
"display_name": _text(payload.get("workflow_display_name"))
or f"{name} \u5feb\u901f\u89d2\u8272\u5de5\u4f5c\u6d41",
"status": _text(payload.get("workflow_status")) or "draft",
"metadata": {
"source": "quick_profile",
"profile_id": profile.profile_id,
**({"draft_id": draft_id} if draft_id else {}),
"profile_preview": preview,
**({"questionnaire": questionnaire} if questionnaire else {}),
},
},
ctx,
)
result["workflow"] = workflow_detail.workflow.to_dict()
result["nodes"] = [node.to_dict() for node in workflow_detail.nodes]
return result
2026-07-06 02:55:19 +08:00
2026-07-05 00:20:59 +08:00
def _text(value: Any) -> str:
return str(value or "").strip()
def _join(value: Any) -> str:
if isinstance(value, list):
return ", ".join(str(item).strip() for item in value if str(item).strip())
return _text(value)
_STRUCTURED_IDENTITY_ALIASES: dict[str, tuple[str, ...]] = {
"gender_presentation": ("gender_presentation",),
"age_stage": ("age_stage", "age_group"),
"species": ("species",),
"body_type": ("body_type", "height_build"),
"distinctive_features": ("distinctive_features", "body_features"),
}
def _first_text(values: dict[str, Any], *keys: str) -> str:
for key in keys:
value = _text(values.get(key))
if value:
return value
return ""
def _normalize_questionnaire(questionnaire: dict[str, Any]) -> dict[str, Any]:
normalized = dict(questionnaire)
for canonical_key, aliases in _STRUCTURED_IDENTITY_ALIASES.items():
if _text(normalized.get(canonical_key)):
continue
value = _first_text(questionnaire, *aliases)
if value:
normalized[canonical_key] = value
return normalized
def _build_profile_metadata(metadata: Any, questionnaire: dict[str, Any], draft_id: str) -> dict[str, Any]:
result = dict(metadata) if isinstance(metadata, dict) else {}
existing_questionnaire = result.get("questionnaire")
if isinstance(existing_questionnaire, dict):
# User-provided nested metadata takes precedence while retaining all
# normalized questionnaire fields and arbitrary custom keys.
merged_questionnaire = {
**questionnaire,
**_normalize_questionnaire(existing_questionnaire),
}
else:
merged_questionnaire = dict(questionnaire)
if merged_questionnaire:
result["questionnaire"] = merged_questionnaire
for canonical_key in _STRUCTURED_IDENTITY_ALIASES:
value = _text(questionnaire.get(canonical_key))
if value:
result.setdefault(canonical_key, value)
result["source"] = "quick_profile"
if draft_id:
result["draft_id"] = draft_id
return result