# ByT5 Lacuna Restorer — Cloud Run service
# CPU-only, min-instances=0.  Autoscales to zero between calls.
# Expected cost: ~€0-3/mo at current traffic.
#
# Build:
#   docker build -t byt5-restorer .
#
# The container refuses to start without MODEL_URI in its environment —
# there is no default checkpoint, because the service labels every response
# with the fine-tuned adapter's name and must not silently serve other
# weights. Env contract and deploy command: README.md alongside this file.

FROM python:3.11-slim

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    # Point HuggingFace at a writable path. The previous default
    # (~/.cache/huggingface) lived under /home/svc, which `useradd --system`
    # does *not* create — the runtime then crashed with
    # `PermissionError at /home/svc when downloading google/byt5-small`.
    HF_HOME=/app/.hf-cache \
    TRANSFORMERS_OFFLINE=0

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Pre-download a checkpoint into the image's HF cache so cold starts don't
# have to hit HuggingFace (~300 MB for byt5-small-sized weights; bakes
# deterministically). Build-time cache warming ONLY — it does not choose
# what the service serves. That is the runtime MODEL_URI env var, and the
# prebake saves the startup download only when the two match, so pass
#   --build-arg PREBAKE_MODEL_URI=<same value you deploy as MODEL_URI>
ARG PREBAKE_MODEL_URI=google/byt5-small
RUN mkdir -p ${HF_HOME} && \
    python -c "from transformers import AutoTokenizer, AutoModelForSeq2SeqLM; \
        AutoTokenizer.from_pretrained('${PREBAKE_MODEL_URI}'); \
        AutoModelForSeq2SeqLM.from_pretrained('${PREBAKE_MODEL_URI}')"

COPY main.py .

# Non-root, but with a real home so HF_HOME-style downloads (if a future
# MODEL_URI bypasses the pre-bake) still have somewhere to land.
RUN groupadd --system svc && useradd --system --gid svc -d /app svc && \
    chown -R svc:svc /app
USER svc

EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
