{ "cells": [ { "cell_type": "markdown", "id": "640208dc", "metadata": { "tags": [ "papermill-error-cell-tag" ] }, "source": [ "An Exception was encountered at 'In [2]'." ] }, { "cell_type": "markdown", "id": "8c387081", "metadata": { "papermill": { "duration": 0.012814, "end_time": "2026-08-05T13:26:48.860275+00:00", "exception": false, "start_time": "2026-08-05T13:26:48.847461+00:00", "status": "completed" }, "tags": [] }, "source": [ "# Phase 2 — Semantic Normalization / Identity Extraction\n", "\n", "**Goal:** Normalize brands, extract identity attributes from original titles, parse variant attributes, build core titles and identity hashes.\n", "\n", "**Input:** `phase1_output.parquet` (4,440 × 14)\n", "\n", "**Output:** `phase2_output.parquet` (4,440 × 34) + `phase2_validation.json` + `phase2_statistics.json`\n", "\n", "**CRITICAL:** Identity information is extracted from the ORIGINAL title BEFORE any destructive normalization.\n", "\n", "**No LLM used. All deterministic/rule-based.**" ] }, { "cell_type": "code", "execution_count": 1, "id": "45fbf818", "metadata": { "execution": { "iopub.execute_input": "2026-08-05T13:26:48.882368Z", "iopub.status.busy": "2026-08-05T13:26:48.881790Z", "iopub.status.idle": "2026-08-05T13:26:49.992622Z", "shell.execute_reply": "2026-08-05T13:26:49.988873Z" }, "papermill": { "duration": 1.121741, "end_time": "2026-08-05T13:26:49.994614+00:00", "exception": false, "start_time": "2026-08-05T13:26:48.872873+00:00", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "import json\n", "import re\n", "from datetime import datetime, timezone\n", "\n", "import pandas as pd\n", "import numpy as np\n", "\n", "VERSION = \"2.0.0\"\n", "TIMESTAMP = datetime.now(timezone.utc).isoformat()\n", "\n", "def log(msg):\n", " print(f\"[Phase2] {msg}\")" ] }, { "cell_type": "markdown", "id": "49786aa1", "metadata": { "papermill": { "duration": 0.004796, "end_time": "2026-08-05T13:26:50.004290+00:00", "exception": false, "start_time": "2026-08-05T13:26:49.999494+00:00", "status": "completed" }, "tags": [] }, "source": [ "## A. Load Phase 1 Output" ] }, { "cell_type": "markdown", "id": "71172033", "metadata": { "tags": [ "papermill-error-cell-tag" ] }, "source": [ "Execution using papermill encountered an exception here and stopped:" ] }, { "cell_type": "code", "execution_count": 2, "id": "184d1d7d", "metadata": { "execution": { "iopub.execute_input": "2026-08-05T13:26:50.019388Z", "iopub.status.busy": "2026-08-05T13:26:50.017616Z", "iopub.status.idle": "2026-08-05T13:26:50.607235Z", "shell.execute_reply": "2026-08-05T13:26:50.603169Z" }, "papermill": { "duration": 0.599348, "end_time": "2026-08-05T13:26:50.609679+00:00", "exception": true, "start_time": "2026-08-05T13:26:50.010331+00:00", "status": "failed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Phase2] Loading Phase 1 output ...\n" ] }, { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'phase1_output.parquet'", "output_type": "error", "traceback": [ "\u001b[31m---------------------------------------------------------------------------\u001b[39m", "\u001b[31mFileNotFoundError\u001b[39m Traceback (most recent call last)", "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[2]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m 1\u001b[39m log(\u001b[33m\"Loading Phase 1 output ...\"\u001b[39m)\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m df = pd.read_parquet(\u001b[33m\"phase1_output.parquet\"\u001b[39m)\n\u001b[32m 3\u001b[39m log(f\"Loaded: {df.shape[\u001b[32m0\u001b[39m]} rows, {df.shape[\u001b[32m1\u001b[39m]} columns\")\n\u001b[32m 4\u001b[39m df.head()\n", "\u001b[36mFile \u001b[39m\u001b[32m~/gsoc/compliments-reference-db/.venv/lib/python3.13/site-packages/pandas/io/parquet.py:671\u001b[39m, in \u001b[36mread_parquet\u001b[39m\u001b[34m(path, engine, columns, storage_options, dtype_backend, filesystem, filters, to_pandas_kwargs, **kwargs)\u001b[39m\n\u001b[32m 668\u001b[39m impl = get_engine(engine)\n\u001b[32m 669\u001b[39m check_dtype_backend(dtype_backend)\n\u001b[32m--> \u001b[39m\u001b[32m671\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mimpl\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mread\u001b[39;49m\u001b[30;43m(\u001b[39;49m\n\u001b[32m 672\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mpath\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 673\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mcolumns\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mcolumns\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 674\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mfilters\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mfilters\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 675\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mstorage_options\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mstorage_options\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 676\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mdtype_backend\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mdtype_backend\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 677\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mfilesystem\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mfilesystem\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 678\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mto_pandas_kwargs\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mto_pandas_kwargs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 679\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 680\u001b[39m \u001b[30;43m\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n", "\u001b[36mFile \u001b[39m\u001b[32m~/gsoc/compliments-reference-db/.venv/lib/python3.13/site-packages/pandas/io/parquet.py:253\u001b[39m, in \u001b[36mPyArrowImpl.read\u001b[39m\u001b[34m(self, path, columns, filters, dtype_backend, storage_options, filesystem, to_pandas_kwargs, **kwargs)\u001b[39m\n\u001b[32m 240\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mread\u001b[39m(\n\u001b[32m 241\u001b[39m \u001b[38;5;28mself\u001b[39m,\n\u001b[32m 242\u001b[39m path,\n\u001b[32m (...)\u001b[39m\u001b[32m 249\u001b[39m **kwargs,\n\u001b[32m 250\u001b[39m ) -> DataFrame:\n\u001b[32m 251\u001b[39m kwargs[\u001b[33m\"\u001b[39m\u001b[33muse_pandas_metadata\u001b[39m\u001b[33m\"\u001b[39m] = \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m253\u001b[39m path_or_handle, handles, filesystem = \u001b[30;43m_get_path_or_handle\u001b[39;49m\u001b[30;43m(\u001b[39;49m\n\u001b[32m 254\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mpath\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 255\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mfilesystem\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 256\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mstorage_options\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mstorage_options\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 257\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mmode\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43m\"\u001b[39;49m\u001b[30;43mrb\u001b[39;49m\u001b[30;43m\"\u001b[39;49m\u001b[30;43m,\u001b[39;49m\n\u001b[32m 258\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 259\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m 260\u001b[39m pa_table = \u001b[38;5;28mself\u001b[39m.api.parquet.read_table(\n\u001b[32m 261\u001b[39m path_or_handle,\n\u001b[32m 262\u001b[39m columns=columns,\n\u001b[32m (...)\u001b[39m\u001b[32m 265\u001b[39m **kwargs,\n\u001b[32m 266\u001b[39m )\n", "\u001b[36mFile \u001b[39m\u001b[32m~/gsoc/compliments-reference-db/.venv/lib/python3.13/site-packages/pandas/io/parquet.py:141\u001b[39m, in \u001b[36m_get_path_or_handle\u001b[39m\u001b[34m(path, fs, storage_options, mode, is_dir)\u001b[39m\n\u001b[32m 131\u001b[39m handles = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 132\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m (\n\u001b[32m 133\u001b[39m \u001b[38;5;129;01mnot\u001b[39;00m fs\n\u001b[32m 134\u001b[39m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m is_dir\n\u001b[32m (...)\u001b[39m\u001b[32m 139\u001b[39m \u001b[38;5;66;03m# fsspec resources can also point to directories\u001b[39;00m\n\u001b[32m 140\u001b[39m \u001b[38;5;66;03m# this branch is used for example when reading from non-fsspec URLs\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m141\u001b[39m handles = \u001b[30;43mget_handle\u001b[39;49m\u001b[30;43m(\u001b[39;49m\n\u001b[32m 142\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43mpath_or_handle\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mmode\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mis_text\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43;01mFalse\u001b[39;49;00m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mstorage_options\u001b[39;49m\u001b[30;43m=\u001b[39;49m\u001b[30;43mstorage_options\u001b[39;49m\n\u001b[32m 143\u001b[39m \u001b[30;43m \u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 144\u001b[39m fs = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 145\u001b[39m path_or_handle = handles.handle\n", "\u001b[36mFile \u001b[39m\u001b[32m~/gsoc/compliments-reference-db/.venv/lib/python3.13/site-packages/pandas/io/common.py:939\u001b[39m, in \u001b[36mget_handle\u001b[39m\u001b[34m(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)\u001b[39m\n\u001b[32m 930\u001b[39m handle = \u001b[38;5;28mopen\u001b[39m(\n\u001b[32m 931\u001b[39m handle,\n\u001b[32m 932\u001b[39m ioargs.mode,\n\u001b[32m (...)\u001b[39m\u001b[32m 935\u001b[39m newline=\u001b[33m\"\u001b[39m\u001b[33m\"\u001b[39m,\n\u001b[32m 936\u001b[39m )\n\u001b[32m 937\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m 938\u001b[39m \u001b[38;5;66;03m# Binary mode\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m939\u001b[39m handle = \u001b[30;43mopen\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43mhandle\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mioargs\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mmode\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 940\u001b[39m handles.append(handle)\n\u001b[32m 942\u001b[39m \u001b[38;5;66;03m# Convert BytesIO or file objects passed with an encoding\u001b[39;00m\n", "\u001b[31mFileNotFoundError\u001b[39m: [Errno 2] No such file or directory: 'phase1_output.parquet'" ] } ], "source": [ "log(\"Loading Phase 1 output ...\")\n", "df = pd.read_parquet(\"phase1_output.parquet\")\n", "log(f\"Loaded: {df.shape[0]} rows, {df.shape[1]} columns\")\n", "df.head()" ] }, { "cell_type": "markdown", "id": "a571e057", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "source": [ "## B. Brand Normalization" ] }, { "cell_type": "code", "execution_count": null, "id": "119609b0", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "outputs": [], "source": [ "BRAND_MAP = {\n", " \"compliments organic\": (\"Compliments\", \"Organic\"),\n", " \"compliments balance\": (\"Compliments\", \"Balance\"),\n", " \"compliments naturally simple\": (\"Compliments\", \"Naturally Simple\"),\n", " \"compliments green care\": (\"Compliments\", \"Green\"),\n", " \"compliments green\": (\"Compliments\", \"Green\"),\n", " \"compliments little ones\": (\"Compliments\", \"Little Ones\"),\n", " \"sensations\": (\"Sensations\", \"Sensations\"),\n", " \"compliments\": (\"Compliments\", \"Core\"),\n", " \"compliments \": (\"Compliments\", \"Core\"),\n", " \" compliments\": (\"Compliments\", \"Core\"),\n", "}\n", "\n", "def normalize_brand(clean_brand):\n", " if pd.isna(clean_brand):\n", " return (\"Unknown\", \"Core\")\n", " key = str(clean_brand).strip().lower()\n", " if key in BRAND_MAP:\n", " return BRAND_MAP[key]\n", " if \"compliments\" in key:\n", " return (\"Compliments\", \"Core\")\n", " if \"sensations\" in key:\n", " return (\"Sensations\", \"Sensations\")\n", " return (str(clean_brand).strip(), \"Core\")\n", "\n", "brand_col = \"brand_clean\" if \"brand_clean\" in df.columns else \"brand\"\n", "brand_results = df[brand_col].apply(normalize_brand)\n", "df[\"brand_norm\"] = brand_results.apply(lambda x: x[0])\n", "df[\"product_line\"] = brand_results.apply(lambda x: x[1])\n", "\n", "print(\"Brand normalization:\")\n", "print(df[\"brand_norm\"].value_counts().to_string())\n", "print(\"\\nProduct lines:\")\n", "print(df[\"product_line\"].value_counts().to_string())" ] }, { "cell_type": "markdown", "id": "47c0f9f3", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "source": [ "## C. Identity Attribute Extraction (from ORIGINAL title)" ] }, { "cell_type": "code", "execution_count": null, "id": "71e095e4", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "outputs": [], "source": [ "def extract_identity_flags(title):\n", " t = title.lower()\n", " return {\n", " \"is_organic\": bool(re.search(r\"\\borganic\\b\", t)),\n", " \"is_gluten_free\": bool(re.search(r\"\\bgluten[\\s-]+free\\b\", t)),\n", " \"is_naturally_simple\": bool(re.search(r\"\\bnaturally\\s+simple\\b\", t)),\n", " \"is_sugar_free\": bool(re.search(\n", " r\"\\bsugar[\\s-]+free\\b|\\b(?:no sugar added|unsweetened)\\b|\\bzero\\s+sugar\\b\", t)),\n", " \"is_unsalted\": bool(re.search(r\"\\bunsalted\\b|\\bno salt\\b\", t)),\n", " \"is_lactose_free\": bool(re.search(r\"\\blactose[\\s-]+free\\b\", t)),\n", " \"is_peanut_free\": bool(re.search(r\"\\bpeanut[\\s-]+free\\b\", t)),\n", " \"is_plant_based\": bool(re.search(r\"\\bplant[\\s-]*based\\b\", t)),\n", " \"is_reduced_sodium\": bool(re.search(\n", " r\"\\breduced\\s+sodium\\b|\\blow\\s+sodium\\b|\\bno\\s+salt\\s+added\\b\", t)),\n", " }\n", "\n", "identity_flags = df[\"title\"].apply(extract_identity_flags)\n", "id_df = pd.DataFrame(identity_flags.tolist())\n", "for col in id_df.columns:\n", " df[col] = id_df[col].values\n", "\n", "print(\"Identity flags:\")\n", "for col in [\"is_organic\", \"is_gluten_free\", \"is_naturally_simple\", \"is_sugar_free\",\n", " \"is_unsalted\", \"is_lactose_free\", \"is_peanut_free\", \"is_plant_based\",\n", " \"is_reduced_sodium\"]:\n", " print(f\" {col}: {int(df[col].sum())}\")" ] }, { "cell_type": "markdown", "id": "cc1fd7e9", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "source": [ "## D. Fat Info + Flavour + Formulation Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "0ff388a0", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "outputs": [], "source": [ "def extract_fat_info(title):\n", " t = title.lower()\n", " fat_level = \"regular\"\n", " if re.search(r\"\\b(?:light|lite|reduced fat|low fat|lean)\\b\", t):\n", " fat_level = \"reduced_fat\"\n", " elif re.search(r\"\\bfat[\\s-]+free\\b\", t):\n", " fat_level = \"fat_free\"\n", " fat_percentage = None\n", " pct_match = re.search(r\"(\\d+(?:\\.\\d+)?)\\s*%\", title)\n", " if pct_match:\n", " val = float(pct_match.group(1))\n", " skip_context = any(w in t for w in [\"cocoa\", \"alcohol\", \"isopropyl\", \"peanuts\"])\n", " if val < 100 and not skip_context:\n", " fat_percentage = val\n", " if 0 < val <= 0.7:\n", " fat_level = \"fat_free\"\n", " return {\"fat_level\": fat_level, \"fat_percentage\": fat_percentage}\n", "\n", "fat_info = df[\"title\"].apply(extract_fat_info)\n", "fat_df = pd.DataFrame(fat_info.tolist())\n", "df[\"fat_level\"] = fat_df[\"fat_level\"].values\n", "df[\"fat_percentage\"] = fat_df[\"fat_percentage\"].values\n", "\n", "FLAVOUR_KEYWORDS = [\n", " \"almond\", \"apple\", \"banana\", \"blueberry\", \"caramel\", \"cherry\",\n", " \"chocolate\", \"cinnamon\", \"coconut\", \"cranberry\", \"honey\", \"lemon\",\n", " \"lime\", \"mango\", \"maple\", \"mixed berry\", \"peach\", \"peanut\",\n", " \"peppermint\", \"pineapple\", \"pomegranate\", \"raspberry\", \"strawberry\",\n", " \"tropical\", \"vanilla\", \"watermelon\", \"white chocolate\", \"berry\",\n", "]\n", "\n", "def extract_flavours(title):\n", " t = title.lower()\n", " return sorted(set(kw for kw in FLAVOUR_KEYWORDS if kw in t))\n", "\n", "FORMULATION_KEYWORDS = [\n", " \"smooth\", \"crunchy\", \"creamy\", \"chunky\", \"whole\", \"halves\",\n", " \"sliced\", \"ground\", \"chopped\", \"breaded\", \"fresh\", \"frozen\",\n", " \"roasted\", \"smoked\",\n", "]\n", "\n", "def extract_formulation(title):\n", " t = title.lower()\n", " return sorted(set(kw for kw in FORMULATION_KEYWORDS if kw in t))\n", "\n", "df[\"flavour\"] = df[\"title\"].apply(extract_flavours)\n", "df[\"formulation\"] = df[\"title\"].apply(extract_formulation)\n", "\n", "print(f\"Products with flavour: {(df['flavour'].apply(len) > 0).sum()}\")\n", "print(f\"Products with formulation: {(df['formulation'].apply(len) > 0).sum()}\")\n", "print(f\"\\nFat levels:\")\n", "print(df[\"fat_level\"].value_counts().to_string())" ] }, { "cell_type": "markdown", "id": "1f69d434", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "source": [ "## E. Variant Attributes Parsing + Core Title Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "bc3a5247", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "outputs": [], "source": [ "def build_variant_attributes(size_str):\n", " if not size_str or pd.isna(size_str):\n", " return {}\n", " s = str(size_str).strip()\n", " attrs = {}\n", " m = re.match(r\"(\\d+(?:\\.\\d+)?)\\s*x\\s*(\\d+(?:\\.\\d+)?)\\s*(g|kg|ml|l|oz|lb)s?\\s*$\", s, re.IGNORECASE)\n", " if m:\n", " return {\"qty\": int(float(m.group(1))), \"amount\": float(m.group(2)), \"unit\": m.group(3).lower()}\n", " m = re.match(r\"(\\d+(?:\\.\\d+)?)\\s*(g|kg|ml|l|oz|lb)s?\\s*(?:x\\s*(\\d+))?\\s*$\", s, re.IGNORECASE)\n", " if m:\n", " attrs = {\"amount\": float(m.group(1)), \"unit\": m.group(2).lower()}\n", " if m.group(3):\n", " attrs[\"multiplier\"] = int(m.group(3))\n", " return attrs\n", " m = re.match(r\"(\\d+)\\s*(?:per\\s+pack|count|ea|pack|piece|slice|cups?|pound)s?\\s*$\", s, re.IGNORECASE)\n", " if m:\n", " return {\"count\": int(m.group(1))}\n", " return {\"raw\": s}\n", "\n", "df[\"variant_attributes\"] = df[\"size\"].apply(\n", " lambda x: json.dumps(build_variant_attributes(x)) if pd.notna(x) else \"{}\"\n", ")\n", "\n", "BRAND_PREFIXES = [\n", " (\"Compliments Naturally Simple \", \"Compliments \"),\n", " (\"Compliments Balance \", \"Compliments Balance \"),\n", " (\"Compliments Organic \", \"Compliments Organic \"),\n", " (\"Compliments Green Care \", \"Compliments Green \"),\n", " (\"Compliments Little Ones \", \"Compliments Little Ones \"),\n", " (\"Compliments \", \"\"),\n", " (\"Sensations \", \"\"),\n", "]\n", "SIZE_PATTERNS = [\n", " r\"\\s+\\d[\\d,.]*\\s*(?:g|kg|ml|l|oz|lb|count|ea|pack|piece|slice|cups?|litre|liters?|pound)s?\\s*$\",\n", " r\"\\s+\\d+\\s*x\\s+\\d+\\s*(?:g|kg|ml|l)\\s*$\",\n", " r\"\\s+\\d+\\s*x\\s*$\",\n", " r\"\\s+\\d+\\s+per\\s+pack\\s*$\",\n", " r\"\\s+\\d+\\s+count\\s*$\",\n", "]\n", "BRACKET_PATTERN = r\"\\s*\\([^)]*\\)\\s*\"\n", "\n", "def extract_core_title(title, product_line):\n", " t = title.strip()\n", " for prefix, replacement in BRAND_PREFIXES:\n", " if t.lower().startswith(prefix.lower()):\n", " t = replacement + t[len(prefix):]\n", " break\n", " for pat in SIZE_PATTERNS:\n", " t = re.sub(pat, \"\", t, flags=re.IGNORECASE)\n", " t = re.sub(BRACKET_PATTERN, \" \", t)\n", " return re.sub(r\"\\s+\", \" \", t).strip()\n", "\n", "df[\"core_title\"] = df.apply(lambda row: extract_core_title(row[\"title\"], row[\"product_line\"]), axis=1)\n", "print(f\"Core titles: {df['core_title'].nunique()} unique\")" ] }, { "cell_type": "markdown", "id": "8c9e0071", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "source": [ "## F. Identity Hash" ] }, { "cell_type": "code", "execution_count": null, "id": "4774b526", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "outputs": [], "source": [ "def build_identity_hash(row):\n", " parts = []\n", " for col in [\"is_organic\", \"is_gluten_free\", \"is_naturally_simple\",\n", " \"is_sugar_free\", \"is_unsalted\", \"is_lactose_free\",\n", " \"is_peanut_free\", \"is_plant_based\", \"is_reduced_sodium\"]:\n", " parts.append(\"1\" if row.get(col) else \"0\")\n", " fp = row.get(\"fat_percentage\")\n", " if pd.notna(fp) and fp is not None:\n", " parts.append(f\"fat{fp:.2g}\" if fp else \"fat0\")\n", " else:\n", " parts.append(\"fat_none\")\n", " parts.append(str(row.get(\"fat_level\", \"regular\")))\n", " parts.append(str(row.get(\"product_line\", \"Core\")))\n", " fl = row.get(\"flavour\", [])\n", " parts.append(\",\".join(sorted(fl)) if fl else \"\")\n", " fm = row.get(\"formulation\", [])\n", " parts.append(\",\".join(sorted(fm)) if fm else \"\")\n", " return \"|\".join(parts)\n", "\n", "df[\"identity_hash\"] = df.apply(lambda row: build_identity_hash(row.to_dict()), axis=1)\n", "print(f\"Identity hashes: {df['identity_hash'].nunique()} unique\")" ] }, { "cell_type": "markdown", "id": "45d3a284", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "source": [ "## G. Save Outputs" ] }, { "cell_type": "code", "execution_count": null, "id": "3582ddf5", "metadata": { "papermill": { "duration": null, "end_time": null, "exception": null, "start_time": null, "status": "pending" }, "tags": [] }, "outputs": [], "source": [ "df.to_parquet(\"phase2_output.parquet\", index=False)\n", "log(\"Saved phase2_output.parquet\")\n", "print(f\"\\n=== PHASE 2 COMPLETE (v{VERSION}) ===\")\n", "print(f\"Input: 4440 rows\")\n", "print(f\"Output: {df.shape[0]} rows, {df.shape[1]} columns\")\n", "print(f\"Columns added: {sorted(set(df.columns) - set(pd.read_parquet('phase1_output.parquet').columns))}\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.7" }, "papermill": { "default_parameters": {}, "duration": 5.303654, "end_time": "2026-08-05T13:26:51.442995+00:00", "environment_variables": {}, "exception": true, "input_path": "code/notebooks/phase2.ipynb", "output_path": "code/notebooks/phase2.ipynb", "parameters": {}, "start_time": "2026-08-05T13:26:46.139341+00:00", "version": "2.7.0" } }, "nbformat": 4, "nbformat_minor": 5 }