GCP OCR と Java による請求書データの抽出
OCR のレスポンスから得られるのはテキストですが、請求書のワークフローには、内容を確認できる項目が必要です。この Maven CLI は、生成したサンプル請求書を Google Cloud Vision に送信し、ラベル付きの行を解析して、請求書番号、日付、販売元、USD 建ての合計金額を含む JSON を書き出します。財務処理のために送信する前に、出力を人が確認する必要があります。
前提条件
以下のコマンドは、Linux または macOS の Bash シェルで実行します。このサンプルでは、JDK 21.0.12.1、Maven 3.10.0、Google Cloud CLI を使用します。Google の
Java クライアントライブラリは Java 21 をサポートしています。mvn が利用できない場合は、公式のインストール手順に従って Maven をインストールしてください。
また、課金と Cloud Vision API がすでに有効になっているプロジェクトと、そのプロジェクトの API および割り当てを使用する権限のあるアカウントが必要です。これらの前提条件を満たしていない場合は、Google の Vision セットアップガイドに従ってください。まずは、以下の機密情報を含まない生成済み請求書を使用してください。OCR を呼び出すたびに画像が Google に送信され、料金が発生する場合があります。
請求書レイアウトの定義
このパーサーは、米国式の月/日/年の日付と、USD を明記した金額を含む、四つのラベル付き行を処理します。
Invoice No: INV-123
Date: 03/19/2025
Vendor: Example Ltd
Total: USD 1,234.56
項目の有無、ラベルの重複、暦上の日付の妥当性、金額の構文を検証します。もっともらしい値を OCR が正しく読み取ったかどうかは判定できません。使用する前に JSON と画像を照合してください。レイアウトや通貨が異なる請求書では、これらのルールが適用できると想定せず、その文書に合わせてパーサーを変更してテストしてください。
Java SDK の認証
ローカル開発では、SDK は
Application Default Credentials を使用します。両方のコマンドで YOUR_PROJECT_ID をプロジェクト ID に置き換えてください。
gcloud auth application-default login --project=YOUR_PROJECT_ID &&
gcloud auth application-default set-quota-project YOUR_PROJECT_ID
割り当てプロジェクトは、割り当てと課金に使用するプロジェクトを決定します。gcloud auth login のセッションだけでは、SDK の ADC は提供されません。ローカルユーザーの ADC を使用する場合は、SDK が別の認証情報ファイルを選択しないように、シェルから古い GOOGLE_APPLICATION_CREDENTIALS の上書き設定を削除してください。このローカルのサンプルには、サービスアカウントキーは不要です。
Maven プロジェクトの作成
既存の Maven プロジェクトの外にあるディレクトリで、次のブロックを実行してください。ツールを確認し、上位に pom.xml または
.mvn の設定がある場合は、ファイルを作成せずに処理を拒否します。
(
cd -P . || exit 1
parent="$PWD"
while :; do
if [ -e "$parent/pom.xml" ] || [ -e "$parent/.mvn" ]; then
printf '%s\n' 'Choose a directory outside an existing Maven project.' >&2
exit 1
fi
[ "$parent" = / ] && break
parent="${parent%/*}"
[ -n "$parent" ] || parent=/
done
java -version && javac -version && mvn -version && gcloud --version || exit 1
mkdir invoice-ocr && mkdir -p invoice-ocr/src/main/java
)
既存の invoice-ocr ディレクトリは保持され、処理は拒否されます。既存のプロジェクトを削除せず、新しい親ディレクトリを選んでください。空のディレクトリを作成した後に処理が停止した場合は、原因を解消し、そのディレクトリ内で src/main/java を完了してから、以下のファイルを保存してください。
この完全な pom.xml を invoice-ocr/pom.xml として保存してください。Google Cloud BOM がライブラリのバージョンを管理します。この固定設定では、Vision 3.97.0 と Gson 2.14.0 が解決されます。パッケージ化の処理ではクラスをコンパイルし、Java ランチャー向けに実行時依存関係を target/dependency にコピーします。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example</groupId>
<artifactId>invoice-ocr</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.90.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-vision</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.9.0</version>
<executions>
<execution>
<id>runtime-dependencies</id>
<phase>package</phase>
<goals><goal>copy-dependencies</goal></goals>
<configuration><includeScope>runtime</includeScope></configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
サンプル請求書の生成
GenerateInvoice.java を invoice-ocr/src/main/java に保存してください。上記の既知の項目から PNG を作成するため、顧客の文書や画像のダウンロードは不要です。保存先がすでに存在する場合は処理を拒否します。
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import javax.imageio.ImageIO;
public class GenerateInvoice {
public static void main(String[] args) {
try {
if (args.length != 1) {
throw new IllegalArgumentException("Expected one PNG destination");
}
BufferedImage image = new BufferedImage(1600, 600, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
try {
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
graphics.setColor(Color.BLACK);
graphics.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 48));
String[] lines = {
"Invoice No: INV-123", "Date: 03/19/2025",
"Vendor: Example Ltd", "Total: USD 1,234.56"
};
for (int index = 0; index < lines.length; index++) {
graphics.drawString(lines[index], 80, 120 + index * 110);
}
} finally {
graphics.dispose();
}
try (OutputStream output = Files.newOutputStream(Path.of(args[0]),
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
if (!ImageIO.write(image, "png", output)) {
throw new IllegalStateException("PNG encoder unavailable");
}
}
} catch (Exception error) {
System.err.println("Sample creation failed (" + error.getClass().getSimpleName() + ")");
System.exit(1);
}
}
}
ラベル付き項目の解析と検証
InvoiceParser.java をジェネレーターと同じ場所に保存してください。ラベル全体を照合することで、Total と Subtotal を区別します。Invoice Date や Amount Due などの別名も受け付けますが、同じ項目に二つのラベルがある場合は、値が一致していても拒否します。日付には厳密な暦のパーサーを使用します。米国式を明示しているため、03/04/2025 は 3月4日を意味します。小数点にカンマを使用した金額、他の通貨、金額や日付に余分なテキストがある場合は拒否します。金額は十進数の文字列のまま保持するため、JSON の利用側で金額の計算に二進浮動小数点演算を使う必要はありません。
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
public class InvoiceParser {
public static Map<String, String> parseInvoiceData(String text) {
Map<String, String> fields = new LinkedHashMap<>();
for (String line : text.split("\\R")) {
String[] parts = line.strip().split(":", 2);
if (parts.length != 2) continue;
String field = switch (parts[0].strip().toLowerCase(Locale.ROOT)) {
case "invoice no", "invoice no.", "invoice number", "invoice #" -> "invoiceNumber";
case "date", "invoice date" -> "date";
case "total", "amount due", "balance due" -> "totalAmount";
case "vendor", "supplier", "from", "company" -> "vendor";
default -> null;
};
if (field == null) continue;
if (fields.putIfAbsent(field, parts[1].strip()) != null) {
throw new IllegalArgumentException("Duplicate invoice field: " + field);
}
}
for (String field : new String[] {"invoiceNumber", "date", "vendor", "totalAmount"}) {
if (!fields.containsKey(field) || fields.get(field).isBlank()) {
throw new IllegalArgumentException("Missing invoice field: " + field);
}
}
if (!fields.get("invoiceNumber").matches("[A-Za-z0-9][A-Za-z0-9/-]*")) {
throw new IllegalArgumentException("Invalid invoice number");
}
if (!fields.get("date").matches("[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}")) {
throw new IllegalArgumentException("Expected a US month/day/year date");
}
DateTimeFormatter dates = DateTimeFormatter.ofPattern("M/d/uuuu", Locale.US)
.withResolverStyle(ResolverStyle.STRICT);
fields.put("date", LocalDate.parse(fields.get("date"), dates).toString());
String total = fields.get("totalAmount");
if (!total.matches("USD[ \\t]+(?:[0-9]+|[0-9]{1,3}(?:,[0-9]{3})+)\\.[0-9]{2}")) {
throw new IllegalArgumentException("Expected one USD amount with two decimal places");
}
fields.put("totalAmount", new BigDecimal(total.substring(3).strip()
.replace(",", "")).toPlainString());
fields.put("currency", "USD");
return fields;
}
}
Vision OCR と JSON 出力の接続
InvoiceOCR.java を同じディレクトリに保存してください。CLI はローカル画像を一つ読み込み、Vision を呼び出し、返されたテキストを
InvoiceParser に直接渡して、解析した項目を Gson でシリアライズします。使用する DOCUMENT_TEXT_DETECTION のレスポンスは、高密度のテキストや文書向けに最適化されています。Vision のレスポンスにはレイアウト情報も含まれますが、この小さなパーサーではテキストだけを使用します。
このコードは Google の EU OCR エンドポイントと、EU を明示したリクエストの親リソースを選択します。認識処理の自動再試行を無効にし、RPC タイムアウトを 20秒に設定します。失敗またはタイムアウトしたリクエストも Google に到達している可能性があるため、再度呼び出すと追加の料金が発生する場合があります。
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesRequest;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;
import com.google.gson.GsonBuilder;
import com.google.protobuf.ByteString;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.DateTimeException;
import java.time.Duration;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.imageio.ImageIO;
public class InvoiceOCR {
public static void main(String[] args) {
try {
if (args.length != 3 || !args[0].matches("[a-z][a-z0-9-]{4,28}[a-z0-9]")) {
System.err.println("Usage: InvoiceOCR PROJECT_ID IMAGE_PATH NEW_JSON_PATH");
System.exit(1);
}
Path output = Path.of(args[2]);
if (Files.exists(output)) {
throw new InvoiceFailure("Output already exists; choose a fresh JSON destination.");
}
byte[] bytes = Files.readAllBytes(Path.of(args[1]));
if (ImageIO.read(new ByteArrayInputStream(bytes)) == null) {
throw new InvoiceFailure("Image cannot be decoded; check the input file.");
}
String text = recognize(args[0], bytes);
Map<String, String> invoice = InvoiceParser.parseInvoiceData(text);
Map<String, Object> review = new LinkedHashMap<>();
review.put("status", "needs_review");
review.put("invoice", invoice);
review.put("ocrText", text);
String json = new GsonBuilder().setPrettyPrinting().create().toJson(review) + "\n";
Files.writeString(output, json, StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
System.out.println("Saved JSON for human review.");
} catch (InvoiceFailure error) {
System.err.println(error.getMessage());
System.exit(1);
} catch (IllegalArgumentException | DateTimeException error) {
System.err.println("Invoice rejected: check labels, duplicate fields, US dates, and USD amounts.");
System.exit(1);
} catch (ApiException error) {
System.err.println("Vision request failed (" + error.getStatusCode().getCode() + ").");
System.exit(1);
} catch (Exception error) {
System.err.println("Invoice processing failed (" + error.getClass().getSimpleName()
+ "). Check input, output, and ADC; no invoice was submitted.");
System.exit(1);
}
}
private static String recognize(String project, byte[] bytes) throws IOException {
ImageAnnotatorSettings.Builder settings = ImageAnnotatorSettings.newBuilder()
.setEndpoint("eu-vision.googleapis.com:443")
.setQuotaProjectId(project)
.setTransportChannelProvider(InstantiatingGrpcChannelProvider.newBuilder()
.setChannelConfigurator(channel -> channel.disableRetry()).build());
settings.batchAnnotateImagesSettings().setRetryableCodes(Collections.emptySet());
settings.batchAnnotateImagesSettings().setRetrySettings(
settings.batchAnnotateImagesSettings().getRetrySettings().toBuilder()
.setMaxAttempts(1)
.setInitialRpcTimeoutDuration(Duration.ofSeconds(20))
.setMaxRpcTimeoutDuration(Duration.ofSeconds(20))
.setTotalTimeoutDuration(Duration.ofSeconds(20)).build());
AnnotateImageRequest imageRequest = AnnotateImageRequest.newBuilder()
.setImage(Image.newBuilder().setContent(ByteString.copyFrom(bytes)).build())
.addFeatures(Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build())
.build();
BatchAnnotateImagesRequest request = BatchAnnotateImagesRequest.newBuilder()
.setParent("projects/" + project + "/locations/eu")
.addRequests(imageRequest)
.build();
try (ImageAnnotatorClient client = ImageAnnotatorClient.create(settings.build())) {
BatchAnnotateImagesResponse batch = client.batchAnnotateImages(request);
if (batch.getResponsesCount() != 1) {
throw new InvoiceFailure("Expected one Vision response; output was not created.");
}
AnnotateImageResponse response = batch.getResponses(0);
if (response.hasError()) {
throw new InvoiceFailure("Vision returned an image error (code "
+ response.getError().getCode() + "); output was not created.");
}
String text = response.getFullTextAnnotation().getText();
if (text.isBlank()) {
throw new InvoiceFailure("No text found; output was not created.");
}
return text;
}
}
private static class InvoiceFailure extends IOException {
private static final long serialVersionUID = 1L;
InvoiceFailure(String message) {
super(message);
}
}
}
このサンプルはラスター画像を使用します。PDF/TIFF 入力では、文書のバイト列を Image に入れるのではなく、ファイルのアノテーションリクエストが必要です。また、パーサーは各ラベルと値が OCR の同じ行にあることを前提とします。表を解釈するのではなく、明細の説明など、認識対象ではない行を無視します。
完全なサンプルのビルドと実行
invoice-ocr の親ディレクトリで、YOUR_PROJECT_ID を置き換えてから、以下を貼り付けてください。
(
cd invoice-ocr &&
mvn -q package &&
java -Djava.awt.headless=true -cp 'target/classes:target/dependency/*' GenerateInvoice invoice.png &&
java -cp 'target/classes:target/dependency/*' InvoiceOCR YOUR_PROJECT_ID invoice.png invoice.json &&
cat invoice.json
)
ここでのクラスパスの区切り文字は、Linux と macOS で使用する
: です。ビルドが失敗すると、以前にコンパイルしたクラスが存在していても起動を停止します。実行に成功すると、invoice.png と
invoice.json が作成されます。JSON の invoice オブジェクトには、キーの順序にかかわらず、次の値が含まれるはずです。
{
"invoiceNumber": "INV-123",
"date": "2025-03-19",
"vendor": "Example Ltd",
"totalAmount": "1234.56",
"currency": "USD"
}
外側のオブジェクトには status: "needs_review" と実際の ocrText が含まれるため、パーサーが取り込んだ内容を確認できます。五つの値をすべて
invoice.png と照合してください。構文上は有効な項目でも、内容が誤っている場合があります。JSON は UTF-8 で、末尾に改行が付きます。
ジェネレーターと CLI は、既存の出力パスを拒否します。そのため、ブロック全体を再実行すると、次の認識リクエストを送る前に、既存の invoice.png の時点で停止します。すでにある画像と JSON は保持してください。失敗の原因を修正してから OCR だけを再試行するには、新しい JSON 保存先を使用してください。
(
cd invoice-ocr &&
java -cp 'target/classes:target/dependency/*' InvoiceOCR YOUR_PROJECT_ID invoice.png invoice-retry.json &&
cat invoice-retry.json
)
CLI がゼロ以外の終了コードで終了した場合は、再試行する前に出力ファイルの有無を確認してください。引数、デコード、プロバイダー、空のテキスト、解析に関する失敗は、JSON の作成前に発生します。ローカルへの書き込みに失敗すると、新規ファイルが不完全な状態で残る場合があります。確認用に保持し、別の保存先を選んでください。既存の出力は保持されます。画像が空白の場合は、スキャン画像を確認してください。項目が拒否された場合は、四つのラベル付き行とその形式を確認してください。Vision で失敗した場合は、ADC、API アクセス、割り当て、ネットワーク接続を確認してください。CLI は、プロバイダーの生のエラーと認証情報の詳細を表示しません。
財務データを使用する前の確認
このワークフローは、ローカルの確認用成果物を作成した時点で完了します。会計サービスには何も送信しません。画像と項目を照合した後、別の連携処理で送信先の文書化されたスキーマに項目を対応付け、送信時や再試行の状態を照合する際に、送信先の冪等性の仕組みを使用できます。項目の有無と形式の検証は、支払いの承認や請求書の真正性の証明にはなりません。
