mistralM

Docs

sideBar

Mistral OCR-4 Comprehensive Feature Showcase

Hands-on notebooks and guides for building with the Mistral API.

Mistral OCR-4 Comprehensive Feature Showcase

This notebook demonstrates four core capabilities of Mistral OCR-4 via the Azure AI Foundry endpoint:

#

Feature

Sample File

Key Parameter

1Bounding Box Detectionreceipt.png, mistral7b.pdfinclude_blocks: true
2Block Classificationmistral7b.pdf (all pages)include_blocks: true
3Confidence Scoresreceipt.png, mistral7b.pdf, MS 8-Kconfidence_scores_granularity
4Multilingual CapabilitiesSynthetic image + TranscriptFY25q4.docxAuto-detection

Model: mistral-ocr-4-0 via Azure AI Foundry<br /> Reference: Mistral OCR Docs

0. Setup

import base64
import json
import os
from io import BytesIO
from typing import List

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import Markdown, display
from PIL import Image, ImageDraw

print('Notebook libraries loaded successfully')
from ocr4_utils import OCRConfig

config = OCRConfig.from_env()
AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT = config.endpoint
AZURE_MISTRAL_DOCUMENT_AI_KEY = config.api_key
AZURE_AI_DEPLOYMENT_NAME = config.model_name
REQUEST_HEADERS = config.headers
SAMPLES_DIR = os.path.join(os.path.dirname(os.path.abspath('__file__')), 'samples')

print(f'Model     : {AZURE_AI_DEPLOYMENT_NAME}')
print(f'Samples   : {SAMPLES_DIR}')
import importlib
import ocr4_utils

ocr4_utils = importlib.reload(ocr4_utils)
from ocr4_utils import BLOCK_COLORS, encode_file, ocr_request, sample_path as sample

print('Shared OCR helpers imported.')

1. Bounding Box Detection

OCR-4 returns pixel-precise coordinates for every recognised content block via the include_blocks parameter. Each block carries:

top_left_x  / top_left_y        (origin corner)
bottom_right_x / bottom_right_y (opposite corner)
type                             (see Section 2)
content                          (extracted text)

All coordinates are in image pixels at the DPI reported in page.dimensions.

# ── 1a. API call: receipt image with bounding boxes ─────────────────────────

receipt_payload = {
    'model': AZURE_AI_DEPLOYMENT_NAME,
    'document': {
        'type': 'document_url',
        'document_url': f'data:image/png;base64,{encode_file(sample("receipt.png"))}',
    },
    'include_blocks': True,
    'extract_header': True,
    'extract_footer': True,
    'confidence_scores_granularity': 'page',
}

receipt_response = ocr_request(receipt_payload)
receipt_page     = receipt_response['pages'][0]
receipt_blocks   = receipt_page['blocks']
receipt_dims     = receipt_page['dimensions']

print(f'Blocks detected : {len(receipt_blocks)}')
print(f'Image size      : {receipt_dims["width"]} x {receipt_dims["height"]} px  (DPI {receipt_dims["dpi"]})')
print(f'Model           : {receipt_response["model"]}')
# ── 1b. Raw block data as a DataFrame ───────────────────────────────────────

df_receipt_bb = pd.DataFrame([
    {
        'type':    b['type'],
        'x1':      b['top_left_x'],
        'y1':      b['top_left_y'],
        'x2':      b['bottom_right_x'],
        'y2':      b['bottom_right_y'],
        'width':   b['bottom_right_x'] - b['top_left_x'],
        'height':  b['bottom_right_y'] - b['top_left_y'],
        'content': b['content'][:60].replace('\n', ' ') + ('…' if len(b['content']) > 60 else ''),
    }
    for b in receipt_blocks
])

display(df_receipt_bb)
# ── 1c. Visualise bounding boxes on receipt ──────────────────────────────────

from ocr4_utils import page_confidence, plot_bounding_boxes

plot_bounding_boxes(
    sample('receipt.png'),
    receipt_blocks,
    title='OCR-4 Bounding Box Detection — Parking Receipt (receipt.png)',
    confidence=page_confidence(receipt_page),
)
# ── 1d. Bounding boxes on a PDF page (mistral7b.pdf, page 0) ────────────────

