Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / generate_food_db.py

generate_food_db.py580 lines · 23.3 KiBRaw
1#!/usr/bin/env python3
2"""Offline generator: Open Food Facts CSV export -> health/src/main/assets/food.bin.br
3
4The health app's recipe builder searches food entirely on-device. This builds
5the data it searches, as a compressed asset compiled into the APK, so the app
6never calls a nutrition API at runtime.
7
8The asset is a flat columnar file, not a SQLite database. The app rebuilds the
9database from it on first launch (a few seconds), which is worth doing because
10a shipped SQLite file carries a great deal that is either derivable or pure
11container: the FTS index alone was 4.5 MB compressed, and page structure,
12record headers and B-tree pointers another 3.7 MB. Measured over the real
13export, the same 465,000 products ship in 10.9 MB this way against 19.1 MB as
14a SQLite file with its index.
15
16Source data
17-----------
18Open Food Facts publishes a full CSV export, rebuilt daily:
19
20 https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz
21
22It is ~1.2 GB gzipped / ~10 GB expanded, tab-delimited despite the `.csv` name,
23and carries ~200 columns (see `location_share_server/headers.txt`). This script
24streams it straight out of the gzip, so the expanded TSV is never written to
25disk. The download is cached in ~/.cache/openfoodfacts and resumed on rerun.
26
27Open Food Facts data is ODbL-licensed: attribution and share-alike are required
28wherever the app ships this database.
29
30Size
31----
32The export is far too big to ship as-is, so three things shrink it, none of
33which lose anything the app can display:
34
35 1. Only `product_name`, `brands` and the 41 nutrients the app renders are
36 kept. `code`, `ingredients_text` and ~150 other columns are dropped.
37 2. Products reporting no nutrients at all are dropped entirely - about half
38 the export.
39 3. Nutrients live in one sparse BLOB rather than 41 REAL columns. Only 8.8
40 of the 41 are populated on an average product, but a 41-column row pays
41 44 bytes of record header whether or not the values are there, plus 8
42 bytes for every REAL it does store. Measured on the full export that was
43 93 MB of header and 149 MB of values; the blob replaces both with ~26
44 bytes a row. This is by far the largest saving.
45 4. Near-duplicate products are collapsed. Open Food Facts holds many
46 separate entries for the same thing - only 83% of products with nutrition
47 are distinct on (name, brands) - and showing a user five identical
48 "Whole milk" rows is a bug as much as it is wasted space.
49The app builds its FTS index with `detail=none`, dropping every token position
50while keeping the per-row size table. `bm25()` still works and, measured over
51real queries, returns the identical ranking: product names are too short for a
52term to occur twice, so term frequency is always 1 and positions tell bm25
53nothing. The length normalisation it does use lives in the size table, which is
54retained. What `detail=none` costs is phrase queries, which the app never
55issues - see `escape_fts_query`, which emits one token per quoted term
56precisely so it never needs them.
57
58The asset is brotli-compressed rather than gzipped: 26% smaller on this data
59for no loss, and the app already ships a brotli decoder.
60
61Asset format
62------------
63Little-endian throughout. A 29-byte header, then five sections laid out one
64after another - columnar, not row-interleaved, which costs nothing to write
65and is 1.2 MB smaller compressed because it puts like bytes next to like:
66
67 magic 4 b"FDB1"
68 version 1 FORMAT_VERSION
69 rowCount 4 uint32
70 idsLen 4 uint32 } byte length of each section, so a reader can
71 scoresLen 4 uint32 } bounds-check and a truncated asset fails
72 namesLen 4 uint32 } loudly instead of decoding into nonsense
73 brandsLen 4 uint32
74 blobsLen 4 uint32
75
76 ids rowCount LEB128 varints, delta-encoded (ids ascend, so the
77 deltas are almost all tiny)
78 scores rowCount bytes, one per product
79 names rowCount x (LEB128 byte length, then UTF-8)
80 brands rowCount x (LEB128 byte length, then UTF-8)
81 blobs rowCount x (LEB128 byte length, then the nutrient blob)
82
83Score
84-----
85One byte per product, supplementing bm25 rather than replacing it:
86
87 bit 7 set when the product reports any of protein/carbs/fat/energy
88 bits 0-4 floor(log2(scans + 1)), capped at 31
89
90The app sorts on the macro bit first, then bm25 relevance, then this score as a
91popularity tie-break. Popularity is a coarse log tier rather than a raw count
92so it only separates products bm25 already considers comparable. The 128
93boundary is load-bearing: the app tests `score >= 128`.
94
95`MAX_PRODUCTS` optionally caps the result to the most-scanned products, which
96is the lever to reach a given APK budget - see the constant below.
97
98Blob format
99-----------
100 bytes 0-5 little-endian bitmap, one bit per NUTRIENTS slot, set when the
101 product reports that nutrient
102 then one LEB128 varint per set bit, in ascending slot order:
103 (mantissa << 4) | exponent, value = mantissa * 10^-exponent
104
105Nutrients span nine orders of magnitude - 900 kcal down to 20 ug of vitamin D
106per 100 g - so no single scale factor covers them; a per-nutrient scale chosen
107for typical values silently rounds that nutrient's smaller readings to zero.
108A per-value decimal exponent is the only encoding measured that stays bounded
109(<=0.5% by construction, 0.017% median) across the whole range.
110
111It is also the smallest, because it happens to suit both the data and the
112compressor. Nutrition labels carry two or three significant digits, so
113stripping trailing zeros leaves mantissas of 1-3 digits that repeat heavily
114across products - 34, 100, 250 - which brotli models far better than float16's
115effectively random mantissa bits. Measured over the real export it is 5.88 MB
116compressed against float16's 6.79 MB, and 11.80 MB raw against 14.93 MB.
117
118float16 was the previous encoding. Besides compressing worse it silently lost
119values below its ~6e-8 subnormal floor: 0.51% of all readings, mostly trace
120micronutrients, were stored as 0.0 and became indistinguishable from absent.
121
122Product ids
123-----------
124Ids must stay identical to the ones `location_share_server/build_db.py` assigns,
125because two things already depend on them: `Ingredient` rows saved on users'
126devices store the product id, and the `/api/food/*` endpoints kept for older
127app builds resolve that same id. `build_db.py` inserts every CSV row without an
128explicit id, so SQLite assigns rowids 1..N in file order. This script therefore
129numbers rows the same way - counting *every* row, including the ones it drops -
130and inserts kept rows under their original ordinal.
131
132Usage
133-----
134 python3 scripts/generate_food_db.py [--csv PATH] [--max-products N] [--keep-db]
135"""
136
137import argparse
138import csv
139import gzip
140import json
141import os
142import sqlite3
143import subprocess
144import sys
145import time
146from pathlib import Path
147
148CSV_URL = "https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz"
149CACHE_DIR = Path.home() / ".cache" / "openfoodfacts"
150CACHED_CSV = CACHE_DIR / "en.openfoodfacts.org.products.csv.gz"
151
152REPO_ROOT = Path(__file__).resolve().parent.parent
153ASSET_DIR = REPO_ROOT / "health" / "src" / "main" / "assets"
154ASSET_BIN = ASSET_DIR / "food.bin.br"
155ASSET_META = ASSET_DIR / "food.bin.meta.json"
156
157MAGIC = b"FDB1"
158
159# Keep only the N most-scanned products, or None for every product with
160# nutrition data. This is the APK-size dial: Open Food Facts is dominated by
161# products that are scanned once and never again, so a cap here cuts the asset
162# hard while barely touching what a real search finds.
163#
164# Be aware of what the cut selects for. Open Food Facts began in France and its
165# scan counts still lean that way, so a popularity cap pulls the database
166# towards European - especially French - products, and away from the long tail
167# of regional ones everywhere.
168MAX_PRODUCTS = 465_000
169
170# Bumped in lockstep with FoodDatabase.SUPPORTED_SCHEMA_VERSION in the app.
171# 2: nutrients moved into a sparse blob; bm25 replaced by a stored score.
172# 3: FTS index restored to detail=full so the app can rank with bm25 again.
173# 4: detail=none (bm25 is unaffected by it) and brotli instead of gzip.
174# 5: nutrient blob switched from float16 to a presence bitmap plus per-value
175# decimal floats - smaller, better compressed, and no subnormal underflow.
176# 6: asset is a columnar binary the app turns into SQLite, not a SQLite file.
177SCHEMA_VERSION = 6
178
179BATCH_SIZE = 50_000
180
181# (database column, CSV header). Order matches NutritionData's declaration
182# order in the app and the SELECT in the server's handlers/food.rs - the app
183# reads these positionally.
184NUTRIENTS = [
185 ("proteins_100g", "proteins_100g"),
186 ("carbohydrates_100g", "carbohydrates_100g"),
187 ("fat_100g", "fat_100g"),
188 ("fiber_100g", "fiber_100g"),
189 ("sugars_100g", "sugars_100g"),
190 ("sodium_100g", "sodium_100g"),
191 ("biotin_100g", "biotin_100g"),
192 ("caffeine_100g", "caffeine_100g"),
193 ("calcium_100g", "calcium_100g"),
194 ("chloride_100g", "chloride_100g"),
195 ("cholesterol_100g", "cholesterol_100g"),
196 ("chromium_100g", "chromium_100g"),
197 ("copper_100g", "copper_100g"),
198 ("folates_100g", "folates_100g"),
199 ("vitamin_b9_100g", "vitamin-b9_100g"),
200 ("iodine_100g", "iodine_100g"),
201 ("iron_100g", "iron_100g"),
202 ("magnesium_100g", "magnesium_100g"),
203 ("manganese_100g", "manganese_100g"),
204 ("molybdenum_100g", "molybdenum_100g"),
205 ("monounsaturated_fat_100g", "monounsaturated-fat_100g"),
206 ("vitamin_pp_100g", "vitamin-pp_100g"),
207 ("pantothenic_acid_100g", "pantothenic-acid_100g"),
208 ("phosphorus_100g", "phosphorus_100g"),
209 ("polyunsaturated_fat_100g", "polyunsaturated-fat_100g"),
210 ("potassium_100g", "potassium_100g"),
211 ("vitamin_b2_100g", "vitamin-b2_100g"),
212 ("saturated_fat_100g", "saturated-fat_100g"),
213 ("selenium_100g", "selenium_100g"),
214 ("vitamin_b1_100g", "vitamin-b1_100g"),
215 ("trans_fat_100g", "trans-fat_100g"),
216 ("unsaturated_fat_100g", "unsaturated-fat_100g"),
217 ("vitamin_a_100g", "vitamin-a_100g"),
218 ("vitamin_b12_100g", "vitamin-b12_100g"),
219 ("vitamin_b6_100g", "vitamin-b6_100g"),
220 ("vitamin_c_100g", "vitamin-c_100g"),
221 ("vitamin_d_100g", "vitamin-d_100g"),
222 ("vitamin_e_100g", "vitamin-e_100g"),
223 ("vitamin_k_100g", "vitamin-k_100g"),
224 ("zinc_100g", "zinc_100g"),
225 ("energy_kcal_100g", "energy-kcal_100g"),
226]
227
228# Open Food Facts stores some wildly out-of-range values (per-package figures
229# filed as per-100g, unit mix-ups). Anything a food cannot physically contain
230# per 100 g is treated as unreported rather than shown to the user.
231MAX_PLAUSIBLE_PER_100G = 10_000.0
232
233# Largest relative error the blob encoding may introduce. Nutrition labels
234# carry two or three significant figures, so half a percent is far below the
235# precision of the source data, and allowing it keeps mantissas short.
236QUANTISATION_TOLERANCE = 0.005
237
238# Indices into NUTRIENTS of protein, carbohydrates, fat and energy. A product
239# reporting none of them is real but close to useless in a recipe, so it sorts
240# below everything that does - the same demotion the server's ORDER BY applies.
241MACRO_INDICES = (0, 1, 2, 40)
242
243
244def mb(n: int) -> str:
245 return f"{n / (1024 ** 2):,.1f} MB"
246
247
248def ensure_csv(path: Path) -> Path:
249 """Download the export if it isn't cached yet, resuming a partial file."""
250 if path.exists() and path.stat().st_size > 0:
251 print(f"Using cached export: {path} ({mb(path.stat().st_size)})")
252 return path
253
254 path.parent.mkdir(parents=True, exist_ok=True)
255 print(f"Downloading {CSV_URL}\n -> {path}")
256 # curl rather than urllib: the export is >1 GB and redirects to S3, and
257 # -C - resumes a partial file instead of restarting.
258 subprocess.run(
259 ["curl", "-fL", "-C", "-", "--retry", "5", "--retry-delay", "5",
260 "-o", str(path), CSV_URL],
261 check=True,
262 )
263 return path
264
265
266def encode_varint(n: int) -> bytes:
267 """LEB128, the length and delta encoding used throughout the asset."""
268 out = bytearray()
269 while True:
270 seven, n = n & 0x7F, n >> 7
271 out.append(seven | (0x80 if n else 0))
272 if not n:
273 return bytes(out)
274
275
276def encode_value(value: float) -> bytes:
277 """Encode one reading as varint((mantissa << 4) | exponent).
278
279 Picks the smallest exponent whose mantissa still round-trips within
280 QUANTISATION_TOLERANCE, which strips trailing zeros: 3.4 becomes 34e-1
281 rather than 3400e-3. Short mantissas are what makes the blob compress.
282 """
283 for exponent in range(16):
284 mantissa = round(value * 10 ** exponent)
285 if mantissa and abs(mantissa / 10 ** exponent - value) <= QUANTISATION_TOLERANCE * value:
286 break
287 else:
288 mantissa, exponent = round(value * 10 ** 15), 15
289
290 return encode_varint((mantissa << 4) | exponent)
291
292
293def parse_nutrient(raw: str):
294 """CSV cell -> float, or None when absent, unparseable, zero or absurd."""
295 if not raw:
296 return None
297 try:
298 value = float(raw)
299 except ValueError:
300 return None
301 # NaN fails every comparison, which also rules it out here.
302 if not (0.0 < value <= MAX_PLAUSIBLE_PER_100G):
303 return None
304 return value
305
306
307def build(csv_path: Path, db_path: Path, max_products):
308 if db_path.exists():
309 db_path.unlink()
310
311 conn = sqlite3.connect(db_path)
312 cur = conn.cursor()
313 cur.executescript("""
314 PRAGMA journal_mode = OFF;
315 PRAGMA synchronous = 0;
316 PRAGMA cache_size = -262144;
317 PRAGMA temp_store = MEMORY;
318 """)
319
320 # nutrient_count and popularity only survive long enough to pick a winner
321 # among duplicates; both are dropped before the database ships.
322 cur.execute("""
323 CREATE TABLE products (
324 id INTEGER PRIMARY KEY,
325 product_name TEXT,
326 brands TEXT,
327 nutrients BLOB,
328 score INTEGER,
329 nutrient_count INTEGER,
330 popularity INTEGER
331 )
332 """)
333 insert_sql = ("INSERT INTO products (id, product_name, brands, nutrients, score, "
334 "nutrient_count, popularity) VALUES (?, ?, ?, ?, ?, ?, ?)")
335
336 csv.field_size_limit(sys.maxsize)
337 started = time.time()
338 total_rows = 0
339 kept = 0
340 batch = []
341
342 print("Streaming export (nothing is expanded to disk)...")
343 with gzip.open(csv_path, "rt", encoding="utf-8", errors="replace", newline="") as fh:
344 reader = csv.reader(fh, delimiter="\t")
345 header = next(reader)
346 index = {name: i for i, name in enumerate(header)}
347
348 missing = [h for _, h in NUTRIENTS if h not in index] + \
349 [h for h in ("product_name", "brands", "unique_scans_n") if h not in index]
350 if missing:
351 raise SystemExit(f"Export is missing expected columns: {missing}")
352
353 # Resolve column positions once; per-row dict building is the single
354 # biggest cost at this row count.
355 name_i = index["product_name"]
356 brands_i = index["brands"]
357 scans_i = index["unique_scans_n"]
358 nutrient_i = [index[h] for _, h in NUTRIENTS]
359 widest = max([name_i, brands_i, scans_i] + nutrient_i)
360
361 for row in reader:
362 # Ordinal over EVERY row, kept or not - this is the product id
363 # build_db.py would assign. Must not be filtered.
364 total_rows += 1
365
366 if len(row) <= widest:
367 continue
368
369 name = row[name_i].strip()
370 if not name:
371 # Unfindable in a name search, so it is pure weight.
372 continue
373
374 present = 0
375 body = bytearray()
376 has_macro = False
377 count = 0
378 for slot, col in enumerate(nutrient_i):
379 value = parse_nutrient(row[col])
380 if value is None:
381 continue
382 present |= 1 << slot
383 body += encode_value(value)
384 count += 1
385 if slot in MACRO_INDICES:
386 has_macro = True
387
388 if not count:
389 continue
390 blob = present.to_bytes(6, "little") + body
391
392 try:
393 scans = int(row[scans_i]) if row[scans_i] else 0
394 except ValueError:
395 scans = 0
396
397 # Coarse log2 popularity tier, so that near-equally-popular
398 # products are separated by name relevance rather than by a
399 # handful of extra scans. Whole score fits in one byte, and 0
400 # costs no payload bytes at all in SQLite's record format.
401 tier = min(max(scans + 1, 1).bit_length() - 1, 31)
402 score = (128 if has_macro else 0) + tier
403
404 batch.append((total_rows, name, row[brands_i].strip(), bytes(blob),
405 score, count, scans))
406 kept += 1
407
408 if len(batch) >= BATCH_SIZE:
409 cur.executemany(insert_sql, batch)
410 batch.clear()
411 conn.commit()
412 elapsed = time.time() - started
413 print(f" {total_rows:>9,} read {kept:>9,} kept "
414 f"{elapsed:>6.0f}s {total_rows / max(elapsed, 1):>8,.0f} rows/s")
415
416 if batch:
417 cur.executemany(insert_sql, batch)
418 conn.commit()
419
420 print(f"Read {total_rows:,} products, kept {kept:,} with nutrition data "
421 f"({total_rows - kept:,} dropped) in {time.time() - started:.0f}s")
422
423 # --- Collapse duplicates -------------------------------------------------
424 # Open Food Facts carries the same product many times over. Keep the entry
425 # with the most nutrients, breaking ties by popularity then by lowest id so
426 # the choice is deterministic across rebuilds. NOCASE because "Whole Milk"
427 # and "Whole milk" are the same thing to anyone searching.
428 print("Collapsing duplicate products...")
429 started = time.time()
430 cur.execute("""
431 DELETE FROM products WHERE id IN (
432 SELECT id FROM (
433 SELECT id, ROW_NUMBER() OVER (
434 PARTITION BY product_name COLLATE NOCASE, brands COLLATE NOCASE
435 ORDER BY nutrient_count DESC, popularity DESC, id ASC
436 ) AS rn
437 FROM products
438 ) WHERE rn > 1
439 )
440 """)
441 removed = cur.rowcount
442 conn.commit()
443 kept -= removed
444 print(f" removed {removed:,} duplicates, {kept:,} remain "
445 f"({time.time() - started:.0f}s)")
446
447 if max_products and kept > max_products:
448 # Cut on the raw scan count, not the log2 tier in `score`: whole tiers
449 # hold hundreds of thousands of products, so a tier-based cut would
450 # land mid-tier and keep whichever happened to have the lowest id.
451 cur.execute("""
452 DELETE FROM products WHERE id NOT IN (
453 SELECT id FROM products
454 ORDER BY (score >= 128) DESC, popularity DESC, id ASC
455 LIMIT ?
456 )
457 """, (max_products,))
458 conn.commit()
459 print(f"Capped to the {max_products:,} highest-ranked products "
460 f"({kept - max_products:,} removed)")
461 kept = max_products
462
463 cur.execute("ALTER TABLE products DROP COLUMN nutrient_count")
464 cur.execute("ALTER TABLE products DROP COLUMN popularity")
465 conn.commit()
466
467 # No FTS index and no VACUUM: the app builds the index itself, and this
468 # database is never shipped - only the columnar export below is.
469 return conn, {"rows": kept, "source_rows": total_rows, "duplicates": removed}
470
471
472def export_binary(conn, out_path: Path) -> dict:
473 """Write the columnar asset described in the module docstring."""
474 cur = conn.cursor()
475 ids = bytearray()
476 scores = bytearray()
477 names = bytearray()
478 brands = bytearray()
479 blobs = bytearray()
480
481 previous_id = 0
482 rows = 0
483 for pid, name, brand, nutrients, score in cur.execute(
484 "SELECT id, product_name, COALESCE(brands, ''), nutrients, score "
485 "FROM products ORDER BY id"
486 ):
487 ids += encode_varint(pid - previous_id)
488 previous_id = pid
489 scores.append(score & 0xFF)
490 encoded = name.encode("utf-8")
491 names += encode_varint(len(encoded)) + encoded
492 encoded = brand.encode("utf-8")
493 brands += encode_varint(len(encoded)) + encoded
494 blobs += encode_varint(len(nutrients)) + nutrients
495 rows += 1
496
497 header = (
498 MAGIC
499 + bytes([SCHEMA_VERSION])
500 + rows.to_bytes(4, "little")
501 + len(ids).to_bytes(4, "little")
502 + len(scores).to_bytes(4, "little")
503 + len(names).to_bytes(4, "little")
504 + len(brands).to_bytes(4, "little")
505 + len(blobs).to_bytes(4, "little")
506 )
507 with open(out_path, "wb") as f:
508 f.write(header)
509 for section in (ids, scores, names, brands, blobs):
510 f.write(section)
511
512 print(f" sections: ids {mb(len(ids))} scores {mb(len(scores))} names {mb(len(names))}"
513 f" brands {mb(len(brands))} blobs {mb(len(blobs))}")
514 return {"rows": rows}
515
516
517def compress(src_path: Path, out_path: Path) -> None:
518 """Brotli-compress the export into the asset the APK ships.
519
520 Brotli rather than gzip because it is ~26% smaller on this data at no cost:
521 the app decodes it with org.brotli:dec, which `:library:network` already
522 pulls in for HTTP content-encoding.
523 """
524 out_path.parent.mkdir(parents=True, exist_ok=True)
525 print("Compressing asset (brotli -q 11)...")
526 started = time.time()
527 if out_path.exists():
528 out_path.unlink()
529 try:
530 subprocess.run(["brotli", "-q", "11", "-o", str(out_path), str(src_path)], check=True)
531 except FileNotFoundError:
532 raise SystemExit("brotli not found - install it (brew install brotli / apt install brotli)")
533 print(f" {out_path.name}: {mb(out_path.stat().st_size)} in {time.time() - started:.0f}s")
534
535
536def main() -> None:
537 ap = argparse.ArgumentParser(description=__doc__,
538 formatter_class=argparse.RawDescriptionHelpFormatter)
539 ap.add_argument("--csv", type=Path, default=CACHED_CSV,
540 help="Path to the gzipped Open Food Facts export (downloaded if absent)")
541 ap.add_argument("--max-products", type=int, default=MAX_PRODUCTS,
542 help="Keep only the N highest-ranked products (default: %(default)s)")
543 ap.add_argument("--keep-db", action="store_true",
544 help="Leave the staging SQLite database behind for inspection")
545 args = ap.parse_args()
546
547 csv_path = ensure_csv(args.csv)
548 ASSET_DIR.mkdir(parents=True, exist_ok=True)
549 staging = ASSET_DIR / "staging.db"
550
551 conn, stats = build(csv_path, staging, args.max_products)
552
553 raw_asset = ASSET_DIR / "food.bin"
554 print("Writing columnar export...")
555 export_binary(conn, raw_asset)
556 conn.close()
557 raw_bytes = raw_asset.stat().st_size
558 print(f" food.bin: {mb(raw_bytes)} for {stats['rows']:,} products")
559
560 compress(raw_asset, ASSET_BIN)
561 raw_asset.unlink()
562 if not args.keep_db:
563 staging.unlink()
564
565 ASSET_META.write_text(json.dumps({
566 "schemaVersion": SCHEMA_VERSION,
567 "rows": stats["rows"],
568 "bytes": raw_bytes,
569 "compressedBytes": ASSET_BIN.stat().st_size,
570 }, indent=2) + "\n")
571
572 print("\nAsset summary")
573 print(f" products {stats['rows']:,} of {stats['source_rows']:,} in the export "
574 f"({stats['duplicates']:,} duplicates collapsed)")
575 print(f" in APK {mb(ASSET_BIN.stat().st_size)} ({ASSET_BIN.relative_to(REPO_ROOT)})")
576 print(f" unpacks to {mb(raw_bytes)}, which the app turns into a database on first launch")
577
578
579if __name__ == "__main__":
580 main()