# Dockerfile optimized for Hugging Face Spaces FROM python:3.11-slim # Set environment variables for Hugging Face Spaces ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 ENV DEBIAN_FRONTEND=noninteractive # Hugging Face Spaces specific ENV GRADIO_SERVER_NAME="0.0.0.0" ENV GRADIO_SERVER_PORT=7860 # Set working directory WORKDIR /app # Install system dependencies required for OpenCV and other packages RUN apt-get update && apt-get install -y \ libgl1 \ libglib2.0-0 \ libsm6 \ libxext6 \ libxrender-dev \ libgomp1 \ libgtk-3-0 \ libavcodec-dev \ libavformat-dev \ libswscale-dev \ libgstreamer-plugins-base1.0-dev \ libgstreamer1.0-dev \ libpng-dev \ libjpeg-dev \ libopenexr-dev \ libtiff-dev \ libwebp-dev \ curl \ wget \ git \ && rm -rf /var/lib/apt/lists/* # Copy requirements first for better Docker layer caching COPY requirements.txt . # Install Python dependencies RUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r requirements.txt # Copy application files COPY main.py . COPY start_backend.py . # Create directories for temporary files and models RUN mkdir -p /tmp/uploads /tmp/models /tmp/logs # Pre-download YOLOv8 model to avoid download during runtime # This helps with cold start times on Hugging Face Spaces RUN python -c "from ultralytics import YOLO; model = YOLO('yolov8s.pt'); print('YOLOv8 model downloaded successfully')" # Expose port 7860 (required for Hugging Face Spaces) EXPOSE 7860 # Create startup script for Hugging Face Spaces RUN echo '#!/bin/bash\n\ echo "🚀 Starting Crowd Detection API on Hugging Face Spaces..."\n\ echo "📊 Loading AI models..."\n\ python -c "from ultralytics import YOLO; YOLO(\"yolov8s.pt\")" 2>/dev/null || echo "Model already cached"\n\ echo "✅ Models loaded successfully"\n\ echo "🌐 Starting FastAPI server on port 7860..."\n\ exec python -m uvicorn main:app --host 0.0.0.0 --port 7860 --workers 1\n' > /app/start.sh # Make startup script executable # RUN chmod +x /app/start.sh # Start the application CMD ["python", "start_backend.py"]