pdf_payload = {
    'model': AZURE_AI_DEPLOYMENT_NAME,
    'document': {
        'type': 'document_url',
        'document_url': f'data:application/pdf;base64,{encode_file(sample("mistral7b.pdf"))}',
    },
    'include_blocks': True,
    'include_image_base64': True,
    'extract_header': True,
    'extract_footer': True,
    'confidence_scores_granularity': 'page',
}

pdf_response = ocr_request(pdf_payload)
print(f'Pages processed : {len(pdf_response["pages"])}')

# Summarise block counts per page
page_summary = [
    {
        'page': p['index'] + 1,
        'blocks': len(p['blocks']) if p.get('blocks') else 0,
        'images': len(p['images']) if p.get('images') else 0,
        'tables': len(p['tables']) if p.get('tables') else 0,
        'has_header': bool(p.get('header')),
        'has_footer': bool(p.get('footer')),
    }
    for p in pdf_response['pages']
]
display(pd.DataFrame(page_summary))
# ── 1e. Bounding boxes on the first PDF page ─────────────────────────────────

from ocr4_utils import page_confidence, plot_page_bounding_boxes

plot_page_bounding_boxes(
    pdf_response['pages'][0],
    title='OCR-4 Bounding Boxes — mistral7b.pdf, Page 1',
    confidence=page_confidence(pdf_response['pages'][0]),
)
# ── 1f. Block area distribution on page 0 ───────────────────────────────────

p0_blocks = pdf_response['pages'][0].get('blocks') or []
areas = [
    (b['type'],
     (b['bottom_right_x'] - b['top_left_x']) * (b['bottom_right_y'] - b['top_left_y']))
    for b in p0_blocks
]

fig, ax = plt.subplots(figsize=(10, 4))
for i, (btype, area) in enumerate(areas):
    color = BLOCK_COLORS.get(btype, '#888888')
    ax.bar(i, area, color=color, alpha=0.8, edgecolor='white')
    ax.text(i, area + 500, btype, ha='center', va='bottom', fontsize=6, rotation=45)

ax.set_xlabel('Block index (reading order)')
ax.set_ylabel('Area (px²)')
ax.set_title('Bounding Box Areas — mistral7b.pdf Page 1 (reading order)', fontweight='bold')
plt.tight_layout()
plt.show()

2. Block Classification

OCR-4 classifies every extracted region into one of 13 semantic block types:

Category

Types

Structuretitle, header, footer
Body texttext, list, aside_text
Specialisedtable, image, equation, code, caption, references, signature

Blocks are returned in reading order and include pixel coordinates, making them useful for downstream layout analysis.

# ── 2a. Collect all blocks across every page of mistral7b.pdf ───────────────

ALL_BLOCK_TYPES = [
    'text', 'title', 'list', 'table', 'image',
    'equation', 'caption', 'code', 'references',
    'aside_text', 'header', 'footer', 'signature',
]

all_blocks = []
for page in pdf_response['pages']:
    for block in (page.get('blocks') or []):
        all_blocks.append({
            'page':    page['index'] + 1,
            'type':    block['type'],
            'content': block['content'],
            'x1':      block['top_left_x'],
            'y1':      block['top_left_y'],
            'x2':      block['bottom_right_x'],
            'y2':      block['bottom_right_y'],
            'width':   block['bottom_right_x'] - block['top_left_x'],
            'height':  block['bottom_right_y'] - block['top_left_y'],
            'area':    (block['bottom_right_x'] - block['top_left_x']) *
                       (block['bottom_right_y'] - block['top_left_y']),
        })

df_blocks = pd.DataFrame(all_blocks)
print(f'Total blocks across {len(pdf_response["pages"])} pages: {len(df_blocks)}')
print()
print(df_blocks['type'].value_counts().to_string())
# ── 2b. Block-type distribution charts ──────────────────────────────────────

type_counts = df_blocks['type'].value_counts()
colors      = [BLOCK_COLORS.get(t, '#888888') for t in type_counts.index]

fig, (ax_bar, ax_pie) = plt.subplots(1, 2, figsize=(14, 5))

# Horizontal bar chart
bars = ax_bar.barh(type_counts.index, type_counts.values,
                   color=colors, alpha=0.85, edgecolor='white')
for bar, val in zip(bars, type_counts.values):
    ax_bar.text(bar.get_width() + 0.3, bar.get_y() + bar.get_height() / 2,
                str(val), va='center', fontsize=9)
