DEV Community

Cover image for Install olmOCR: The Best Open-Source OCR Toolkit for Document Parsing
Aditi Bindal for NodeShift

Posted on

Install olmOCR: The Best Open-Source OCR Toolkit for Document Parsing

When working with language models, extracting high-quality text from PDFs is a crucial yet challenging task due to the diversity of document formats, layouts, and embedded elements like tables, equations, and handwritten notes. olmOCR is an open-source Python toolkit designed to tackle this challenge by converting PDFs into clean, structured plain text while maintaining natural reading order. Built on a fine-tuned 7B vision language model (VLM), olmOCR efficiently processes large-scale document collections, making it a powerful tool for anyone dealing with extensive PDF datasets.

In this guide, we’ll walk you through the steps to install olmOCR-7B-0225-preview locally, ensuring you have everything set up for seamless document parsing and text extraction.

Prerequisites

The minimum system requirements for this use case are:

  • GPUs: RTX 4090 or RTX A6000

  • Disk Space: 50 - 100 GB

  • RAM: At least 8 GB.

  • Nvidia CUDA installed.

Note: The prerequisites for this are highly variable across use cases. A high-end configuration could be used for a large-scale deployment.

Step-by-step process to install and run olmOCR for document parsing

For the purpose of this tutorial, we’ll use a GPU-powered Virtual Machine by NodeShift since it provides high compute Virtual Machines at a very affordable cost on a scale that meets GDPR, SOC2, and ISO27001 requirements. Also, it offers an intuitive and user-friendly interface, making it easier for beginners to get started with Cloud deployments. However, feel free to use any cloud provider of your choice and follow the same steps for the rest of the tutorial.

Step 1: Setting up a NodeShift Account

Visit app.nodeshift.com and create an account by filling in basic details, or continue signing up with your Google/GitHub account.

If you already have an account, login straight to your dashboard.

Image-step1-1

Step 2: Create a GPU Node

After accessing your account, you should see a dashboard (see image), now:

1) Navigate to the menu on the left side.

2) Click on the GPU Nodes option.

Image-step2-1

3) Click on Start to start creating your very first GPU node.

Image-step2-2

These GPU nodes are GPU-powered virtual machines by NodeShift. These nodes are highly customizable and let you control different environmental configurations for GPUs ranging from H100s to A100s, CPUs, RAM, and storage, according to your needs.

Step 3: Selecting configuration for GPU (model, region, storage)

1) For this tutorial, we’ll be using the RTX 4090 GPU; however, you can choose any GPU of your choice based on your needs.

2) Similarly, we’ll opt for 200GB storage by sliding the bar. You can also select the region where you want your GPU to reside from the available ones.

Image-step3-1

Step 4: Choose GPU Configuration and Authentication method

1) After selecting your required configuration options, you'll see the available VMs in your region and according to (or very close to) your configuration. In our case, we'll choose a 1x RTX 4090 GPU node with 12 vCPUs/96GB RAM/200 GB SSD.

2) Next, you'll need to select an authentication method. Two methods are available: Password and SSH Key. We recommend using SSH keys, as they are a more secure option. To create one, head over to our official documentation.

Image-step4-1

Step 5: Choose an Image

The final step would be to choose an image for the VM, which in our case is Nvidia Cuda, where we’ll deploy and run the inference of our model.

Image-step5-1

That's it! You are now ready to deploy the node. Finalize the configuration summary, and if it looks good, click Create to deploy the node.

Image-step5-2

Image-step5-3

Step 6: Connect to active Compute Node using SSH

1) As soon as you create the node, it will be deployed in a few seconds or a minute. Once deployed, you will see a status Running in green, meaning that our Compute node is ready to use!

2) Once your GPU shows this status, navigate to the three dots on the right and click on Connect with SSH. This will open a pop-up box with the Host details. Copy and paste that in your local terminal to connect to the remote server via SSH.

Image-step6-2

Step 7: Set up the project environment with dependencies

Create a virtual environment using Anaconda.

conda create -n olmocr python=3.11 && conda activate olmocr
Enter fullscreen mode Exit fullscreen mode

Output:

Image-step7-1

2) Once you're inside the environment, install dependencies to run the model.

