astrbot_plugin_imagestudio/backend/services/integration_service.py

122 行
4.3 KiB
Python

"""External plugin integration service."""
from __future__ import annotations
from typing import Any
from uuid import uuid4
from backend.dto.common import ApiError, ErrorCode
from backend.services.wardrobe_service import WardrobeService
from core.identity import RequestContext
from database.repositories.integration_repository import IntegrationRepository
PRIVATE_COMPANION = "astrbot_plugin_private_companion"
class IntegrationService:
def __init__(
self,
wardrobe_service: WardrobeService,
integration_repository: IntegrationRepository,
):
self.wardrobe_service = wardrobe_service
self.integration_repository = integration_repository
def daily_outfit(self, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]:
source = str(payload.get("request_source") or PRIVATE_COMPANION)
if source != PRIVATE_COMPANION:
error = ApiError(
ErrorCode.INTEGRATION_TOKEN_INVALID,
"unsupported integration source",
{"request_source": source},
)
self._record_failure(source, payload, error)
raise error
profile_id = str(payload.get("profile_id") or "").strip()
if not profile_id:
error = ApiError(ErrorCode.VALIDATION_FAILED, "profile_id is required", {"field": "profile_id"})
self._record_failure(source, payload, error)
raise error
categories = payload.get("categories") or _categories_from_keywords(payload.get("keywords") or [])
try:
match = self.wardrobe_service.match(profile_id, {"categories": categories}, ctx)
except Exception as exc:
self._record_failure(source, payload, exc)
raise
fallback_prompt = _fallback_prompt(payload)
final_prompt = match["outfit_prompt"] or fallback_prompt
response = {
"matched": bool(match["selected_materials"]),
"selected_materials": match["selected_materials"],
"final_prompt": final_prompt,
"job_id": None,
"fallback_used": not bool(match["selected_materials"]),
}
self.integration_repository.record(
{
"integration_log_id": new_integration_log_id(),
"integration_name": source,
"action": "daily_outfit",
"status": "succeeded",
"request": payload,
"response": response,
}
)
return response
def list_integration_logs(
self,
integration_name: str | None = None,
*,
action: str | None = None,
status: str | None = None,
) -> list[dict[str, Any]]:
return self.integration_repository.list(
integration_name=integration_name,
action=action,
status=status,
)
def _record_failure(self, source: str, payload: dict[str, Any], exc: Exception) -> None:
self.integration_repository.record(
{
"integration_log_id": new_integration_log_id(),
"integration_name": source,
"action": "daily_outfit",
"status": "failed",
"request": payload,
"response": {"error_code": _error_code(exc)},
"error_message": str(getattr(exc, "message", None) or exc),
}
)
def new_integration_log_id() -> str:
return f"intlog_{uuid4().hex}"
def _categories_from_keywords(keywords: list[Any]) -> list[str]:
lowered = {str(keyword).lower() for keyword in keywords}
categories = []
for category in ("top", "bottom", "dress", "shoes", "accessory"):
if category in lowered:
categories.append(category)
return categories or ["top", "bottom", "dress", "shoes", "accessory"]
def _fallback_prompt(payload: dict[str, Any]) -> str:
parts = ["daily outfit"]
for key in ("mood", "weather"):
value = payload.get(key)
if value:
parts.append(str(value))
keywords = payload.get("keywords") or []
parts.extend(str(keyword) for keyword in keywords)
return ", ".join(parts)
def _error_code(exc: Exception) -> str:
code = getattr(exc, "error_code", None)
value = getattr(code, "value", None)
return str(value or code or exc.__class__.__name__)