ax_bar.set_xlabel('Block count')
ax_bar.set_title('Block Counts by Type\n(mistral7b.pdf, all pages)', fontweight='bold')

# Pie chart — group small slices
threshold = 0.02 * type_counts.sum()
major = type_counts[type_counts >= threshold].copy()
minor_sum = int(type_counts[type_counts < threshold].sum())
if minor_sum > 0:
    major = pd.concat([major, pd.Series([minor_sum], index=['other'])])
pie_labels = [str(t) for t in major.index]
pie_colors = [BLOCK_COLORS.get(lbl, '#AAAAAA') for lbl in pie_labels]
ax_pie.pie(major.values, labels=pie_labels, colors=pie_colors,
           autopct='%1.1f%%', startangle=140, pctdistance=0.82)
ax_pie.set_title('Block Type Proportions', fontweight='bold')

plt.suptitle('OCR-4 Block Classification — mistral7b.pdf',
             fontsize=13, fontweight='bold', y=1.01)
plt.tight_layout()
plt.show()
# ── 2c. Block-type heat-map: type × page ────────────────────────────────────

pages_range = sorted(df_blocks['page'].unique())
pivot = (
    df_blocks.groupby(['type', 'page'])
    .size()
    .unstack(fill_value=0)
    .reindex(columns=pages_range, fill_value=0)
)

fig, ax = plt.subplots(figsize=(max(8, len(pages_range) * 0.8), len(pivot) * 0.7 + 1))
im = ax.imshow(pivot.values, aspect='auto', cmap='YlOrRd')

ax.set_xticks(range(len(pages_range)))
ax.set_xticklabels([f'p{p}' for p in pages_range], fontsize=9)
ax.set_yticks(range(len(pivot.index)))
ax.set_yticklabels(pivot.index, fontsize=9)
ax.set_xlabel('Page')
ax.set_ylabel('Block Type')
ax.set_title('Blocks per Page by Type — mistral7b.pdf', fontsize=12, fontweight='bold')

for i in range(len(pivot.index)):
    for j in range(len(pages_range)):
        val = pivot.values[i, j]
        if val > 0:
            ax.text(j, i, str(val), ha='center', va='center', fontsize=8, color='black')

plt.colorbar(im, ax=ax, label='Block count')
plt.tight_layout()
plt.show()
# ── 2d. One concrete example per detected block type ────────────────────────

print('Block Classification Examples')
print('=' * 72)
for btype in df_blocks['type'].unique():
    row = df_blocks[df_blocks['type'] == btype].iloc[0]
    preview = row['content'][:120].replace('\n', ' ')
    count   = len(df_blocks[df_blocks['type'] == btype])
    print(f'\n  TYPE : {btype.upper():12s}  ({count} occurrences across doc)')
    print(f'  PAGE : {row["page"]}')
    print(f'  BBOX : ({row["x1"]}, {row["y1"]}) → ({row["x2"]}, {row["y2"]})  '
          f'[{row["width"]}×{row["height"]}px]')
    print(f'  TEXT : {preview}{"…" if len(row["content"]) > 120 else ""}')
    print('-' * 72)
# ── 2e. Average bounding-box area per block type ─────────────────────────────

area_stats = (
    df_blocks.groupby('type')['area']
    .agg(['mean', 'median', 'min', 'max', 'count'])
    .sort_values('mean', ascending=False)
    .rename(columns={'mean': 'avg_area', 'median': 'med_area',
                     'min': 'min_area', 'max': 'max_area', 'count': 'n'})
)

fig, ax = plt.subplots(figsize=(11, 5))
colors = [BLOCK_COLORS.get(t, '#888888') for t in area_stats.index]
x_pos = np.arange(len(area_stats))
ax.bar(x_pos, area_stats['avg_area'] / 1_000, color=colors, alpha=0.8)
ax.errorbar(
    x=x_pos,
    y=area_stats['avg_area'].to_numpy() / 1_000,
    yerr=[
        (area_stats['avg_area'] - area_stats['min_area']).to_numpy() / 1_000,
        (area_stats['max_area'] - area_stats['avg_area']).to_numpy() / 1_000,
    ],
    fmt='none', color='gray', capsize=4, linewidth=1,
)
ax.set_xticks(x_pos)
ax.set_xticklabels(area_stats.index, rotation=20, ha='right')
ax.set_ylabel('Average area (×1 000 px²)')
ax.set_xlabel('Block type')
ax.set_title('Mean Bounding-Box Area by Block Type (error bars = min / max)',
             fontweight='bold')
