Inferensys

Prompt

Handwritten Text Detection Prompt for OCR Routing

A practical prompt playbook for detecting handwritten content in document images to route pages to specialized handwriting OCR models versus standard text extraction pipelines.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Determine when page-level handwriting classification is the right routing decision for your document pipeline versus alternative approaches.

This prompt is designed for document intelligence platform teams who need to classify individual document pages or image regions as containing handwritten text, printed text, or a mix of both. The classification output determines whether the page is routed to a specialized handwriting recognition model (such as Amazon Textract's handwriting mode, Google Document AI's handwriting processor, or a fine-tuned TrOCR model) or a standard OCR pipeline optimized for machine-printed text. Standard OCR models trained predominantly on printed fonts degrade sharply on cursive, block capitals, and low-contrast handwriting. Sending handwritten pages through a print-optimized pipeline produces garbled output that silently corrupts downstream extraction. Conversely, routing printed pages through handwriting models wastes compute and can introduce transcription errors where the model overfits to stroke-like features in serif fonts.

This prompt operates as a binary or ternary classifier at the ingress layer of a document processing pipeline. It accepts a page image and returns a content type label, a confidence score, and an optional region map for mixed-content pages. The output feeds directly into a routing dispatcher that selects the appropriate OCR model per page or per region. Use this prompt when your ingestion pipeline handles heterogeneous document types (forms, letters, invoices, notes), when you operate separate OCR models for handwriting and print with different cost or latency profiles, when you need page-level routing decisions before committing to expensive GPU inference, or when you process scanned documents where handwritten annotations, signatures, or margin notes appear alongside printed text.

Do not use this prompt when you have a single unified OCR model that handles both handwriting and print adequately, when your documents are exclusively born-digital PDFs with no handwriting, when you need character-level or word-level handwriting detection rather than page-level classification, or when latency constraints require sub-100ms decisions without a vision model call. For mixed-content pages where handwriting appears in small regions alongside printed text, consider whether region-level classification with bounding box outputs is necessary rather than a single page-level label. If your pipeline already performs layout analysis, you may be able to combine this classification step with existing region detection to avoid redundant model calls.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Handwritten Text Detection Prompt delivers value and where it falls short in production OCR routing pipelines.

01

Good Fit: Mixed-Format Document Ingestion

Use when: Your pipeline ingests documents containing both printed and handwritten content, and you need page-level or region-level routing to specialized handwriting OCR models. Guardrail: Pair this prompt with a confidence threshold; route low-confidence regions to both standard and handwriting OCR, then reconcile outputs.

02

Bad Fit: Real-Time Single-Word Detection

Avoid when: You need to detect individual handwritten words within a line of printed text at sub-second latency. This prompt is designed for page-level or region-level classification, not word-level segmentation. Guardrail: Use a lightweight object detection model for word-level bounding boxes, then classify each region with this prompt if needed.

03

Required Inputs: Image Quality Thresholds

Risk: Low-resolution images, heavy compression artifacts, or poor lighting cause false negatives where handwriting is present but undetectable. Guardrail: Enforce a minimum input resolution (e.g., 200 DPI) and reject or upscale images below threshold before classification. Log image quality metrics alongside classification results for audit.

04

Operational Risk: Cursive and Stylized Handwriting

Risk: Highly stylized cursive, calligraphy, or unusual handwriting styles may be classified as printed text or decorative elements, causing missed routing to handwriting OCR. Guardrail: Include cursive and stylized samples in your eval set. Set a lower confidence threshold for handwriting detection when the document source is known to contain handwritten content (e.g., medical forms, historical documents).

05

Operational Risk: Handwriting Overlapping Printed Text

Risk: Annotations, signatures, or notes written over printed text create ambiguous regions where the model may default to the dominant modality, missing the handwriting entirely. Guardrail: Request region-level classification with bounding boxes rather than a single page-level label. Flag overlapping regions for dual-path processing through both OCR pipelines.

