Upload notebooks/phase5_audit_executed.ipynb with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Phase 5 — Nutrition Integration Audit\n", "\n", "This notebook audits the authoritative nutrition dataset before implementing Phase 5.\n", "\n", "**Data sources:**\n", "- `saraNour/compliments-brand/source_of_truth/nutrition.parquet`\n", "- `saraNour/compliments-brand/source_of_truth/products.parquet`\n", "\n", "**Requirements:** `pandas`, `pyarrow`, `huggingface_hub`" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:30.167225Z", "iopub.status.busy": "2026-07-30T18:23:30.166713Z", "iopub.status.idle": "2026-07-30T18:23:33.350641Z", "shell.execute_reply": "2026-07-30T18:23:33.345093Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setup complete.\n" ] } ], "source": [ "!pip install -q pandas pyarrow huggingface_hub\n", "\n", "import pandas as pd\n", "import numpy as np\n", "from huggingface_hub import hf_hub_download\n", "\n", "def load_hf(repo, filename):\n", " path = hf_hub_download(repo_id=repo, filename=filename, repo_type='dataset')\n", " print(f'Loaded {filename} from {repo}')\n", " if filename.endswith('.parquet'):\n", " return pd.read_parquet(path)\n", " return pd.read_csv(path)\n", "\n", "print('Setup complete.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Load Data" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:33.441813Z", "iopub.status.busy": "2026-07-30T18:23:33.441017Z", "iopub.status.idle": "2026-07-30T18:23:34.396067Z", "shell.execute_reply": "2026-07-30T18:23:34.384222Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded source_of_truth/nutrition.parquet from saraNour/compliments-brand\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Loaded source_of_truth/products.parquet from saraNour/compliments-brand\n", "\n", "nutrition: 4440 rows, 21 cols\n", "products: 4440 rows, 16 cols\n" ] } ], "source": [ "nutrition = load_hf('saraNour/compliments-brand', 'source_of_truth/nutrition.parquet')\n", "products = load_hf('saraNour/compliments-brand', 'source_of_truth/products.parquet')\n", "\n", "print(f'\\nnutrition: {len(nutrition)} rows, {len(nutrition.columns)} cols')\n", "print(f'products: {len(products)} rows, {len(products.columns)} cols')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Nutrition Schema" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:34.404066Z", "iopub.status.busy": "2026-07-30T18:23:34.403187Z", "iopub.status.idle": "2026-07-30T18:23:34.456397Z", "shell.execute_reply": "2026-07-30T18:23:34.454663Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Rows: 4440\n", "Columns: 21\n", "\n", "Column details:\n", " upc str null= 1 ( 0.0%) unique=3271\n", " external_id str null= 0 ( 0.0%) unique=4440\n", " title str null= 0 ( 0.0%) unique=4375\n", " serving_size str null= 1505 (33.9%) unique=566\n", " calories float64 null= 1661 (37.4%) unique=73\n", " carbohydrate_g float64 null= 1876 (42.3%) unique=89\n", " sugars_g float64 null= 2466 (55.5%) unique=53\n", " sodium_mg float64 null= 1959 (44.1%) unique=131\n", " potassium_mg float64 null= 1891 (42.6%) unique=39\n", " fat_g float64 null= 2311 (52.0%) unique=53\n", " saturated_fat_g float64 null= 2467 (55.6%) unique=30\n", " polyunsaturated_fat_g float64 null= 4343 (97.8%) unique=20\n", " omega6_g float64 null= 4368 (98.4%) unique=15\n", " omega3_g float64 null= 4377 (98.6%) unique=15\n", " monounsaturated_fat_g float64 null= 4352 (98.0%) unique=21\n", " sugar_alcohols_g float64 null= 4329 (97.5%) unique=2\n", " fibre_g float64 null= 2852 (64.2%) unique=19\n", " protein_g float64 null= 1887 (42.5%) unique=45\n", " calcium_mg float64 null= 3225 (72.6%) unique=19\n", " iron_mg float64 null= 3281 (73.9%) unique=27\n", " cholesterol_mg float64 null= 3309 (74.5%) unique=40\n" ] } ], "source": [ "print(f'Rows: {len(nutrition)}')\n", "print(f'Columns: {len(nutrition.columns)}')\n", "print(f'\\nColumn details:')\n", "for col in nutrition.columns:\n", " dtype = str(nutrition[col].dtype)\n", " null_count = int(nutrition[col].isna().sum())\n", " null_pct = null_count / len(nutrition) * 100\n", " nuniq = int(nutrition[col].nunique())\n", " print(f' {col:40s} {dtype:15s} null={null_count:5d} ({null_pct:4.1f}%) unique={nuniq}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Product-Nutrition Relationship" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:34.465862Z", "iopub.status.busy": "2026-07-30T18:23:34.465322Z", "iopub.status.idle": "2026-07-30T18:23:34.553322Z", "shell.execute_reply": "2026-07-30T18:23:34.550424Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Products: 4440 unique external_ids\n", "Nutrition: 4440 unique external_ids\n", "Matching: 4440\n", "Products without nutrition: 0\n", "Nutrition without product: 0\n", "\n", "Records per product: mean=1.00, max=1\n", "Products with 1 record: 4440\n", "Products with 2+ records: 0\n", "\n", "=== RELATIONSHIP: 1:1 (perfect match by external_id) ===\n" ] } ], "source": [ "products_eids = set(products['external_id'].astype(str).unique())\n", "nutrition_eids = set(nutrition['external_id'].astype(str).unique())\n", "\n", "print(f'Products: {len(products_eids)} unique external_ids')\n", "print(f'Nutrition: {len(nutrition_eids)} unique external_ids')\n", "print(f'Matching: {len(products_eids & nutrition_eids)}')\n", "print(f'Products without nutrition: {len(products_eids - nutrition_eids)}')\n", "print(f'Nutrition without product: {len(nutrition_eids - products_eids)}')\n", "\n", "nutrition_per_product = nutrition.groupby('external_id').size()\n", "print(f'\\nRecords per product: mean={nutrition_per_product.mean():.2f}, max={nutrition_per_product.max()}')\n", "print(f'Products with 1 record: {(nutrition_per_product == 1).sum()}')\n", "print(f'Products with 2+ records: {(nutrition_per_product > 1).sum()}')\n", "\n", "print(f'\\n=== RELATIONSHIP: 1:1 (perfect match by external_id) ===')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Matching Quality Table" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:34.559953Z", "iopub.status.busy": "2026-07-30T18:23:34.559296Z", "iopub.status.idle": "2026-07-30T18:23:34.603930Z", "shell.execute_reply": "2026-07-30T18:23:34.600833Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " method records pct confidence\n", " external_id exact 4440 100.0% HIGH\n", " UPC exact 3271 73.7% HIGH\n", " other identifier 0 0.0% \n", "deterministic composite 0 0.0% \n", " unresolved 0 0.0% \n" ] } ], "source": [ "products_upcs = set(products['upc'].astype(str).dropna().unique())\n", "nutrition_upcs = set(nutrition['upc'].astype(str).dropna().unique())\n", "\n", "match_data = [\n", " {'method': 'external_id exact', 'records': len(products_eids & nutrition_eids), 'pct': f'{len(products_eids & nutrition_eids)/len(nutrition)*100:.1f}%', 'confidence': 'HIGH'},\n", " {'method': 'UPC exact', 'records': len(products_upcs & nutrition_upcs), 'pct': f'{len(products_upcs & nutrition_upcs)/len(nutrition)*100:.1f}%', 'confidence': 'HIGH'},\n", " {'method': 'other identifier', 'records': 0, 'pct': '0.0%', 'confidence': ''},\n", " {'method': 'deterministic composite', 'records': 0, 'pct': '0.0%', 'confidence': ''},\n", " {'method': 'unresolved', 'records': 0, 'pct': '0.0%', 'confidence': ''},\n", "]\n", "match_df = pd.DataFrame(match_data)\n", "print(match_df.to_string(index=False))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Suspicious Values" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:34.610018Z", "iopub.status.busy": "2026-07-30T18:23:34.609409Z", "iopub.status.idle": "2026-07-30T18:23:34.639575Z", "shell.execute_reply": "2026-07-30T18:23:34.636915Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "calories > 1000:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " 733225EA: Compliments Mushroom Whole White 680 g... calories=1000000.0\n", " 218890KG: Compliments Whole Chicken Grade A... calories=2100.0\n", "\n", "fat_g > 100:\n", " 274613EA: Compliments Extra Old Cheddar Cheese 300 g... fat_g=710.0\n", " 218890KG: Compliments Whole Chicken Grade A... fat_g=150.0\n", "\n", "protein_g > 100:\n", " 218890KG: Compliments Whole Chicken Grade A... protein_g=190.0\n", "\n", "Records with ALL 17 nutrition fields null: 1505\n" ] } ], "source": [ "print('calories > 1000:')\n", "for _, row in nutrition[nutrition['calories'] > 1000].iterrows():\n", " print(f' {row[\"external_id\"]}: {row[\"title\"][:50]}... calories={row[\"calories\"]}')\n", "\n", "print('\\nfat_g > 100:')\n", "for _, row in nutrition[nutrition['fat_g'] > 100].iterrows():\n", " print(f' {row[\"external_id\"]}: {row[\"title\"][:50]}... fat_g={row[\"fat_g\"]}')\n", "\n", "print('\\nprotein_g > 100:')\n", "for _, row in nutrition[nutrition['protein_g'] > 100].iterrows():\n", " print(f' {row[\"external_id\"]}: {row[\"title\"][:50]}... protein_g={row[\"protein_g\"]}')\n", "\n", "null_fields = [\"calories\",\"carbohydrate_g\",\"sugars_g\",\"sodium_mg\",\"potassium_mg\",\"fat_g\",\"saturated_fat_g\",\"protein_g\",\"fibre_g\",\"calcium_mg\",\"iron_mg\",\"cholesterol_mg\"]\n", "all_null = nutrition[null_fields].isna().all(axis=1).sum()\n", "print(f'\\nRecords with ALL 17 nutrition fields null: {all_null}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Serving Size Analysis" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:34.645023Z", "iopub.status.busy": "2026-07-30T18:23:34.644442Z", "iopub.status.idle": "2026-07-30T18:23:34.671020Z", "shell.execute_reply": "2026-07-30T18:23:34.667988Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Non-null serving_size: 2935 / 4440\n", "Unique: 566\n", "\n", "Top 10 serving sizes:\n", " \"100 g\": 148 records\n", " \"50 g\": 125 records\n", " \"85 g\": 111 records\n", " \"30 g\": 107 records\n", " \"125 mL\": 79 records\n", " \"\": 56 records\n", " \"1 cup (250 mL)\": 52 records\n", " \"3 cm cube (30 g)\": 51 records\n", " \"140 g\": 51 records\n", " \"40 g\": 50 records\n", "\n", "Records with serving_size = \"100 g\": 148\n", " calories range: 20.0 - 2100.0\n" ] } ], "source": [ "ss = nutrition['serving_size'].dropna()\n", "print(f'Non-null serving_size: {len(ss)} / {len(nutrition)}')\n", "print(f'Unique: {ss.nunique()}')\n", "print(f'\\nTop 10 serving sizes:')\n", "for v, c in ss.value_counts().head(10).items():\n", " print(f' \"{v}\": {c} records')\n", "\n", "per_100g = nutrition[nutrition['serving_size'] == '100 g']\n", "print(f'\\nRecords with serving_size = \"100 g\": {len(per_100g)}')\n", "if len(per_100g) > 0:\n", " print(f' calories range: {per_100g[\"calories\"].min()} - {per_100g[\"calories\"].max()}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Sample Examples" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:34.677987Z", "iopub.status.busy": "2026-07-30T18:23:34.677342Z", "iopub.status.idle": "2026-07-30T18:23:34.702762Z", "shell.execute_reply": "2026-07-30T18:23:34.701131Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "=== Successful exact match ===\n", " external_id: 484125EA\n", " title: Compliments Naturally Simple Peanut Butter Crunchy 100% Natural 500 g\n", " serving_size: nan\n", " calories: nan\n", " fat_g: nan\n", " protein_g: nan\n", "\n", "=== Most complete record ===\n", " external_id: 6207EA\n", " title: Compliments Frozen Haddock Fillets Battered 575 g\n", " serving_size: 1 piece (100 g)\n", " calories: 250.0\n", " All fields: 17/17\n" ] } ], "source": [ "print('=== Successful exact match ===')\n", "sample = nutrition[nutrition['external_id'] == '484125EA'].iloc[0]\n", "print(f' external_id: {sample[\"external_id\"]}')\n", "print(f' title: {sample[\"title\"]}')\n", "print(f' serving_size: {sample[\"serving_size\"]}')\n", "print(f' calories: {sample[\"calories\"]}')\n", "print(f' fat_g: {sample[\"fat_g\"]}')\n", "print(f' protein_g: {sample[\"protein_g\"]}')\n", "\n", "print('\\n=== Most complete record ===')\n", "nonnull_counts = nutrition.drop(columns=['upc', 'external_id', 'title', 'serving_size']).notna().sum(axis=1)\n", "best_idx = nonnull_counts.idxmax()\n", "sample = nutrition.loc[best_idx]\n", "print(f' external_id: {sample[\"external_id\"]}')\n", "print(f' title: {sample[\"title\"]}')\n", "print(f' serving_size: {sample[\"serving_size\"]}')\n", "print(f' calories: {sample[\"calories\"]}')\n", "print(f' All fields: {nonnull_counts.max()}/17')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Save Audit Files" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2026-07-30T18:23:34.706952Z", "iopub.status.busy": "2026-07-30T18:23:34.706332Z", "iopub.status.idle": "2026-07-30T18:23:34.719947Z", "shell.execute_reply": "2026-07-30T18:23:34.718345Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Saved audit/nutrition_matching_quality.csv\n", "\n", "Audit complete.\n" ] } ], "source": [ "import os\n", "os.makedirs('audit', exist_ok=True)\n", "\n", "match_df.to_csv('audit/nutrition_matching_quality.csv', index=False)\n", "print('Saved audit/nutrition_matching_quality.csv')\n", "\n", "print('\\nAudit complete.')" ] } ], "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" } }, "nbformat": 4, "nbformat_minor": 4}notebooks/phase5_audit_executed.ipynbAdded+506