plt.tight_layout()
plt.show()

display(area_stats.style.format({'avg_area': '{:,.0f}', 'med_area': '{:,.0f}',
                                  'min_area': '{:,.0f}', 'max_area': '{:,.0f}'}))

3. Confidence Scores

OCR-4 exposes confidence scoring at two granularities via confidence_scores_granularity:

Value

What you get

"page"Per-page average and minimum confidence score
"word"Per-word score array plus page-level stats

Scores range 0 → 1. Values below ~0.8 typically flag ambiguous characters, low-resolution regions, or unusual fonts.

# ── 3a. Page-level confidence across three document types ────────────────────

DOCS = {
    'Receipt (PNG)': {
        'path': sample('receipt.png'),
        'mime': 'image/png',
    },
    'Mistral 7B Paper (PDF)': {
        'path': sample('mistral7b.pdf'),
        'mime': 'application/pdf',
    },
    'MS 8-K Filing (PDF)': {
        'path': sample('0000950170-25-100226.pdf'),
        'mime': 'application/pdf',
    },
}

doc_responses = {}
for doc_name, info in DOCS.items():
    payload = {
        'model': AZURE_AI_DEPLOYMENT_NAME,
        'document': {
            'type': 'document_url',
            'document_url': f'data:{info["mime"]};base64,{encode_file(info["path"])}',
        },
        'include_blocks': False,
        'confidence_scores_granularity': 'page',
    }
    # Reuse cached responses from earlier sections where available
    if doc_name == 'Receipt (PNG)':
        doc_responses[doc_name] = receipt_response
    elif doc_name == 'Mistral 7B Paper (PDF)':
        doc_responses[doc_name] = pdf_response
    else:
        doc_responses[doc_name] = ocr_request(payload)
    pages = len(doc_responses[doc_name]['pages'])
    print(f'  {doc_name}: {pages} page(s)')

ms8k_response = doc_responses['MS 8-K Filing (PDF)']
# ── 3b. Per-page confidence bar charts ──────────────────────────────────────

def get_page_conf(response: dict) -> List[float]:
    return [
        p['confidence_scores']['average_page_confidence_score']
        for p in response['pages']
        if p.get('confidence_scores')
        and p['confidence_scores'].get('average_page_confidence_score') is not None
    ]


conf_data = {name: get_page_conf(resp) for name, resp in doc_responses.items()}
n_plots   = sum(1 for v in conf_data.values() if v)

fig, axes = plt.subplots(n_plots, 1, figsize=(12, 4 * n_plots))
if n_plots == 1:
    axes = [axes]

plot_idx = 0
for doc_name, scores in conf_data.items():
    if not scores:
        continue
    ax = axes[plot_idx]
    plot_idx += 1
    page_nums = range(1, len(scores) + 1)
    bar_colors = ['#E74C3C' if s < 0.8 else '#2ECC71' for s in scores]
    bars = ax.bar(page_nums, scores, color=bar_colors, alpha=0.85, edgecolor='white')
    ax.axhline(y=0.90, color='gray',  linestyle='--', alpha=0.5, label='90 % threshold')
    ax.axhline(y=np.mean(scores), color='#2980B9', linestyle='-', linewidth=1.5,
               label=f'Mean {np.mean(scores):.3f}')
    ax.set_ylim(0, 1.08)
    ax.set_xlabel('Page')
    ax.set_ylabel('Avg confidence')
    ax.set_title(f'Page-Level Confidence — {doc_name}', fontweight='bold')
    ax.legend(fontsize=9)
    for bar, sc in zip(bars, scores):
        ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.005,
                f'{sc:.3f}', ha='center', va='bottom', fontsize=7)

plt.tight_layout()
plt.show()
# ── 3c. Summary statistics table ────────────────────────────────────────────

