Turning a Restaurant Menu Photo into Structured JSON with a Vision Model: Schema, Prompt and the Pitfalls
Short answer: skip classic OCR and send the photo directly to a vision-capable LLM with a strict JSON schema (sections → dishes → name, original-script name, price, description). Fix image orientation and size before sen
Short answer: skip classic OCR and send the photo directly to a vision-capable LLM with a strict JSON schema (sections → dishes → name, original-script name, price, description). Fix image orientation and size before sending, tell the model to copy only what's visible, validate the output with Pydantic, and keep a small labeled test set, because menus fail in very specific ways.
Restaurant menus are a great real-world extraction problem. They mix languages, use multi-column layouts and decorative fonts, put prices in odd places, and are often photographed at an angle in dim light. I've spent a lot of time photographing menus while traveling, and this is the pipeline I'd suggest if you want to build something similar.
Why not just use OCR?
Traditional OCR (Tesseract, cloud OCR APIs) returns lines of text with coordinates. That's the easy half. The hard half is structure: which price belongs to which dish, which lines are section headers, and which small line is a description rather than a new dish. On a two-column menu with dotted leaders, rebuilding that structure from coordinates is a project of its own.
A vision LLM reads the layout the way a person does and can return the structure directly. The trade-offs: it's slower and costs more per image, and it can invent text that isn't there. Most of this post is about containing that last risk.
What schema should a menu extraction use?
Keep it flat enough for the model to fill reliably, but rich enough to be useful:
from pydantic import BaseModel, Field
from typing import Optional
class Dish(BaseModel):
name: str = Field(description="Dish name as printed, translated to English if not English")
name_original: Optional[str] = Field(description="Exact original-script text, e.g. 親子丼")
price: Optional[str] = Field(description="Price exactly as printed, including currency symbol")
description: Optional[str] = Field(description="Only if printed on the menu")
uncertain: bool = Field(description="True if any part was hard to read")
class Section(BaseModel):
title: Optional[str]
dishes: list[Dish]
class Menu(BaseModel):
language: str = Field(description="Main language of the menu, BCP-47 code")
currency: Optional[str]
sections: list[Section]
Three decisions worth explaining:
- Prices as strings. "¥980", "12/18", "MP" (market price), "+2" add-ons. Parse them into numbers later, in code you control.
-
name_original. Keep the original script. It's what you show to the server when ordering, and it's your best key for de-duplication. -
uncertainflag. Giving the model a legal way to say "I'm not sure" reduces confident guessing.
How do I prepare the image?
Most "bad model output" I've seen was really bad input:
from PIL import Image, ImageOps
import base64, io
def prepare(path: str, long_edge: int = 2048) -> str:
img = Image.open(path)
img = ImageOps.exif_transpose(img) # phone photos are often rotated via EXIF
img = img.convert("RGB")
img.thumbnail((long_edge, long_edge)) # keep aspect ratio
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=90)
return base64.b64encode(buf.getvalue()).decode()
- EXIF orientation is the number-one silent failure. Many libraries ignore it, so the model receives a sideways menu.
- Resolution: very large images get downscaled by the provider anyway; around 2,000 px on the long edge keeps small print readable without wasting tokens.
- One page per image. A photo of two pages at an angle is worse than two straight photos.
What prompt works for menu extraction?
SYSTEM = """You extract restaurant menus from photos into JSON.
Rules:
- Copy only text that is visible in the image. Never invent dishes, prices or descriptions.
- Keep the original-script dish name in name_original.
- If a dish has no printed description, leave description null.
- If text is partly unreadable, still include the dish and set uncertain=true.
- Section headers become Section.title. Toppings and add-ons belong to the section they appear in.
- Prices: copy exactly as printed, including symbols. Do not convert currencies."""
"Never invent" doesn't make hallucination impossible, but combined with a nullable description and the uncertain flag it cuts it down noticeably. The common failure without these rules is the model writing a plausible description for every dish.
How do I call the model with structured outputs?
Here with the OpenAI Python SDK and a JSON schema; most providers now offer an equivalent "structured output" or "JSON schema" mode.
from openai import OpenAI
client = OpenAI()
MODEL = "your-vision-model"
def extract(path: str) -> Menu:
b64 = prepare(path)
resp = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": [
{"type": "text", "text": "Extract this menu."},
{"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
]},
],
response_format={
"type": "json_schema",
"json_schema": {"name": "menu", "schema": Menu.model_json_schema()},
},
)
return Menu.model_validate_json(resp.choices[0].message.content)
Always validate with Pydantic (or Zod in TypeScript) even when the provider promises schema compliance. You want a loud failure, not a silently missing field. See your provider's structured outputs guide for schema features it does and doesn't support; some reject Optional without explicit null types or require additionalProperties: false.
What are the common pitfalls with menu photos?
| Pitfall | What happens | Fix |
|---|---|---|
| Two-column layout | Prices from the right column attach to dishes in the left | Ask for sections in reading order; check that dish and price counts per section match |
| Vertical Japanese text | Lines read in the wrong order | Mention "text may be vertical, read right-to-left columns"; test with real samples |
| Handwritten boards | Low confidence, guessed characters | Rely on uncertain; show those dishes differently in your UI |
| Shared prices ("all rolls 8") | Price missing on each dish | Allow a section-level price note, or post-process |
| Multiple photos of one menu | Duplicate dishes | De-duplicate on normalized name_original + price |
| Glare and dim light | Missing lines | Ask users for a second photo; don't try to "repair" in the prompt |
| Sizes ("S/M/L 9/12/15") | One price picked | Keep the raw string; parse into variants later |
How do I know if it's working?
Build a tiny evaluation set before you tune anything: 20–30 real menu photos across languages and layouts, with hand-labeled dishes and prices. Track three numbers per run:
- Dish recall: labeled dishes found / labeled dishes total.
- Price accuracy: dishes with the exact printed price.
- Hallucination rate: extracted dishes that don't exist on the menu.
The third is the one users feel. One invented dish on a menu destroys trust faster than three missing ones. When you change the prompt, the model or the image size, rerun the set; menu extraction regressions are easy to miss by eye.
Where to go from here
Once you have clean JSON, the interesting parts start: translating dish names with context (a literal translation of "ants climbing a tree" helps nobody), ranking dishes against what a diner already likes, remembering their taste across meals, or generating a reference image for dishes with no photo. ChefBear is a good example of that finished flow from the diner's side: it suggests what to order, remembers your taste and shows a picture of each dish.
FAQ
Is a vision LLM better than OCR for menus?
For structure, usually yes: it pairs dishes with prices and sections directly. For raw character accuracy on clean printed text, dedicated OCR is still very good and cheaper. Some pipelines use both.
How do I stop the model from inventing dish descriptions?
Make the description field nullable, tell the model to copy only visible text, and measure the hallucination rate on a labeled test set.
What image size should I send?
Around 2,000 px on the long edge is a good starting point for menus. Test smaller sizes on your eval set to save cost.
Can this handle handwritten menus?
Partly. Expect more uncertain fields. Show those to users clearly rather than presenting them as confident results.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.