background-removal / Dockerfile
sdragly's picture
Segmentation model
f952998
FROM python:3.11-slim
# System deps for Pillow / onnxruntime / rembg
RUN apt-get update && apt-get install -y --no-install-recommends \
libgl1 \
libglib2.0-0 \
&& rm -rf /var/lib/apt/lists/*
# HF Spaces runs containers as a non-root user with uid 1000.
# Create a matching user so file ownership and the model cache Just Work.
RUN useradd -m -u 1000 user
USER user
ENV PATH="/home/user/.local/bin:$PATH"
ENV HOME=/home/user
ENV U2NET_HOME=/home/user/.u2net
WORKDIR /app
# Install Python deps first so this layer caches across code edits.
# CPU-only torch from the dedicated index shaves ~600MB vs the default
# CUDA wheel, which matters for HF's free tier image size limit.
COPY --chown=user space/requirements.txt .
RUN pip install --no-cache-dir --user \
--index-url https://download.pytorch.org/whl/cpu \
torch
RUN pip install --no-cache-dir --user -r requirements.txt
# Pre-download models so the first request isn't slow and so the
# weights live in the image layer (no re-download on Space restart).
RUN python -c "from rembg import new_session; new_session('isnet-general-use')"
RUN python -c "from transformers import pipeline; pipeline('mask-generation', model='Zigeng/SlimSAM-uniform-77')"
# Backend — FastAPI app serves both /remove-bg and the static frontend.
COPY --chown=user space/app.py .
# Frontend — served by the same FastAPI process via StaticFiles mount.
COPY --chown=user index.html style.css ./
COPY --chown=user js ./js
# HF Spaces uses port 7860 by default for Docker Spaces.
EXPOSE 7860
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]