Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 82 additions & 2 deletions backend/app/api/outfits.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from datetime import date, datetime
from typing import Annotated
from uuid import UUID
from uuid import UUID, uuid4

from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, computed_field, field_validator
Expand All @@ -12,7 +12,7 @@
from app.api.pagination import PaginationParams
from app.config import get_settings
from app.database import DbSession
from app.models.item import ClothingItem
from app.models.item import ClothingItem, ItemStatus
from app.models.outfit import (
FamilyOutfitRating,
Outfit,
Expand All @@ -38,6 +38,7 @@
AIRecommendationError,
InsufficientWardrobeError,
RecommendationService,
warmer_layer_can_come_off,
)
from app.services.studio_service import (
ItemOwnershipError,
Expand All @@ -48,6 +49,7 @@
from app.services.suggestion_cache import clear_suggestions
from app.services.weather_service import WeatherData
from app.utils.auth import get_current_user
from app.utils.clothing import covered_regions
from app.utils.rate_limit import rate_limit_by_user
from app.utils.scales import RATING_MAX, RATING_MIN
from app.utils.signed_urls import sign_optional
Expand Down Expand Up @@ -122,6 +124,27 @@ def thumbnail_url(self) -> str | None:
return sign_optional(self.thumbnail_path)


class OutfitExtraItemResponse(BaseModel):
id: UUID
type: str
subtype: str | None = None
name: str | None = None
primary_color: str | None = None
colors: list[str] = []
image_path: str | None = None
thumbnail_path: str | None = None

@computed_field
@property
def image_url(self) -> str | None:
return sign_optional(self.image_path)

@computed_field
@property
def thumbnail_url(self) -> str | None:
return sign_optional(self.thumbnail_path)


class WoreInsteadItem(BaseModel):
id: UUID
type: str
Expand Down Expand Up @@ -175,6 +198,8 @@ class OutfitResponse(BaseModel):
highlights: list[str] | None = None
weather: dict | None = None
items: list[OutfitItemResponse]
if_cooler: OutfitExtraItemResponse | None = None
if_warmer: OutfitExtraItemResponse | None = None
feedback: FeedbackSummary | None = None
family_ratings: list[FamilyRatingResponse] | None = None
family_rating_average: float | None = None
Expand Down Expand Up @@ -341,6 +366,42 @@ async def fetch_wore_instead_items_map(
return wore_instead_map


def _extra_item_response(item: ClothingItem | None) -> OutfitExtraItemResponse | None:
if item is None:
return None
return OutfitExtraItemResponse(
id=item.id,
type=item.type,
subtype=item.subtype,
name=item.name,
primary_color=item.primary_color,
colors=item.colors or [],
image_path=item.image_path,
thumbnail_path=item.thumbnail_path,
)


def _extra_is_available(item: ClothingItem) -> bool:
return item.status == ItemStatus.ready and not item.is_archived


# Stand-ins for the wardrobe's pieces: the response has no candidate pool to ask which regions
# the wardrobe can dress, so an outfit is held to covering the upper and lower body, and the
# feet when it has shoes now.
_REGION_STAND_INS = {"upper": "t-shirt", "lower": "jeans", "feet": "sneakers"}


def _completeness_type_map(outfit: Outfit) -> dict[UUID, str]:
type_map = {
outfit_item.item_id: (outfit_item.item.type or "").lower() for outfit_item in outfit.items
}
worn = covered_regions(list(type_map), type_map)
for region, item_type in _REGION_STAND_INS.items():
if region != "feet" or "feet" in worn:
type_map[uuid4()] = item_type
return type_map


def outfit_to_response(
outfit: Outfit,
wore_instead_items_map: dict[str, list[WoreInsteadItem]] | None = None,
Expand All @@ -364,6 +425,23 @@ def outfit_to_response(
)
)

# The outfit's items can change after the AI named its extras (studio edits), so an extra
# that no longer fits is hidden rather than shown wrongly.
# Likewise an extra archived or not ready since, and a warmer layer the outfit now needs.
outfit_item_ids = [outfit_item.item_id for outfit_item in outfit.items]
if_cooler = outfit.if_cooler_item
if if_cooler is not None and (
if_cooler.id in outfit_item_ids or not _extra_is_available(if_cooler)
):
if_cooler = None
if_warmer = outfit.if_warmer_item
if if_warmer is not None:
type_map = _completeness_type_map(outfit)
if not _extra_is_available(if_warmer) or not warmer_layer_can_come_off(
if_warmer.id, outfit_item_ids, type_map
):
if_warmer = None

feedback_summary = None
if outfit.feedback:
wore_instead = None
Expand Down Expand Up @@ -423,6 +501,8 @@ def outfit_to_response(
highlights=highlights,
weather=outfit.weather_data,
items=items,
if_cooler=_extra_item_response(if_cooler),
if_warmer=_extra_item_response(if_warmer),
feedback=feedback_summary,
family_ratings=family_ratings_list,
family_rating_average=family_rating_average,
Expand Down
22 changes: 22 additions & 0 deletions backend/app/models/outfit.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,21 @@ class Outfit(Base):

name: Mapped[str | None] = mapped_column(String(100), nullable=True)

# Weather-aware extras the AI may name: a wardrobe layer to add if it gets cooler, and one
# of the outfit's own layers to take off if it warms up. Both are validated before saving.
if_cooler_item_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True),
ForeignKey("clothing_items.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
if_warmer_item_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True),
ForeignKey("clothing_items.id", ondelete="SET NULL"),
nullable=True,
index=True,
)

replaces_outfit_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True),
ForeignKey("outfits.id", ondelete="SET NULL"),
Expand Down Expand Up @@ -129,6 +144,13 @@ class Outfit(Base):
source_item: Mapped[Optional["ClothingItem"]] = relationship(
"ClothingItem", foreign_keys=[source_item_id]
)
# Loaded with the outfit, so every query that serializes one includes the extras.
if_cooler_item: Mapped[Optional["ClothingItem"]] = relationship(
"ClothingItem", foreign_keys=[if_cooler_item_id], lazy="selectin"
)
if_warmer_item: Mapped[Optional["ClothingItem"]] = relationship(
"ClothingItem", foreign_keys=[if_warmer_item_id], lazy="selectin"
)
replaces: Mapped[Optional["Outfit"]] = relationship(
"Outfit",
foreign_keys=[replaces_outfit_id],
Expand Down
14 changes: 12 additions & 2 deletions backend/app/prompts/recommendation.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CONTEXT:
- Time of day: {time_of_day}
- Weather: {temperature}°C (feels like {feels_like}°C), {condition}, {precipitation_chance}% chance of rain
{temp_range_text}
{weather_details_text}
- Items are pre-ranked by suitability. Higher-numbered items are less compatible — prefer items near the top of the list.
{preferences_text}

Expand All @@ -21,6 +22,7 @@ Texture and fabric:
- Do not double the same texture (two shiny pieces, two heavy knits, two identical weaves)
- Heavier and rougher fabrics read more casual; lighter and refined fabrics read more polished
- Match fabric weight to weather — linen and cotton for warmth, wool and knit for cold
- Match footwear weight to the weather: light, breathable shoes when warm; heavier, closed shoes when cold or wet. Each footwear item lists its weight (light, medium or heavy)

Proportion and silhouette:
- Balance volume: if the top is relaxed or oversized, the bottom should be more fitted, and vice versa
Expand Down Expand Up @@ -52,13 +54,21 @@ RULES:
- Suit: ONE top + ONE suit (<<SUIT_TYPES>>) + ONE footwear; the suit replaces the bottom
- OPTIONAL: legwear (<<LEGWEAR_TYPES>>) under a skirt, dress or shorts in cool or cold weather; leave it out when it is warm, and put only thermal legwear under trousers or a jumpsuit, only when it is very cold. Legwear does not replace the bottom, the one-piece garment or footwear
- OPTIONAL: ONE bag if appropriate for the occasion
- OPTIONAL: accessories (belt, scarf, hat, watch, jewelry) that genuinely complement the outfit
- OPTIONAL: accessories (belt, scarf, watch, jewelry) that genuinely complement the outfit
- Add a hat only if it suits the outfit's style and the weather calls for it: a cap or sun hat when the UV index is 6 or higher, a warm hat (beanie, wool cap) when it is cold (about 8°C or below) or windy. Never add a hat just to complete the look
- For cold or rainy weather, add outerwear (jacket/coat) if available
- Every piece must earn its place — do not add items just to fill slots
- Do NOT pick the same item number twice
- Return item NUMBERS only

WEATHER EXTRAS (optional, per outfit):
- "if_cooler": the number of ONE extra layer (<<MID_LAYER_TYPES>>, <<OUTER_LAYER_TYPES>>) from AVAILABLE ITEMS that is NOT in this outfit, to add if it gets cooler. It must match the outfit's style and colours and must not be an item already in the outfit
- "if_warmer": the number of ONE layer that IS in this outfit (a jacket, coat, blazer, cardigan, hoodie or vest) that can come off if it warms up. The outfit must still be complete and look good without it
- Suggest "if_cooler" for every outfit whenever a fitting layer exists, so the person always knows how to cover up if the weather turns; use null only on a clearly hot day (feels like about 26°C or more all day) or when no layer fits the style
- Suggest "if_warmer" whenever the outfit has a removable layer and it could get warmer during the day; use null otherwise
- Never invent an item to fill them

Respond with valid JSON containing exactly 3 distinct outfit options. Each must be a complete look.
{{"outfits": [{{"items": [item numbers], "headline": "Short catchy outfit title (max 5 words)", "highlights": ["One short sentence each — vary your reasoning across color, texture, proportion, occasion, weather, or time of day"], "styling_tip": "One specific, actionable styling detail — do not suggest rolling up sleeves every time, vary your advice"}}, ...]}}
{{"outfits": [{{"items": [item numbers], "headline": "Short catchy outfit title (max 5 words)", "highlights": ["One short sentence each — vary your reasoning across color, texture, proportion, occasion, weather, or time of day"], "styling_tip": "One specific, actionable styling detail — do not suggest rolling up sleeves every time, vary your advice", "if_cooler": item number or null, "if_warmer": item number or null}}, ...]}}

Each outfit MUST use different key pieces (different tops, bottoms, one-piece garments or suits). Vary color palettes and energy levels. First outfit = strongest recommendation.
Loading
Loading