Spaces:
Sleeping
Sleeping
Download app.py from FelipeFavalli/behring-bjj-face-api: direct link, hf CLI and curl.
- Browser
- Download file 7.76 kB
-
https://huggingface.co/spaces/FelipeFavalli/behring-bjj-face-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/FelipeFavalli/behring-bjj-face-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/FelipeFavalli/behring-bjj-face-api/resolve/main/app.py
7.76 kB
| import base64 | |
| import os | |
| import cv2 | |
| import numpy as np | |
| import requests | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from typing import List, Optional | |
| import insightface | |
| from insightface.app import FaceAnalysis | |
| # Initialize FastAPI app | |
| app = FastAPI( | |
| title="InsightFace Centralized Face Recognition API", | |
| description="Stateless cloud microservice for extracting face embeddings and performing attendance checks.", | |
| version="1.0.0" | |
| ) | |
| # Enable CORS for cross-origin frontend requests | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Dummy decorator fallback so code runs seamlessly on CPU hardware | |
| class spaces: | |
| def GPU(func): | |
| return func | |
| # Initialize InsightFace FaceAnalysis | |
| print("Initializing InsightFace FaceAnalysis app...") | |
| try: | |
| import onnxruntime as ort | |
| original_init = ort.InferenceSession.__init__ | |
| def patched_init(self, *args, **kwargs): | |
| if 'sess_options' not in kwargs or kwargs['sess_options'] is None: | |
| opts = ort.SessionOptions() | |
| opts.intra_op_num_threads = 1 | |
| opts.inter_op_num_threads = 1 | |
| opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL | |
| opts.enable_cpu_mem_arena = False | |
| kwargs['sess_options'] = opts | |
| elif isinstance(kwargs['sess_options'], ort.SessionOptions): | |
| kwargs['sess_options'].intra_op_num_threads = 1 | |
| kwargs['sess_options'].inter_op_num_threads = 1 | |
| kwargs['sess_options'].execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL | |
| kwargs['sess_options'].enable_cpu_mem_arena = False | |
| original_init(self, *args, **kwargs) | |
| ort.InferenceSession.__init__ = patched_init | |
| # Root set to /home/user/.insightface matching Docker container path | |
| model_root = os.path.expanduser('/home/user/.insightface') if os.path.exists('/home/user') else os.path.expanduser('~/.insightface') | |
| face_app = FaceAnalysis(name='buffalo_s', root=model_root, providers=['CPUExecutionProvider'], allowed_modules=['detection', 'recognition']) | |
| face_app.prepare(ctx_id=0, det_size=(480, 480)) | |
| print("InsightFace loaded successfully!") | |
| except Exception as e: | |
| print(f"Error loading InsightFace: {e}") | |
| face_app = None | |
| # Pydantic models | |
| class SelfieRequest(BaseModel): | |
| image_base64: str | |
| class StudentReference(BaseModel): | |
| id: str | |
| embedding: List[float] | |
| class GroupPresenceRequest(BaseModel): | |
| group_image_base64: str | |
| students: List[StudentReference] | |
| threshold: Optional[float] = 0.40 | |
| class GDriveUploadRequest(BaseModel): | |
| gdrive_url: str | |
| image_base64: str | |
| filename: str | |
| def decode_base64_to_image(base64_str: str) -> np.ndarray: | |
| try: | |
| if "," in base64_str: | |
| base64_str = base64_str.split(",")[1] | |
| img_bytes = base64.b64decode(base64_str) | |
| nparr = np.frombuffer(img_bytes, np.uint8) | |
| img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) | |
| if img is None: | |
| raise ValueError("CV2 failed to decode image bytes.") | |
| return img | |
| except Exception as e: | |
| raise HTTPException(status_code=400, detail=f"Erro ao processar imagem base64: {str(e)}") | |
| def health_check(): | |
| status = "running" if face_app is not None else "failed_initialization" | |
| return {"status": status, "model": "buffalo_s", "backend": "onnxruntime", "service": "Behring BJJ Face API"} | |
| def extract_embedding(req: SelfieRequest): | |
| if face_app is None: | |
| raise HTTPException(status_code=500, detail="InsightFace não foi inicializado corretamente no servidor.") | |
| try: | |
| img = decode_base64_to_image(req.image_base64) | |
| faces = face_app.get(img) | |
| if not faces: | |
| raise HTTPException(status_code=422, detail="Nenhum rosto foi detectado na foto. Tire uma selfie nítida e bem iluminada.") | |
| largest_face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])) | |
| embedding = largest_face.normed_embedding if hasattr(largest_face, 'normed_embedding') else largest_face.embedding | |
| norm = np.linalg.norm(embedding) | |
| if norm > 0: | |
| embedding = embedding / norm | |
| return { | |
| "embedding": embedding.tolist(), | |
| "confidence": float(largest_face.det_score) | |
| } | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Erro interno de processamento: {str(e)}") | |
| def recognize_presence(req: GroupPresenceRequest): | |
| if face_app is None: | |
| raise HTTPException(status_code=500, detail="InsightFace não foi inicializado corretamente no servidor.") | |
| group_img = decode_base64_to_image(req.group_image_base64) | |
| group_faces = face_app.get(group_img) | |
| if not group_faces: | |
| results = [{"studentId": s.id, "match": False, "confidence": 0} for s in req.students] | |
| return { | |
| "matches": results, | |
| "detected_faces_count": 0, | |
| "warning": "Nenhum rosto detectado na foto do treino." | |
| } | |
| normed_group_embeddings = [] | |
| for g_face in group_faces: | |
| emb = g_face.normed_embedding if hasattr(g_face, 'normed_embedding') else g_face.embedding | |
| norm = np.linalg.norm(emb) | |
| if norm > 0: | |
| normed_group_embeddings.append(emb / norm) | |
| else: | |
| normed_group_embeddings.append(emb) | |
| similarities = [] | |
| for student in req.students: | |
| ref_embedding = np.array(student.embedding, dtype=np.float32) | |
| ref_norm = np.linalg.norm(ref_embedding) | |
| if ref_norm > 0: | |
| ref_embedding = ref_embedding / ref_norm | |
| max_similarity = -1.0 | |
| for g_embedding in normed_group_embeddings: | |
| similarity = float(np.dot(ref_embedding, g_embedding)) | |
| if similarity > max_similarity: | |
| max_similarity = similarity | |
| similarities.append(max_similarity) | |
| results = [] | |
| for i, student in enumerate(req.students): | |
| max_similarity = similarities[i] | |
| match = max_similarity >= req.threshold | |
| pct_score = min(int(max_similarity * 100), 99) if max_similarity > 0 else 0 | |
| if match and max_similarity > 0: | |
| pct_score = max(pct_score, 91) | |
| results.append({ | |
| "studentId": student.id, | |
| "match": match, | |
| "confidence": pct_score | |
| }) | |
| return { | |
| "matches": results, | |
| "detected_faces_count": len(normed_group_embeddings) | |
| } | |
| def upload_to_drive(req: GDriveUploadRequest): | |
| if not req.gdrive_url: | |
| raise HTTPException(status_code=400, detail="URL do Google Drive não configurada.") | |
| try: | |
| payload = {"image_base64": req.image_base64, "filename": req.filename} | |
| res = requests.post(req.gdrive_url, json=payload, timeout=15) | |
| if res.status_code == 200: | |
| try: | |
| return res.json() | |
| except Exception: | |
| return {"success": True, "detail": res.text} | |
| else: | |
| raise HTTPException(status_code=res.status_code, detail=f"Erro do Google Script (HTTP {res.status_code}): {res.text}") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Erro ao enviar para o Google Drive: {str(e)}") | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 7860)) | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=port) |