使用 llamaextract 和 pydantic 模型提取商店收據
在本文中,我們將探索如何使用 llamaextract 與 pydantic 模型中的模式相結合,以便從商店收據中提取結構化數據。這種方法有助于系統地組織收據信息,使其更易于分析和管理。
設置
首先,確保您安裝了 llama-extract 客戶端庫。使用以下命令:
pip install llama-extract pydantic
注意: 如果您看到有關更新 pip 的通知,您可以使用提供的命令進行更新。
首先,登錄llama index cloud并免費獲取一個api-key
為您的 llamaextract api 密鑰設置環境變量:
import os os.environ["llama_cloud_api_key"] = "your llama index cloud api here"
加載數據
對于此示例,假設我們有一個 pdf 格式的商店收據數據集。將這些文件放在名為receipts的目錄中。
data_dir = "data/receipts" fnames = os.listdir(data_dir) fnames = [fname for fname in fnames if fname.endswith(".pdf")] fpaths = [os.path.join(data_dir, fname) for fname in fnames] fpaths
輸出應列出收據的文件路徑:
['data/receipts/receipt.pdf']
定義 pydantic 模型
我們將使用 pydantic 定義我們的數據模型,這將告訴 api 我們期望或想要從 pdf 中提取哪些字段/數據。對于商店收據,我們可能有興趣提取商店名稱、日期、總金額和購買的商品列表。
from pydantic import basemodel from typing import list class item(basemodel): name: str quantity: int price: float class receipt(basemodel): store_name: str date: str total_amount: float items: list[item]
創建架構
現在,我們可以使用 pydantic 模型在 llamaextract 中定義提取模式。
from llama_extract import llamaextract extractor = llamaextract(verbose=true) schema_response = await extractor.acreate_schema("receipt schema", data_schema=receipt) schema_response.data_schema
輸出架構應類似于以下內容:
{ 'type': 'object', '$defs': { 'item': { 'type': 'object', 'title': 'item', 'required': ['name', 'quantity', 'price'], 'properties': { 'name': {'type': 'string', 'title': 'name'}, 'quantity': {'type': 'integer', 'title': 'quantity'}, 'price': {'type': 'number', 'title': 'price'} } } }, 'title': 'receipt', 'required': ['store_name', 'date', 'total_amount', 'items'], 'properties': { 'store_name': {'type': 'string', 'title': 'store name'}, 'date': {'type': 'string', 'title': 'date'}, 'total_amount': {'type': 'number', 'title': 'total amount'}, 'items': { 'type': 'array', 'title': 'items', 'items': {'$ref': '#/$defs/item'} } } }
運行提取
定義模式后,我們現在可以從收據文件中提取結構化數據。通過指定收據作為響應模型,我們確保提取的數據經過驗證和結構化。
responses = await extractor.aextract( schema_response.id, fpaths, response_model=receipt )
如果需要,您可以訪問原始 json 輸出:
data = responses[0].data print(data)
json 輸出示例:
{ 'store_name': 'ABC Electronics', 'date': '2024-08-05', 'total_amount': 123.45, 'items': [ {'name': 'Laptop', 'quantity': 1, 'price': 999.99}, {'name': 'Mouse', 'quantity': 1, 'price': 25.00}, {'name': 'Keyboard', 'quantity': 1, 'price': 50.00} ] }
結論
在本文中,我們演示了如何將 llamaextract 與 pydantic 模型結合使用來定義數據模式并從商店收據中提取結構化數據。這種方法可確保提取的信息組織良好且經過驗證,從而更易于處理和分析。
這也可用于許多案例、發票、收據、報告等。
快樂編碼??!
你有一個項目?想讓我幫你發郵件給我??:wilbertmisingo@gmail.com
有疑問或想成為第一個了解我的帖子的人:-
在 linkedin 上關注 ? 我?
在 twitter/x 上關注 ? 我?
以上就是使用 AI 創建最快、最精確的發票數據提取器以進行結構輸出的詳細內容,更多請關注愛掏網 - it200.com其它相關文章!