"""Taste Engine — learn visual aesthetic from reference images using FashionSigLIP.""" import hashlib import json import numpy as np from pathlib import Path from PIL import Image SUPPORTED_EXT = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".avif"} def find_images(folder: Path) -> list[Path]: images = [] for f in folder.iterdir(): if f.suffix.lower() in SUPPORTED_EXT and not f.name.startswith("."): images.append(f) return sorted(images, key=lambda p: p.name.lower()) class TasteEngine: """FashionSigLIP-based taste engine with multi-centroid HDBSCAN + MaxSim scoring. All paths are explicit — no defaults. The caller (CLI/pipeline) resolves them from config/profile. """ def __init__(self, data_dir: Path): self.data_dir = Path(data_dir) self.data_dir.mkdir(parents=True, exist_ok=True) self.ratings_path = self.data_dir / "ratings.json" self.cache_dir = self.data_dir / "embeddings" self.cache_dir.mkdir(exist_ok=True) self._model = None self._preprocess = None self._tokenizer = None self._device = None @property def device(self): if self._device is None: import torch if torch.cuda.is_available(): self._device = "cuda" elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): self._device = "mps" else: self._device = "cpu" return self._device def _load_model(self): if self._model is not None: return import open_clip import torch # noqa: F811 model, _, preprocess = open_clip.create_model_and_transforms( "hf-hub:Marqo/marqo-fashionSigLIP" ) self._model = model.to(self.device) self._model.requires_grad_(False) self._preprocess = preprocess self._tokenizer = open_clip.get_tokenizer("hf-hub:Marqo/marqo-fashionSigLIP") def _cache_key(self, path: Path) -> str: stat = path.stat() raw = f"fashionsiglip:{path.resolve()}:{stat.st_size}:{stat.st_mtime_ns}" return hashlib.blake2b(raw.encode(), digest_size=16).hexdigest() # --- Encoding --- def encode(self, path: Path) -> np.ndarray: import torch path = Path(path) key = self._cache_key(path) cache_path = self.cache_dir / f"{key}.npy" if cache_path.exists(): return np.load(cache_path) self._load_model() img = Image.open(path).convert("RGB") tensor = self._preprocess(img).unsqueeze(0).to(self.device) with torch.no_grad(): emb = self._model.encode_image(tensor) emb = emb / emb.norm(dim=-1, keepdim=True) result = emb.squeeze().cpu().float().numpy() np.save(cache_path, result) return result def encode_text(self, text: str) -> np.ndarray: import torch self._load_model() tokens = self._tokenizer([text]).to(self.device) with torch.no_grad(): emb = self._model.encode_text(tokens) emb = emb / emb.norm(dim=-1, keepdim=True) return emb.squeeze().cpu().float().numpy() def encode_text_batch( self, texts: list[str], batch_size: int = 32 ) -> dict[str, np.ndarray]: """Encode many texts. Returns {text: emb}. Skips empty strings.""" import torch unique = sorted({t.strip() for t in texts if t and t.strip()}) if not unique: return {} self._load_model() results = {} for i in range(0, len(unique), batch_size): batch = unique[i : i + batch_size] tokens = self._tokenizer(batch).to(self.device) with torch.no_grad(): embs = self._model.encode_text(tokens) embs = embs / embs.norm(dim=-1, keepdim=True) for t, emb in zip(batch, embs.cpu().float().numpy()): results[t] = emb return results def encode_product( self, image_paths: list[Path], text: str = "", text_weight: float = 0.2, ) -> np.ndarray | None: """Fused product embedding: mean of image embs + optional text emb. text_weight=0 disables text fusion. Empirically 0.2 is the sweet spot (validated on Boozt multi-angle retrieval, top-1 0.95→1.00). """ valid_paths = [Path(p) for p in image_paths if Path(p).exists()] if not valid_paths and not text.strip(): return None if valid_paths: embs = [self.encode(p) for p in valid_paths] img_emb = np.mean(embs, axis=0) img_emb = img_emb / np.linalg.norm(img_emb) else: img_emb = None text = text.strip()[:200] if img_emb is None: return self.encode_text(text) if not text or text_weight <= 0: return img_emb txt_emb = self.encode_text(text) fused = (1 - text_weight) * img_emb + text_weight * txt_emb return fused / np.linalg.norm(fused) def encode_batch( self, paths: list[Path], batch_size: int = 16, progress_cb=None ) -> dict[str, np.ndarray]: import torch results = {} to_encode = [] for p in paths: key = self._cache_key(p) cache_path = self.cache_dir / f"{key}.npy" if cache_path.exists(): results[str(p)] = np.load(cache_path) else: to_encode.append(p) done = len(results) total = len(paths) if to_encode: self._load_model() for i in range(0, len(to_encode), batch_size): batch_paths = to_encode[i : i + batch_size] tensors, valid = [], [] for p in batch_paths: try: img = Image.open(p).convert("RGB") tensors.append(self._preprocess(img)) valid.append(p) except Exception: done += 1 continue if tensors: batch = torch.stack(tensors).to(self.device) with torch.no_grad(): embs = self._model.encode_image(batch) embs = embs / embs.norm(dim=-1, keepdim=True) for p, emb in zip(valid, embs.cpu().float().numpy()): key = self._cache_key(p) np.save(self.cache_dir / f"{key}.npy", emb) results[str(p)] = emb done += 1 if progress_cb: progress_cb(done / total) return results # --- Ratings --- # Each entry is either an int (legacy) or {"rating": int, "category": str}. def load_ratings(self) -> dict[str, int]: """Load ratings as a flat {path: int} dict (legacy-compatible).""" raw = self._load_ratings_raw() return {k: self._rating_val(v) for k, v in raw.items()} def _load_ratings_raw(self) -> dict: if self.ratings_path.exists(): return json.loads(self.ratings_path.read_text()) return {} @staticmethod def _rating_val(entry) -> int: if isinstance(entry, int): return entry if isinstance(entry, dict): return entry.get("rating", 0) return 0 @staticmethod def _rating_cat(entry) -> str: if isinstance(entry, dict): return entry.get("category", "") return "" def save_rating(self, path: Path, rating: int, category: str = ""): raw = self._load_ratings_raw() key = str(Path(path).resolve()) raw[key] = {"rating": rating, "category": category} self.ratings_path.write_text(json.dumps(raw, indent=2)) def clear_ratings(self, paths: list[Path] | None = None): if paths is None: self.ratings_path.write_text("{}") return raw = self._load_ratings_raw() for p in paths: raw.pop(str(Path(p).resolve()), None) self.ratings_path.write_text(json.dumps(raw, indent=2)) def seed_from_references(self, folder: Path): raw = self._load_ratings_raw() images = find_images(folder) seeded = 0 for img in images: key = str(img.resolve()) if key not in raw: self.save_rating(img, 1) seeded += 1 return seeded def stats(self) -> dict: ratings = self.load_ratings() liked = sum(1 for v in ratings.values() if v == 1) disliked = sum(1 for v in ratings.values() if v == -1) skipped = sum(1 for v in ratings.values() if v == 0) return {"total": len(ratings), "liked": liked, "disliked": disliked, "skipped": skipped} # --- Taste model (multi-centroid HDBSCAN + MaxSim) --- def build_taste_vector(self) -> list[np.ndarray] | None: """Build unified multi-centroid taste model. Returns list of centroid vectors.""" ratings = self.load_ratings() liked = [] for path_str, rating in ratings.items(): p = Path(path_str) if not p.exists() or rating != 1: continue liked.append(self.encode(p)) if not liked: return None return self._cluster_centroids(np.array(liked)) def build_category_taste(self) -> dict: """Build per-category centroids + unified fallback. Returns {"categories": {cat: [centroids]}, "unified": [centroids]} where unified is built from ALL liked images across categories. Categories with no liked images won't have an entry. """ raw = self._load_ratings_raw() all_liked = [] by_cat: dict[str, list[np.ndarray]] = {} for path_str, entry in raw.items(): p = Path(path_str) if not p.exists() or self._rating_val(entry) != 1: continue emb = self.encode(p) all_liked.append(emb) cat = self._normalize_category(self._rating_cat(entry)) if cat: by_cat.setdefault(cat, []).append(emb) if not all_liked: return {"categories": {}, "unified": None} # Per-category centroids (simple mean — categories typically have few examples) cat_centroids = {} for cat, embs in by_cat.items(): arr = np.array(embs) if len(arr) >= 3: cat_centroids[cat] = self._cluster_centroids(arr) else: c = np.mean(arr, axis=0) cat_centroids[cat] = [c / np.linalg.norm(c)] # Unified fallback from all liked images unified = self._cluster_centroids(np.array(all_liked)) return {"categories": cat_centroids, "unified": unified} @staticmethod def _normalize_category(raw_cat: str) -> str: """Map raw category strings to canonical names for centroid grouping.""" if not raw_cat: return "" low = raw_cat.lower() # Map common patterns to canonical category names _PATTERNS = { "bags": ["bag", "veske", "väsk", "tote", "clutch", "wallet", "purse", "shoulder"], "dresses": ["dress", "kjoler", "kjole", "klänning"], "tops": ["top", "blouse", "t-shirt", "t_shirt", "topper", "blus", "shirt", "skjorte"], "jackets": ["jacket", "coat", "jakke", "kåpe", "jacka", "blazer", "outerwear", "trench"], "trousers": ["trouser", "pant", "bukse", "byxor", "jean", "short"], "skirts": ["skirt", "skjørt", "kjol"], "knitwear": ["knit", "sweater", "cardigan", "strikk", "genser"], "shoes": ["shoe", "boot", "sandal", "sneaker", "heel", "loafer", "sko", "ballerina", "skor", "pump"], } for canonical, patterns in _PATTERNS.items(): if any(p in low for p in patterns): return canonical return raw_cat.strip().lower() def _cluster_centroids(self, embeddings: np.ndarray) -> list[np.ndarray]: n = len(embeddings) if n < 5: c = np.mean(embeddings, axis=0) c = c / np.linalg.norm(c) return [c] try: from sklearn.cluster import HDBSCAN as HDBSCANCluster clusterer = HDBSCANCluster(min_cluster_size=3, min_samples=2) labels = clusterer.fit_predict(embeddings) except Exception: from sklearn.cluster import KMeans k = min(3, n // 3) if n >= 6 else 1 labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(embeddings) centroids = [] for label in set(labels): mask = labels == label if label == -1: for emb in embeddings[mask]: centroids.append(emb / np.linalg.norm(emb)) else: c = np.mean(embeddings[mask], axis=0) centroids.append(c / np.linalg.norm(c)) if not centroids: c = np.mean(embeddings, axis=0) centroids = [c / np.linalg.norm(c)] return centroids def _compute_dim_weights(self, embeddings: np.ndarray) -> np.ndarray: variances = np.var(embeddings, axis=0) inv_var = 1.0 / (variances + 1e-8) return inv_var / np.mean(inv_var) # --- Scoring --- def score(self, path: Path, centroids: list[np.ndarray]) -> float: emb = self.encode(path) return max(float(np.dot(emb, c)) for c in centroids) def score_product_images( self, image_paths: list[Path], centroids: list[np.ndarray] ) -> list[tuple[Path, float]]: embeddings = self.encode_batch(image_paths) c_arr = np.array(centroids) scores = [] for p in image_paths: key = str(p) if key in embeddings: emb = embeddings[key] s = float(np.max(emb @ c_arr.T)) scores.append((p, s)) scores.sort(key=lambda x: x[1], reverse=True) return scores @staticmethod def derive_user_metadata_profile(rated_products: list[dict]) -> dict: """Derive user's price band + sale preference from rated products. Args: rated_products: list of {price_nok, on_sale, rating} where rating in {-1, 0, 1}. Returns: {"price_band": {p10,p25,p50,p75,p90} or None, "sale_pref": float in [-1,1]} """ liked = [p for p in rated_products if p.get("rating", 0) > 0 and (p.get("price_nok") or 0) > 0] if len(liked) < 3: price_band = None else: prices = sorted(p["price_nok"] for p in liked) price_band = { "p10": float(np.percentile(prices, 10)), "p25": float(np.percentile(prices, 25)), "p50": float(np.percentile(prices, 50)), "p75": float(np.percentile(prices, 75)), "p90": float(np.percentile(prices, 90)), } rated_with_sale = [p for p in rated_products if "on_sale" in p and p.get("rating", 0) != 0] if len(rated_with_sale) >= 4: liked_sale = sum(1 for p in rated_with_sale if p["rating"] > 0 and p.get("on_sale")) liked_full = sum(1 for p in rated_with_sale if p["rating"] > 0 and not p.get("on_sale")) disliked_sale = sum(1 for p in rated_with_sale if p["rating"] < 0 and p.get("on_sale")) disliked_full = sum(1 for p in rated_with_sale if p["rating"] < 0 and not p.get("on_sale")) n_liked = liked_sale + liked_full n_disliked = disliked_sale + disliked_full if n_liked > 0 and n_disliked > 0: sale_pref = (liked_sale / n_liked) - (disliked_sale / n_disliked) else: sale_pref = 0.0 else: sale_pref = 0.0 return {"price_band": price_band, "sale_pref": float(sale_pref)} @staticmethod def _price_bias(price: float, band: dict | None) -> float: """Price-distribution alignment in [0.7, 1.0]. Returns 1.0 if price is within the user's [p25, p75] of liked items; decays linearly to 0.7 outside [p10, p90]. Floor 0.7 — never zero out. """ if not band or not price or price <= 0: return 1.0 p25, p75 = band.get("p25", 0), band.get("p75", 0) p10, p90 = band.get("p10", 0), band.get("p90", 0) if p25 <= price <= p75: return 1.0 if price < p25 and p10 < p25: x = max(0.0, (price - p10) / (p25 - p10)) return 0.7 + 0.3 * x if price > p75 and p90 > p75: x = max(0.0, (p90 - price) / (p90 - p75)) return 0.7 + 0.3 * x return 0.7 @staticmethod def _sale_bias(on_sale: bool, sale_pref: float) -> float: """Sale preference bias. sale_pref ∈ [-1, 1] from user history. Returns multiplier in [0.95, 1.05].""" if sale_pref == 0: return 1.0 if on_sale: return 1.0 + 0.05 * sale_pref return 1.0 - 0.05 * sale_pref def score_products_by_category( self, products: list[dict], taste: dict, text_weight: float = 0.3, price_band: dict | None = None, sale_pref: float = 0.0, ) -> list[dict]: """Score products using per-category centroids with unified fallback. Each product dict supports: image_path: str (single primary image) image_paths: list[str] (optional — multi-image, takes precedence) category: str text: str (optional — fused with image at text_weight) Returns: list of {image_path, score, embedding} (image_path = first available). `embedding` is the visual embedding (image-only, mean-pooled, unit-norm) used for anchor-conditioned outfit pairing — text fusion is deliberately kept out so visual harmony isn't polluted by brand/name overlap. """ cat_centroids = taste.get("categories", {}) unified = taste.get("unified") if not unified: return [] # Collect all images and texts up front for batched encoding all_image_paths: set[str] = set() for p in products: paths = p.get("image_paths") or [p.get("image_path", "")] for ip in paths: if ip and Path(ip).exists(): all_image_paths.add(str(ip)) img_embs = self.encode_batch([Path(s) for s in all_image_paths]) if all_image_paths else {} texts = [p.get("text", "") for p in products] text_embs = self.encode_text_batch(texts) if text_weight > 0 else {} unified_arr = np.array(unified) results = [] for p in products: paths = p.get("image_paths") or [p.get("image_path", "")] valid = [ip for ip in paths if ip and str(Path(ip)) in img_embs] if not valid: continue # Preserve caller's identity — return the original image_path key ret_key = p.get("image_path") or str(Path(valid[0])) embs = [img_embs[str(Path(ip))] for ip in valid] img_emb = np.mean(embs, axis=0) img_emb = img_emb / np.linalg.norm(img_emb) text = (p.get("text", "") or "").strip() if text and text_weight > 0 and text in text_embs: fused = (1 - text_weight) * img_emb + text_weight * text_embs[text] emb = fused / np.linalg.norm(fused) else: emb = img_emb cat = self._normalize_category(p.get("category", "")) c_arr = np.array(cat_centroids[cat]) if cat in cat_centroids else unified_arr s = float(np.max(emb @ c_arr.T)) # Apply metadata biases (multiplicative, transparent, ablatable) if price_band is not None: s *= self._price_bias(float(p.get("price_nok") or 0), price_band) if sale_pref: s *= self._sale_bias(bool(p.get("on_sale", False)), sale_pref) results.append({"image_path": ret_key, "score": s, "embedding": img_emb}) return results