mistralM

Docs

sideBar

Annotations

Extrayez du JSON structuré à partir de documents grâce aux annotations de bbox et de document, selon un format que vous définissez dans votre requête OCR.

En plus de la fonctionnalité d’OCR de base, l’API Mistral Document AI ajoute la fonctionnalité annotations, qui vous permet d’extraire des informations dans un format JSON structuré que vous fournissez.

Avant de commencer

Que pouvez-vous faire avec les annotations ?

Plus précisément, elle propose deux types d’annotations :

  • bbox_annotation : fournit l’annotation des bbox extraites par le modèle OCR (graphiques, figures, etc.) selon les besoins de l’utilisateur et le format d’annotation de bbox/d’image fourni. L’utilisateur peut par exemple demander de décrire la figure ou de lui ajouter une légende.
  • document_annotation : renvoie l’annotation du document entier selon le format d’annotation de document fourni.

annotations_explanation_graph

Capacités principales

  • Étiquetage et annotation de données
  • Extraction et structuration d’informations précises de documents dans un format JSON prédéfini
  • Automatisation de l’extraction de données pour réduire la saisie manuelle et les erreurs
  • Traitement efficace de grands volumes de documents pour les applications d’entreprise

Cas d’usage courants

  • Analyse de formulaires, classification de documents et traitement d’images, y compris le texte, les graphiques et les signatures
  • Conversion de graphiques en tableaux, extraction des petits caractères des figures, ou définition de types d’images personnalisés
  • Capture des données de reçus, y compris le nom des commerçants et le montant des transactions, pour la gestion des notes de frais.
  • Extraction d’informations clés, comme les coordonnées des fournisseurs et les montants, à partir de factures pour une comptabilité automatisée.
  • Extraction des clauses et conditions clés des contrats pour en faciliter l’examen et la gestion

Fonctionnement

annotations_workflow_graph

Annotations de BBox

  • Tous les types de documents :
    • Une fois l’OCR classique terminée, nous appelons un LLM doté de capacités de vision pour chaque bbox individuellement, avec le format d’annotation fourni.

Annotation de document

  • Tous les types de documents :
    • Nous exécutons l’OCR et envoyons le texte de sortie en Markdown, avec les huit premières bounding boxes d’images extraites, à un LMM doté de capacités de vision, accompagné du format d’annotation fourni.

Formats acceptés

Vous pouvez utiliser notre API avec les formats de documents suivants :

Dans les extraits de code ci-dessous, nous considérons le format OCR with pdf.

Usage

Comment annoter

Comme indiqué précédemment, vous pouvez :

  • Utiliser la fonctionnalité bbox_annotation, qui vous permet d’extraire des informations des bbox du document.
  • Utiliser la fonctionnalité document_annotation, qui vous permet d’extraire des informations du document entier.
    • En option, nous permettons aussi d’ajouter un document_annotation_prompt, un prompt général de haut niveau qui guide et indique comment annoter le document.
  • Utiliser les deux fonctionnalités en même temps.

Voici un exemple d’utilisation de nos fonctionnalités d’annotation de BBox.

Définir le modèle de données

Commencez par définir les formats de réponse pour BBox Annotation, avec des schémas Pydantic ou Zod pour nos SDK, ou un JSON Schema pour un appel d’API avec curl.

Les schémas Pydantic/Zod/JSON acceptent les objets imbriqués, les tableaux, les enums, etc.

from pydantic import BaseModel

# BBOX Annotation response formats
class Image(BaseModel):
  image_type: str
  short_description: str
  summary: str

Vous pouvez aussi fournir une description pour chaque entrée ; elle sera utilisée comme information détaillée et comme instruction pendant l’annotation, par exemple :

from pydantic import BaseModel, Field

# BBOX Annotation response formats
class Image(BaseModel):
  image_type: str = Field(..., description="The type of the image.")
  short_description: str = Field(..., description="A description in english describing the image.")
  summary: str = Field(..., description="Summarize the image.")

Lancer la requête

Ensuite, effectuez une requête et assurez-vous que la réponse respecte les structures définies en définissant bbox_annotation_format sur les schémas correspondants :

import os
from mistralai import Mistral
from mistralai import DocumentURLChunk, ImageURLChunk, ResponseFormat
from mistralai.extra import response_format_from_pydantic_model

api_key = os.environ["MISTRAL_API_KEY"]

client = Mistral(api_key=api_key)