06

Boundary: Synthetic and Font-Based Handwriting

Risk: Handwriting-style fonts, synthetic handwriting generators, and decorative typefaces can trigger false positives, routing born-digital text to expensive handwriting OCR unnecessarily. Guardrail: Add a secondary check for digital document metadata (font embedding, creation software). If the document is born-digital with handwriting fonts, route to standard text extraction and log the override for review.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable system prompt for detecting handwritten content in document images to route pages to the correct OCR pipeline.

This prompt template is designed to be pasted directly into your system prompt or a dedicated classification step in your document intelligence pipeline. It instructs the model to analyze an image of a document page and determine whether it contains handwritten text, printed text, or a mix of both. The output is a structured JSON classification that your application can use to route the page to a standard OCR model, a specialized handwriting recognition model, or a hybrid processing path. The square-bracket placeholders allow you to configure the confidence thresholds, output schema, and routing labels to match your specific infrastructure without rewriting the core instruction.

text
You are a document image classifier for an OCR routing system. Your task is to analyze the provided document page image and determine the presence and type of text content.

## INPUT
[IMAGE]: A single document page image, which may be a scan, a photo, or a born-digital page.

## CLASSIFICATION TASK
Analyze the image and classify the text content into one of the following categories:
- `printed_only`: The page contains only machine-printed or typeset text.
- `handwritten_only`: The page contains only handwritten text.
- `mixed`: The page contains a combination of printed and handwritten text.
- `no_text`: The page contains no detectable text.

## DETAILED INSTRUCTIONS
1. Examine the entire page, including margins, annotations, signatures, and stamps.
2. Distinguish handwriting from decorative or script fonts by looking for irregular character shapes, inconsistent baselines, and variable spacing.
3. If the page is mostly printed but contains a signature or a short handwritten note in the margin, classify it as `mixed`.
4. If the page is a pre-printed form filled out by hand, classify it as `mixed`.
5. If you are uncertain, reflect that in the confidence score rather than guessing.

## OUTPUT_SCHEMA
Return a single JSON object with the following fields:
{
  "classification": "printed_only" | "handwritten_only" | "mixed" | "no_text",
  "confidence": 0.0-1.0,
  "handwriting_percentage": 0-100,
  "rationale": "A brief, one-sentence explanation of the classification decision.",
  "routing_label": "[PRINTED_QUEUE]" | "[HANDWRITING_QUEUE]" | "[HYBRID_QUEUE]" | "[REVIEW_QUEUE]"
}

## ROUTING RULES
- If `classification` is `printed_only` and `confidence` is above [CONFIDENCE_THRESHOLD], set `routing_label` to "[PRINTED_QUEUE]".
- If `classification` is `handwritten_only` and `confidence` is above [CONFIDENCE_THRESHOLD], set `routing_label` to "[HANDWRITING_QUEUE]".
- If `classification` is `mixed`, set `routing_label` to "[HYBRID_QUEUE]".
- If `classification` is `no_text` or `confidence` is below [CONFIDENCE_THRESHOLD], set `routing_label` to "[REVIEW_QUEUE]".

## CONSTRAINTS
- Do not perform OCR or transcribe any text.
- Do not describe the content of the text beyond what is necessary for classification.
- If the image quality is too poor to make a determination, set `confidence` to a low value and route to `[REVIEW_QUEUE]`.

To adapt this template for your environment, replace the bracketed placeholders with your actual queue names and thresholds. Set [CONFIDENCE_THRESHOLD] to a value like 0.85 to start, then tune based on your eval results. Replace [PRINTED_QUEUE], [HANDWRITING_QUEUE], [HYBRID_QUEUE], and [REVIEW_QUEUE] with the actual topic names, queue ARNs, or workflow identifiers your downstream system expects. If your pipeline uses a different routing mechanism, you can replace the routing_label field with a target_model or pipeline_id field. For high-stakes document processing where misclassification could cause data loss, always route mixed and low-confidence pages to a human review step before automated extraction.

