This directory contains standalone examples demonstrating how to use the LeapOCR Python SDK.
All examples require:
- Python 3.9 or higher
- LeapOCR SDK installed (
pip install leapocroruv add leapocr) LEAPOCR_API_KEYenvironment variable set with your API key
export LEAPOCR_API_KEY="your-api-key-here"Each example is a standalone script that can be run directly:
# Using Python
python examples/basic/process_file.py
# Or using uv
uv run examples/basic/process_file.pyProcess a local PDF file with LeapOCR.
Features demonstrated:
- Creating a LeapOCR client
- Processing local files
- Using
process_file()/process_url()followed bywait_until_done() - Accessing results and metadata
Usage:
# Create a sample PDF in the examples/basic directory
cd examples/basic
# Add your sample-document.pdf here
python process_file.pyProcess a document from a URL with manual status polling.
Features demonstrated:
- Processing documents from URLs
- Manual status polling
- Progress tracking
- Different output formats
Usage:
python examples/basic/process_url.py
# Or with custom URL
TEST_DOCUMENT_URL="https://your-url.com/doc.pdf" python examples/basic/process_url.pyProcess multiple documents concurrently using asyncio.
Features demonstrated:
- Concurrent processing with
asyncio.gather() - Batch job management
- Error tracking across multiple jobs
- Calculating total credits and processing time
Usage:
python examples/advanced/batch_processing.pyExtract structured data using custom schemas.
Features demonstrated:
- Custom schema definition
- Structured data extraction
- JSON schema for invoice processing
- Working with nested data structures
Usage:
python examples/advanced/schema_extraction.py
# Or with custom invoice URL
INVOICE_URL="https://your-url.com/invoice.pdf" python examples/advanced/schema_extraction.pyUse custom configuration and polling options.
Features demonstrated:
- Custom client configuration (timeout, retries, base URL)
- Custom polling options
- Progress callbacks
- API health checks
- Different output formats
Usage:
python examples/advanced/custom_config.py
# With custom base URL
OCR_BASE_URL="https://api-staging.example.com" python examples/advanced/custom_config.pyUse pre-configured templates for document processing.
Features demonstrated:
- Using templates by slug
- Batch processing with templates
- Multiple template types for different document types
- Template-based extraction without defining schemas
Usage:
python examples/advanced/template_usage.pyCompare and use different OCR models including custom models.
Features demonstrated:
- Using predefined models (Standard and Pro)
- Custom organization-specific models
- Model performance comparison
- Credit usage per model
- Concurrent processing with different models
Usage:
python examples/advanced/model_selection.pyAdvanced job management including status tracking and deletion.
Features demonstrated:
- Manual job submission and status polling
- Job status monitoring
- Result retrieval
- Job deletion when no longer needed
- Batch job cleanup
Usage:
python examples/advanced/job_management.pyDemonstrate different error types and handling strategies.
Features demonstrated:
- Authentication errors
- Validation errors
- Job errors
- Error hierarchy and catching
- Error inspection and attributes
- Recovery strategies
Usage:
python examples/error_handling/error_types.pyHandle timeouts and task cancellation.
Features demonstrated:
- Custom timeout configuration
- Task cancellation and cleanup
- Manual polling with timeouts
- Timeout recommendations by document size
Usage:
python examples/error_handling/timeout_handling.pyAll examples use the async context manager pattern for proper resource cleanup:
from leapocr import Format, Model, ProcessOptions
async with LeapOCR(api_key) as client:
job = await client.ocr.process_file(
"document.pdf",
options=ProcessOptions(format=Format.MARKDOWN, model=Model.STANDARD_V2),
)
result = await client.ocr.wait_until_done(job.job_id)Catch SDK-specific errors for better error handling:
from leapocr import APIError, Format, LeapOCRError, Model, ProcessOptions, ValidationError
try:
result = await client.ocr.process_file(
"document.pdf",
options=ProcessOptions(format=Format.MARKDOWN, model=Model.STANDARD_V2),
)
except ValidationError as e:
print(f"Invalid input: {e.message}")
except APIError as e:
print(f"API error: {e.message} (status: {e.status_code})")
except LeapOCRError as e:
print(f"SDK error: {e.message}")Use progress callbacks for long-running operations:
def progress_callback(status):
print(f"Progress: {status.progress:.1f}%")
job = await client.ocr.process_file(
"document.pdf",
options=ProcessOptions(format=Format.MARKDOWN, model=Model.STANDARD_V2),
)
result = await client.ocr.wait_until_done(
job.job_id,
poll_options=PollOptions(
poll_interval=2.0,
on_progress=progress_callback,
),
)| Variable | Description | Default | Required |
|---|---|---|---|
LEAPOCR_API_KEY |
Your LeapOCR API key | None | Yes |
OCR_BASE_URL |
API base URL | https://api.leapocr.com/api/v1 |
No |
TEST_DOCUMENT_URL |
URL for testing | Example URL | No |
INVOICE_URL |
Invoice URL for schema example | Example URL | No |
- Start with basic examples to understand the fundamentals
- Check error messages carefully - they include helpful information
- Use progress callbacks for long-running operations
- Set appropriate timeouts based on document size
- Handle errors gracefully in production code
- Use structured format with schemas for data extraction
- Process in batches for multiple documents
- Monitor credits usage to optimize costs
- Use templates (
template_slug) to reuse extraction configurations - Delete jobs when no longer needed to clean up resources
Set your API key: export LEAPOCR_API_KEY="your-key"
Ensure you're running examples from the correct directory or provide full paths.
Increase PollOptions.max_wait or ClientConfig.timeout for large documents.
Install the SDK: pip install leapocr or uv add leapocr
If you encounter issues or have questions:
- Check the documentation
- Open an issue on GitHub
- Contact support at support@leapocr.com