summary_rows = []
for doc_name, scores in conf_data.items():
    if not scores:
        continue
    summary_rows.append({
        'Document': doc_name,
        'Pages': len(scores),
        'Min': f'{min(scores):.4f}',
        'Mean': f'{np.mean(scores):.4f}',
        'Max': f'{max(scores):.4f}',
        'Pages < 80%': sum(1 for s in scores if s < 0.8),
        'Pages ≥ 90%': sum(1 for s in scores if s >= 0.9),
    })

display(pd.DataFrame(summary_rows).set_index('Document'))
# ── 3d. Word-level confidence on the receipt image ───────────────────────────

word_payload = {
    'model': AZURE_AI_DEPLOYMENT_NAME,
    'document': {
        'type': 'document_url',
        'document_url': f'data:image/png;base64,{encode_file(sample("receipt.png"))}',
    },
    'include_blocks': True,
    'confidence_scores_granularity': 'word',
}

word_response = ocr_request(word_payload)
word_page     = word_response['pages'][0]
word_conf     = word_page['confidence_scores']
word_scores   = word_conf.get('word_confidence_scores') or []

print(f'Page average confidence : {word_conf["average_page_confidence_score"]:.4f}')
print(f'Page minimum confidence : {word_conf["minimum_page_confidence_score"]:.4f}')
print(f'Individual word scores  : {len(word_scores)} words')
# ── 3e. Word confidence histogram and CDF ───────────────────────────────────

if word_scores:
    page_avg = word_conf['average_page_confidence_score']
    page_min = word_conf['minimum_page_confidence_score']

    fig, (ax_hist, ax_cdf) = plt.subplots(1, 2, figsize=(13, 5))
    confidences = [d["confidence"] for d in word_scores]
    # Histogram
    n, bins, patches_list = ax_hist.hist(
        confidences, bins=25, edgecolor='white', alpha=0.85)
    for patch, b_left in zip(patches_list, bins):
        patch.set_facecolor('#E74C3C' if b_left < 0.8 else '#2ECC71')
    ax_hist.axvline(x=page_avg, color='#2980B9', linestyle='--', linewidth=1.8,
                    label=f'Page avg {page_avg:.3f}')
    ax_hist.axvline(x=page_min, color='#E67E22', linestyle=':', linewidth=1.8,
                    label=f'Page min {page_min:.3f}')
    ax_hist.axvline(x=0.8, color='gray', linestyle='-', alpha=0.4, label='0.80 threshold')
    ax_hist.set_xlabel('Confidence score')
    ax_hist.set_ylabel('Word count')
    ax_hist.set_title('Word Confidence Distribution\n(receipt.png)', fontweight='bold')
    ax_hist.legend(fontsize=9)

    # CDF
    sorted_s = np.sort(confidences)
    cdf = np.arange(1, len(sorted_s) + 1) / len(sorted_s)
    ax_cdf.plot(sorted_s, cdf, color='#E74C3C', linewidth=2)
    ax_cdf.fill_between(sorted_s, 0, cdf, alpha=0.1, color='#E74C3C')
    ax_cdf.axvline(x=0.9, color='gray', linestyle='--', alpha=0.6, label='0.90')
    ax_cdf.axvline(x=0.8, color='orange', linestyle='--', alpha=0.6, label='0.80')
    ax_cdf.set_xlabel('Confidence score')
    ax_cdf.set_ylabel('Cumulative proportion of words')
    ax_cdf.set_title('Cumulative Distribution — Word Confidence', fontweight='bold')
    ax_cdf.legend(fontsize=9)

    plt.tight_layout()
    plt.show()

    low_80 = sum(1 for s in confidences if s < 0.8)
    print(f'\nWords below 80 % confidence : {low_80} / {len(confidences)} '
          f'({100 * low_80 / len(confidences):.1f} %)')
else:
    print('Word-level scores were not returned for this document/request.')
    print(f'Page stats — average: {word_conf["average_page_confidence_score"]:.4f}, '
          f'minimum: {word_conf["minimum_page_confidence_score"]:.4f}')
# ── 3f. Confidence × block type: does structure affect confidence? ───────────
#
# Use the receipt blocks (with word-level confidence call) to relate
# per-block type to per-page average — then do the same for the PDF.

# For the PDF we have page-level scores and block types per page.
pdf_page_confs = {
    p['index']: p['confidence_scores']['average_page_confidence_score']
    for p in pdf_response['pages']
    if p.get('confidence_scores')
    and p['confidence_scores'].get('average_page_confidence_score') is not None
}

