Zerox OCR Engine

repository·main·Indexed 11 days ago

https://github.com/getomni-ai/zerox

An OCR engine designed for AI ingestion that converts documents (PDFs, images, DOCX, and others) into Markdown using vision models. It supports standard OCR, structured data extraction via JSON Schema, and hybrid extraction. Available as Node.js and Python SDKs, Zerox integrates with providers including OpenAI, Azure OpenAI, AWS Bedrock, and Google Gemini.

Tokens
7.7K
Snippets
12
Records
28
Agent score
91%

What's inside Zerox

  1. What is Focused ReAct and how does it improve reasoning?

    main

    Focused ReAct is an enhanced version of the ReAct (Reason+Act) paradigm designed to improve performance in Question Answering (QA) tasks. It addresses two primary failure modes of the standard ReAct framework:

    1. Context Loss: In long reasoning chains, the model often loses track of the original user query as the context window fills with reasoning steps and observations.
    2. Action Loops: The model can become stuck in repetitive cycles, performing the same action multiple times without progressing toward a solution.

    Focused ReAct introduces two mechanisms to mitigate these issues: Reiterate and Early Stop.

  2. How the Reiterate mechanism solves context loss

    main

    The Reiterate mechanism prevents the original question from being overshadowed by an increasingly long reasoning context.

    Implementation: The original question is restated at the beginning of every reasoning step within the ReAct cycle. This constant re-emphasis ensures the model's outputs remain aligned with the user's initial intent, even as the conversation history grows.

  3. Configure model providers for Python Zerox

    main

    Zerox uses LiteLLM to support various vision model providers. You must configure the appropriate environment variables based on your provider.

    Common configurations include:

    • OpenAI: Set OPENAI_API_KEY and use model names like gpt-4o-mini.
    • Azure OpenAI: Set AZURE_API_KEY, AZURE_API_BASE, and AZURE_API_VERSION. Use the format azure/<your_deployment_name>.
    • Gemini: Set GEMINI_API_KEY and use the format gemini/<gemini_model>.
    • Anthropic: Set ANTHROPIC_API_KEY.
    • Vertex AI: Use vertex_ai/<model_name>. You can provide credentials via gcloud auth application-default login or by passing a JSON string of your service account credentials via the vertex_credentials keyword argument in kwargs.
  4. How `maintainFormat` works

    main

    The maintainFormat: true option is useful for documents with complex layouts or tables that span multiple pages. It ensures consistent formatting by passing the Markdown output of the previous page as context for the current page's request.

    Note: This requires requests to run synchronously, making it significantly slower than the default concurrent processing.

    Workflow:

    1. Request #1 $\rightarrow$ page_1_image
    2. Request #2 $\rightarrow$ page_1_markdown + page_2_image
    3. Request #3 $\rightarrow$ page_2_markdown + page_3_image
  5. How the Early Stop mechanism prevents action repetition

    main

    The Early Stop mechanism prevents the model from getting trapped in repetitive action loops.

    Implementation: The system monitors for duplicate actions. When the program detects that an action is being repeated, it triggers a termination request. This instructs the model to stop performing new actions and instead generate a final answer based on the information already gathered in the context.

  6. Install Node Zerox

    main

    Install the Zerox Node.js SDK via npm:

    npm install zerox

    System Dependencies: Zerox requires graphicsmagick and ghostscript for converting PDFs to images. While these may be pulled automatically, you may need to install them manually. On Linux, use:

    sudo apt-get update
    sudo apt-get install -y graphicsmagick
  7. Perform structured data extraction with Zerox

    main

    Zerox can extract specific information from documents into a structured format using JSON Schema.

    To use this feature:

    1. Set extractOnly: true.
    2. Provide a schema following the JSON Schema standard.
    3. (Optional) Use extractPerPage to perform extraction on a per-page basis.
    4. (Optional) Configure extractionModel, extractionModelProvider, and extractionCredentials to use a different model for the extraction step than the initial OCR step. By default, the same model is used for both.
  8. Use the `zerox` asynchronous API in Python

    main

    The pyzerox.zerox function is an asynchronous API that performs OCR (Optical Character Recognition) to convert PDF files (or other supported document formats) into markdown format using vision models.

    Requirements:

    • You must use a Vision Model.
    • You must set up environment variables for your chosen model provider (e.g., OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.).
    • The model name should follow the LiteLLM provider format (e.g., gpt-4o-mini for OpenAI or azure/gpt-4o-mini for Azure OpenAI).
    from pyzerox import zerox
    import os
    import asyncio
    
    # Example setup for OpenAI
    os.environ["OPENAI_API_KEY"] = "your-api-key"
    model = "gpt-4o-mini"
    
    async def main():
        file_path = "path/to/your/document.pdf"
        output_dir = "./output_dir"
        
        # Perform OCR
        result = await zerox(
            file_path=file_path, 
            model=model, 
            output_dir=output_dir
        )
        print(result)
    
    asyncio.run(main())
  9. Use Zerox for OCR in Node.js

    main

    The zerox function converts documents (PDF, DOCX, images, etc.) into Markdown by converting pages to images and processing them with a vision model. You can provide a file URL or a local file path.

    Basic Usage (File URL):

    import { zerox } from "zerox";
    
    const result = await zerox({
      filePath: "https://omni-demo-data.s3.amazonaws.com/test/cs101.pdf",
      credentials: {
        apiKey: process.env.OPENAI_API_KEY,
      },
    });

    Basic Usage (Local Path):

    import { zerox } from "zerox";
    import path from "path";
    
    const result = await zerox({
      filePath: path.resolve(__dirname, "./cs101.pdf"),
      credentials: {
        apiKey: process.env.OPENAI_API_KEY,
      },
    });
  10. Understand Zerox operation modes

    main

    Zerox operates in three primary modes depending on your configuration:

    1. OCR Mode (Default):

      • Triggered when no schema is provided.
      • Converts document pages into markdown text.
      • Returns pages containing the text content.
    2. Extraction Mode:

      • Triggered when schema is provided and extractOnly is true (or enableHybridExtraction is false).
      • Uses the LLM to map document content directly to the provided JSON schema.
      • Returns an extracted object matching the schema structure.
    3. Hybrid Extraction Mode:

      • Triggered when schema is provided and enableHybridExtraction is true.
      • Step 1: Performs OCR on all pages to generate markdown text.
      • Step 2: Uses the generated text (and optionally images) to perform structured extraction via the LLM.
      • This is useful when the LLM benefits from both the visual context and the OCR text.

    Constraints:

    • enableHybridExtraction cannot be used if directImageExtraction or extractOnly is true.
    • extractOnly mode requires a schema.
    • maintainFormat is only supported in OCR mode.
  11. Example of Zerox OCR output: Financial Executive Summary

    main

    This record demonstrates the structured data extraction capabilities of Zerox by showcasing a processed financial document. The output includes highly structured sections such as 'Executive Summary', 'Asset Allocation', 'Portfolio Construction', and 'Tax Transition/Overlap Analysis'.

    Key data points extracted include:

    • Portfolio Metrics: Total value, allocation percentages (e.g., 82%/18% Stocks/Bonds), and profile.
    • Asset Allocation Tables: Breakdown of Cash, US Stocks, Non-US Stocks, and Bonds.
    • Sector and Geographic Distributions: Detailed percentage breakdowns compared against benchmarks (e.g., Cyclical, Sensitive, Defensive sectors).
    • Tabular Financial Data: A detailed 'Tax Transition/Overlap Analysis' table containing Security Name, Ticker, Units, Cost, Value, Gain/Loss, and year-specific projections (2024, 2025, 2026).
    ### Tax Transition/Overlap Analysis Table Example
    
    | Security Name | Ticker | Units | Cost | Value | Gain/Loss | 2024 | 2025 | 2026 |
    | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
    | PFIZER INC | PFE | 23.00 | $1,114.91 | $662 | ($453) | ($453) | | |
    | NVIDIA CORP | NVDA | 5.00 | $2,477.52 | $2,576 | $98 | $98 | | |