Add OpenDB_Compliments_Merged folder with 11 files
#1
by SanjayH9305 - opened
- OpenDB_Compliments_Merged/.gitattributes +60 -0
- OpenDB_Compliments_Merged/Deduplication_Pipeline_Documentation.docx +0 -0
- OpenDB_Compliments_Merged/README.md +61 -0
- OpenDB_Compliments_Merged/candidate_gen.py +197 -0
- OpenDB_Compliments_Merged/canonical_products.parquet +3 -0
- OpenDB_Compliments_Merged/deduplicated_comparison.csv +0 -0
- OpenDB_Compliments_Merged/generate_outputs.py +147 -0
- OpenDB_Compliments_Merged/llm_grouper.py +137 -0
- OpenDB_Compliments_Merged/llm_utils.py +115 -0
- OpenDB_Compliments_Merged/preprocess.py +120 -0
- OpenDB_Compliments_Merged/product_mapping.parquet +3 -0
OpenDB_Compliments_Merged/.gitattributes
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
# Audio files - uncompressed
|
| 40 |
+
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
# Audio files - compressed
|
| 44 |
+
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
# Image files - uncompressed
|
| 50 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
# Image files - compressed
|
| 55 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
# Video files - compressed
|
| 59 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
*.webm filter=lfs diff=lfs merge=lfs -text
|
OpenDB_Compliments_Merged/Deduplication_Pipeline_Documentation.docx
ADDED
|
Binary file (30.3 kB). View file
|
|
|
OpenDB_Compliments_Merged/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
- fr
|
| 5 |
+
license: mit
|
| 6 |
+
task_categories:
|
| 7 |
+
- text-classification
|
| 8 |
+
- tabular-classification
|
| 9 |
+
tags:
|
| 10 |
+
- grocery
|
| 11 |
+
- deduplication
|
| 12 |
+
- retail
|
| 13 |
+
- food
|
| 14 |
+
pretty_name: Bilingual Grocery Product Deduplication
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# Bilingual Grocery Product Deduplication Dataset
|
| 18 |
+
|
| 19 |
+
## Dataset Summary
|
| 20 |
+
This dataset contains a fully deduplicated, canonical list of bilingual (English and French) grocery products. The original raw data consisted of noisy grocery inventory records with varying formats, typos, languages, and branding.
|
| 21 |
+
|
| 22 |
+
This repository provides the final cleaned dataset, the mapping of raw barcodes to canonical IDs, and a side-by-side comparison file to review the deduplication results. The deduplication was performed using a high-precision "Name-First" architecture combining token-overlap heuristics, multilingual embeddings, and Large Language Model (LLM) reasoning.
|
| 23 |
+
|
| 24 |
+
## File Structure
|
| 25 |
+
|
| 26 |
+
| File | Description |
|
| 27 |
+
|---|---|
|
| 28 |
+
| `canonical_products.parquet` | The clean, deduplicated database of the 1,109 unique canonical products, complete with averaged nutritional data. |
|
| 29 |
+
| `product_mapping.parquet` | The lookup table mapping every original 13-digit barcode (`code`) to its new `canonical_product_id`. |
|
| 30 |
+
| `deduplicated_comparison.csv` | A flat, human-readable CSV that joins the original data side-by-side with the new canonical groupings. Excellent for human review of the "before and after" state. |
|
| 31 |
+
| `Deduplication_Pipeline_Documentation.docx` | Comprehensive documentation outlining the v3 pipeline architecture, the modifier vetoes, the LLM usage, and final metrics. |
|
| 32 |
+
| `preprocess.py` | Phase 1 of the pipeline: Strict text normalization, cleaning, and exact-matching. Drops unnamed rows. |
|
| 33 |
+
| `candidate_gen.py` | Phase 2 of the pipeline: Generates fuzzy-match candidate pairs using a 0.65 Jaccard overlap threshold, bilingual embeddings, and applies hardcoded Modifier/Ingredient Vetoes. |
|
| 34 |
+
| `llm_grouper.py` | Phase 3 of the pipeline: Feeds the surviving ambiguous clusters to the LLM for atomic, semantic grouping to prevent chain-merging. |
|
| 35 |
+
| `llm_utils.py` | A custom LLM load balancer that routes requests between Groq, OpenRouter, NVIDIA, and Ollama, handling rate limits and JSON parsing. |
|
| 36 |
+
| `generate_outputs.py` | Phase 4 of the pipeline: Reads the final canonical JSON and builds the resulting Parquet and CSV dataset files. |
|
| 37 |
+
|
| 38 |
+
## Methodology (The v3 "Name-First" Architecture)
|
| 39 |
+
|
| 40 |
+
The dataset was constructed using a highly defensive deduplication pipeline designed to prioritize precision over recall (i.e., strictly avoiding the merging of different flavours, heat levels, or base ingredients).
|
| 41 |
+
|
| 42 |
+
1. **Phase 1: Strict Normalization & Exact Match**
|
| 43 |
+
- Stripped brand prefixes (e.g., "Compliments", "Sensations").
|
| 44 |
+
- Fixed French encoding artifacts and normalized casing/plurals.
|
| 45 |
+
- Grouped all exact textual matches automatically. Unnamed barcode rows were intentionally dropped from the deduplication pool to prevent nutrition-based pollution.
|
| 46 |
+
|
| 47 |
+
2. **Phase 2: High-Confidence Candidate Generation & Vetoes**
|
| 48 |
+
- Pairs were generated using a strict **Jaccard Token Overlap** threshold (≥ 0.65).
|
| 49 |
+
- Multilingual embeddings (`paraphrase-multilingual-MiniLM-L12-v2`) were selectively applied *only* to cross-language (English ↔ French) pairs.
|
| 50 |
+
- **Modifier Veto:** Before any candidate was approved, it passed through a rigorous check against hardcoded lists of flavours, heat levels, fat percentages, and core ingredient nouns. E.g., If a candidate pair consisted of *Cherry Jelly Powder* and *Lime Jelly Powder*, the flavour mismatch triggered an auto-veto.
|
| 51 |
+
|
| 52 |
+
3. **Phase 3: Group-Based LLM Judging**
|
| 53 |
+
- Surviving ambiguous candidates were clustered into connected components.
|
| 54 |
+
- These small clusters were passed to an LLM (Llama 3.3 70B / Llama 3.1 8B). The LLM evaluated entire groups atomically to explicitly prevent transitive chain-merging (where A=B and B=C incorrectly causes A=C).
|
| 55 |
+
|
| 56 |
+
## Results
|
| 57 |
+
- **Original Dataset:** 2,078 rows (1,322 named products, 756 unnamed)
|
| 58 |
+
- **Final Canonical Products:** 1,109
|
| 59 |
+
- **Safe Deduplication Rate:** 46.6% (on named products)
|
| 60 |
+
|
| 61 |
+
The pipeline successfully resolved complex typos (e.g., *Two Bite Brownines* -> *TWO-BITE Brownies*) and bilingual equivalents (e.g., *Fromage Cottage* -> *Cottage Cheese*), while successfully isolating specific product varieties (e.g., separating *Lemon Lime Sparkling Water* from *Orange Sparkling Water*).
|
OpenDB_Compliments_Merged/candidate_gen.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
import numpy as np
|
| 5 |
+
from fastembed import TextEmbedding
|
| 6 |
+
|
| 7 |
+
# ── Configuration ────────────────────────────────────────────────────────────
|
| 8 |
+
JACCARD_THRESHOLD = 0.65
|
| 9 |
+
EMBEDDING_THRESHOLD = 0.88
|
| 10 |
+
|
| 11 |
+
STOPWORDS = {'and','with','de','du','le','la','les','des','au','aux','et','en',
|
| 12 |
+
'une','un','a','the','in','of','from','for','to','by','no','not',
|
| 13 |
+
'%','g','ml','kg','l','oz','lb','pack','pkg','box','bag','can'}
|
| 14 |
+
|
| 15 |
+
FRENCH_MARKERS = ['de ', 'du ', 'le ', 'la ', 'les ', 'des ', 'au ', 'aux ', 'et ', 'en ',
|
| 16 |
+
'une ', 'un ', 'avec ', 'sans ', 'beurre', 'fromage', 'lait', 'poulet',
|
| 17 |
+
'boeuf', 'porc', 'canneberge', 'fraise', 'framboise', 'citron', 'pomme',
|
| 18 |
+
'crème', 'sauce', 'soupe', 'bouillon', 'vinaigre', 'moutarde', 'chocolat',
|
| 19 |
+
'noir', 'suisse', 'amande', 'noix', 'mélange', 'riz', 'thon', 'séchée', 'pain']
|
| 20 |
+
|
| 21 |
+
MODIFIER_CATEGORIES = {
|
| 22 |
+
'FLAVOUR': {'cherry', 'lime', 'lemon', 'orange', 'raspberry', 'strawberry', 'blueberry',
|
| 23 |
+
'mango', 'peach', 'grape', 'apple', 'pineapple', 'coconut', 'vanilla', 'chocolate',
|
| 24 |
+
'caramel', 'maple', 'honey', 'garlic', 'herb', 'original', 'plain', 'cinnamon',
|
| 25 |
+
'ginger', 'mint', 'limeade', 'tangerine', 'blackberry', 'watermelon', 'cranberry',
|
| 26 |
+
'banana', 'hazelnut', 'almond', 'mocha', 'cola', 'root', 'cream'},
|
| 27 |
+
'HEAT': {'hot', 'spicy', 'mild', 'medium', 'sweet', 'smoky'},
|
| 28 |
+
'SALT': {'salted', 'unsalted', 'salt free', 'low sodium', 'no salt', 'reduced sodium'},
|
| 29 |
+
'FAT': {'lean', 'extra lean', 'skim', 'whole', '1%', '2%', '3.25%', '5%', '7%', '14%', '18%',
|
| 30 |
+
'light', 'low fat', 'fat free', 'reduced fat', 'full fat'},
|
| 31 |
+
'DIET': {'diet', 'sugar free', 'zero', 'decaf', 'caffeine free'},
|
| 32 |
+
'SIZE': {'mini', 'large', 'extra large', 'medium', 'small', 'jumbo', 'thin', 'thick'},
|
| 33 |
+
'PROCESS': {'dark', 'milk', 'white', 'semi sweet', 'artificial', 'real', 'pure'},
|
| 34 |
+
'TEXTURE': {'smooth', 'crunchy', 'chunky', 'sliced', 'whole', 'diced', 'crushed', 'shredded',
|
| 35 |
+
'grated', 'minced', 'ground', 'halves', 'pieces', 'strips', 'sticks', 'flaked'},
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
MODIFIER_MAP = {}
|
| 39 |
+
for cat, words in MODIFIER_CATEGORIES.items():
|
| 40 |
+
for w in words:
|
| 41 |
+
MODIFIER_MAP[w] = cat
|
| 42 |
+
|
| 43 |
+
INGREDIENT_NOUNS = {
|
| 44 |
+
'chicken', 'turkey', 'beef', 'pork', 'lamb', 'fish', 'tuna', 'salmon', 'shrimp', 'cod', 'pollock', 'sole',
|
| 45 |
+
'canola', 'sunflower', 'sesame', 'olive', 'coconut', 'avocado',
|
| 46 |
+
'cheddar', 'mozzarella', 'havarti', 'swiss', 'asiago', 'parmesan', 'feta', 'goat',
|
| 47 |
+
'almond', 'cashew', 'peanut', 'walnut', 'pecan', 'pistachio',
|
| 48 |
+
'kidney', 'black', 'navy', 'chickpea', 'lentil',
|
| 49 |
+
'rice', 'wheat', 'oat', 'corn', 'barley', 'rye',
|
| 50 |
+
'strawberry', 'cherry', 'lemon', 'lime', 'orange', 'raspberry', 'blueberry', 'blackberry', 'cranberry',
|
| 51 |
+
'tomato', 'carrot', 'pea', 'spinach', 'broccoli', 'mushroom',
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def tokenize(s):
|
| 56 |
+
# s is already normalized from Phase 1, just split and remove stopwords
|
| 57 |
+
tokens = s.split()
|
| 58 |
+
return [t for t in tokens if t not in STOPWORDS and len(t) > 1]
|
| 59 |
+
|
| 60 |
+
def get_modifiers(tokens):
|
| 61 |
+
result = defaultdict(list)
|
| 62 |
+
for t in tokens:
|
| 63 |
+
if t in MODIFIER_MAP:
|
| 64 |
+
result[MODIFIER_MAP[t]].append(t)
|
| 65 |
+
return dict(result)
|
| 66 |
+
|
| 67 |
+
def modifier_veto(tokens_a, tokens_b):
|
| 68 |
+
mods_a = get_modifiers(tokens_a)
|
| 69 |
+
mods_b = get_modifiers(tokens_b)
|
| 70 |
+
|
| 71 |
+
# 1. Check modifier categories
|
| 72 |
+
for cat in set(mods_a) & set(mods_b):
|
| 73 |
+
vals_a = set(mods_a[cat])
|
| 74 |
+
vals_b = set(mods_b[cat])
|
| 75 |
+
if vals_a != vals_b:
|
| 76 |
+
return True, f"Differ on {cat}: {vals_a} vs {vals_b}"
|
| 77 |
+
|
| 78 |
+
# 2. Check ingredient nouns
|
| 79 |
+
ing_a = {t for t in tokens_a if t in INGREDIENT_NOUNS}
|
| 80 |
+
ing_b = {t for t in tokens_b if t in INGREDIENT_NOUNS}
|
| 81 |
+
if ing_a and ing_b and ing_a != ing_b:
|
| 82 |
+
return True, f"Differ on INGREDIENT: {ing_a} vs {ing_b}"
|
| 83 |
+
|
| 84 |
+
return False, ""
|
| 85 |
+
|
| 86 |
+
def is_french(name):
|
| 87 |
+
nl = name.lower()
|
| 88 |
+
return any(m in nl for m in FRENCH_MARKERS)
|
| 89 |
+
|
| 90 |
+
def run_phase_2_candidate_gen():
|
| 91 |
+
print("Loading named_groups.json...")
|
| 92 |
+
with open('named_groups.json', 'r', encoding='utf-8') as f:
|
| 93 |
+
groups = json.load(f)
|
| 94 |
+
|
| 95 |
+
names = [g['normalized_key'] for g in groups]
|
| 96 |
+
tokenized = {n: tokenize(n) for n in names}
|
| 97 |
+
is_fr = {n: is_french(n) for n in names}
|
| 98 |
+
|
| 99 |
+
print(f"Total unique names: {len(names)}")
|
| 100 |
+
|
| 101 |
+
edges = set()
|
| 102 |
+
|
| 103 |
+
# ── PASS A: Jaccard (Same Language / General) ────────────────────────────
|
| 104 |
+
print("Running Pass A: Jaccard similarity...")
|
| 105 |
+
jaccard_candidates = 0
|
| 106 |
+
vetoed = 0
|
| 107 |
+
for i in range(len(names)):
|
| 108 |
+
for j in range(i + 1, len(names)):
|
| 109 |
+
na, nb = names[i], names[j]
|
| 110 |
+
ta, tb = tokenized[na], tokenized[nb]
|
| 111 |
+
|
| 112 |
+
if not ta or not tb: continue
|
| 113 |
+
|
| 114 |
+
inter = set(ta) & set(tb)
|
| 115 |
+
union = set(ta) | set(tb)
|
| 116 |
+
j = len(inter) / len(union) if union else 0
|
| 117 |
+
|
| 118 |
+
if j >= JACCARD_THRESHOLD:
|
| 119 |
+
jaccard_candidates += 1
|
| 120 |
+
is_vetoed, _ = modifier_veto(ta, tb)
|
| 121 |
+
if not is_vetoed:
|
| 122 |
+
edges.add((na, nb))
|
| 123 |
+
else:
|
| 124 |
+
vetoed += 1
|
| 125 |
+
|
| 126 |
+
print(f" Jaccard >= {JACCARD_THRESHOLD} pairs: {jaccard_candidates}")
|
| 127 |
+
print(f" Vetoed by modifiers: {vetoed}")
|
| 128 |
+
print(f" Jaccard pairs accepted: {jaccard_candidates - vetoed}")
|
| 129 |
+
|
| 130 |
+
# ── PASS B: Bilingual Embeddings ──────────────────────────────────────────
|
| 131 |
+
print("\nRunning Pass B: Bilingual Embeddings...")
|
| 132 |
+
cross_lang_pairs = [(i, j) for i in range(len(names)) for j in range(i + 1, len(names))
|
| 133 |
+
if is_fr[names[i]] != is_fr[names[j]]]
|
| 134 |
+
|
| 135 |
+
print(f" Identified {len(cross_lang_pairs)} cross-language pairs to test.")
|
| 136 |
+
|
| 137 |
+
if cross_lang_pairs:
|
| 138 |
+
print(" Generating embeddings (fastembed)...")
|
| 139 |
+
model = TextEmbedding("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
| 140 |
+
embeddings = np.array(list(model.embed(names)))
|
| 141 |
+
# Normalize embeddings to calculate cosine similarity via dot product
|
| 142 |
+
norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
|
| 143 |
+
embeddings = embeddings / norms
|
| 144 |
+
|
| 145 |
+
bilingual_accepted = 0
|
| 146 |
+
for i, j in cross_lang_pairs:
|
| 147 |
+
na, nb = names[i], names[j]
|
| 148 |
+
sim = np.dot(embeddings[i], embeddings[j])
|
| 149 |
+
|
| 150 |
+
if sim >= EMBEDDING_THRESHOLD:
|
| 151 |
+
# Add without English modifier veto (because one is French)
|
| 152 |
+
edges.add((na, nb))
|
| 153 |
+
bilingual_accepted += 1
|
| 154 |
+
|
| 155 |
+
print(f" Bilingual pairs accepted (sim >= {EMBEDDING_THRESHOLD}): {bilingual_accepted}")
|
| 156 |
+
|
| 157 |
+
# ── Connected Components ──────────────────────────────────────────────────
|
| 158 |
+
print("\nBuilding candidate clusters (Connected Components)...")
|
| 159 |
+
|
| 160 |
+
adj = defaultdict(set)
|
| 161 |
+
for u, v in edges:
|
| 162 |
+
adj[u].add(v)
|
| 163 |
+
adj[v].add(u)
|
| 164 |
+
|
| 165 |
+
visited = set()
|
| 166 |
+
clusters = []
|
| 167 |
+
|
| 168 |
+
for node in names:
|
| 169 |
+
if node not in visited and node in adj:
|
| 170 |
+
cluster = set()
|
| 171 |
+
stack = [node]
|
| 172 |
+
while stack:
|
| 173 |
+
curr = stack.pop()
|
| 174 |
+
if curr not in cluster:
|
| 175 |
+
cluster.add(curr)
|
| 176 |
+
stack.extend(adj[curr] - cluster)
|
| 177 |
+
visited.update(cluster)
|
| 178 |
+
clusters.append(sorted(list(cluster)))
|
| 179 |
+
|
| 180 |
+
# Add isolated nodes as their own cluster of 1 (so they aren't lost)
|
| 181 |
+
for node in names:
|
| 182 |
+
if node not in visited:
|
| 183 |
+
clusters.append([node])
|
| 184 |
+
|
| 185 |
+
print(f"Total clusters for LLM: {len(clusters)}")
|
| 186 |
+
multi_clusters = [c for c in clusters if len(c) > 1]
|
| 187 |
+
print(f" Singletons: {len(clusters) - len(multi_clusters)}")
|
| 188 |
+
print(f" Multi-item clusters (need judging): {len(multi_clusters)}")
|
| 189 |
+
|
| 190 |
+
# Save the clusters
|
| 191 |
+
with open('candidate_clusters.json', 'w', encoding='utf-8') as f:
|
| 192 |
+
json.dump(clusters, f, indent=2, ensure_ascii=False)
|
| 193 |
+
|
| 194 |
+
print("Saved candidate_clusters.json")
|
| 195 |
+
|
| 196 |
+
if __name__ == "__main__":
|
| 197 |
+
run_phase_2_candidate_gen()
|
OpenDB_Compliments_Merged/canonical_products.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cbd92ffe6f14e449d65e027d32ba94069ff7367083727d9eb9c597c82bdf14a8
|
| 3 |
+
size 28351
|
OpenDB_Compliments_Merged/deduplicated_comparison.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
OpenDB_Compliments_Merged/generate_outputs.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
generate_outputs.py — Phase 4: Output Generation
|
| 3 |
+
|
| 4 |
+
Reads: final_groups.json
|
| 5 |
+
original.parquet (read-only, for original product names)
|
| 6 |
+
Writes: canonical_products.parquet — deduplicated product list
|
| 7 |
+
product_mapping.parquet — every code → canonical_product_id
|
| 8 |
+
deduplicated_comparison.csv — side-by-side view for human review
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
FINAL_IN = "final_groups.json"
|
| 15 |
+
ORIGINAL_IN = "original.parquet"
|
| 16 |
+
CANON_OUT = "canonical_products.parquet"
|
| 17 |
+
MAPPING_OUT = "product_mapping.parquet"
|
| 18 |
+
COMPARISON_OUT = "deduplicated_comparison.csv"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
print(f"Loading {FINAL_IN}...")
|
| 23 |
+
with open(FINAL_IN, "r", encoding="utf-8") as f:
|
| 24 |
+
final_groups: list = json.load(f)
|
| 25 |
+
print(f" {len(final_groups)} canonical groups")
|
| 26 |
+
|
| 27 |
+
print(f"Loading {ORIGINAL_IN}...")
|
| 28 |
+
df_orig = pd.read_parquet(ORIGINAL_IN)
|
| 29 |
+
print(f" {len(df_orig)} original rows")
|
| 30 |
+
|
| 31 |
+
# ── Build canonical_products table ─────────────────────────────────────────
|
| 32 |
+
canonical_rows = []
|
| 33 |
+
mapping_rows = []
|
| 34 |
+
|
| 35 |
+
for cid, group in enumerate(final_groups, start=1):
|
| 36 |
+
canon_name = group["canonical_name"]
|
| 37 |
+
nutr = group.get("avg_nutrition", {})
|
| 38 |
+
num_codes = len(group.get("codes", []))
|
| 39 |
+
|
| 40 |
+
canonical_rows.append({
|
| 41 |
+
"canonical_product_id": cid,
|
| 42 |
+
"canonical_name" : canon_name,
|
| 43 |
+
"num_codes" : num_codes,
|
| 44 |
+
"energy_kcal_100g" : nutr.get("energy_kcal_100g"),
|
| 45 |
+
"fat_100g" : nutr.get("fat_100g"),
|
| 46 |
+
"proteins_100g" : nutr.get("proteins_100g"),
|
| 47 |
+
"sugars_100g" : nutr.get("sugars_100g"),
|
| 48 |
+
"carbohydrates_100g" : nutr.get("carbohydrates_100g"),
|
| 49 |
+
})
|
| 50 |
+
|
| 51 |
+
for code in group["codes"]:
|
| 52 |
+
mapping_rows.append({
|
| 53 |
+
"code" : str(code),
|
| 54 |
+
"canonical_product_id": cid,
|
| 55 |
+
"canonical_name" : canon_name,
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
df_canon = pd.DataFrame(canonical_rows)
|
| 59 |
+
df_mapping = pd.DataFrame(mapping_rows)
|
| 60 |
+
|
| 61 |
+
# ── Integrity check ────────────────────────────────────────────────────────
|
| 62 |
+
print("\nRunning integrity checks...")
|
| 63 |
+
orig_codes = set(df_orig["code"].astype(str))
|
| 64 |
+
map_codes = set(df_mapping["code"])
|
| 65 |
+
|
| 66 |
+
missing_in_map = orig_codes - map_codes
|
| 67 |
+
extra_in_map = map_codes - orig_codes
|
| 68 |
+
duplicate_codes = df_mapping[df_mapping.duplicated("code", keep=False)]
|
| 69 |
+
|
| 70 |
+
if missing_in_map:
|
| 71 |
+
print(f" ⚠️ {len(missing_in_map)} original codes NOT in mapping!")
|
| 72 |
+
else:
|
| 73 |
+
print(" ✅ All original codes present in mapping.")
|
| 74 |
+
|
| 75 |
+
if extra_in_map:
|
| 76 |
+
print(f" ⚠️ {len(extra_in_map)} extra codes in mapping (not in original)!")
|
| 77 |
+
else:
|
| 78 |
+
print(" ✅ No extra codes in mapping.")
|
| 79 |
+
|
| 80 |
+
if len(duplicate_codes) > 0:
|
| 81 |
+
print(f" ⚠️ {len(duplicate_codes)} duplicate codes found in mapping!")
|
| 82 |
+
else:
|
| 83 |
+
print(" ✅ All codes in mapping are unique.")
|
| 84 |
+
|
| 85 |
+
# ── Save parquets ─────────────────────────────────────────────────────────
|
| 86 |
+
df_canon.to_parquet(CANON_OUT, index=False)
|
| 87 |
+
df_mapping.to_parquet(MAPPING_OUT, index=False)
|
| 88 |
+
print(f"\n Saved → {CANON_OUT} ({len(df_canon)} canonical products)")
|
| 89 |
+
print(f" Saved → {MAPPING_OUT} ({len(df_mapping)} code mappings)")
|
| 90 |
+
|
| 91 |
+
# ── Build comparison CSV ───────────────────────────────────────────────────
|
| 92 |
+
# Join original data with mapping
|
| 93 |
+
df_orig_str = df_orig.copy()
|
| 94 |
+
df_orig_str["code"] = df_orig_str["code"].astype(str)
|
| 95 |
+
|
| 96 |
+
df_comparison = df_orig_str.merge(df_mapping[["code", "canonical_product_id", "canonical_name"]], on="code", how="left")
|
| 97 |
+
|
| 98 |
+
# Parse nutriments JSON to flat columns for the CSV
|
| 99 |
+
import json as _json
|
| 100 |
+
|
| 101 |
+
def get_nutr_val(nutr_json, key):
|
| 102 |
+
if not nutr_json or pd.isna(nutr_json):
|
| 103 |
+
return None
|
| 104 |
+
try:
|
| 105 |
+
d = _json.loads(nutr_json)
|
| 106 |
+
return d.get(key)
|
| 107 |
+
except Exception:
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
df_comparison["energy_kcal_100g"] = df_comparison["nutriments"].apply(lambda x: get_nutr_val(x, "energy-kcal_100g"))
|
| 111 |
+
df_comparison["fat_100g"] = df_comparison["nutriments"].apply(lambda x: get_nutr_val(x, "fat_100g"))
|
| 112 |
+
df_comparison["proteins_100g"] = df_comparison["nutriments"].apply(lambda x: get_nutr_val(x, "proteins_100g"))
|
| 113 |
+
df_comparison["sugars_100g"] = df_comparison["nutriments"].apply(lambda x: get_nutr_val(x, "sugars_100g"))
|
| 114 |
+
|
| 115 |
+
# Select & order columns for readability
|
| 116 |
+
csv_cols = [
|
| 117 |
+
"canonical_product_id",
|
| 118 |
+
"canonical_name",
|
| 119 |
+
"product_name", # original messy name
|
| 120 |
+
"code",
|
| 121 |
+
"brand",
|
| 122 |
+
"serving_size",
|
| 123 |
+
"energy_kcal_100g",
|
| 124 |
+
"fat_100g",
|
| 125 |
+
"proteins_100g",
|
| 126 |
+
"sugars_100g",
|
| 127 |
+
]
|
| 128 |
+
df_csv = df_comparison[csv_cols].sort_values(["canonical_name", "product_name"])
|
| 129 |
+
df_csv.to_csv(COMPARISON_OUT, index=False, encoding="utf-8-sig")
|
| 130 |
+
print(f" Saved → {COMPARISON_OUT} ({len(df_csv)} rows)")
|
| 131 |
+
|
| 132 |
+
# ── Print summary ─────────────────────────────────────────────────────────
|
| 133 |
+
print("\n=== FINAL RESULTS ===")
|
| 134 |
+
print(f"Original rows : {len(df_orig)}")
|
| 135 |
+
print(f"Canonical products : {len(df_canon)}")
|
| 136 |
+
reduction = (1 - len(df_canon) / len(df_orig)) * 100
|
| 137 |
+
print(f"Deduplication rate : {reduction:.1f}%")
|
| 138 |
+
print()
|
| 139 |
+
print("Top 10 largest groups:")
|
| 140 |
+
top10 = df_canon.sort_values("num_codes", ascending=False).head(10)
|
| 141 |
+
print(top10[["canonical_name", "num_codes"]].to_string(index=False))
|
| 142 |
+
|
| 143 |
+
print("\n✅ Phase 4 complete. All outputs generated.")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
main()
|
OpenDB_Compliments_Merged/llm_grouper.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from llm_utils import call_llm
|
| 5 |
+
|
| 6 |
+
def merge_groups_data(members, named_groups_dict, canonical_name):
|
| 7 |
+
"""Combines the data from multiple Phase 1 groups into a single canonical group."""
|
| 8 |
+
all_codes = []
|
| 9 |
+
all_original_names = []
|
| 10 |
+
nutri_sums = {'energy_kcal_100g': 0, 'fat_100g': 0, 'proteins_100g': 0, 'sugars_100g': 0, 'carbohydrates_100g': 0}
|
| 11 |
+
nutri_counts = {k: 0 for k in nutri_sums}
|
| 12 |
+
|
| 13 |
+
for m in members:
|
| 14 |
+
g = named_groups_dict[m]
|
| 15 |
+
all_codes.extend(g['codes'])
|
| 16 |
+
all_original_names.extend(g['original_names'])
|
| 17 |
+
for k, v in g['avg_nutrition'].items():
|
| 18 |
+
nutri_sums[k] += v
|
| 19 |
+
nutri_counts[k] += 1
|
| 20 |
+
|
| 21 |
+
avg_nutri = {}
|
| 22 |
+
for k, v in nutri_sums.items():
|
| 23 |
+
if nutri_counts[k] > 0:
|
| 24 |
+
avg_nutri[k] = v / nutri_counts[k]
|
| 25 |
+
|
| 26 |
+
return {
|
| 27 |
+
"canonical_name": canonical_name,
|
| 28 |
+
"codes": list(set(all_codes)),
|
| 29 |
+
"original_names": list(set(all_original_names)),
|
| 30 |
+
"avg_nutrition": avg_nutri
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
def run_phase_3_llm_grouper():
|
| 34 |
+
print("Loading candidate_clusters.json and named_groups.json...")
|
| 35 |
+
with open('candidate_clusters.json', 'r', encoding='utf-8') as f:
|
| 36 |
+
clusters = json.load(f)
|
| 37 |
+
with open('named_groups.json', 'r', encoding='utf-8') as f:
|
| 38 |
+
named_groups = json.load(f)
|
| 39 |
+
|
| 40 |
+
named_groups_dict = {g['normalized_key']: g for g in named_groups}
|
| 41 |
+
|
| 42 |
+
singletons = [c for c in clusters if len(c) == 1]
|
| 43 |
+
multi_clusters = [c for c in clusters if len(c) > 1]
|
| 44 |
+
|
| 45 |
+
print(f"Total singletons (auto-accepted): {len(singletons)}")
|
| 46 |
+
print(f"Total multi-clusters to judge: {len(multi_clusters)}")
|
| 47 |
+
|
| 48 |
+
final_groups = []
|
| 49 |
+
|
| 50 |
+
# Process singletons
|
| 51 |
+
for s in singletons:
|
| 52 |
+
key = s[0]
|
| 53 |
+
display = named_groups_dict[key]['display_name']
|
| 54 |
+
final_groups.append(merge_groups_data([key], named_groups_dict, display.title()))
|
| 55 |
+
|
| 56 |
+
# Process multi-clusters via LLM
|
| 57 |
+
BATCH_SIZE = 10
|
| 58 |
+
total_batches = (len(multi_clusters) + BATCH_SIZE - 1) // BATCH_SIZE
|
| 59 |
+
|
| 60 |
+
system_prompt = """You are a product deduplication expert for a Canadian grocery store.
|
| 61 |
+
Your job is to take clusters of similar product names and group the ones that are EXACTLY the same product.
|
| 62 |
+
Be conservative — if unsure, keep them SEPARATE.
|
| 63 |
+
|
| 64 |
+
RULES:
|
| 65 |
+
1. SAME product = same item, just different formatting, word order, or language:
|
| 66 |
+
MERGE: "Cottage Cheese" + "COTTAGE CHEESE" + "Fromage Cottage"
|
| 67 |
+
MERGE: "Black Forest Ham" + "Natural Black Forest Ham" + "Black forest ham"
|
| 68 |
+
MERGE: "Extra Lean Ground Beef" + "Compliments Extra Lean Ground Beef"
|
| 69 |
+
|
| 70 |
+
2. DIFFERENCES = ALWAYS SEPARATE:
|
| 71 |
+
SEPARATE: Flavour (Cherry vs Lime vs Strawberry)
|
| 72 |
+
SEPARATE: Texture (Smooth vs Crunchy, Sliced vs Whole)
|
| 73 |
+
SEPARATE: Heat (Hot vs Mild)
|
| 74 |
+
SEPARATE: Animal/Ingredient (Chicken vs Turkey, Canola vs Sunflower)
|
| 75 |
+
SEPARATE: Fat/Diet (2% vs 7%, Diet vs Regular)
|
| 76 |
+
SEPARATE: Process (Vanilla vs Artificial Vanilla)
|
| 77 |
+
SEPARATE: Salt (Salted vs Unsalted)
|
| 78 |
+
|
| 79 |
+
When in doubt -> SEPARATE.
|
| 80 |
+
Output JSON format ONLY:
|
| 81 |
+
[
|
| 82 |
+
{
|
| 83 |
+
"cluster_id": "the provided cluster id",
|
| 84 |
+
"groups": [
|
| 85 |
+
{
|
| 86 |
+
"canonical_name": "English Title Case Name",
|
| 87 |
+
"members": ["exact name 1", "exact name 2"]
|
| 88 |
+
}
|
| 89 |
+
]
|
| 90 |
+
}
|
| 91 |
+
]
|
| 92 |
+
Every input name must appear in exactly one subgroup.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
for i in range(0, len(multi_clusters), BATCH_SIZE):
|
| 96 |
+
batch = multi_clusters[i:i+BATCH_SIZE]
|
| 97 |
+
batch_num = (i // BATCH_SIZE) + 1
|
| 98 |
+
|
| 99 |
+
prompt_data = []
|
| 100 |
+
for j, cluster in enumerate(batch):
|
| 101 |
+
prompt_data.append({
|
| 102 |
+
"cluster_id": f"batch_{batch_num}_cluster_{j}",
|
| 103 |
+
"names_to_group": cluster
|
| 104 |
+
})
|
| 105 |
+
|
| 106 |
+
user_prompt = "Process these clusters:\n" + json.dumps(prompt_data, indent=2, ensure_ascii=False)
|
| 107 |
+
|
| 108 |
+
print(f" Batch {batch_num}/{total_batches} ({len(batch)} clusters)...", end="", flush=True)
|
| 109 |
+
try:
|
| 110 |
+
data = call_llm(user_prompt, system_prompt)
|
| 111 |
+
|
| 112 |
+
# Process LLM decisions
|
| 113 |
+
for cluster_out in data:
|
| 114 |
+
for grp in cluster_out.get('groups', []):
|
| 115 |
+
canon = grp.get('canonical_name', 'Unknown')
|
| 116 |
+
members = grp.get('members', [])
|
| 117 |
+
# Filter out hallucinations
|
| 118 |
+
valid_members = [m for m in members if m in named_groups_dict]
|
| 119 |
+
if valid_members:
|
| 120 |
+
final_groups.append(merge_groups_data(valid_members, named_groups_dict, canon))
|
| 121 |
+
print(" ✓")
|
| 122 |
+
except Exception as e:
|
| 123 |
+
print(f" ERROR: {e}")
|
| 124 |
+
# Fallback: keep them separate
|
| 125 |
+
for cluster in batch:
|
| 126 |
+
for member in cluster:
|
| 127 |
+
display = named_groups_dict[member]['display_name']
|
| 128 |
+
final_groups.append(merge_groups_data([member], named_groups_dict, display.title()))
|
| 129 |
+
|
| 130 |
+
print("\nSaving final_groups.json...")
|
| 131 |
+
with open('final_groups.json', 'w', encoding='utf-8') as f:
|
| 132 |
+
json.dump(final_groups, f, indent=2, ensure_ascii=False)
|
| 133 |
+
|
| 134 |
+
print(f"Final canonical groups: {len(final_groups)}")
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
run_phase_3_llm_grouper()
|
OpenDB_Compliments_Merged/llm_utils.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
llm_utils.py — Shared LLM load balancer for the deduplication pipeline.
|
| 3 |
+
|
| 4 |
+
Provider priority:
|
| 5 |
+
1. Ollama (local) — primary, no rate limits, no cost
|
| 6 |
+
2. Groq — backup, fast, 100K daily token limit
|
| 7 |
+
3. NVIDIA — backup, rate limited
|
| 8 |
+
|
| 9 |
+
Usage:
|
| 10 |
+
from llm_utils import call_llm
|
| 11 |
+
result = call_llm("Your prompt here") # returns parsed JSON or raises
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
import random
|
| 17 |
+
import os
|
| 18 |
+
import httpx
|
| 19 |
+
from openai import OpenAI
|
| 20 |
+
|
| 21 |
+
# ── Provider configuration ─────────────────────────────────────────────────────
|
| 22 |
+
PROVIDERS = [
|
| 23 |
+
{
|
| 24 |
+
"name": "Groq",
|
| 25 |
+
"client": OpenAI(
|
| 26 |
+
base_url="https://api.groq.com/openai/v1",
|
| 27 |
+
api_key=os.environ.get("GROQ_API_KEY", "your-groq-api-key-here"),
|
| 28 |
+
timeout=httpx.Timeout(30.0),
|
| 29 |
+
),
|
| 30 |
+
"model": "llama-3.3-70b-versatile",
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"name": "OpenRouter",
|
| 34 |
+
"client": OpenAI(
|
| 35 |
+
base_url="https://openrouter.ai/api/v1",
|
| 36 |
+
api_key=os.environ.get("OPENROUTER_API_KEY", "your-openrouter-api-key-here"),
|
| 37 |
+
timeout=httpx.Timeout(60.0),
|
| 38 |
+
),
|
| 39 |
+
"model": "meta-llama/llama-3.1-8b-instruct",
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"name": "NVIDIA",
|
| 43 |
+
"client": OpenAI(
|
| 44 |
+
base_url="https://integrate.api.nvidia.com/v1",
|
| 45 |
+
api_key=os.environ.get("NVIDIA_API_KEY", "your-nvidia-api-key-here"),
|
| 46 |
+
timeout=httpx.Timeout(30.0),
|
| 47 |
+
),
|
| 48 |
+
"model": "meta/llama-3.1-70b-instruct",
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"name": "Ollama (Local)",
|
| 52 |
+
"client": OpenAI(
|
| 53 |
+
base_url="http://localhost:11434/v1",
|
| 54 |
+
api_key="ollama",
|
| 55 |
+
timeout=httpx.Timeout(300.0),
|
| 56 |
+
),
|
| 57 |
+
"model": "llama3.1",
|
| 58 |
+
},
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
SYSTEM_PROMPT = (
|
| 62 |
+
"You are a helpful data processing assistant. "
|
| 63 |
+
"Output ONLY valid JSON with no markdown, no code fences, no extra text."
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _strip_fences(text: str) -> str:
|
| 68 |
+
"""Extract JSON array or object from text."""
|
| 69 |
+
text = text.strip()
|
| 70 |
+
# Find the first [ or { and the last ] or }
|
| 71 |
+
first_idx = min([i for i, c in enumerate(text) if c in '[{'] or [0])
|
| 72 |
+
last_idx = max([i for i, c in enumerate(text) if c in ']}'] or [len(text)-1])
|
| 73 |
+
return text[first_idx:last_idx+1].strip()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def call_llm(prompt: str, system_prompt: str = None, max_retries: int = 3) -> any:
|
| 77 |
+
"""
|
| 78 |
+
Send a prompt to the LLM and return the parsed JSON response.
|
| 79 |
+
|
| 80 |
+
Tries each provider in order. If all providers fail on an attempt,
|
| 81 |
+
backs off exponentially before the next attempt.
|
| 82 |
+
|
| 83 |
+
Raises RuntimeError if all retries across all providers are exhausted.
|
| 84 |
+
"""
|
| 85 |
+
sys_prompt = system_prompt if system_prompt else SYSTEM_PROMPT
|
| 86 |
+
for attempt in range(1, max_retries + 1):
|
| 87 |
+
for provider in PROVIDERS:
|
| 88 |
+
try:
|
| 89 |
+
completion = provider["client"].chat.completions.create(
|
| 90 |
+
model=provider["model"],
|
| 91 |
+
messages=[
|
| 92 |
+
{"role": "system", "content": sys_prompt},
|
| 93 |
+
{"role": "user", "content": prompt},
|
| 94 |
+
],
|
| 95 |
+
temperature=0,
|
| 96 |
+
top_p=0.95,
|
| 97 |
+
max_tokens=4096,
|
| 98 |
+
stream=False,
|
| 99 |
+
)
|
| 100 |
+
raw = completion.choices[0].message.content or ""
|
| 101 |
+
cleaned = _strip_fences(raw)
|
| 102 |
+
parsed = json.loads(cleaned)
|
| 103 |
+
return parsed
|
| 104 |
+
|
| 105 |
+
except json.JSONDecodeError as e:
|
| 106 |
+
print(f" [{provider['name']}] JSON parse error: {e}")
|
| 107 |
+
print(f" Raw response: {raw[:300]}")
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f" [{provider['name']}] Error: {e}")
|
| 110 |
+
|
| 111 |
+
backoff = attempt * 10
|
| 112 |
+
print(f" All providers failed on attempt {attempt}/{max_retries}. Backing off {backoff}s...")
|
| 113 |
+
time.sleep(backoff)
|
| 114 |
+
|
| 115 |
+
raise RuntimeError("All LLM providers exhausted with no successful response.")
|
OpenDB_Compliments_Merged/preprocess.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
import unicodedata
|
| 5 |
+
|
| 6 |
+
BRAND_PREFIXES = [
|
| 7 |
+
'compliments',
|
| 8 |
+
'our compliments',
|
| 9 |
+
'nos compliments',
|
| 10 |
+
'naturally simple',
|
| 11 |
+
'sensations compliments',
|
| 12 |
+
'sensations',
|
| 13 |
+
'compliment'
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
def fix_mojibake(text):
|
| 17 |
+
"""Fix common UTF-8 encoding artifacts found in the dataset."""
|
| 18 |
+
if not isinstance(text, str):
|
| 19 |
+
return text
|
| 20 |
+
try:
|
| 21 |
+
# If it was double-encoded UTF-8 read as latin-1
|
| 22 |
+
return text.encode('latin1').decode('utf-8')
|
| 23 |
+
except (UnicodeEncodeError, UnicodeDecodeError):
|
| 24 |
+
# Fallback to manual replacements if strict decoding fails
|
| 25 |
+
return text.replace('é', 'é').replace('è', 'è').replace('ô', 'ô').replace('â', 'â').replace('Γ£ô', '')
|
| 26 |
+
|
| 27 |
+
def strip_accents(text):
|
| 28 |
+
return ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')
|
| 29 |
+
|
| 30 |
+
def generate_comparison_key(name):
|
| 31 |
+
"""Generate a highly normalized string used purely for exact-matching."""
|
| 32 |
+
if not isinstance(name, str) or not name.strip():
|
| 33 |
+
return ""
|
| 34 |
+
|
| 35 |
+
s = name.lower().strip()
|
| 36 |
+
s = fix_mojibake(s)
|
| 37 |
+
s = strip_accents(s)
|
| 38 |
+
|
| 39 |
+
# Strip non-alphanumeric characters
|
| 40 |
+
s = re.sub(r'[^\w\s]', ' ', s)
|
| 41 |
+
s = re.sub(r'\s+', ' ', s).strip()
|
| 42 |
+
|
| 43 |
+
# Remove brand prefixes
|
| 44 |
+
for brand in BRAND_PREFIXES:
|
| 45 |
+
if s.startswith(brand + ' '):
|
| 46 |
+
s = s[len(brand)+1:].strip()
|
| 47 |
+
|
| 48 |
+
# Simple plural normalization: if last word ends in 's' and isn't 'ss', strip it
|
| 49 |
+
words = s.split()
|
| 50 |
+
if words:
|
| 51 |
+
last = words[-1]
|
| 52 |
+
if len(last) > 3 and last.endswith('s') and not last.endswith('ss'):
|
| 53 |
+
words[-1] = last[:-1]
|
| 54 |
+
s = ' '.join(words)
|
| 55 |
+
|
| 56 |
+
return s
|
| 57 |
+
|
| 58 |
+
def clean_display_name(name):
|
| 59 |
+
"""Clean the name for display purposes (keep accents and plurals, just fix encoding)."""
|
| 60 |
+
if not isinstance(name, str):
|
| 61 |
+
return ""
|
| 62 |
+
s = fix_mojibake(name)
|
| 63 |
+
s = re.sub(r'\s+', ' ', s).strip()
|
| 64 |
+
return s
|
| 65 |
+
|
| 66 |
+
def run_phase_1():
|
| 67 |
+
print("Loading original.parquet...")
|
| 68 |
+
df = pd.read_parquet('original.parquet')
|
| 69 |
+
total_original = len(df)
|
| 70 |
+
|
| 71 |
+
# Drop completely unnamed rows
|
| 72 |
+
df = df[df['product_name'].notna() & (df['product_name'].str.strip() != '')].copy()
|
| 73 |
+
total_named = len(df)
|
| 74 |
+
|
| 75 |
+
print(f"Dropped {total_original - total_named} unnamed products.")
|
| 76 |
+
print(f"Processing {total_named} named products.")
|
| 77 |
+
|
| 78 |
+
# Create the display name and comparison key
|
| 79 |
+
df['clean_name'] = df['product_name'].apply(clean_display_name)
|
| 80 |
+
df['compare_key'] = df['product_name'].apply(generate_comparison_key)
|
| 81 |
+
|
| 82 |
+
# Save the working copy (original is untouched)
|
| 83 |
+
df.to_parquet('working.parquet')
|
| 84 |
+
|
| 85 |
+
# Group by exact match on compare_key
|
| 86 |
+
grouped = df.groupby('compare_key')
|
| 87 |
+
|
| 88 |
+
groups_out = []
|
| 89 |
+
for key, group in grouped:
|
| 90 |
+
if not key:
|
| 91 |
+
continue
|
| 92 |
+
# Use the most frequent clean_name as the representative display name
|
| 93 |
+
display_name = group['clean_name'].value_counts().index[0]
|
| 94 |
+
|
| 95 |
+
# Aggregate nutrition (mean of available numerical data)
|
| 96 |
+
nutri_cols = ['energy_kcal_100g', 'fat_100g', 'proteins_100g', 'sugars_100g', 'carbohydrates_100g']
|
| 97 |
+
avg_nutri = {}
|
| 98 |
+
for col in nutri_cols:
|
| 99 |
+
if col in group.columns:
|
| 100 |
+
val = group[col].mean()
|
| 101 |
+
if pd.notna(val):
|
| 102 |
+
avg_nutri[col] = float(val)
|
| 103 |
+
|
| 104 |
+
groups_out.append({
|
| 105 |
+
"normalized_key": key,
|
| 106 |
+
"display_name": display_name,
|
| 107 |
+
"codes": group['code'].tolist(),
|
| 108 |
+
"original_names": group['product_name'].unique().tolist(),
|
| 109 |
+
"avg_nutrition": avg_nutri
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
print(f"Exact match grouping reduced {total_named} named products to {len(groups_out)} unique groups.")
|
| 113 |
+
|
| 114 |
+
with open('named_groups.json', 'w', encoding='utf-8') as f:
|
| 115 |
+
json.dump(groups_out, f, indent=2, ensure_ascii=False)
|
| 116 |
+
|
| 117 |
+
print("Saved working.parquet and named_groups.json")
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
run_phase_1()
|
OpenDB_Compliments_Merged/product_mapping.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:005b5c808e58887322d8fb1212f6106e696a40a774c011a4aab7805df1d5a878
|
| 3 |
+
size 37460
|