{"id":14964618,"url":"https://github.com/dicklesworthstone/llm_aided_ocr","last_synced_at":"2025-05-14T05:12:13.621Z","repository":{"id":184078803,"uuid":"671266493","full_name":"Dicklesworthstone/llm_aided_ocr","owner":"Dicklesworthstone","description":"Enhance Tesseract OCR output for scanned PDFs by applying Large Language Model (LLM) corrections.","archived":false,"fork":false,"pushed_at":"2025-02-27T11:18:30.000Z","size":1478,"stargazers_count":2628,"open_issues_count":19,"forks_count":179,"subscribers_count":22,"default_branch":"main","last_synced_at":"2025-05-07T00:36:38.979Z","etag":null,"topics":["ai-assist","llama2","llm","ocr","ocr-correction","tesseract"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Dicklesworthstone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-07-26T23:54:37.000Z","updated_at":"2025-05-06T19:08:04.000Z","dependencies_parsed_at":"2024-07-27T19:05:13.093Z","dependency_job_id":"62026834-f142-430c-a47e-d8b8ecb21585","html_url":"https://github.com/Dicklesworthstone/llm_aided_ocr","commit_stats":{"total_commits":50,"total_committers":4,"mean_commits":12.5,"dds":"0.18000000000000005","last_synced_commit":"c79f6b709a8db62903f55647bec4816823b86b9e"},"previous_names":["dicklesworthstone/llama2_aided_tesseract","dicklesworthstone/llm_aided_ocr"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fllm_aided_ocr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fllm_aided_ocr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fllm_aided_ocr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dicklesworthstone%2Fllm_aided_ocr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Dicklesworthstone","download_url":"https://codeload.github.com/Dicklesworthstone/llm_aided_ocr/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254076850,"owners_count":22010611,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-assist","llama2","llm","ocr","ocr-correction","tesseract"],"created_at":"2024-09-24T13:33:30.874Z","updated_at":"2025-05-14T05:12:08.554Z","avatar_url":"https://github.com/Dicklesworthstone.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LLM-Aided OCR Project\n\n## Introduction\n\nThe 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.\n\n## Example Outputs\n\nTo see what the LLM-Aided OCR Project can do, check out these example outputs:\n\n- [Original PDF](https://github.com/Dicklesworthstone/llm_aided_ocr/blob/main/160301289-Warren-Buffett-Katharine-Graham-Letter.pdf) \n- [Raw OCR Output](https://github.com/Dicklesworthstone/llm_aided_ocr/blob/main/160301289-Warren-Buffett-Katharine-Graham-Letter__raw_ocr_output.txt)\n- [LLM-Corrected Markdown Output](https://github.com/Dicklesworthstone/llm_aided_ocr/blob/main/160301289-Warren-Buffett-Katharine-Graham-Letter_llm_corrected.md)\n\n## Features\n\n- PDF to image conversion\n- OCR using Tesseract\n- Advanced error correction using LLMs (local or API-based)\n- Smart text chunking for efficient processing\n- Markdown formatting option\n- Header and page number suppression (optional)\n- Quality assessment of the final output\n- Support for both local LLMs and cloud-based API providers (OpenAI, Anthropic)\n- Asynchronous processing for improved performance\n- Detailed logging for process tracking and debugging\n- GPU acceleration for local LLM inference\n\n## Detailed Technical Overview\n\n### PDF Processing and OCR\n\n1. **PDF to Image Conversion**\n   - Function: `convert_pdf_to_images()`\n   - Uses `pdf2image` library to convert PDF pages into images\n   - Supports processing a subset of pages with `max_pages` and `skip_first_n_pages` parameters\n\n2. **OCR Processing**\n   - Function: `ocr_image()`\n   - Utilizes `pytesseract` for text extraction\n   - Includes image preprocessing with `preprocess_image()` function:\n     - Converts image to grayscale\n     - Applies binary thresholding using Otsu's method\n     - Performs dilation to enhance text clarity\n\n### Text Processing Pipeline\n\n1. **Chunk Creation**\n   - The `process_document()` function splits the full text into manageable chunks\n   - Uses sentence boundaries for natural splits\n   - Implements an overlap between chunks to maintain context\n\n2. **Error Correction and Formatting**\n   - Core function: `process_chunk()`\n   - Two-step process:\n     a. OCR Correction:\n        - Uses LLM to fix OCR-induced errors\n        - Maintains original structure and content\n     b. Markdown Formatting (optional):\n        - Converts text to proper markdown format\n        - Handles headings, lists, emphasis, and more\n\n3. **Duplicate Content Removal**\n   - Implemented within the markdown formatting step\n   - Identifies and removes exact or near-exact repeated paragraphs\n   - Preserves unique content and ensures text flow\n\n4. **Header and Page Number Suppression (Optional)**\n   - Can be configured to remove or distinctly format headers, footers, and page numbers\n\n### LLM Integration\n\n1. **Flexible LLM Support**\n   - Supports both local LLMs and cloud-based API providers (OpenAI, Anthropic)\n   - Configurable through environment variables\n\n2. **Local LLM Handling**\n   - Function: `generate_completion_from_local_llm()`\n   - Uses `llama_cpp` library for local LLM inference\n   - Supports custom grammars for structured output\n\n3. **API-based LLM Handling**\n   - Functions: `generate_completion_from_claude()` and `generate_completion_from_openai()`\n   - Implements proper error handling and retry logic\n   - Manages token limits and adjusts request sizes dynamically\n\n4. **Asynchronous Processing**\n   - Uses `asyncio` for concurrent processing of chunks when using API-based LLMs\n   - Maintains order of processed chunks for coherent final output\n\n### Token Management\n\n1. **Token Estimation**\n   - Function: `estimate_tokens()`\n   - Uses model-specific tokenizers when available\n   - Falls back to `approximate_tokens()` for quick estimation\n\n2. **Dynamic Token Adjustment**\n   - Adjusts `max_tokens` parameter based on prompt length and model limits\n   - Implements `TOKEN_BUFFER` and `TOKEN_CUSHION` for safe token management\n\n### Quality Assessment\n\n1. **Output Quality Evaluation**\n   - Function: `assess_output_quality()`\n   - Compares original OCR text with processed output\n   - Uses LLM to provide a quality score and explanation\n\n### Logging and Error Handling\n\n- Comprehensive logging throughout the codebase\n- Detailed error messages and stack traces for debugging\n- Suppresses HTTP request logs to reduce noise\n\n## Configuration and Customization\n\nThe project uses a `.env` file for easy configuration. Key settings include:\n\n- LLM selection (local or API-based)\n- API provider selection\n- Model selection for different providers\n- Token limits and buffer sizes\n- Markdown formatting options\n\n## Output and File Handling\n\n1. **Raw OCR Output**: Saved as `{base_name}__raw_ocr_output.txt`\n2. **LLM Corrected Output**: Saved as `{base_name}_llm_corrected.md` or `.txt`\n\nThe script generates detailed logs of the entire process, including timing information and quality assessments.\n\n## Requirements\n\n- Python 3.12+\n- Tesseract OCR engine\n- PDF2Image library\n- PyTesseract\n- OpenAI API (optional)\n- Anthropic API (optional)\n- Local LLM support (optional, requires compatible GGUF model)\n\n## Installation\n\n1. Install Pyenv and Python 3.12 (if needed):\n\n```bash\n# Install Pyenv and python 3.12 if needed and then use it to create venv:\nif ! command -v pyenv \u0026\u003e /dev/null; then\n    sudo apt-get update\n    sudo apt-get install -y build-essential libssl-dev zlib1g-dev libbz2-dev \\\n    libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \\\n    xz-utils tk-dev libffi-dev liblzma-dev python3-openssl git\n\n    git clone https://github.com/pyenv/pyenv.git ~/.pyenv\n    echo 'export PYENV_ROOT=\"$HOME/.pyenv\"' \u003e\u003e ~/.zshrc\n    echo 'export PATH=\"$PYENV_ROOT/bin:$PATH\"' \u003e\u003e ~/.zshrc\n    echo 'eval \"$(pyenv init --path)\"' \u003e\u003e ~/.zshrc\n    source ~/.zshrc\nfi\ncd ~/.pyenv \u0026\u0026 git pull \u0026\u0026 cd -\npyenv install 3.12\n```\n\n2. Set up the project:\n\n```bash\n# Use pyenv to create virtual environment:\ngit clone https://github.com/Dicklesworthstone/llm_aided_ocr    \ncd llm_aided_ocr          \npyenv local 3.12\npython -m venv venv\nsource venv/bin/activate\npython -m pip install --upgrade pip\npython -m pip install wheel\npython -m pip install --upgrade setuptools wheel\npip install -r requirements.txt\n```\n\n3. Install Tesseract OCR engine (if not already installed):\n   - For Ubuntu: `sudo apt-get install tesseract-ocr`\n   - For macOS: `brew install tesseract`\n   - For Windows: Download and install from [GitHub](https://github.com/UB-Mannheim/tesseract/wiki)\n\n4. Set up your environment variables in a `.env` file:\n   ```\n   USE_LOCAL_LLM=False\n   API_PROVIDER=OPENAI\n   OPENAI_API_KEY=your_openai_api_key\n   ANTHROPIC_API_KEY=your_anthropic_api_key\n   ```\n\n## Usage\n\n1. Place your PDF file in the project directory.\n\n2. Update the `input_pdf_file_path` variable in the `main()` function with your PDF filename.\n\n3. Run the script:\n   ```\n   python llm_aided_ocr.py\n   ```\n\n4. The script will generate several output files, including the final post-processed text.\n\n## How It Works\n\nThe LLM-Aided OCR project employs a multi-step process to transform raw OCR output into high-quality, readable text:\n\n1. **PDF Conversion**: Converts input PDF into images using `pdf2image`.\n\n2. **OCR**: Applies Tesseract OCR to extract text from images.\n\n3. **Text Chunking**: Splits the raw OCR output into manageable chunks for processing.\n\n4. **Error Correction**: Each chunk undergoes LLM-based processing to correct OCR errors and improve readability.\n\n5. **Markdown Formatting** (Optional): Reformats the corrected text into clean, consistent Markdown.\n\n6. **Quality Assessment**: An LLM-based evaluation compares the final output quality to the original OCR text.\n\n## Code Optimization\n\n- **Concurrent Processing**: When using API-based models, chunks are processed concurrently to improve speed.\n- **Context Preservation**: Each chunk includes a small overlap with the previous chunk to maintain context.\n- **Adaptive Token Management**: The system dynamically adjusts the number of tokens used for LLM requests based on input size and model constraints.\n\n## Configuration\n\nThe project uses a `.env` file for configuration. Key settings include:\n\n- `USE_LOCAL_LLM`: Set to `True` to use a local LLM, `False` for API-based LLMs.\n- `API_PROVIDER`: Choose between \"OPENAI\" or \"CLAUDE\".\n- `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`: API keys for respective services.\n- `CLAUDE_MODEL_STRING`, `OPENAI_COMPLETION_MODEL`: Specify the model to use for each provider.\n- `LOCAL_LLM_CONTEXT_SIZE_IN_TOKENS`: Set the context size for local LLMs.\n\n## Output Files\n\nThe script generates several output files:\n\n1. `{base_name}__raw_ocr_output.txt`: Raw OCR output from Tesseract.\n2. `{base_name}_llm_corrected.md`: Final LLM-corrected and formatted text.\n\n## Limitations and Future Improvements\n\n- The system's performance is heavily dependent on the quality of the LLM used.\n- Processing very large documents can be time-consuming and may require significant computational resources.\n\n## Contributing\n\nContributions to this project are welcome! Please fork the repository and submit a pull request with your proposed changes.\n\n## License\n\nThis project is licensed under the MIT License.\n\n---\n\nThanks 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:\n\n**[YoutubeTranscriptOptimizer.com](https://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.\n\nThe 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.\n\n**[FixMyDocuments.com](https://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.\n\nIn 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.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdicklesworthstone%2Fllm_aided_ocr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdicklesworthstone%2Fllm_aided_ocr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdicklesworthstone%2Fllm_aided_ocr/lists"}