47
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Mistral OCR API を使って PDF からテキストを抽出する

Last updated at Posted at 2025-03-07

はじめに

Mistral OCR API を利用して、ローカルの PDF からテキストを抽出し、Markdown 形式で保存する方法を紹介します。

Mistral OCR は、レイアウトを保持したままテキストを取得できる高精度な OCR エンジンです。本記事では、ローカルの PDF をアップロードし、OCR 解析を実行し、取得したテキストを保存する Python スクリプトを解説します。

必要なライブラリのインストール

まず、Mistral の Python SDK をインストールします。

pip install mistralai

OCR スクリプト

以下の Python スクリプトを実行することで、PDF を Mistral OCR にアップロードし、OCR 処理を行い、テキストを Markdown 形式で取得できます。

スクリプト全体

import os
from mistralai import Mistral

# APIキーの取得(本当は環境変数から取得するのが推奨)
api_key = ""
if not api_key:
    raise ValueError("MISTRAL_API_KEYが設定されていません")

# Mistral APIクライアントの作成
client = Mistral(api_key=api_key)

# ローカルPDFのパス
pdf_path = ""

# PDFをMistralにアップロード
uploaded_pdf = client.files.upload(
    file={
        "file_name": "",
        "content": open(pdf_path, "rb"),
    },
    purpose="ocr"
)

# アップロードしたPDFのサイン付きURLを取得
signed_url = client.files.get_signed_url(file_id=uploaded_pdf.id)

# OCR処理を実行
ocr_response = client.ocr.process(
    model="mistral-ocr-latest",
    document={
        "type": "document_url",
        "document_url": signed_url.url,
    }
)

# OCRの結果を取得(最初のページのmarkdown形式テキスト)
ocr_text = ocr_response.pages[0].markdown if ocr_response.pages else ""

# 抽出されたテキストを保存
output_txt_path = ""
with open(output_txt_path, "w", encoding="utf-8") as f:
    f.write(ocr_text)

print(f"OCR結果を {output_txt_path} に保存しました。")

スクリプトの流れ

  1. APIキーを取得

    • api_key に Mistral の API キーを設定します。
  2. PDFをアップロード

    • client.files.upload() を使用して Mistral のサーバーに PDF をアップロードします。
  3. サイン付きURLを取得

    • client.files.get_signed_url() で、アップロードした PDF の URL を取得します。
  4. OCR処理を実行

    • client.ocr.process() で OCR を実行します。
    • model="mistral-ocr-latest" を指定して、最新の OCR モデルを利用します。
  5. OCR結果を取得し保存

    • ocr_response.pages[0].markdown から、最初のページのテキストを取得します。
    • output.txt に OCR 結果を保存します。

実行方法

PowerShell またはターミナルで以下を実行します。

python ocr_mistral.py

実行後、output.txt に OCR 結果が保存されます。

まとめ

Mistral OCR API を使用すれば、簡単にローカルの PDF を OCR 解析し、Markdown 形式でテキストを取得できます。

ポイント:

  • Mistral API を使って PDF をアップロード
  • OCR 結果を取得し、Markdown 形式で保存
  • Python で簡単に実装可能

興味があれば、ぜひ試してみてください! 🚀

参考

時間があれば

以下で作ってみたいところ。

フロントエンド:React + Tailwind CSS
バックエンド:FastAPI(Python)
OCR処理:Mistral OCR API
ストレージ:ローカル

47
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?