# Map each block's page confidence to the block type
type_to_page_conf = []
for block_row in all_blocks:
    page_idx = block_row['page'] - 1
    if page_idx in pdf_page_confs:
        type_to_page_conf.append({
            'type': block_row['type'],
            'page_confidence': pdf_page_confs[page_idx],
        })

if type_to_page_conf:
    df_type_conf = pd.DataFrame(type_to_page_conf)
    agg = df_type_conf.groupby('type')['page_confidence'].agg(['mean', 'std', 'count'])

    fig, ax = plt.subplots(figsize=(10, 4))
    colors_agg = [BLOCK_COLORS.get(t, '#888888') for t in agg.index]
    ax.bar(agg.index, agg['mean'], yerr=agg['std'].fillna(0),
           color=colors_agg, alpha=0.8, capsize=4, edgecolor='white')
    ax.set_ylim(0.7, 1.0)
    ax.set_ylabel('Mean page confidence score')
    ax.set_xlabel('Block type')
    ax.set_title('Page Confidence by Block Type — mistral7b.pdf\n'
                 '(error bars = ±1 std)', fontweight='bold')
    plt.xticks(rotation=20, ha='right')
    plt.tight_layout()
    plt.show()

4. Multilingual Capabilities

Mistral OCR-4 supports 40+ languages with no language parameter required — the model auto-detects script and language.

Supported script families (non-exhaustive):

Family

Languages

LatinEnglish, French, Spanish, German, Italian, Portuguese, Dutch, Polish, Czech, Romanian, Swedish, Danish …
CyrillicRussian, Ukrainian, Bulgarian, Serbian, Kazakh …
ArabicArabic, Farsi, Urdu, Pashto …
CJKChinese (Simplified & Traditional), Japanese, Korean
DevanagariHindi, Marathi, Nepali …
OtherGreek, Hebrew, Thai, Vietnamese, Tamil, Bengali …

Key properties:

  • No language tag needed — one endpoint, all languages
  • Mixed-language documents processed in a single pass
  • Localized number/date formats (e.g. 1.234,56 vs 1,234.56) parsed correctly
  • RTL scripts (Arabic, Hebrew) laid out correctly in reading order
# ── 4a. Build a synthetic multilingual test image via PIL ────────────────────
#
# We create a white-background PNG that contains the same sentence in seven
# European languages together with localized currency amounts, then submit it
# directly to OCR-4 via base64.

def create_multilingual_test_image(width: int = 920, row_h: int = 48) -> bytes:
    """Render one sentence in multiple European languages on a white canvas."""
    rows = [
        ('English',    'The quick brown fox jumps over the lazy dog.  Invoice #12345  Total: $1,234.56'),
        ('Espanol',    'El veloz zorro marron salta sobre el perro perezoso.  Factura #67890  Total: 2.345,67 EUR'),
        ('Francais',   'Le renard brun rapide saute par-dessus le chien paresseux.  Facture #11111  Total: 1 234,56 EUR'),
        ('Deutsch',    'Der schnelle braune Fuchs springt uber den faulen Hund.  Rechnung #22222  Gesamt: 1.234,56 EUR'),
        ('Italiano',   'La volpe marrone veloce salta sopra il cane pigro.  Fattura #33333  Totale: 1.234,56 EUR'),
        ('Portugues',  'A raposa marrom rapida salta sobre o cao preguicoso.  Fatura #44444  Total: R$ 1.234,56'),
        ('Nederlands', 'De snelle bruine vos springt over de luie hond.  Factuur #55555  Totaal: 1.234,56 EUR'),
        ('Polski',     'Szybki brazowy lis przeskakuje nad leniwym psem.  Faktura #66666  Razem: 1 234,56 PLN'),
    ]

    height = row_h * len(rows) + 80
    img    = Image.new('RGB', (width, height), color=(255, 255, 255))
    draw   = ImageDraw.Draw(img)

    # Title bar
    draw.rectangle([(0, 0), (width, 38)], fill=(44, 62, 80))
    draw.text((14, 10), 'Mistral OCR-4 Multilingual Test Image', fill=(255, 255, 255))

    # One row per language
    for i, (lang, text) in enumerate(rows):
        y      = 44 + i * row_h
        bg     = (248, 248, 248) if i % 2 == 0 else (255, 255, 255)
        draw.rectangle([(0, y), (width, y + row_h - 2)], fill=bg)
        draw.text((10,  y + 4),  f'[{lang}]', fill=(52, 73, 94))
        draw.text((130, y + 4),  text,         fill=(0,   0,  0))

    buf = BytesIO()
    img.save(buf, format='PNG')
    return buf.getvalue()


