Upload 2 files
Browse filesFiles changed (2)
- README.md+767-3
- docker-compose.yml+24-72
123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767# DeepSeek-OCR: PDF to Markdown ConverterA powerful OCR solution that converts PDF documents to Markdown format using DeepSeek-OCR with FastAPI backend. This project provides both a batch processing script and a REST API for flexible document conversion.## π Quick Start### Option 1: Batch Processing with pdf_to_markdown_processor.py1. Place your PDF files in the `data/` directory2. Ensure the DeepSeek-OCR API is running (see Docker setup below)3. Run the processor:```bashpython pdf_to_markdown_processor.py```### Option 2: REST API with Docker Backend1. Build and start the Docker container2. Use the API endpoints to process documents3. Integrate with your applications---## π Prerequisites### Hardware Requirements- **NVIDIA GPU** with CUDA 11.8+ support- **GPU Memory**: Minimum 12GB VRAM (Model takes ~9GB)- **System RAM**: Minimum 32GB (recommended: 64GB+)- **Storage**: 50GB+ free space for model and containers### Software Requirements- **Python 3.8+** (for local processing)- **Docker** 20.10+ with GPU support- **Docker Compose** 2.0+- **NVIDIA Container Toolkit** installed- **CUDA 11.8** compatible drivers---## π³ Docker Backend Setup### 1. Download Model WeightsCreate a directory for model weights and download the DeepSeek-OCR model:```bash# Create models directorymkdir -p models# Download using Hugging Face CLIpip install huggingface_hubhuggingface-cli download deepseek-ai/DeepSeek-OCR --local-dir models/deepseek-ai/DeepSeek-OCR# Or using gitgit clone https://huggingface.co/deepseek-ai/DeepSeek-OCR models/deepseek-ai/DeepSeek-OCR```### 2. Build and Run the Docker Container#### Windows Users```cmdREM Build the Docker imagebuild.batREM Start the servicedocker-compose up -dREM Check logsdocker-compose logs -f deepseek-ocr```#### Linux/macOS Users```bash# Build the Docker imagedocker-compose build# Start the servicedocker-compose up -d# Check logsdocker-compose logs -f deepseek-ocr```### 3. Verify Installation```bash# Health checkcurl http://localhost:8000/health# Expected response:{"status": "healthy","model_loaded": true,"model_path": "/app/models/deepseek-ai/DeepSeek-OCR","cuda_available": true,"cuda_device_count": 1}```---## π PDF Processing ScriptsThis project provides several PDF processing scripts, each designed for different use cases. All scripts scan the `data/` directory for PDF files and convert them to Markdown format with different prompts and post-processing options.### Output Naming ConventionAll processors append a suffix to the output filename to indicate the processing method used:- **-MD.md**: Markdown conversion (preserves document structure)- **-OCR.md**: Plain OCR extraction (raw text without formatting)- **-CUSTOM.md**: Custom prompt processing (uses prompt from YAML file)For example, processing `document.pdf` will create:- `document-MD.md` (markdown processors)- `document-OCR.md` (OCR processor)- `document-CUSTOM.md` (custom prompt processors)---### 1. pdf_to_markdown_processor.py**Purpose**: Basic PDF to Markdown conversion using the standard markdown prompt**Features**:- Uses prompt: `'<image>\n<|grounding|>Convert the document to markdown.'`- Converts PDFs to structured Markdown format- Simple processing without image extraction- Outputs files with `-MD.md` suffix**Usage**:```bash# Place PDF files in the data directorycp your_document.pdf data/# Run the processorpython pdf_to_markdown_processor.py# Check resultsls data/*-MD.md```---### 2. pdf_to_markdown_processor_enhanced.py**Purpose**: Enhanced PDF to Markdown conversion with post-processing**Features**:- Uses the same markdown prompt as the basic version- **Post-processing features**:- Image extraction and saving to `data/images/` folder- Special token cleanup- Reference processing for layout information- Content cleaning and formatting- Outputs files with `-MD.md` suffix**Usage**:```bash# Place PDF files in the data directorycp your_document.pdf data/# Run the enhanced processorpython pdf_to_markdown_processor_enhanced.py# Check results (including extracted images)ls data/*-MD.mdls data/images/```---### 3. pdf_to_ocr_enhanced.py**Purpose**: Plain OCR text extraction without markdown formatting**Features**:- Uses OCR prompt: `'<image>\nFree OCR.'`- Extracts raw text without markdown structure- Includes the same post-processing features as the enhanced markdown processor- Outputs files with `-OCR.md` suffix**Usage**:```bash# Place PDF files in the data directorycp your_document.pdf data/# Run the OCR processorpython pdf_to_ocr_enhanced.py# Check resultsls data/*-OCR.md```---### 4. pdf_to_custom_prompt.py**Purpose**: PDF processing with custom prompts (raw output)**Features**:- Uses custom prompt loaded from `custom_prompt.yaml`- Returns raw model response without post-processing- Ideal for testing and debugging different prompts- Outputs files with `-CUSTOM.md` suffix**Configuration**:Edit `custom_prompt.yaml` to customize the prompt:```yaml# Custom prompt for PDF processingprompt: '<image>\n<|grounding|>Convert the document to markdown.'```**Usage**:```bash# Edit the prompt in custom_prompt.yamlnano custom_prompt.yaml# Place PDF files in the data directorycp your_document.pdf data/# Run the custom prompt processorpython pdf_to_custom_prompt.py# Check resultsls data/*-CUSTOM.md```---### 5. pdf_to_custom_prompt_enhanced.py**Purpose**: PDF processing with custom prompts and full post-processing**Features**:- Uses custom prompt loaded from `custom_prompt.yaml`- Includes all post-processing features (image extraction, content cleaning, etc.)- Combines custom prompts with enhanced output processing- Outputs files with `-CUSTOM.md` suffix**Configuration**:Same as `pdf_to_custom_prompt.py` - edit `custom_prompt.yaml` to customize the prompt.**Usage**:```bash# Edit the prompt in custom_prompt.yamlnano custom_prompt.yaml# Place PDF files in the data directorycp your_document.pdf data/# Run the enhanced custom prompt processorpython pdf_to_custom_prompt_enhanced.py# Check results (including extracted images)ls data/*-CUSTOM.mdls data/images/```---## π Comparison of Processors| Processor | Prompt | Post-Processing | Image Extraction | Output Suffix | Use Case ||-----------|--------|-----------------|------------------|---------------|----------|| `pdf_to_markdown_processor.py` | Markdown | β | β | `-MD.md` | Quick markdown conversion || `pdf_to_markdown_processor_enhanced.py` | Markdown | β | β | `-MD.md` | Full-featured markdown with images || `pdf_to_ocr_enhanced.py` | Free OCR | β | β | `-OCR.md` | Raw text extraction || `pdf_to_custom_prompt.py` | Custom (YAML) | β | β | `-CUSTOM.md` | Testing custom prompts || `pdf_to_custom_prompt_enhanced.py` | Custom (YAML) | β | β | `-CUSTOM.md` | Custom prompts with full features |---## π Common Usage Patterns### Comparing Different Processing MethodsTo compare how different processors handle the same document:```bash# Place a PDF in the data directorycp test_document.pdf data/# Run all processorspython pdf_to_markdown_processor.pypython pdf_to_markdown_processor_enhanced.pypython pdf_to_ocr_enhanced.pypython pdf_to_custom_prompt.py# Compare outputsls data/test_document-*.md```### Processing with Custom Prompts1. Edit `custom_prompt.yaml` with your desired prompt:```yamlprompt: '<image>\nExtract all tables and format as CSV.'```2. Run the custom processor:```bashpython pdf_to_custom_prompt_enhanced.py```3. Check the specialized output:```bashcat data/your_document-CUSTOM.md```------## π REST API UsageThe FastAPI backend provides several endpoints for document processing.### API Endpoints#### Health Check```bashGET http://localhost:8000/health```#### Process Single Image```bashcurl -X POST "http://localhost:8000/ocr/image" \-H "accept: application/json" \-H "Content-Type: multipart/form-data" \-F "file=@your_image.jpg"```#### Process PDF```bashcurl -X POST "http://localhost:8000/ocr/pdf" \-H "accept: application/json" \-H "Content-Type: multipart/form-data" \-F "file=@your_document.pdf"```#### Batch Processing```bashcurl -X POST "http://localhost:8000/ocr/batch" \-H "accept: application/json" \-H "Content-Type: multipart/form-data" \-F "files=@image1.jpg" \-F "files=@document.pdf" \-F "files=@image2.png"```### Response Formats#### Single Image Response```json{"success": true,"result": "# Document Title\n\nThis is the OCR result in markdown format...","page_count": 1}```#### PDF Response```json{"success": true,"results": [{"success": true,"result": "# Page 1 Content\n...","page_count": 1},{"success": true,"result": "# Page 2 Content\n...","page_count": 2}],"total_pages": 2,"filename": "document.pdf"}```---## π» Client Integration Examples### Python Client```pythonimport requestsclass DeepSeekOCRClient:def __init__(self, base_url="http://localhost:8000"):self.base_url = base_urldef process_image(self, image_path):with open(image_path, 'rb') as f:response = requests.post(f"{self.base_url}/ocr/image",files={"file": f})return response.json()def process_pdf(self, pdf_path):with open(pdf_path, 'rb') as f:response = requests.post(f"{self.base_url}/ocr/pdf",files={"file": f})return response.json()# Usageclient = DeepSeekOCRClient()result = client.process_pdf("document.pdf")if result["success"]:for page_result in result["results"]:print(f"Page {page_result['page_count']}:")print(page_result["result"])print("---")```### JavaScript Client```javascriptclass DeepSeekOCR {constructor(baseUrl = 'http://localhost:8000') {this.baseUrl = baseUrl;}async processImage(file) {const formData = new FormData();formData.append('file', file);const response = await fetch(`${this.baseUrl}/ocr/image`, {method: 'POST',body: formData});return await response.json();}async processPDF(file) {const formData = new FormData();formData.append('file', file);const response = await fetch(`${this.baseUrl}/ocr/pdf`, {method: 'POST',body: formData});return await response.json();}}// Usage in browserconst ocr = new DeepSeekOCR();document.getElementById('fileInput').addEventListener('change', async (e) => {const file = e.target.files[0];const result = await ocr.processPDF(file);if (result.success) {result.results.forEach(page => {console.log(`Page ${page.page_count}:`, page.result);});}});```---## βοΈ Configuration### Custom Configuration and Critical FixesThis project includes custom files that replace the original DeepSeek-OCR library code to fix critical issues and provide enhanced functionality. These replacements are applied transparently during the Docker build process.#### π¨ Critical Prompt Parameter Fix**Issue**: The original DeepSeek-OCR library has a bug where the `tokenize_with_images()` method is called without the required `prompt` parameter during model initialization, causing server startup failures.**Solution**: Custom run scripts have been created to properly handle the prompt parameter and prevent startup errors.#### Custom Files and Their PurposeThe following custom files in the project root replace their counterparts during Docker build:- **`custom_config.py`**: Custom configuration with customizable default prompt and settings- **`custom_image_process.py`**: Fixed version of the image processing module that handles the prompt parameter correctly- **`custom_run_dpsk_ocr_pdf.py`**: Enhanced PDF script that accepts `--prompt` argument and fixes the initialization issue- **`custom_run_dpsk_ocr_image.py`**: Enhanced image script that accepts `--prompt` argument and fixes the initialization issue- **`custom_run_dpsk_ocr_eval_batch.py`**: Enhanced batch script that accepts `--prompt` argument and fixes the initialization issueThese custom files are automatically copied over the original library files during the Docker build process, ensuring the fixes are applied without requiring manual intervention.#### Using Custom Configuration1. **Edit the Default Prompt**:```python# Edit custom_config.pyPROMPT = '<image>\n<|grounding|>Your custom default prompt here.'```2. **Use Custom Prompts with Direct Scripts**:```bash# Using default prompt from custom_config.pypython custom_run_dpsk_ocr_pdf.py --input your_file.pdf --output output_dir# Using custom prompt via command linepython custom_run_dpsk_ocr_pdf.py --prompt "<image>\n<|grounding|>Extract tables as CSV." --input your_file.pdf```3. **Use Custom Prompts with API**:```bash# Using default promptcurl -X POST "http://localhost:8000/ocr/pdf" -F "file=@your_file.pdf"# Using custom promptcurl -X POST "http://localhost:8000/ocr/pdf" -F "file=@your_file.pdf" -F "prompt=<image>\n<|grounding|>Your custom prompt here."```4. **Build and Run**:```bash# Rebuild with custom configuration and fixesdocker-compose build# Start the containerdocker-compose up -d```#### Docker Build ProcessThe Dockerfile automatically applies the custom files during the build process:```dockerfile# Copy custom files to replace the originals (transparent replacement approach)COPY custom_config.py ./DeepSeek-OCR-vllm/config.pyCOPY custom_image_process.py ./DeepSeek-OCR-vllm/process/image_process.py# Copy custom run scripts to replace the originalsCOPY custom_run_dpsk_ocr_pdf.py ./DeepSeek-OCR-vllm/run_dpsk_ocr_pdf.pyCOPY custom_run_dpsk_ocr_image.py ./DeepSeek-OCR-vllm/run_dpsk_ocr_image.pyCOPY custom_run_dpsk_ocr_eval_batch.py ./DeepSeek-OCR-vllm/run_dpsk_ocr_eval_batch.py```This transparent replacement approach ensures that:- The critical prompt parameter fix is applied- Custom configuration options are available- No manual modification of the original library code is required- The fixes persist across container rebuildsFor detailed documentation, see **`CUSTOM_CONFIG_README.md`**.### Environment VariablesEdit `docker-compose.yml` to adjust these settings:```yamlenvironment:- CUDA_VISIBLE_DEVICES=0 # GPU device to use- MODEL_PATH=/app/models/deepseek-ai/DeepSeek-OCR # Model path- MAX_CONCURRENCY=50 # Max concurrent requests- GPU_MEMORY_UTILIZATION=0.85 # GPU memory usage (0.1-1.0)```### Performance Tuning#### For High-Throughput Processing```yamlenvironment:- MAX_CONCURRENCY=100- GPU_MEMORY_UTILIZATION=0.95```#### For Memory-Constrained Systems```yamlenvironment:- MAX_CONCURRENCY=10- GPU_MEMORY_UTILIZATION=0.7```---## π§ Troubleshooting### Common Issues#### 1. Out of Memory Errors```bash# Reduce concurrency and GPU memory usage# Edit docker-compose.yml:environment:- MAX_CONCURRENCY=10- GPU_MEMORY_UTILIZATION=0.7```#### 2. Model Loading Issues```bash# Check model directory structurels -la models/deepseek-ai/DeepSeek-OCR/# Verify model files are presentdocker-compose exec deepseek-ocr ls -la /app/models/deepseek-ai/DeepSeek-OCR/```#### 3. CUDA Errors```bash# Check GPU availabilitynvidia-smi# Check Docker GPU supportdocker run --rm --gpus all nvidia/cuda:11.8-base-ubuntu20.04 nvidia-smi```#### 4. API Connection Errors```bash# Check if the API is runningcurl http://localhost:8000/health# Check container logsdocker-compose logs -f deepseek-ocr# Restart the servicedocker-compose restart deepseek-ocr```#### 5. PDF Processing Errors```bash# Check if PDF files are validfile data/your_document.pdf# Try processing a single PDF manuallycurl -X POST "http://localhost:8000/ocr/pdf" \-H "accept: application/json" \-H "Content-Type: multipart/form-data" \-F "file=@data/your_document.pdf"```#### 6. Prompt Parameter Error (Fixed)If you encounter this error during server startup:```TypeError: DeepseekOCRProcessor.tokenize_with_images() missing 1 required positional argument: 'prompt'```This error has been fixed with the custom files included in the Docker build. If you still see it:1. **Ensure you're using the updated Dockerfile** (includes custom run scripts)2. **Rebuild the container completely**:```bashdocker-compose downdocker-compose build --no-cachedocker-compose up -d```3. **Verify the fix is applied**:```bashdocker-compose exec deepseek-ocr ls -la /app/DeepSeek-OCR-vllm/run_dpsk_ocr_*.py# These should show recent timestamps from the build```The fix ensures that the `tokenize_with_images()` method is called with the correct prompt parameter during model initialization.### Debug ModeFor debugging, you can run the container with additional tools:```bash# Run with shell accessdocker-compose run --rm deepseek-ocr bash# Check model loadingpython -c "import syssys.path.insert(0, '/app/DeepSeek-OCR-master/DeepSeek-OCR-vllm')from config import MODEL_PATHprint(f'Model path: {MODEL_PATH}')print(f'Model exists: {os.path.exists(MODEL_PATH)}')"```---## π Performance Tips1. **Batch Processing**: Process multiple files at once using the `/ocr/batch` endpoint2. **Optimize DPI**: The default DPI of 144 provides good balance between quality and speed3. **GPU Utilization**: Adjust `GPU_MEMORY_UTILIZATION` based on your GPU capacity4. **Concurrency**: Increase `MAX_CONCURRENCY` for better throughput on powerful GPUs5. **File Size**: For large PDFs, consider splitting them into smaller chunks---## ποΈ Project Structure```DeepSeek-OCR/βββ README.md # This fileβββ CUSTOM_CONFIG_README.md # Custom configuration documentationβββ pdf_to_markdown_processor.py # Basic markdown conversionβββ pdf_to_markdown_processor_enhanced.py # Enhanced markdown with post-processingβββ pdf_to_ocr_enhanced.py # OCR text extractionβββ pdf_to_custom_prompt.py # Custom prompt processing (raw)βββ pdf_to_custom_prompt_enhanced.py # Custom prompt with post-processingβββ custom_prompt.yaml # Configuration for custom promptsβββ custom_config.py # Custom configuration (replaces original config.py)βββ custom_image_process.py # Fixed image processing (replaces original)βββ custom_run_dpsk_ocr_pdf.py # Custom PDF script with prompt support (replaces original)βββ custom_run_dpsk_ocr_image.py # Custom image script with prompt support (replaces original)βββ custom_run_dpsk_ocr_eval_batch.py # Custom batch script with prompt support (replaces original)βββ test_custom_config.py # Test script for custom configurationβββ start_server.py # FastAPI serverβββ Dockerfile # Docker container definition (includes custom files)βββ docker-compose.yml # Docker compose configurationβββ build.bat # Windows build scriptβββ data/ # Input/output directory for PDFsβ βββ images/ # Extracted images (when using enhanced processors)β βββ *.md # Generated markdown filesβββ models/ # Model weights directoryβββ DeepSeek-OCR/ # DeepSeek-OCR source codeβββ DeepSeek-OCR-master/βββ DeepSeek-OCR-vllm/ # Original library files (replaced during build)```---## π LicenseThis project follows the same license as the DeepSeek-OCR project. Please refer to the original project's license file for details.---## π€ SupportFor issues related to:- **Docker setup**: Check this README first- **DeepSeek-OCR model**: Refer to the [official repository](https://github.com/deepseek-ai/DeepSeek-OCR)- **vLLM**: Refer to [vLLM documentation](https://docs.vllm.ai/)---## π Usage Workflow```mermaidgraph TDA[Start] --> B{Choose Method}B -->|Batch Processing| C[Place PDFs in data/ folder]B -->|API Usage| D[Start Docker Container]C --> E[Run python pdf_to_markdown_processor.py]D --> F[Use API endpoints]E --> G[Check data/ folder for .md files]F --> H[Process results from API response]G --> I[Done]H --> Istyle A fill:#e1f5festyle I fill:#e8f5e8style C fill:#fff3e0style D fill:#fff3e0style E fill:#f3e5f5style F fill:#f3e5f5
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576services:postgres:image: postgres:latestenvironment:- POSTGRES_USER=openvsx- POSTGRES_PASSWORD=openvsxlogging:options:max-size: 10mmax-file: "3"ports:- '5432:5432'profiles:- db- debugelasticsearch:image: elasticsearch:8.7.1environment:- xpack.security.enabled=false- xpack.ml.enabled=false- discovery.type=single-node- bootstrap.memory_lock=true- cluster.routing.allocation.disk.threshold_enabled=falseports:- 9200:9200- 9300:9300healthcheck:test: curl -s http://elasticsearch01:9200 >/dev/null || exit 1interval: 10stimeout: 5sretries: 50start_period: 5sprofiles:- es- debugkibana:image: kibana:8.7.1ports:- "5601:5601"environment:- ELASTICSEARCH_URL=http://elasticsearch:9200depends_on:- elasticsearchprofiles:- kibanaserver:image: ghcr.io/eclipse/openvsx-server:7f658d0volumes:- ./application.yml:/home/openvsx/server/config/application.ymlports:- 8080:8080depends_on:- postgres- elasticsearchhealthcheck:interval: 10stimeout: 5sretries: 50start_period: 5sprofiles:- openvsx- backendwebui:image: ghcr.io/eclipse/openvsx-webui:7f658d0ports:- 3000:3000depends_on:- serverprofiles:- openvsx- frontend12345678910111213141516171819202122232425262728services:deepseek-ocr:build: .container_name: deepseek-ocr-vllmports:- "8000:8000"volumes:- ./models:/app/models # Mount directory for model weights- ./outputs:/app/outputs # Mount directory for output filesenvironment:- CUDA_VISIBLE_DEVICES=0- MODEL_PATH=/app/models/deepseek-ai/DeepSeek-OCR # Update with your model path- MAX_CONCURRENCY=5 # Adjust based on your GPU memory- GPU_MEMORY_UTILIZATION=0.85 # Adjust based on your GPU memorydeploy:resources:reservations:devices:- driver: nvidiacount: 1capabilities: [gpu]restart: unless-stoppedhealthcheck:test: ["CMD", "curl", "-f", "http://localhost:8000/health"]interval: 30stimeout: 10sretries: 3start_period: 120s # Give time for model to load
README.md+767-3
docker-compose.yml+24-72