先週はGoogle DeepMindがGemini 2.0をリリースこれらには以下が含まれる。 ジェミニ 2.0 Flash(完全に利用可能)、Gemini 2.0 Flash-Lite(新しい費用対効果)、Gemini 2.0 Pro(実験的)。すべてのモデルが少なくとも100万をサポート トークン 入力コンテキスト・ウィンドウの、テキスト、画像、音声、および関数呼び出し/構造化出力をサポートする。本稿は LLM OCRの限界:華やかさの下にある文書解析の課題 参考図書。
これにより、PDF処理の優れたユースケースが開かれる。PDFを構造化テキストや機械可読テキストに変換することは、常に大きな課題でした。もし、PDFを文書から構造化されたデータに変換することができたらと想像してみてほしい。ここでGemini 2.0の出番です。
このチュートリアルでは、Gemini 2.0を使用して、PDF文書から直接、請求書番号や日付などの構造化情報を抽出する方法を学習します:
- 環境のセットアップと推論クライアントの作成
- PDFやその他の文書の取り扱い
- Gemini 2.0とPydanticによる構造化出力
- Gemini 2.0でPDFから構造化データを抽出する
1.環境のセットアップと推論クライアントの作成
最初の作業は google-genai
Python SDK でAPIキーを取得する。読者がAPIキーをまだ持っていない場合は、そのキーを グーグルAIスタジオ ゲットだ:Gemini APIキーを取得する.
%pip install "google-genai>=1"
SDKとAPIキーを入手したら、読者はクライアントを作成し、使用するモデル、すなわち、1日あたり1,500リクエスト(2025年2月6日現在)の無料ティアで利用可能な新しいGemini 2.0 Flashモデルを定義することができる。
from google import genai # Create a client api_key = "XXXXX" client = genai.Client(api_key=api_key) # Define the model you are going to use model_id = "gemini-2.0-flash" # or "gemini-2.0-flash-lite-preview-02-05" , "gemini-2.0-pro-exp-02-05"
注:読者がバーテックスAIを使用したい場合は、以下を参照のこと。ここをクリッククライアントの作成方法
2.PDFやその他の文書の処理
ジェミニ・モデルは、次のような対応が可能です。画像とビデオこれは、base64文字列または files
Python APIにはアップロードと削除のメソッドがある。Python APIにはuploadメソッドとdeleteメソッドがあります。
この例では、ユーザーは2つのPDFサンプル、基本的な請求書と手書き値のフォームを持っています。
!wget -q -O https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/handwriting_form.pdf !wget -q -O https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/invoice.pdf
これで読者はクライアントと upload
メソッドを使ってファイルをアップロードすることができる。あるファイルで試してみよう。
invoice_pdf = client.files.upload(file="invoice.pdf", config={'display_name': 'invoice'})
注:File APIでは、1つのプロジェクトにつき最大20GB、1ファイルあたりの最大ファイルサイズは2GBまでファイルを保存できます。ファイルは48時間保存されます。この間、ファイルはユーザーのAPIキーを使用してアクセスできますが、ダウンロードすることはできません。ファイルのアップロードは無料です。
ファイルがアップロードされると、読者はそれがいくつのトークンに変換されたかを確認することができる。これは、ユーザーが何を扱っているかの背景を理解するのに役立つだけでなく、コストを追跡するのにも役立つ。
file_size = client.models.count_tokens(model=model_id,contents=invoice_pdf) print(f'File: {invoice_pdf.display_name} equals to {file_size.total_tokens} tokens') # File: invoice equals to 821 tokens
3.Gemini2.0とPydanticを使用した構造化出力
構造化出力は、Geminiが常にJSONスキーマのような定義済みのフォーマットに準拠したレスポンスを生成することを保証する機能です。これは、ユーザが定義したスキーマを持つ有効なJSONオブジェクトを返すことが保証されるため、ユーザが出力やアプリケーションへの統合方法をよりコントロールできることを意味します。
Gemini 2.0は現在、3種類のJSONスキーマ定義をサポートしています:
- Pythonの単一の型、例えば タイプ注釈 で使用されているものと同じである。
- ピダンティック ベースモデル
- genai.types.スキーマ / ピダンティック・ベースモデル 辞書相当語句
テキストベースの簡単な例を見てみよう。
from pydantic import BaseModel, Field # Define a Pydantic model # Use the Field class to add a description and default value to provide more context to the model class Topic(BaseModel): name: str = Field(description="The name of the topic") class Person(BaseModel): first_name: str = Field(description="The first name of the person") last_name: str = Field(description="The last name of the person") age: int = Field(description="The age of the person, if not provided please return 0") work_topics: list[Topic] = Field(description="The fields of interest of the person, if not provided please return an empty list") # Define the prompt prompt = "Philipp Schmid is a Senior AI Developer Relations Engineer at Google DeepMind working on Gemini, Gemma with the mission to help every developer to build and benefit from AI in a responsible way. " # Generate a response using the Person model response = client.models.generate_content(model=model_id, contents=prompt, config={'response_mime_type': 'application/json', 'response_schema': Person}) # print the response as a json string print(response.text) # sdk automatically converts the response to the pydantic model philipp: Person = response.parsed # access an attribute of the json response print(f"First name is {philipp.first_name}")
4.Gemini2.0を使用してPDFから構造化データを抽出する
では、File APIと構造化出力を組み合わせて、PDFから情報を抽出してみましょう。ユーザーはローカルファイルパスとPydanticモデルを受け取り、構造化されたデータを返す簡単なメソッドを作成することができます。このメソッドは
- File APIへのファイルのアップロード
- 利用する ジェミニAPI 構造化された応答を生成する
- レスポンスをPydanticモデルに変換して
def extract_structured_data(file_path: str, model: BaseModel): # Upload the file to the File API file = client.files.upload(file=file_path, config={'display_name': file_path.split('/')[-1].split('.')[0]}) # Generate a structured response using the Gemini API prompt = f"Extract the structured data from the following PDF file" response = client.models.generate_content(model=model_id, contents=[prompt, file], config={'response_mime_type': 'application/json', 'response_schema': model}) # Convert the response to the pydantic model and return it return response.parsed
この例では、それぞれのPDFは他のPDFとは異なります。したがって、Gemini 2.0の性能を実証するために、ユーザーは各PDFに対してユニークなPydanticモデルを定義する必要があります。非常に類似したPDFがあり、同じ情報を抽出したい場合、すべてのPDFに対して同じモデルを使用することができます。
Invoice.pdf
請求書番号、日付、明細、数量、合計金額、合計総額を含むすべてのリスト項目を抽出します。handwriting_form.pdf
:出金フォーム番号、スキーム開始日、年初および年末のスキーム負債額
注:Pydantic機能を使用することで、ユーザーはより正確なモデルを作成するために、より多くのコンテキストを追加し、データの検証を行うことができます。インストラクターのようなライブラリは、検証エラーに基づく自動再試行を追加し、これは非常に便利ですが、追加のリクエストコストを追加します。
請求書.pdf
from pydantic import BaseModel, Field class Item(BaseModel): description: str = Field(description="The description of the item") quantity: float = Field(description="The Qty of the item") gross_worth: float = Field(description="The gross worth of the item") class Invoice(BaseModel): """Extract the invoice number, date and all list items with description, quantity and gross worth and the total gross worth.""" invoice_number: str = Field(description="The invoice number e.g. 1234567890") date: str = Field(description="The date of the invoice e.g. 2024-01-01") items: list[Item] = Field(description="The list of items with description, quantity and gross worth") total_gross_worth: float = Field(description="The total gross worth of the invoice") result = extract_structured_data("invoice.pdf", Invoice) print(type(result)) print(f"Extracted Invoice: {result.invoice_number} on {result.date} with total gross worth {result.total_gross_worth}") for item in result.items: print(f"Item: {item.description} with quantity {item.quantity} and gross worth {item.gross_worth}")
素晴らしい!このモデルは請求書から情報を抽出するのに優れた仕事をしてくれる。
手書きフォーム.pdf
class Form(BaseModel): """Extract the form number, fiscal start date, fiscal end date, and the plan liabilities beginning of the year and end of the year.""" form_number: str = Field(description="The Form Number") start_date: str = Field(description="Effective Date") beginning_of_year: float = Field(description="The plan liabilities beginning of the year") end_of_year: float = Field(description="The plan liabilities end of the year") result = extract_structured_data("handwriting_form.pdf", Form) print(f'Extracted Form Number: {result.form_number} with start date {result.start_date}. \nPlan liabilities beginning of the year {result.beginning_of_year} and end of the year {result.end_of_year}') # Extracted Form Number: CA530082 with start date 02/05/2022. # Plan liabilities beginning of the year 40000.0 and end of the year 55000.0
ベストプラクティスと限界
PDF処理にGemini 2.0を使用する場合、以下の点に留意してください:
- ファイルサイズ管理:File APIは大きなファイルをサポートしていますが、ベストプラクティスはアップロードする前にPDFを最適化することです。
- トークンの制限: 大規模なドキュメントを扱う場合は、トークンの数をチェックして、ユーザーがモデルの制限と予算内に収まるようにします。
- 構造化された出力設計:ユーザーのパイドランティックモデルを慎重に設計し、明瞭さを維持しながら必要な情報をすべて取り込み、説明や例を追加することでモデルのパフォーマンスを向上させることができます。
- エラー処理:ファイルアップロードと処理状態のための堅牢なエラー処理を実装します。モデルからのエラーメッセージの再試行と処理を含みます。
評決を下す
Gemini 2.0のマルチモーダル機能と構造化出力の組み合わせは、PDFやその他のドキュメントからの情報の処理と抽出を支援します。これにより、複雑で時間のかかる手動または半自動でのデータ抽出プロセスが不要になります。請求書処理システム、文書分析ツール、またはその他の文書中心のアプリケーションを構築しているかどうかにかかわらず、Gemini 2.0を試すべきである。 Googleは、Gemini 2.0は最初は無料でテストでき、その後100万トークンあたり0.1ドルしかかからないことを強調している。