支持私有云部署
AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


Mistral OCR + 结构化输出:结合OCR与LLM,实现高效数据提取与组织!

发布日期:2025-03-31 08:59:49 浏览次数: 1570 作者:YourwayAI
推荐语

Mistral OCR与LLM的结合,开启智能数据提取新时代!

核心内容:
1. Mistral OCR核心功能:从PDF和图像中提取文本并生成结构化JSON输出
2. 技术亮点:基于模型的结构化解析与多模态支持,提升数据提取准确性
3. 应用场景:收据、合同等文档信息提取与分析,快速上手指南

杨芳贤
53A创始人/腾讯云(TVP)最具价值专家

 

导语:

你是否需要一款工具,能够结合OCR的文本识别能力和大型语言模型(LLM)的理解能力,实现更准确、更有组织的数据提取?Mistral OCR来了!这款工具不仅支持从PDF和图像中提取文本,还能通过Pixtral-12B或Ministral-8B模型生成结构化JSON输出。无论是处理收据、合同,还是其他文档,Mistral OCR都能为你提供高效的数据提取解决方案。本文将为你全面解析Mistral OCR的功能、使用方法及技术亮点,带你轻松玩转结构化数据提取!


正文:

1. Mistral OCR的核心功能

  • • OCR能力:支持从PDF和图像文件中提取文本内容。
  • • 多模态集成:将OCR结果与Pixtral-12B或Ministral-8B模型结合,生成结构化数据。
  • • 灵活输入格式:支持PDF文档和各种图像格式。
  • • 自定义输出架构:基于Pydantic定义特定的输出格式,如StructuredOCR类。

2. 技术亮点

  • • 基于模型的结构化解析:利用LLM将OCR提取的文本转换为结构化数据。
  • • 多模态支持:结合视觉模型和文本模型,提升数据提取的准确性和灵活性。
  • • 自定义输出:支持根据需求定义输出格式,满足不同场景的需求。

3. 应用场景

  • • 收据信息提取:从收据中提取金额、日期、支付方式等关键信息。
  • • 合同解析:从合同中提取条款、签署方、有效期等结构化数据。
  • • 文档分析:从PDF或图像文档中提取标题、段落、表格等内容。

4. 快速开始

1. 安装Mistral AI库
pip install mistralai
2. 下载示例文件
wget https://raw.githubusercontent.com/mistralai/cookbook/main/mistral/ocr/mistral7b.pdf
wget https://raw.githubusercontent.com/mistralai/cookbook/main/mistral/ocr/receipt.png
3. 初始化Mistral客户端
from mistralai import Mistral

api_key = "API_KEY"  # 替换为你的API密钥
client = Mistral(api_key=api_key)
4. 处理PDF文件
from pathlib import Path
from mistralai import DocumentURLChunk, ImageURLChunk, TextChunk
import json

# 验证PDF文件是否存在
pdf_file = Path("mistral7b.pdf")
assert pdf_file.is_file()

# 上传PDF文件到Mistral OCR服务
uploaded_file = client.files.upload(
    file={
        "file_name": pdf_file.stem,
        "content": pdf_file.read_bytes(),
    },
    purpose="ocr",
)

# 获取上传文件的URL
signed_url = client.files.get_signed_url(file_id=uploaded_file.id, expiry=1)

# 使用OCR处理PDF文件
pdf_response = client.ocr.process(
    document=DocumentURLChunk(document_url=signed_url.url),
    model="mistral-ocr-latest",
    include_image_base64=True
)

# 将响应转换为JSON格式
response_dict = json.loads(pdf_response.model_dump_json())
print(json.dumps(response_dict, indent=4)[0:1000])  # 打印前1000个字符
5. 处理图像文件
import base64

# 验证图像文件是否存在
image_file = Path("receipt.png")
assert image_file.is_file()

# 将图像编码为base64
encoded = base64.b64encode(image_file.read_bytes()).decode()
base64_data_url = f"data:image/jpeg;base64,{encoded}"

# 使用OCR处理图像
image_response = client.ocr.process(
    document=ImageURLChunk(image_url=base64_data_url),
    model="mistral-ocr-latest"
)

# 将响应转换为JSON格式
response_dict = json.loads(image_response.model_dump_json())
print(json.dumps(response_dict, indent=4))

5. 结构化数据提取

# 获取OCR结果
image_ocr_markdown = image_response.pages[0].markdown

# 使用Pixtral-12B模型生成结构化JSON响应
chat_response = client.chat.complete(
    model="pixtral-12b-latest",
    messages=[
        {
            "role""user",
            "content": [
                ImageURLChunk(image_url=base64_data_url),
                TextChunk(
                    text=(
                        f"This is image's OCR in markdown:\n\n{image_ocr_markdown}\n.\n"
                        "Convert this into a sensible structured json response. "
                        "The output should be strictly be json with no extra commentary"
                    )
                ),
            ],
        }
    ],
    response_format={"type""json_object"},
    temperature=0,
)

# 解析并返回JSON响应
response_dict = json.loads(chat_response.choices[0].message.content)
print(json.dumps(response_dict, indent=4))

6. 自定义结构化输出

from enum import Enum
from pathlib import Path
from pydantic import BaseModel
import base64

classStructuredOCR(BaseModel):
    file_name: str
    topics: list[str]
    languages: str
    ocr_contents: dict

defstructured_ocr(image_path: str) -> StructuredOCR:
    """
    处理图像并提取结构化数据。

    参数:
        image_path: 图像文件路径

    返回:
        StructuredOCR对象,包含提取的数据

    异常:
        AssertionError: 如果图像文件不存在
    """

    # 验证输入文件
    image_file = Path(image_path)
    assert image_file.is_file(), "提供的图像路径不存在。"

    # 读取并编码图像文件
    encoded_image = base64.b64encode(image_file.read_bytes()).decode()
    base64_data_url = f"data:image/jpeg;base64,{encoded_image}"

    # 使用OCR处理图像
    image_response = client.ocr.process(
        document=ImageURLChunk(image_url=base64_data_url),
        model="mistral-ocr-latest"
    )
    image_ocr_markdown = image_response.pages[0].markdown

    # 解析OCR结果为结构化JSON响应
    chat_response = client.chat.parse(
        model="pixtral-12b-latest",
        messages=[
            {
                "role""user",
                "content": [
                    ImageURLChunk(image_url=base64_data_url),
                    TextChunk(text=(
                        f"This is the image's OCR in markdown:\n{image_ocr_markdown}\n.\n"
                        "Convert this into a structured JSON response "
                        "with the OCR contents in a sensible dictionnary."
                        )
                    )
                ]
            }
        ],
        response_format=StructuredOCR,
        temperature=0
    )

    return chat_response.choices[0].message.parsed

# 示例用法
image_path = "receipt.png"# 示例收据图像路径
structured_response = structured_ocr(image_path)  # 处理图像并提取数据

# 解析并返回JSON响应
response_dict = json.loads(structured_response.model_dump_json())
print(json.dumps(response_dict, indent=4))

总结:

Mistral OCR不仅是一款强大的文本提取工具,更是结合LLM实现结构化数据提取的利器。无论你是开发者、数据分析师,还是企业用户,Mistral OCR都能为你提供高效的数据提取解决方案。赶快点击链接,体验这款工具的强大功能吧!

53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询