【Ruby】Google cloud vision APIを使って画像からテキストを抽出する
課題
Google vision apiを使ってドキュメントのスキャン画像からテキストを抽出する。
準備
1. 画像を準備
jpg、pngなどに対応している。pdfの場合はこれらの形式の画像に変換する必要がある。
2. gemをインストール
bundlerを使う場合はGemfileを用意する。
source "https://rubygems.org" gem "google-cloud-vision"
そうしたらbundle install
を実行する。
$ bundle install Using public_suffix 3.0.3 Using addressable 2.5.2 Using bundler 1.16.1 Using multipart-post 2.0.0 Using faraday 0.15.4 Using google-cloud-env 1.0.5 Using google-cloud-core 1.2.7 Using google-protobuf 3.6.1 (x86_64-linux) Using googleapis-common-protos-types 1.0.2 Using grpc 1.17.1 (x86_64-linux) Using googleapis-common-protos 1.3.7 Using jwt 2.1.0 Using memoist 0.16.0 Using multi_json 1.13.1 Using os 1.0.0 Using signet 0.11.0 Using googleauth 0.6.7 Using rly 0.2.3 Using google-gax 1.4.0 Using google-cloud-vision 0.28.0 Bundle complete! 1 Gemfile dependency, 20 gems now installed. Use `bundle info [gemname]` to see where a bundled gem is installed.
依存モジュールがまとめてインストールされた。
3. APIの鍵情報を設定
GoogleのAPIをたたくために鍵情報(認証情報)を設定しよう。
認証情報が書かれたJSONファイル(GCPコンソールからダウンロードできる)をスクリプトから参照させる方法をとる。
そのためにはまず.bashrcなどに次の一行をくわえる。
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/wd/credential.json"
credential.json
のところに実際のファイル名を入れる。このようにするとGOOGLE_APPLICATION_CREDENTIALS
という環境変数を自動的にみるようになる。
スクリプト
次にスクリプトの本体を書こう。
require "google/cloud/vision" project_id = "xxxx" # GCPのコンソールで調べる image_path = './doc.jpg' # スキャン画像など vision = Google::Cloud::Vision.new(project: project_id) image = vision.image(image_path) document = image.document puts document.text
実行すると、doc.jpg
から抽出されたテキストが出力されるとおもう。
雑感
鍵情報の読み込み方がよくわからなくて困った。公式ドキュメントを探したのだけど、見つからなかった。結局、スクリプトを実行して、エラーに書かれたURLに設定方法が書いてあった。環境変数を設定する の箇所を参照のこと。 https://developers.google.com/accounts/docs/application-default-credentials