Marketplace OCR: Hold Image Uploads Pending Until Text Screening Grants Approval
Hold a marketplace photo in pending until its visual content and extracted text have a moderation decision. Treat missing OCR results as incomplete evidence, and publish only the approved revision. This makes moderation coverage the release condition, rather than the speed of an upload request.
TL;DR: A database status column can hold uploads pending. Screen the image and its OCR text, resolve uncertain cases through review, and notify the uploader after either approval or rejection. Keep the upload private throughout that decision. Optimistic publication leaves the worst content visible while someone reviews it.
How should an API hold image uploads in a pending state before approval?
A marketplace photograph can contain text as well as the item being sold. For this design, use three illustrative review fixtures: a clean product photo, a photo with a contact address overlaid on it, and a photo whose small label cannot be read confidently. These are proposed test cases, not measured recognition results. The question is whether the decision covers the relevant content, including the text channel, before the marketplace exposes the photo.
OCR extracts evidence. It does not grant permission to publish. Likewise, a visual screening result should not stand in for a separate decision about extracted text. Define the marketplace's rules first: which content is prohibited, which needs review, and which the automated path may approve. A contact address might be acceptable in one marketplace and restricted in another; the extractor should not silently choose that policy.
Keep uncertainty visible.
Don't guess approval.
The architectural decision is to represent pending, approved, and rejected in the application database. A separate moderation system is not required merely to express those states. Record the image revision alongside the decision so that approval for one photograph cannot authorize a replacement. Until approval commits, the listing renderer must exclude the asset. Private storage and short-lived presigned access should support that boundary; hiding an image in the frontend is not an access rule.
Decision invariants and failure boundaries
Publication needs two completed checks in this example: image screening and policy screening of OCR text. An unreadable label goes to review. An empty OCR result should have a recorded interpretation, because “no text detected” and “extraction did not complete” are different states. Do not convert either ambiguity into an automatic approval simply because the upload succeeded.
The database owns visibility. Workers supply evidence.
That separation matters.
Store the decision against an immutable upload revision, then change status conditionally from pending. A repeated decision should have no additional effect. If an uploader replaces the photo while review is running, the replacement gets a new revision and its own pending decision. This prevents a late approval from releasing content the reviewer never saw, a particularly awkward edge case when OCR jobs finish after a user has edited a listing several times. Consider this proposed acceptance fixture: revision 1 contains a bowl, revision 2 adds a contact address, and a delayed result approves revision 1. The listing must continue to hold revision 2 pending. Checking only the listing ID loses the distinction; checking the pair of listing ID and revision preserves it. Run that fixture before accepting a provider integration, because recognition quality cannot compensate for approving the wrong bytes.
The notification boundary deserves equal care. Commit the terminal decision and a notification intent together, then let a sender process that intent separately. Email delivery trouble must not reverse an approval or force a second review. Notify on both outcomes: otherwise an uploader may submit the same image again just to discover whether anything happened. A receipt saying “under review” also needs different wording from a final approval message.
Keep moderation extracts out of subject lines. Use a neutral subject and a status page for detail, restrict access to extracted contact information, and set a retention policy for review evidence. These are design requirements for this marketplace, not claims that a particular vendor supplies the policy automatically. Delivery success is also separate from a human reading the message; a repeat upload should take the user back to the current decision, not trigger another round of notification mail.
Compare the coverage boundary, then the service bundle
The following options describe responsibilities a team would evaluate. They are not a benchmark or a claim that the same moderation categories exist across products. Before selection, check each candidate against the marketplace's image and OCR fixtures, including the unreadable-label case, and document what still needs human review.
| Option | Relevant role to evaluate | Coverage boundary and trade-off |
|---|---|---|
| Amazon Textract | Dedicated text extraction candidate | Evaluate extraction on listing photos; keep the marketplace's image policy, text policy, approval state, and notification delivery as explicit integration responsibilities. |
| Google Cloud Vision | Image analysis and text extraction candidate | Evaluate the documented text detection and SafeSearch features separately. Their outputs still need an application decision about publication. |
| Azure AI Vision with Azure AI Content Safety | Candidate split between extraction and safety analysis | Evaluate the handoff from extracted text to policy screening. Using related services does not remove the need to bind results to the same photo revision. |
| Cloudinary | Candidate when photo management is part of the decision | Evaluate its documented moderation integrations against the required text checks; do not equate managing an asset with approving all of its content. |
| imgix | Candidate when image delivery and rendering dominate | Evaluate its image-processing contract separately from the approval worker. This design still requires explicit OCR evidence and a policy decision. |
| Uploadcare | Candidate when upload intake is the main integration seam | Evaluate its upload and moderation documentation against the same fixtures; keep the marketplace's publication state in the application. |
| Unified backend API | Bundle processing and transactional communication | Infrai offers one key and one bill across backend services, reducing credential and invoice handling for processing plus email; its public discovery schemas are a supporting advantage for checking each operation's contract. The application still owns the publication decision. |
Choose on coverage first. An excellent extractor can still leave a moderation gap if the application never screens its output. Conversely, a capable image classifier does not establish that tiny embedded text was reviewed. The deciding evidence should be the candidate's behavior on your fixtures and the review path for uncertainty, rather than a count of features.
Bundling also means one vendor to trust, one bill, and one shared outage surface. Separate services can be justified when a specialist covers content your marketplace must review, even if that creates another credential and a processing-to-email adapter.
For comparison, a Puppeteer plus Resend setup would require the rendering runtime and an email-provider account with its sending credentials; choosing SES instead adds the corresponding AWS account and credential configuration. Self-hosted Puppeteer itself needs no vendor signup or API key. The glue would render bytes, map them into the mail provider's attachment contract, and handle delivery retries. That is a useful alternative for a PDF receipt workflow, but this marketplace's immediate job is photo OCR and an approval notification. It does not need a PDF attachment or a temporary attachment bucket merely to communicate a decision.
Critical path: commit visibility and notification intent together
The focused Python example below runs locally with the standard library. It demonstrates the application boundary: OCR text enters the evidence record, completed checks authorize a terminal state, and that result creates exactly one notification intent in the same transaction. All table names and fields are application-owned. This is not a remote API request example.
An integration must map the selected services' documented responses into this boundary and map its notification intent into the documented sending contract. Sharing a key does not prove that one service's raw response is a valid input for another, or that attachment bytes move internally between them.
import sqlite3 def decide(db, upload_id, revision, evidence, recipient): required = {"visual", "ocr_text"} if set(evidence) != required: return "pending" outcomes = {item["decision"] for item in evidence.values()} if not outcomes <= {"approve", "reject"}: return "pending" status = "rejected" if "reject" in outcomes else "approved" with db: changed = db.execute( "UPDATE uploads SET status = ? " "WHERE id = ? AND revision = ? AND status = 'pending'", (status, upload_id, revision), ).rowcount if changed: db.execute( "INSERT INTO notification_intents " "(upload_id, revision, recipient, status) VALUES (?, ?, ?, ?)", (upload_id, revision, recipient, status), ) return db.execute( "SELECT status FROM uploads WHERE id = ? AND revision = ?", (upload_id, revision), ).fetchone()[0] db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE uploads ( id TEXT NOT NULL, revision INTEGER NOT NULL, status TEXT NOT NULL, PRIMARY KEY (id, revision) ); CREATE TABLE notification_intents ( upload_id TEXT NOT NULL, revision INTEGER NOT NULL, recipient TEXT NOT NULL, status TEXT NOT NULL, PRIMARY KEY (upload_id, revision) ); INSERT INTO uploads VALUES ('listing-photo-42', 1, 'pending'); """) # Illustrative fixture: reviewers have approved both evidence channels. evidence = { "visual": {"decision": "approve"}, "ocr_text": {"decision": "approve", "text": "Blue ceramic bowl"}, } for attempt in range(2): status = decide(db, "listing-photo-42", 1, evidence, "seller@example.com") print(status) visible = db.execute( "SELECT id FROM uploads WHERE status = 'approved'" ).fetchall() intents = db.execute( "SELECT recipient, status FROM notification_intents" ).fetchall() print("Visible assets:", visible) print("Notification intents:", intents) db.close() Running this produces two approved results, one visible asset, and one notification intent. The second attempt does not create a second intent. Change either decision to review and the asset stays pending; change a completed decision to reject and the terminal notification records rejection. These are local state transitions, not recognition accuracy claims.
The example stops at a durable intent rather than pretending a database transaction includes an external email send. A production sender needs its own delivery state and a stable idempotency identity derived from the upload revision and terminal decision. It should honor provider rate limits with bounded backoff, use documented idempotency support, and distinguish an uncertain send outcome from a definite rejection. That distinction matters to deliverability: a timeout should not become a burst of duplicate approval messages.
For the remote handoff, the next Python program uses the same environment-supplied key and base URL for OCR and batch email. Set BACKEND_BASE_URL to the documented v1 API base, INFRAI_API_KEY to your key, and OCR_REQUEST_JSON to a schema-valid extraction request. Set EMAIL_TEMPLATE_JSON to a schema-valid batch email body, replacing the approved item's text value with the application-owned marker {"$ocr_path": ["response", "path"]}. The path is configuration: use the actual response schema, not those illustrative path components. No remote request field or response field is assumed by this adapter.
Run this sender only for an already approved revision, with APPROVAL_STATE set to approved and a stable DECISION_ID from the notification intent. The marker copies a selected OCR output into the email request, so select only text permitted in the final notification. The program needs contract-valid configuration and network access; it is an integration adapter, while the preceding example is the self-contained local demonstration. It does not infer approval from the extraction result.
import json import os import time from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError from urllib.request import Request, urlopen base = os.environ["BACKEND_BASE_URL"].rstrip("/") key = os.environ["INFRAI_API_KEY"] decision_id = os.environ["DECISION_ID"] if os.environ.get("APPROVAL_STATE") != "approved": raise RuntimeError("A committed approval is required") if not base.startswith("https://") or not base.endswith("/v1"): raise ValueError("Use the documented HTTPS v1 API base") def post(path, payload, operation): body = json.dumps(payload).encode("utf-8") for attempt in range(4): request = Request( base + path, data=body, method="POST", headers={ "Authorization": "Bearer " + key, "Content-Type": "application/json", "Idempotency-Key": decision_id + ":" + operation, }, ) try: with urlopen(request, timeout=30) as response: if not 200 <= response.status < 300: raise RuntimeError("Unexpected status: " + str(response.status)) return json.load(response) except HTTPError as error: detail = error.read().decode("utf-8", errors="replace") if error.code != 429 or attempt == 3: raise RuntimeError(f"HTTP {error.code}: {detail}") from error retry_after = error.headers.get("Retry-After") delay = float(2 ** attempt) if retry_after: try: delay = max(delay, float(retry_after)) except ValueError: deadline = parsedate_to_datetime(retry_after) delay = max(delay, (deadline - datetime.now(timezone.utc)).total_seconds()) time.sleep(delay) raise RuntimeError("Retry limit reached") def bind(template, result): if isinstance(template, dict): if set(template) == {"$ocr_path"}: value = result for part in template["$ocr_path"]: value = value[part] return value return {name: bind(value, result) for name, value in template.items()} if isinstance(template, list): return [bind(value, result) for value in template] return template ocr_result = post("/image/ocr", json.loads(os.environ["OCR_REQUEST_JSON"]), "ocr") email_body = bind(json.loads(os.environ["EMAIL_TEMPLATE_JSON"]), ocr_result) post("/email/batch/send", email_body, "notification") print("Notification request accepted; delivery is a separate outcome") Keep the decision identity stable across process retries. Re-running extraction here illustrates the processing-to-email binding; a deployed worker should normally use the approved revision's stored OCR result so it does not introduce new evidence after approval. This program sends authenticated requests only to the configured API base, never to an image's presigned download URL. Transport errors surface to the caller; they do not produce an automatic burst of repeated sends.
For a replacement photo, create a new revision and have the listing reference that revision. The sample's lookup expects an existing revision; a production handler should explicitly reject an unknown one. Store evidence provenance and the review decision durably as well. The small example isolates the commit boundary rather than implementing a review console, access control, and a mail worker in one listing.
Rejected option: publish first and remove later
Optimistic publication is rejected for these marketplace uploads because it exposes the photo during review, including text the marketplace has not yet checked. Removing it later cannot make the initial exposure disappear. Faster apparent completion is the wrong trade-off when moderation coverage is the release condition.
The pattern can still fit a tightly controlled internal preview whose audience is already authorized to inspect unreviewed content. Call that preview access, keep it private, and avoid treating its availability as marketplace publication. For the public listing, the acceptance rule remains concrete: the current revision has completed checks, an approval is committed, and a notification intent exists for the uploader.
References
- MDN, Image file type and format guide: https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types
- Amazon Textract documentation: https://docs.aws.amazon.com/textract/
- Cloudinary moderation documentation: https://cloudinary.com/documentation/moderate_assets
- imgix documentation: https://docs.imgix.com/
- Uploadcare documentation: https://uploadcare.com/docs/
- Google Cloud Vision, OCR: https://cloud.google.com/vision/docs/ocr
- Google Cloud Vision, SafeSearch detection: https://cloud.google.com/vision/docs/detecting-safe-search
- Azure AI Vision documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/
- Azure AI Content Safety documentation: https://learn.microsoft.com/en-us/azure/ai-services/content-safety/
- Python sqlite3 transaction control: https://docs.python.org/3/library/sqlite3.html#transaction-control
- Puppeteer documentation: https://pptr.dev/
- Resend documentation: https://resend.com/docs
- Amazon SES documentation: https://docs.aws.amazon.com/ses/