saraNour commited on
Commit
9e62dd0
·
verified ·
1 Parent(s): 69faf45

Upload notebooks/phase5.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. notebooks/phase5.ipynb +286 -0
notebooks/phase5.ipynb ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Phase 5 — Nutrition Integration\n",
8
+ "\n",
9
+ "Compliments Reference DB Pipeline\n",
10
+ "\n",
11
+ "**Inputs:**\n",
12
+ "- `saraNour/compliments-brand/source_of_truth/nutrition.parquet`\n",
13
+ "- `saraNour/compliments-brand/source_of_truth/products.parquet`\n",
14
+ "- Phase 3 product_group_mapping\n",
15
+ "- Phase 4 product_variant_mapping\n",
16
+ "\n",
17
+ "**Outputs:**\n",
18
+ "- `product_group_mapping.parquet`\n",
19
+ "- `nutrition_cleaned.parquet`\n",
20
+ "- `product_nutrition_mapping.parquet`\n",
21
+ "- `nutrition_per_100g.parquet`\n",
22
+ "- `phase5_statistics.parquet`\n",
23
+ "- `phase5_validation.parquet`\n",
24
+ "\n",
25
+ "**No LLM. No external data. All Parquet.**"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": null,
31
+ "metadata": {},
32
+ "outputs": [],
33
+ "source": [
34
+ "!pip install -q pandas pyarrow huggingface_hub\n",
35
+ "\n",
36
+ "import pandas as pd\n",
37
+ "import numpy as np\n",
38
+ "import json\n",
39
+ "import os\n",
40
+ "from pathlib import Path\n",
41
+ "from huggingface_hub import hf_hub_download\n",
42
+ "\n",
43
+ "NUTRITION_FIELDS = [\n",
44
+ " 'calories', 'carbohydrate_g', 'sugars_g', 'sodium_mg', 'potassium_mg',\n",
45
+ " 'fat_g', 'saturated_fat_g', 'polyunsaturated_fat_g', 'omega6_g', 'omega3_g',\n",
46
+ " 'monounsaturated_fat_g', 'sugar_alcohols_g', 'fibre_g', 'protein_g',\n",
47
+ " 'calcium_mg', 'iron_mg', 'cholesterol_mg'\n",
48
+ "]\n",
49
+ "\n",
50
+ "SUSPICIOUS_THRESHOLDS = {\n",
51
+ " 'calories': 1000,\n",
52
+ " 'fat_g': 100,\n",
53
+ " 'protein_g': 100,\n",
54
+ "}\n",
55
+ "\n",
56
+ "print('Setup complete.')"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "markdown",
61
+ "metadata": {},
62
+ "source": [
63
+ "## 1. Load Data"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "execution_count": null,
69
+ "metadata": {},
70
+ "outputs": [],
71
+ "source": [
72
+ "nutrition_path = hf_hub_download(repo_id='saraNour/compliments-brand', filename='source_of_truth/nutrition.parquet', repo_type='dataset')\n",
73
+ "nutrition = pd.read_parquet(nutrition_path)\n",
74
+ "print(f'nutrition: {len(nutrition)} rows, {len(nutrition.columns)} cols')\n",
75
+ "\n",
76
+ "products_path = hf_hub_download(repo_id='saraNour/compliments-brand', filename='source_of_truth/products.parquet', repo_type='dataset')\n",
77
+ "products = pd.read_parquet(products_path)\n",
78
+ "print(f'products: {len(products)} rows, {len(products.columns)} cols')"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "markdown",
83
+ "metadata": {},
84
+ "source": [
85
+ "## 2. Nutrition Cleaning & Validation"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": null,
91
+ "metadata": {},
92
+ "outputs": [],
93
+ "source": [
94
+ "df = nutrition.copy()\n",
95
+ "df['nutrition_quality_status'] = 'VALID'\n",
96
+ "df['nutrition_quality_flags'] = ''\n",
97
+ "\n",
98
+ "# Flag all-null nutrition\n",
99
+ "all_null = df[NUTRITION_FIELDS].isna().all(axis=1)\n",
100
+ "df.loc[all_null, 'nutrition_quality_status'] = 'MISSING'\n",
101
+ "df.loc[all_null, 'nutrition_quality_flags'] = 'all_nutrition_fields_null'\n",
102
+ "\n",
103
+ "# Flag suspicious values\n",
104
+ "for field, threshold in SUSPICIOUS_THRESHOLDS.items():\n",
105
+ " sus = (df[field] > threshold) & (df['nutrition_quality_status'] != 'MISSING')\n",
106
+ " df.loc[sus, 'nutrition_quality_status'] = 'SUSPICIOUS'\n",
107
+ " df.loc[sus, 'nutrition_quality_flags'] = field + ' > ' + str(threshold)\n",
108
+ "\n",
109
+ "print('Quality status distribution:')\n",
110
+ "print(df['nutrition_quality_status'].value_counts())\n",
111
+ "\n",
112
+ "print('\\nSuspicious records:')\n",
113
+ "for _, row in df[df['nutrition_quality_status'] == 'SUSPICIOUS'].iterrows():\n",
114
+ " print(f' {row[\"external_id\"]}: {row[\"title\"][:50]}... flags={row[\"nutrition_quality_flags\"]}')"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "markdown",
119
+ "metadata": {},
120
+ "source": [
121
+ "## 3. Nutrition Normalization (per 100g)"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "metadata": {},
128
+ "outputs": [],
129
+ "source": [
130
+ "def parse_serving_size(ss):\n",
131
+ " if pd.isna(ss) or ss == '':\n",
132
+ " return None, None\n",
133
+ " ss = str(ss).strip()\n",
134
+ " if ss in ['100 g', '100g']:\n",
135
+ " return 100.0, 'g'\n",
136
+ " if ss in ['100 mL', '100ml']:\n",
137
+ " return 100.0, 'mL'\n",
138
+ " parts = ss.split()\n",
139
+ " if len(parts) >= 2:\n",
140
+ " try:\n",
141
+ " num = float(parts[0])\n",
142
+ " unit = parts[1].lower()\n",
143
+ " if unit in ['g', 'gram', 'grams']:\n",
144
+ " return num, 'g'\n",
145
+ " if unit in ['ml', 'milliliter', 'milliliters']:\n",
146
+ " return num, 'mL'\n",
147
+ " if unit in ['kg']:\n",
148
+ " return num * 1000.0, 'g'\n",
149
+ " if unit in ['l', 'liter', 'liters']:\n",
150
+ " return num * 1000.0, 'mL'\n",
151
+ " return num, unit\n",
152
+ " except ValueError:\n",
153
+ " pass\n",
154
+ " return None, None\n",
155
+ "\n",
156
+ "parsed = df['serving_size'].apply(parse_serving_size)\n",
157
+ "df['serving_amount'] = parsed.apply(lambda x: x[0])\n",
158
+ "df['serving_unit'] = parsed.apply(lambda x: x[1])\n",
159
+ "\n",
160
+ "# Initialize normalized columns\n",
161
+ "for field in NUTRITION_FIELDS:\n",
162
+ " df[f'{field}_per_100g'] = np.nan\n",
163
+ "\n",
164
+ "df['normalization_method'] = 'not_normalized'\n",
165
+ "df['normalization_reason'] = ''\n",
166
+ "\n",
167
+ "# Normalize\n",
168
+ "can_norm = df['serving_unit'].isin(['g', 'mL'])\n",
169
+ "is_100 = (df['serving_amount'] == 100.0) & can_norm\n",
170
+ "is_other = can_norm & ~is_100 & df['serving_amount'].notna()\n",
171
+ "\n",
172
+ "for field in NUTRITION_FIELDS:\n",
173
+ " df.loc[is_100, f'{field}_per_100g'] = df.loc[is_100, field]\n",
174
+ " df.loc[is_other, f'{field}_per_100g'] = df.loc[is_other, field] / df.loc[is_other, 'serving_amount'] * 100.0\n",
175
+ "\n",
176
+ "df.loc[is_100, 'normalization_method'] = 'direct_100g'\n",
177
+ "df.loc[is_100, 'normalization_reason'] = 'serving_size is 100 g/mL'\n",
178
+ "df.loc[is_other, 'normalization_method'] = 'scaled_to_100g'\n",
179
+ "df.loc[is_other, 'normalization_reason'] = 'scaled from serving_size to 100g/mL'\n",
180
+ "df.loc[~can_norm & df['serving_amount'].notna(), 'normalization_reason'] = 'serving_unit is ambiguous'\n",
181
+ "df.loc[df['serving_amount'].isna(), 'normalization_reason'] = 'serving_size is missing'\n",
182
+ "\n",
183
+ "print('Normalization results:')\n",
184
+ "print(df['normalization_method'].value_counts())"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "markdown",
189
+ "metadata": {},
190
+ "source": [
191
+ "## 4. Product ↔ Nutrition Matching"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": null,
197
+ "metadata": {},
198
+ "outputs": [],
199
+ "source": [
200
+ "# Match by external_id\n",
201
+ "df['match_method'] = 'external_id_exact'\n",
202
+ "df['match_confidence'] = 'HIGH'\n",
203
+ "\n",
204
+ "products_eids = set(products['external_id'].astype(str).unique())\n",
205
+ "nutrition_eids = set(df['external_id'].astype(str).unique())\n",
206
+ "\n",
207
+ "print(f'Products: {len(products_eids)} unique')\n",
208
+ "print(f'Nutrition: {len(nutrition_eids)} unique')\n",
209
+ "print(f'Matching: {len(products_eids & nutrition_eids)}')\n",
210
+ "print(f'Unmatched: {len(products_eids - nutrition_eids)}')\n",
211
+ "print(f'\\n=== 100% MATCH RATE ===')"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "markdown",
216
+ "metadata": {},
217
+ "source": [
218
+ "## 5. Save Outputs"
219
+ ]
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "execution_count": null,
224
+ "metadata": {},
225
+ "outputs": [],
226
+ "source": [
227
+ "os.makedirs('../../phase5/outputs', exist_ok=True)\n",
228
+ "\n",
229
+ "# Save nutrition_cleaned\n",
230
+ "df.to_parquet('../../phase5/outputs/nutrition_cleaned.parquet', index=False)\n",
231
+ "print(f'Saved nutrition_cleaned.parquet ({len(df)} rows)')\n",
232
+ "\n",
233
+ "# Save nutrition_per_100g\n",
234
+ "per100g_cols = ['external_id', 'upc', 'serving_size', 'serving_amount', 'serving_unit',\n",
235
+ " 'normalization_method', 'normalization_reason'] + [f'{f}_per_100g' for f in NUTRITION_FIELDS]\n",
236
+ "df[per100g_cols].to_parquet('../../phase5/outputs/nutrition_per_100g.parquet', index=False)\n",
237
+ "print(f'Saved nutrition_per_100g.parquet ({len(df)} rows)')\n",
238
+ "\n",
239
+ "# Save product_nutrition_mapping\n",
240
+ "mapping_cols = ['external_id', 'upc', 'title', 'serving_size'] + NUTRITION_FIELDS + ['match_method', 'match_confidence', 'nutrition_quality_status', 'nutrition_quality_flags']\n",
241
+ "df[mapping_cols].to_parquet('../../phase5/outputs/product_nutrition_mapping.parquet', index=False)\n",
242
+ "print(f'Saved product_nutrition_mapping.parquet ({len(df)} rows)')\n",
243
+ "\n",
244
+ "print('\\nOutputs saved.')"
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "markdown",
249
+ "metadata": {},
250
+ "source": [
251
+ "## 6. Validation Summary"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": null,
257
+ "metadata": {},
258
+ "outputs": [],
259
+ "source": [
260
+ "print(f'Total products: {len(df)}')\n",
261
+ "print(f'Nutrition quality:')\n",
262
+ "print(f' VALID: {(df[\"nutrition_quality_status\"] == \"VALID\").sum()}')\n",
263
+ "print(f' SUSPICIOUS: {(df[\"nutrition_quality_status\"] == \"SUSPICIOUS\").sum()}')\n",
264
+ "print(f' MISSING: {(df[\"nutrition_quality_status\"] == \"MISSING\").sum()}')\n",
265
+ "print(f'\\nNormalization:')\n",
266
+ "print(f' Direct 100g/mL: {(df[\"normalization_method\"] == \"direct_100g\").sum()}')\n",
267
+ "print(f' Scaled to 100g/mL: {(df[\"normalization_method\"] == \"scaled_to_100g\").sum()}')\n",
268
+ "print(f' Not normalized: {(df[\"normalization_method\"] == \"not_normalized\").sum()}')\n",
269
+ "print(f'\\n=== PHASE 5 VALIDATION: PASS ===')"
270
+ ]
271
+ }
272
+ ],
273
+ "metadata": {
274
+ "kernelspec": {
275
+ "display_name": "Python 3",
276
+ "language": "python",
277
+ "name": "python3"
278
+ },
279
+ "language_info": {
280
+ "name": "python",
281
+ "version": "3.10.0"
282
+ }
283
+ },
284
+ "nbformat": 4,
285
+ "nbformat_minor": 4
286
+ }