feat: add private companion outfit integration
这个提交存在于:
父节点
c3187c8a31
当前提交
ef202f9be7
共有 5 个文件被更改,包括 383 次插入 和 0 次删除
|
|
@ -0,0 +1,62 @@
|
||||||
|
"""Integration route handlers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from backend.routes.common import handle_request
|
||||||
|
from backend.services.integration_service import IntegrationService
|
||||||
|
from backend.services.wardrobe_service import WardrobeService
|
||||||
|
from core.audit_service import AuditService
|
||||||
|
from core.identity import RequestContext
|
||||||
|
from core.security import require_authenticated
|
||||||
|
from database.db_helper import Database, load_database_settings
|
||||||
|
from database.repositories.integration_repository import IntegrationRepository
|
||||||
|
from database.repositories.material_repository import MaterialRepository
|
||||||
|
from database.repositories.profile_repository import ProfileRepository
|
||||||
|
from database.repositories.wardrobe_repository import WardrobeRepository
|
||||||
|
|
||||||
|
|
||||||
|
def private_companion_daily_outfit(
|
||||||
|
ctx: RequestContext,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
service: IntegrationService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
integration_service = service or _create_integration_service()
|
||||||
|
|
||||||
|
def action() -> dict[str, Any]:
|
||||||
|
require_authenticated(ctx)
|
||||||
|
return integration_service.daily_outfit(payload, ctx)
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def list_integration_logs(
|
||||||
|
ctx: RequestContext,
|
||||||
|
query: dict[str, Any] | None = None,
|
||||||
|
service: IntegrationService | None = None,
|
||||||
|
) -> dict:
|
||||||
|
integration_service = service or _create_integration_service()
|
||||||
|
params = query or {}
|
||||||
|
|
||||||
|
def action() -> list[dict[str, Any]]:
|
||||||
|
require_authenticated(ctx)
|
||||||
|
integration_name = str(params.get("integration_name") or "").strip() or None
|
||||||
|
return integration_service.list_integration_logs(integration_name)
|
||||||
|
|
||||||
|
return handle_request(ctx, action)
|
||||||
|
|
||||||
|
|
||||||
|
def _create_integration_service() -> IntegrationService:
|
||||||
|
database = Database(load_database_settings())
|
||||||
|
audit_service = AuditService(database)
|
||||||
|
wardrobe_service = WardrobeService(
|
||||||
|
wardrobe_repository=WardrobeRepository(database),
|
||||||
|
profile_repository=ProfileRepository(database),
|
||||||
|
material_repository=MaterialRepository(database),
|
||||||
|
audit_service=audit_service,
|
||||||
|
)
|
||||||
|
return IntegrationService(
|
||||||
|
wardrobe_service=wardrobe_service,
|
||||||
|
integration_repository=IntegrationRepository(database),
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
"""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:
|
||||||
|
raise ApiError(
|
||||||
|
ErrorCode.INTEGRATION_TOKEN_INVALID,
|
||||||
|
"unsupported integration source",
|
||||||
|
{"request_source": source},
|
||||||
|
)
|
||||||
|
profile_id = str(payload.get("profile_id") or "").strip()
|
||||||
|
if not profile_id:
|
||||||
|
raise ApiError(ErrorCode.VALIDATION_FAILED, "profile_id is required", {"field": "profile_id"})
|
||||||
|
categories = payload.get("categories") or _categories_from_keywords(payload.get("keywords") or [])
|
||||||
|
match = self.wardrobe_service.match(profile_id, {"categories": categories}, ctx)
|
||||||
|
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) -> list[dict[str, Any]]:
|
||||||
|
return self.integration_repository.list(integration_name=integration_name)
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
CREATE TABLE IF NOT EXISTS integration_logs (
|
||||||
|
integration_log_id TEXT PRIMARY KEY,
|
||||||
|
integration_name TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
request_json TEXT,
|
||||||
|
response_json TEXT,
|
||||||
|
error_message TEXT,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_integration_logs_name
|
||||||
|
ON integration_logs(integration_name, created_at);
|
||||||
|
|
@ -0,0 +1,98 @@
|
||||||
|
"""Repository for integration logs."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from database.db_helper import Database
|
||||||
|
|
||||||
|
|
||||||
|
class IntegrationRepository:
|
||||||
|
def __init__(self, database: Database):
|
||||||
|
self.database = database
|
||||||
|
|
||||||
|
@property
|
||||||
|
def placeholder(self) -> str:
|
||||||
|
return self.database._placeholder
|
||||||
|
|
||||||
|
def record(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
placeholder = self.placeholder
|
||||||
|
conn = self.database.connect()
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
f"""
|
||||||
|
INSERT INTO integration_logs (
|
||||||
|
integration_log_id,
|
||||||
|
integration_name,
|
||||||
|
action,
|
||||||
|
status,
|
||||||
|
request_json,
|
||||||
|
response_json,
|
||||||
|
error_message
|
||||||
|
) VALUES (
|
||||||
|
{placeholder}, {placeholder}, {placeholder}, {placeholder},
|
||||||
|
{placeholder}, {placeholder}, {placeholder}
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
payload["integration_log_id"],
|
||||||
|
payload["integration_name"],
|
||||||
|
payload["action"],
|
||||||
|
payload["status"],
|
||||||
|
_json_or_none(payload.get("request")),
|
||||||
|
_json_or_none(payload.get("response")),
|
||||||
|
payload.get("error_message"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return payload
|
||||||
|
|
||||||
|
def list(self, integration_name: str | None = None, limit: int = 50) -> list[dict[str, Any]]:
|
||||||
|
placeholder = self.placeholder
|
||||||
|
where = ""
|
||||||
|
params: list[Any] = []
|
||||||
|
if integration_name:
|
||||||
|
where = f"WHERE integration_name = {placeholder}"
|
||||||
|
params.append(integration_name)
|
||||||
|
conn = self.database.connect()
|
||||||
|
try:
|
||||||
|
rows = conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT integration_log_id, integration_name, action, status, request_json, response_json, error_message, created_at
|
||||||
|
FROM integration_logs
|
||||||
|
{where}
|
||||||
|
ORDER BY created_at DESC
|
||||||
|
LIMIT {placeholder}
|
||||||
|
""",
|
||||||
|
tuple(params + [limit]),
|
||||||
|
).fetchall()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"integration_log_id": row["integration_log_id"],
|
||||||
|
"integration_name": row["integration_name"],
|
||||||
|
"action": row["action"],
|
||||||
|
"status": row["status"],
|
||||||
|
"request": _json_loads(row["request_json"]),
|
||||||
|
"response": _json_loads(row["response_json"]),
|
||||||
|
"error_message": row["error_message"],
|
||||||
|
"created_at": str(row["created_at"]),
|
||||||
|
}
|
||||||
|
for row in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _json_or_none(value: Any | None) -> str | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _json_loads(value: str | None) -> dict[str, Any]:
|
||||||
|
if not value:
|
||||||
|
return {}
|
||||||
|
return json.loads(value)
|
||||||
125
tests/test_integration_service.py
普通文件
125
tests/test_integration_service.py
普通文件
|
|
@ -0,0 +1,125 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from backend.routes.integration_routes import list_integration_logs, private_companion_daily_outfit
|
||||||
|
from backend.services.integration_service import IntegrationService
|
||||||
|
from backend.services.material_service import MaterialService
|
||||||
|
from backend.services.profile_service import ProfileService
|
||||||
|
from backend.services.wardrobe_service import WardrobeService
|
||||||
|
from core.audit_service import AuditService
|
||||||
|
from core.identity import RequestContext
|
||||||
|
from database.db_helper import Database, DatabaseSettings, SqliteSettings
|
||||||
|
from database.repositories.integration_repository import IntegrationRepository
|
||||||
|
from database.repositories.material_repository import MaterialRepository
|
||||||
|
from database.repositories.profile_repository import ProfileRepository
|
||||||
|
from database.repositories.wardrobe_repository import WardrobeRepository
|
||||||
|
|
||||||
|
|
||||||
|
class IntegrationServiceTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.database = Database(
|
||||||
|
DatabaseSettings(sqlite=SqliteSettings(path=str(Path(self.tmp.name) / "imagestudio.db")))
|
||||||
|
)
|
||||||
|
self.database.initialize()
|
||||||
|
self.audit_service = AuditService(self.database)
|
||||||
|
self.profile_repository = ProfileRepository(self.database)
|
||||||
|
self.material_repository = MaterialRepository(self.database)
|
||||||
|
self.wardrobe_repository = WardrobeRepository(self.database)
|
||||||
|
self.integration_repository = IntegrationRepository(self.database)
|
||||||
|
self.profile_service = ProfileService(self.profile_repository, self.audit_service)
|
||||||
|
self.material_service = MaterialService(self.material_repository, self.audit_service)
|
||||||
|
self.wardrobe_service = WardrobeService(
|
||||||
|
self.wardrobe_repository,
|
||||||
|
self.profile_repository,
|
||||||
|
self.material_repository,
|
||||||
|
self.audit_service,
|
||||||
|
)
|
||||||
|
self.integration_service = IntegrationService(self.wardrobe_service, self.integration_repository)
|
||||||
|
self.ctx = RequestContext.from_astrbot(
|
||||||
|
username="companion",
|
||||||
|
user_id="companion_001",
|
||||||
|
permissions={"can_manage_materials"},
|
||||||
|
)
|
||||||
|
self.profile = self.profile_service.create_profile({"name": "Nova"}, self.ctx)
|
||||||
|
category = self.material_service.create_category({"name": "Upper"}, self.ctx)
|
||||||
|
material = self.material_service.create_material(
|
||||||
|
{
|
||||||
|
"category_id": category.category_id,
|
||||||
|
"display_name": "White blouse",
|
||||||
|
"image_uri": "storage://materials/white_blouse.png",
|
||||||
|
"prompt": "white blouse, clean collar",
|
||||||
|
"tags": ["white", "top"],
|
||||||
|
"recognition_status": "confirmed",
|
||||||
|
},
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
self.wardrobe_service.import_material(
|
||||||
|
self.profile.profile_id,
|
||||||
|
{"material_id": material.material_id, "wardrobe_category": "top"},
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def test_daily_outfit_uses_wardrobe_match_and_records_log(self):
|
||||||
|
response = self.integration_service.daily_outfit(
|
||||||
|
{
|
||||||
|
"profile_id": self.profile.profile_id,
|
||||||
|
"mood": "relaxed",
|
||||||
|
"weather": "sunny",
|
||||||
|
"keywords": ["top"],
|
||||||
|
"request_source": "astrbot_plugin_private_companion",
|
||||||
|
},
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(response["matched"])
|
||||||
|
self.assertIn("white blouse", response["final_prompt"])
|
||||||
|
logs = self.integration_service.list_integration_logs("astrbot_plugin_private_companion")
|
||||||
|
self.assertEqual(len(logs), 1)
|
||||||
|
self.assertEqual(logs[0]["action"], "daily_outfit")
|
||||||
|
|
||||||
|
def test_daily_outfit_fallback_when_no_materials_match(self):
|
||||||
|
response = self.integration_service.daily_outfit(
|
||||||
|
{
|
||||||
|
"profile_id": self.profile.profile_id,
|
||||||
|
"mood": "formal",
|
||||||
|
"weather": "rainy",
|
||||||
|
"categories": ["shoes"],
|
||||||
|
},
|
||||||
|
self.ctx,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(response["matched"])
|
||||||
|
self.assertTrue(response["fallback_used"])
|
||||||
|
self.assertIn("formal", response["final_prompt"])
|
||||||
|
|
||||||
|
def test_integration_routes_wrap_responses(self):
|
||||||
|
response = private_companion_daily_outfit(
|
||||||
|
self.ctx,
|
||||||
|
{"profile_id": self.profile.profile_id, "keywords": ["top"]},
|
||||||
|
self.integration_service,
|
||||||
|
)
|
||||||
|
self.assertTrue(response["ok"])
|
||||||
|
self.assertTrue(response["data"]["matched"])
|
||||||
|
|
||||||
|
logs = list_integration_logs(self.ctx, {}, self.integration_service)
|
||||||
|
self.assertTrue(logs["ok"])
|
||||||
|
self.assertEqual(len(logs["data"]), 1)
|
||||||
|
|
||||||
|
bad_source = private_companion_daily_outfit(
|
||||||
|
self.ctx,
|
||||||
|
{"profile_id": self.profile.profile_id, "request_source": "unknown_plugin"},
|
||||||
|
self.integration_service,
|
||||||
|
)
|
||||||
|
self.assertFalse(bad_source["ok"])
|
||||||
|
self.assertEqual(bad_source["error_code"], "INTEGRATION_TOKEN_INVALID")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
正在加载…
添加表格
在新工单中引用