IMPLEMENTATION TABLE

Prompt Variables

Replace these placeholders in your implementation. Each variable controls a specific routing behavior or threshold. Validate inputs before sending to the model to prevent silent misclassification.

PlaceholderPurposeExampleValidation Notes

[IMAGE_INPUT]

Base64-encoded image or image URL to analyze for handwritten content

data:image/png;base64,iVBORw0KGgo...

Validate MIME type is image/png, image/jpeg, or image/tiff. Reject inputs larger than 20MB. Null not allowed.

[DOCUMENT_CONTEXT]

Optional metadata about the document source, page number, or expected content type to improve routing accuracy

{"page": 3, "total_pages": 12, "document_type": "medical_form"}

Must be valid JSON if provided. Null allowed for single-image analysis without document context.

[HANDWRITING_CONFIDENCE_THRESHOLD]

Minimum confidence score required to route to handwriting OCR pipeline instead of standard text extraction

0.65

Must be a float between 0.0 and 1.0. Values below 0.5 increase false positives on stylized fonts. Values above 0.9 risk missing light cursive handwriting.

[OUTPUT_SCHEMA]

Expected JSON structure for the classification result including handwriting presence, confidence, and routing decision

{"has_handwriting": true, "confidence": 0.87, "routing_target": "handwriting_ocr", "mixed_content": true}

Schema must include has_handwriting (boolean), confidence (float), routing_target (enum), and mixed_content (boolean). Validate output against schema before routing.

[MIXED_CONTENT_POLICY]

Instruction for handling pages containing both printed and handwritten text

route_to_handwriting_ocr_with_print_fallback

Must be one of: route_to_handwriting_ocr, route_to_standard_ocr, route_to_both_and_merge, or escalate_for_review. Controls pipeline fork behavior.

[LOW_CONTRAST_THRESHOLD]

Confidence floor below which the model should flag the image for human review due to poor legibility

0.4

Must be a float between 0.0 and 1.0. Should be lower than HANDWRITING_CONFIDENCE_THRESHOLD. Triggers escalation rather than forced routing.

[CURSIVE_WEIGHT]

Bias factor for detecting cursive versus print handwriting when both styles may appear

0.7

Must be a float between 0.0 and 1.0. Higher values prioritize cursive detection at the cost of print handwriting recall. Null allowed for default balanced behavior.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the handwritten text detection prompt into a production document processing pipeline with validation, retries, and routing logic.

This prompt is designed as a classification gate before OCR execution. In a production pipeline, the model call should be wrapped in a service that accepts an image or document page, invokes the prompt, parses the structured JSON response, and routes the page to either a handwriting-specific OCR model (e.g., Amazon Textract with handwriting analysis, Google Document AI with handwriting recognition, or a fine-tuned TrOCR model) or a standard printed-text extraction pipeline. The routing decision should be based on the classification field and the handwriting_confidence score, not on raw model logprobs, to keep the decision boundary explicit and auditable.

Implement a validation layer immediately after the model response that checks: (1) the output is valid JSON matching the expected schema, (2) the classification field is one of the allowed enum values (handwritten, printed, mixed), (3) the handwriting_confidence is a float between 0.0 and 1.0, and (4) the regions array, if present, contains valid bounding box coordinates. If validation fails, retry once with a repair prompt that includes the validation error message and the original image. If the retry also fails, route the page to a manual review queue and log the failure with the page ID, model response, and validation errors for debugging. For mixed classifications, extract the region coordinates and crop the page into handwriting and print zones before routing each crop to the appropriate OCR model.

