用 Python 解析發票:一份 REST API 指南
使用 Python 從發票中提取結構化資料。本指南將說明如何呼叫一個簡單的 REST API,從任何發票影像中取得 JSON 欄位、條列項目以及可供驗證的座標。
從發票中提取結構化資料是個常見卻惱人的任務。您可能有一堆掃描的收據或廠商發票,格式是 JPEG 或 PNG,而您需要從中取出發票號碼、總金額和每個條列項目,以利會計或分析之用。大多數 OCR 工具只會輸出一大堆文字,讓您得用脆弱的正規表示式(regular expressions)辛苦地重組資料結構。
其實有個更直接的方法:透過一次 REST API 呼叫,就能回傳您需要的結構化 JSON,而且每個數值都能追溯到它在頁面上的確切位置。下方的互動式範例展示了最終成果。點擊左側任何欄位,即可看到它在發票上對應的位置反白顯示。

Each value with a box carries a verified on-page location — in data.cells[path], that is box + 4-point quad + evidence.match_ratio — on a 0–1000 normalized grid (0,0 top-left → 1000,1000 bottom-right), the same shape the live API returns. Hover a field to trace it back to the pixels it came from.

space-ocr 不是一個需要安裝的函式庫,而是一個單純的 HTTP 服務。流程很簡單:準備一張發票影像,將它傳送到 POST /ocr/fields 端點,並定義您希望回傳的資料綱要(schema)。您可以指定像是 invoice_number、total_due 等欄位,以及一個包含品項描述和價格欄位的 line_items 表格。API 會把您宣告的綱要原樣放在 data.values 回傳,座標與驗證結果則分別放在同層的其他鍵裡。
回應會把資料和驗證結果分開存放。data.values 就是您宣告的綱要本身,invoice_number 的 "20250430-001" 也在您定義的位置上。data.cells 是一個以路徑為鍵的扁平對映,cells["total_due"] 裡放著該值在頁面上的 box 與 quad,以及一個 verified 判定。data.review.flagged 則是一份簡短清單,列出值得再看一眼的路徑和對應的 reasons。下方的綱要宣告了日期與數字,因此 data.normalized 會一併回傳解析後的值,而 values 保留讀取到的原始寫法。下方的 Python 腳本會依序取出這些內容。
import os
import base64
import json
import requests
# Get your API key from an environment variable
API_KEY = os.environ.get("SPACE_OCR_API_KEY")
IMAGE_PATH = "./path/to/your/invoice.jpg" # Path to your invoice image
API_URL = "https://api.space-ocr.com/ocr/fields"
if not API_KEY:
raise ValueError("API key not found. Set the SPACE_OCR_API_KEY environment variable.")
# Declare the schema you want back.
# 'type' adds a deterministic parse under data.normalized; 'required' and 'pattern'
# are checked after extraction and show up in the review list when they fail.
# Declarations never reach the model: they do not change the value, only the signals.
fields_schema = [
{"name": "supplier", "type": "string", "description": "The name of the company that issued the invoice."},
{"name": "invoice_number", "type": "string", "required": True, "pattern": "^[0-9]{8}-[0-9]{3}$"},
{"name": "issue_date", "type": "date", "required": True},
{"name": "total_due", "type": "number", "required": True},
{
"name": "line_items",
"type": "array",
"description": "All items listed in the invoice table.",
"children": [
{"name": "item_description", "type": "string"},
{"name": "unit_price", "type": "number"},
{"name": "quantity", "type": "integer"},
{"name": "line_total", "type": "number"}
]
}
]
# Read the image file and encode it in base64
with open(IMAGE_PATH, "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"image": base64_image,
"imageType": "base64",
"fields": fields_schema
}
print(f"Sending request for {IMAGE_PATH}...")
response = requests.post(API_URL, headers=headers, json=payload)
if response.status_code != 200:
# Errors use one envelope: {"error": {"code", "message", "requestId"}, "details": {...}}
try:
err = response.json()["error"]
print(f"HTTP {response.status_code} {err['code']}: {err['message']} (requestId {err['requestId']})")
except (ValueError, KeyError):
# A body over 32MiB is cut off before the app sees it and comes back as HTML
print(f"HTTP {response.status_code}: {response.text[:200]}")
if response.status_code == 429:
print(f"Rate limited - Retry-After: {response.headers.get('Retry-After')} seconds")
# 400 invalid_image is not charged and a retry will not help; 502 is refunded and worth
# retrying; 504 means the 180s sync ceiling was hit, so send that page on its own.
raise SystemExit(1)
data = response.json()["data"]
values = data["values"] # your schema, and nothing else
cells = data["cells"] # flat map: path -> box / quad / verified / review / evidence
review = data["review"] # what is worth a second look
normalized = data.get("normalized", {}) # deterministic parse of the types you declared
image = data["image"] # {"width", "height"} - the frame the coordinates use
print("\n--- Extracted Invoice Data ---")
print(json.dumps(values, ensure_ascii=False, indent=2))
# 'values' keeps the text as it was read; the parsed form lives here.
# A null leaf means the parse failed - the reason sits in cells[path]["normalized"]["error"].
print("\nissue_date parsed:", normalized.get("issue_date"))
print("total_due parsed :", normalized.get("total_due"))
# The review queue: every entry carries a path and a rank-ordered reasons array.
print(f"\n{len(review['flagged'])} of {review['declared']} declared fields were flagged:")
for item in review["flagged"]:
path = item["path"]
reasons = item["reasons"] # reasons[0] is the primary one
cell = cells.get(path) # 'missing' and 'nobox' have no cell to point at
box = cell["box"] if cell else None
print(f" {path}: {reasons[0]} ({', '.join(reasons)}) box={box}")
# Where a single value came from
total = cells.get("total_due")
if total:
print("\ntotal_due")
print(" box :", total["box"]) # {"xmin", "ymin", "xmax", "ymax"}, 0-1000
print(" quad :", total["quad"]) # four {"x", "y"} points, following the page tilt
print(" verified:", total["verified"]) # False if flagged, True if a check ran clean, None if there was nothing to check
print(" evidence:", total["evidence"]) # text_match, source, match_ratio, printed_text ...
left = total["box"]["xmin"] / 1000 * image["width"]
top = total["box"]["ymin"] / 1000 * image["height"]
print(f" pixels : ({left:.0f}, {top:.0f}) on a {image['width']}x{image['height']} page")
# Line items: values holds the rows, cells is keyed by the indexed path
print("\nline_items")
for i, row in enumerate(values.get("line_items") or []):
cell = cells.get(f"line_items[{i}].line_total")
verified = cell["verified"] if cell else None
print(f" row {i}: {row.get('item_description')} x{row.get('quantity')} "
f"= {row.get('line_total')} (verified={verified})")為了確保準確性,space-ocr 並不全然相信語言模型的輸出。模型會回傳文字值以及它在頁面上使用了哪些詞彙的提示。接著,引擎會對照頁面上實際的 OCR 符號,對擷取出的數值進行逐字元比對。這個過程會產生 match_ratio 信賴度分數(≥ 0.85 即為高信賴度比對)和座標,兩者都放在 data.cells[path] 裡:box 是 xmin、ymin、xmax、ymax 四個整數鍵,quad 則是隨頁面傾斜的四個點。所有座標都標準化到 0-1000,因此與原始影像的解析度無關;要換算成像素時,請用 data.image 提供的頁面尺寸。比對本身的結果記在 evidence.text_match,而 verified 是該單元的整體判定 —— 只要有任何指摘成立,包含您自行宣告的規則,它就會變成 false。
API 的計價方式是按次計費,而非根據欄位數量或頁面複雜度。每張影像 $0.05(含稅),若請求未能成功產生結果則不收費。新註冊帳戶每月可獲得 100 次免費掃描額度。
- 取得您的 API 金鑰註冊一個免費的 space-ocr 帳戶,並在儀表板設定中找到您的 API 金鑰。金鑰會以「spocr_」開頭。
- 準備您的發票影像將您的發票儲存為常見的影像檔,例如 JPEG 或 PNG。記下檔案路徑以供腳本使用。
- 定義您的資料綱要在您的 Python 腳本中建立一個 JSON 陣列,用來定義您想擷取的欄位名稱和類型,包含任何條列項目表格。
- 撰寫 Python 腳本使用 requests 函式庫,撰寫一個腳本來讀取影像、將其轉換為 base64,並將 API 金鑰放在 Authorization 標頭中,向 https://api.space-ocr.com/ocr/fields 發送 POST 請求。
- 執行並處理 JSON執行您的腳本。把 `data.values` 載入資料庫、會計軟體或分析工具,並先核對 `data.review.flagged` 中列出的那幾個值。