Add AI smart menu import (Cargar menú)

Import a menu from PDF, photo, Excel/CSV, web link, or pasted text and turn it
into draft sections + products with Claude.

- Product.aiEstimated JSON flags AI-inferred macros/allergens (migration 0002)
- POST /api/[slug]/import: resolves the source (vision via Sonnet for PDF/photo,
  Haiku for text/CSV/XLSX/web), extracts structured JSON for review only
- POST /api/[slug]/import/apply: writes to the draft in add or replace mode,
  preserving aiEstimated flags; replace wipes the draft first
- Editor: 'Cargar menú' button + glass ImportModal (method -> review -> add/replace),
  'Estimado por IA — verifica' badges, verification disclaimer; ProductEditor shows
  the badge and clears the flag when the value is edited
- Reuses anthropic.ts, upload/guard, shared extractJson (moved to lib/json.ts)
- i18n labels (es/en); adds xlsx dependency for spreadsheet parsing

Verified: build passes; migration applies; apply add/replace persist correctly
with aiEstimated; extract validation + auth guard behave as expected.
This commit is contained in:
Jorem Juárez committed 2026-06-13 20:43:06 -06:00
1 parent 24a412f793
commit 112e95dc28
19 files changed
+819 -16

No files matched your search

+1
View File
@@ -57,6 +57,7 @@ export default async function EditorPage({
macros: p.macros as Record<string, number>,
media: p.media as { type: 'image' | 'video'; path: string; order: number }[],
translationStatus: p.translationStatus as { en?: 'auto' | 'reviewed' },
aiEstimated: p.aiEstimated as { macros?: boolean; allergens?: boolean },
})),
})),
};
+1 -10
View File
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getAnthropic, HAIKU_MODEL } from '@/lib/anthropic';
import { extractJson } from '@/lib/json';
import { pickText } from '@/lib/text';
import type { Locale } from '@/i18n/config';
import type { MenuSnapshot } from '@/lib/types';
@@ -82,13 +83,3 @@ export async function POST(req: Request, { params }: { params: { slug: string }
return NextResponse.json({ error: 'ai_failed' }, { status: 502 });
}
}
// Tolerate models that wrap JSON in prose or code fences.
function extractJson(text: string): string {
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
if (fenced) return fenced[1];
const start = text.indexOf('{');
const end = text.lastIndexOf('}');
if (start !== -1 && end !== -1) return text.slice(start, end + 1);
return text;
}
+68
View File
@@ -0,0 +1,68 @@
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { requireEditor } from '@/lib/guard';
import type { ImportedSection } from '@/lib/import';
export const dynamic = 'force-dynamic';
// Applies a reviewed import to the DRAFT. mode 'replace' wipes the current draft
// first; mode 'add' appends after existing sections. AI-inferred data keeps its
// aiEstimated flags so the editor can badge it.
export async function POST(req: Request, { params }: { params: { slug: string } }) {
const guard = await requireEditor(params.slug);
if ('error' in guard) return guard.error;
const body = await req.json().catch(() => null);
const mode = body?.mode === 'replace' ? 'replace' : 'add';
const sections: ImportedSection[] = Array.isArray(body?.sections) ? body.sections : [];
if (sections.length === 0) {
return NextResponse.json({ error: 'invalid' }, { status: 400 });
}
const restaurantId = guard.restaurant.id;
await prisma.$transaction(async (tx) => {
if (mode === 'replace') {
await tx.product.deleteMany({ where: { restaurantId } });
await tx.section.deleteMany({ where: { restaurantId } });
}
const startOrder =
mode === 'add' ? await tx.section.count({ where: { restaurantId } }) : 0;
for (let si = 0; si < sections.length; si++) {
const s = sections[si];
const section = await tx.section.create({
data: {
restaurantId,
name: (s.name ?? {}) as object,
order: startOrder + si,
},
});
for (let pi = 0; pi < (s.products?.length ?? 0); pi++) {
const p = s.products[pi];
const en = p.name?.en || p.description?.en;
await tx.product.create({
data: {
sectionId: section.id,
restaurantId,
name: (p.name ?? {}) as object,
description: (p.description ?? {}) as object,
price: Number(p.price) || 0,
order: pi,
allergens: Array.isArray(p.allergens) ? p.allergens : [],
dietTags: Array.isArray(p.dietTags) ? p.dietTags : [],
macros: (p.macros ?? {}) as object,
media: [],
// Imported translations come from the model → mark English as auto.
translationStatus: (en ? { en: 'auto' } : {}) as object,
aiEstimated: (p.aiEstimated ?? {}) as object,
},
});
}
}
});
const count = sections.reduce((n, s) => n + (s.products?.length ?? 0), 0);
return NextResponse.json({ ok: true, sections: sections.length, products: count });
}
+45
View File
@@ -0,0 +1,45 @@
import { NextResponse } from 'next/server';
import { requireEditor } from '@/lib/guard';
import { resolveSource, extractMenu, type ImportMethod } from '@/lib/import';
import type { Locale } from '@/i18n/config';
export const dynamic = 'force-dynamic';
export const maxDuration = 120;
// Extracts a menu from an uploaded file / link / pasted text using Claude and
// returns the structure for review. Does NOT touch the draft.
export async function POST(req: Request, { params }: { params: { slug: string } }) {
const guard = await requireEditor(params.slug);
if ('error' in guard) return guard.error;
const form = await req.formData().catch(() => null);
if (!form) return NextResponse.json({ error: 'invalid' }, { status: 400 });
const method = String(form.get('method') ?? '') as ImportMethod;
if (!['file', 'link', 'text'].includes(method)) {
return NextResponse.json({ error: 'invalid_method' }, { status: 400 });
}
const fileEntry = form.get('file');
try {
const source = await resolveSource({
method,
file: fileEntry instanceof File ? fileEntry : null,
link: String(form.get('link') ?? ''),
text: String(form.get('text') ?? ''),
});
const result = await extractMenu(source, guard.restaurant.defaultLocale as Locale);
if (result.sections.length === 0) {
return NextResponse.json({ error: 'nothing_found' }, { status: 422 });
}
return NextResponse.json(result);
} catch (err) {
const code = err instanceof Error ? err.message : 'import_failed';
const known = ['empty_text', 'invalid_link', 'fetch_failed', 'no_file'];
console.error('import extract error', err);
return NextResponse.json(
{ error: known.includes(code) ? code : 'import_failed' },
{ status: known.includes(code) ? 400 : 502 },
);
}
}
@@ -12,6 +12,7 @@ const FIELDS = [
'macros',
'media',
'translationStatus',
'aiEstimated',
'sectionId',
] as const;
+1
View File
@@ -30,6 +30,7 @@ export async function POST(req: Request, { params }: { params: { slug: string }
macros: (body?.macros as object) ?? {},
media: (body?.media as object) ?? [],
translationStatus: (body?.translationStatus as object) ?? {},
aiEstimated: (body?.aiEstimated as object) ?? {},
},
});
return NextResponse.json(product);
+21
View File
@@ -9,6 +9,7 @@ import { api } from './api';
import ProductEditor from './ProductEditor';
import SectionTitleEditor from './SectionTitleEditor';
import VersionHistory from './VersionHistory';
import ImportModal from './ImportModal';
export default function CatalogTab({
slug,
@@ -26,8 +27,10 @@ export default function CatalogTab({
onRestored: (name: string | null) => void;
}) {
const t = useTranslations('editor');
const ti = useTranslations('import');
const locale = useLocale() as Locale;
const [editing, setEditing] = useState<{ product: EditorProduct } | null>(null);
const [importOpen, setImportOpen] = useState(false);
const [dragSection, setDragSection] = useState<string | null>(null);
const [dragProduct, setDragProduct] = useState<{ sectionId: string; id: string } | null>(null);
@@ -55,6 +58,7 @@ export default function CatalogTab({
allergens: created.allergens ?? [],
dietTags: created.dietTags ?? [],
translationStatus: created.translationStatus ?? {},
aiEstimated: created.aiEstimated ?? {},
};
setSections((prev) =>
prev.map((s) => (s.id === sectionId ? { ...s, products: [...s.products, product] } : s)),
@@ -135,6 +139,12 @@ export default function CatalogTab({
>
👁 {t('viewMenu')}
</a>
<button
onClick={() => setImportOpen(true)}
className="glass-pill rounded-full px-4 py-2 text-sm font-medium"
>
✨ {ti('loadMenu')}
</button>
<button
onClick={onPublish}
className="ml-auto rounded-full bg-[var(--accent)] px-5 py-2 text-sm font-semibold text-white shadow"
@@ -256,6 +266,17 @@ export default function CatalogTab({
onDelete={deleteProduct}
/>
)}
{importOpen && (
<ImportModal
slug={slug}
onClose={() => setImportOpen(false)}
onApplied={() => {
// Reload to pull the freshly imported draft into the editor.
window.location.reload();
}}
/>
)}
</div>
);
}
+249
View File
@@ -0,0 +1,249 @@
'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import type { Locale } from '@/i18n/config';
import { pickText } from '@/lib/text';
type Method = 'file' | 'link' | 'text';
type ImportedProduct = {
name: { es?: string; en?: string };
description: { es?: string; en?: string };
price: number;
allergens: string[];
dietTags: string[];
macros: Record<string, number | undefined>;
aiEstimated: { macros?: boolean; allergens?: boolean };
};
type ImportedSection = { name: { es?: string; en?: string }; products: ImportedProduct[] };
type Step = 'input' | 'review';
export default function ImportModal({
slug,
onClose,
onApplied,
}: {
slug: string;
onClose: () => void;
onApplied: () => void;
}) {
const t = useTranslations('import');
const tc = useTranslations('common');
const locale = useLocale() as Locale;
const [step, setStep] = useState<Step>('input');
const [method, setMethod] = useState<Method>('file');
const [file, setFile] = useState<File | null>(null);
const [link, setLink] = useState('');
const [text, setText] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<ImportedSection[]>([]);
const [mode, setMode] = useState<'add' | 'replace'>('add');
async function extract() {
setError(null);
if (method === 'file' && !file) return;
if (method === 'link' && !link.trim()) return;
if (method === 'text' && !text.trim()) return;
setLoading(true);
try {
const form = new FormData();
form.append('method', method);
if (method === 'file' && file) form.append('file', file);
if (method === 'link') form.append('link', link.trim());
if (method === 'text') form.append('text', text);
const res = await fetch(`/api/${slug}/import`, { method: 'POST', body: form });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError(t.has(`errors.${data.error}`) ? t(`errors.${data.error}`) : t('errors.import_failed'));
return;
}
const data = await res.json();
setResult(data.sections);
setStep('review');
} catch {
setError(t('errors.import_failed'));
} finally {
setLoading(false);
}
}
async function apply() {
setLoading(true);
try {
await fetch(`/api/${slug}/import/apply`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sections: result, mode }),
});
onApplied();
} finally {
setLoading(false);
}
}
const totalProducts = result.reduce((n, s) => n + s.products.length, 0);
return (
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-2 backdrop-blur-sm sm:items-center">
<div className="glass flex max-h-[92vh] w-full max-w-lg flex-col gap-4 overflow-y-auto rounded-3xl p-4">
<div className="flex items-center justify-between">
<h3 className="display text-lg font-semibold">{t('title')}</h3>
<button onClick={onClose} className="glass-pill rounded-full px-3 py-1">
✕
</button>
</div>
{step === 'input' && (
<>
{/* Method selector */}
<div className="glass-pill flex rounded-full p-1 text-sm">
{(['file', 'link', 'text'] as Method[]).map((m) => (
<button
key={m}
onClick={() => setMethod(m)}
className={`flex-1 rounded-full py-1.5 font-medium transition ${
method === m ? 'bg-white/70 text-[var(--text)] shadow' : 'text-[var(--text)]/60'
}`}
>
{t(`method.${m}`)}
</button>
))}
</div>
{method === 'file' && (
<label className="flex cursor-pointer flex-col items-center gap-2 rounded-3xl border border-dashed border-[var(--accent)]/40 p-6 text-center">
<span className="text-3xl">📄</span>
<span className="text-sm font-medium">
{file ? file.name : t('filePrompt')}
</span>
<span className="text-xs text-[var(--text)]/55">{t('fileHint')}</span>
<input
type="file"
hidden
accept=".pdf,.csv,.xlsx,.xls,image/*"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
/>
</label>
)}
{method === 'link' && (
<input
value={link}
onChange={(e) => setLink(e.target.value)}
placeholder="https://…"
className="glass-soft rounded-2xl px-4 py-3 text-sm outline-none"
/>
)}
{method === 'text' && (
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
rows={8}
placeholder={t('textPrompt')}
className="glass-soft rounded-2xl px-4 py-3 text-sm outline-none"
/>
)}
{error && <p className="text-sm text-red-600">{error}</p>}
<p className="rounded-2xl bg-amber-50/70 px-3 py-2 text-xs text-amber-800">
⚠️ {t('disclaimer')}
</p>
<button
onClick={extract}
disabled={loading}
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
>
{loading ? t('extracting') : t('extract')}
</button>
</>
)}
{step === 'review' && (
<>
<p className="text-sm text-[var(--text)]/70">
{t('reviewSummary', { sections: result.length, products: totalProducts })}
</p>
<div className="flex flex-col gap-3">
{result.map((s, si) => (
<div key={si} className="glass-soft rounded-2xl p-3">
<div className="display mb-2 font-semibold">
{pickText(s.name, locale) || '—'}
</div>
<div className="flex flex-col gap-1.5">
{s.products.map((p, pi) => (
<div key={pi} className="rounded-xl bg-white/40 px-3 py-2 text-sm">
<div className="flex justify-between gap-2">
<span className="font-medium">{pickText(p.name, locale) || '—'}</span>
<span className="text-[var(--accent)]">${(p.price ?? 0).toFixed(2)}</span>
</div>
{pickText(p.description, locale) && (
<p className="text-xs text-[var(--text)]/60">
{pickText(p.description, locale)}
</p>
)}
{(p.aiEstimated?.macros || p.aiEstimated?.allergens) && (
<span className="mt-1 inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-medium text-amber-700">
✨ {t('estimatedBadge')}
</span>
)}
</div>
))}
</div>
</div>
))}
</div>
{/* Add vs replace */}
<div className="flex flex-col gap-2">
<label className="glass-soft flex items-center gap-3 rounded-2xl px-4 py-3 text-sm">
<input
type="radio"
checked={mode === 'add'}
onChange={() => setMode('add')}
/>
{t('modeAdd')}
</label>
<label className="glass-soft flex items-center gap-3 rounded-2xl px-4 py-3 text-sm">
<input
type="radio"
checked={mode === 'replace'}
onChange={() => setMode('replace')}
/>
{t('modeReplace')}
</label>
{mode === 'replace' && (
<p className="text-xs text-red-600">⚠️ {t('replaceWarning')}</p>
)}
</div>
<p className="rounded-2xl bg-amber-50/70 px-3 py-2 text-xs text-amber-800">
⚠️ {t('disclaimer')}
</p>
<div className="flex gap-2">
<button
onClick={() => setStep('input')}
className="glass-pill flex-1 rounded-2xl py-3 text-sm"
>
{tc('back')}
</button>
<button
onClick={apply}
disabled={loading}
className="flex-1 rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
>
{loading ? '…' : t('apply')}
</button>
</div>
</>
)}
</div>
</div>
);
}
+28 -5
View File
@@ -50,6 +50,7 @@ export default function ProductEditor({
macros: draft.macros,
media: draft.media,
translationStatus: draft.translationStatus,
aiEstimated: draft.aiEstimated,
},
});
onSave(draft);
@@ -262,6 +263,7 @@ export default function ProductEditor({
{/* Macros */}
<Field label="Macros">
{draft.aiEstimated.macros && <EstimatedBadge />}
<div className="grid grid-cols-3 gap-2">
{MACRO_KEYS.map((key) => (
<label key={key} className="flex flex-col gap-1 text-xs">
@@ -271,10 +273,15 @@ export default function ProductEditor({
min={0}
value={draft.macros[key] ?? ''}
onChange={(e) =>
set('macros', {
...draft.macros,
[key]: e.target.value === '' ? undefined : Number(e.target.value),
} as Record<string, number>)
setDraft((d) => ({
...d,
macros: {
...d.macros,
[key]: e.target.value === '' ? undefined : Number(e.target.value),
} as Record<string, number>,
// Editing a macro means the user verified it.
aiEstimated: { ...d.aiEstimated, macros: false },
}))
}
className="glass-soft rounded-xl px-2 py-1.5 outline-none"
/>
@@ -285,10 +292,17 @@ export default function ProductEditor({
{/* Allergens */}
<Field label={t('allergens')}>
{draft.aiEstimated.allergens && <EstimatedBadge />}
<Chips
options={ALLERGENS}
selected={draft.allergens}
onToggle={(v) => set('allergens', toggleIn(draft.allergens, v))}
onToggle={(v) =>
setDraft((d) => ({
...d,
allergens: toggleIn(d.allergens, v),
aiEstimated: { ...d.aiEstimated, allergens: false },
}))
}
/>
</Field>
@@ -321,6 +335,15 @@ export default function ProductEditor({
);
}
function EstimatedBadge() {
const t = useTranslations('import');
return (
<span className="inline-flex w-fit items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-medium text-amber-700">
✨ {t('estimatedBadge')}
</span>
);
}
function Field({
label,
children,
+1
View File
@@ -14,6 +14,7 @@ export type EditorProduct = {
macros: Record<string, number>;
media: { type: 'image' | 'video'; path: string; order: number }[];
translationStatus: { en?: 'auto' | 'reviewed' };
aiEstimated: { macros?: boolean; allergens?: boolean };
};
export type EditorSection = {
+4
View File
@@ -3,6 +3,10 @@ import Anthropic from '@anthropic-ai/sdk';
// Claude Haiku — cheapest model that works well for translation and the consultant.
export const HAIKU_MODEL = 'claude-haiku-4-5';
// Sonnet — used for VISUAL menu extraction (PDF / photo of a menu) where
// stronger vision + layout reasoning matters than Haiku provides.
export const SONNET_MODEL = 'claude-sonnet-4-6';
let client: Anthropic | null = null;
export function getAnthropic(): Anthropic {
+223
View File
@@ -0,0 +1,223 @@
import * as XLSX from 'xlsx';
import Anthropic from '@anthropic-ai/sdk';
import { getAnthropic, HAIKU_MODEL, SONNET_MODEL } from './anthropic';
import { extractJson } from './json';
import type { Locale } from '@/i18n/config';
// Structure returned for review (NOT yet applied to the draft).
export type ImportedProduct = {
name: { es?: string; en?: string };
description: { es?: string; en?: string };
price: number;
allergens: string[];
dietTags: string[];
macros: { protein?: number; carbs?: number; sugar?: number; fat?: number; fiber?: number; kcal?: number };
aiEstimated: { macros?: boolean; allergens?: boolean };
};
export type ImportedSection = {
name: { es?: string; en?: string };
products: ImportedProduct[];
};
export type ImportResult = { sections: ImportedSection[] };
export type ImportMethod = 'file' | 'link' | 'text';
const IMAGE_MIMES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'] as const;
const PDF_MIME = 'application/pdf';
const CSV_MIMES = ['text/csv', 'application/csv'];
const XLSX_MIMES = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
];
// Prompt that drives structured extraction. Both ES and EN are requested so the
// imported menu is bilingual from the start; inferred macros/allergens are flagged.
function systemPrompt(defaultLocale: Locale): string {
return [
'You extract a restaurant menu into structured JSON for a digital-menu editor.',
'From the provided source (text, spreadsheet rows, web page, photo, or PDF of a menu),',
'identify SECTIONS and their PRODUCTS. For each product extract: name, description, price.',
'Translate name and description into BOTH Spanish (es) and English (en); if the source is',
`already in one language, translate to the other. The restaurant's primary language is "${defaultLocale}".`,
'Prices: numeric only (strip currency symbols). If a price is missing, use 0.',
'INFER macros (protein, carbs, sugar, fat, fiber in grams; kcal) and allergens ONLY when',
'reasonable from the dish; these are ESTIMATES. Allergen vocabulary (Spanish, lowercase):',
'gluten, lácteos, frutos secos, mariscos, huevo, soya, pescado. Diet tags (Spanish, lowercase):',
'vegetariano, vegano, sin gluten, sin lácteos, keto, picante.',
'Mark aiEstimated.macros=true when you inferred macros (not present in the source), and',
'aiEstimated.allergens=true when you inferred allergens. If a value came directly from the',
'source, set the corresponding flag to false.',
'Reply with ONLY JSON of this exact shape:',
'{"sections":[{"name":{"es":"","en":""},"products":[{"name":{"es":"","en":""},',
'"description":{"es":"","en":""},"price":0,"allergens":[],"dietTags":[],',
'"macros":{"protein":0,"carbs":0,"sugar":0,"fat":0,"fiber":0,"kcal":0},',
'"aiEstimated":{"macros":true,"allergens":true}}]}]}',
'Do not invent dishes that are not in the source. No prose, no code fences.',
].join(' ');
}
// Strip HTML to a compact text blob for link imports.
function htmlToText(html: string): string {
return html
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/&nbsp;/g, ' ')
.replace(/&amp;/g, '&')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 24000);
}
// Convert a spreadsheet (xlsx/xls/csv buffer) into CSV text for the model.
function spreadsheetToText(buffer: Buffer): string {
const wb = XLSX.read(buffer, { type: 'buffer' });
return wb.SheetNames.map((n) => XLSX.utils.sheet_to_csv(wb.Sheets[n]))
.join('\n')
.slice(0, 24000);
}
type Source =
| { kind: 'text'; text: string; visual: false }
| { kind: 'image'; data: string; mediaType: string; visual: true }
| { kind: 'pdf'; data: string; visual: true };
// Resolve any supported input into a Claude-ready source.
export async function resolveSource(input: {
method: ImportMethod;
file?: File | null;
link?: string;
text?: string;
}): Promise<Source> {
if (input.method === 'text') {
const text = (input.text ?? '').trim();
if (!text) throw new Error('empty_text');
return { kind: 'text', text: text.slice(0, 24000), visual: false };
}
if (input.method === 'link') {
const link = (input.link ?? '').trim();
if (!/^https?:\/\//i.test(link)) throw new Error('invalid_link');
const res = await fetch(link, {
headers: { 'User-Agent': 'SmartMenuImporter/1.0' },
redirect: 'follow',
});
if (!res.ok) throw new Error('fetch_failed');
const html = await res.text();
return { kind: 'text', text: htmlToText(html), visual: false };
}
// method === 'file'
const file = input.file;
if (!file) throw new Error('no_file');
const mime = file.type;
const buffer = Buffer.from(await file.arrayBuffer());
if ((IMAGE_MIMES as readonly string[]).includes(mime)) {
return { kind: 'image', data: buffer.toString('base64'), mediaType: mime, visual: true };
}
if (mime === PDF_MIME) {
return { kind: 'pdf', data: buffer.toString('base64'), visual: true };
}
if (CSV_MIMES.includes(mime) || XLSX_MIMES.includes(mime) || /\.(csv|xlsx|xls)$/i.test(file.name)) {
return { kind: 'text', text: spreadsheetToText(buffer), visual: false };
}
// Fallback: treat unknown files as UTF-8 text.
return { kind: 'text', text: buffer.toString('utf8').slice(0, 24000), visual: false };
}
// Run extraction against Claude. Visual sources use Sonnet; text uses Haiku.
export async function extractMenu(
source: Source,
defaultLocale: Locale,
): Promise<ImportResult> {
const client = getAnthropic();
const content: Anthropic.ContentBlockParam[] = [];
if (source.kind === 'image') {
content.push({
type: 'image',
source: { type: 'base64', media_type: source.mediaType as 'image/jpeg', data: source.data },
});
content.push({ type: 'text', text: 'Extract this menu image into the JSON schema.' });
} else if (source.kind === 'pdf') {
content.push({
type: 'document',
source: { type: 'base64', media_type: 'application/pdf', data: source.data },
});
content.push({ type: 'text', text: 'Extract this menu PDF into the JSON schema.' });
} else {
content.push({ type: 'text', text: `MENU SOURCE:\n${source.text}` });
}
const msg = await client.messages.create({
model: source.visual ? SONNET_MODEL : HAIKU_MODEL,
max_tokens: 4000,
system: systemPrompt(defaultLocale),
messages: [{ role: 'user', content }],
});
const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}';
const parsed = JSON.parse(extractJson(text));
return { sections: normalizeSections(parsed?.sections) };
}
// Defensive normalization so a partially-malformed model reply can't crash apply.
function normalizeSections(sections: unknown): ImportedSection[] {
if (!Array.isArray(sections)) return [];
return sections.slice(0, 40).map((s): ImportedSection => {
const sec = s as Record<string, unknown>;
return {
name: localized(sec.name),
products: Array.isArray(sec.products)
? sec.products.slice(0, 200).map(normalizeProduct)
: [],
};
});
}
function normalizeProduct(p: unknown): ImportedProduct {
const prod = (p ?? {}) as Record<string, unknown>;
const macros = (prod.macros ?? {}) as Record<string, unknown>;
const est = (prod.aiEstimated ?? {}) as Record<string, unknown>;
return {
name: localized(prod.name),
description: localized(prod.description),
price: num(prod.price),
allergens: strArray(prod.allergens),
dietTags: strArray(prod.dietTags),
macros: {
protein: optNum(macros.protein),
carbs: optNum(macros.carbs),
sugar: optNum(macros.sugar),
fat: optNum(macros.fat),
fiber: optNum(macros.fiber),
kcal: optNum(macros.kcal),
},
aiEstimated: { macros: !!est.macros, allergens: !!est.allergens },
};
}
function localized(v: unknown): { es?: string; en?: string } {
if (typeof v === 'string') return { es: v };
const o = (v ?? {}) as Record<string, unknown>;
return {
es: typeof o.es === 'string' ? o.es : undefined,
en: typeof o.en === 'string' ? o.en : undefined,
};
}
function strArray(v: unknown): string[] {
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
}
function num(v: unknown): number {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
}
function optNum(v: unknown): number | undefined {
if (v === null || v === undefined || v === '') return undefined;
const n = Number(v);
return Number.isFinite(n) ? n : undefined;
}
+9
View File
@@ -0,0 +1,9 @@
// Tolerate models that wrap JSON in prose or code fences.
export function extractJson(text: string): string {
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
if (fenced) return fenced[1];
const start = text.indexOf('{');
const end = text.lastIndexOf('}');
if (start !== -1 && end !== -1) return text.slice(start, end + 1);
return text;
}