From c3187c8a3162b7b5441eeadcf756e6b8affbe664 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 5 Jul 2026 09:59:26 +0800 Subject: [PATCH] feat: add wardrobe import and match --- backend/dto/wardrobe_dto.py | 39 ++++- backend/routes/wardrobe_routes.py | 96 +++++++++++ backend/services/wardrobe_service.py | 140 +++++++++++++++ database/migrations/0009_wardrobe_items.sql | 22 +++ database/repositories/wardrobe_repository.py | 169 +++++++++++++++++++ tests/test_wardrobe_service.py | 145 ++++++++++++++++ 6 files changed, 610 insertions(+), 1 deletion(-) create mode 100644 backend/routes/wardrobe_routes.py create mode 100644 backend/services/wardrobe_service.py create mode 100644 database/migrations/0009_wardrobe_items.sql create mode 100644 database/repositories/wardrobe_repository.py create mode 100644 tests/test_wardrobe_service.py diff --git a/backend/dto/wardrobe_dto.py b/backend/dto/wardrobe_dto.py index f15998a..088f6c2 100644 --- a/backend/dto/wardrobe_dto.py +++ b/backend/dto/wardrobe_dto.py @@ -1 +1,38 @@ -"""Wardrobe DTO placeholder.""" +"""Wardrobe DTOs.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + + +@dataclass(frozen=True) +class WardrobeItem: + wardrobe_item_id: str + profile_id: str + material_id: str + wardrobe_category: str + tags: list[str] + season: str | None + style: str | None + is_favorite: bool + usage_count: int + last_used_at: str | None + created_at: str + updated_at: str + + def to_dict(self) -> dict[str, Any]: + return { + "wardrobe_item_id": self.wardrobe_item_id, + "profile_id": self.profile_id, + "material_id": self.material_id, + "wardrobe_category": self.wardrobe_category, + "tags": self.tags, + "season": self.season, + "style": self.style, + "is_favorite": self.is_favorite, + "usage_count": self.usage_count, + "last_used_at": self.last_used_at, + "created_at": self.created_at, + "updated_at": self.updated_at, + } diff --git a/backend/routes/wardrobe_routes.py b/backend/routes/wardrobe_routes.py new file mode 100644 index 0000000..3c43eb9 --- /dev/null +++ b/backend/routes/wardrobe_routes.py @@ -0,0 +1,96 @@ +"""Wardrobe route handlers.""" + +from __future__ import annotations + +from typing import Any + +from backend.routes.common import handle_request +from backend.services.wardrobe_service import WardrobeService +from core.audit_service import AuditService +from core.identity import RequestContext +from core.security import require_authenticated, require_permission +from database.db_helper import Database, load_database_settings +from database.repositories.material_repository import MaterialRepository +from database.repositories.profile_repository import ProfileRepository +from database.repositories.wardrobe_repository import WardrobeRepository + + +def list_wardrobe_items( + ctx: RequestContext, + profile_id: str, + query: dict[str, Any] | None = None, + service: WardrobeService | None = None, +) -> dict: + wardrobe_service = service or _create_wardrobe_service() + params = query or {} + + def action() -> list[dict[str, Any]]: + require_authenticated(ctx) + return [ + item.to_dict() + for item in wardrobe_service.list_items(profile_id, _optional_str(params.get("wardrobe_category"))) + ] + + return handle_request(ctx, action) + + +def import_wardrobe_material( + ctx: RequestContext, + profile_id: str, + payload: dict[str, Any], + service: WardrobeService | None = None, +) -> dict: + wardrobe_service = service or _create_wardrobe_service() + + def action() -> dict[str, Any]: + require_permission(ctx, "can_manage_materials") + return wardrobe_service.import_material(profile_id, payload, ctx).to_dict() + + return handle_request(ctx, action) + + +def delete_wardrobe_item( + ctx: RequestContext, + profile_id: str, + wardrobe_item_id: str, + service: WardrobeService | None = None, +) -> dict: + wardrobe_service = service or _create_wardrobe_service() + + def action() -> dict[str, Any]: + require_permission(ctx, "can_manage_materials") + return wardrobe_service.delete_item(profile_id, wardrobe_item_id, ctx).to_dict() + + return handle_request(ctx, action) + + +def match_wardrobe( + ctx: RequestContext, + profile_id: str, + payload: dict[str, Any] | None = None, + service: WardrobeService | None = None, +) -> dict: + wardrobe_service = service or _create_wardrobe_service() + + def action() -> dict[str, Any]: + require_authenticated(ctx) + return wardrobe_service.match(profile_id, payload or {}, ctx) + + return handle_request(ctx, action) + + +def _create_wardrobe_service() -> WardrobeService: + database = Database(load_database_settings()) + return WardrobeService( + wardrobe_repository=WardrobeRepository(database), + profile_repository=ProfileRepository(database), + material_repository=MaterialRepository(database), + audit_service=AuditService(database), + ) + + +def _optional_str(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None diff --git a/backend/services/wardrobe_service.py b/backend/services/wardrobe_service.py new file mode 100644 index 0000000..311eebe --- /dev/null +++ b/backend/services/wardrobe_service.py @@ -0,0 +1,140 @@ +"""Wardrobe service and matching.""" + +from __future__ import annotations + +from typing import Any +from uuid import uuid4 + +from backend.dto.common import ApiError, ErrorCode +from backend.dto.wardrobe_dto import WardrobeItem +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 + + +class WardrobeService: + def __init__( + self, + wardrobe_repository: WardrobeRepository, + profile_repository: ProfileRepository, + material_repository: MaterialRepository, + audit_service: AuditService, + ): + self.wardrobe_repository = wardrobe_repository + self.profile_repository = profile_repository + self.material_repository = material_repository + self.audit_service = audit_service + + def import_material(self, profile_id: str, payload: dict[str, Any], ctx: RequestContext) -> WardrobeItem: + self._ensure_profile(profile_id) + 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}) + 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), + } + ) + 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 = None) -> list[WardrobeItem]: + self._ensure_profile(profile_id) + 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) + 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 match(self, profile_id: str, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]: + self._ensure_profile(profile_id) + categories = payload.get("categories") or [] + if not categories: + categories = ["top", "bottom", "dress", "shoes", "accessory"] + selected: list[dict[str, Any]] = [] + prompt_parts: list[str] = [] + for category in categories: + candidates = self.wardrobe_repository.list_by_profile(profile_id, str(category)) + if not candidates: + continue + item = candidates[0] + material = self.material_repository.get_material(item.material_id) + if material is None: + continue + 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, + "tags": item.tags, + } + ) + if material.prompt: + prompt_parts.append(material.prompt) + result = { + "profile_id": profile_id, + "selected_materials": selected, + "outfit_prompt": ", ".join(prompt_parts), + "fallback_used": not selected, + } + 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) -> None: + profile = self.profile_repository.get(profile_id) + if profile is None or profile.status == "deleted": + raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "profile not found", {"profile_id": profile_id}) + + +def new_wardrobe_item_id() -> str: + return f"wardrobe_{uuid4().hex}" diff --git a/database/migrations/0009_wardrobe_items.sql b/database/migrations/0009_wardrobe_items.sql new file mode 100644 index 0000000..f5394db --- /dev/null +++ b/database/migrations/0009_wardrobe_items.sql @@ -0,0 +1,22 @@ +CREATE TABLE IF NOT EXISTS wardrobe_items ( + wardrobe_item_id TEXT PRIMARY KEY, + profile_id TEXT NOT NULL, + material_id TEXT NOT NULL, + wardrobe_category TEXT NOT NULL, + tags_json TEXT, + season TEXT, + style TEXT, + is_favorite INTEGER NOT NULL DEFAULT 0, + usage_count INTEGER NOT NULL DEFAULT 0, + last_used_at TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY(profile_id) REFERENCES character_profiles(profile_id) ON DELETE CASCADE, + FOREIGN KEY(material_id) REFERENCES materials(material_id) ON DELETE CASCADE +); + +CREATE INDEX IF NOT EXISTS idx_wardrobe_profile + ON wardrobe_items(profile_id, wardrobe_category); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_wardrobe_profile_material + ON wardrobe_items(profile_id, material_id, wardrobe_category); diff --git a/database/repositories/wardrobe_repository.py b/database/repositories/wardrobe_repository.py new file mode 100644 index 0000000..529bf77 --- /dev/null +++ b/database/repositories/wardrobe_repository.py @@ -0,0 +1,169 @@ +"""Repository for wardrobe items.""" + +from __future__ import annotations + +import json +from typing import Any + +from backend.dto.wardrobe_dto import WardrobeItem +from database.db_helper import Database + + +WARDROBE_COLUMNS = """ + wardrobe_item_id, + profile_id, + material_id, + wardrobe_category, + tags_json, + season, + style, + is_favorite, + usage_count, + last_used_at, + created_at, + updated_at +""" + + +class WardrobeRepository: + def __init__(self, database: Database): + self.database = database + + @property + def placeholder(self) -> str: + return self.database._placeholder + + def create(self, payload: dict[str, Any]) -> WardrobeItem: + placeholder = self.placeholder + conn = self.database.connect() + try: + conn.execute( + f""" + INSERT INTO wardrobe_items ( + wardrobe_item_id, + profile_id, + material_id, + wardrobe_category, + tags_json, + season, + style, + is_favorite + ) VALUES ( + {placeholder}, {placeholder}, {placeholder}, {placeholder}, + {placeholder}, {placeholder}, {placeholder}, {placeholder} + ) + """, + ( + payload["wardrobe_item_id"], + payload["profile_id"], + payload["material_id"], + payload["wardrobe_category"], + _json_or_none(payload.get("tags") or []), + payload.get("season"), + payload.get("style"), + 1 if payload.get("is_favorite") else 0, + ), + ) + conn.commit() + finally: + conn.close() + item = self.get(payload["wardrobe_item_id"]) + if item is None: + raise RuntimeError("wardrobe item was inserted but could not be read back") + return item + + def get(self, wardrobe_item_id: str) -> WardrobeItem | None: + placeholder = self.placeholder + conn = self.database.connect() + try: + row = conn.execute( + f"SELECT {WARDROBE_COLUMNS} FROM wardrobe_items WHERE wardrobe_item_id = {placeholder}", + (wardrobe_item_id,), + ).fetchone() + finally: + conn.close() + return _row_to_item(row) if row else None + + def list_by_profile(self, profile_id: str, wardrobe_category: str | None = None) -> list[WardrobeItem]: + placeholder = self.placeholder + where = [f"profile_id = {placeholder}"] + params: list[Any] = [profile_id] + if wardrobe_category: + where.append(f"wardrobe_category = {placeholder}") + params.append(wardrobe_category) + conn = self.database.connect() + try: + rows = conn.execute( + f""" + SELECT {WARDROBE_COLUMNS} + FROM wardrobe_items + WHERE {" AND ".join(where)} + ORDER BY is_favorite DESC, usage_count ASC, created_at ASC + """, + tuple(params), + ).fetchall() + finally: + conn.close() + return [_row_to_item(row) for row in rows] + + def delete(self, wardrobe_item_id: str) -> WardrobeItem | None: + before = self.get(wardrobe_item_id) + if before is None: + return None + placeholder = self.placeholder + conn = self.database.connect() + try: + conn.execute(f"DELETE FROM wardrobe_items WHERE wardrobe_item_id = {placeholder}", (wardrobe_item_id,)) + conn.commit() + finally: + conn.close() + return before + + def mark_used(self, wardrobe_item_id: str) -> WardrobeItem | None: + placeholder = self.placeholder + conn = self.database.connect() + try: + conn.execute( + f""" + UPDATE wardrobe_items + SET usage_count = usage_count + 1, + last_used_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP + WHERE wardrobe_item_id = {placeholder} + """, + (wardrobe_item_id,), + ) + conn.commit() + finally: + conn.close() + return self.get(wardrobe_item_id) + + +def _row_to_item(row) -> WardrobeItem: + return WardrobeItem( + wardrobe_item_id=row["wardrobe_item_id"], + profile_id=row["profile_id"], + material_id=row["material_id"], + wardrobe_category=row["wardrobe_category"], + tags=_json_loads_list(row["tags_json"]), + season=row["season"], + style=row["style"], + is_favorite=bool(row["is_favorite"]), + usage_count=int(row["usage_count"] or 0), + last_used_at=str(row["last_used_at"]) if row["last_used_at"] else None, + created_at=str(row["created_at"]), + updated_at=str(row["updated_at"]), + ) + + +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_list(value: str | None) -> list[str]: + if not value: + return [] + loaded = json.loads(value) + return [str(item) for item in loaded] if isinstance(loaded, list) else [] diff --git a/tests/test_wardrobe_service.py b/tests/test_wardrobe_service.py new file mode 100644 index 0000000..8dc2d77 --- /dev/null +++ b/tests/test_wardrobe_service.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from backend.routes.wardrobe_routes import ( + delete_wardrobe_item, + import_wardrobe_material, + list_wardrobe_items, + match_wardrobe, +) +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.material_repository import MaterialRepository +from database.repositories.profile_repository import ProfileRepository +from database.repositories.wardrobe_repository import WardrobeRepository + + +class WardrobeServiceTests(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.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.ctx = RequestContext.from_astrbot( + username="admin", + user_id="user_001", + permissions={"can_manage_materials"}, + ) + self.profile = self.profile_service.create_profile({"name": "Nova"}, self.ctx) + self.category = self.material_service.create_category({"name": "Upper"}, self.ctx) + self.material = self.material_service.create_material( + { + "category_id": self.category.category_id, + "display_name": "White blouse", + "image_uri": "storage://materials/white_blouse.png", + "prompt": "white blouse, clean collar", + "tags": ["white", "upper"], + "recognition_status": "confirmed", + }, + self.ctx, + ) + + def tearDown(self): + self.tmp.cleanup() + + def test_import_list_match_and_delete_wardrobe_item(self): + item = self.wardrobe_service.import_material( + self.profile.profile_id, + { + "material_id": self.material.material_id, + "wardrobe_category": "top", + "tags": ["summer", "white"], + "is_favorite": True, + }, + self.ctx, + ) + self.assertTrue(item.wardrobe_item_id.startswith("wardrobe_")) + + items = self.wardrobe_service.list_items(self.profile.profile_id, "top") + self.assertEqual([entry.wardrobe_item_id for entry in items], [item.wardrobe_item_id]) + + matched = self.wardrobe_service.match( + self.profile.profile_id, + {"categories": ["top"]}, + self.ctx, + ) + self.assertFalse(matched["fallback_used"]) + self.assertEqual(matched["selected_materials"][0]["material_id"], self.material.material_id) + self.assertIn("white blouse", matched["outfit_prompt"]) + self.assertEqual(self.wardrobe_repository.get(item.wardrobe_item_id).usage_count, 1) + + deleted = self.wardrobe_service.delete_item(self.profile.profile_id, item.wardrobe_item_id, self.ctx) + self.assertEqual(deleted.wardrobe_item_id, item.wardrobe_item_id) + self.assertEqual(self.wardrobe_service.list_items(self.profile.profile_id), []) + + def test_unconfirmed_material_cannot_be_imported(self): + pending = self.material_service.create_material( + { + "category_id": self.category.category_id, + "display_name": "Pending", + "image_uri": "storage://materials/pending.png", + }, + self.ctx, + ) + + with self.assertRaises(Exception): + self.wardrobe_service.import_material( + self.profile.profile_id, + {"material_id": pending.material_id, "wardrobe_category": "top"}, + self.ctx, + ) + + def test_wardrobe_routes_wrap_responses_and_require_permissions(self): + imported = import_wardrobe_material( + self.ctx, + self.profile.profile_id, + {"material_id": self.material.material_id, "wardrobe_category": "top"}, + self.wardrobe_service, + ) + self.assertTrue(imported["ok"]) + wardrobe_item_id = imported["data"]["wardrobe_item_id"] + + listed = list_wardrobe_items(self.ctx, self.profile.profile_id, {}, self.wardrobe_service) + self.assertTrue(listed["ok"]) + self.assertEqual(len(listed["data"]), 1) + + matched = match_wardrobe(self.ctx, self.profile.profile_id, {"categories": ["top"]}, self.wardrobe_service) + self.assertTrue(matched["ok"]) + self.assertEqual(len(matched["data"]["selected_materials"]), 1) + + read_only = RequestContext.from_astrbot(username="viewer", user_id="viewer_001") + denied = import_wardrobe_material( + read_only, + self.profile.profile_id, + {"material_id": self.material.material_id, "wardrobe_category": "top"}, + self.wardrobe_service, + ) + self.assertFalse(denied["ok"]) + self.assertEqual(denied["error_code"], "FORBIDDEN") + + deleted = delete_wardrobe_item(self.ctx, self.profile.profile_id, wardrobe_item_id, self.wardrobe_service) + self.assertTrue(deleted["ok"]) + + +if __name__ == "__main__": + unittest.main()