feat(gpu): support NVIDIA opt-in (RTX 2060) pour PaddleOCR et LaMa
- ocr.py : SCALPER_PADDLE_DEVICE (ex. gpu:0) forwardé à PaddleOCR(device=...) ; non défini -> auto (CPU sur l'image par défaut). - inpaint.py : _providers() -> CUDAExecutionProvider si SCALPER_LAMA_DEVICE=gpu ET onnxruntime-gpu dispo, sinon repli CPU avec warning stderr. - Dockerfile.gpu : CUDA 12.6 runtime/cuDNN en wheels pip (nvidia-cuda-runtime-cu12, nvidia-cudnn-cu12), paddlepaddle-gpu==3.2.2 via index Baidu cu126 (pas sur PyPI), onnxruntime-gpu pour big-lama. Dockerfile racine (CPU) inchangé. - docker-compose.gpu.yml : réserve 1 GPU (nvidia) + pose les 2 variables GPU. - Tests : device forwardé, providers CUDA si dispo, repli CPU sinon. README + .env.example. Co-authored-by: Orionis312050 <Orionis312050@users.noreply.github.com>
This commit is contained in:
1 parent
420d86694f
commit
5f88874ee2
8 files changed
+159
-3
No files matched your search
@@ -13,5 +13,8 @@ MISTRAL_MODEL=mistral-small-latest
|
||||
# SCALPER_INPAINT_ENGINE=lama
|
||||
# Tier PP-OCRv6 pour l'OCR paddle (défaut medium ; tiny ne lit pas le japonais) :
|
||||
# SCALPER_PADDLE_OCR_TIER=medium
|
||||
# GPU (image Dockerfile.gpu + docker-compose.gpu.yml, hôte NVIDIA + nvidia-ctk) :
|
||||
# SCALPER_PADDLE_DEVICE=gpu:0
|
||||
# SCALPER_LAMA_DEVICE=gpu
|
||||
# SCALPER_LAMA_CACHE=/app/data/.lama
|
||||
# SCALPER_LAMA_MODEL=/chemin/vers/lama_fp32.onnx # modèle local, si déjà téléchargé ailleurs
|
||||
@@ -0,0 +1,45 @@
|
||||
# Image GPU (NVIDIA, ex. RTX 2060 / 6 Go VRAM) — build :
|
||||
# docker compose -f docker-compose.yml -f docker-compose.gpu.yml up -d --build
|
||||
# Prérequis hôte : driver NVIDIA >= 525 (runtime CUDA 12.6) + NVIDIA Container Toolkit
|
||||
# (nvidia-ctk) installé et runtime par défaut configuré.
|
||||
# L'image par défaut (CPU) reste le Dockerfile racine.
|
||||
FROM python:3.12-slim
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr fonts-dejavu-core \
|
||||
libgl1 libglib2.0-0 libgomp1 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Runtime CUDA 12.6 + cuDNN en wheels pip : le driver (libcuda) est injecté dans le
|
||||
# conteneur par le NVIDIA Container Toolkit au lancement.
|
||||
RUN pip install --no-cache-dir nvidia-cuda-runtime-cu12 nvidia-cudnn-cu12
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY pyproject.toml README.md ./
|
||||
COPY src ./src
|
||||
|
||||
# Paddle GPU 3.x non publié sur PyPI : index Baidu cu126 (paddlepaddle-gpu==3.2.2,
|
||||
# même pin <3.3 qu'en CPU pour le bug oneDNN 3.3.x). onnxruntime-gpu pour LaMa en CUDA.
|
||||
# (pas d'extra .[ocr-paddle] ici : il tirerait le wheel CPU paddlepaddle en conflit)
|
||||
RUN pip install --no-cache-dir "paddlepaddle-gpu==3.2.2" \
|
||||
-i https://www.paddlepaddle.org.cn/packages/stable/cu126/ \
|
||||
&& pip install --no-cache-dir \
|
||||
"paddleocr>=3.0" "pytesseract>=0.3.10" "pillow>=10.1" "onnxruntime-gpu" "numpy" \
|
||||
&& pip install --no-cache-dir -e .
|
||||
|
||||
RUN useradd -m scalper && mkdir -p /app/data /app/out && chown -R scalper:scalper /app
|
||||
|
||||
# Le conteneur démarre en root : l'entrypoint chown les répertoires montés
|
||||
# (bind mounts root côté hôte, ex. Coolify) puis droppe les privilèges (setpriv).
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz')" || exit 1
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
CMD ["scalper", "serve", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -154,6 +154,29 @@ les modèles ne sont téléchargés qu'une fois, dans le volume monté.
|
||||
`"zip_export": true` (zip `export-<date>-<heure>-<minutes>.zip` à la fin, puis supprime le reste de `out/`)
|
||||
et `"zip_include_clean": true` (embarque aussi `cleaned/` dans le zip, debug inpainting).
|
||||
|
||||
## GPU NVIDIA (ex. RTX 2060, 6 Go VRAM)
|
||||
|
||||
Le modèle recommandé reste **PP-OCRv6_medium** (`SCALPER_PADDLE_OCR_TIER=medium`) : 34,5 M params,
|
||||
moins de 1 Go de VRAM en inférence — la RTX 2060 suffit largement, et le gain de vitesse est
|
||||
conséquent (le doc annonce 0,13 s/page sur A100 ; sur RTX 2060 comptez une fraction de seconde).
|
||||
`PaddleOCR-VL` (VLM 0,9 B) n'est PAS conseillé ici : trop lourd/limite en 6 Go et mauvais outil
|
||||
(parsing de documents, pas de bulles).
|
||||
|
||||
Déploiement GPU (opt-in, l'image par défaut reste CPU) :
|
||||
|
||||
```bash
|
||||
# prérequis hôte : driver NVIDIA >= 525 (CUDA 12.6) + NVIDIA Container Toolkit (nvidia-ctk)
|
||||
docker compose -f docker-compose.yml -f docker-compose.gpu.yml up -d --build
|
||||
# vérif : docker compose exec scalper nvidia-smi
|
||||
```
|
||||
|
||||
- `Dockerfile.gpu` : runtime CUDA 12.6 + cuDNN en wheels pip (`nvidia-cuda-runtime-cu12`,
|
||||
`nvidia-cudnn-cu12`), `paddlepaddle-gpu==3.2.2` depuis l'index Baidu cu126 (les wheels GPU 3.x
|
||||
ne sont pas sur PyPI), `onnxruntime-gpu` pour LaMa.
|
||||
- `docker-compose.gpu.yml` : réserve 1 GPU (`deploy.resources.reservations.devices`, driver
|
||||
`nvidia`) et pose `SCALPER_PADDLE_DEVICE=gpu:0` (PaddleOCR sur le GPU) + `SCALPER_LAMA_DEVICE=gpu`
|
||||
(big-lama en CUDA). Sans ces variables, tout retombe sur le CPU automatiquement.
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Skills Mistral** (workspace, v1) : `manga-scraper`, `chapter-cleaner`,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Override GPU (NVIDIA, ex. RTX 2060) — build + up :
|
||||
# docker compose -f docker-compose.yml -f docker-compose.gpu.yml up -d --build
|
||||
#
|
||||
# Prérequis hôte : driver NVIDIA >= 525 (runtime CUDA 12.6) + NVIDIA Container Toolkit
|
||||
# (`nvidia-ctk runtime configure --runtime=docker` + restart docker), puis `nvidia-smi`
|
||||
# dans le conteneur pour vérifier.
|
||||
#
|
||||
# L'override merge `environment` (clé par clé) avec docker-compose.yml : on n'y met
|
||||
# que les variables GPU.
|
||||
services:
|
||||
scalper:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.gpu
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities: [gpu]
|
||||
environment:
|
||||
SCALPER_PADDLE_DEVICE: gpu:0 # PaddleOCR / PaddleX sur le GPU (PP-OCRv6_medium, < 1 Go VRAM)
|
||||
SCALPER_LAMA_DEVICE: gpu # big-lama ONNX en CUDA via onnxruntime-gpu
|
||||
+13
-1
@@ -215,9 +215,21 @@ class LamaInpainter:
|
||||
) from e
|
||||
model = self._resolve_model_path()
|
||||
print(f"[scalper][lama] modèle ONNX : {model}", file=sys.stderr)
|
||||
self._session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
|
||||
self._session = ort.InferenceSession(str(model), providers=self._providers(ort))
|
||||
return self._session
|
||||
|
||||
def _providers(self, ort) -> list[str]:
|
||||
"""CUDA si SCALPER_LAMA_DEVICE=gpu ET disponible (onnxruntime-gpu), sinon CPU
|
||||
(avec un warning si le GPU était demandé mais indisponible)."""
|
||||
want_gpu = os.environ.get("SCALPER_LAMA_DEVICE", "cpu").strip().lower() in ("gpu", "cuda", "gpu:0")
|
||||
get_avail = getattr(ort, "get_available_providers", None)
|
||||
available = get_avail() if callable(get_avail) else ["CPUExecutionProvider"]
|
||||
if want_gpu and "CUDAExecutionProvider" in available:
|
||||
return ["CUDAExecutionProvider", "CPUExecutionProvider"]
|
||||
if want_gpu:
|
||||
print("[scalper][lama] SCALPER_LAMA_DEVICE=gpu mais CUDA indisponible (onnxruntime CPU ?) -> repli CPU", file=sys.stderr)
|
||||
return ["CPUExecutionProvider"]
|
||||
|
||||
def _crop_rect(self, box: tuple[int, int, int, int], img_w: int, img_h: int) -> tuple[int, int, int, int]:
|
||||
"""Crop carré centré sur la boîte, avec contexte (côté >= 2x la boîte et >= min_context),
|
||||
borné à l'image."""
|
||||
|
||||
+6
-1
@@ -148,12 +148,17 @@ class PaddleOCR:
|
||||
if self._engine is None:
|
||||
paddle_lang = _PADDLE_LANGS.get((lang or self.lang), "en")
|
||||
tier = _paddle_tier(paddle_lang)
|
||||
self._engine = _PaddleEngine(
|
||||
kwargs: dict[str, Any] = dict(
|
||||
lang=paddle_lang,
|
||||
use_textline_orientation=True, # texte vertical (manga JP)
|
||||
text_detection_model_name=f"PP-OCRv6_{tier}_det",
|
||||
text_recognition_model_name=f"PP-OCRv6_{tier}_rec",
|
||||
)
|
||||
# SCALPER_PADDLE_DEVICE=gpu:0 (ex. RTX 2060, image Dockerfile.gpu) ; sinon auto (cpu sur l'image CPU)
|
||||
device = os.environ.get("SCALPER_PADDLE_DEVICE", "").strip()
|
||||
if device:
|
||||
kwargs["device"] = device
|
||||
self._engine = _PaddleEngine(**kwargs)
|
||||
results = self._engine.predict(str(image_path))
|
||||
if results is None:
|
||||
return []
|
||||
|
||||
+26
-1
@@ -232,7 +232,7 @@ class TestCropAndMask(unittest.TestCase):
|
||||
self.assertEqual(mask.getpixel((125, 115)), 255)
|
||||
|
||||
|
||||
def _fake_onnxruntime_module(fill_value=200.0, identity=False):
|
||||
def _fake_onnxruntime_module(fill_value=200.0, identity=False, available_providers=None):
|
||||
"""Module onnxruntime factice : session qui renvoie `fill_value` dans le masque et
|
||||
recopopie l'entrée (x255) hors masque, comme le vrai modèle.
|
||||
`identity=True` : simule un modèle no-op (sortie = entrée, delta nul)."""
|
||||
@@ -262,6 +262,7 @@ def _fake_onnxruntime_module(fill_value=200.0, identity=False):
|
||||
|
||||
mod.InferenceSession = FakeSession
|
||||
mod.SessionOptions = SessionOptions
|
||||
mod.get_available_providers = lambda: (available_providers or ["CPUExecutionProvider"])
|
||||
return mod, FakeSession
|
||||
|
||||
|
||||
@@ -284,6 +285,30 @@ class TestLamaInpainter(unittest.TestCase):
|
||||
inp._get_session()
|
||||
self.assertIn("inpaint-lama", str(cm.exception))
|
||||
|
||||
def test_providers_cuda_when_gpu_available(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model = Path(tmp) / "lama_fp32.onnx"
|
||||
model.write_bytes(b"fake")
|
||||
fake_mod, fake_session_cls = _fake_onnxruntime_module(
|
||||
available_providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
|
||||
with mock.patch.dict(sys.modules, {"onnxruntime": fake_mod}):
|
||||
with mock.patch.dict(os.environ, {"SCALPER_LAMA_DEVICE": "gpu"}):
|
||||
inp = LamaInpainter(model_path=model)
|
||||
inp._get_session()
|
||||
self.assertEqual(fake_session_cls.instances[-1].providers,
|
||||
["CUDAExecutionProvider", "CPUExecutionProvider"])
|
||||
|
||||
def test_providers_cpu_fallback_when_cuda_unavailable(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model = Path(tmp) / "lama_fp32.onnx"
|
||||
model.write_bytes(b"fake")
|
||||
fake_mod, fake_session_cls = _fake_onnxruntime_module() # CPU only
|
||||
with mock.patch.dict(sys.modules, {"onnxruntime": fake_mod}):
|
||||
with mock.patch.dict(os.environ, {"SCALPER_LAMA_DEVICE": "gpu"}):
|
||||
inp = LamaInpainter(model_path=model)
|
||||
inp._get_session()
|
||||
self.assertEqual(fake_session_cls.instances[-1].providers, ["CPUExecutionProvider"])
|
||||
|
||||
def test_inpaint_image_composites_only_masked_pixels(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
model = Path(tmp) / "lama_fp32.onnx"
|
||||
|
||||
@@ -205,6 +205,25 @@ class TestPaddleOCRMapping(unittest.TestCase):
|
||||
self.assertEqual(seen["lang"], "japan")
|
||||
self.assertEqual(seen["text_recognition_model_name"], "PP-OCRv6_small_rec", "tiny ne lit pas le japonais")
|
||||
|
||||
def test_device_env_forwarded_to_engine(self):
|
||||
from scalper.ocr import PaddleOCR
|
||||
|
||||
seen = {}
|
||||
|
||||
class FakeEngine:
|
||||
def __init__(self, **kw):
|
||||
seen.update(kw)
|
||||
|
||||
def predict(self, path):
|
||||
return []
|
||||
|
||||
fake_mod = types.ModuleType("paddleocr")
|
||||
fake_mod.PaddleOCR = FakeEngine
|
||||
with mock.patch.dict(sys.modules, {"paddleocr": fake_mod}):
|
||||
with mock.patch.dict(os.environ, {"SCALPER_PADDLE_DEVICE": "gpu:0"}):
|
||||
PaddleOCR(lang="eng").recognize(Path("p.png"))
|
||||
self.assertEqual(seen.get("device"), "gpu:0")
|
||||
|
||||
def test_missing_paddle_raises_clear_error(self):
|
||||
from scalper.ocr import PaddleOCR
|
||||
|
||||
|
||||
Reference in new issue
Block a user