Build an e‑commerce variant canonicalization: color/size options, availability, and…
- User
Build an e‑commerce variant canonicalization: color/size options, availability, and dedup strategy.
Assistant
Build an e‑commerce variant canonicalization: color/size options, availability, and dedup strategy.
The user wants me to build a system for "e-commerce variant canonicalization." This involves handling product variations (like color and size), checking their availability, and implementing a strategy to deduplicate products to establish a "canonical" representation.
This is a common problem in e-commerce data processing, especially when aggregating data from multiple sources or managing a large catalog where products can be represented in multiple ways.
Key components needed:
Step 1: Define the Data Model
Product usually has a SKU, title, description, price, etc.Variant usually has specific attributes like Color, Size, Material.Step 2: Variant Grouping (The "Product" level)
VariantGrouper that uses a signature (e.g., normalized title + category) to group items.Step 3: Canonical Selection
Step 4: Deduplication (Dedup Strategy)
Step 5: Availability
Drafting the Solution Structure: I will provide a Python solution. It's the most readable language for this logic.
ProductVariant: Dataclass for holding raw data.CanonicalProduct: The output object representing the grouped entity.normalize_text: For cleaning titles.Canonicalizer:
generate_signature(): Creates a key to group variants.select_canonical(): Picks the best variant.process(): The main pipeline.Refining the "Dedup Strategy": There are two levels of deduping:
Detailed Logic for Canonical Selection:
Code Outline:
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class RawVariant:
sku: str
title: str
color: str
size: str
price: float
in_stock: bool
image_url: str
class Canonicalizer:
# logic to group and select
pass
Let's add a bit of sophistication to the "Signature" generation. To group "Nike T-Shirt Red" and "Nike T-Shirt Blue", we need to remove the color words from the title.
Plan:
RawSKU and CanonicalProduct.This covers all user requirements:
I will write the code and explain the strategy. I should also provide a conceptual explanation of the dedup strategy (e.g., clustering vs. exact matching).
Self-Correction/Refinement: Should I implement fuzzy matching?
fuzzywuzzy or sklearn), exact matching on normalized strings is safer for a standalone code block.Final check of requirements: "Build an e‑commerce variant canonicalization..." This sounds like "Show me the code" and "Explain the strategy". I will do both.
Structure of the response:
Let's write the code mentally first.
generate_group_key(title) -> lowercase, remove punctuation, remove colors (stopwords), sort words. This handles "Shirt Blue" vs "Blue Shirt".
select_canonical(variants) ->
Let's go.
This solution outlines a robust strategy for handling product variants (color/size), managing availability logic, and implementing a deduplication strategy to group SKUs into a single canonical product representation.
Before writing code, we must define the rules for canonicalization:
To determine if two SKUs belong to the same product, we generate a Normalized Group Key.
nike tshirt blue and t-shirt nike both become key: nike tshirt.Which variant represents the group?
Here is a complete implementation using Python dataclasses. This script takes a raw feed of mixed SKUs and groups them into canonical products.
In the code, generate_group_key handles the deduplication.
Variants are stored as a list within the CanonicalProduct.
CanonicalProduct object. It iterates through variants to populate color swatches and size dropdowns.variants where color='Black' to see which sizes (S, M, L) are available.There are two levels of availability:
sku.in_stock (Boolean).is_available (Aggregated).
count(variants.where(stock > 0)) > 0.noindex meta tags to prevent search engines from indexing empty pages.When a user lands on the Product Detail Page (PDP), which variant do they see?
in_stock == True.site.com/shirt?color=red, the <link rel="canonical"> should point to the base product URL site.com/shirt (or the chosen hero URL) to consolidate link equity.import re
from dataclasses import dataclass, field
from typing import List, Optional, Dict
import hashlib
# --- 1. Data Models ---
@dataclass
class RawSku:
"""Represents the raw data feed from a scraper or ERP."""
sku_id: str
title: str
price: float
color: Optional[str] = None
size: Optional[str] = None
in_stock: bool = True
image_url: str = ""
brand: str = ""
@dataclass
class CanonicalProduct:
"""The final grouped product entity."""
canonical_id: str
group_key: str
title: str
variants: List[RawSku] = field(default_factory=list)
@property
def is_available(self) -> bool:
"""Product is available if at least one variant is in stock."""
return any(v.in_stock for v in self.variants)
@property
def price_range(self) -> (float, float):
"""Calculate min/max price across variants."""
prices = [v.price for v in self.variants if v.price > 0]
return (min(prices), max(prices)) if prices else (0.0, 0.0)
def get_canonical_variant(self) -> RawSku:
"""Selects the 'hero' variant based on strategy."""
# Strategy: 1. In Stock > 2. Lowest Price
sorted_variants = sorted(
self.variants,
key=lambda v: (not v.in_stock, v.price)
)
return sorted_variants[0]
# --- 2. Canonicalization Engine ---
class CanonicalizationEngine:
def __init__(self):
self.stopwords = {'the', 'a', 'an', 'new', 'original', 'official', 'free', 'shipping'}
def _clean_text(self, text: str) -> str:
"""Normalize text for comparison."""
if not text: return ""
# Lowercase, remove non-alphanumeric
text = text.lower()
text = re.sub(r'[^a-z0-9\s]', '', text)
# Remove stopwords and sort words to ensure order independence
words = [w for w in text.split() if w not in self.stopwords]
return " ".join(sorted(words))
def generate_group_key(self, sku: RawSku) -> str:
"""
Creates a unique signature for the product group
(ignoring size/color specific differences).
"""
# Typically we group by Brand + Base Title
# Here we strip size/color from title to find the "base" product name
# (Simplified logic for demonstration)
base_attributes = f"{sku.brand}_{sku.title}"
return hashlib.md5(self._clean_text(base_attributes).encode()).hexdigest()
def process(self, raw_skus: List[RawSku]) -> Dict[str, CanonicalProduct]:
product_map: Dict[str, CanonicalProduct] = {}
for sku in raw_skus:
# 1. Generate Key
key = self.generate_group_key(sku)
# 2. Group or Create
if key not in product_map:
product_map[key] = CanonicalProduct(
canonical_id=f"PROD_{key[:8]}",
group_key=key,
title=sku.title # Inherit title from first found (or clean it later)
)
# 3. Add Variant
product_map[key].variants.append(sku)
return product_map
# --- 3. Simulation & Usage ---
# Raw Data: Notice the messy titles and duplicates
raw_data = [
RawSku("SKU_001", "Nike Dri-Fit T-Shirt (Black, M)", 25.00, color="Black", size="M", in_stock=True, brand="Nike"),
RawSku("SKU_002", "Nike Dri-Fit T-Shirt (Black, L)", 25.00, color="Black", size="L", in_stock=False, brand="Nike"),
RawSku("SKU_003", "Official Nike T-Shirt Dri-Fit Red S", 30.00, color="Red", size="S", in_stock=True, brand="Nike"),
RawSku("SKU_999", "Adidas Runner Shorts", 40.00, color="Blue", size="M", in_stock=True, brand="Adidas"),
]
# Run Engine
engine = CanonicalizationEngine()
catalog = engine.process(raw_data)
# Output Results
print(f"Total Raw SKUs: {len(raw_data)}")
print(f"Total Canonical Products: {len(catalog)}")
print("-" * 50)
for prod_id, product in catalog.items():
hero = product.get_canonical_variant()
min_p, max_p = product.price_range
print(f"Product: {product.title}")
print(f" ID: {product.canonical_id}")
print(f" Variants Found: {len(product.variants)}")
print(f" Global Availability: {'In Stock' if product.is_available else 'Out of Stock'}")
print(f" Price Range: ${min_p} - ${max_p}")
print(f" -> Selected Hero Variant: {hero.color} / {hero.size} (${hero.price})")
print("-" * 20)