[Python] How can I run DeepFace in a docker container on a mac?

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to install deepface in docker container to do image comparison and I am close to getting it to run... however, I think I am probably missing dependencies... but cannot figure out which ones I need.

    In my main.py... If I comment this line out the app starts up and runs... when I uncomment it hangs

    from deepface import DeepFace

    I am running on a mac book with Docker desktop installed and using VS Code. (latest version for all)

    .devcontainer/devcontainer.json

    {
    "name": "AI Devcontainer",
    "dockerComposeFile": "../docker-compose.yml",
    "service": "rp",
    "workspaceFolder": "/usr/src/app",
    "postCreateCommand": "pip install -r requirements.txt"
    }



    ./docker-compose.yml

    services:
    rp:
    container_name: ai
    platform: linux/amd64
    build: .
    command: sleep infinity
    networks:
    - RP
    volumes:
    - .:/usr/src/app
    ports:
    - '8000:8000'

    networks:
    RP:
    external: true


    ./Dockerfile

    # Use the official Python image from the DockerHub
    FROM python:3.9-slim

    # Set the working directory in the container
    WORKDIR /app

    # Install system dependencies required for DeepFace
    # Update package list and install dependencies
    RUN apt update && apt install -y \
    tzdata \
    libgl1-mesa-glx \
    libegl1-mesa \
    libxrandr2 \
    libxss1 \
    libxcursor1 \
    libxcomposite1 \
    libasound2 \
    libxi6 \
    libxtst6 \
    curl \
    ffmpeg \
    git \
    nano \
    gnupg2 \
    libsm6 \
    wget \
    unzip \
    libxcb-icccm4 \
    libxkbcommon-x11-0 \
    libxcb-keysyms1 \
    libxcb-render0 \
    libxcb-render-util0 \
    libxcb-image0 \
    python3 \
    python3-pip

    # Install required Qt and X11 libraries
    RUN apt update && apt install -y \
    libx11-xcb1 \
    libxcb1 \
    libxcomposite1 \
    libxkbcommon-x11-0 \
    libxkbcommon0 \
    libxcb-cursor0 \
    libxcb-shape0 \
    libxcb-shm0 \
    libxcb-sync1 \
    libxcb-xfixes0 \
    libxcb-xinerama0 \
    libxcb-xinput0 \
    libxcb-xkb1


    # Upgrade pip and install required Python packages
    RUN python -m pip install --upgrade pip
    RUN python -m pip install \
    onnxruntime==1.15.1 \
    numpy==1.21.6 \
    h5py \
    numexpr \
    protobuf==3.20.2 \
    opencv-python==4.8.0.74 \
    opencv-contrib-python==4.8.0.74 \
    pyqt6==6.5.1 \
    onnx==1.14.0 \
    torch==1.13.1 \
    torchvision==0.14.1


    # Install dependencies
    COPY requirements.txt ./
    RUN pip install --no-cache-dir -r requirements.txt

    # Copy the rest of the application code into the container
    COPY . .

    # Expose port 8000 for the FastAPI app
    EXPOSE 8000

    # Command to run FastAPI with Uvicorn
    CMD ["sleep", "infinity"]


    ./requirements.txt

    fastapi
    uvicorn
    requests

    deepface
    flask
    numpy
    pandas
    tensorflow-cpu
    gunicorn
    pillow
    opencv-python


    I load the devcontainer in VS Code, the container builds and I see this in Docker desktop



    I execute `` the container spits out this and then hangs

    root@1f6928173e34:/usr/src/app# uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
    INFO: Will watch for changes in these directories: ['/usr/src/app']
    INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
    INFO: Started reloader process [1104] using StatReload
    INFO:numexpr.utils:NumExpr defaulting to 8 threads.


    main.py

    import logging
    logging.basicConfig(level=logging.DEBUG)

    from fastapi import FastAPI, HTTPException
    import uvicorn
    import base64
    from typing import List, Dict, Union

    # THIS IS THE LINE THAT IS CAUSING ISSUES
    # If I comment it out... the app starts up and runs... uncomment it hangs
    from deepface import DeepFace


    app = FastAPI(title="RP AI Documentation", docs_url="/api-docs")

    @app.on_event("startup")
    async def startup_event():
    print("Starting up...")
    # Simulate any heavy lifting during startup if needed
    print("Startup finished!")

    if __name__ == "__main__":
    print("Starting app...")
    uvicorn.run(app, host="0.0.0.0", port=8000)
    print("App started!")

    # Function to process the images and perform the comparison using DeepFace
    def process_and_compare_images(images: List[Dict[str, Union[str, int]]]) -> bool:
    match = none
    return match


    @app.post("/compare", tags=["AI"])
    def compare(images: List[Dict[str, Union[str, int]]]):
    try:
    # Call the function to process images and compare
    match_result = {}
    match_result = process_and_compare_images(images)

    # If match is None or an unexpected outcome, handle it gracefully
    if match_result is None:
    return {"match_results": "No comparison was made."}
    return {"match_results": match_result}

    except HTTPException as e:
    raise e
    except Exception as e:
    raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")



    I also looked up this:

    Use the Latest TensorFlow Version with the tensorflow-cpu Package

    Ensure you’re installing the latest TensorFlow CPU version, which should automatically be compiled without AVX support.

    TRY 1

    Put this in Dockerfile

    # Use the official Python image from the DockerHub
    FROM python:3.9-slim
    FROM serengil/deepface


    Ran this:

    uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload


    got this:

    INFO: Will watch for changes in these directories: ['/usr/src/app']
    INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
    INFO: Started reloader process [521] using StatReload
    INFO: Started server process [523]
    INFO: Waiting for application startup.
    Starting up...
    Startup finished!


    Uncommented this line from deepface import DeepFace in main.py

    got this:

    WARNING: StatReload detected changes in 'app/main.py'. Reloading...
    INFO: Shutting down
    INFO: Waiting for application shutdown.
    INFO: Application shutdown complete.
    INFO: Finished server process [523]
    The TensorFlow library was compiled to use AVX instructions, but these aren't available on your machine.

    Continue reading...

Compartilhe esta Página