# ─── Stage 1: Base Image ─────────────────────────────────────────────────── FROM python:3.10-slim # Set working directory WORKDIR /app # ─── Environment Variables ───────────────────────────────────────────────── # Prevent Python from writing .pyc files ENV PYTHONDONTWRITEBYTECODE=1 # Prevent Python from buffering stdout/stderr ENV PYTHONUNBUFFERED=1 # HuggingFace Spaces runs on port 7860 ENV PORT=7860 # Pin CPU threads — prevents over-subscription on HF free-tier (2 vCPUs) ENV OMP_NUM_THREADS=2 ENV MKL_NUM_THREADS=2 # ─── Create a non-root user FIRST (HuggingFace requirement) ──────────────── RUN useradd -m -u 1000 appuser # ─── Install System Dependencies ─────────────────────────────────────────── RUN apt-get update && apt-get install -y --no-install-recommends \ libglib2.0-0 \ libsm6 \ libxrender1 \ libxext6 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* # ─── Install Python Dependencies ─────────────────────────────────────────── COPY requirements.txt . # Use CPU-only PyTorch index to keep image lean and avoid CUDA download timeouts RUN pip install --no-cache-dir \ --extra-index-url https://download.pytorch.org/whl/cpu \ -r requirements.txt # ─── Copy Application Files ──────────────────────────────────────────────── COPY app.py . COPY cifar10_model.pth . COPY templates/ ./templates/ # ─── Fix file ownership so appuser can read all files ────────────────────── RUN chown -R appuser:appuser /app # ─── Switch to non-root user ─────────────────────────────────────────────── USER appuser # ─── Expose Port ─────────────────────────────────────────────────────────── EXPOSE 7860 # ─── Launch with Gunicorn (production WSGI server) ───────────────────────── # --worker-class gthread: Uses a threaded worker so the heartbeat thread # stays alive during long CPU inference (sync workers block the heartbeat # and get killed by the arbiter even when timeout is set high). # --threads 2: One thread handles the request, the other keeps heartbeat alive. # --timeout 300: Safety net for very slow inference on free-tier CPUs. # --preload: Load the model once before forking (saves memory). CMD ["gunicorn", \ "--bind", "0.0.0.0:7860", \ "--workers", "1", \ "--worker-class", "gthread", \ "--threads", "2", \ "--timeout", "300", \ "--preload", \ "--log-level", "info", \ "app:app"]