AgPerry's picture
Add files using upload-large-folder tool
2401aa7 verified
Raw History Blame Contribute Delete
8.59 kB
"""Read-only catalogue view over the frozen, source-derived product data.
Every image path resolves to a byte-exact local file under static/assets/img;
the clone makes no runtime remote request.
"""
from __future__ import annotations
import json
import pathlib
import re
from functools import lru_cache
BASE = pathlib.Path(__file__).resolve().parent
DATA = BASE / "data"
IMG_DIR = BASE / "static/assets/img"
PAGE_DIR = BASE / "static/assets/page"
CARD, HERO, GALLERY, SWATCH = "400x", "1000x", "600x", "150x"
# Storefront-wide promotion observed on the source (15% off, sitewide banner code).
SITEWIDE_DISCOUNT = 0.15
FREE_SHIPPING_THRESHOLD = 100.0
def local_name(src: str, size: str) -> str:
base = src.partition("?")[0].rsplit("/", 1)[-1]
stem, _, ext = base.rpartition(".")
stem = re.sub(r"[^A-Za-z0-9_.-]", "-", stem)[:90]
return f"{stem}__{size}.{ext}"
def img_url(src: str | None, size: str) -> str | None:
if not src:
return None
name = local_name(src, size)
return f"/static/assets/img/{name}" if (IMG_DIR / name).exists() else None
def page_url(src: str | None) -> str | None:
if not src:
return None
name = re.sub(r"[^A-Za-z0-9_.-]", "-", src.partition("?")[0].rsplit("/", 1)[-1])[:110]
return f"/static/assets/page/{name}" if (PAGE_DIR / name).exists() else None
COLOR_FAMILIES = ["White", "Cream", "Beige", "Grey", "Blue", "Brown", "Green",
"Multi", "Orange", "Pink", "Red", "Yellow"]
SIZE_ORDER = ["Twin", "Twin XL", "Full", "Queen", "King", "Cali King", "Standard", "Euro"]
FABRICS = ["Brushed Flannel", "Classic Percale", "Heathered Cashmere", "Luxe Sateen",
"Plush", "Ribbed Cotton TENCEL\u2122", "Super-Plush", "Waffle",
"Washed Classic Percale", "Washed European Linen"]
PATTERNS = {"Stripes": ("stripe", "striped"), "Florals": ("floral", "bloom", "dandelion", "botanical"),
"Abstract": ("abstract", "patchwork", "tandem", "weave", "checker", "plaid", "gingham")}
BUNDLE_TYPES = {"Bedding Move-In Bundles": ("move-in",), "Comforter & Duvet Bundles": ("comforter",),
"Core Sheet Sets": ("core sheet",), "Duvet & Quilt Sets": ("duvet set", "quilt set"),
"Hardcore Sheet Bundles": ("hardcore",), "No Flat Sheet Set Bundles": ("no flat",),
"Starter Bundles": ("starter",)}
COMFORTER_TYPES = {"Down": ("down",), "Lightweight": ("lightweight",), "All-Season": ("all-season", "all season")}
BEDDING_LAYERS = {"Essentials": ("essential",), "Base Layer": ("sheet", "pillowcase"),
"Top Layer": ("duvet", "comforter", "quilt", "blanket")}
def _hex_family(hex_value: str | None, name: str) -> str | None:
"""Classify a swatch into the source's twelve colour families."""
lowered = name.lower()
if any(w in lowered for w in ("stripe", "patchwork", "multi", "plaid", "gingham", "floral", "check")):
return "Multi"
if not hex_value or not hex_value.startswith("#") or len(hex_value) != 7:
for family in COLOR_FAMILIES:
if family.lower() in lowered:
return family
return None
r, g, b = (int(hex_value[i:i + 2], 16) for i in (1, 3, 5))
mx, mn = max(r, g, b), min(r, g, b)
chroma, light = mx - mn, mx / 255
if chroma < 26:
if light > 0.93:
return "White"
if light > 0.82:
return "Cream"
return "Grey"
import colorsys
hue = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)[0] * 360
if hue < 16 or hue >= 340:
return "Red" if light > 0.45 and chroma > 70 else "Brown"
if hue < 42:
return "Brown" if light < 0.62 else ("Beige" if chroma < 70 else "Orange")
if hue < 68:
return "Yellow"
if hue < 165:
return "Green"
if hue < 260:
return "Blue"
if hue < 290:
return "Blue"
return "Pink"
def _facets_for(product: dict, swatches: dict) -> dict[str, list[str]]:
title = product["title"].lower()
tags = {t.lower() for t in product["tags"]}
colors, sizes, patterns = [], [], []
for v in product["variants"]:
name = v.get("option1") or ""
meta = swatches.get(name, {})
family = _hex_family(meta.get("hex"), name)
if family and family not in colors:
colors.append(family)
size = v.get("option2")
if size and size not in sizes:
sizes.append(size)
lowered = name.lower()
for label, needles in PATTERNS.items():
if any(n in lowered for n in needles) and label not in patterns:
patterns.append(label)
if not patterns:
patterns = ["Solid"]
fabric = [f for f in FABRICS if f.lower() in title or f.lower() in tags]
featured = []
if "bundle" in title or "bundle savings" in tags:
featured.append("Bundle Savings")
if any("cooling" in t for t in tags) or "percale" in title:
featured.append("Cooling")
if any("hsa" in t for t in tags):
featured.append("HSA/FSA Eligible")
bundle = [k for k, needles in BUNDLE_TYPES.items() if any(n in title for n in needles)]
comforter = [k for k, needles in COMFORTER_TYPES.items()
if any(n in title for n in needles)] if "comforter" in title else []
layers = [k for k, needles in BEDDING_LAYERS.items() if any(n in title for n in needles)]
return {"product_type": [product["product_type"]] if product["product_type"] else [],
"color": colors, "size": [s for s in SIZE_ORDER if s in sizes] or sizes,
"fabric": fabric, "featured": featured, "pattern": patterns,
"bundle_type": bundle, "comforter_type": comforter, "bedding_layers": layers}
FACET_GROUPS = [("product_type", "Product Type"), ("color", "Color"), ("size", "Size"),
("fabric", "Fabric"), ("featured", "Featured"), ("bedding_layers", "Bedding Layers"),
("bundle_type", "Bundle Type"), ("pattern", "Pattern"),
("comforter_type", "Comforter Type")]
FACET_ORDER = {"color": COLOR_FAMILIES, "size": SIZE_ORDER, "fabric": FABRICS}
def _stable_reviews(handle: str) -> int:
"""Deterministic per-product review count; no source review data is copied."""
return 40 + (sum(handle.encode()) * 37) % 4000
@lru_cache(maxsize=1)
def swatch_table() -> dict:
"""Site-wide colour table (hex, pattern image, copy) as published by the source."""
path = DATA / "swatches.json"
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
@lru_cache(maxsize=1)
def catalog() -> dict:
raw = json.loads((DATA / "catalog.json").read_text(encoding="utf-8"))
p0 = set(json.loads((DATA / "p0-products.json").read_text(encoding="utf-8")))
for handle, p in raw["products"].items():
p["detail_closed"] = handle in p0
p["card_image"] = img_url(p["images"][0] if p["images"] else None, CARD)
p["review_count"] = _stable_reviews(handle)
p["sale_price"] = round(p["price_min"] * (1 - SITEWIDE_DISCOUNT), 2)
p["on_sale"] = True
p["discount_pct"] = int(SITEWIDE_DISCOUNT * 100)
p["badge"] = _badge(p)
seen, swatches = set(), []
for v in p["variants"]:
key = v.get("option1")
if key in seen:
continue
seen.add(key)
meta = swatch_table().get(key or "", {})
swatches.append({"title": key, "hex": meta.get("hex"),
"description": meta.get("description"),
"image": img_url(v.get("image"), SWATCH)})
p["swatches"] = swatches
p["facets"] = _facets_for(p, swatch_table())
raw["by_handle"] = raw["products"]
return raw
def _badge(p: dict) -> str | None:
tags = {t.lower() for t in p["tags"]}
if "super-plush towels" in tags or "super-plush 2.0" in tags:
return "FLUFFIEST"
if any("cooling" in t for t in tags):
return "COOLING"
if "newarrivals" in tags:
return "NEW"
if "best sellers" in tags:
return "BEST SELLER"
return None
def products_for(handles) -> list[dict]:
by = catalog()["products"]
return [by[h] for h in handles if h in by]
def collection(handle: str) -> dict | None:
for c in catalog()["collections"]:
if c["handle"] == handle:
return c
return None
def variant_index() -> dict[int, tuple[str, dict]]:
idx = {}
for handle, p in catalog()["products"].items():
for v in p["variants"]:
idx[v["id"]] = (handle, v)
return idx