response = client.ocr.process(
    model="mistral-ocr-latest",
    document=DocumentURLChunk(
      document_url="https://arxiv.org/pdf/2410.07073"
    ),
    bbox_annotation_format=response_format_from_pydantic_model(Image),
    include_image_base64=True
  )
Sortie
{
  "pages": [
    {
      "index": 0,
      "markdown": "# Pixtral 12B \n\n![img-0.jpeg](img-0.jpeg)\n\n## Abstract\n\nWe introduce Pixtral 12B, a 12-billion-parameter multimodal language model. Pixtral 12B is trained to understand both natural images and documents, achieving leading performance on various multimodal benchmarks, surpassing a number of larger models. Unlike many open-source models, Pixtral is also a cutting-edge text model for its size, and does not compromise on natural language performance to excel in multimodal tasks. Pixtral uses a new vision encoder trained from scratch, which allows it to ingest images at their natural resolution and aspect ratio. This gives users flexibility on the number of tokens used to process an image. Pixtral is also able to process any number of images in its long context window of 128 K tokens. Pixtral 12B substanially outperforms other open models of similar sizes (Llama-3.2 11B \\& Qwen-2-VL 7B). It also outperforms much larger open models like Llama-3.2 90B while being 7x smaller. We further contribute an open-source benchmark, MM-MT-Bench, for evaluating vision-language models in practical scenarios, and provide detailed analysis and code for standardized evaluation protocols for multimodal LLMs. Pixtral 12B is released under Apache 2.0 license.\n\nWebpage: https://mistral.ai/news/pixtral-12b/\nInference code: https://github.com/mistralai/mistral-inference/\nEvaluation code: https://github.com/mistralai/mistral-evals/\n\n## 1 Introduction\n\nThis paper describes Pixtral 12B, a multimodal language model trained to understand both images and text, released with open weights under an Apache 2.0 license. Pixtral is an instruction tuned model which is pretrained on large scale interleaved image and text documents, and hence is capable of multi-turn, multi-image conversation.\n\nPixtral comes with a new vision encoder which is trained with a novel RoPE-2D implementation, allowing it to process images at their native resolution and aspect ratio. In this way, the model can flexibly process images at low resolution in latency-constrained settings, while processing images at high resolution when fine-grained reasoning is required.\nWhen compared against models of a similar size in the same evaluation setting, we find that Pixtral delivers strong multimodal reasoning capabilities without sacrificing text-only reasoning performance.",
      "images": [
        {
          "id": "img-0.jpeg",
          "top_left_x": 413,
          "top_left_y": 563,
          "bottom_right_x": 1286,
          "bottom_right_y": 862,
          "image_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...",
          "image_annotation": "{\n  \"image_type\": \"Logo\",\n  \"short_description\": \"A 3D-rendered logo of the text 'Mistral AI' with a gradient color scheme transitioning from orange to yellow.\",\n  \"summary\": \"The image features a 3D-rendered logo of the text 'Mistral AI'. The text is stylized with a gradient color scheme that transitions from a warm orange to a bright yellow, giving it a vibrant and modern appearance. The letters are slightly tilted to the right, adding a dynamic touch to the overall design.\"\n}"
        }
      ],
      "dimensions": {
        "dpi": 200,
        "height": 2200,
        "width": 1700
      }
    },
    {
      "index": 1,
      "markdown": "![img-1.jpeg](img-1.jpeg)\n\nFigure 1: Pixtral Performance. Pixtral outperforms all open-models within its weight class on multimodal tasks by a substantial margin. Left: Performance on MM-MT-Bench, a new multimodal, multiturn, instruction following benchmark designed to reflect real world usage of multimodal language models. Right: Performance on the public LMSys leaderboard (Vision arena, October 2024).\n\nFor instance, our model matches or exceeds the performance of models like Qwen2-VL 7B [23] and Llama-3.2 11B [6] on popular multimodal benchmarks like MMMU [24] and MathVista [14], while outperforming most open-source models on popular text-only tasks like MATH [7] and HumanEval [26]. Pixtral even outperforms much larger models like Llama-3.2 90B [6], as well as closed models such as Claude-3 Haiku [1] and Gemini-1.5 Flash 8B [18], on multimodal benchmarks.\n\nDuring evaluation of Pixtral and the baselines, we found that evaluation protocols for multimodal language models is not standardized, and that small changes in the setup can dramatically change the performance of some models. We provide thorough analysis of our experience in re-evaluating vision-language models under a common evaluation protocol.\n\nSpecifically, we identify two issues with evaluation:\n\n- Prompts: Several benchmarks have default prompts which are under-specified, and dramatically reduce the performance of leading closed source models [16, 1] compared to reported figures.\n- Evaluation Metrics: The official metrics typically require exact match, which score model generations as correct only if they exactly match the reference answer. However, this metric penalizes answers which are substantively correct but in a slightly different format (e.g., \"6.0\" vs \"6\").\n\nTo alleviate these issues, we propose 'Explicit' prompts that explicitly specify the format required by the reference answer. We further analyze the impact of flexible parsing for various models, releasing the evaluation code and prompts in an effort to establish fair and standardized evaluation protocols ${ }^{1}$.\n\nMoreover, while current multimodal benchmarks mostly evaluate short-form or multiple-choice question answering given an input image, they do not fully capture a model's utility for practical use cases (e.g. in a multi-turn, long-form assistant setting). To address this, we open-source a novel multimodal, multi-turn evaluation: MM-MT-Bench ${ }^{2}$. We find that performance on MM-MT-Bench correlates highly with ELO rankings on the LMSys Vision Leaderboard.\n\nPixtral excels at multimodal instruction following, surpassing comparable open-source models on the MM-MT-Bench benchmark (see Figure 1). Based on human preferences on the LMSys Vision Leaderboard, Pixtral 12B is currently the highest ranked Apache 2.0 model, substantially outperforming other open-models such Llama-3.2 11B [6] and Qwen2-VL 7B [23]. It even ranks higher than several closed models such as Claude-3 Opus \\& Claude-3 Sonnet [1], and several larger models such as Llama-3.2 90B [6].\n\n[^0]\n[^0]:    ${ }^{1}$ https://github.com/mistralai/mistral-evals/\n    ${ }^{2}$ https://huggingface.co/datasets/mistralai/MM-MT-Bench",
      "images": [
        {
          "id": "img-1.jpeg",
          "top_left_x": 294,
          "top_left_y": 193,
          "bottom_right_x": 1405,
          "bottom_right_y": 675,
          "image_base64": "...",
          "image_annotation": "{\n  \"image_type\": \"scatter plot\",\n  \"short_description\": \"This image shows two scatter plots comparing the performance and cost of various AI models.\",\n  \"summary\": \"The image consists of two scatter plots. The left plot compares the performance on the MM-MT-Bench against the cost/number of parameters (in billions) for different AI models. The right plot compares the performance on the LMSys-Vision ELO against the same cost/number of parameters. In both plots, the Pixtral 12B model is highlighted as having the best performance/cost ratio. Other models like Qwen-2-VL 72B, Llama-3.2 90B, and Llama-3.2 11B are also shown, with varying performance and cost metrics. The plots indicate that Pixtral 12B offers a strong balance of performance and cost efficiency.\"\n}"
        }
      ],
      "dimensions": {
        "dpi": 200,
        "height": 2200,
        "width": 1700
      }
    },
    {
      "index": 2,
      "markdown": "![img-2.jpeg](img-2.jpeg)\n\nFigure 2: Pixtral Vision Encoder. Pixtral uses a new vision encoder, which is trained from scratch to natively support variable image sizes and aspect ratios. Block-diagonal attention masks enable sequence packing for batching, while RoPE-2D encodings facilitate variable image sizes. Note that the attention mask and position encodings are fed to the vision transformer as additional input, and utilized only in the self-attention layers.\n\n# 2 Architectural details \n\nPixtral 12B is based on the transformer architecture [22], and consists of a multimodal decoder to perform highlevel reasoning, and a vision encoder to allow the model to ingest images. The main parameters of the model are summarized in Table 1.\n\n### 2.1 Multimodal Decoder\n\nPixtral 12B is built on top of Mistral Nemo 12B [15], a 12-billion parameter decoder-only language model that achieves strong performance across a range of knowledge and reasoning tasks.\n\n| Parameters | Decoder | Encoder |\n| :-- | --: | --: |\n| dim | 5120 | 1024 |\n| n_layers | 40 | 24 |\n| head_dim | 128 | 64 |\n| hidden_dim | 14336 | 4096 |\n| n_heads | 32 | 16 |\n| n_kv_heads | 8 | 16 |\n| context_len | 131072 | 4096 |\n| vocab_size | 131072 | - |\n| patch_size | - | 16 |\n\nTable 1: Decoder and encoder parameters.\n\n### 2.2 Vision Encoder\n\nIn order for Pixtral 12B to ingest images, we train a new vision encoder from scratch, named PixtralViT. Here, our goal is to instantiate a simple architecture which is capable of processing images across a wide range of resolutions and aspect ratios. To do this, we build a 400 million parameter vision transformer [5] (see Table 1) and make four key changes over the standard architectures [17]:\nBreak tokens: In order to assist the model in distinguishing between images with the same number of patches (same area) but different aspect ratios, we include [IMAGE BREAK] tokens between image rows [2]. We further include an [IMAGE END] token at the end of an image sequence.\nGating in FFN: Instead of standard feedforward layer in the attention block, we use gating in the hidden layer [19].\nSequence packing: In order to efficiently process images within a single batch, we flatten the images along the sequence dimension and concatenate them [3]. We construct a block-diagonal mask to ensure no attention leakage between patches from different images.\nRoPE-2D: We replace traditional learned and absolute position embeddings for image patches with relative, rotary position encodings [11, 20] in the self-attention layers. While learned position embeddings must be interpolated to deal with new image sizes (often at the cost of performance), relative position encodings lend themselves naturally to variable image sizes.",
      "images": [
        {
          "id": "img-2.jpeg",
          "top_left_x": 309,
          "top_left_y": 191,
          "bottom_right_x": 1387,
          "bottom_right_y": 655,
          "image_base64": "...",
          "image_annotation": "{\n  \"image_type\": \"diagram\",\n  \"short_description\": \"A diagram illustrating the architecture of the Pixtral-ViT model.\",\n  \"summary\": \"The diagram shows the architecture of the Pixtral-ViT model, which processes image patches through various stages. Starting with image patches, the model applies RoPE-2D positional embeddings and a block-diagonal attention mask. The processed data is then fed into a bidirectional transformer, followed by a vision-language projector, and finally, output embeddings are generated. The diagram also includes visual representations of the positional embeddings and attention mechanisms used in the model.\"\n}"
        }
      ],
      "dimensions": {
        "dpi": 200,
        "height": 2200,
        "width": 1700
      }
    },
    ...
    {
      "index": 23,
      "markdown": "|  | Mathvista <br> 2017 | MMMU <br> 2017 | ChartQA <br> 2017 | DocVQA <br> 2017 | VQAr2 <br> 2017 March | MM-MT-Bench <br> 2017 to 2020 | LMSys-Vision <br> Nov 2017 |\n| :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: |\n| Pixtral 12B | 58.3 | 52.0 | 81.8 | 90.7 | 78.6 | 6.05 | 1076 |\n| Qwen-2-VL 7B [23] |  |  |  |  |  |  |  |\n| Measured (Exact Match) | 53.7 | 48.1 | 41.2 | 94.5 | 75.9 | 5.45 |  |\n| Measured (Custom evaluation, see Section E.3) | 63.7 | 50.6 | 83.4 | 94.5 | 82.1 | - | 1040 |\n| Reported | 58.2 | 54.1 | 83.0 | 94.5 | - | - |  |\n| Llama-3.2 11B [6] |  |  |  |  |  |  |  |\n| Measured (Exact Match) | 24.3 | 23.0 | 14.8 | 91.1 | 67.1 | 4.79 |  |\n| Measured (Custom evaluation, see Section E.4) | 47.9 | 46.6 | 78.5 | 91.1 | 67.1 | - | 1032 |\n| Reported | 51.5 | 50.7 | 83.4 | 88.4 | 75.2 | - |  |\n| Molmo-D 7B [4] |  |  |  |  |  |  |  |\n| Measured (Exact Match) | 12.3 | 24.3 | 27.0 | 72.2 | 57.1 | 3.72 |  |\n| Measured (Custom evaluation, see Section E.6) | 43.2 | 47.0 | 76.7 | 72.2 | 70.0 | - | - |\n| Reported | 51.6 | 45.3 | 84.1 | 92.2 | 85.6 | - |  |\n| LLaVA-OneVision 7B [9] |  |  |  |  |  |  |  |\n| Measured (Exact Match) | 36.1 | 45.1 | 67.2 | 90.5 | 78.4 | 4.12 |  |\n| Measured (Custom evaluation, see Section E.5) | 63.1 | 48.1 | 80.2 | 90.5 | 83.7 | - | - |\n| Reported | 63.2 | 48.8 | 80.0 | 87.5 | - | - |  |\n| Molmo 72B [4] |  |  |  |  |  |  | - |\n| Measured (Exact Match) | 52.2 | 52.7 | 75.6 | 86.5 | 75.2 | 3.51 |  |\n| Measured (Custom evaluation, see Section E.6) | 61.3 | 52.9 | 82.3 | 86.5 | 75.5 | - | - |\n| Reported | 58.6 | 54.1 | 87.3 | 93.5 | 86.5 | - |  |\n| Llama-3.2 90B [6] |  |  |  |  |  |  |  |\n| Measured (Exact Match) | 49.1 | 53.7 | 33.8 | 85.7 | 67.0 | 5.50 |  |\n| Measured (Custom evaluation, see Section E.4) | 57.5 | 60.2 | 91.7 | 91.5 | 67.0 | - | 1071 |\n| Reported | 57.3 | 60.3 | 85.5 | 90.1 | 78.1 | - |  |\n| Claude-3 Haiku [1] |  |  |  |  |  |  |  |\n| Measured (Exact Match) | 44.8 | 50.4 | 69.6 | 74.6 | 68.4 | 5.46 |  |\n| Measured (Custom evaluation, see Section E.2) | 44.8 | 51.3 | 79.8 | 74.6 | 68.4 | - | 1000 |\n| Reported | 46.4 | 50.2 | 81.7 | 88.8 | - | - |  |\n| Gemini-1.5-Flash 8B[18,17, [18] |  |  |  |  |  |  |  |\n| Measured (Exact Match) | 56.9 | 50.7 | 78.0 | 79.5 | 65.5 | 5.93 |  |\n| Measured (Custom evaluation, see Section E.2) | 57.1 | 50.7 | 78.2 | 79.5 | 69.2 | - | 1111 |\n| Reported | - | 50.3 | - | 75.6 | - | - |  |\n\nTable 8: Reproducing the reported performance of prior models. In Table 2 we conduct fair re-evaluation of all models through the same evaluation harness, with the same prompt and metric. Here, we endeavour to recover the reported performance of all models by tuning evaluation settings towards individual models. We highlight that Pixtral 12B, like strong closed-source models (e.g. Gemini-1.5-Flash 8B [18] and Claude-3 Haiku [1]) is able reports strong performance without such interventions.",
      "images": [],
      "dimensions": {
        "dpi": 200,
        "height": 2200,
        "width": 1700
      }
    }
  ],
  "model": "mistral-ocr-2505-completion",
  "document_annotation": null,
  "usage_info": {
    "pages_processed": 24,
    "doc_size_bytes": 12640953
  }
}

