FROM python:3.10-slim

ARG TORCH_VARIANT=cpu
ARG TORCH_INDEX=https://download.pytorch.org/whl/${TORCH_VARIANT}

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 && rm -rf /var/lib/apt/lists/*

RUN pip install --no-cache-dir "typing-extensions==4.12.2" "numpy==2.2.6"

RUN pip install --no-cache-dir torch torchvision --index-url ${TORCH_INDEX}

RUN pip install --no-cache-dir --no-deps basicsr==1.4.2 realesrgan==0.3.0 gfpgan==1.3.8 facexlib==0.3.0 && \
    pip install --no-cache-dir "numpy==2.2.6" "opencv-python-headless==5.0.0.93" addict future lmdb Pillow pyyaml \
      requests scikit-image scipy tqdm filterpy numba fastapi "uvicorn[standard]" python-multipart

RUN BASICSR_DEG=$(python -c "import basicsr; import os; print(os.path.join(os.path.dirname(basicsr.__file__), 'data', 'degradations.py'))" 2>/dev/null) || \
    BASICSR_DEG=$(find /usr/local/lib/python3.10 -path "*/basicsr/data/degradations.py" 2>/dev/null | head -1) && \
    if [ -n "$BASICSR_DEG" ]; then \
      sed -i 's/from torchvision.transforms.functional_tensor/from torchvision.transforms.functional/g' "$BASICSR_DEG" && \
      echo "basicsr patch applied to $BASICSR_DEG"; \
    else \
      echo "basicsr degradations.py not found, skipping patch"; \
    fi

COPY app.py ./
COPY vendor/ ./vendor/

ENV PHOTO_AI_MODELS_DIR=/models
ENV MODEL_PATH=/models/RealESRGAN_x2plus.pth

VOLUME /models

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