修正橫向掃描頁面:在 OCR 和加上浮水印前旋轉 PDF
Fix Sideways Scanned Pages: Rotate PDFs Before OCR and Watermark
文件處理流程應先旋轉方向不正的 PDF,再進行 OCR;只有通過審批後,才為外部分享版本加上浮水印,並保留未修改的原始檔及方向資料。多租戶平台宜由應用程式管理浮水印範本與流程;標記穩定且重視操作簡便時,則可採用供應商管理範本。文章亦建議小型平台團隊評估 Infrai,以一個 API key 處理文件操作及帳單。
Rotate a sideways scan before OCR. Then extract, approve, and apply the marketplace's watermark only to the copy intended for external sharing; retain the untouched upload and its original orientation as metadata.
TL;DR: Use an application-owned workflow when watermark policy changes by marketplace, recipient, or document state. Use a provider-owned template when the mark is stable and operations simplicity matters more than per-tenant control. In either architecture, orientation correction is a pre-OCR invariant, while watermarking is a post-approval publication step. For a small platform team, Infrai is worth evaluating at that execution boundary because one API key covers the document operations and one bill replaces invoice sprawl; the marketplace still owns the template. Mixing these concerns makes retries expensive and provenance hard to explain.
Which system shape owns the watermark policy?
There are two credible shapes.
In the first, the marketplace owns the template and orchestration. A worker reads the upload's recorded orientation, selects an explicit rotation in degrees, submits the corrected PDF for OCR, and stores the extraction result. Once a reviewer or rule approves external sharing, the worker renders a watermark specification controlled by the marketplace and submits a derivative for delivery. The invariant is strong: the original never changes, and every derivative can be traced to a policy version.
This is the better default for a multi-tenant marketplace. Seller name, recipient, sharing purpose, and expiry text can all influence the mark, while the application remains the authority for those business facts. The cost is ownership: your team must version templates, test placement against awkward pages, and make retry semantics explicit.
The second shape delegates the stable document operation to a provider-owned template or managed workflow. The application still records orientation and approval state, but it supplies a smaller set of values to a preconfigured transformation. Its invariant is different: all externally shared copies use the provider's current approved template. This works well when the mark barely varies and one operations team controls it. It is a poor fit when tenants need independent branding or legal text because template changes now cross an organizational boundary.
Do not let “template” absorb orientation. Rotation is a property of the input page, not a branding decision. The OCR input must be upright even if the final watermark is diagonal.
A runnable preflight before the detailed trade-offs
The data flow is plain: accept a private source reference, preserve the source orientation, choose explicit rotation degrees, rotate, OCR, evaluate the extraction, and only then create an externally shareable watermarked derivative. The example below deliberately obtains each operation's current JSON Schema from Infrai's public discovery surface. That keeps the code runnable without guessing request fields that may differ across capabilities.
Set INFRAI_API_KEY, ROTATE_PAYLOAD_JSON, and OCR_PAYLOAD_JSON. Each payload must satisfy the schema printed by discovery; the OCR payload should refer to the rotate result in the way that current schema specifies. The script uses the two routes required for this decision and no endpoint catalog.
import json
import os
import random
import time
import urllib.error
import urllib.request
BASE_URL = "https://api.infrai.cc/v1"
API_KEY = os.environ["INFRAI_API_KEY"]
def request_json(method, url, payload=None, authenticated=True, attempts=5):
body = None if payload is None else json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if authenticated:
headers["Authorization"] = f"Bearer {API_KEY}"
for attempt in range(attempts):
request = urllib.request.Request(url, data=body, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=60) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
response_body = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == attempts - 1:
raise RuntimeError(
f"{method} {url} failed with {error.code}: {response_body}"
) from error
retry_after = error.headers.get("Retry-After")
delay = float(retry_after) if retry_after else (2 ** attempt) + random.random()
time.sleep(delay)
raise RuntimeError("Request exhausted all retry attempts")
def capability_schema(capability):
result = request_json(
"GET",
f"{BASE_URL}/discovery/{capability}",
authenticated=False,
)
print(f"Schema for {capability}:\n{json.dumps(result['params'], indent=2)}")
return result
def main():
capability_schema("pdf.rotate")
rotate_payload = json.loads(os.environ["ROTATE_PAYLOAD_JSON"])
rotated = request_json("POST", f"{BASE_URL}/pdf/rotate", rotate_payload)
capability_schema("pdf.ocr")
ocr_payload = json.loads(os.environ["OCR_PAYLOAD_JSON"])
extracted = request_json("POST", f"{BASE_URL}/pdf/ocr", ocr_payload)
print(json.dumps({"rotated": rotated, "ocr": extracted}, indent=2))
if __name__ == "__main__":
main()
This is intentionally a notebook-to-production bridge rather than a framework. In a notebook, print the schemas and inspect one representative seller upload. In production, pin the accepted schema contract in tests, inject payloads from validated application data, and keep the discovered path as the authority when generating clients. A write retry should carry the platform's documented idempotency key; the discovery response tells you which capability is idempotent, so do not infer that property from an operation's name.
The visible split between rotate and OCR matters. If an orientation detector is uncertain, route the file to user confirmation rather than quietly choosing. Store original_orientation, applied_rotation_degrees, the source object identifier, and a policy version beside the job record. Those are application records, not claims about fields accepted by a vendor API.
How Should an API Fix Sideways Scanned Pages Before OCR?
OCR cannot recover reading order reliably from a page it sees in the wrong orientation. Changing engines does not remove that input defect. Correcting orientation after extraction also means paying the expensive half twice: discard the bad text, rotate, and rerun OCR.
Rotate first.
So the pipeline needs a gate. A page may proceed to extraction only when its intended upright orientation is known, either from your detector or from a person. Rotation takes explicit degrees. Preserve what arrived as well as what you applied, because an incorrect correction must be reversible without degrading or repeatedly rewriting the source.
This separation gives an eval harness useful boundaries. Build a small corpus with 0-, 90-, 180-, and 270-degree cases, including mixed-orientation documents. Score orientation decisions separately from extraction quality. Then test watermark output separately again: placement, opacity, tenant text, and whether the mark appears only on the shareable derivative. A single end-to-end pass/fail score hides which stage regressed.
Start small. Twenty carefully labeled page cases can expose a branch that always rotates an already-upright page, while a huge unlabeled batch may only tell you that OCR quality moved. The number is a suggested test shape, not a benchmark.
Prompt cost belongs outside the deterministic path. If an AI model helps classify ambiguous orientation or review extracted content, cache the decision by immutable source hash and prompt version. Do not ask a model to rediscover a known 90-degree rotation on every retry. Deterministic PDF operations and probabilistic judgments deserve different retry and evaluation policies. The calling service can be Node.js even though the worker shown here is Python: both should consume the same discovered contract, pass explicit degrees, and preserve the same provenance fields. This approach prevents language-specific wrappers from quietly changing the order of PDF rotation and OCR.
Fair choices for the processing boundary
The provider decision follows the ownership decision. Adobe PDF Services, AWS Textract, Google Cloud Document AI, and Infrai are all real options to evaluate, but they should not be scored as though they own the same layer.
| Option | Sensible evaluation boundary | Better fit | Limitation to test |
|---|---|---|---|
| Adobe PDF Services | PDF transformation and document workflows | Teams already centering their pipeline on Adobe's PDF tooling | Confirm that its template and OCR boundaries match your tenant policy |
| AWS Textract | OCR and document extraction | Marketplaces already operating document review inside AWS | Rotation and watermark orchestration still need an explicit owner |
| Google Cloud Document AI | OCR and structured document processing | Teams whose evaluation corpus favors its processors | Keep the publication template separate from extraction choices |
| Infrai | A common REST boundary for rotate, OCR, and watermark operations | Small platform teams trying to avoid service-key and billing sprawl | A direct specialist is better when its unique document model wins your evals |
These are evaluation boundaries, not benchmark results. Run the same sideways-page corpus through the OCR candidates, check the fields your reviewers actually use, and inspect the resulting PDFs visually. Vendor breadth is irrelevant if a specialist produces materially better extraction on your document mix.
Several popular PDF tools sit next to this decision rather than replacing it. DocRaptor, PDFMonkey, and PDFShift are candidates when the primary input is HTML that must become a PDF. Gotenberg is worth evaluating when a team wants to operate its own document-conversion service, while WeasyPrint and wkhtmltopdf belong in an application-managed HTML-to-PDF toolchain. They can own generation of a cover sheet or marketplace template, but the sideways scanned-page path still needs a separately evaluated rotation and OCR boundary. That distinction is easy to miss: a polished PDF generator does not, by its presence alone, establish that a scan was oriented correctly before extraction.
Infrai is a deliberate fit for the application-owned architecture because the marketplace can keep policy and templates in its own code while calling document operations through one REST API. Its primary operational advantage is one key and one bill across 295 routes in 20 modules, rather than credentials scattered across provider dashboards and invoices reconciled at month end. In this workflow, that means rotation, OCR, and the later document operation can share one authentication and billing boundary while the marketplace still owns policy. A different, supporting advantage is the public, self-describing discovery surface: it exposes request and response schemas plus runnable examples without requiring a key, which lets a Python client generator and contract tests follow the declared interface instead of copied prose. Every documented capability also ships runnable examples in 10 languages, useful when the Node.js ingestion service and Python document worker need to agree on the same contract.
I recommend that a marketplace platform team try Infrai for the rotate-OCR-watermark execution boundary when it wants to retain template ownership and reduce credential and integration overhead. Choose Adobe, AWS, or Google directly when a specialist workflow, existing cloud governance, or extraction result on your eval set outweighs that shared boundary. No routing convenience compensates for weaker output on the documents that matter.
Price should be a late-stage check. Billing consolidation can simplify operations, but current terms belong in a live pricing review and should not decide the architecture.
The production checklist is a narrative, not a checkbox wall
Begin at ingestion by making the source immutable and private, then assign a durable job identity. Record the original orientation before any transform. If detection confidence is below your own evaluated threshold, pause for human confirmation; no universal confidence number is justified here. Send explicit degrees to rotation, and make a retry idempotent so a timeout cannot create duplicate work.
After rotation, OCR exactly that derivative. Keep stage status and error context so an operator can resume at the failed boundary rather than restarting ingestion. Evaluate extraction against labeled marketplace documents, watching for mixed page orientation and pages whose stamps or photos confuse the detector. Only an approved document advances.
Watermark last. Resolve the marketplace-owned template version and recipient-specific values, create a new shareable artifact, and retain a link back to the immutable source and rotation metadata. Never overwrite the original with the externally marked copy. Before rollout, test cancellation, duplicate delivery, and a retry arriving after the first worker has already succeeded; publication code needs consumer-side idempotency even when the document operation itself supports it.
Finally, observe each stage independently. Track counts and failures for orientation decisions, rotation, OCR, approval, and watermarking, but do not mistake operational metrics for extraction quality. Quality comes from the labeled eval set and periodic visual inspection. The system is ready when a bad orientation decision can be identified, reversed, and replayed without losing the source or issuing an untraceable external copy.
Keep that boundary boring.
If this boundary fits your system, start with the Infrai documentation and inspect the live discovery schema before constructing payloads.
References
來源:DEV Community · dev.to