Model choice matters here. Use a vision-capable model (GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro) rather than a text-only model receiving OCR pre-pass output, because the prompt needs to reason about visual features like stroke variation, baseline consistency, and connected characters that OCR engines often strip. Set temperature=0 for deterministic classification. For high-throughput pipelines processing thousands of pages per hour, consider batching multiple page images into a single request with a page-indexed output schema, or deploy a lightweight classifier model (e.g., a fine-tuned ViT or ConvNeXt) for the initial detection and reserve the LLM call for ambiguous cases where the lightweight model's confidence falls below a threshold. Log every classification decision with the page ID, confidence score, model version, and routing outcome to build a dataset for evaluating classification drift over time.

Human review should be triggered when handwriting_confidence falls between 0.4 and 0.6, when the classification is mixed with conflicting region predictions, or when the model explicitly sets requires_review: true. Route these cases to a review queue with the original image, the model's classification, and the confidence score, and allow reviewers to override the routing decision. Track override rates by confidence bucket to calibrate the review threshold. For regulated document workflows (healthcare, legal, finance), require human confirmation on any page classified as handwritten before routing to OCR, because handwriting OCR errors in regulated contexts can propagate downstream into extracted fields, summaries, and decisions. The harness should emit structured logs with trace IDs that connect the classification decision to the downstream OCR output and any human corrections, creating an audit trail from ingestion to extraction.

IMPLEMENTATION TABLE

Expected Output Contract

The model must return a single, parseable JSON object. Use this contract to validate the response in your application layer before routing the document to the OCR pipeline.

Field or ElementType or FormatRequiredValidation Rule

classification

string (enum)

Must be exactly 'handwritten', 'printed', or 'mixed'. Any other value fails schema validation.

handwriting_confidence

