astrbot_plugin_imagestudio/backend/services/wardrobe_service.py

453 行
21 KiB
Python

"""Wardrobe service and matching."""
from __future__ import annotations
import sqlite3
from typing import Any
from uuid import uuid4
from backend.dto.common import ApiError, ErrorCode
from backend.dto.wardrobe_dto import WardrobeItem
from backend.services.composition_builder import CompositionBuilder, CompositionPlan
from backend.services.material_normalization_service import MaterialNormalizationService
from core.audit_service import AuditService
from core.identity import RequestContext
from database.repositories.material_repository import MaterialRepository
from database.repositories.profile_repository import ProfileRepository
from database.repositories.wardrobe_repository import WardrobeRepository
DEFAULT_WARDROBE_CATEGORIES = ("top", "bottom", "dress", "shoes", "accessory")
class WardrobeService:
def __init__(
self,
wardrobe_repository: WardrobeRepository,
profile_repository: ProfileRepository,
material_repository: MaterialRepository,
audit_service: AuditService,
composition_builder: CompositionBuilder | None = None,
normalization_service: MaterialNormalizationService | None = None,
):
self.wardrobe_repository = wardrobe_repository
self.profile_repository = profile_repository
self.material_repository = material_repository
self.audit_service = audit_service
self.composition_builder = composition_builder or CompositionBuilder()
self.normalization_service = normalization_service or MaterialNormalizationService()
def import_material(self, profile_id: str, payload: dict[str, Any], ctx: RequestContext) -> WardrobeItem:
self._ensure_profile(profile_id, ctx)
material_id = str(payload.get("material_id") or "").strip()
wardrobe_category = str(payload.get("wardrobe_category") or "").strip()
if not material_id:
raise ApiError(ErrorCode.VALIDATION_FAILED, "material_id is required", {"field": "material_id"})
if not wardrobe_category:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"wardrobe_category is required",
{"field": "wardrobe_category"},
)
material = self.material_repository.get_material(material_id)
if material is None or material.recognition_status != "confirmed":
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "confirmed material not found", {"material_id": material_id})
duplicate = next(
(
existing
for existing in self.wardrobe_repository.list_by_profile(profile_id, wardrobe_category)
if existing.material_id == material_id
),
None,
)
if duplicate is not None:
raise _duplicate_wardrobe_item_error(profile_id, material_id, wardrobe_category, duplicate.wardrobe_item_id)
try:
item = self.wardrobe_repository.create(
{
"wardrobe_item_id": payload.get("wardrobe_item_id") or new_wardrobe_item_id(),
"profile_id": profile_id,
"material_id": material_id,
"wardrobe_category": wardrobe_category,
"tags": payload.get("tags") or material.tags,
"season": payload.get("season"),
"style": payload.get("style"),
"is_favorite": payload.get("is_favorite", False),
}
)
except Exception as exc:
if not _is_unique_constraint_error(exc):
raise
raise _duplicate_wardrobe_item_error(profile_id, material_id, wardrobe_category) from None
self.audit_service.record(
ctx=ctx,
action="add_wardrobe_item",
target_type="wardrobe_item",
target_id=item.wardrobe_item_id,
after_snapshot=item.to_dict(),
)
return item
def list_items(
self,
profile_id: str,
wardrobe_category: str | None,
ctx: RequestContext,
) -> list[WardrobeItem]:
self._ensure_profile(profile_id, ctx)
return self.wardrobe_repository.list_by_profile(profile_id, wardrobe_category)
def delete_item(self, profile_id: str, wardrobe_item_id: str, ctx: RequestContext) -> WardrobeItem:
self._ensure_profile(profile_id, ctx)
before = self.wardrobe_repository.get(wardrobe_item_id)
if before is None or before.profile_id != profile_id:
raise ApiError(
ErrorCode.RESOURCE_NOT_FOUND,
"wardrobe item not found",
{"wardrobe_item_id": wardrobe_item_id},
)
deleted = self.wardrobe_repository.delete(wardrobe_item_id)
assert deleted is not None
self.audit_service.record(
ctx=ctx,
action="delete_wardrobe_item",
target_type="wardrobe_item",
target_id=wardrobe_item_id,
before_snapshot=deleted.to_dict(),
)
return deleted
def list_templates(self, profile_id: str, ctx: RequestContext) -> list[dict[str, Any]]:
profile = self._ensure_profile(profile_id, ctx)
templates = profile.metadata.get("wardrobe_templates") if isinstance(profile.metadata.get("wardrobe_templates"), list) else []
return [dict(item) for item in templates if isinstance(item, dict)]
def save_template(self, profile_id: str, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]:
profile = self._ensure_profile(profile_id, ctx)
name = str(payload.get("name") or "").strip()
material_ids = [str(item).strip() for item in payload.get("material_ids", []) if str(item).strip()] if isinstance(payload.get("material_ids"), list) else []
if not name or not material_ids:
raise ApiError(ErrorCode.VALIDATION_FAILED, "template name and material_ids are required", {"fields": ["name", "material_ids"]})
owned_material_ids = {item.material_id for item in self.wardrobe_repository.list_by_profile(profile_id)}
missing = [material_id for material_id in material_ids if material_id not in owned_material_ids]
if missing:
raise ApiError(ErrorCode.VALIDATION_FAILED, "template contains materials outside this wardrobe", {"material_ids": missing})
template_id = str(payload.get("template_id") or f"outfit_{uuid4().hex}")
templates = self.list_templates(profile_id, ctx)
template = {
"template_id": template_id,
"name": name,
"material_ids": list(dict.fromkeys(material_ids)),
"description": str(payload.get("description") or "").strip(),
"scene": str(payload.get("scene") or "").strip(),
"season": str(payload.get("season") or "").strip(),
"style": str(payload.get("style") or "").strip(),
"material_options": payload.get("material_options") if isinstance(payload.get("material_options"), dict) else {},
}
templates = [item for item in templates if item.get("template_id") != template_id] + [template]
updated = self.profile_repository.update(profile_id, {"metadata": {**profile.metadata, "wardrobe_templates": templates}})
if updated is None:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id})
self.audit_service.record(ctx=ctx, action="save_wardrobe_template", target_type="character_profile", target_id=profile_id, after_snapshot=template)
return template
def delete_template(self, profile_id: str, template_id: str, ctx: RequestContext) -> dict[str, Any]:
profile = self._ensure_profile(profile_id, ctx)
templates = self.list_templates(profile_id, ctx)
removed = next((item for item in templates if item.get("template_id") == template_id), None)
if removed is None:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "wardrobe template not found", {"template_id": template_id})
self.profile_repository.update(profile_id, {"metadata": {**profile.metadata, "wardrobe_templates": [item for item in templates if item.get("template_id") != template_id]}})
self.audit_service.record(ctx=ctx, action="delete_wardrobe_template", target_type="character_profile", target_id=profile_id, before_snapshot=removed)
return removed
def apply_template(self, profile_id: str, template_id: str, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]:
template = next((item for item in self.list_templates(profile_id, ctx) if item.get("template_id") == template_id), None)
if template is None:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "wardrobe template not found", {"template_id": template_id})
wardrobe = self.wardrobe_repository.list_by_profile(profile_id)
item_by_material = {item.material_id: item for item in wardrobe}
selected: list[dict[str, Any]] = []
options = template.get("material_options") if isinstance(template.get("material_options"), dict) else {}
for material_id in template.get("material_ids") or []:
item = item_by_material.get(str(material_id))
material = self.material_repository.get_material(str(material_id))
if item is None or material is None or material.recognition_status != "confirmed":
continue
selected.append({
"wardrobe_item_id": item.wardrobe_item_id,
"material_id": material.material_id,
"wardrobe_category": item.wardrobe_category,
"display_name": material.display_name,
"prompt": material.prompt,
"negative_prompt": material.negative_prompt,
"image_uri": material.image_uri,
"metadata": self.normalization_service.ensure_legacy_structures(prompt=material.prompt, negative_prompt=material.negative_prompt, tags=material.tags, metadata=material.metadata, category_hint=item.wardrobe_category),
**(options.get(material.material_id) if isinstance(options.get(material.material_id), dict) else {}),
})
result = self.composition_builder.build({
"materials": selected,
"user_prompt": str(payload.get("prompt") or template.get("scene") or "").strip(),
"prompt_budget": payload.get("prompt_budget") or 4000,
"max_reference_images": payload.get("max_reference_images") or 8,
}).to_dict()
self.audit_service.record(ctx=ctx, action="apply_wardrobe_template", target_type="character_profile", target_id=profile_id, after_snapshot={"template_id": template_id, "composition": result})
return {"profile_id": profile_id, "template": template, "composition": result}
def match(self, profile_id: str, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]:
self._ensure_profile(profile_id, ctx)
categories = _normalize_categories(payload.get("categories"))
if not categories:
categories = list(DEFAULT_WARDROBE_CATEGORIES)
context = _match_context(payload)
selected: list[dict[str, Any]] = []
missing_categories: list[str] = []
material_options = payload.get("material_options") if isinstance(payload.get("material_options"), dict) else {}
for category in categories:
candidates = self.wardrobe_repository.list_by_profile(profile_id, str(category))
if not candidates:
missing_categories.append(str(category))
continue
scored_candidates = []
for index, item in enumerate(candidates):
material = self.material_repository.get_material(item.material_id)
if material is None or material.recognition_status != "confirmed":
continue
score, breakdown = _score_candidate(item, material, context)
scored_candidates.append((score, -index, item, material, breakdown))
if not scored_candidates:
missing_categories.append(str(category))
continue
score, _order, item, material, breakdown = max(scored_candidates, key=lambda candidate: (candidate[0], candidate[1]))
self.wardrobe_repository.mark_used(item.wardrobe_item_id)
selected.append(
{
"wardrobe_item_id": item.wardrobe_item_id,
"material_id": material.material_id,
"wardrobe_category": item.wardrobe_category,
"display_name": material.display_name,
"prompt": material.prompt,
"negative_prompt": material.negative_prompt,
"image_uri": material.image_uri,
"metadata": self.normalization_service.ensure_legacy_structures(
prompt=material.prompt,
negative_prompt=material.negative_prompt,
tags=material.tags,
metadata=material.metadata,
category_hint=item.wardrobe_category,
),
"tags": item.tags,
"season": item.season,
"style": item.style,
"is_favorite": item.is_favorite,
"usage_count": item.usage_count,
"score": score,
"score_breakdown": breakdown,
**(
material_options.get(material.material_id)
if isinstance(material_options.get(material.material_id), dict)
else {}
),
}
)
fallback_strategy = _fallback_outfit_strategy(payload, categories, missing_categories, selected, context)
composition = self.composition_builder.build(
CompositionPlan(
materials=selected,
identity_prompt=str(payload.get("identity_prompt") or "").strip(),
user_prompt=fallback_strategy["prompt"] if fallback_strategy["reason"] else "",
negative_prompt=str(payload.get("negative_prompt") or "").strip(),
prompt_budget=max(int(payload.get("prompt_budget") or 4000), 256),
max_reference_images=max(int(payload.get("max_reference_images") or 8), 0),
visible_slots=[str(item).strip() for item in payload.get("visible_slots", []) if str(item).strip()] if isinstance(payload.get("visible_slots"), list) else [],
season=str(payload.get("season") or "").strip(),
scene=str(payload.get("scene") or "").strip(),
)
)
outfit_prompt = composition.prompt or fallback_strategy["prompt"]
result = {
"profile_id": profile_id,
"selected_materials": selected,
"outfit_prompt": outfit_prompt,
"fallback_used": not selected,
"fallback_supplement_used": bool(selected and missing_categories),
"fallback_reason": fallback_strategy["reason"],
"fallback_prompt": fallback_strategy["prompt"] if fallback_strategy["reason"] else None,
"fallback_strategy": fallback_strategy,
"composition": composition.to_dict(),
"match_details": {
"requested_categories": categories,
"missing_categories": missing_categories,
"matched_count": len(selected),
"keywords": sorted(context["keywords"]),
"requested_tags": sorted(context["requested_tags"]),
"season": context["season"],
"style": context["style"],
},
}
self.audit_service.record(
ctx=ctx,
action="wardrobe_match",
target_type="character_profile",
target_id=profile_id,
after_snapshot=result,
)
return result
def _ensure_profile(self, profile_id: str, ctx: RequestContext):
profile = self.profile_repository.get(profile_id)
if profile is None or profile.status == "deleted" or profile.owner_user_id != ctx.actor_id:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id})
return profile
def new_wardrobe_item_id() -> str:
return f"wardrobe_{uuid4().hex}"
def _duplicate_wardrobe_item_error(
profile_id: str,
material_id: str,
wardrobe_category: str,
wardrobe_item_id: str | None = None,
) -> ApiError:
details: dict[str, Any] = {
"profile_id": profile_id,
"material_id": material_id,
"wardrobe_category": wardrobe_category,
}
if wardrobe_item_id:
details["wardrobe_item_id"] = wardrobe_item_id
return ApiError(ErrorCode.VALIDATION_FAILED, "material already exists in wardrobe category", details)
def _is_unique_constraint_error(exc: Exception) -> bool:
if isinstance(exc, sqlite3.IntegrityError):
return True
return getattr(exc, "sqlstate", None) == "23505" or getattr(exc, "pgcode", None) == "23505"
def _normalize_categories(value: Any) -> list[str]:
if not isinstance(value, list):
return []
categories = []
for item in value:
category = str(item or "").strip()
if category and category not in categories:
categories.append(category)
return categories
def _match_context(payload: dict[str, Any]) -> dict[str, Any]:
keywords = _text_set(payload.get("keywords"))
requested_tags = _text_set(payload.get("tags")) | keywords
season = _optional_lower(payload.get("season"))
style = _optional_lower(payload.get("style"))
mood = _optional_lower(payload.get("mood"))
weather = _optional_lower(payload.get("weather"))
for value in (season, style, mood, weather):
if value:
requested_tags.add(value)
return {
"keywords": keywords,
"requested_tags": requested_tags,
"season": season,
"style": style,
"mood": mood,
"weather": weather,
}
def _score_candidate(item: WardrobeItem, material, context: dict[str, Any]) -> tuple[int, dict[str, int]]:
item_terms = _text_set(item.tags) | _text_set(material.tags) | _words(material.display_name) | _words(material.prompt)
requested_tags = context["requested_tags"]
tag_overlap = len(item_terms & requested_tags)
prompt_hits = sum(1 for keyword in context["keywords"] if keyword and keyword in _search_blob(item, material))
breakdown = {
"category": 50,
"favorite": 15 if item.is_favorite else 0,
"freshness": max(0, 10 - min(item.usage_count, 10)),
"tag_overlap": tag_overlap * 8,
"prompt_hits": prompt_hits * 3,
"season": 12 if context["season"] and _optional_lower(item.season) == context["season"] else 0,
"style": 12 if context["style"] and _optional_lower(item.style) == context["style"] else 0,
}
return sum(breakdown.values()), breakdown
def _fallback_outfit_strategy(
payload: dict[str, Any],
categories: list[str],
missing_categories: list[str],
selected: list[dict[str, Any]],
context: dict[str, Any],
) -> dict[str, Any]:
if not missing_categories and selected:
return {
"name": None,
"reason": None,
"missing_categories": [],
"prompt": "",
}
reason = "missing_categories" if selected else "no_matching_materials"
target_categories = missing_categories or categories
descriptors = [_category_fallback(category) for category in target_categories]
parts = ["daily outfit fallback"]
for key in ("style", "season", "mood", "weather"):
if context.get(key):
parts.append(str(context[key]))
keywords = payload.get("keywords") if isinstance(payload.get("keywords"), list) else []
parts.extend(str(keyword).strip() for keyword in keywords if str(keyword).strip())
if descriptors:
parts.append("with " + ", ".join(descriptors))
parts.append("cohesive colors, clean character outfit reference")
return {
"name": "random_prompt_generation",
"reason": reason,
"missing_categories": target_categories,
"prompt": ", ".join(parts),
}
def _category_fallback(category: str) -> str:
return {
"top": "coordinated top",
"bottom": "matching bottom",
"dress": "one-piece dress alternative",
"shoes": "matching shoes",
"accessory": "subtle accessory",
}.get(str(category), f"matching {category}")
def _search_blob(item: WardrobeItem, material) -> str:
return " ".join(
[
material.display_name or "",
material.prompt or "",
" ".join(item.tags),
" ".join(material.tags),
item.season or "",
item.style or "",
]
).lower()
def _text_set(value: Any) -> set[str]:
if isinstance(value, str):
values = value.split(",")
elif isinstance(value, list):
values = value
elif isinstance(value, tuple):
values = list(value)
else:
values = []
return {str(item).strip().lower() for item in values if str(item).strip()}
def _words(value: Any) -> set[str]:
return {part.strip(" ,.;:/\\_-").lower() for part in str(value or "").split() if part.strip(" ,.;:/\\_-")}
def _optional_lower(value: Any) -> str | None:
text = str(value or "").strip().lower()
return text or None