Spaces:
Running
Running
| from flask import Flask, request, jsonify | |
| import cv2 | |
| import numpy as np | |
| from huggingface_hub import hf_hub_download | |
| import os | |
| app = Flask(__name__) | |
| # Auto-download YuNet model from official HF repo (only once, cached after) | |
| model_filename = "face_detection_yunet_2023mar.onnx" | |
| model_path = hf_hub_download( | |
| repo_id="opencv/face_detection_yunet", | |
| filename=model_filename | |
| ) | |
| # Initialize YuNet detector | |
| face_detector = cv2.FaceDetectorYN_create( | |
| model_path, | |
| "", | |
| (320, 320), # input size | |
| 0.87, # score threshold (adjust if too strict/loose) | |
| 0.3, # NMS threshold | |
| 5000 # top K | |
| ) | |
| def home(): | |
| return jsonify({ | |
| "status": "API is running", | |
| "usage": "POST a JPEG image to /detect with form-data key 'image'", | |
| "response": "Returns {'has_face': true/false, 'count': number}" | |
| }) | |
| def detect(): | |
| if 'image' not in request.files: | |
| return jsonify({"error": "No 'image' file in request"}), 400 | |
| file = request.files['image'] | |
| if file.filename == '': | |
| return jsonify({"error": "No selected file"}), 400 | |
| filestr = file.read() | |
| npimg = np.frombuffer(filestr, np.uint8) | |
| img = cv2.imdecode(npimg, cv2.IMREAD_COLOR) | |
| if img is None: | |
| return jsonify({"error": "Invalid or corrupted image"}), 400 | |
| # Set input size to match the uploaded image | |
| height, width = img.shape[:2] | |
| face_detector.setInputSize((width, height)) | |
| # Run detection | |
| _, faces = face_detector.detect(img) | |
| has_face = faces is not None and len(faces) > 0 | |
| result = { | |
| "has_face": has_face, | |
| "count": len(faces) if faces is not None else 0, | |
| "message": "Face detected" if has_face else "No face detected" | |
| } | |
| return jsonify(result) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860, debug=True) |