FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/library/python:3.12-slim-bookworm

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \
    DEEPFACE_HOME=/root/.deepface \
    TF_CPP_MIN_LOG_LEVEL=2

WORKDIR /opt/people-flow

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

COPY requirements-docker.txt ./requirements-docker.txt

RUN python -m pip install --upgrade pip setuptools wheel && \
    pip install "numpy<2" && \
    pip install --extra-index-url https://download.pytorch.org/whl/cpu \
        "torch==2.6.0+cpu" "torchvision==0.21.0+cpu" && \
    pip install "tensorflow==2.16.1" "tf-keras==2.16.0" && \
    pip install -r requirements-docker.txt

COPY . .
COPY scripts/docker-entrypoint.sh /opt/people-flow/scripts/docker-entrypoint.sh

RUN test -f /opt/people-flow/weights/yolo11n.pt && \
    test -f /opt/people-flow/weights/deepface/age_model_weights.h5 && \
    test -f /opt/people-flow/weights/deepface/gender_model_weights.h5 && \
    test -f /opt/people-flow/weights/deepface/retinaface.h5 && \
    mkdir -p /root/.deepface/weights /opt/people-flow/outputs && \
    cp /opt/people-flow/weights/deepface/*.h5 /root/.deepface/weights/ && \
    chmod +x /opt/people-flow/scripts/docker-entrypoint.sh

EXPOSE 18082

HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:18082/api/manage/health', timeout=3).read()" || exit 1

ENTRYPOINT ["/opt/people-flow/scripts/docker-entrypoint.sh"]
