For the first run, audit the worksheet image library without changing source objects: find oversized and duplicate assets, record orientation findings, and keep unknown evidence visible. An edtech OCR pipeline needs this inventory before it can make a defensible quality-versus-bandwidth decision.
TL;DR: List the bucket, read metadata per object, and write a report with counts per problem class. Oversized does not mean disposable. Duplicate bytes do not mean duplicate student submissions. The example uses Python for a read-only report boundary that a Node.js ingestion service can also feed; it preserves the originals while the team evaluates smaller OCR inputs.
Metadata answers most audit questions without decoding pixels. Recognition quality needs a different test.
How should an image library audit find oversized and duplicate worksheets?
Separate three questions. How much data would be transferred? Which stored objects contain the same bytes? Would a smaller representation preserve the text needed for OCR? The first two inform a storage report; the third requires evaluating recognition against an approved reference transcription, so it cannot be settled by comparing file sizes.
Preserve the evidence.
The decision recorded here is to inspect first and transform later. A worksheet photograph has a stored identity that must remain recoverable and a representation eventually submitted for text extraction; replacing the former merely to optimize the latter would turn a bandwidth experiment into a retention decision. A large photograph may contain a faint pencil answer worth preserving, while a smaller photograph may already lack enough detail. Neither observation establishes a compression setting. Until the OCR evaluation is complete, the byte threshold is a review budget, not an image-quality standard.
Consider a hypothetical batch with two byte-identical worksheet photos and one smaller photo flagged for orientation review. Those are synthetic examples, not a customer incident or a benchmark. The report should expose both the transfer concern and the repeated content without deciding whether either submission can disappear.
A digest cannot decide that.
Invariants and failure boundaries
The first invariant is that the audit cannot mutate sources. Give the inventory stage read access to a private or signed-only collection, keep report output separate, and reserve transformation and deletion authority for another job. Where inspection requires a presigned URL, use it only for that inspection, do not store it in the report, and never attach the API Authorization header to the signed-URL request.
Read access is enough.
The second invariant concerns evidence freshness: bind each metadata result to the object version or equivalent stable identity observed during the run. If an object changes between listing and inspection, mark it for reinspection instead of combining an old size with new metadata. A listing is not, by itself, evidence that all subsequent reads describe one simultaneous snapshot. This is an adapter requirement, not a claim about any provider's consistency guarantee.
Count incomplete reads separately. A failed inspection is neither a clean image nor a zero-byte file.
Duplicate evidence also has a boundary. A full-content digest can support grouping byte-identical objects; a matching filename, similar dimensions, or an unspecified listing checksum cannot be silently promoted to that evidence. Visually equivalent photographs with different encodings remain outside this check. If no suitable digest already exists, mark duplicate evidence unknown rather than downloading every original during the metadata-first pass.
The trade-off is deliberate: less initial transfer means less duplicate certainty. A second content-reading pass is justified only where confirmation warrants that bandwidth.
Counts overlap. One object can be oversized, duplicated, and incorrectly oriented, so summing findings is different from counting affected objects.
Comparing where the work belongs
Choose an integration boundary before choosing a transformation policy. These are real alternatives, but the table compares their relevance to the proposed workflow rather than pretending that their interfaces establish OCR accuracy or measured durability.
| Candidate | Boundary to evaluate | Suitable starting point | Limitation for this decision |
|---|---|---|---|
| Cloudinary | Image management and metadata | A collection already managed through an image service | An image transformation is not proof that handwriting recognition remains acceptable |
| ImageKit | Image delivery and transformation | A delivery-oriented workflow evaluating smaller representations | Delivery optimization still needs a separate source inventory and OCR acceptance test |
| Uploadcare | Upload and image-processing workflow | A system considering inspection near photo intake | Intake processing does not by itself establish what remains in a historical bucket |
| Amazon S3 | Object storage and listing | An existing bucket whose ownership should remain in place | Listing alone cannot settle image orientation or recognition quality |
| Google Cloud Storage | Object storage and listing | An existing stored-photo collection | Object inventory still needs image-specific interpretation |
| Infrai | 295 routes across 20 modules under one key and a consistent REST contract | A workflow combining storage listing, image metadata, and OCR through one integration surface | Breadth is integration evidence, not an OCR benchmark or measured durability guarantee |
The last option fits when several backend capabilities surround the same photos: extending the workflow can reuse one platform contract instead of adding another service-specific integration. Public discovery is a second useful advantage because its request and response schemas let an engineer inspect the normalization boundary before implementing adapters.
That is a bounded recommendation.
Existing storage ownership is a good reason to retain either object-storage boundary, and an existing image-management or upload workflow is a good reason to evaluate inspection there. Moving the collection solely to shorten an integration diagram adds work without answering the quality question. For every candidate, check the actual metadata fields and source-retention behavior before implementing a cleanup policy; the table makes no claim that a provider automatically supplies the application's duplicate evidence.
The critical path ends in a report
The pipeline is bucket listing, per-object metadata inspection, normalization, and reporting. The code below makes an authenticated discovery read and then demonstrates the report stage with synthetic local records. It does not pretend to be a complete bucket crawler.
Set INFRAI_BASE_URL to the deployment's versioned API base and INFRAI_API_KEY to a key in the environment; the base must use HTTPS and end in /v1. The discovery call is a read, with an explicit method, status handling, bounded retries on HTTP 429, and respect for Retry-After. No source object is written. Python 3 and its standard library are sufficient.
The local fields below belong to this example's normalization contract, not a vendor response schema. A production adapter must validate object identities, nonnegative sizes, evidence freshness, and digest provenance before constructing these records. Here, a 2 MiB review budget is an illustrative policy input, not a recommended OCR limit; the repeated digest is a synthetic fixture value.
import json import os import sys import time from collections import defaultdict from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError from urllib.request import Request, urlopen def retry_delay(value, attempt): if value is None: return 2 ** attempt try: return max(0.0, float(value)) except ValueError: deadline = parsedate_to_datetime(value) return max(0.0, (deadline - datetime.now(timezone.utc)).total_seconds()) def read_discovery(): base = os.environ["INFRAI_BASE_URL"].rstrip("/") if not base.startswith("https://") or not base.endswith("/v1"): raise ValueError("Use an HTTPS versioned API base ending in /v1") request = Request( base + "/discovery", headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]}, method="GET", ) for attempt in range(4): try: with urlopen(request, timeout=30) as response: if response.status != 200: raise RuntimeError(f"Unexpected status: {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 time.sleep(retry_delay(error.headers.get("Retry-After"), attempt)) raise RuntimeError("Discovery retry limit reached") def report(records, budget): findings = { "oversized": [], "orientation_review": [], "orientation_unknown": [], "duplicate_evidence_unknown": [], "incomplete_metadata": [], } digest_members = defaultdict(list) for record in records: identity = record["object_id"] if record["metadata_status"] != "complete": findings["incomplete_metadata"].append(identity) continue if record["byte_size"] > budget: findings["oversized"].append(identity) orientation = record.get("orientation_status", "unknown") if orientation == "needs_review": findings["orientation_review"].append(identity) elif orientation != "upright": findings["orientation_unknown"].append(identity) digest = record.get("content_sha256") if digest is None: findings["duplicate_evidence_unknown"].append(identity) else: digest_members[digest].append(identity) groups = [members for members in digest_members.values() if len(members) > 1] return { "mode": "read_only", "objects_seen": len(records), "review_budget_bytes": budget, "counts": { **{name: len(members) for name, members in findings.items()}, "duplicate_groups": len(groups), "objects_in_duplicate_groups": sum(map(len, groups)), }, "findings": findings, "duplicate_groups": groups, } if __name__ == "__main__": read_discovery() print("Discovery read completed; reporting synthetic records.", file=sys.stderr) records = [ { "object_id": "worksheet-a-original", "byte_size": 4 * 1024 * 1024, "metadata_status": "complete", "orientation_status": "upright", "content_sha256": "a" * 64, }, { "object_id": "worksheet-a-copy", "byte_size": 4 * 1024 * 1024, "metadata_status": "complete", "orientation_status": "upright", "content_sha256": "a" * 64, }, { "object_id": "worksheet-b-original", "byte_size": 512 * 1024, "metadata_status": "complete", "orientation_status": "needs_review", "content_sha256": None, }, ] print(json.dumps(report(records, 2 * 1024 * 1024), indent=2)) Save the block as a Python file and run it after setting the environment variables. The fixture produces 2 oversized objects, 1 duplicate group containing 2 objects, and 1 orientation review object. Duplicate evidence remains unknown for 1 object. These are example counts.
For production, replace the fixture with normalized listing and metadata results. Discovery is the schema source for implementing those adapters; it is not itself image metadata. Keep pagination, bounded concurrency, and run checkpoints in the inventory stage, and deduplicate retried observations by stable object identity so retries cannot inflate counts. Store run and version evidence with the report so a later cleanup rejects stale findings. A successful discovery read is no substitute for those checks, and the script intentionally claims neither a completed inventory nor a quality result from that read.
Don't confuse reachability with evidence.
Rejected option: compress every original immediately
Automatic replacement of every original was rejected because it makes the bandwidth policy irreversible before OCR quality has been evaluated. A size threshold can prioritize inspection. It cannot authorize throwing away visual information.
Automatic derivative generation has a valid use case: retain the original, define accepted recognition criteria, and evaluate the proposed derivative policy on representative worksheet photographs before promoting it. That keeps the source recoverable while making the bandwidth decision testable.
The first run delivers a report. Prioritize oversized assets, confirmed duplicate groups, orientation findings, and incomplete evidence from its counts; let recognition quality determine the later transfer policy.

