A Python script that converts PDF files to clean Markdown format using the OLMOCR vision-language model via LM Studio.
- High-quality OCR: Uses the
allenai/olmocr-2-7bmodel for accurate text extraction - Command-line interface: Simple usage with automatic output path generation
- Batch processing: Processes all pages in a PDF automatically
- Progress tracking: Visual progress bar with tqdm
- Robust parsing: Handles multiple response formats from the model
- Python 3.8+
- LM Studio running locally with OLMOCR model loaded
- Required Python packages
- Clone or download this script
- Install dependencies:
pip install openai pypdf tqdm- Install OLMOCR:
pip install olmocr- Start LM Studio and load the OLMOCR model:
- Model:
allenai/olmocr-2-7b - Quantization:
q4_k_m(recommended) - Ensure LM Studio API server is running on
http://localhost:1234
- Model:
Basic usage:
python ocr_script.py path/to/your/document.pdfThis will create path/to/your/document.md automatically.
Currently supports:
- Input PDF file path (required)
- Output path is automatically generated in the same directory with
.mdextension
- PDF Reading: Uses PyPDF to read the PDF file structure
- Page Processing: Each page is sent to LM Studio as an image
- OCR Processing: OLMOCR model extracts and formats text from the image
- Response Parsing: Handles both JSON and YAML-like response formats
- Markdown Assembly: Combines all pages into a single Markdown file
The script handles two response formats from the model:
- JSON format:
{"natural_text": "extracted text here"} - YAML separator format:
---\nmetadata\n---\nextracted text here
The script produces a Markdown file with:
- Each PDF page's content as a separate section
- Clean formatting suitable for documentation, notes, or further processing
- UTF-8 encoding for international character support
# Convert a PDF file
python ocr_script.py ~/Documents/research_paper.pdf
# Output will be created at:
# ~/Documents/research_paper.md-
LM Studio not running:
Error: Connection refusedSolution: Start LM Studio and ensure the API server is enabled
-
Model not loaded:
Error: Model not foundSolution: Load
allenai/olmocr-2-7bin LM Studio -
Memory issues:
Error: CUDA out of memorySolution: Use smaller PDFs or increase LM Studio's context size
To debug, you can add print statements to see the raw response:
# Add this after line 45 in the script
print(f"Raw response for page {page_num}: {content[:200]}...")- Processing speed depends on your GPU/CPU and LM Studio settings
- Large PDFs may take several minutes to process
- Memory usage scales with PDF page size and resolution
- Requires LM Studio running locally
- Model may struggle with complex layouts or handwritten text
- Processing is sequential (one page at a time)
This script is provided as-is for educational and personal use.