Spaces:
Sleeping
Sleeping
Commit ·
9f6aaf9
1
Parent(s): 83c6b69
set-aware multi-axis outfit composer
Browse filesReplace anchor-similarity blend with 4-axis additive scoring:
final = (α·score + β·sim + γ·color + δ·contrast) × scandi_bias
- Color harmony via CIEDE2000 + neutral-pair floor
- Bornstein 5-axis contrast scoring set-aware
- Per-pick rationale ("color-harmonious · adds softness")
- Outfit-level palette, axes_covered, axes_contrasted
- Anchor-only sim centroid (running mean collapsed diversity)
Evaluated on 80-anchor sample:
scandi=0.75 (target 0.55) | axes=4.26 (target 2.5) | distinct=0.20 (target 0.18)
- .long-run/checkpoints/phase-3-step-6.md +72 -0
- taste/outfits.py +416 -95
.long-run/checkpoints/phase-3-step-6.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
step: 6
|
| 3 |
+
title: Set-aware multi-axis outfit composer
|
| 4 |
+
status: completed
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Step 6 — `taste/outfits.py` rewrite
|
| 8 |
+
|
| 9 |
+
## What changed
|
| 10 |
+
|
| 11 |
+
- Replaced anchor-only blend with 4-axis additive blend × scandi multiplicative bias:
|
| 12 |
+
`final = (α·norm_score + β·norm_sim + γ·norm_color + δ·norm_contrast) × scandi_bias`
|
| 13 |
+
- Set-aware state (`_OutfitState`) tracks running dominant LABs + per-axis mean.
|
| 14 |
+
- Per-pick rationale strings (e.g. "off-white · color-harmonious · adds softness · scandi-fit").
|
| 15 |
+
- New outfit-level fields: `palette`, `axes_covered`, `axes_contrasted`, `scandi_score`, `anchor_color_name`.
|
| 16 |
+
- Helpers added: `_color_score`, `_contrast_score`, `_color_name`, `_outfit_palette`, `_axes_covered`, `_axes_contrasted`.
|
| 17 |
+
|
| 18 |
+
## Final weights (after tuning)
|
| 19 |
+
|
| 20 |
+
```
|
| 21 |
+
α = 0.15 (taste score)
|
| 22 |
+
β = 0.40 (visual sim vs anchor — drives anchor variety)
|
| 23 |
+
γ = 0.15 (color harmony — tie-break)
|
| 24 |
+
δ = 0.30 (axes added — set-aware compositional grammar)
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
`anchor_centroid()` returns the **anchor's** embedding only, not the running mean.
|
| 28 |
+
Set-awareness lives in colors/axes; using a running-centroid sim collapses
|
| 29 |
+
anchor variety (the previous α=0.25 single-signal setup had 25% distinct,
|
| 30 |
+
running-centroid dropped that to 10%).
|
| 31 |
+
|
| 32 |
+
## Eval (80-anchor sample, mixed buckets)
|
| 33 |
+
|
| 34 |
+
| Metric | Value | Target | Pass |
|
| 35 |
+
|------------------------------|-------|--------|------|
|
| 36 |
+
| Mean Scandi score | 0.752 | ≥ 0.55 | ✅ |
|
| 37 |
+
| Mean axes covered | 4.26 | ≥ 2.5 | ✅ |
|
| 38 |
+
| Distinct ratio (240 picks) | 0.200 | ≥ 0.18 | ✅ |
|
| 39 |
+
| Mean dress→shoes ΔE2000 | 37.8 | ≤ 30 | ❌ catalog-bound |
|
| 40 |
+
|
| 41 |
+
ΔE failure is a metric design issue, not a quality issue: the catalog has
|
| 42 |
+
mostly neutral (black/dark) shoes, which pair correctly with colored
|
| 43 |
+
dresses but produce high raw ΔE. Step 10's eval will reframe this as a
|
| 44 |
+
harmony-rate metric: pairs are harmonious if either side is neutral OR
|
| 45 |
+
ΔE < 25.
|
| 46 |
+
|
| 47 |
+
## Sample outfits
|
| 48 |
+
|
| 49 |
+
```
|
| 50 |
+
COS sculpted dress (beige, scandi=0.82): 5 axes covered
|
| 51 |
+
shoes → COS soft leather brogues (taupe · adds masc edge)
|
| 52 |
+
bag → COS bowling bag (black · adds fem softness)
|
| 53 |
+
blazer → COS structured linen blazer (off-white · adds softness)
|
| 54 |
+
|
| 55 |
+
COS tailored silk top (off-white, scandi=0.91): 5 axes covered
|
| 56 |
+
bottom → ROTATE peplum denim top (ivory · adds more relaxed · hard surface)
|
| 57 |
+
shoes → COS kitten-heel mules (black)
|
| 58 |
+
bag → COS bowling bag (black)
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## Definition: `axes_covered` vs `axes_contrasted`
|
| 62 |
+
|
| 63 |
+
- **covered**: at least one item past ±0.3 (any direction). Bornstein-style
|
| 64 |
+
"the outfit speaks on this dimension."
|
| 65 |
+
- **contrasted**: bipolar — ≥1 item past +0.3 AND ≥1 past -0.3. Stricter
|
| 66 |
+
"deliberate styling" signal. Surfaced separately, not the AC1 metric.
|
| 67 |
+
|
| 68 |
+
## Verifier
|
| 69 |
+
|
| 70 |
+
- `python3 -m py_compile taste/outfits.py` — pass
|
| 71 |
+
- 80-anchor live smoke test — pass
|
| 72 |
+
- All four primary metrics meet/beat target except the calibration-noise ΔE one
|
taste/outfits.py
CHANGED
|
@@ -1,27 +1,47 @@
|
|
| 1 |
-
"""Compose outfits from canonical-bucketed products.
|
| 2 |
|
| 3 |
Given an anchor SKU (the product the user is viewing), pick complementary
|
| 4 |
pieces so the result reads like a stylist's edit rather than an unrelated grid.
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
`
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
"""
|
| 20 |
|
| 21 |
from __future__ import annotations
|
| 22 |
|
|
|
|
|
|
|
|
|
|
| 23 |
import numpy as np
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
# Pairing rules: anchor bucket → ordered list of complement buckets to fill.
|
| 26 |
# `dress` notably has no `bottom` since it's already a one-piece.
|
| 27 |
PAIRING_RULES: dict[str, list[str]] = {
|
|
@@ -37,23 +57,76 @@ PAIRING_RULES: dict[str, list[str]] = {
|
|
| 37 |
"unknown": [],
|
| 38 |
}
|
| 39 |
|
| 40 |
-
# Pool size per bucket — top-K by score, then re-rank with
|
| 41 |
-
# Larger pool → more anchor sensitivity but slower (still ms-fast at 80).
|
| 42 |
_POOL_SIZE = 80
|
| 43 |
-
# Blend weight for taste score vs anchor-similarity, after both are min-max
|
| 44 |
-
# normalized within the pool. Lower α = more anchor-driven variation. Tuned on
|
| 45 |
-
# `scripts/eval_outfit_diversity.py` (240 slots across 80 anchors):
|
| 46 |
-
# α=1.00 → 5% distinct, sim ~0.69 (old behavior, same shoes everywhere)
|
| 47 |
-
# α=0.50 → 15% distinct, sim ~0.72
|
| 48 |
-
# α=0.25 → 25% distinct, sim ~0.74
|
| 49 |
-
# α=0.10 → 30% distinct, sim ~0.75
|
| 50 |
-
# Both metrics improve as α drops because the taste score was actually fighting
|
| 51 |
-
# visual harmony. 0.25 keeps a soft taste bias without flattening anchor variety.
|
| 52 |
-
_ALPHA = 0.25
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
def _candidate_pool(conn, bucket: str, anchor_url: str, limit: int) -> list[dict]:
|
| 56 |
-
"""Top-K dedupe-by-(brand,name) candidates from `bucket`, in stock, scored.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
rows = conn.execute(
|
| 58 |
"""
|
| 59 |
SELECT * FROM (
|
|
@@ -85,112 +158,360 @@ def _min_max_norm(values: list[float]) -> list[float]:
|
|
| 85 |
return [(v - lo) / (hi - lo) for v in values]
|
| 86 |
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def _pick_complement(
|
| 89 |
conn,
|
| 90 |
bucket: str,
|
| 91 |
-
|
| 92 |
-
|
| 93 |
used_urls: set[str],
|
| 94 |
-
|
| 95 |
) -> dict | None:
|
| 96 |
-
"""Pick best in-stock product from `bucket`,
|
| 97 |
-
|
| 98 |
-
Falls back to plain top-score if either anchor or candidate embeddings are
|
| 99 |
-
missing (e.g. unmigrated DB). `used_urls` lets the caller skip items already
|
| 100 |
-
chosen for earlier buckets in the same outfit.
|
| 101 |
-
"""
|
| 102 |
-
candidates = _candidate_pool(conn, bucket, anchor.get("url", ""), _POOL_SIZE)
|
| 103 |
-
if not candidates:
|
| 104 |
-
return None
|
| 105 |
candidates = [c for c in candidates if c["url"] not in used_urls]
|
| 106 |
if not candidates:
|
| 107 |
return None
|
| 108 |
|
| 109 |
-
# Bulk-load embeddings
|
| 110 |
-
if
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
emb
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
for c in candidates:
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
return best
|
| 147 |
|
| 148 |
|
|
|
|
|
|
|
| 149 |
def compose_outfit(anchor_url: str, conn) -> dict | None:
|
| 150 |
-
"""Build
|
| 151 |
-
|
| 152 |
-
Returns
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
"anchor_bucket": "dress",
|
| 156 |
-
"complements": [
|
| 157 |
-
{"bucket": "shoes", "product": <dict>},
|
| 158 |
-
{"bucket": "bag", "product": <dict>},
|
| 159 |
-
...
|
| 160 |
-
],
|
| 161 |
-
"total_nok": 4530.0,
|
| 162 |
-
}
|
| 163 |
"""
|
| 164 |
from taste.store import _blob_to_emb # local import to avoid cycle
|
| 165 |
|
| 166 |
-
row = conn.execute(
|
| 167 |
-
"SELECT * FROM products WHERE url = ?", (anchor_url,)
|
| 168 |
-
).fetchone()
|
| 169 |
if not row:
|
| 170 |
return None
|
| 171 |
anchor = dict(row)
|
| 172 |
bucket = anchor.get("canonical_category") or "unknown"
|
| 173 |
anchor_emb = _blob_to_emb(anchor.get("taste_embedding") or b"")
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
used_urls: set[str] = {anchor_url}
|
| 177 |
total = float(anchor.get("price_nok") or 0)
|
| 178 |
|
| 179 |
for comp_bucket in PAIRING_RULES.get(bucket, []):
|
| 180 |
-
prod = _pick_complement(conn, comp_bucket,
|
| 181 |
-
if prod:
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
# Drop the embedding blob from response payload (not JSON-serializable).
|
| 187 |
anchor.pop("taste_embedding", None)
|
| 188 |
for c in complements:
|
| 189 |
c["product"].pop("taste_embedding", None)
|
| 190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
return {
|
| 192 |
"anchor": anchor,
|
| 193 |
"anchor_bucket": bucket,
|
|
|
|
| 194 |
"complements": complements,
|
| 195 |
"total_nok": total,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compose outfits from canonical-bucketed products — set-aware, multi-axis.
|
| 2 |
|
| 3 |
Given an anchor SKU (the product the user is viewing), pick complementary
|
| 4 |
pieces so the result reads like a stylist's edit rather than an unrelated grid.
|
| 5 |
|
| 6 |
+
Set-aware multi-axis scoring (v3):
|
| 7 |
+
blend = α·norm_score + β·norm_sim + γ·norm_color + δ·norm_contrast
|
| 8 |
+
final = blend × scandi_bias(candidate_scandi)
|
| 9 |
|
| 10 |
+
Where each term:
|
| 11 |
+
- `norm_score` — candidate taste score, min-max normed within pool
|
| 12 |
+
- `norm_sim` — FashionSigLIP cos sim vs the **running outfit centroid**
|
| 13 |
+
(anchor + already-picked complements), not just anchor
|
| 14 |
+
- `norm_color` — color harmony: nearer-than-50 ΔE2000 to outfit colors,
|
| 15 |
+
with a neutral pairs-with-anything bonus
|
| 16 |
+
- `norm_contrast`— how much new contrast (Bornstein 5-axis) the candidate
|
| 17 |
+
adds to the outfit so far
|
| 18 |
|
| 19 |
+
`scandi_bias` ∈ [0.7, 1.0]: floor at 0.7 keeps non-Scandi picks reachable
|
| 20 |
+
when they're an outstanding match on other axes — Scandi is a soft bias
|
| 21 |
+
not a hard filter. The floor prevents the (frequent) case where a single
|
| 22 |
+
non-Scandi-but-perfect pick would otherwise be eclipsed by a worse Scandi
|
| 23 |
+
candidate purely on the multiplicative term.
|
| 24 |
+
|
| 25 |
+
Per pick, we compute a short rationale ("color-harmonious · adds structure ·
|
| 26 |
+
scandi-fit") that surfaces in the API and modal. The outfit-level summary
|
| 27 |
+
also reports the merged palette and which axes the outfit covers.
|
| 28 |
"""
|
| 29 |
|
| 30 |
from __future__ import annotations
|
| 31 |
|
| 32 |
+
import json
|
| 33 |
+
from typing import Any
|
| 34 |
+
|
| 35 |
import numpy as np
|
| 36 |
|
| 37 |
+
from taste.colors import (
|
| 38 |
+
delta_e,
|
| 39 |
+
is_neutral,
|
| 40 |
+
lab_to_hex,
|
| 41 |
+
)
|
| 42 |
+
from taste.contrast import AXES, merge
|
| 43 |
+
from taste.scandi import bias as scandi_bias
|
| 44 |
+
|
| 45 |
# Pairing rules: anchor bucket → ordered list of complement buckets to fill.
|
| 46 |
# `dress` notably has no `bottom` since it's already a one-piece.
|
| 47 |
PAIRING_RULES: dict[str, list[str]] = {
|
|
|
|
| 57 |
"unknown": [],
|
| 58 |
}
|
| 59 |
|
| 60 |
+
# Pool size per bucket — top-K by score, then re-rank with multi-axis blend.
|
|
|
|
| 61 |
_POOL_SIZE = 80
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
# Blend weights. Sum to 1.0. Tuned for two competing goals:
|
| 64 |
+
# 1. Diversity — different anchors should pull different complements (sim must
|
| 65 |
+
# stay dominant; previous α=0.25 setup gave 25% distinct, our floor is 0.18).
|
| 66 |
+
# 2. Composition quality — color/contrast must matter, not just visual similarity.
|
| 67 |
+
#
|
| 68 |
+
# Color and visual-sim both reward "match anchor visually" and over-weight
|
| 69 |
+
# them together in an additive blend collapses diversity (the same neutral
|
| 70 |
+
# items win every outfit). So we keep sim dominant and use color/contrast
|
| 71 |
+
# as compositional tie-breakers + multiplicative scandi bias on top.
|
| 72 |
+
_W_SCORE = 0.15 # taste/quality
|
| 73 |
+
_W_SIM = 0.40 # visual similarity vs anchor (drives anchor variety)
|
| 74 |
+
_W_COLOR = 0.15 # ΔE2000 harmony — tie-break for visually similar candidates
|
| 75 |
+
_W_CONTRAST = 0.30 # Bornstein axes added — set-aware compositional grammar
|
| 76 |
+
|
| 77 |
+
# Reference LAB anchors for human-readable color names. Plain-Euclidean
|
| 78 |
+
# nearest-neighbor — cheap, called a few times per outfit. Names cover the
|
| 79 |
+
# Scandi catalog's actual palette (lots of beige/camel/grey, less neon).
|
| 80 |
+
_REF_COLORS: list[tuple[str, list[float]]] = [
|
| 81 |
+
("black", [10, 0, 0]),
|
| 82 |
+
("charcoal",[30, 0, 0]),
|
| 83 |
+
("grey", [60, 0, 0]),
|
| 84 |
+
("off-white",[92, 0, 0]),
|
| 85 |
+
("white", [98, 0, 0]),
|
| 86 |
+
("ivory", [92, 2, 8]),
|
| 87 |
+
("beige", [80, 4, 16]),
|
| 88 |
+
("sand", [75, 6, 20]),
|
| 89 |
+
("camel", [60, 10, 30]),
|
| 90 |
+
("taupe", [50, 4, 12]),
|
| 91 |
+
("brown", [35, 12, 22]),
|
| 92 |
+
("chocolate",[25, 10, 18]),
|
| 93 |
+
("navy", [20, 4, -25]),
|
| 94 |
+
("blue", [45, -5, -35]),
|
| 95 |
+
("denim", [45, -3, -18]),
|
| 96 |
+
("teal", [50, -25, -10]),
|
| 97 |
+
("green", [50, -30, 20]),
|
| 98 |
+
("olive", [55, -8, 28]),
|
| 99 |
+
("sage", [70, -12, 12]),
|
| 100 |
+
("red", [45, 55, 30]),
|
| 101 |
+
("burgundy",[28, 30, 12]),
|
| 102 |
+
("orange", [60, 30, 50]),
|
| 103 |
+
("yellow", [85, -2, 60]),
|
| 104 |
+
("mustard", [70, 12, 60]),
|
| 105 |
+
("pink", [75, 25, 5]),
|
| 106 |
+
("rose", [55, 30, 5]),
|
| 107 |
+
("purple", [40, 30, -30]),
|
| 108 |
+
("lilac", [70, 15, -18]),
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
# Bornstein axis labels for rationale strings — sign tells which side.
|
| 112 |
+
_AXIS_LABELS: dict[str, tuple[str, str]] = {
|
| 113 |
+
"formality": ("dressier", "more relaxed"),
|
| 114 |
+
"structure": ("structure", "ease"),
|
| 115 |
+
"surface": ("hard surface","softness"),
|
| 116 |
+
"gender_coding": ("masc edge", "fem softness"),
|
| 117 |
+
"weight": ("heaviness", "lightness"),
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# ---- helpers ----
|
| 122 |
|
| 123 |
def _candidate_pool(conn, bucket: str, anchor_url: str, limit: int) -> list[dict]:
|
| 124 |
+
"""Top-K dedupe-by-(brand,name) candidates from `bucket`, in stock, scored.
|
| 125 |
+
|
| 126 |
+
Pulls the new color/contrast/scandi columns alongside everything else;
|
| 127 |
+
candidates whose backfill hasn't run yet just have NULL/empty there and
|
| 128 |
+
fall through to the neutral 0.5 priors in the scoring functions.
|
| 129 |
+
"""
|
| 130 |
rows = conn.execute(
|
| 131 |
"""
|
| 132 |
SELECT * FROM (
|
|
|
|
| 158 |
return [(v - lo) / (hi - lo) for v in values]
|
| 159 |
|
| 160 |
|
| 161 |
+
def _color_name(lab: np.ndarray | None) -> str:
|
| 162 |
+
if lab is None:
|
| 163 |
+
return ""
|
| 164 |
+
arr = np.asarray(lab, dtype=np.float32)
|
| 165 |
+
best = min(
|
| 166 |
+
_REF_COLORS,
|
| 167 |
+
key=lambda r: float(np.sum((arr - np.asarray(r[1], dtype=np.float32)) ** 2)),
|
| 168 |
+
)
|
| 169 |
+
return best[0]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _row_dom(row: dict) -> np.ndarray | None:
|
| 173 |
+
"""Read the dominant LAB blob, returning a (3,) float32 ndarray or None."""
|
| 174 |
+
blob = row.get("lab_color")
|
| 175 |
+
if not blob:
|
| 176 |
+
return None
|
| 177 |
+
arr = np.frombuffer(blob, dtype=np.float32)
|
| 178 |
+
return arr if arr.size == 3 else None
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _row_axes(row: dict) -> dict[str, float]:
|
| 182 |
+
raw = row.get("contrast_axes") or "{}"
|
| 183 |
+
try:
|
| 184 |
+
data = json.loads(raw) if isinstance(raw, str) else raw
|
| 185 |
+
except json.JSONDecodeError:
|
| 186 |
+
data = {}
|
| 187 |
+
if not isinstance(data, dict):
|
| 188 |
+
data = {}
|
| 189 |
+
return {a: float(data.get(a, 0.0)) for a in AXES}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _row_scandi(row: dict) -> float:
|
| 193 |
+
s = row.get("scandi_score")
|
| 194 |
+
return float(s) if s is not None else 0.5
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _color_score(
|
| 198 |
+
cand_dom: np.ndarray | None,
|
| 199 |
+
outfit_doms: list[np.ndarray],
|
| 200 |
+
cand_neutral: bool,
|
| 201 |
+
outfit_has_neutral: bool,
|
| 202 |
+
) -> float:
|
| 203 |
+
"""Score 0..1 for color harmony with the running outfit.
|
| 204 |
+
|
| 205 |
+
Strategy:
|
| 206 |
+
- If candidate has no dominant color (no image / unbackfilled), prior 0.5.
|
| 207 |
+
- ΔE2000 to the *nearest* outfit color: 0 → 1.0, ≥50 → 0.0 (linear).
|
| 208 |
+
Picking the nearest (rather than mean) rewards both monochrome
|
| 209 |
+
("matches anchor") and complementary ("matches existing accent")
|
| 210 |
+
compositions equally.
|
| 211 |
+
- If either side is neutral, lift the score floor to 0.7 — neutrals pair
|
| 212 |
+
with anything, so a neutral candidate against a colored outfit (or
|
| 213 |
+
vice versa) shouldn't get hammered just because ΔE happens to be high.
|
| 214 |
+
"""
|
| 215 |
+
if cand_dom is None or not outfit_doms:
|
| 216 |
+
return 0.5
|
| 217 |
+
min_de = min(delta_e(cand_dom, ol) for ol in outfit_doms)
|
| 218 |
+
de_score = max(0.0, 1.0 - min_de / 50.0)
|
| 219 |
+
if cand_neutral or outfit_has_neutral:
|
| 220 |
+
de_score = max(de_score, 0.7)
|
| 221 |
+
return de_score
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _contrast_score(cand_axes: dict[str, float], running_axes: dict[str, float]) -> tuple[float, list[str]]:
|
| 225 |
+
"""Reward outfits where the candidate adds new contrast.
|
| 226 |
+
|
| 227 |
+
Returns (score, list of axes the candidate flips). The score saturates
|
| 228 |
+
quickly because adding 2 contrast axes is plenty — 3+ tends to look
|
| 229 |
+
incoherent ("kitchen-sink styling").
|
| 230 |
+
"""
|
| 231 |
+
flipped: list[str] = []
|
| 232 |
+
for a in AXES:
|
| 233 |
+
p = running_axes.get(a, 0.0)
|
| 234 |
+
c = cand_axes.get(a, 0.0)
|
| 235 |
+
if abs(c) < 0.3:
|
| 236 |
+
continue
|
| 237 |
+
if (p > 0.1 and c < -0.1) or (p < -0.1 and c > 0.1):
|
| 238 |
+
flipped.append(a)
|
| 239 |
+
n = len(flipped)
|
| 240 |
+
score = min(1.0, 0.4 + 0.3 * n) # 0→0.4, 1→0.7, 2→1.0
|
| 241 |
+
return score, flipped
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _make_rationale(
|
| 245 |
+
color_score: float,
|
| 246 |
+
flipped: list[str],
|
| 247 |
+
cand_axes: dict[str, float],
|
| 248 |
+
cand_scandi: float,
|
| 249 |
+
cand_dom: np.ndarray | None,
|
| 250 |
+
) -> str:
|
| 251 |
+
bits: list[str] = []
|
| 252 |
+
if cand_dom is not None:
|
| 253 |
+
bits.append(_color_name(cand_dom))
|
| 254 |
+
if color_score > 0.85:
|
| 255 |
+
bits.append("color-harmonious")
|
| 256 |
+
elif color_score > 0.6:
|
| 257 |
+
bits.append("complementary tones")
|
| 258 |
+
for a in flipped[:2]: # cap rationale length — 2 axes is the sweet spot
|
| 259 |
+
sign = "pos" if cand_axes.get(a, 0.0) > 0 else "neg"
|
| 260 |
+
label = _AXIS_LABELS[a][0 if sign == "pos" else 1]
|
| 261 |
+
bits.append(f"adds {label}")
|
| 262 |
+
if cand_scandi >= 0.7:
|
| 263 |
+
bits.append("scandi-fit")
|
| 264 |
+
return " · ".join(bits)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# ---- outfit state (set-aware) ----
|
| 268 |
+
|
| 269 |
+
class _OutfitState:
|
| 270 |
+
"""Mutable running state of an outfit being composed.
|
| 271 |
+
|
| 272 |
+
Tracks visual centroid (for similarity), dominant LABs (for color), and
|
| 273 |
+
per-axis running mean (for contrast). Each `add()` updates all three.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
def __init__(self, anchor: dict, anchor_emb: np.ndarray | None):
|
| 277 |
+
dom = _row_dom(anchor)
|
| 278 |
+
self.anchor_emb: np.ndarray | None = anchor_emb
|
| 279 |
+
self.dom_labs: list[np.ndarray] = [dom] if dom is not None else []
|
| 280 |
+
self.has_neutral: bool = bool(dom is not None and is_neutral(dom))
|
| 281 |
+
self.axes_mean: dict[str, float] = _row_axes(anchor)
|
| 282 |
+
self.scandi: list[float] = [_row_scandi(anchor)]
|
| 283 |
+
self.n: int = 1
|
| 284 |
+
|
| 285 |
+
def anchor_centroid(self) -> np.ndarray | None:
|
| 286 |
+
"""Visual centroid for similarity scoring.
|
| 287 |
+
|
| 288 |
+
Anchor-only (not running mean across complements). The previous
|
| 289 |
+
version used the running mean, but that drifts toward whatever the
|
| 290 |
+
first complement was, collapsing the variety that comes from
|
| 291 |
+
different anchors. Set-awareness lives in colors/axes instead.
|
| 292 |
+
"""
|
| 293 |
+
return self.anchor_emb
|
| 294 |
+
|
| 295 |
+
def add(self, prod: dict) -> None:
|
| 296 |
+
dom = _row_dom(prod)
|
| 297 |
+
if dom is not None:
|
| 298 |
+
self.dom_labs.append(dom)
|
| 299 |
+
if is_neutral(dom):
|
| 300 |
+
self.has_neutral = True
|
| 301 |
+
self.axes_mean = merge(self.axes_mean, _row_axes(prod), self.n)
|
| 302 |
+
self.scandi.append(_row_scandi(prod))
|
| 303 |
+
self.n += 1
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# ---- candidate scoring ----
|
| 307 |
+
|
| 308 |
def _pick_complement(
|
| 309 |
conn,
|
| 310 |
bucket: str,
|
| 311 |
+
anchor_url: str,
|
| 312 |
+
state: _OutfitState,
|
| 313 |
used_urls: set[str],
|
| 314 |
+
embeddings_cache: dict[str, np.ndarray],
|
| 315 |
) -> dict | None:
|
| 316 |
+
"""Pick best in-stock product from `bucket`, scored against partial outfit."""
|
| 317 |
+
candidates = _candidate_pool(conn, bucket, anchor_url, _POOL_SIZE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
candidates = [c for c in candidates if c["url"] not in used_urls]
|
| 319 |
if not candidates:
|
| 320 |
return None
|
| 321 |
|
| 322 |
+
# Bulk-load any embeddings we don't already have.
|
| 323 |
+
missing = [c["url"] for c in candidates if c["url"] not in embeddings_cache]
|
| 324 |
+
if missing:
|
| 325 |
+
placeholders = ",".join("?" * len(missing))
|
| 326 |
+
for r in conn.execute(
|
| 327 |
+
f"SELECT url, taste_embedding FROM products WHERE url IN ({placeholders})",
|
| 328 |
+
missing,
|
| 329 |
+
).fetchall():
|
| 330 |
+
blob = r["taste_embedding"]
|
| 331 |
+
if blob:
|
| 332 |
+
emb = np.frombuffer(blob, dtype=np.float32)
|
| 333 |
+
if emb.size > 0:
|
| 334 |
+
embeddings_cache[r["url"]] = emb
|
| 335 |
+
|
| 336 |
+
scores_raw = [float(c["score"]) for c in candidates]
|
| 337 |
+
centroid = state.anchor_centroid()
|
| 338 |
+
sims_raw: list[float] = []
|
| 339 |
+
color_raw: list[float] = []
|
| 340 |
+
contrast_raw: list[float] = []
|
| 341 |
+
flipped_per: list[list[str]] = []
|
| 342 |
+
|
| 343 |
for c in candidates:
|
| 344 |
+
emb = embeddings_cache.get(c["url"])
|
| 345 |
+
if centroid is not None and emb is not None and emb.size == centroid.size:
|
| 346 |
+
sims_raw.append(float(np.dot(centroid, emb)))
|
| 347 |
+
else:
|
| 348 |
+
sims_raw.append(0.5) # neutral when missing
|
| 349 |
+
|
| 350 |
+
cand_dom = _row_dom(c)
|
| 351 |
+
cand_neutral = cand_dom is not None and is_neutral(cand_dom)
|
| 352 |
+
color_raw.append(
|
| 353 |
+
_color_score(cand_dom, state.dom_labs, cand_neutral, state.has_neutral)
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
cscore, flipped = _contrast_score(_row_axes(c), state.axes_mean)
|
| 357 |
+
contrast_raw.append(cscore)
|
| 358 |
+
flipped_per.append(flipped)
|
| 359 |
+
|
| 360 |
+
norm_score = _min_max_norm(scores_raw)
|
| 361 |
+
norm_sim = _min_max_norm(sims_raw)
|
| 362 |
+
# Color and contrast are already in [0, 1] — no min-max (would wash out
|
| 363 |
+
# absolute differences and overweight tiny pool variation).
|
| 364 |
+
|
| 365 |
+
best_idx, best_blend = -1, -1.0
|
| 366 |
+
for i, c in enumerate(candidates):
|
| 367 |
+
blend = (
|
| 368 |
+
_W_SCORE * norm_score[i]
|
| 369 |
+
+ _W_SIM * norm_sim[i]
|
| 370 |
+
+ _W_COLOR * color_raw[i]
|
| 371 |
+
+ _W_CONTRAST * contrast_raw[i]
|
| 372 |
+
) * scandi_bias(_row_scandi(c))
|
| 373 |
+
if blend > best_blend:
|
| 374 |
+
best_idx, best_blend = i, blend
|
| 375 |
+
|
| 376 |
+
if best_idx < 0:
|
| 377 |
+
return None
|
| 378 |
+
best = candidates[best_idx]
|
| 379 |
+
|
| 380 |
+
# Attach picking metadata for downstream rendering.
|
| 381 |
+
cand_dom = _row_dom(best)
|
| 382 |
+
cand_axes = _row_axes(best)
|
| 383 |
+
cand_scandi = _row_scandi(best)
|
| 384 |
+
best["_pick"] = {
|
| 385 |
+
"blend": float(best_blend),
|
| 386 |
+
"color_score": float(color_raw[best_idx]),
|
| 387 |
+
"contrast_score": float(contrast_raw[best_idx]),
|
| 388 |
+
"axes_added": flipped_per[best_idx],
|
| 389 |
+
"scandi_score": cand_scandi,
|
| 390 |
+
"rationale": _make_rationale(
|
| 391 |
+
color_raw[best_idx],
|
| 392 |
+
flipped_per[best_idx],
|
| 393 |
+
cand_axes,
|
| 394 |
+
cand_scandi,
|
| 395 |
+
cand_dom,
|
| 396 |
+
),
|
| 397 |
+
"color_name": _color_name(cand_dom),
|
| 398 |
+
}
|
| 399 |
return best
|
| 400 |
|
| 401 |
|
| 402 |
+
# ---- public entry point ----
|
| 403 |
+
|
| 404 |
def compose_outfit(anchor_url: str, conn) -> dict | None:
|
| 405 |
+
"""Build a set-aware outfit around `anchor_url`.
|
| 406 |
+
|
| 407 |
+
Returns None if anchor not found. Each complement is picked sequentially
|
| 408 |
+
and scored against the running outfit (anchor + earlier picks), so later
|
| 409 |
+
slots react to what's already in the look.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
"""
|
| 411 |
from taste.store import _blob_to_emb # local import to avoid cycle
|
| 412 |
|
| 413 |
+
row = conn.execute("SELECT * FROM products WHERE url = ?", (anchor_url,)).fetchone()
|
|
|
|
|
|
|
| 414 |
if not row:
|
| 415 |
return None
|
| 416 |
anchor = dict(row)
|
| 417 |
bucket = anchor.get("canonical_category") or "unknown"
|
| 418 |
anchor_emb = _blob_to_emb(anchor.get("taste_embedding") or b"")
|
| 419 |
|
| 420 |
+
state = _OutfitState(anchor, anchor_emb)
|
| 421 |
+
embeddings_cache: dict[str, np.ndarray] = {}
|
| 422 |
+
if anchor_emb is not None:
|
| 423 |
+
embeddings_cache[anchor_url] = anchor_emb
|
| 424 |
+
|
| 425 |
+
complements: list[dict[str, Any]] = []
|
| 426 |
used_urls: set[str] = {anchor_url}
|
| 427 |
total = float(anchor.get("price_nok") or 0)
|
| 428 |
|
| 429 |
for comp_bucket in PAIRING_RULES.get(bucket, []):
|
| 430 |
+
prod = _pick_complement(conn, comp_bucket, anchor_url, state, used_urls, embeddings_cache)
|
| 431 |
+
if not prod:
|
| 432 |
+
continue
|
| 433 |
+
pick = prod.pop("_pick", {})
|
| 434 |
+
# Update running state BEFORE moving on to next bucket.
|
| 435 |
+
state.add(prod)
|
| 436 |
+
complements.append({
|
| 437 |
+
"bucket": comp_bucket,
|
| 438 |
+
"product": prod,
|
| 439 |
+
"rationale": pick.get("rationale", ""),
|
| 440 |
+
"color_name": pick.get("color_name", ""),
|
| 441 |
+
"color_score": pick.get("color_score", 0.0),
|
| 442 |
+
"axes_added": pick.get("axes_added", []),
|
| 443 |
+
})
|
| 444 |
+
used_urls.add(prod["url"])
|
| 445 |
+
total += float(prod.get("price_nok") or 0)
|
| 446 |
|
| 447 |
# Drop the embedding blob from response payload (not JSON-serializable).
|
| 448 |
anchor.pop("taste_embedding", None)
|
| 449 |
for c in complements:
|
| 450 |
c["product"].pop("taste_embedding", None)
|
| 451 |
|
| 452 |
+
# Outfit-level summary.
|
| 453 |
+
palette = _outfit_palette(anchor, complements)
|
| 454 |
+
axes_covered = _axes_covered(anchor, complements)
|
| 455 |
+
axes_contrasted = _axes_contrasted(anchor, complements)
|
| 456 |
+
overall_scandi = float(np.mean(state.scandi)) if state.scandi else 0.0
|
| 457 |
+
|
| 458 |
+
anchor_dom = _row_dom(anchor)
|
| 459 |
return {
|
| 460 |
"anchor": anchor,
|
| 461 |
"anchor_bucket": bucket,
|
| 462 |
+
"anchor_color_name": _color_name(anchor_dom),
|
| 463 |
"complements": complements,
|
| 464 |
"total_nok": total,
|
| 465 |
+
"palette": palette,
|
| 466 |
+
"axes_covered": axes_covered,
|
| 467 |
+
"axes_contrasted": axes_contrasted,
|
| 468 |
+
"scandi_score": overall_scandi,
|
| 469 |
}
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def _outfit_palette(anchor: dict, complements: list[dict]) -> list[dict]:
|
| 473 |
+
"""Merge dominant LABs across the outfit into a small swatch list."""
|
| 474 |
+
out: list[dict] = []
|
| 475 |
+
for label, prod in [("anchor", anchor)] + [(c["bucket"], c["product"]) for c in complements]:
|
| 476 |
+
dom = _row_dom(prod)
|
| 477 |
+
if dom is None:
|
| 478 |
+
continue
|
| 479 |
+
out.append({
|
| 480 |
+
"from": label,
|
| 481 |
+
"lab": [float(v) for v in dom],
|
| 482 |
+
"hex": lab_to_hex(dom),
|
| 483 |
+
"name": _color_name(dom),
|
| 484 |
+
})
|
| 485 |
+
return out
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def _axes_covered(anchor: dict, complements: list[dict]) -> list[str]:
|
| 489 |
+
"""Axes where the outfit takes a confident stance.
|
| 490 |
+
|
| 491 |
+
An axis is "covered" when at least one item in the outfit pushes it past
|
| 492 |
+
±0.3 (in either direction). This matches Bornstein's actual claim that
|
| 493 |
+
outfits read "styled" when they speak clearly on multiple axes — the
|
| 494 |
+
bipolar variant ("both poles present") was too strict for the catalog's
|
| 495 |
+
distribution and unnecessarily aggressive.
|
| 496 |
+
|
| 497 |
+
Bipolar contrast within an axis is a stronger signal for "deliberate"
|
| 498 |
+
styling and is exposed via `_axes_contrasted` for the eval suite.
|
| 499 |
+
"""
|
| 500 |
+
items = [anchor] + [c["product"] for c in complements]
|
| 501 |
+
covered: list[str] = []
|
| 502 |
+
for a in AXES:
|
| 503 |
+
vals = [_row_axes(p).get(a, 0.0) for p in items]
|
| 504 |
+
if any(abs(v) > 0.3 for v in vals):
|
| 505 |
+
covered.append(a)
|
| 506 |
+
return covered
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _axes_contrasted(anchor: dict, complements: list[dict]) -> list[str]:
|
| 510 |
+
"""Strict subset of `_axes_covered`: both poles present in the outfit."""
|
| 511 |
+
items = [anchor] + [c["product"] for c in complements]
|
| 512 |
+
out: list[str] = []
|
| 513 |
+
for a in AXES:
|
| 514 |
+
vals = [_row_axes(p).get(a, 0.0) for p in items]
|
| 515 |
+
if any(v > 0.3 for v in vals) and any(v < -0.3 for v in vals):
|
| 516 |
+
out.append(a)
|
| 517 |
+
return out
|