This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
|
||||
const datasetUrl = 'https://data.ademe.fr/data-fair/api/v1/datasets/agribalyse-31-synthese';
|
||||
const outputPath = resolve(dirname(fileURLToPath(import.meta.url)), '../src/data/agribalyse.js');
|
||||
const version = '3.2';
|
||||
const fields = {
|
||||
climate: ['Changement_climatique', 'kg CO2 eq/kg de produit'],
|
||||
landUse: ['Utilisation_du_sol', 'Pt/kg de produit'],
|
||||
waterScarcity: ['Épuisement_des_ressources_eau', 'm3 depriv./kg de produit'],
|
||||
singleScore: ['Score_unique_EF', 'mPt/kg de produit']
|
||||
};
|
||||
|
||||
function finite(value) {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
async function getJson(url) {
|
||||
const response = await fetch(url, { headers: { Accept: 'application/json' } });
|
||||
if (!response.ok) throw new Error(`ADEME request failed: ${response.status} ${url}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function importAgribalyse({ fetchJson = getJson, write = writeFile } = {}) {
|
||||
const metadata = await fetchJson(datasetUrl);
|
||||
if (!metadata.description?.includes(`AGRIBALYSE® v${version}`)) {
|
||||
throw new Error('ADEME dataset version changed; review schema and units before importing.');
|
||||
}
|
||||
for (const [key, [column, unit]] of Object.entries(fields)) {
|
||||
const schema = metadata.schema?.find((item) => item.key === column);
|
||||
if (!schema || !schema.description?.includes(unit)) {
|
||||
throw new Error(`Missing or changed ${column} (${unit}); review the ADEME schema.`);
|
||||
}
|
||||
}
|
||||
|
||||
const rows = [];
|
||||
let next = `${datasetUrl}/lines?size=500`;
|
||||
while (next) {
|
||||
const page = await fetchJson(next);
|
||||
if (!Array.isArray(page.results)) throw new Error('Invalid ADEME response.');
|
||||
rows.push(...page.results);
|
||||
next = page.next || null;
|
||||
}
|
||||
const products = rows.map((row) => ({
|
||||
id: String(row.Code_AGB || ''),
|
||||
ciqualCode: String(row.Code_CIQUAL || ''),
|
||||
nameEn: row.LCI_Name || '',
|
||||
nameFr: row['Nom_du_Produit_en_Français'] || '',
|
||||
group: row["Groupe_d'aliment"] || '',
|
||||
subgroup: row["Sous-groupe_d'aliment"] || '',
|
||||
preparation: row['Préparation'] || '',
|
||||
delivery: row.Livraison || '',
|
||||
climate: finite(row[fields.climate[0]]),
|
||||
landUse: finite(row[fields.landUse[0]]),
|
||||
waterScarcity: finite(row[fields.waterScarcity[0]]),
|
||||
singleScore: finite(row[fields.singleScore[0]])
|
||||
})).filter((row) => row.id && row.climate !== null);
|
||||
if (products.length < 2000 || new Set(products.map((row) => row.id)).size !== products.length) {
|
||||
throw new Error(`Incomplete or duplicate ADEME dataset (${products.length} records).`);
|
||||
}
|
||||
const snapshot = {
|
||||
version,
|
||||
source: datasetUrl,
|
||||
sourceId: metadata.id,
|
||||
dataUpdatedAt: metadata.dataUpdatedAt,
|
||||
reference: '1 kg of food consumed by the consumer (French-market average)',
|
||||
units: Object.fromEntries(Object.entries(fields).map(([key, [, unit]]) => [key, unit])),
|
||||
products
|
||||
};
|
||||
await mkdir(dirname(outputPath), { recursive: true });
|
||||
await write(outputPath, `// Generated by scripts/importAgribalyse.mjs from ADEME's public finished-food summary.\nexport default ${JSON.stringify(snapshot)};\n`);
|
||||
return products.length;
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const count = await importAgribalyse();
|
||||
console.log(`Imported ${count} AGRIBALYSE ${version} finished-food entries to ${outputPath}`);
|
||||
}
|
||||
Reference in New Issue
Block a user