S103 衣橱匹配评分

这个提交存在于:
YokiiroBW 2026-07-06 03:43:21 +08:00
父节点 0df3546c6d
当前提交 6f34dd56d1
共有 2 个文件被更改,包括 174 次插入 和 5 次删除

查看文件

@ -14,6 +14,9 @@ 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,
@ -89,19 +92,29 @@ class WardrobeService:
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 []
categories = _normalize_categories(payload.get("categories"))
if not categories:
categories = ["top", "bottom", "dress", "shoes", "accessory"]
categories = list(DEFAULT_WARDROBE_CATEGORIES)
context = _match_context(payload)
selected: list[dict[str, Any]] = []
prompt_parts: list[str] = []
missing_categories: list[str] = []
for category in categories:
candidates = self.wardrobe_repository.list_by_profile(profile_id, str(category))
if not candidates:
missing_categories.append(str(category))
continue
item = candidates[0]
material = self.material_repository.get_material(item.material_id)
if material is None:
scored_candidates = []
for index, item in enumerate(candidates):
material = self.material_repository.get_material(item.material_id)
if material is None:
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(
{
@ -111,6 +124,12 @@ class WardrobeService:
"display_name": material.display_name,
"prompt": material.prompt,
"tags": item.tags,
"season": item.season,
"style": item.style,
"is_favorite": item.is_favorite,
"usage_count": item.usage_count,
"score": score,
"score_breakdown": breakdown,
}
)
if material.prompt:
@ -120,6 +139,15 @@ class WardrobeService:
"selected_materials": selected,
"outfit_prompt": ", ".join(prompt_parts),
"fallback_used": not selected,
"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,
@ -138,3 +166,85 @@ class WardrobeService:
def new_wardrobe_item_id() -> str:
return f"wardrobe_{uuid4().hex}"
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 _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

查看文件

@ -86,12 +86,71 @@ class WardrobeServiceTests(unittest.TestCase):
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(matched["match_details"]["matched_count"], 1)
self.assertEqual(matched["match_details"]["missing_categories"], [])
self.assertGreater(matched["selected_materials"][0]["score"], 0)
self.assertIn("freshness", matched["selected_materials"][0]["score_breakdown"])
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_match_prefers_candidate_by_tags_season_and_style(self):
self.wardrobe_service.import_material(
self.profile.profile_id,
{
"material_id": self.material.material_id,
"wardrobe_category": "top",
"tags": ["white", "formal"],
"season": "summer",
"style": "formal",
"is_favorite": True,
},
self.ctx,
)
street_material = self.material_service.create_material(
{
"category_id": self.category.category_id,
"display_name": "Blue hoodie",
"image_uri": "storage://materials/blue_hoodie.png",
"prompt": "blue hoodie, streetwear layer",
"tags": ["blue", "street", "hoodie"],
"recognition_status": "confirmed",
},
self.ctx,
)
self.wardrobe_service.import_material(
self.profile.profile_id,
{
"material_id": street_material.material_id,
"wardrobe_category": "top",
"tags": ["blue", "street", "hoodie"],
"season": "winter",
"style": "street",
},
self.ctx,
)
matched = self.wardrobe_service.match(
self.profile.profile_id,
{
"categories": ["top"],
"keywords": ["streetwear"],
"tags": ["blue", "hoodie"],
"season": "winter",
"style": "street",
},
self.ctx,
)
selected = matched["selected_materials"][0]
self.assertEqual(selected["material_id"], street_material.material_id)
self.assertEqual(selected["score_breakdown"]["season"], 12)
self.assertEqual(selected["score_breakdown"]["style"], 12)
self.assertGreaterEqual(selected["score_breakdown"]["tag_overlap"], 16)
self.assertEqual(matched["match_details"]["requested_tags"], ["blue", "hoodie", "street", "streetwear", "winter"])
def test_unconfirmed_material_cannot_be_imported(self):
pending = self.material_service.create_material(
{