Exemple de sortie d’annotation de BBox

La fonctionnalité d’annotation de BBox permet d’extraire des données des images extraites du document d’origine et de les annoter. Voici l’une des images d’un document extraite par notre processeur OCR.

bbox-image

L’image extraite est fournie encodée en base64.

{ 
  "image_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGB{LONG_MIDDLE_SEQUENCE}KKACiiigAooooAKKKKACiiigD//2Q==..." 
}

Vous pouvez annoter l’image avec le schéma de modèle de votre choix ; voici un exemple de sortie.

{
  "image_type": "scatter plot",
  "short_description": "Comparison of different models based on performance and cost.",
  "summary": "The image consists of two scatter plots comparing various models on two different performance metrics against their cost or number of parameters. The left plot shows performance on the MM-MT-Bench, while the right plot shows performance on the LMSys-Vision ELO. Each point represents a different model, with the x-axis indicating the cost or number of parameters in billions (B) and the y-axis indicating the performance score. The shaded region in both plots highlights the best performance/cost ratio, with Pixtral 12B positioned within this region in both plots, suggesting it offers a strong balance of performance and cost efficiency. Other models like Qwen-2-VL 72B and Qwen-2-VL 7B also show high performance but at varying costs."
}

Cookbooks

Pour plus d’informations et de guides sur l’utilisation de l’OCR, nous proposons les cookbooks suivants :

FAQ

Oui, l’API Document Intelligence comporte certaines limites. Les fichiers de documents envoyés ne doivent pas dépasser 50 Mo ni 1 000 pages.

Avec les annotations de documents, chaque annotation accepte au maximum 8 bounding boxes d’images. Nous recommandons l’annotation de document pour les documents principalement textuels.