mistralM

Docs

sideBar

Mistral Document AI Basics

Hands-on notebooks and guides for building with the Mistral API.
import base64
import json
import requests
import os
from dotenv import load_dotenv
from typing import Dict, Any
from IPython.display import Markdown, display, Image

Mistral Document AI Basics

Mistral Document AI offers enterprise-level document processing, combining cutting-edge OCR technology with advanced structured data extraction. This notebook showcases a few examples of basic OCR extraction for text and images.

We will be using the mistral-document-ai-2505 model with a few documents and images to show the capabilities of the model.

Note: The Document AI endpoint on Azure Foundry cannot process sources from external URLSs, instead we show you how to encode documents and images and call the API.

0. Setup

From Azure AI Foundry, after clicking on "Use this model" and going through standard Foundry setup you will need the provided Endpoint, Key and Deployment Name.

The Endpoint is used as the url in the REST request, the Key is used for authentication in the header, and the Deployment Name is used in the body of the request.

load_dotenv()

AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT = os.getenv("AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT")
AZURE_MISTRAL_DOCUMENT_AI_KEY = os.getenv("AZURE_MISTRAL_DOCUMENT_AI_KEY")
AZURE_AI_DEPLOYMENT_NAME = os.getenv("AZURE_AI_DEPLOYMENT_NAME")


REQUEST_HEADERS = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {AZURE_MISTRAL_DOCUMENT_AI_KEY}",
}

1. Helper Functions

from ocr4_utils import (
    bboxannotation,
    encode_file,
    simple_combined_markdown,
)

import json


def testBBoxAnnotationOutput(response: dict) -> None:
    for page in response.get('pages', []):
        for image in page.get('images', []):
            annotation = json.loads(image['image_annotation'])
            properties = annotation.get('properties', annotation)
            print(f"page {page['index']}")
            print('Image type:', properties.get('image_type'))
            print('Short description:', properties.get('short_description'))

2. Image/Document Annotations

In addition to basic OCR functionality, Mistral Document AI has annotations that allow you to extract information from documents and images in structured json with a single call to the API. It offers two types of annotations that can be used independently, or together:

bbox_annotation: gives you the annotation of the bounding boxes extracted by the OCR model (charts/figures etc.) based on a structure that you define in the request. This is provided for every image, in every page of the document. document_annotation: like the bbox_annotation, but for the extracted text across the entire document. Note: Document annotations are currently limited at 8 pages. Please see the model card for the most up-to-date information on limits

!wget  -P samples  https://raw.githubusercontent.com/mistralai/cookbook/refs/heads/main/mistral/ocr/receipt.png 
!wget  -P samples https://raw.githubusercontent.com/mistralai/cookbook/refs/heads/main/mistral/ocr/mistral7b.pdf

Construct the request and parse the response

display(Image(filename="samples/receipt.png"))
bb1Response_image = requests.post(
    url=AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT,
    json=bboxannotation(encode_file("samples/receipt.png"), 'document_annotation_format'),
    headers=REQUEST_HEADERS,
)
response = bb1Response_image.json()
doc_annotation = json.loads(response["document_annotation"])
doc_annotation["short_description"]
bb1Response_image.json()

Retrieve Confidence Score

print(response["pages"][0]["confidence_scores"])

Retreive Blocks based on 'include_blocks' set to True

print(response["pages"][0]["blocks"][0])
bb1Response_document = requests.post(
    url=AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT,
    json=bboxannotation(encode_file("samples/mistral7b.pdf"), 'bbox_annotation_format'),
    headers=REQUEST_HEADERS,
)
image = bb1Response_document.json()["pages"][0]["images"][0]
iaj = json.loads(image["image_annotation"])
print(iaj["short_description"])

You will notice that for every page, the API returns text data in html format, along with information about detected images.

display(Markdown(bb1Response_document.json()["pages"][6]["header"]))
display(bb1Response_document.json()["pages"][4]["footer"])

4. Tabular Example

Next we look at a document with tabular data, for this example we are using Microsoft's 8-K filing located here: https://www.microsoft.com/en-us/investor/sec-filings

ms8kDocument = encode_file("samples/0000950170-25-100226.pdf")
msRequestPayload = {
    "model": f"{AZURE_AI_DEPLOYMENT_NAME}",
    "document": {
        "type": "document_url",
        "document_url": f"data:application/pdf;base64,{ms8kDocument}",
    },
    "table_format": "html",
    "extract_header": True, 
    "extract_footer": True,
}
ms8kResponse = requests.post(
    url=AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT,
    json=msRequestPayload,
    headers=REQUEST_HEADERS,
)

Selecting a page with tables

display(ms8kResponse.json()["pages"][0]["header"])
print(ms8kResponse.json()["pages"][0]["tables"][0]['content'])
print(ms8kResponse.json()["pages"][0]["markdown"])
display(Markdown(simple_combined_markdown(ms8kResponse.json()["pages"][0])))

As observed, the extracted text in the table is accurate and true to the original tabular representation.

5. Microsoft Word Documents

wordDocument = encode_file("samples/TranscriptFY25q4.docx")
wordPayload = {
    "model": f"{AZURE_AI_DEPLOYMENT_NAME}",
    "document": {
        "type": "document_url",
        "document_url": f"data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,{wordDocument}",
    },
    "table_format": "html",
    "extract_header": True, 
    "extract_footer": True, 
}
wordResponse = requests.post(
    url=AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT,
    json=wordPayload,
    headers=REQUEST_HEADERS,
)
print(wordResponse.json()["pages"][0]['markdown'])
# limiting to 1000 characters for easier reading
display(Markdown(simple_combined_markdown(wordResponse.json()["pages"][0])[:1000]))

6. Microsoft Powerpoint Presentations

!wget -P samples https://github.com/mistralai/cookbook/raw/52ed72962a4d2be2c922919d7c25016b71b900df/data/sample.pptx
powerpointDocument = encode_file("samples/sample.pptx")
pptxPayload = {
    "model": f"{AZURE_AI_DEPLOYMENT_NAME}",
    "document": {
        "type": "document_url",
        "document_url": f"data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,{powerpointDocument}",
    },
    "include_image_base64": "false",
    "image_limit": 0,
    "table_format": "html",
    "extract_header": True, 
    "extract_footer": True, 
}
pptxResponse = requests.post(
    url=AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT,
    json=pptxPayload,
    headers=REQUEST_HEADERS,
)
pptxResponse.json()["pages"][0]['markdown']
print(json.dumps(pptxResponse.json(), indent=4))

EPub File Format

epubDocument = encode_file("samples/minimal.epub")
epubPayload = {
    "model": f"{AZURE_AI_DEPLOYMENT_NAME}",
    "document": {
        "type": "document_url",
        "document_url": f"data:application/epub+zip;base64,{epubDocument}",
    },
    "include_image_base64": "false",
    "image_limit": 0,
    "table_format": "html",
    "extract_header": True, 
    "extract_footer": True, 
}
epubResponse = requests.post(
    url=AZURE_MISTRAL_DOCUMENT_AI_ENDPOINT,
    json=epubPayload,
    headers=REQUEST_HEADERS,
)
epubResponse.json()["pages"][0]['markdown']

7. Wrap-up

Documents and images are a wealth of information, but that information is only useful if it can be extracted accurately. Mistral Document AI on Azure is a powerful tool that can help you extract text and images from documents accurately, with ease. We hope you found this notebook helpful and we look forward to seeing what you build with it!