number (0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive. If classification is 'printed', this value must be <= 0.2.

handwriting_percentage

number (0-100)

Integer or float representing the estimated percentage of the page containing handwriting. Must be 0 if classification is 'printed'.

detected_scripts

array of strings

If present, each element must be a valid ISO 15924 script code (e.g., 'Latn', 'Arab'). Null or empty array is acceptable.

requires_handwriting_ocr

boolean

Must be true if classification is 'handwritten' or 'mixed'. Must be false if classification is 'printed'.

low_contrast_flag

boolean

If true, indicates the source image has low contrast that may reduce OCR accuracy. Must be accompanied by a confidence value below 0.7.

routing_target

string (enum)

Must be one of: 'standard_ocr_pipeline', 'handwriting_ocr_pipeline', or 'hybrid_ocr_pipeline'. Must align with the classification field.

failure_reason

string or null

If the model cannot classify the page, this field must contain a specific reason (e.g., 'image_too_blurry'). Must be null on successful classification.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when detecting handwritten text for OCR routing, and how to guard against it in production.

01

Printed Text Misclassified as Handwritten

What to watch: Decorative, italic, or serif fonts with ligatures and cursive styling trigger false positives. This is especially common with wedding invitations, certificates, and formal letterheads. Guardrail: Add a negative example set of decorative printed fonts to your eval suite. Implement a secondary check that looks for the uniform stroke width and consistent character repetition typical of machine text.

02

Handwritten Text on Noisy Backgrounds Missed

What to watch: Handwriting on textured, patterned, or low-contrast backgrounds (e.g., sticky notes on wood, whiteboard markers on glass) drops below the detection threshold. The model sees the background as the dominant signal. Guardrail: Preprocess images with adaptive thresholding or background subtraction before classification. Include low-contrast handwriting samples in your eval set and measure recall specifically on SNR < 10dB inputs.

03

Mixed Content Pages Routed Incorrectly

What to watch: A single page containing both printed form fields and handwritten entries (e.g., a filled tax form) gets routed to only one pipeline, losing either the printed structure or the handwritten answers. Guardrail: Require page-level or region-level classification, not document-level. Route mixed pages to a hybrid pipeline that runs both standard and handwriting OCR, then merges results with spatial reconciliation.

04

Confidence Score Calibration Drift

What to watch: The model outputs high confidence scores for incorrect classifications, especially on ambiguous cursive that resembles print. Downstream routing trusts the score and skips fallback review. Guardrail: Calibrate confidence thresholds against a labeled holdout set. Implement a 'disagree' band (e.g., 0.45–0.75) where ambiguous scores force human review or dual-routing to both OCR pipelines. Log calibration drift monthly.

05

Low-Resolution or Compressed Image Degradation

What to watch: Heavy JPEG compression or low DPI scans (under 150 DPI) blur the fine strokes that distinguish handwriting from printed text, causing both false negatives and false positives. Guardrail: Add a pre-check for image resolution and compression artifacts. If DPI is below 200 or compression artifacts are detected, route to a super-resolution preprocessing step or flag for human review before classification.

06

Handwriting in Non-Latin Scripts Overlooked

What to watch: Detection models trained primarily on Latin script handwriting fail on Arabic, Devanagari, CJK, or Cyrillic cursive, routing handwritten pages to standard OCR that produces garbage output. Guardrail: Include script detection as a parallel classification step. If a non-Latin script is detected, route to a script-specific handwriting model or flag for manual review. Maintain a per-script recall metric in your eval dashboard.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks against a labeled golden dataset of at least 200 pages covering your document distribution. The rubric measures recall on cursive, print, and low-contrast handwriting samples while penalizing false positives on printed text and blank pages.

CriterionPass StandardFailure SignalTest Method

Handwriting recall (cursive)

= 0.95 recall on cursive samples

Cursive pages classified as PRINTED or UNCLEAR below threshold

Run against 50 labeled cursive pages; measure recall@[CONFIDENCE_THRESHOLD]

Handwriting recall (print)

= 0.90 recall on hand-printed samples

Hand-printed pages classified as PRINTED below threshold

Run against 50 labeled hand-print pages; measure recall@[CONFIDENCE_THRESHOLD]

Handwriting recall (low-contrast)

= 0.85 recall on low-contrast or faint handwriting

Faint handwriting pages classified as PRINTED or UNCLEAR

Run against 30 labeled low-contrast samples; measure recall@[CONFIDENCE_THRESHOLD]

Printed text precision

= 0.98 precision on born-digital or clean printed pages

Printed pages classified as HANDWRITTEN or MIXED

Run against 50 labeled printed-only pages; measure precision

Mixed page detection

= 0.90 accuracy on pages with both handwriting and printed text

Mixed pages classified as PRINTED-ONLY or HANDWRITTEN-ONLY

Run against 30 labeled mixed pages; measure exact match to MIXED label

Blank page handling

Blank pages classified as PRINTED or NONE with confidence >= 0.95

Blank pages classified as HANDWRITTEN or MIXED

Run against 20 labeled blank pages; check label and confidence floor

Confidence calibration

Mean confidence for correct predictions >= 0.85; mean for incorrect <= 0.60

High-confidence misclassifications or low-confidence correct predictions

Compute mean confidence by correctness bucket across full 200-page dataset

Edge case: stamps and signatures

<= 5% false positive rate on printed pages with stamps or signatures

Printed pages with stamps/signatures classified as HANDWRITTEN

Run against 20 labeled printed pages with stamps/signatures; measure false positive rate

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt\nStart with the base prompt and a small set of labeled images. Remove strict schema requirements initially—accept a simple JSON with `has_handwriting` (boolean) and `confidence` (0-1). Use a frontier model via API.\n\n```\nAnalyze this document image and determine if it contains handwritten text.\nReturn JSON: {\"has_handwriting\": boolean, \"confidence\": float}\n```\n\n### Watch for\n- Cursive handwriting misclassified as printed text\n- Low-contrast or faint pencil marks missed entirely\n- Overconfidence on ambiguous cases (e.g., stylized fonts that mimic handwriting)\n- No handling for mixed pages where only a signature is handwritten

Prasad Kumkar

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.