OCR
doc2mark.ocr: the OCR facade, its configuration and result types, the
provider registry and the three providers. Guide: OCR.
The facade
- class doc2mark.OCR(provider='openai', *, api_key=None, **config_kwargs)[source]
The single user-facing entry point for structured OCR.
Wraps an OCR provider behind an ergonomic facade:
from doc2mark.ocr import OCR ocr = OCR("openai") # creds from env results = ocr.read(images) # List[bytes] -> List[OCRResult] results[0].text # rendered markdown (back-compat) results[0].document.raw.text # structured verbatim transcription results[0].document.interpretation # structured analysis (may be None)
Ergonomic kwargs are coerced:
OCR("openai", task="receipt")maps the string toTask.RECEIPT, and an unknowntask/detailraises a clearValueError.Keyword arguments that are
OCRConfigfields build the config; the provider’s own arguments go to the provider:OCR("vertex_ai", project="my-gcp-project", location="europe-west4"),timeoutandmax_retries(the request timeout and retries, not the deprecated config fields),max_workers,prompt_template,default_prompt,top_p,frequency_penalty,presence_penalty. Anything else raisesTypeError.- Parameters:
provider (str | OCRProvider)
api_key (str | None)
Configuration
- class doc2mark.OCRConfig(model=None, task=Task.AUTO, language=None, temperature=None, max_tokens=None, base_url=None, max_concurrency=None, structured=True, detail='full', response_model=None, on_parse_error='raw_text', context_pages=0, enhance_image=True, detect_tables=True, detect_layout=True, max_retries=3, timeout=30, extra=None, non_content_judge=None)[source]
Configuration for OCR processing.
The live knobs for LLM providers are
model,task,language,max_concurrency, and the structured-output controls (structured/detail/response_model/on_parse_error). The remaining fields are either Tesseract-only (enhance_image,detect_layout) or deprecated no-ops kept for backward compatibility (see_DEPRECATED_LLM_FIELDS).- Parameters:
model (str | None)
task (Task)
language (str | None)
temperature (float | None)
max_tokens (int | None)
base_url (str | None)
max_concurrency (int | None)
structured (bool)
detail (Literal['raw', 'full'])
response_model (Type[BaseModel] | None)
on_parse_error (Literal['raw_text', 'raise'])
context_pages (int)
enhance_image (bool)
detect_tables (bool)
detect_layout (bool)
max_retries (int)
timeout (int)
extra (Dict[str, Any] | None)
non_content_judge (Callable[[str], float | None] | None)
Field |
Default |
Used by |
|---|---|---|
|
|
OpenAI ( |
|
|
OpenAI, Vertex AI (structured prompt). |
|
|
OpenAI, Vertex AI: language of the answer. Tesseract: recognition language (Tesseract languages). |
|
|
OpenAI, Vertex AI (defaults 0 and 8192), unless the provider’s own argument is given. |
|
|
OpenAI (else |
|
|
OpenAI, Vertex AI (else the provider’s |
|
|
OpenAI, Vertex AI: |
|
|
|
|
|
A pydantic model to parse into instead of |
|
|
|
|
|
PDF neighbour-page context: 1 for page renders, 2 also for pictures (Contextual OCR strategy). |
|
|
OpenAI, Vertex AI: screens answers the refusal patterns keep (OCR). |
|
|
Tesseract only (grey-scale threshold; page segmentation mode). Deprecated for the LLM providers. |
|
|
Nothing; deprecated (a non-default value makes the OpenAI and Vertex AI providers emit a
|
Results and enums
- class doc2mark.ocr.OCRResult(text, confidence=None, language=None, metadata=None, document=None)[source]
Result from OCR processing.
textis always populated (rendered fromdocument.rawwhen structured output is used) for backward compatibility.documentcarries the structuredOCRPagewhen available – or, withOCRConfig.response_modelset, the answer parsed into that model (textis then its fields as JSON) – orNonefor legacy/free-form results.text(Markdown,""for a refusal or a failure),confidence,language,metadata(LLM providers:model,token_usage, flags such asfailedandocr_refusal; Tesseract: engine details andfailed) anddocument(anOCRPage, the parsed object of yourresponse_model, orNonefor free-form answers and failed Tesseract images).- Parameters:
text (str)
confidence (float | None)
language (str | None)
metadata (Dict[str, Any] | None)
document (OCRPage | BaseModel | None)
- class doc2mark.Task(*values)[source]
OCR intent. Replaces the free-form
PromptTemplatevariants with a small set of intent names that select a schema-aligned instruction (seeTASK_PROMPTS).languageis a config field, not a task, so the oldMULTILINGUALtemplate is dropped.- AUTO = 'auto'
- CODE = 'code'
- DOCUMENT = 'document'
- FORM = 'form'
- HANDWRITING = 'handwriting'
- RECEIPT = 'receipt'
- TABLE = 'table'
Providers
OCRFactory maps a provider name (case-insensitive) to a BaseOCR
subclass; "gemini" is an alias of "vertex_ai". Subclass BaseOCR (implement
batch_process_images) and register it to add a provider.
from doc2mark import OCRConfig, OCRFactory
print(sorted(OCRFactory.list_providers())) # ['gemini', 'openai', 'tesseract', 'vertex_ai']
tesseract = OCRFactory.create("tesseract", config=OCRConfig(language="english"))
results = tesseract.batch_process_images([open("receipt.png", "rb").read()])
print(results[0].text)
- class doc2mark.OCRFactory[source]
Factory for creating OCR providers.
- classmethod create(provider, api_key=None, config=None, **provider_kwargs)[source]
Create an OCR provider instance.
- Parameters:
provider (OCRProvider | str) – Provider type or string name
api_key (str | None) – API key for the provider
config (OCRConfig | None) – OCR configuration
**provider_kwargs (Any) – Arguments of the provider class itself (for example
projectandlocationof the Vertex AI provider,timeoutof the OpenAI one)
- Returns:
OCR provider instance
- Raises:
ValueError – If provider is not registered
- Return type:
- classmethod list_providers()[source]
List available OCR providers.
- Returns:
List of provider names
- Return type:
List[str]
- classmethod register_provider(provider, provider_class)[source]
Register an OCR provider.
- Parameters:
provider (OCRProvider) – Provider enum value
provider_class (type) – Provider class type
- class doc2mark.ocr.BaseOCR(api_key=None, config=None)[source]
Abstract base class for OCR providers.
- Parameters:
api_key (str | None)
config (OCRConfig | None)
- abstractmethod batch_process_images(images, **kwargs)[source]
Process multiple images in batch using LangChain.
This is the primary method for OCR processing. All implementations must use LangChain for efficient batch processing.
- Parameters:
images (List[bytes]) – List of image data as bytes
**kwargs – Additional provider-specific options
- Returns:
List of OCRResult objects in the same order as input
- Return type:
List[OCRResult]
- class doc2mark.ocr.openai.OpenAIOCR(api_key=None, config=None, model=<object object>, temperature=<object object>, max_tokens=<object object>, max_workers=None, default_prompt=None, prompt_template=None, timeout=30, max_retries=3, base_url=<object object>, top_p=None, frequency_penalty=None, presence_penalty=None, **kwargs)[source]
OpenAI GPT-4V based OCR implementation with comprehensive configuration options.
- Parameters:
api_key (str | None)
config (OCRConfig | None)
model (Any)
temperature (Any)
max_tokens (Any)
max_workers (int | None)
default_prompt (str | None)
prompt_template (str | PromptTemplate | None)
timeout (int)
max_retries (int)
base_url (Any)
top_p (float | None)
frequency_penalty (float | None)
presence_penalty (float | None)
- class doc2mark.ocr.vertex_ai.VertexAIOCR(api_key=None, config=None, project=None, location='global', model=<object object>, temperature=<object object>, max_tokens=<object object>, default_prompt=None, prompt_template=None, timeout=30, max_retries=3, max_workers=None, top_p=None, frequency_penalty=None, presence_penalty=None, **kwargs)[source]
Google Gemini based OCR implementation via langchain-google-genai.
- Parameters:
api_key (str | None)
config (OCRConfig | None)
project (str | None)
location (str)
model (Any)
temperature (Any)
max_tokens (Any)
default_prompt (str | None)
prompt_template (str | PromptTemplate | None)
timeout (int)
max_retries (int)
max_workers (int | None)
top_p (float | None)
frequency_penalty (float | None)
presence_penalty (float | None)