A Practical Guide to Multimodal AI: From UI Screenshot Replication to Structured Receipt Extraction

    This article provides a practical engineering guide for implementing multimodal AI capabilities—such as image understanding and document parsing—as replaceable infrastructure. It covers model selection criteria, adapter-based architecture design, and detailed workflows for three core tasks: replicating UI screenshots into front-end code, extracting structured data from receipts and handwritten forms, and enabling question-answering over long documents and videos. The guide also includes actionable validation rules, cost measurement methods, and compliance considerations for production deployment.

    1. Background and Model Selection

    Many teams rely on a single vendor’s API for image understanding and document parsing. When the service provider adjusts free-tier limits or daily call caps, batch processing jobs can be interrupted without warning. Multimodal capabilities should therefore be designed as swappable infrastructure, with business logic decoupled from any specific vendor.

    Multimodal tasks generally fall into three categories: converting UI screenshots into front-end code, extracting structured data from receipts and forms, and enabling retrieval and Q&A over long documents and videos. All three tasks require the model to comprehend content, spatial position, and relational attribution simultaneously. Standard OCR only outputs a text stream, losing positional information—making it impossible to determine, for example, which field a number belongs to.

    Model selection can be evaluated across five dimensions: visual grounding capability, long-context handling, structured output reliability, cost, and deployment method. A single test sample is insufficient to draw conclusions. Follow these steps instead:

    1. Build a representative sample set from real business data, covering normal documents, blurry scans, handwritten forms, stamped documents, and multi-page files. Sample size should scale with business volume; the key is including edge cases.
    2. Define evaluation metrics per task type, such as field-level accuracy, field completeness rate, JSON validity rate, and bounding-box hit rate.
    3. Test all candidate models using the same sample set and the same prompt templates. Record every failure case.
    4. Measure cost empirically: track input tokens, output tokens, image/video token multipliers, and retry counts per sample, then calculate the average cost per document. Do not substitute estimates for measured data.
    5. For self-hosted deployments, measure GPU memory usage and single-inference latency. Record batch sizes and concurrency levels to verify whether business latency requirements are met on the target hardware.

    It is recommended to add an adapter layer between business code and the underlying model:

    1. Business Layer
    2. -> Task Interfaces (extract_fields / generate_ui / summarize_doc)
    3. -> Model Adapter (unified I/O, timeout control, retries, call logging)
    4. -> Model Service (managed API or self-hosted instance)

    Switching models requires only modifying the adapter layer; business logic and validation rules remain unchanged. The adapter should also log per-call latency, token usage, and error types to support cost analysis.

    2. UI Replication

    UI replication is the most direct vision-to-code scenario. A reliable workflow typically includes the following steps:

    1. Layout recognition: identify navigation bars, card list areas, detail sections, and bottom action bars.
    2. Component decomposition: extract recurring structures into reusable card components to avoid generating excessive repetitive markup.
    3. Style tokenization: centralize colors, spacing, border radii, and font sizes into CSS variables for easy future adjustments.
    4. Image placeholders: use placeholder elements for images while preserving semantic descriptions, to be replaced later with production assets.
    5. State-driven interactions: implement actions like likes, comment expansion, and progress bar dragging via state management—not hardcoded into the page.
    6. Iterative refinement: address one modification point per round. Each round’s input should contain only the previous version of the code and the current change request, avoiding irrelevant context that could degrade output quality. Save each version as a separate file for easy rollback.

    Prompts should clearly specify structure, format, and output scope:

    1. Task: Reconstruct the page structure and interactions from the screenshot.
    2. Requirements:
    3. 1. Use semantic HTML tags; use list elements for list areas.
    4. 2. Use placeholder elements for images, retaining alt and data-topic attributes.
    5. 3. Output only a single complete HTML file, with styles in a style tag.
    6. 4. Write interaction logic in a script tag, without external libraries.

    Here is a complete skeleton that can be opened directly in a browser:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8" />
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    6. <title>Note List</title>
    7. <style>
    8. :root { --card-radius: 12px; --gap: 16px; }
    9. .note-list { display: grid; gap: var(--gap); padding: var(--gap); }
    10. .note-card { border-radius: var(--card-radius); background: #fff; padding: var(--gap); }
    11. .note-cover { width: 100%; height: 160px; background: #e5e7eb; object-fit: cover; }
    12. </style>
    13. </head>
    14. <body>
    15. <main class="note-list">
    16. <article class="note-card" data-topic="outdoor camping">
    17. <img class="note-cover" src="placeholder.jpg" alt="Outdoor camping cover" />
    18. <h3 class="note-title">Weekend Camping Gear Checklist</h3>
    19. <button class="like-btn" aria-pressed="false">Like</button>
    20. </article>
    21. </main>
    22. <script>
    23. document.querySelectorAll('.like-btn').forEach(btn => {
    24. btn.addEventListener('click', () => {
    25. const pressed = btn.getAttribute('aria-pressed') === 'true';
    26. btn.setAttribute('aria-pressed', String(!pressed));
    27. });
    28. });
    29. </script>
    30. </body>
    31. </html>

    Before running, prepare a placeholder image file or replace the src attribute with an accessible placeholder URL. This skeleton has no external dependencies.

    After generating the code, check three things: whether tags are semantic, whether nesting levels are reasonable, and whether interaction states are maintained through attributes or data structures. A large number of meaningless nested div elements typically indicates that the prompt lacked structural constraints—add rules and regenerate.

    Image Placeholders and Asset Retrieval

    Images in screenshots are often low-resolution. Cropping them directly introduces blurry content into the page and may raise copyright concerns. A safer approach is to generate placeholder elements, record the image topic via a data-topic attribute, and then generate search keywords to find candidates in your own asset library or licensed stock photo repositories.

    If retrieval fails, retain the placeholder and mark the record as “assets pending”—do not fill the gap with unrelated images. Search results require manual confirmation of copyright and content safety, with reviewer, review date, and license scope documented. After replacing with production assets, re-check the page rendering.

    3. Receipt and Handwritten Material Extraction

    Why Plain OCR Is Insufficient

    For an invoice or a stamped document, the model must not only read the field values but also determine each value’s position, attribution, and source. Whether an amount appears in the “total incl. tax” row or in the remarks section makes a material difference. Output must therefore include positional information and distinguish between printed and handwritten content.

    Field Definition

    Using an invoice as an example, define fields as follows:

    Field Type Required Description
    invoice_no string Yes Invoice number
    issue_date date (YYYY-MM-DD) Yes Date of issue
    buyer_name string Yes Buyer name
    seller_name string Yes Seller name
    amount_excl_tax number Yes Amount excluding tax
    tax_amount number Yes Tax amount
    amount_incl_tax number Yes Total amount incl. tax
    handwritten_note string No Handwritten remark

    Output Format

    Instruct the model to output only a single JSON object, with each field carrying position and source information:

    1. {
    2. "doc_type": "invoice",
    3. "page_count": 1,
    4. "fields": [
    5. {
    6. "name": "invoice_no",
    7. "value": "Sample Number",
    8. "source": "printed",
    9. "bbox": [120, 80, 360, 110],
    10. "page": 1,
    11. "self_confidence": 0.92,
    12. "needs_review": false
    13. }
    14. ],
    15. "stamps": [{"present": true, "bbox": [500, 600, 640, 740]}]
    16. }

    Model self-reported confidence should not be treated as actual accuracy. Calibrate it against test samples—examine the real error rate across different confidence intervals—before deciding on thresholds.

    Prompt Template

    1. Task: Extract specified fields from the receipt image. Output only a single JSON object.
    2. Rules:
    3. 1. Strictly follow the given schema. If a field is not found, set its value to null. Do not guess.
    4. 2. Set source to "printed" for printed content and "handwritten" for handwritten content.
    5. 3. Output stamp regions separately under stamps; do not include them as field values.
    6. 4. Mark unrecognized characters with "?" and set needs_review to true for that field.
    7. 5. Format dates as YYYY-MM-DD. Keep amounts to two decimal places.
    8. 6. Do not output any text other than the JSON object.

    Validation Rules

    After the model produces output, programmatic validation should take priority over manual review. At minimum, include the following checks:

    • Format validation: Can the JSON be parsed? Are field types correct? Can dates be parsed?
    • Completeness validation: Do all required fields exist?
    • Cross-field validation: Does amount excluding tax plus tax amount equal the total amount including tax? Document the allowable rounding tolerance explicitly in the rules.
    • Position validation: Are bounding boxes within image boundaries? Does the page number match the actual page count?
    • Retry strategy: On JSON parse failure, append the error message to the original prompt and retry, up to two times. If it still fails, route to the manual review queue.

    Manual Review

    Reviews should be tiered by risk. Critical fields—amounts, dates, invoice numbers—should go through full review whenever any of the following occur: a needs_review flag, a cross-field validation failure, or a format anomaly. Other fields can be spot-checked by sampling ratio. Each review session should record the reviewer, the before/after values, and the reason for modification, to support subsequent analysis of model error patterns.

    Data Privacy, Authorization, and Retention

    Handwritten documents may contain names, phone numbers, ID numbers, addresses, and bank account details. Follow these steps before processing:

    1. Extract only the minimum set of fields required by the business. Do not extract unrelated personal information.
    2. Mask sensitive fields such as ID numbers, phone numbers, and bank account numbers in displays and logs. Do not write raw values into logs.
    3. Confirm the legal basis for data processing and retain authorization records.
    4. Before sending data to third-party models, verify the service provider’s data retention policy and cross-border transfer requirements.
    5. Follow contractual and regulatory retention periods. Delete original images and intermediate results upon expiry.

    4. Long Document and Video Understanding

    Long Documents

    Documents of hundreds of pages cannot be fed into a model in a single pass. A common approach is hierarchical processing: first extract per page, then generate section-level summaries, and finally answer questions based on summaries and original excerpts. Every excerpt must retain its page number, and answers should cite page numbers for manual verification.

    Splitting can follow chapter headings or fixed page counts, with some overlapping content retained to avoid truncating sentences that span pages. For retrieval, first identify relevant pages, then feed those pages’ images or text to the model for answering.

    The Q&A prompt should constrain the model to the provided source material:

    1. You will answer questions based on the following excerpts with page numbers.
    2. Requirements:
    3. 1. Use only information from the excerpts. If the answer is not in the excerpts, respond "Not mentioned in the provided material."
    4. 2. Cite the source page number after each conclusion, e.g., (Page 12).
    5. 3. Do not infer numbers or dates that are not explicitly provided.

    Videos

    The cost of processing long videos is primarily driven by the number of frames sampled. Two common strategies: sample frames at fixed time intervals, or sample only when the scene changes significantly. The sampling interval must be tested against business samples—it should retain critical frames while keeping the total frame count manageable. If the video contains speech, first transcribe it into timestamped text, then combine it with visual information for output.

    Every conclusion should include a timestamp, e.g., “A device model label appears at 03:12.” During spot checks, jump directly to the corresponding timestamp to verify.

    5. Validation, Cost, and Compliance

    Pre-Launch Checklist

    Check Item Approach
    Evaluation set Cover normal documents, blurry scans, handwritten forms, stamped documents, and multi-page files
    Regression testing Re-run the same evaluation set after every model or prompt change
    Output validation All four rule types must pass: format, completeness, cross-field, and position
    Manual review Full review for critical fields; ratio-based spot checks for other fields
    Failure fallback Items that fail after retries must have a defined fallback path