import pandas as pd import json import re import unicodedata BRAND_PREFIXES = [ 'compliments', 'our compliments', 'nos compliments', 'naturally simple', 'sensations compliments', 'sensations', 'compliment' ] def fix_mojibake(text): """Fix common UTF-8 encoding artifacts found in the dataset.""" if not isinstance(text, str): return text try: # If it was double-encoded UTF-8 read as latin-1 return text.encode('latin1').decode('utf-8') except (UnicodeEncodeError, UnicodeDecodeError): # Fallback to manual replacements if strict decoding fails return text.replace('é', 'é').replace('è', 'è').replace('ô', 'ô').replace('â', 'â').replace('Γ£ô', '') def strip_accents(text): return ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn') def generate_comparison_key(name): """Generate a highly normalized string used purely for exact-matching.""" if not isinstance(name, str) or not name.strip(): return "" s = name.lower().strip() s = fix_mojibake(s) s = strip_accents(s) # Strip non-alphanumeric characters s = re.sub(r'[^\w\s]', ' ', s) s = re.sub(r'\s+', ' ', s).strip() # Remove brand prefixes for brand in BRAND_PREFIXES: if s.startswith(brand + ' '): s = s[len(brand)+1:].strip() # Simple plural normalization: if last word ends in 's' and isn't 'ss', strip it words = s.split() if words: last = words[-1] if len(last) > 3 and last.endswith('s') and not last.endswith('ss'): words[-1] = last[:-1] s = ' '.join(words) return s def clean_display_name(name): """Clean the name for display purposes (keep accents and plurals, just fix encoding).""" if not isinstance(name, str): return "" s = fix_mojibake(name) s = re.sub(r'\s+', ' ', s).strip() return s def run_phase_1(): print("Loading original.parquet...") df = pd.read_parquet('original.parquet') total_original = len(df) # Drop completely unnamed rows df = df[df['product_name'].notna() & (df['product_name'].str.strip() != '')].copy() total_named = len(df) print(f"Dropped {total_original - total_named} unnamed products.") print(f"Processing {total_named} named products.") # Create the display name and comparison key df['clean_name'] = df['product_name'].apply(clean_display_name) df['compare_key'] = df['product_name'].apply(generate_comparison_key) # Save the working copy (original is untouched) df.to_parquet('working.parquet') # Group by exact match on compare_key grouped = df.groupby('compare_key') groups_out = [] for key, group in grouped: if not key: continue # Use the most frequent clean_name as the representative display name display_name = group['clean_name'].value_counts().index[0] # Aggregate nutrition (mean of available numerical data) nutri_cols = ['energy_kcal_100g', 'fat_100g', 'proteins_100g', 'sugars_100g', 'carbohydrates_100g'] avg_nutri = {} for col in nutri_cols: if col in group.columns: val = group[col].mean() if pd.notna(val): avg_nutri[col] = float(val) groups_out.append({ "normalized_key": key, "display_name": display_name, "codes": group['code'].tolist(), "original_names": group['product_name'].unique().tolist(), "avg_nutrition": avg_nutri }) print(f"Exact match grouping reduced {total_named} named products to {len(groups_out)} unique groups.") with open('named_groups.json', 'w', encoding='utf-8') as f: json.dump(groups_out, f, indent=2, ensure_ascii=False) print("Saved working.parquet and named_groups.json") if __name__ == "__main__": run_phase_1()