File size: 3,260 Bytes
2cb3b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ─── 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"]