LoginSignup
11
10

More than 3 years have passed since last update.

Azure Form Recognizerで帳票をバッチ処理する

Last updated at Posted at 2020-09-08

Azure Form recognizerというサービスがあります。
https://azure.microsoft.com/ja-jp/services/cognitive-services/form-recognizer/

帳票をいい感じに読み取って狙ったデータを抽出してくれる優れものです。APIもあるので複数の帳票をまとめて処理できるPython scriptを書いてみました
https://github.com/yosukearaiMS13/formrecognizerbatch/blob/master/fy.py

以下、スクリプトの中身と使い方について説明します

スクリプトの中身

スクリプトは、ドキュメントにあるサンプルを拡張して作っています
https://docs.microsoft.com/ja-jp/azure/cognitive-services/form-recognizer/quickstarts/python-labeled-data?tabs=v2-0

スクリプトは4つのsectionから構成されています
https://github.com/yosukearaiMS13/formrecognizerbatch/blob/master/fy.py

fr.py

# Configurations: 各種設定パラメータ

# Post 分析対象pdf section
## Form recognizerに対し、分析対象データを一旦全部postします

# Get analyze results section
## 先ほどpostしたデータの分析結果(抽出されたデータ含む)を取得します。

# 抽出結果のcsv出力 section
## 抽出結果を出力します。余計な空白の除去と、信頼性が低い抽出値の置き換え
##(しきい値以下の場合抽出値は採用せず、代わりに信頼度を[]囲みで出力)
## を行っています

Get analyze resultsと抽出結果のcsv出力sectionでは、Form recognizerから返されたjsonをパースしています。jsonのフォーマットはこちらです
https://github.com/Azure-Samples/cognitive-services-REST-api-samples/blob/master/curl/form-recognizer/Invoice_1.pdf.ocr.json

出力されるcsvのフォーマットは以下です。
- 先頭列: 分析対象の帳票ファイル名
- 2列目以降: 分析モデルに設定した全ラベル(タグ)と、それに対応する抽出値
csv.png

各セクションで利用しているAPIは以下です
- Post 分析対象pdf: Analyze Form
- Get analyze results: Get Analyze Form Result
- CSV出力section: Get Custom Model
 - 当該APIにて定義済みの全ラベルを取得し、csvのヘッダの値として使用しています

スクリプトの使い方

1. 環境

Win10 Enterprise, Python 3.8.5, IDEは任意

2. データ抽出準備

(※前提作業~データ抽出準備1までは、こちらのQiita記事も参考になります)

fr.py
## Configurations
endpoint = r"https://xxxxx.cognitiveservices.azure.com/"
apim_key = "xxxxx"
model_id = "xxxxx"
sourceDir = r"C:\xxxxx\*"
confidence_setting = 0.9 # 0~1. 信頼性がこの値以下の場合採用しない

  - endpoint: Form Recognizerのエンドポイント
  - apim_key: Form Recognizerのキー1 or 2image.png
  - sourceDir: 分析対象の帳票ファイルの配置場所をフルパスで記述
  - confidence_setting: 0~1の値を設定(※スクリプトの仕様として、信頼性がこの値以下の場合抽出された値は採用せず、代わりに信頼性の評価値を[]囲みで出力する仕様にしています)

fr.py
## Configurations
endpoint = r"https://xxxxx.cognitiveservices.azure.com/"
apim_key = "xxxxx"
model_id = "xxxxx"
sourceDir = r"C:\xxxxx\*"
confidence_setting = 0.9 # 0~1. 信頼性がこの値以下の場合採用しない

  - Model_id: 上記で取得したModel IDをセットします

3.データ抽出実施

  • sourceDirに分析対象の帳票ファイルを配置する
  • fr.pyを実行
  • スクリプトと同じフォルダにデータ抽出結果csvが出力されます
  • exec_py.png

4. 制約など

  • トレーニング及び分析対象帳票のファイル形式ですが、PDFしか試していません
  • Form recognizerの現行バージョンv2.0ベースで作っています。他バージョンで使う場合、APIのURLの適宜変更と、Form recognizerが返すjsonフォーマット変更への対応が必要になると思います
11
10
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
11
10