ml_image_bytes   = create_multilingual_test_image()
ml_image_encoded = base64.b64encode(ml_image_bytes).decode('utf-8')

# Preview the test image inline
from IPython.display import Image as IPImage
display(IPImage(data=ml_image_bytes, format='png'))
print(f'Test image created: {len(ml_image_bytes):,} bytes')
# ── 4b. Submit multilingual image to OCR-4 ──────────────────────────────────

ml_payload = {
    'model': AZURE_AI_DEPLOYMENT_NAME,
    'document': {
        'type': 'document_url',
        'document_url': f'data:image/png;base64,{ml_image_encoded}',
    },
    'include_blocks': True,
    'confidence_scores_granularity': 'word',
}

ml_response  = ocr_request(ml_payload)
ml_page      = ml_response['pages'][0]
ml_conf      = ml_page['confidence_scores'] or {}

print('=== Extracted Markdown ===')
print(ml_page['markdown'])
if ml_conf:
    print(f'\nAverage confidence : {ml_conf["average_page_confidence_score"]:.4f}')
    print(f'Minimum confidence : {ml_conf["minimum_page_confidence_score"]:.4f}')
else:
    print('\nConfidence scores not available for this document.')
# ── 4c. Inspect block classification on multilingual content ─────────────────

ml_blocks = ml_page.get('blocks') or []
print(f'Blocks detected: {len(ml_blocks)}')
print()
for b in ml_blocks:
    print(f"  [{b['type']:12s}]  ({b['top_left_x']},{b['top_left_y']}) → "
          f"({b['bottom_right_x']},{b['bottom_right_y']})")
    print(f"               {b['content'][:80].replace(chr(10), ' ')}")
# ── 4d. Real-world multilingual-capable document: MS FY25 Q4 Transcript ──────
#
# The earnings transcript mixes financial terminology, proper nouns,
# and jargon from global markets — a realistic production use-case.

transcript_path = sample('TranscriptFY25q4.docx')
transcript_payload = {
    'model': AZURE_AI_DEPLOYMENT_NAME,
    'document': {
        'type': 'document_url',
        'document_url': (
            'data:application/vnd.openxmlformats-officedocument'
            '.wordprocessingml.document;base64,'
            + encode_file(transcript_path)
        ),
    },
    'include_blocks': True,
    'confidence_scores_granularity': 'page',
    'table_format': 'html',
    'extract_header': True,
    'extract_footer': True,
}

transcript_response = ocr_request(transcript_payload)
n_pages = len(transcript_response['pages'])
print(f'Pages processed: {n_pages}')

# Sample first 500 characters of page 1
print('\n--- Page 1 excerpt ---')
print(transcript_response['pages'][0]['markdown'][:500])
# ── 4e. Confidence comparison across all tested document types ───────────────

def first_page_avg(resp: dict) -> float:
    """Return the first page's average confidence, or NaN."""
    cs = resp['pages'][0].get('confidence_scores') or {}
    return cs.get('average_page_confidence_score', float('nan'))


comparison = {
    'Receipt\n(PNG print)':          first_page_avg(receipt_response),
    'Mistral 7B Paper\n(scanned PDF)': first_page_avg(pdf_response),
    'MS 8-K Filing\n(native PDF)':   first_page_avg(ms8k_response),
    'Earnings Transcript\n(DOCX)':   first_page_avg(transcript_response),
    'Multilingual Image\n(8 languages)': ml_conf.get('average_page_confidence_score', float('nan')),
}

labels = list(comparison.keys())
values = list(comparison.values())
colors = ['#3498DB', '#2ECC71', '#E67E22', '#9B59B6', '#E74C3C']

