Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/food-data.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ name: Food data

# Imports into GRIT's food database (packages/food-data). Runs by hand for
# full imports (USDA after each release, twice a year; Open Food Facts;
# CoFID), and daily for Open Food Facts' changes to products already in the
# database. Needs the DIRECT_URL repository secret: a session-mode
# the national tables: CoFID, CNF, CIQUAL, Fineli), and daily for Open Food
# Facts' changes to products already in the database. Needs the DIRECT_URL repository secret: a session-mode
# connection, not Supabase's transaction pooler on port 6543 (see the
# package README). Without it, the workflow does nothing.

Expand All @@ -13,7 +13,7 @@ on:
source:
description: What to import
type: choice
options: [off-delta, fdc, off, cofid]
options: [off-delta, fdc, off, cofid, cnf, ciqual, fineli]
default: off-delta
options:
description: 'Options, e.g. "--dataset foundation,sr,fndds --full", "--min-scans 5 --countries gb,us", "--only-existing", "--dry-run"'
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ grit/
│ └── mobile/ # Expo (React Native) app
└── packages/
├── backend/ # NestJS REST API
└── food-data/ # Importers for GRIT's food database (USDA, Open Food Facts, UK CoFID)
└── food-data/ # Importers for GRIT's food database (USDA, Open Food Facts, national tables)
```

---
Expand Down Expand Up @@ -245,7 +245,7 @@ A cloud instance can't run a simulator. Use it for type-checking and linting, or

### Food data

GRIT's food database is filled by the importers in [`packages/food-data`](./packages/food-data/README.md): USDA FoodData Central (public domain), Open Food Facts (ODbL) and the UK's CoFID (Open Government Licence). Each is idempotent, so a re-run changes nothing. The [Food data workflow](./.github/workflows/food-data.yml) runs them against the database in the `DIRECT_URL` repository secret: by hand for full imports, and daily for Open Food Facts' changes. Sources are credited in the app under Profile → Food data sources.
GRIT's food database is filled by the importers in [`packages/food-data`](./packages/food-data/README.md): USDA FoodData Central (public domain), Open Food Facts (ODbL) and the national tables of the UK (CoFID, Open Government Licence), Canada (CNF, OGL – Canada), France (CIQUAL, Licence Ouverte) and Finland (Fineli, CC BY 4.0). Each is idempotent, so a re-run changes nothing. The [Food data workflow](./.github/workflows/food-data.yml) runs them against the database in the `DIRECT_URL` repository secret: by hand for full imports, and daily for Open Food Facts' changes. Sources are credited in the app under Profile → Food data sources.

---

Expand Down
26 changes: 23 additions & 3 deletions apps/mobile/lib/foodSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Nutrients screen. Edit the wording here.
*/
export interface FoodSource {
/** The `source` code foods carry (fdc, off, cofid) */
/** The `source` code foods carry (fdc, off, cofid, cnf, ciqual, fineli) */
code: string;
name: string;
/** Who publishes it, or the attribution the licence asks for */
Expand Down Expand Up @@ -39,8 +39,28 @@ export const FOOD_SOURCES: FoodSource[] = [
licence: 'Open Government Licence v3.0',
url: 'https://www.gov.uk/government/publications/composition-of-foods-integrated-dataset-cofid',
},
// Canada's CNF, France's CIQUAL and Finland's Fineli join this list when
// they're imported (see docs/ROADMAP.md, Phase 7)
{
code: 'cnf',
name: 'Canadian Nutrient File',
credit: 'Canadian Nutrient File 2015, Health Canada.',
notice: 'Contains information licensed under the Open Government Licence – Canada.',
licence: 'Open Government Licence – Canada',
url: 'https://www.canada.ca/en/health-canada/services/food-nutrition/healthy-eating/nutrient-data.html',
},
{
code: 'ciqual',
name: 'ANSES-CIQUAL',
credit: 'ANSES-CIQUAL French food composition table, 2025 version (Anses), last updated 19 November 2025.',
licence: 'Licence Ouverte / Open Licence 2.0 (Etalab)',
url: 'https://ciqual.anses.fr',
},
{
code: 'fineli',
name: 'Fineli',
credit: 'Finnish Institute for Health and Welfare (THL), Fineli, the Finnish food composition database, release 20.',
licence: 'Creative Commons Attribution 4.0 (CC BY 4.0)',
url: 'https://fineli.fi',
},
];

/** "fdc.nal.usda.gov" from a source's URL, for its link text. */
Expand Down
13 changes: 9 additions & 4 deletions docs/PLAN_PHASES_5_TO_9.md
Original file line number Diff line number Diff line change
Expand Up @@ -438,9 +438,14 @@ with these differences:
- **Size:** the full Open Food Facts and USDA branded imports would take
12–14 GB as stored, well over the 2–4 GB estimated here. They aren't
imported yet (see ROADMAP).
- **National tables:** the UK's CoFID is imported. Canada's, France's and
Finland's sites couldn't be downloaded from a server, so those wait for
the files.
- **National tables:** the UK's CoFID, Canada's CNF 2015, France's
CIQUAL 2025 and Finland's Fineli (release 20) are imported, with their
other-language names. Health Canada's and Fineli's sites refuse servers,
so those two release files are kept in the repository and checked by
SHA-256; CIQUAL comes from Recherche Data Gouv, where ANSES deposits it.
- **Search** scores a food on each of its names, so a French table's food
found by its French name ranks like a product named exactly that, and
shows one result per name and brand before its limit.
- **Smart log** matches unbranded items to measured foods and branded
items to branded foods first, and only when the calories agree with the
reading. Branded before measured, for branded items, keeps "Fage yogurt"
Expand Down Expand Up @@ -566,7 +571,7 @@ duplicating them.
| USDA FoodData Central: Branded | ~400k US products, label nutrients | Public domain |
| Open Food Facts | ~3M products from about 150 countries, names in many languages | **ODbL** (decision 3) |
| UK CoFID | UK foods | Open Government Licence |
| Canada CNF, France CIQUAL, Finland Fineli | National foods | Open licences; confirm each |
| Canada CNF, France CIQUAL, Finland Fineli | National foods | OGL – Canada; Licence Ouverte 2.0; CC BY 4.0 |

- **Size:** filtered Open Food Facts plus everything else is roughly 2–4 GB.
Only products with a name and calories are imported, using bulk `COPY` into
Expand Down
26 changes: 16 additions & 10 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,12 @@ writing is on.
- Open Food Facts: the full export, or a filtered one, and a daily job
for its changes. Only label values are kept; OFF's own estimates from
ingredients are left out;
- the UK's CoFID (2,854 foods);
- the national tables of the UK (CoFID, 2,854 foods), Canada (CNF 2015,
5,690), France (CIQUAL 2025, 3,341) and Finland (Fineli, 4,231), with
their French, Finnish and Swedish names, so "ruisleipä" finds rye
bread. Health Canada's and Fineli's sites refuse servers, so their
release files are kept in the repository (`packages/food-data/data`);
CIQUAL comes from Recherche Data Gouv;
- the same product from two sources is one food, showing the better
source (government tables, then manufacturers, then Open Food Facts).
- **Search** runs on GRIT's own data:
Expand All @@ -240,7 +245,9 @@ writing is on.
scanned (the "core") are always searched in full; the millions of
other products are sampled, so common words stay fast;
- ranked by the user's own foods (logged, favourite, remembered), then
their country's, how closely the name matches, quality and popularity;
their country's, how closely any of a food's names matches, quality
and popularity, with one result per name and brand (so 60 products
called "Baguette" don't hide the French table's baguette);
- results show the typical serving and a "Verified" label for
government and manufacturer data;
- p95 of 131 ms on 3.4 million foods, locally with the full Open Food
Expand Down Expand Up @@ -273,8 +280,8 @@ writing is on.

**After deploying Phase 7:** apply the migration to Supabase. Add the
`DIRECT_URL` repository secret (Supabase's session pooler, port 5432), then
run the Food data workflow for `fdc` and `cofid`. Together they take about
90 MB, within the Free plan. Until then search falls back to Open Food
run the Food data workflow for `fdc`, `cofid`, `cnf`, `ciqual` and
`fineli`. Together they take about 170 MB, within the Free plan. Until then search falls back to Open Food
Facts live, and only scanned products carry micronutrients. The daily job
then keeps saved Open Food Facts products up to date. Deploy the backend
before the app: the app sends new fields that older backends reject.
Expand All @@ -289,9 +296,6 @@ before the app: the app sends new fields that older backends reject.
first searches after a database restart time out (2.5 s) until its cache
warms up (seen locally on 3.4 million foods); they fall back to the live
search meanwhile.
- Canada's CNF, France's CIQUAL and Finland's Fineli: their sites couldn't
be downloaded from the server (no response, maintenance, a bot check), so
their importers wait for the files.
- Open Food Facts' licence (ODbL) review by a lawyer (decision 3): the
barcode lookup already saves the products it finds, and every saved row
is marked with its source, so they can all be removed in one step.
Expand Down Expand Up @@ -355,9 +359,11 @@ Ordered from easiest to hardest, each phase is released on its own:
- Food database (Phase 7):
- add the `DIRECT_URL` repository secret in GitHub (Supabase → Connect →
Session pooler, port 5432, with the database password), then run the
Food data workflow for `fdc` and then `cofid`;
Food data workflow for `fdc`, then `cofid`, `cnf`, `ciqual` and
`fineli`;
- decide on Supabase Pro and filters before importing all of Open Food
Facts and USDA's branded products (12–14 GB as stored now);
- have a lawyer review the Open Food Facts licence (decision 3);
- download Canada's CNF, France's CIQUAL and Finland's Fineli files in a
browser (their sites block servers) so their importers can be built.
- when Health Canada publishes CNF 2026, or Fineli a new release,
download it in a browser and replace the file in
`packages/food-data/data` (their sites block servers).
8 changes: 6 additions & 2 deletions docs/TRUST_AND_SAFETY.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,5 +244,9 @@ completed with a lawyer.*
- **UK CoFID (Open Government Licence v3.0)**, imported with the required
statement in the app.
- **USDA FoodData Central** is public domain; credited as a courtesy.
- **Canada's CNF (OGL – Canada), France's CIQUAL (Licence Ouverte) and
Finland's Fineli (CC BY 4.0):** confirm each before they're imported.
- **Canada's CNF (Open Government Licence – Canada), France's CIQUAL
(Licence Ouverte / Open Licence 2.0) and Finland's Fineli (CC BY
4.0):** open licences that allow commercial use and redistribution
with attribution, given in the app with the wording each asks for
(CIQUAL's includes the date it was last updated). CNF's and Fineli's
release files are kept unchanged in the repository.
57 changes: 56 additions & 1 deletion packages/backend/src/food/food-db.db-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ async function seed(
servings?: { label: string; grams: number; typical?: boolean }[];
extra?: Record<string, number>;
basis?: string;
names?: { name: string; lang: string }[];
} = {},
) {
const nutrients = {
Expand All @@ -51,7 +52,12 @@ async function seed(
quality: over.quality ?? 1,
popularity: over.popularity ?? 0,
verified: over.verified ?? true,
searchText: searchTextOf(name, over.brand),
searchText: searchTextOf(
name,
over.brand,
over.names?.map((n) => n.name),
),
names: over.names ? { create: over.names } : undefined,
barcodes: over.barcode ? { create: { code: over.barcode } } : undefined,
servings: over.servings ? { create: over.servings } : undefined,
nutrients: {
Expand Down Expand Up @@ -227,6 +233,55 @@ describe('food database search', () => {
});
});

describe('search across many products and languages', () => {
it('shows one product per name and brand, so other foods still fit', async () => {
// 60 products with one name would fill every place before
for (let i = 0; i < 60; i++) {
await seed(`test_quib_${i}`, 'Quibbet', {
kind: 'branded',
source: 'off',
countries: ['fr'],
quality: 0.6,
verified: false,
basis: 'label',
});
}
await seed('test_quib_ciqual', 'Bread, French bread, quibbet', {
source: 'ciqual',
countries: ['fr'],
});
const results = await foodDb.search('quibbet', { country: 'FR' });
expect(results.filter((r) => r.name === 'Quibbet')).toHaveLength(1);
expect(results.map((r) => r.foodId)).toContain('test_quib_ciqual');
});

it("ranks a food by its name in the user's language too", async () => {
await seed('test_zorp_ciqual', 'Chocolate zorpleck, from bakery', {
source: 'ciqual',
countries: ['fr'],
names: [{ name: 'Zorpleck au chocolat, artisanal', lang: 'fr' }],
});
// A product named exactly what's typed
await seed('test_zorp_off', 'Zorpleck au chocolat', {
kind: 'branded',
source: 'off',
countries: ['fr'],
quality: 0.6,
verified: false,
basis: 'label',
});
const results = await foodDb.search('zorpleck au chocolat', {
country: 'FR',
});
// The French table's food, found by its French name, leads (a near
// miss search adds real products after these two)
expect(results.slice(0, 2).map((r) => r.foodId)).toEqual([
'test_zorp_ciqual',
'test_zorp_off',
]);
});
});

describe('barcodes and single foods', () => {
it('finds a barcode however it was written', async () => {
for (const code of ['099999888775', '0099999888775', '00099999888775']) {
Expand Down
48 changes: 35 additions & 13 deletions packages/backend/src/food/food-db.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,22 +230,44 @@ export class FoodDbService {
SELECT h.id,
h.id IN (SELECT "foodId" FROM mine) AS mine,
extensions.word_similarity(${key}, h."searchText") AS wsim,
extensions.similarity(${key}, h."searchText") AS sim,
h."searchText" LIKE ${key + '%'} AS prefix,
-- The search text joins every name ("chocolate croissant … pain
-- au chocolat"), so a food also scores on each name of its own
GREATEST(
extensions.similarity(${key}, h."searchText"),
(SELECT max(extensions.similarity(${key}, lower(n.name)))
FROM food_names n WHERE n."foodId" = h.id)
) AS sim,
(h."searchText" LIKE ${key + '%'} OR EXISTS (
SELECT 1 FROM food_names n
WHERE n."foodId" = h.id AND lower(n.name) LIKE ${key + '%'}
)) AS prefix,
${country} = ANY(h.countries) AS local,
h.kind, h.quality, h.popularity, h.verified
h.kind, h.quality, h.popularity, h.verified,
lower(h.name) AS name, lower(coalesce(h.brand, '')) AS brand
FROM cand c JOIN foods h ON h.id = c.id
),
ranked AS (
SELECT id, mine, wsim, name, brand,
((CASE WHEN mine THEN 1.0 ELSE 0 END)
+ (CASE WHEN local THEN 0.25 ELSE 0 END)
+ 0.5 * sim + 0.2 * wsim
+ (CASE WHEN prefix THEN 0.3 ELSE 0 END)
+ (CASE WHEN kind = 'generic' THEN 0.05 ELSE 0 END)
+ (CASE WHEN verified THEN 0.2 ELSE 0 END)
+ 0.5 * quality
+ 0.1 * least(1.0, ln(1 + popularity) / ln(101))) AS score
FROM scored
),
-- One food per name and brand before the limit: dozens of products
-- called "Baguette" would otherwise fill it, and the national
-- table's baguette would never be seen
best AS (
SELECT DISTINCT ON (name, brand) id, mine, wsim, score
FROM ranked
ORDER BY name, brand, score DESC, id
)
SELECT id, mine, wsim::float8 AS wsim,
((CASE WHEN mine THEN 1.0 ELSE 0 END)
+ (CASE WHEN local THEN 0.25 ELSE 0 END)
+ 0.5 * sim + 0.2 * wsim
+ (CASE WHEN prefix THEN 0.3 ELSE 0 END)
+ (CASE WHEN kind = 'generic' THEN 0.05 ELSE 0 END)
+ (CASE WHEN verified THEN 0.2 ELSE 0 END)
+ 0.5 * quality
+ 0.1 * least(1.0, ln(1 + popularity) / ln(101)))::float8 AS score
FROM scored
SELECT id, mine, wsim::float8 AS wsim, score::float8 AS score
FROM best
ORDER BY score DESC, id
LIMIT ${limit * 2}`;

Expand Down
Loading
Loading