This prompt is designed for document ingestion engineers and archival teams who need to programmatically assess the quality of scanned PDFs before text extraction. The core job-to-be-done is not just to read text, but to produce a machine-readable damage report: identifying specific regions of a page that are illegible, classifying the type of degradation (such as heavy blur, bleed-through from the reverse side, faint pencil marks, or physical obstructions like staples), and attaching a calibrated confidence score to each region. The ideal user is building an automated pipeline where silent OCR failures are unacceptable, and they need a triage step to route degraded pages for manual review or specialized image preprocessing.
Prompt
Illegible Region Detection Prompt for Scanned PDFs

When to Use This Prompt
Define the job, the ideal user, required inputs, and the boundaries where this prompt should not be applied.
You should use this prompt when you are processing large volumes of scanned archival material, legal discovery documents, or historical records where image quality is inconsistent. It is appropriate when your downstream system requires structured metadata about page quality to make decisions—for example, skipping text extraction on a page flagged as 90% illegible, or flagging a specific clause area for human transcription. The prompt requires a pre-processed input: a high-resolution page image and, optionally, the raw OCR text output for comparison. It is not a general-purpose OCR engine and should not be used as the primary text extraction step. It is a diagnostic layer that sits before extraction.
Do not use this prompt for clean, born-digital PDFs where text is already selectable and rendering artifacts are minimal. It is overkill for documents with uniform, high-contrast text. Avoid using it as a standalone quality gate without human review in high-stakes scenarios, such as single-source financial audits or medical record digitization, where a false negative (marking a region as legible when it is not) could have serious consequences. In those cases, the output should feed a human-in-the-loop review queue, not an automated deletion or acceptance workflow. The prompt also assumes a single page image per call; multi-page logic should be handled by your application's iteration harness.
Use Case Fit
Where the Illegible Region Detection Prompt works, where it fails, and the operational preconditions required before deploying it into a document pipeline.
Good Fit: Degraded Archival Scans
Use when: processing large backlogs of scanned documents with known degradation such as blur, bleed-through, faint text, or speckle noise. Guardrail: Pair with a representative degradation sample set for threshold calibration before production use.
Bad Fit: Clean Digital-Native PDFs
Avoid when: documents are born-digital with selectable text and no image artifacts. Guardrail: Route through a pre-classification step that checks for raster content; skip illegibility detection if the page contains only vector text.
Required Input: Rendered Page Images
Risk: Feeding raw PDF bytes or mixed text-plus-image streams produces inconsistent region coordinates. Guardrail: Always pre-render each page to a high-resolution image (300 DPI minimum) and pass image references, not PDF binaries, to the prompt.
Required Input: Degradation Taxonomy
Risk: Without a defined taxonomy, the model invents degradation categories or lumps distinct issues together. Guardrail: Supply an explicit closed-set taxonomy (blur, bleed-through, faint-text, obstruction, speckle, skew) in the prompt constraints.
Operational Risk: Silent False Negatives
Risk: The model misses illegible regions entirely, especially low-contrast text on textured backgrounds. Guardrail: Run a parallel OCR engine on the same page and compare character-confidence maps; flag pages where the prompt reports no issues but OCR confidence is low.
Operational Risk: Coordinate Drift Across Renderers
Risk: Bounding box coordinates shift when the rendering library or DPI changes, breaking downstream redaction or review UI overlays. Guardrail: Lock the rendering pipeline version and DPI; include a coordinate validation step using known anchor regions on a calibration page.
Copy-Ready Prompt Template
A reusable prompt template for detecting illegible regions in scanned PDF pages, classifying degradation types, and estimating OCR confidence per region.
This prompt template is designed to be dropped into a document processing pipeline that handles scanned PDFs. It expects pre-extracted text and layout metadata from an OCR engine as input, and it returns a structured JSON report of illegible regions. The template uses square-bracket placeholders for all variable inputs, constraints, and output schemas so you can adapt it to your specific OCR engine, document types, and downstream requirements without rewriting the core instruction logic.
textYou are an expert document quality analyzer. Your task is to examine the provided OCR output and page metadata from a scanned PDF page and identify all regions where the text is illegible or likely to be incorrectly transcribed. ## INPUT - OCR Text: [OCR_TEXT] - OCR Confidence Scores (word-level): [OCR_CONFIDENCE_MAP] - Page Layout Data (bounding boxes): [PAGE_LAYOUT] - Page Image Description (optional): [PAGE_IMAGE_DESCRIPTION] ## TASK 1. Identify all regions on the page where the text is likely illegible, unreadable, or incorrectly transcribed. 2. For each identified region, classify the primary degradation type. 3. Estimate a confidence score (0.0 to 1.0) for the OCR output in that region. 4. Provide the bounding box coordinates for each illegible region. 5. If possible, suggest what the illegible text might be based on context, but clearly mark this as a guess. ## DEGRADATION TYPES Classify each region into one of the following types: - `blur`: Out-of-focus or motion-blurred text - `bleed_through`: Text from the reverse side of the page showing through - `faint_text`: Low-contrast or faded text - `obstruction`: Text covered by a stain, stamp, mark, or physical object - `skew_warp`: Text distorted by page skew or warping - `font_degradation`: Broken, compressed, or stylized fonts that OCR cannot parse - `background_noise`: Text obscured by background patterns or artifacts - `handwriting`: Cursive or handwritten text that printed OCR cannot reliably transcribe - `other`: Any other degradation not listed above (describe briefly) ## OUTPUT SCHEMA Return a JSON object conforming to this exact schema: { "page_number": [PAGE_NUMBER], "overall_page_quality": "high" | "medium" | "low" | "unusable", "illegible_regions": [ { "region_id": "string", "bounding_box": { "x": number, "y": number, "width": number, "height": number, "unit": "pixel" | "point" | "inch" }, "degradation_type": "blur" | "bleed_through" | "faint_text" | "obstruction" | "skew_warp" | "font_degradation" | "background_noise" | "handwriting" | "other", "degradation_description": "string (brief description of the degradation)", "ocr_confidence_estimate": number (0.0 to 1.0), "affected_text_guess": "string or null (your best guess at the text, or null if impossible)", "recommended_action": "re_scan" | "manual_review" | "alternate_ocr_engine" | "image_preprocessing" | "ignore" } ], "processing_notes": "string (any additional observations about the page quality)" } ## CONSTRAINTS - Only report regions that are genuinely illegible. Do not flag regions with minor noise that a human could easily read. - If the entire page is clean and legible, return an empty `illegible_regions` array and set `overall_page_quality` to "high". - If you cannot determine the degradation type with confidence, use "other" and describe what you observe. - Do not invent text guesses. If you cannot make a reasonable guess based on context, set `affected_text_guess` to null. - Bounding box coordinates must correspond to the coordinate system specified in [PAGE_LAYOUT]. ## EXAMPLES [EXAMPLES] ## RISK LEVEL [RISK_LEVEL]
To adapt this template, replace each square-bracket placeholder with your pipeline's actual data and configuration. The [OCR_TEXT] and [OCR_CONFIDENCE_MAP] placeholders should receive output directly from your OCR engine (such as Tesseract, Azure Form Recognizer, or Amazon Textract). The [PAGE_LAYOUT] placeholder expects structured bounding box data—pass it in the coordinate system your downstream system uses. The [EXAMPLES] placeholder is critical for few-shot performance; include at least two annotated examples showing both a degraded page and a clean page. Set [RISK_LEVEL] to guide the model's caution: use "low" for archival digitization where false positives are acceptable, "high" for legal or medical documents where missed illegible regions could cause harm, and "medium" for most enterprise workflows. For high-risk use cases, always route flagged regions to human review before the extracted text enters any downstream system.
Prompt Variables
Required inputs for the Illegible Region Detection Prompt. Each variable must be populated before the prompt is assembled and sent. Validation notes describe how to check the input at runtime before incurring model cost.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[PAGE_IMAGE_BASE64] | Base64-encoded PNG or JPEG of a single scanned page to analyze for illegible regions. | iVBORw0KGgoAAAANSUhEUgAA... (truncated) | Validate string is non-empty, starts with valid Base64 charset, and decodes to an image under 20 MB. Reject if MIME type is not image/png or image/jpeg. |
[OCR_TEXT_LAYER] | Raw OCR text output for the page, including character bounding boxes if available. Used to correlate OCR confidence with visual regions. | {"text": "The quick brown fox...", "words": [{"text": "The", "bbox": [10,20,30,40]}, ...]} | Validate JSON parse succeeds. Check that words array exists and each word has text and bbox fields. Allow empty string for image-only pages with no OCR layer. |
[OCR_CONFIDENCE_THRESHOLD] | Minimum character or word confidence score below which a region is considered potentially illegible. Float between 0.0 and 1.0. | 0.65 | Validate is a float between 0.0 and 1.0 inclusive. Default to 0.7 if not provided. Log warning if threshold is below 0.5 or above 0.95. |
[DEGRADATION_CLASSES] | List of degradation types the prompt should classify. Controls the granularity of the degradation_type field in the output. | ["blur", "bleed_through", "faint_text", "obstruction", "speckle_noise", "skew_warp"] | Validate is a non-empty array of strings. Each string must match one of the known degradation class labels. Reject unknown labels to prevent model hallucination on unsupported types. |
[MIN_REGION_AREA_PX] | Minimum bounding box area in square pixels for a region to be reported. Filters out noise-level artifacts. | 500 | Validate is a positive integer. Default to 200 if not provided. Regions smaller than this are excluded from output to reduce noise. |
[OUTPUT_SCHEMA] | JSON schema describing the expected output structure for each detected illegible region. Injected into the prompt as a format constraint. | {"type": "object", "properties": {"regions": {"type": "array", "items": {"type": "object", "properties": {"bbox": {"type": "array", "items": {"type": "number"}}, "degradation_type": {"type": "string"}, "confidence_estimate": {"type": "number"}, "affected_text": {"type": "string"}}}}}} | Validate JSON parse succeeds and schema is a valid JSON Schema draft. Check that required output fields (bbox, degradation_type, confidence_estimate) are present in properties. Reject if schema is empty or malformed. |
[PAGE_NUMBER] | Page number of the document for traceability in multi-page processing. Included in output metadata. | 42 | Validate is a positive integer or null. If null, output metadata omits page_number. Log warning if page_number is 0 or negative. |
Implementation Harness Notes
How to wire the illegible region detection prompt into a production document ingestion pipeline with validation, retries, and human review gates.
The illegible region detection prompt is designed to operate as a post-OCR quality gate within a document ingestion pipeline. After a scanned PDF passes through an OCR engine, each page image and its corresponding OCR text output are sent to the model. The prompt returns a structured JSON payload identifying regions where the OCR confidence is low, classifying the degradation type (blur, bleed-through, faint text, obstruction), and providing bounding box coordinates for each illegible zone. This output should be consumed by a downstream routing decision: pages with no flagged regions proceed to extraction; pages with flagged regions above a configurable threshold are routed to a human review queue or a higher-resolution re-scan workflow.
Wire the prompt into your application as a stateless function that accepts a page image (base64-encoded) and the raw OCR text for that page. The function should enforce a strict output schema using a JSON validator before the result is accepted. If the model returns malformed JSON, missing required fields (regions, page_confidence), or coordinates outside the page dimensions, the application should retry once with a repair prompt that includes the validation error message. After two consecutive failures, escalate the page to human review and log the failure for prompt debugging. For model choice, use a vision-capable model (GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro) since the task requires comparing the rendered page image against the OCR text. Set temperature=0 to minimize coordinate drift and classification inconsistency across runs.
Build an evaluation harness before deploying to production. Create a golden dataset of 50–100 scanned pages with known degradation types and manually annotated illegible region bounding boxes. For each page, run the prompt and compare the model's output against ground truth using Intersection over Union (IoU) for region localization and exact-match accuracy for degradation type classification. Set acceptance thresholds: IoU ≥ 0.7 for region detection and ≥ 85% accuracy for degradation classification. Run this eval suite on every prompt change and on a weekly cadence against production samples to detect model behavior drift. Log every model response, including confidence scores and region counts, to monitor for sudden spikes in flagged regions that may indicate upstream scanner issues rather than prompt failures.
The highest-risk failure mode in production is a false negative—an illegible region that the model misses entirely. A missed illegible region propagates garbled text into downstream extraction, where it may produce silently corrupted structured data. Mitigate this by implementing a second-pass check: after extraction runs on pages that passed the illegibility gate, run a low-confidence extraction flagging prompt on the extracted fields. If the extraction prompt flags fields with low confidence that correspond to regions the illegibility prompt marked as clean, log the discrepancy and route the page for human review. This dual-gate pattern catches both detection failures and extraction failures before data enters your system of record. Do not rely on the illegibility prompt alone for high-stakes document processing; it is a filter, not a guarantee.
Expected Output Contract
The JSON output contract for the Illegible Region Detection Prompt. Every field must be validated before downstream ingestion. Missing or malformed fields should trigger a retry or fallback, not a silent pass.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
regions | Array of objects | Must be a non-null array. If no illegible regions are found, return an empty array, not null or a string. | |
regions[].id | String | Must be a unique, non-empty string within the array. Recommended format: region-{page}-{index}. | |
regions[].page_number | Integer | Must be a positive integer. Must not exceed the total page count of the source document. | |
regions[].bounding_box | Object | Must contain x, y, width, height keys. All values must be positive numbers. Coordinates should be normalized (0.0-1.0) if [COORDINATE_SYSTEM] is 'normalized', else in points. | |
regions[].degradation_type | String (enum) | Must be one of: 'blur', 'bleed_through', 'faint_text', 'obstruction', 'skew', 'noise', 'handwriting', 'other'. Reject any value not in this enum. | |
regions[].ocr_confidence | Number | Must be a float between 0.0 and 1.0 inclusive. Represents the mean character-level confidence for the region. Null is not allowed; use 0.0 for completely illegible. | |
regions[].transcription_attempt | String or null | The OCR engine's best-effort text for the region. Must be null if ocr_confidence is below [MIN_CONFIDENCE_THRESHOLD]. If not null, must be a non-empty string. | |
regions[].adjacent_legible_context | String or null | If present, must be a non-empty string containing the 50 characters before and after the region. Null is allowed if no adjacent text exists. |
Common Failure Modes
Illegible region detection fails silently in predictable ways. These are the most common failure modes when deploying the prompt against real-world degraded scans, along with practical mitigations.
False Negatives on Faint Text
What to watch: The model misses faint but still-readable text, classifying it as illegible or skipping it entirely. This happens most often with low-contrast gray text on white backgrounds or thin serif fonts in older documents. Guardrail: Include a minimum contrast threshold in the prompt and require the model to report confidence scores per region. Test against a golden set of known faint-text samples with ground-truth transcriptions.
Bleed-Through Misclassified as Content
What to watch: Text bleeding through from the reverse side of a scanned page is incorrectly treated as foreground content, producing ghost characters in the extraction output. This is common with thin paper stock and double-sided scans. Guardrail: Add explicit instructions to identify and flag bleed-through patterns (reversed orientation, lower contrast, overlapping with foreground text). Include a dedicated degradation_type field with bleed_through as a distinct class.
Obstruction Boundary Overreach
What to watch: When a stain, stamp, or sticker partially obscures text, the model marks an overly large region as illegible, discarding readable characters adjacent to the obstruction. Guardrail: Require pixel-precise bounding boxes for illegible regions and instruct the model to distinguish between fully occluded characters and partially visible ones. Validate boundary precision against manually annotated obstruction samples.
Handwriting Confused with Degradation
What to watch: Handwritten annotations, signatures, or marginalia are incorrectly flagged as degradation artifacts rather than intentional content. This is especially problematic for archival documents where handwriting is part of the record. Guardrail: Add a separate classification for handwriting versus print degradation. Include few-shot examples showing handwritten text that should be marked as legible but noted as handwriting in the output schema.
Confidence Score Inflation
What to watch: The model reports high OCR confidence for regions that are actually ambiguous or degraded, often because it defaults to a likely word rather than acknowledging uncertainty. This produces clean-looking output with hidden errors. Guardrail: Calibrate confidence scores against a benchmark where you know the ground-truth error rate per confidence band. Add a prompt instruction to lower confidence when multiple character hypotheses are plausible. Log confidence distributions in production to detect drift.
Multi-Column Layout Misattribution
What to watch: In multi-column scanned documents, degradation in one column causes the model to merge text across column boundaries or skip the degraded column entirely while misattributing surrounding content. Guardrail: Combine illegible region detection with layout-aware extraction. Require the model to preserve column boundaries in its output and flag when degradation crosses column separators. Test against multi-column newspaper and journal scans with known degradation zones.
Evaluation Rubric
Use this rubric to test the Illegible Region Detection Prompt against known degradation samples before shipping. Each criterion targets a specific failure mode observed in production document pipelines.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Region Recall | All illegible regions in the ground-truth sample set are detected with bounding box overlap >= 0.8 IoU | Missed regions with no bounding box output or IoU < 0.5 on known degraded areas | Run prompt against 20 annotated scan samples with known degradation regions; compute per-region IoU against ground truth |
Degradation Classification Accuracy | Degradation type matches ground truth for >= 90% of detected regions across blur, bleed-through, faint text, and obstruction categories | Frequent misclassification of bleed-through as faint text or obstruction as blur; confusion matrix shows > 20% error on any single class | Run prompt against balanced degradation-type test set with 15 samples per type; compute per-class precision and recall |
False Positive Rate on Clean Regions | <= 5% of clean text regions incorrectly flagged as illegible | Clean, high-contrast text regions marked as illegible with confidence > 0.6; false positive rate exceeds 10% | Include 10 clean-scan pages in test set; count flagged regions outside ground-truth degradation areas |
OCR Confidence Score Calibration | Per-region confidence scores correlate with ground-truth character error rate (CER) with Spearman rank correlation >= 0.7 | High confidence scores (> 0.8) assigned to regions with ground-truth CER > 20%; low confidence scores (< 0.3) assigned to regions with CER < 5% | Compute CER from ground-truth transcriptions for each detected region; calculate Spearman correlation between confidence and CER |
Bounding Box Precision | Output bounding boxes are valid JSON arrays with exactly 4 numeric coordinates and fall within page dimensions | Bounding boxes with negative coordinates, coordinates exceeding page dimensions, non-numeric values, or array length != 4 | Validate all output bounding boxes against page dimension metadata; check JSON schema compliance with automated validator |
Multi-Page Consistency | Regions spanning page breaks are detected on both pages with consistent degradation type and confidence scores within 0.15 of each other | Region detected on one page but missed on adjacent page; degradation type differs across page boundary for same region | Include 5 multi-page degradation samples in test set; verify region continuity and type consistency across page boundaries |
Output Schema Compliance | 100% of responses parse as valid JSON matching the expected output schema with all required fields present | JSON parse failures; missing required fields such as region_id, bounding_box, degradation_type, or confidence_score | Run automated schema validation on all test outputs; reject any response that fails JSON.parse or schema check |
Edge Case: Mixed Degradation | Regions with multiple degradation types are flagged with primary type and secondary type noted when confidence split is within 0.2 | Single degradation type assigned when region exhibits clear characteristics of two types; no secondary type or note field populated | Include 8 samples with mixed degradation (e.g., blur + bleed-through); verify primary and secondary type fields are populated correctly |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a small set of known degradation samples. Use a frontier model (GPT-4o or Claude 3.5 Sonnet) with vision capabilities. Send page images directly without pre-processing OCR output. Keep the output schema simple: region_id, bbox, degradation_type, confidence.
codeAnalyze this scanned page image and identify all illegible regions. For each region, return: - region_id: unique identifier - bbox: [x1, y1, x2, y2] in pixel coordinates - degradation_type: one of ["blur", "bleed_through", "faint_text", "obstruction", "noise", "other"] - confidence: 0.0 to 1.0 estimate of OCR readability Page image: [PAGE_IMAGE]
Watch for
- Models hallucinating regions on clean pages
- Inconsistent bbox coordinate systems across pages
- Overly broad region boundaries that cover entire paragraphs
- Missing subtle degradation like faint text on light backgrounds

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us