fig, ax = plt.subplots(figsize=(12, 5))
bars = ax.bar(labels, values, color=colors, alpha=0.85, edgecolor='white', width=0.55)
ax.axhline(y=0.9, color='gray', linestyle='--', alpha=0.6, label='90 % threshold')
ax.set_ylim(0.0, 1.1)
ax.set_ylabel('Average page confidence', fontsize=11)
ax.set_title(
    'OCR-4 Confidence Across Document Types & Languages',
    fontsize=13, fontweight='bold',
)
ax.legend(fontsize=9)

for bar, val in zip(bars, values):
    if not np.isnan(val):
        ax.text(
            bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.015,
            f'{val:.3f}', ha='center', va='bottom', fontsize=10, fontweight='bold',
        )
    else:
        ax.text(
            bar.get_x() + bar.get_width() / 2, 0.05,
            'N/A', ha='center', va='bottom', fontsize=9, color='gray',
        )

plt.tight_layout()
plt.show()
# ── 4f. Word confidence on the multilingual image ────────────────────────────

ml_word_scores = ml_conf.get('word_confidence_scores') or []

if ml_word_scores:
    fig, ax = plt.subplots(figsize=(10, 4))
    confidences = [d["confidence"] for d in ml_word_scores]
    ax.plot(range(len(confidences)), confidences,
            color='#3498DB', linewidth=1.2, alpha=0.8)
    ax.fill_between(range(len(confidences)), confidences,
                    color='#3498DB', alpha=0.15)
    ax.axhline(y=ml_conf['average_page_confidence_score'],
               color='red', linestyle='--', linewidth=1.5,
               label=f'Page avg {ml_conf["average_page_confidence_score"]:.3f}')
    ax.axhline(y=0.8, color='orange', linestyle=':', alpha=0.7, label='0.80 threshold')
    ax.set_xlabel('Word index (reading order)')
    ax.set_ylabel('Confidence')
    ax.set_title('Word-Level Confidence — Multilingual Image (8 European Languages)',
                 fontweight='bold')
    ax.legend(fontsize=9)
    ax.set_ylim(0, 1.05)
    plt.tight_layout()
    plt.show()

    low = [s for s in confidences if s < 0.8]
    print(f'Words total    : {len(confidences)}')
    print(f'Below 80 %     : {len(low)} ({100*len(low)/len(confidences):.1f} %)')
    print(f'Avg confidence : {np.mean(confidences):.4f}')
else:
    print('Word scores returned as empty list — page-level stats above apply.')
# ── 4g. Reference: minimal multilingual payload structure ────────────────────
#
# No language tag is needed.  The same payload works for any of the 40+ languages.

reference_payload = {
    'model': 'mistral-ocr-4-0',          # or AZURE_AI_DEPLOYMENT_NAME
    'document': {
        'type': 'document_url',
        # Supported MIME types for multilingual content:
        #   image/png · image/jpeg · image/avif
        #   application/pdf
        #   application/vnd.openxmlformats-officedocument.wordprocessingml.document
        #   application/vnd.openxmlformats-officedocument.presentationml.presentation
        #   application/epub+zip
        'document_url': 'data:<mime>;base64,<base64-encoded-content>',
    },
    # ↓ Feature flags shown in earlier sections
    'include_blocks': True,                      # Section 1 & 2
    'confidence_scores_granularity': 'word',     # Section 3 — 'page' | 'word'
    'extract_header': True,
    'extract_footer': True,
    'table_format': 'html',                      # None | 'markdown' | 'html'
    # Optional: annotate images with structured JSON schema
    # 'bbox_annotation_format': { 'type': 'json_schema', 'json_schema': { ... } },
    # 'document_annotation_format': { 'type': 'json_schema', 'json_schema': { ... } },
}

print(json.dumps(reference_payload, indent=2))

Summary

Feature

Parameter(s)

Key Result

Bounding Boxinclude_blocks: truePixel-precise (x1,y1,x2,y2) for every block, in reading order
Block Classificationinclude_blocks: true13 semantic types: title, text, list, table, image, equation, caption, code, references, aside_text, header, footer, signature
Confidence Scoresconfidence_scores_granularity: 'page' | 'word'Page-level avg/min or individual word scores; flags degraded regions
Multilingual(none required)40+ languages auto-detected; handles mixed scripts, RTL, localized formats

All four features compose freely — a single API call with include_blocks: true and confidence_scores_granularity: 'word' returns the full structural decomposition, confidence information, and language-agnostic text in one round-trip.