How to Evaluate Image Text Recognition in Multimodal LLMs: A Pre-Launch Checklist

    This guide describes a reproducible method for testing how accurately multimodal large language models read text and layout in images, using your own data. It covers how to fix evaluation conditions, build and annotate a sample set, measure character error rate, hallucination rate, and structured-output validity, check SVG and front-end code generation, and run an automated scoring script. It ends with a pre-launch checklist.

    Introduction

    Whether a multimodal large language model can read the text and structure in an image determines if it can be used for receipt recognition, document digitization, or interface generation. Many teams decide to launch based only on vendor demos, then find missing characters, wrong reading order, or broken formats on real data. This guide provides a reproducible evaluation method so developers can test a model on their own data and complete checks before launch.

    1. Fix the Evaluation Protocol

    Evaluation results can only be compared across runs when the protocol stays fixed. Before you start, record the following:

    • Model name, version number, call date, and API endpoint
    • Sampling parameters, such as temperature, top_p, and max_tokens
    • Input image resolution, format, and compression quality
    • The full prompt text, including the system prompt

    Set the sampling temperature to 0. If the API does not guarantee deterministic output, run each sample at least three times, take the median, and record the range of variation. This helps separate model capability from random variation.

    For the sample set, use at least 32 images per task type. Keep at least 8 images each for four conditions: clear, low light, partial occlusion, and small font size. Keep only one copy of each source image to avoid counting images from the same source more than once. Two people annotate independently, and you should calculate their agreement rate. A third person resolves disagreements, and the final annotations serve as the reference answers (ground truth). If the agreement rate is low, revise the annotation guidelines before evaluating the model.

    2. Core Metrics

    The table below defines each metric. For every metric, state the denominator and how it is collected. Otherwise, numbers from different batches cannot be compared.

    Metric Formula or Criterion Denominator Direction Collection Method
    Character error rate (CER) (substitutions + deletions + insertions) / number of reference characters Total number of reference characters Lower is better Script
    Full field match rate A record counts as correct only if its text and direction both match the reference answer Number of sample records Higher is better Script comparison
    Hallucination rate Number of characters without support / total number of characters in the model output Total number of characters in the model output Lower is better Manual review
    Structured parsing success rate Share of outputs that parse as JSON and pass schema validation Total number of requests Higher is better Script validation
    Valid SVG rate Share of outputs that parse as XML with an svg root node Total number of generated outputs Higher is better Script validation
    Render similarity Structural similarity index (SSIM) between the rendered image and the reference image Total number of generated outputs Higher is better Script calculation
    Code runnability rate Share of outputs that build and start without errors Total number of generated outputs Higher is better Script or headless browser

    Hallucination rate requires manual review using the following rules. Check every character in the model output against the image. If a character is visible in the image or can be reasonably recognized, mark it as supported. If no matching strokes appear in the image, and the character cannot be reasonably inferred from context, mark it as unsupported. For example, if the image reads “价格:18元” (Price: 18 yuan) and the model outputs “价格:18元(含税)” (Price: 18 yuan (tax included)), the characters “含税” (tax included) are unsupported. That makes 2 hallucinated characters, and the denominator is the total number of characters in that output. Two people review independently, and a third person resolves disagreements.

    CER uses the number of reference characters as its denominator, and hallucination rate uses the number of model output characters. The two metrics cannot replace each other, so report them separately.

    3. Complex-Layout OCR and Occluded Text Inference

    Vertical traditional Chinese, classical calligraphy, and multilingual posters are three typical difficult cases. If the prompt only says “recognize the text in the image,” the output format is unstable and the results are hard to measure. We recommend asking the model for structured output. The prompt template is as follows:

    1. Identify all text in the image and output one JSON object that contains only a blocks array.
    2. Each element in blocks is ordered by reading order, with the following fields:
    3. - text: the recognized text, keeping the original glyph forms. Do not rewrite, simplify, or correct it.
    4. - bbox: [x1, y1, x2, y2], in original image pixels, with the origin at the top-left corner of the image
    5. - direction: ltr (left to right), rtl (right to left), or ttb (top to bottom)
    6. - confidence: high, medium, or low. Text that is uncertain must be marked as low.
    7. If the overlapping area of two text boxes exceeds half the area of the smaller box, keep only one of them.
    8. Output only the JSON. Do not output explanatory text or use a Markdown code block.

    The bbox coordinate definition must match the evaluation script. The origin stays at the top-left corner of the original image, and units are original image pixels. If the model receives an image that has been resized or compressed, the evaluation script should first convert the coordinates back to the original image size before calculating position error. Otherwise, results from batches with different resolutions cannot be compared.

    The schema is shown below. The top level may contain only the blocks array. Each element must contain four fields, and no extra fields are allowed.

    1. {
    2. "type": "object",
    3. "properties": {
    4. "blocks": {
    5. "type": "array",
    6. "items": {
    7. "type": "object",
    8. "properties": {
    9. "text": {"type": "string"},
    10. "bbox": {
    11. "type": "array",
    12. "items": {"type": "number"},
    13. "minItems": 4,
    14. "maxItems": 4
    15. },
    16. "direction": {"type": "string", "enum": ["ltr", "rtl", "ttb"]},
    17. "confidence": {"type": "string", "enum": ["high", "medium", "low"]}
    18. },
    19. "required": ["text", "bbox", "direction", "confidence"],
    20. "additionalProperties": false
    21. }
    22. }
    23. },
    24. "required": ["blocks"],
    25. "additionalProperties": false
    26. }

    Occluded text inference needs its own rules. If the model cannot identify an occluded character, it should mark the text as low confidence instead of filling it in from context. Filled-in characters count toward the hallucination rate. If the business truly needs inference, output the inferred results separately from the recognized results, and score them separately in the evaluation.

    Complex OCR failures fall into the following categories. Classifying failures shows where problems cluster, and helps the team decide whether to fix the prompt, add data, or change the model.

    • Omission: text appears in the image but is missing from the output. This happens most often with small fonts and partially occluded samples.
    • Misrecognition: a visually similar character is recognized incorrectly, such as a similar-looking character or mixed simplified and traditional forms.
    • Glyph rewriting: the model automatically replaces an archaic or variant character with a modern standard character. This is common in classical calligraphy and vertical traditional Chinese samples, and it directly causes full field match failures.
    • Reading order errors: in vertical or multi-column layouts, the reading order differs from the reference answer.
    • Direction errors: the direction field does not match the actual text orientation.
    • Bbox offset: the bbox differs substantially from the actual text position.
    • Structural failures: the output is not valid JSON, or fields are missing, have the wrong type, or include extra fields.
    • Hallucination: the output contains text that does not appear in the image.
    • Confidence miscalibration: the model marks blurry text as high confidence, or marks clear text as low confidence.

    At the end of each evaluation round, count the failures in each category and attach two or three representative samples for review.

    4. SVG and Front-End Code Generation Evaluation

    The output of these tasks is executable code. The evaluation focuses on whether the code can be parsed, whether it renders, and how closely the rendered result matches the reference image.

    For SVG, the evaluation has three steps. The first step checks validity: the output must parse as XML, and the root node must be svg. The second step renders the SVG to PNG, keeping the same dimensions as the reference image. The third step compares the two images using the structural similarity index (SSIM). SSIM ranges from -1 to 1, and values closer to 1 indicate higher similarity. The team should set the pass threshold based on its business tolerance and should not copy thresholds from other teams.

    For front-end code, the evaluation also has two steps. The first step is building and starting the code: check whether the HTML, CSS, JavaScript, or component code builds in a clean environment, and whether the runtime produces console errors. The second step is visual comparison: take a screenshot with a headless browser, then compare its similarity with the reference interface. If the code loads external resources, confirm that those resources are available before evaluating. Otherwise, screenshot results will vary with the network environment.

    Common failures in SVG and front-end code include syntax errors, out-of-bounds coordinates, missing elements, wrong colors or positions, blank renders, missing dependencies, references to external URLs, and build errors.

    Parse XML output from the model with defusedxml to prevent parsing attacks such as entity expansion. Do not run generated code directly in an environment with network access. Run it in an isolated container, and limit CPU, memory, and execution time.

    5. Automated Checking Code

    The script below includes CER calculation, OCR output validation, field matching, bbox intersection over union (IoU) calculation, and SVG validation. The required packages are jsonschema and defusedxml, which you can install with pip install jsonschema defusedxml.

    1. import json
    2. from jsonschema import validate, ValidationError
    3. from defusedxml import ElementTree as ET
    4. def cer(ref: str, hyp: str) -> float:
    5. """Compute character-level edit distance, then divide by the number of reference characters."""
    6. m, n = len(ref), len(hyp)
    7. if m == 0:
    8. return 0.0 if n == 0 else 1.0
    9. prev = list(range(n + 1))
    10. for i in range(1, m + 1):
    11. cur = [i] + [0] * n
    12. for j in range(1, n + 1):
    13. cost = 0 if ref[i - 1] == hyp[j - 1] else 1
    14. cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost)
    15. prev = cur
    16. return prev[n] / m
    17. def check_ocr_output(raw: str, schema: dict) -> tuple[bool, str]:
    18. """Return (passed, failure type)."""
    19. try:
    20. data = json.loads(raw)
    21. except json.JSONDecodeError:
    22. return False, "json_parse_error"
    23. try:
    24. validate(instance=data, schema=schema)
    25. except ValidationError:
    26. return False, "schema_error"
    27. return True, "ok"
    28. def field_exact_match(ref_blocks: list, hyp_blocks: list) -> bool:
    29. """Compare text and direction in reading order. Bbox and confidence are tracked separately."""
    30. if len(ref_blocks) != len(hyp_blocks):
    31. return False
    32. return all(
    33. r["text"] == h["text"] and r["direction"] == h["direction"]
    34. for r, h in zip(ref_blocks, hyp_blocks)
    35. )
    36. def iou(a: list, b: list) -> float:
    37. """Compute the intersection over union of two [x1, y1, x2, y2] boxes."""
    38. x1, y1 = max(a[0], b[0]), max(a[1], b[1])
    39. x2, y2 = min(a[2], b[2]), min(a[3], b[3])
    40. inter = max(0.0, x2 - x1) * max(0.0, y2 - y1)
    41. area_a = (a[2] - a[0]) * (a[3] - a[1])
    42. area_b = (b[2] - b[0]) * (b[3] - b[1])
    43. union = area_a + area_b - inter
    44. return inter / union if union > 0 else 0.0
    45. def check_svg(raw: str) -> tuple[bool, str]:
    46. """Check that the SVG can be parsed and that the root node is svg."""
    47. try:
    48. root = ET.fromstring(raw)
    49. except ET.ParseError:
    50. return False, "xml_parse_error"
    51. tag = root.tag.split("}")[-1]
    52. if tag != "svg":
    53. return False, "root_not_svg"
    54. return True, "ok"

    The script only makes pass/fail judgments. It does not set thresholds for you. Teams should set the IoU and SSIM thresholds based on business requirements and record them in the evaluation report.

    6. Pre-Launch Checklist

    Before launch, confirm each item below. If any item fails, fix it before deciding whether to launch.

    1. The protocol is recorded: model version, call date, sampling parameters, image preprocessing, and the full prompt text are all archived.
    2. The sample set is complete: each task type has at least 32 samples, each of the four conditions has at least 8 samples, and there are no duplicate images from the same source.
    3. Annotations are reliable: the agreement rate between the two annotators is calculated, and disagreements were resolved by a third person.
    4. Outputs are parseable: the structured parsing success rate meets the threshold set by the team, and failed samples are saved.
    5. Hallucinations are acceptable: hallucination rate was assessed by manual review and checked against business tolerance.
    6. Failures are classified: the count and representative samples for each failure type are compiled and mapped to a fix plan.
    7. Code is verified: the valid SVG rate, render similarity, or code runnability rate meets its threshold.
    8. Privacy is handled: images containing personal information are anonymized, and logs do not record original images or sensitive fields.
    9. Keys are isolated: API keys are stored in environment variables or a key management service, not in code or the repository.
    10. A rollback plan is ready: if online performance drops, the team can switch back to the previous model version or a manual workflow.

    After completing these checks, launch with a small traffic canary and keep sampling and reviewing online results. Whenever the model version changes, repeat the evaluation starting from the protocol in Section 1.