astrbot_plugin_imagestudio/backend/services/integration_service.py

142 行
5.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, _wardrobe_match_payload(payload, categories), ctx)
except Exception as exc:
self._record_failure(source, payload, exc)
raise
fallback_prompt = match.get("fallback_prompt") or _fallback_prompt(payload)
final_prompt = _final_prompt(match, 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"]),
"fallback_supplement_used": bool(match.get("fallback_supplement_used")),
"fallback_reason": match.get("fallback_reason"),
"fallback_prompt": fallback_prompt if match.get("fallback_reason") else None,
"fallback_strategy": match.get("fallback_strategy"),
"match_details": match.get("match_details"),
}
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 _wardrobe_match_payload(payload: dict[str, Any], categories: list[str]) -> dict[str, Any]:
match_payload = {"categories": categories}
for key in ("keywords", "tags", "mood", "weather", "season", "style"):
if key in payload:
match_payload[key] = payload[key]
return match_payload
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 _final_prompt(match: dict[str, Any], fallback_prompt: str) -> str:
outfit_prompt = str(match.get("outfit_prompt") or "").strip()
if match.get("fallback_supplement_used") and outfit_prompt and fallback_prompt:
return f"{outfit_prompt}, {fallback_prompt}"
return outfit_prompt or fallback_prompt
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__)