The LLM-Aided OCR Project is an advanced system designed to significantly enhance the quality of Optical Character Recognition (OCR) output. By leveraging cutting-edge natural language processing techniques and large language models (LLMs), this project transforms raw OCR text into highly accurate, well-formatted, and readable documents.
To see what the LLM-Aided OCR Project can do, check out these example outputs:
convert_pdf_to_images()pdf2image library to convert PDF pages into imagesSupports processing a subset of pages with max_pages and skip_first_n_pages parameters
OCR Processing
ocr_image()pytesseract for text extractionpreprocess_image() function:process_document() function splits the full text into manageable chunksImplements an overlap between chunks to maintain context
Error Correction and Formatting
process_chunk()Two-step process: a. OCR Correction: - Uses LLM to fix OCR-induced errors - Maintains original structure and content b. Markdown Formatting (optional): - Converts text to proper markdown format - Handles headings, lists, emphasis, and more
Duplicate Content Removal
Preserves unique content and ensures text flow
Header and Page Number Suppression (Optional)
Configurable through environment variables
Local LLM Handling
generate_completion_from_local_llm()llama_cpp library for local LLM inferenceSupports custom grammars for structured output
API-based LLM Handling
generate_completion_from_claude() and generate_completion_from_openai()Manages token limits and adjusts request sizes dynamically
Asynchronous Processing
asyncio for concurrent processing of chunks when using API-based LLMsestimate_tokens()Falls back to approximate_tokens() for quick estimation
Dynamic Token Adjustment
max_tokens parameter based on prompt length and model limitsTOKEN_BUFFER and TOKEN_CUSHION for safe token managementassess_output_quality()The project uses a .env file for easy configuration. Key settings include:
{base_name}__raw_ocr_output.txt{base_name}_llm_corrected.md or .txtThe script generates detailed logs of the entire process, including timing information and quality assessments.
# Install Pyenv and python 3.12 if needed and then use it to create venv:
if ! command -v pyenv &> /dev/null; then
sudo apt-get update
sudo apt-get install -y build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \
xz-utils tk-dev libffi-dev liblzma-dev python3-openssl git
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
source ~/.zshrc
fi
cd ~/.pyenv && git pull && cd -
pyenv install 3.12
# Use pyenv to create virtual environment:
git clone https://github.com/Dicklesworthstone/llm_aided_ocr
cd llm_aided_ocr
pyenv local 3.12
python -m venv venv
source venv/bin/activate
python -m pip install --upgrade pip
python -m pip install wheel
python -m pip install --upgrade setuptools wheel
pip install -r requirements.txt
sudo apt-get install tesseract-ocrbrew install tesseractFor Windows: Download and install from GitHub
Set up your environment variables in a .env file:
USE_LOCAL_LLM=False
API_PROVIDER=OPENAI
OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
Place your PDF file in the project directory.
Update the input_pdf_file_path variable in the main() function with your PDF filename.
Run the script:
python llm_aided_ocr.py
The script will generate several output files, including the final post-processed text.
The LLM-Aided OCR project employs a multi-step process to transform raw OCR output into high-quality, readable text:
PDF Conversion: Converts input PDF into images using pdf2image.
OCR: Applies Tesseract OCR to extract text from images.
Text Chunking: Splits the raw OCR output into manageable chunks for processing.
Error Correction: Each chunk undergoes LLM-based processing to correct OCR errors and improve readability.
Markdown Formatting (Optional): Reformats the corrected text into clean, consistent Markdown.
Quality Assessment: An LLM-based evaluation compares the final output quality to the original OCR text.
The project uses a .env file for configuration. Key settings include:
USE_LOCAL_LLM: Set to True to use a local LLM, False for API-based LLMs.API_PROVIDER: Choose between "OPENAI" or "CLAUDE".OPENAI_API_KEY, ANTHROPIC_API_KEY: API keys for respective services.CLAUDE_MODEL_STRING, OPENAI_COMPLETION_MODEL: Specify the model to use for each provider.LOCAL_LLM_CONTEXT_SIZE_IN_TOKENS: Set the context size for local LLMs.The script generates several output files:
{base_name}__raw_ocr_output.txt: Raw OCR output from Tesseract.{base_name}_llm_corrected.md: Final LLM-corrected and formatted text.Contributions to this project are welcome! Please fork the repository and submit a pull request with your proposed changes.
This project is licensed under the MIT License (with OpenAI/Anthropic Rider).
Thanks for your interest in my open-source project! I hope you find it useful. You might also find my commercial web apps useful, and I would really appreciate it if you checked them out:
YoutubeTranscriptOptimizer.com makes it really quick and easy to paste in a YouTube video URL and have it automatically generate not just a really accurate direct transcription, but also a super polished and beautifully formatted written document that can be used independently of the video.
The document basically sticks to the same material as discussed in the video, but it sounds much more like a real piece of writing and not just a transcript. It also lets you optionally generate quizzes based on the contents of the document, which can be either multiple choice or short-answer quizzes, and the multiple choice quizzes get turned into interactive HTML files that can be hosted and easily shared, where you can actually take the quiz and it will grade your answers and score the quiz for you.
FixMyDocuments.com lets you submit any kind of document— PDFs (including scanned PDFs that require OCR), MS Word and Powerpoint files, images, audio files (mp3, m4a, etc.) —and turn them into highly optimized versions in nice markdown formatting, from which HTML and PDF versions are automatically generated. Once converted, you can also edit them directly in the site using the built-in markdown editor, where it saves a running revision history and regenerates the PDF/HTML versions.
In addition to just getting the optimized version of the document, you can also generate many other kinds of "derived documents" from the original: interactive multiple-choice quizzes that you can actually take and get graded on; slick looking presentation slides as PDF or HTML (using LaTeX and Reveal.js), an in-depth summary, a concept mind map (using Mermaid diagrams) and outline, custom lesson plans where you can select your target audience, a readability analysis and grade-level versions of your original document (good for simplifying concepts for students), Anki Flashcards that you can import directly into the Anki app or use on the site in a nice interface, and more.
$ claude mcp add llm_aided_ocr \
-- python -m otcore.mcp_server <graph>