pip install torch torchvision torchaudio einops timm pillow
pip install git+https://github.com/huggingface/transformers
pip install git+https://github.com/huggingface/accelerate
pip install git+https://github.com/huggingface/diffusers
pip install huggingface_hub
pip install sentencepiece bitsandbytes protobuf decord numpy
pip install olmocr
Enter fullscreen mode Exit fullscreen mode

Output:

Image-step7-2

3) Install Jupyter notebook and overwrite default channels.

conda install -c conda-forge --override-channels notebook -y
conda install -c conda-forge --override-channels ipywidgets -y
Enter fullscreen mode Exit fullscreen mode

Output:
Image-step7-3

4) Launch Jupyter notebook.

jupyter notebook --allow-root
Enter fullscreen mode Exit fullscreen mode

Output:
Image description

In the above output, you'll see two URLs. Either of them will allow you to access Jupyter Notebook in your local browser.

5) To be able to access the above URLs in the local browser, we'll first need to forward and tunnel our remote server's SSH port.

Run the following command in your local terminal after replacing:

with the PORT allotted to your remote server (For the NodeShift server - you can find it in the deployed GPU details on the dashboard).

with the path to the location where your SSH key is stored.

with the IP address of your remote server.

ssh -L 8888:localhost:8888 -p <YOUR_SERVER_PORT> -i <PATH_TO_SSH> root@<YOUR_SERVER_IP>
Enter fullscreen mode Exit fullscreen mode

Output:
Image description

6) Next, visit the local browser and paste any one URL from that output.

As the page opens, you will be able to select a new .ipynb notebook from the dashboard.

Step 8: Download model checkpoints

In the new Python notebook, you can check GPU details using the below command:

!nvidia-smi
Enter fullscreen mode Exit fullscreen mode

Output
Image-step8-1

2) Import dependencies and download the model.

import torch
import base64
import urllib.request

from io import BytesIO
from PIL import Image
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration

from olmocr.data.renderpdf import render_pdf_to_base64png
from olmocr.prompts import build_finetuning_prompt
from olmocr.prompts.anchor import get_anchor_text

# Initialize the model
model = Qwen2VLForConditionalGeneration.from_pretrained("allenai/olmOCR-7B-0225-preview", torch_dtype=torch.bfloat16).eval()
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
Enter fullscreen mode Exit fullscreen mode

Output:
Image-step8-2

Step 9: Run the model for inference

Finally, we'll test the model on our document to get the parsed results.

# Render page 2 to an image
image_base64 = render_pdf_to_base64png("./Neuroscience-Science-of-the-Brain.pdf", 2, target_longest_image_dim=1024)

# Build the prompt, using document metadata
anchor_text = get_anchor_text("./Neuroscience-Science-of-the-Brain.pdf", 1, pdf_engine="pdfreport", target_length=4000)
prompt = build_finetuning_prompt(anchor_text)

# Build the full prompt
messages = [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt},
                    {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
                ],
            }
        ]

# Apply the chat template and processor
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
main_image = Image.open(BytesIO(base64.b64decode(image_base64)))

inputs = processor(
    text=[text],
    images=[main_image],
    padding=True,
    return_tensors="pt",
)
inputs = {key: value.to(device) for (key, value) in inputs.items()}

# Generate the output
output = model.generate(
            **inputs,
            temperature=0.8,
            max_new_tokens=50,
            num_return_sequences=1,
            do_sample=True,
        )

# Decode the output
prompt_length = inputs["input_ids"].shape[1]
new_tokens = output[:, prompt_length:]
text_output = processor.tokenizer.batch_decode(
    new_tokens, skip_special_tokens=True
)

print(text_output)
Enter fullscreen mode Exit fullscreen mode

In the above code, we've used a document called Neuroscience-Science-of-the-Brain, which is an introductory material for beginners to learn about Neuroscience.

For the specified, we asked the model to parse page no. 2 of that document and the results generated by the output are as shown below:
Image-step9-1

Conclusion

Installing olmOCR locally allows you to efficiently extract structured text from diverse PDFs, leveraging its fine-tuned 7B vision language model for accurate parsing. From handling complex layouts to enabling large-scale batch processing, olmOCR simplifies document conversion for language model training and data analysis. However, NodeShift’s cloud platform provides a seamless solution for those looking to scale beyond local setups. It offers optimized infrastructure for high-volume AI processing with its scalable compute resources and easy AI deployments in just a few clicks.

For more information about NodeShift:

Top comments (0)