Spaces:
Sleeping
Sleeping
Commit ·
3665866
1
Parent(s): 17fbed6
Runs everything on CPU
Browse files- Dockerfile +17 -26
- README.md +1 -2
- config.py +2 -2
- handler.py +16 -36
- main.py +0 -7
- requirements.txt +2 -6
Dockerfile
CHANGED
|
@@ -1,40 +1,31 @@
|
|
| 1 |
-
FROM
|
| 2 |
|
| 3 |
-
#
|
| 4 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 5 |
-
python3.10 \
|
| 6 |
-
python3.10-dev \
|
| 7 |
-
python3-pip \
|
| 8 |
build-essential \
|
|
|
|
| 9 |
libglib2.0-0 \
|
| 10 |
libsm6 \
|
| 11 |
libxext6 \
|
| 12 |
-
|
| 13 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
-
update-alternatives --install /usr/bin/python python /usr/bin/python3.10 1
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
|
|
|
| 20 |
RUN pip install --no-cache-dir --upgrade pip && \
|
| 21 |
pip install --no-cache-dir -r requirements.txt
|
| 22 |
|
| 23 |
-
|
| 24 |
-
COPY . .
|
| 25 |
-
|
| 26 |
-
# Copy static ai-images (baked into container for fast local access)
|
| 27 |
-
RUN if [ -d "ai-images" ]; then echo "ai-images directory found"; else echo "WARNING: ai-images directory not found"; fi
|
| 28 |
-
|
| 29 |
-
# Create insightface cache directory
|
| 30 |
-
RUN mkdir -p /tmp/.insightface
|
| 31 |
-
|
| 32 |
-
# Set environment variables
|
| 33 |
-
ENV CUDA_HOME=/usr/local/cuda
|
| 34 |
-
ENV LD_LIBRARY_PATH=${CUDA_HOME}/lib64:${LD_LIBRARY_PATH}
|
| 35 |
-
ENV PATH=${CUDA_HOME}/bin:${PATH}
|
| 36 |
-
ENV INSIGHTFACE_HOME=/tmp/.insightface
|
| 37 |
|
| 38 |
EXPOSE 7860
|
| 39 |
|
| 40 |
-
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
|
| 3 |
+
# Build tools for InsightFace's Cython extension, plus shared libs OpenCV needs
|
| 4 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
|
|
|
|
|
|
|
|
| 5 |
build-essential \
|
| 6 |
+
libgl1 \
|
| 7 |
libglib2.0-0 \
|
| 8 |
libsm6 \
|
| 9 |
libxext6 \
|
| 10 |
+
libxrender1 \
|
| 11 |
+
&& rm -rf /var/lib/apt/lists/*
|
|
|
|
| 12 |
|
| 13 |
+
# Hugging Face Spaces run the container as UID 1000
|
| 14 |
+
RUN useradd -m -u 1000 user
|
| 15 |
+
USER user
|
| 16 |
+
ENV HOME=/home/user \
|
| 17 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 18 |
+
INSIGHTFACE_HOME=/tmp/.insightface \
|
| 19 |
+
MPLCONFIGDIR=/tmp/matplotlib
|
| 20 |
|
| 21 |
+
WORKDIR $HOME/app
|
| 22 |
+
|
| 23 |
+
COPY --chown=user requirements.txt .
|
| 24 |
RUN pip install --no-cache-dir --upgrade pip && \
|
| 25 |
pip install --no-cache-dir -r requirements.txt
|
| 26 |
|
| 27 |
+
COPY --chown=user . .
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
EXPOSE 7860
|
| 30 |
|
| 31 |
+
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -198,8 +198,7 @@ Facematch_Dev/
|
|
| 198 |
|
| 199 |
## Performance Notes
|
| 200 |
|
| 201 |
-
- **
|
| 202 |
-
- **Hugging Face Spaces**: Runs on GPU, much faster for production
|
| 203 |
- **Embedding Extraction**: Run `/api/extract_embeddings` after uploading new images
|
| 204 |
- **Caching**: Embeddings are cached in Azure for faster subsequent queries
|
| 205 |
|
|
|
|
| 198 |
|
| 199 |
## Performance Notes
|
| 200 |
|
| 201 |
+
- **CPU only**: Runs on CPU everywhere (local and Hugging Face Spaces) using `onnxruntime`. The GPU version is kept on the `uses-gpu` branch.
|
|
|
|
| 202 |
- **Embedding Extraction**: Run `/api/extract_embeddings` after uploading new images
|
| 203 |
- **Caching**: Embeddings are cached in Azure for faster subsequent queries
|
| 204 |
|
config.py
CHANGED
|
@@ -14,7 +14,7 @@ class Config:
|
|
| 14 |
AZURE_TRAINING_IMAGES_FOLDER = os.getenv('AZURE_TRAINING_IMAGES_FOLDER', 'koottu-media/ai-images/')
|
| 15 |
|
| 16 |
# Face Recognition Configuration
|
| 17 |
-
INSIGHTFACE_CTX_ID =
|
| 18 |
FACE_EMBEDDING_DIMENSION = 512
|
| 19 |
SIMILARITY_THRESHOLD = float(os.getenv('SIMILARITY_THRESHOLD', '0.5'))
|
| 20 |
|
|
@@ -83,7 +83,7 @@ class DevelopmentConfig(Config):
|
|
| 83 |
class ProductionConfig(Config):
|
| 84 |
"""Production configuration"""
|
| 85 |
FLASK_DEBUG = False
|
| 86 |
-
INSIGHTFACE_CTX_ID =
|
| 87 |
FLASK_SECRET_KEY = os.getenv('FLASK_SECRET_KEY', 'change-this-in-production')
|
| 88 |
|
| 89 |
class TestingConfig(Config):
|
|
|
|
| 14 |
AZURE_TRAINING_IMAGES_FOLDER = os.getenv('AZURE_TRAINING_IMAGES_FOLDER', 'koottu-media/ai-images/')
|
| 15 |
|
| 16 |
# Face Recognition Configuration
|
| 17 |
+
INSIGHTFACE_CTX_ID = -1 # CPU only
|
| 18 |
FACE_EMBEDDING_DIMENSION = 512
|
| 19 |
SIMILARITY_THRESHOLD = float(os.getenv('SIMILARITY_THRESHOLD', '0.5'))
|
| 20 |
|
|
|
|
| 83 |
class ProductionConfig(Config):
|
| 84 |
"""Production configuration"""
|
| 85 |
FLASK_DEBUG = False
|
| 86 |
+
INSIGHTFACE_CTX_ID = -1
|
| 87 |
FLASK_SECRET_KEY = os.getenv('FLASK_SECRET_KEY', 'change-this-in-production')
|
| 88 |
|
| 89 |
class TestingConfig(Config):
|
handler.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
-
os.environ
|
| 3 |
import json
|
| 4 |
import tempfile
|
| 5 |
import numpy as np
|
|
@@ -19,31 +19,15 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
| 19 |
|
| 20 |
class EndpointHandler:
|
| 21 |
def __init__(self, model_dir=None):
|
| 22 |
-
# Initialize FaceAnalysis
|
| 23 |
print("\n" + "="*80)
|
| 24 |
-
print("INITIALIZING FACEANALYSIS")
|
| 25 |
print("="*80)
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
self.app.prepare(ctx_id=0) # 0 = GPU
|
| 32 |
-
print("✅ GPU initialization successful (ctx_id=0)")
|
| 33 |
-
self.gpu_available = True
|
| 34 |
-
except RuntimeError as e:
|
| 35 |
-
# GPU not available, fall back to CPU
|
| 36 |
-
print(f"⚠️ GPU initialization failed: {str(e)[:100]}...")
|
| 37 |
-
print("Falling back to CPU (CPUExecutionProvider)...")
|
| 38 |
-
try:
|
| 39 |
-
self.app = FaceAnalysis(root="/tmp/.insightface", providers=['CPUExecutionProvider'])
|
| 40 |
-
self.app.prepare(ctx_id=-1) # -1 = CPU
|
| 41 |
-
print("✅ CPU initialization successful (ctx_id=-1)")
|
| 42 |
-
self.gpu_available = False
|
| 43 |
-
except Exception as cpu_error:
|
| 44 |
-
print(f"❌ CPU initialization also failed: {cpu_error}")
|
| 45 |
-
raise
|
| 46 |
-
|
| 47 |
print("="*80 + "\n")
|
| 48 |
|
| 49 |
print("=" * 80)
|
|
@@ -86,14 +70,14 @@ class EndpointHandler:
|
|
| 86 |
self.image_cache_max_size = 100 # Max 100 images in memory
|
| 87 |
self.thread_pool = ThreadPoolExecutor(max_workers=8)
|
| 88 |
|
| 89 |
-
# Pre-warm
|
| 90 |
self._prewarm_models()
|
| 91 |
|
| 92 |
def _prewarm_models(self):
|
| 93 |
-
"""
|
| 94 |
try:
|
| 95 |
print("\n" + "="*80)
|
| 96 |
-
mode = "
|
| 97 |
print(f"PRE-WARMING MODELS ({mode} MODE)")
|
| 98 |
print("="*80)
|
| 99 |
start = time.time()
|
|
@@ -506,14 +490,14 @@ class EndpointHandler:
|
|
| 506 |
return None
|
| 507 |
|
| 508 |
def load_image_from_local(self, local_path):
|
| 509 |
-
"""Load
|
| 510 |
try:
|
| 511 |
start = time.time()
|
| 512 |
-
full_path = os.path.join(
|
| 513 |
-
|
| 514 |
if not os.path.exists(full_path):
|
| 515 |
-
print(f"Local image not found: {full_path}")
|
| 516 |
-
return
|
| 517 |
|
| 518 |
image = cv2.imread(full_path)
|
| 519 |
if image is None:
|
|
@@ -533,7 +517,3 @@ class EndpointHandler:
|
|
| 533 |
np_arr = np.frombuffer(data, np.uint8)
|
| 534 |
img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
|
| 535 |
return img # Returns BGR image as expected by OpenCV
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
# Instantiate the handler
|
| 539 |
-
handler = EndpointHandler()
|
|
|
|
| 1 |
import os
|
| 2 |
+
os.environ.setdefault("INSIGHTFACE_HOME", "/tmp/.insightface")
|
| 3 |
import json
|
| 4 |
import tempfile
|
| 5 |
import numpy as np
|
|
|
|
| 19 |
|
| 20 |
class EndpointHandler:
|
| 21 |
def __init__(self, model_dir=None):
|
| 22 |
+
# Initialize FaceAnalysis on CPU
|
| 23 |
print("\n" + "="*80)
|
| 24 |
+
print("INITIALIZING FACEANALYSIS (CPU)")
|
| 25 |
print("="*80)
|
| 26 |
+
|
| 27 |
+
self.app = FaceAnalysis(root=os.environ["INSIGHTFACE_HOME"], providers=['CPUExecutionProvider'])
|
| 28 |
+
self.app.prepare(ctx_id=-1) # -1 = CPU
|
| 29 |
+
print("✅ CPU initialization successful (ctx_id=-1)")
|
| 30 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
print("="*80 + "\n")
|
| 32 |
|
| 33 |
print("=" * 80)
|
|
|
|
| 70 |
self.image_cache_max_size = 100 # Max 100 images in memory
|
| 71 |
self.thread_pool = ThreadPoolExecutor(max_workers=8)
|
| 72 |
|
| 73 |
+
# Pre-warm models
|
| 74 |
self._prewarm_models()
|
| 75 |
|
| 76 |
def _prewarm_models(self):
|
| 77 |
+
"""Run a dummy inference on startup so the first real request doesn't pay ONNX session warm-up."""
|
| 78 |
try:
|
| 79 |
print("\n" + "="*80)
|
| 80 |
+
mode = "CPU"
|
| 81 |
print(f"PRE-WARMING MODELS ({mode} MODE)")
|
| 82 |
print("="*80)
|
| 83 |
start = time.time()
|
|
|
|
| 490 |
return None
|
| 491 |
|
| 492 |
def load_image_from_local(self, local_path):
|
| 493 |
+
"""Load an ai-images file from the app directory, falling back to the same path in Blob Storage."""
|
| 494 |
try:
|
| 495 |
start = time.time()
|
| 496 |
+
full_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), local_path)
|
| 497 |
+
|
| 498 |
if not os.path.exists(full_path):
|
| 499 |
+
print(f"Local image not found: {full_path}, loading from Blob Storage")
|
| 500 |
+
return self.load_image_from_blob(self.container_client.get_blob_client(local_path))
|
| 501 |
|
| 502 |
image = cv2.imread(full_path)
|
| 503 |
if image is None:
|
|
|
|
| 517 |
np_arr = np.frombuffer(data, np.uint8)
|
| 518 |
img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
|
| 519 |
return img # Returns BGR image as expected by OpenCV
|
|
|
|
|
|
|
|
|
|
|
|
main.py
CHANGED
|
@@ -10,13 +10,6 @@ from datetime import datetime
|
|
| 10 |
from handler import EndpointHandler
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
-
# Run diagnostics on startup (safe import)
|
| 14 |
-
try:
|
| 15 |
-
from debug import run_all_checks
|
| 16 |
-
run_all_checks()
|
| 17 |
-
except Exception as e:
|
| 18 |
-
print(f"⚠️ Diagnostics failed to run: {e}")
|
| 19 |
-
|
| 20 |
app = FastAPI()
|
| 21 |
|
| 22 |
# Enable CORS
|
|
|
|
| 10 |
from handler import EndpointHandler
|
| 11 |
import numpy as np
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
app = FastAPI()
|
| 14 |
|
| 15 |
# Enable CORS
|
requirements.txt
CHANGED
|
@@ -1,15 +1,11 @@
|
|
| 1 |
azure-storage-blob
|
| 2 |
-
onnxruntime
|
| 3 |
-
insightface
|
| 4 |
opencv-python-headless
|
| 5 |
-
flask
|
| 6 |
-
flask-cors
|
| 7 |
numpy<2.0
|
| 8 |
scipy
|
| 9 |
pillow
|
| 10 |
requests
|
| 11 |
scikit-learn
|
| 12 |
-
pandas
|
| 13 |
fastapi
|
| 14 |
uvicorn
|
| 15 |
-
|
|
|
|
| 1 |
azure-storage-blob
|
| 2 |
+
onnxruntime==1.19.2
|
| 3 |
+
insightface==0.7.3
|
| 4 |
opencv-python-headless
|
|
|
|
|
|
|
| 5 |
numpy<2.0
|
| 6 |
scipy
|
| 7 |
pillow
|
| 8 |
requests
|
| 9 |
scikit-learn
|
|
|
|
| 10 |
fastapi
|
| 11 |
uvicorn
|
|
|