True_Kart / src /lib /api.ts
naturality-abhirsc
Prepare Docker app for Hugging Face Space
18fa70e
Raw History Blame Contribute Delete
13.7 kB
import { localProducts } from "@/data/products";
import { cacheProduct, getCachedProduct, getCustomProduct } from "@/lib/storage";
import type { Product, ProductInsight, ProductSource, UserProfile } from "@/types";
type OffResponse = {
status: number;
product?: {
product_name?: string;
product_name_en?: string;
generic_name?: string;
brands?: string;
categories?: string;
image_url?: string;
image_front_url?: string;
ingredients_text?: string;
ingredients_text_en?: string;
ingredients_tags?: string[];
allergens_tags?: string[];
traces_tags?: string[];
additives_tags?: string[];
labels_tags?: string[];
countries?: string;
origins?: string;
packaging?: string;
packaging_tags?: string[];
quantity?: string;
nutriments?: Record<string, number | string | undefined>;
nutriscore_grade?: string;
nova_group?: number;
ecoscore_grade?: string;
};
};
const sourceUrls: Record<Exclude<ProductSource, "Community DB">, string> = {
"Open Food Facts": "https://world.openfoodfacts.org/api/v0/product",
"Open Products Facts": "https://world.openproductsfacts.org/api/v0/product",
};
function normalizeBarcode(barcode: string): string {
return barcode.trim().replace(/\s+/g, "");
}
function normalizeNumber(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim()) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
function cleanText(value: string): string {
return value
.replace(/^en:/i, "")
.replace(/^fr:/i, "")
.replace(/^es:/i, "")
.replace(/-/g, " ")
.replace(/_/g, " ")
.trim();
}
function unique(values: Array<string | null | undefined>): string[] {
return [...new Set(values.map((value) => (value ? cleanText(value).toLowerCase() : "")).filter(Boolean))];
}
function titleize(value: string): string {
return value.replace(/\b\w/g, (char) => char.toUpperCase());
}
function splitIngredients(text: string): string[] {
return text
.split(/[,.;]/)
.map((item) => item.trim())
.filter(Boolean)
.slice(0, 25);
}
function mapCategory(raw?: string): Product["category"] {
const value = (raw ?? "").toLowerCase();
if (value.includes("beverage") || value.includes("drink")) return "beverages";
if (value.includes("dairy") || value.includes("milk") || value.includes("yogurt")) return "dairy";
if (value.includes("grain") || value.includes("cereal") || value.includes("rice")) return "grains";
if (value.includes("meat") || value.includes("chicken") || value.includes("beef")) return "meat";
if (value.includes("fruit") || value.includes("vegetable") || value.includes("produce")) return "produce";
if (value.includes("frozen")) return "frozen";
if (value.includes("condiment") || value.includes("sauce")) return "condiments";
if (value.includes("bread") || value.includes("bakery")) return "bakery";
if (value.includes("snack") || value.includes("biscuit") || value.includes("chip")) return "snacks";
return "other";
}
function mapPackagingType(raw: string[]): Product["packaging_type"] {
const joined = raw.join(" ");
if (joined.includes("glass")) return "glass";
if (joined.includes("cardboard") || joined.includes("paper")) return "cardboard";
if (joined.includes("metal") || joined.includes("aluminium") || joined.includes("steel")) return "metal";
if (joined.includes("biodegradable") || joined.includes("compostable")) return "biodegradable";
if (joined.includes("plastic")) return "plastic";
return "mixed";
}
function asNutri(letter?: string): Product["nutri_score"] {
const normalized = (letter ?? "C").toUpperCase();
if (["A", "B", "C", "D", "E"].includes(normalized)) return normalized as Product["nutri_score"];
return "C";
}
function scoreFromNutri(letter: Product["nutri_score"]): number {
const map: Record<Product["nutri_score"], number> = { A: 90, B: 76, C: 58, D: 36, E: 18 };
return map[letter];
}
function scoreFromEco(eco?: string): number {
const map: Record<string, number> = { a: 90, b: 75, c: 58, d: 40, e: 22 };
return map[(eco ?? "c").toLowerCase()] ?? 58;
}
function inferInsights(args: {
nutriScore: Product["nutri_score"];
novaGroup: Product["nova_group"];
sugarPer100g: number | null;
fiber: number | null;
protein: number | null;
preservatives: string[];
labels: string[];
allergens: string[];
traces: string[];
packagingDetails: string[];
ingredients: string[];
}): ProductInsight {
const summary: string[] = [];
const positives: string[] = [];
const cautions: string[] = [];
const fitTags: string[] = [];
if (args.nutriScore === "A" || args.nutriScore === "B") {
summary.push("Nutrition profile looks relatively strong for a packaged product.");
positives.push(`Nutri-Score ${args.nutriScore} suggests a stronger overall nutritional balance.`);
} else if (args.nutriScore === "D" || args.nutriScore === "E") {
summary.push("Nutrition profile is weaker and worth checking closely.");
cautions.push(`Nutri-Score ${args.nutriScore} suggests this may be harder to fit into everyday healthy choices.`);
}
if (args.novaGroup === 4) {
cautions.push("NOVA 4 means this is likely ultra-processed.");
} else if (args.novaGroup === 1 || args.novaGroup === 2) {
positives.push("Lower processing level than many packaged alternatives.");
}
if (args.sugarPer100g !== null) {
if (args.sugarPer100g >= 15) cautions.push(`High sugar at ${args.sugarPer100g}g per 100g.`);
else if (args.sugarPer100g <= 5) positives.push(`Lower sugar at ${args.sugarPer100g}g per 100g.`);
}
if (args.fiber !== null && args.fiber >= 5) positives.push(`Useful fiber content at ${args.fiber}g per 100g.`);
if (args.protein !== null && args.protein >= 10) positives.push(`Higher protein content at ${args.protein}g per 100g.`);
if (args.preservatives.length >= 3) cautions.push("Contains multiple additives or preservatives.");
if (args.allergens.length > 0) cautions.push(`Declared allergens: ${args.allergens.join(", ")}.`);
if (args.traces.length > 0) cautions.push(`May contain traces of ${args.traces.join(", ")}.`);
const joinedLabels = args.labels.join(" ");
if (joinedLabels.includes("vegan")) fitTags.push("vegan");
if (joinedLabels.includes("vegetarian")) fitTags.push("vegetarian");
if (joinedLabels.includes("organic")) positives.push("Carries organic-related labelling.");
const joinedPackaging = args.packagingDetails.join(" ");
if (joinedPackaging.includes("recyclable")) positives.push("Packaging appears to include recyclable materials.");
if (joinedPackaging.includes("plastic")) cautions.push("Packaging includes plastic.");
if (!summary.length) {
summary.push("This product has enough metadata to screen for ingredients, allergens, and general nutrition fit.");
}
if (!args.ingredients.length) {
cautions.push("Ingredient list is incomplete in the source data.");
}
return { summary, positives, cautions, fit_tags: fitTags };
}
function mapApiProduct(barcode: string, data: OffResponse, source: Exclude<ProductSource, "Community DB">): Product {
const product = data.product ?? {};
const nutriments = product.nutriments ?? {};
const nutriScore = asNutri(product.nutriscore_grade);
const ingredientText = product.ingredients_text_en ?? product.ingredients_text ?? "";
const ingredients = ingredientText
? splitIngredients(ingredientText)
: unique(product.ingredients_tags ?? []).map(titleize);
const allergens = unique(product.allergens_tags ?? []).map(titleize);
const traces = unique(product.traces_tags ?? []).map(titleize);
const preservatives = unique(product.additives_tags ?? []).map(titleize);
const labels = unique(product.labels_tags ?? []).map(titleize);
const packagingDetails = unique([...(product.packaging_tags ?? []), product.packaging]).map(titleize);
const quantity = product.quantity?.trim() || "Unknown";
const nutritionalInfo = {
serving_size: quantity !== "Unknown" ? quantity : "100g",
calories: normalizeNumber(nutriments["energy-kcal_100g"] ?? nutriments["energy-kcal"]),
sugar_per_100g: normalizeNumber(nutriments["sugars_100g"]),
protein: normalizeNumber(nutriments["proteins_100g"]),
fat: normalizeNumber(nutriments["fat_100g"]),
carbs: normalizeNumber(nutriments["carbohydrates_100g"]),
fiber: normalizeNumber(nutriments["fiber_100g"]),
sodium: normalizeNumber(nutriments["sodium_100g"]),
salt: normalizeNumber(nutriments["salt_100g"]),
};
const insights = inferInsights({
nutriScore,
novaGroup: [1, 2, 3, 4].includes(Number(product.nova_group)) ? (Number(product.nova_group) as 1 | 2 | 3 | 4) : null,
sugarPer100g: nutritionalInfo.sugar_per_100g,
fiber: nutritionalInfo.fiber,
protein: nutritionalInfo.protein,
preservatives,
labels,
allergens,
traces,
packagingDetails: packagingDetails.map((item) => item.toLowerCase()),
ingredients,
});
return {
id: `prod-${barcode}`,
barcode,
name: product.product_name_en ?? product.product_name ?? product.generic_name ?? "Unknown product",
brand: product.brands ?? "Unknown brand",
category: mapCategory(product.categories),
image_url: product.image_front_url ?? product.image_url ?? "",
quantity,
ingredient_text: ingredientText,
nutritional_info: nutritionalInfo,
ingredients,
allergens,
traces,
preservatives,
labels,
health_score: scoreFromNutri(nutriScore),
environmental_score: scoreFromEco(product.ecoscore_grade),
certifications: labels.slice(0, 6),
country_of_origin: product.origins?.split(",")[0]?.trim() || product.countries?.split(",")[0]?.trim() || "Unknown",
packaging_type: mapPackagingType(packagingDetails.map((item) => item.toLowerCase())),
packaging_details: packagingDetails,
nutri_score: nutriScore,
nova_group: [1, 2, 3, 4].includes(Number(product.nova_group)) ? (Number(product.nova_group) as 1 | 2 | 3 | 4) : null,
ecoscore_grade: product.ecoscore_grade?.toUpperCase() ?? null,
source_url: `${sourceUrls[source]}/${barcode}.json`,
lookup_sources: [source],
fetched_at: new Date().toISOString(),
data_source: source,
insights,
};
}
async function fetchSource(
barcode: string,
source: Exclude<ProductSource, "Community DB">
): Promise<Product | null> {
const response = await fetch(`${sourceUrls[source]}/${barcode}.json`);
if (!response.ok) return null;
const data = (await response.json()) as OffResponse;
if (data.status !== 1) return null;
return mapApiProduct(barcode, data, source);
}
export function findLocalByBarcode(barcode: string): Product | null {
const normalized = normalizeBarcode(barcode);
return localProducts.find((product) => product.barcode === normalized) ?? null;
}
export async function fetchBarcodeProduct(barcode: string): Promise<Product | null> {
const normalized = normalizeBarcode(barcode);
if (!normalized) return null;
const local = findLocalByBarcode(normalized);
if (local) return local;
const custom = getCustomProduct(normalized);
if (custom) return custom;
const cached = getCachedProduct(normalized);
if (cached) return cached;
const sources: Array<Exclude<ProductSource, "Community DB">> = ["Open Food Facts", "Open Products Facts"];
for (const source of sources) {
try {
const product = await fetchSource(normalized, source);
if (product) {
cacheProduct(product);
return product;
}
} catch {
continue;
}
}
return null;
}
export function getUserProductSignals(product: Product, user: UserProfile) {
const userAllergens = user.allergens.map((item) => item.toLowerCase());
const dietary = user.dietary_restrictions.map((item) => item.toLowerCase());
const productTerms = [
...product.ingredients.map((item) => item.toLowerCase()),
...product.allergens.map((item) => item.toLowerCase()),
...product.labels.map((item) => item.toLowerCase()),
product.category.toLowerCase(),
];
const warnings: string[] = [];
const positives: string[] = [];
const allergenHits = product.allergens.filter((item) => userAllergens.includes(item.toLowerCase()));
const traceHits = product.traces.filter((item) => userAllergens.includes(item.toLowerCase()));
if (allergenHits.length) warnings.push(`Contains your allergen: ${allergenHits.join(", ")}.`);
if (traceHits.length) warnings.push(`May contain your allergen: ${traceHits.join(", ")}.`);
if (product.nutritional_info.sugar_per_100g !== null) {
if (product.nutritional_info.sugar_per_100g > user.sugar_limit) {
warnings.push(
`Sugar per 100g (${product.nutritional_info.sugar_per_100g}g) exceeds your daily target (${user.sugar_limit}g).`
);
} else {
positives.push(`Sugar per 100g stays within your current target (${user.sugar_limit}g).`);
}
}
if (dietary.includes("vegan") && productTerms.some((term) => ["milk", "egg", "honey", "beef", "chicken"].includes(term))) {
warnings.push("This may conflict with a vegan preference.");
}
if (dietary.includes("vegetarian") && productTerms.some((term) => ["beef", "chicken", "pork", "fish", "gelatin"].includes(term))) {
warnings.push("This may conflict with a vegetarian preference.");
}
if (dietary.includes("gluten-free") && productTerms.some((term) => ["wheat", "barley", "rye", "gluten"].includes(term))) {
warnings.push("This may conflict with a gluten-free preference.");
}
return { warnings, positives };
}