# D-OCR preview: download and run This repository includes all four model components plus a compiled OCR/API runtime. It does not include the browser frontend or Python application source. The API returns the same backend-generated text, layout JSON and HTML views used by the local D-OCR app. No training or extra base-model download is needed. ## 1. Requirements - Linux x86-64 host and Docker Engine with the Compose plugin. - For GPU: a CUDA/BF16-capable NVIDIA GPU, a compatible NVIDIA driver, and [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). Local inference was validated on an RTX 5060 Ti with 16 GB VRAM. This is not a minimum-memory specification. - CPU mode is available but slow. Leave sufficient RAM for the OS and container; one tested page peaked near 6.52 GiB in the OCR container. This does not bound memory for all documents. The exact Core i5 laptop has not been benchmarked. - Approximately 2.4 GiB of model downloads, plus runtime dependencies. Allow at least 20 GB free on Docker's storage disk for the CPU build and more for GPU. Build cache, image layers and unpacked files can occupy several copies during the first build. A different project/download disk does not expand Docker storage. The runtime is compiled for CPython 3.12 and Linux x86-64. Use the supplied Docker build to obtain a compatible environment. Windows/macOS native use is not tested. ## 2. Download just the Dockerfile and Compose file No Python installation, source checkout, Git LFS, or manual model download is needed on the host. Choose CPU or GPU and download the matching two small files into an empty folder. For CPU: ```bash mkdir D-OCR-preview cd D-OCR-preview curl -fL -O https://huggingface.co/D-OCR/D-OCR-preview/resolve/main/Dockerfile.cpu curl -fL -O https://huggingface.co/D-OCR/D-OCR-preview/resolve/main/compose.cpu.yml ``` For GPU, download `Dockerfile.gpu` and `compose.gpu.yml` instead. The generic `Dockerfile` also supports `--target cpu` and `--target gpu`; its untargeted build defaults to GPU for compatibility. The build downloads about 2.4 GiB of models, configurations, tokenizers and the compiled runtime from `D-OCR/D-OCR-preview`. It pins release revision `4b557b4626bdfb39db3d7a0aed120a853092c0db` and checks every downloaded asset's size and SHA-256 against that revision's manifest. It also includes license files. The trained SigLIP2 encoder, connector and Qwen decoder are all inside `best.pt`. No separate upstream model downloads are needed. ## 3. Create a local API key ```bash # Linux umask 077 printf 'OCR_API_KEYS=%s\n' "$(openssl rand -hex 32)" > .env ``` ```bash # Windows(Powershell) $bytes = New-Object byte[] 32 [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes) $key = -join ($bytes | ForEach-Object { $_.ToString('x2') }) [IO.File]::WriteAllText("$PWD\.env", "OCR_API_KEYS=$key`n", (New-Object Text.UTF8Encoding $false)) ``` **This makes the key of 32 random bytes written as 64 hex characters.** Compose reads `.env` automatically. Keep it private. The API requires this key in the `X-API-Key` header. Existing installations can use `docker compose --env-file .env.runtime ...` to retain their previous key file. ## 4. Build and start CPU: ```bash docker compose -f compose.cpu.yml up -d --build --wait --wait-timeout 600 ``` GPU (requires NVIDIA Container Toolkit): ```bash docker compose -f compose.gpu.yml up -d --build --wait --wait-timeout 600 ``` The initial build needs internet and may take a while. Completed downloads are cached by BuildKit, and the weights are stored in the resulting image. Restarts need no model download or host model mounts. The application runs offline after building. CPU uses FP32; GPU recognition uses BF16, while Paddle layout/text workers use CPU in both modes. One OCR worker serializes inference requests. Use one configuration at a time. Stop the previous stack with its Compose file before switching. Both use the `docr-preview` project and persistent data volume. Do not pass `down -v` if you want to keep saved documents. Set `OCR_API_PORT` in `.env` to change the host port, or `OCR_CPU_THREADS` to change CPU thread counts. You can also use **only a Dockerfile**, without Compose: ```bash docker build --platform linux/amd64 -f Dockerfile.cpu -t docr-preview:cpu-auto . export OCR_API_KEYS="$(openssl rand -hex 32)" docker run -d --name docr-preview --init \ -p 127.0.0.1:8000:8000 -e OCR_API_KEYS \ -v docr-preview-data:/opt/docr/data docr-preview:cpu-auto ``` For GPU use `Dockerfile.gpu`, tag `docr-preview:gpu-auto`, and add `--gpus all` to `docker run`. Keep the generated key for authorization in `/docs`. Advanced: `--build-arg HF_REVISION=COMMIT_SHA` selects another compatible release with the same manifest/runtime layout. Inference assets are pinned; OS packages and some dependencies still have version ranges, so builds are not bit-for-bit reproducible. Restarting is fully offline; rebuilding can require internet. ## 5. Check startup and open the API UI ```bash curl --fail http://localhost:8000/health ``` Expected: `status: ready`, `pipeline: siglip_qwen`, no warmup failures. Open **http://localhost:8000/docs** in a browser. Select **Authorize**, enter the API key from your local `.env`, then use `POST /v1/ocr` to upload an image or PDF. This is an API testing interface, not the original browser frontend. For a shell request: ```bash set -a . ./.env set +a curl --fail-with-body --max-time 1800 \ -H "X-API-Key: $OCR_API_KEYS" \ -F 'image=@document.png' \ http://localhost:8000/v1/ocr > result.json ``` The file key must be `image`, including for a PDF. For long documents or multiple clients, submit with `POST /v1/jobs`, then poll `GET /v1/jobs/{upload_id}` with both `X-API-Key` and `Authorization: Bearer `. A completed job's `result` has the same structure as the synchronous response. Keep job tokens private. ## 6. Read and save layout outputs Each successful synchronous response contains: - `text`: combined extracted text. - `pages[]`: one result per page, including `text`, `document`, `overlay`, `positioned_html`, and `html`. - `pages[i].document`: region/cell coordinates, types, statuses, warnings and model metadata. - `pages[i].positioned_html`: original-layout reconstruction with recognized text. - `pages[i].html`: reading-order reconstruction. Export the first page's views using any local Python 3 installation: ```bash python3 - <<'PY' import json from pathlib import Path result = json.loads(Path('result.json').read_text()) page = result['pages'][0] Path('extracted.txt').write_text(result['text'], encoding='utf-8') Path('original-layout.html').write_text(page['positioned_html'], encoding='utf-8') Path('reading-view.html').write_text(page['html'], encoding='utf-8') Path('layout.json').write_text(json.dumps(page['document'], ensure_ascii=False, indent=2), encoding='utf-8') PY ``` Open the HTML files in a browser. These use the same reconstruction algorithm as our backend. They are approximate document reconstructions, not pixel-perfect copies: fonts, spacing, missing detections and table errors can differ from the source. Inspect each page's warnings and block statuses as well as its text. ## 7. Weights and architecture - `checkpoints/siglip_qwen/best.pt`: trained SigLIP2 + connector + Qwen text weights. This is a tensor-only PyTorch state dictionary under `model`, not a standalone Transformers model that `AutoModel.from_pretrained` can load directly. - `deploy/models/siglip_qwen/vision/` and `decoder/`: matching configuration and processor/tokenizer files. - `deploy/models/layout_s_paddle322/`: compatible PP-DocLayout-S export. - `deploy/models/PP-OCRv5_mobile_det/`: text detector. - `checkpoints/initial_v1/table/best/`: Table Transformer weights and processor config. - `runtime/`: compiled backend implementation required to connect these components. Advanced users may inspect the state dictionary with `torch.load(path, map_location="cpu", weights_only=True, mmap=True)`. The weights alone do not implement cropping, generation state, reading order or reconstruction; use the bundled runtime to reproduce the full pipeline. ## 8. Limits and troubleshooting - CPU is slow: one 13-block page took about 80 seconds on the test Ryzen 7 PC. Dense pages can take minutes; runtime varies with text length and document complexity. - Limit: 16 MiB/upload, 20 PDF pages, 144 DPI PDF rendering and 20 megapixels/page. - Only the first 200 detected lines receive OCR in the inherited page pipeline. - `no_valid_grid`, `token_limit` or `repetition_stopped` requires review. - `CUDA unavailable`: check `nvidia-smi` and NVIDIA Container Toolkit. CPU mode is the fallback; an incompatible GPU cannot be enabled just by changing the flag. - `Missing ... checkpoint/configuration`: rebuild the image and check download/checksum errors in the build log. - `no space left on device` during image export: free space on Docker's storage disk, then rebuild. Do not delete volumes containing documents to free build space. - Startup failure: run `docker compose -p docr-preview -f compose.gpu.yml logs --tail=80` (replace with `compose.cpu.yml` for CPU). Allow model warmup to finish before requests. - Port 8000 is bound to localhost by default. This preview does not configure a public hosting service. Uploads/results persist in the named Docker volume; there is no automatic retention policy. ## 9. License and evaluation Noncommercial testing/research only for D-OCR contributions. See `LICENSE` and `THIRD_PARTY_NOTICES.md`. Third-party assets retain their upstream licenses. See `README.md` and `evaluation.json` for measured accuracy and limitations.