File size: 6,792 Bytes
98ea29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# syntax=docker/dockerfile:1
# Generated by scripts/release/generate_preview_docker.py.
# Standalone: only this Dockerfile is needed. No local source or weights are copied.
FROM python:3.12-slim-bookworm AS release
ARG HF_REPO=D-OCR/D-OCR-preview
ARG HF_REVISION=4b557b4626bdfb39db3d7a0aed120a853092c0db
RUN --mount=type=cache,target=/download-cache,sharing=locked python - <<'PY'
"""Embedded in standalone Dockerfiles; downloads only verified inference assets."""
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import tarfile
import time
from urllib.error import URLError
from urllib.parse import quote
from urllib.request import urlopen


RUNTIME = 'runtime/docr-runtime-cp312-linux-x86_64.tar.gz'
REQUIRED = {
    RUNTIME, 'requirements-runtime.txt',
    'checkpoints/siglip_qwen/best.pt',
    'checkpoints/initial_v1/table/best/model.safetensors',
    'checkpoints/initial_v1/table/best/config.json',
    'checkpoints/initial_v1/table/best/preprocessor_config.json',
    'deploy/models/siglip_qwen/vision/config.json',
    'deploy/models/siglip_qwen/vision/preprocessor_config.json',
    'deploy/models/siglip_qwen/decoder/config.json',
    'deploy/models/siglip_qwen/decoder/tokenizer.json',
    'deploy/models/siglip_qwen/decoder/tokenizer_config.json',
    *(f'deploy/models/{model}/inference.{suffix}'
      for model in ('layout_s_paddle322', 'PP-OCRv5_mobile_det')
      for suffix in ('json', 'pdiparams', 'yml')),
}


def verified(path, entry):
    if not path.is_file() or path.stat().st_size != entry['size_bytes']:
        return False
    with path.open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest() == entry['sha256']


def fetch(url, path):
    for attempt in range(3):
        try:
            with urlopen(url, timeout=120) as response, path.open('wb') as stream:
                shutil.copyfileobj(response, stream, length=1024 * 1024)
            return
        except (URLError, TimeoutError, ConnectionError):
            if attempt == 2:
                raise
            time.sleep(2 ** attempt)


def download_release(base_url, destination):
    destination = Path(destination)
    destination.mkdir(parents=True, exist_ok=True)
    manifest_path = destination / 'MANIFEST.json'
    fetch(base_url + '/MANIFEST.json', manifest_path)
    manifest = json.loads(manifest_path.read_text())
    entries = manifest['files']
    missing = REQUIRED - {entry['path'] for entry in entries}
    if missing:
        raise ValueError(f'Missing required release assets: {sorted(missing)}')
    for entry in entries:
        relative = entry['path']
        path = PurePosixPath(relative)
        if path.is_absolute() or '..' in path.parts or '\\' in relative:
            raise ValueError(f'Unsafe release path: {relative}')
    for entry in entries:
        relative = entry['path']
        if not (relative in REQUIRED or relative in ('LICENSE', 'THIRD_PARTY_NOTICES.md')
                or relative.startswith(('checkpoints/siglip_qwen/',
                                        'checkpoints/initial_v1/table/best/',
                                        'deploy/models/', 'licenses/'))):
            continue
        target = destination / relative
        if verified(target, entry):
            print(f'Cached: {relative}', flush=True)
            continue
        target.parent.mkdir(parents=True, exist_ok=True)
        temporary = target.with_name(target.name + '.part')
        print(f'Downloading: {relative} ({entry["size_bytes"]:,} bytes)', flush=True)
        try:
            fetch(base_url + '/' + quote(relative, safe='/'), temporary)
            if not verified(temporary, entry):
                raise ValueError(f'Checksum or size mismatch: {relative}')
            temporary.replace(target)
        finally:
            temporary.unlink(missing_ok=True)


if __name__ == '__main__':
    repo = os.environ['HF_REPO']
    revision = os.environ['HF_REVISION']
    base_url = f'https://huggingface.co/{repo}/resolve/{quote(revision, safe="")}'
    cache = Path('/download-cache') / hashlib.sha256(base_url.encode()).hexdigest()
    download_release(base_url, cache)
    output = Path('/release')
    output.mkdir(parents=True, exist_ok=True)
    for name in ('checkpoints', 'deploy', 'licenses'):
        if (cache / name).exists():
            shutil.copytree(cache / name, output / name, dirs_exist_ok=True)
    for name in ('requirements-runtime.txt', 'LICENSE', 'THIRD_PARTY_NOTICES.md', 'MANIFEST.json'):
        if (cache / name).exists():
            shutil.copy2(cache / name, output / name)
    with tarfile.open(cache / RUNTIME, 'r:gz') as archive:
        archive.extractall(output, filter='data')
    (output / 'RELEASE_REVISION').write_text(f'{repo}@{revision}\n')
PY

FROM python:3.12-slim-bookworm AS base
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 \
    HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false \
    OCR_PIPELINE=siglip_qwen OCR_DEVICE=cpu OCR_PADDLE_DEVICE=cpu \
    OCR_PADDLE_PYTHON=/usr/local/bin/python \
    OCR_RECOGNIZER_CHECKPOINT=/opt/docr/checkpoints/siglip_qwen/best.pt \
    OCR_RECOGNIZER_ASSETS=/opt/docr/deploy/models/siglip_qwen \
    OCR_LINE_DETECTOR_MODEL=/opt/docr/deploy/models/PP-OCRv5_mobile_det \
    PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK=True DISABLE_MODEL_SOURCE_CHECK=True \
    OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OCR_MAX_PENDING_JOBS=10 \
    OCR_DATA_DIR=/opt/docr/data HOME=/home/ocr
RUN apt-get update && apt-get install -y --no-install-recommends libgomp1 libglib2.0-0 libgl1 \
    && rm -rf /var/lib/apt/lists/* \
    && useradd --uid 1000 --create-home --home-dir /home/ocr --shell /usr/sbin/nologin ocr
COPY --from=release /release/requirements-runtime.txt /tmp/requirements-runtime.txt
RUN pip install --no-cache-dir -r /tmp/requirements-runtime.txt
WORKDIR /opt/docr
RUN mkdir -p /opt/docr/data && chown ocr:ocr /opt/docr/data
VOLUME ["/opt/docr/data"]
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=300s --retries=3 \
    CMD python -c "import json,urllib.request; r=json.load(urllib.request.urlopen('http://localhost:8000/health',timeout=3)); raise SystemExit(r.get('status')!='ready')"
CMD ["python", "-m", "uvicorn", "api.app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]

FROM base AS cpu
RUN pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu torch==2.9.1+cpu torchvision==0.24.1+cpu \
    && pip check
COPY --from=release /release/ /opt/docr/
USER ocr

FROM base AS gpu
RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cu128 torch==2.9.1+cu128 torchvision==0.24.1+cu128 flash-linear-attention==0.6.0 \
    && pip check
COPY --from=release /release/ /opt/docr/
ENV OCR_DEVICE=cuda
USER ocr

FROM cpu AS default