Spaces:
Paused
Paused
Download app.py from iftikharfoaid/foaid: direct link, hf CLI and curl.
- Browser
- Download file 2.48 kB
-
https://huggingface.co/spaces/iftikharfoaid/foaid/resolve/main/app.py
- Command line
-
hf download hf://spaces/iftikharfoaid/foaid/app.py
-
curl -L -o app.py https://huggingface.co/spaces/iftikharfoaid/foaid/resolve/main/app.py
2.48 kB
| """FOAID Memories — free face matching service (face_recognition / dlib). | |
| Stateless: WordPress sends a photo, this returns a 128-number "face code" for every face in it. | |
| Nothing is stored here, so the free Hugging Face Space can sleep / restart without losing anything. | |
| """ | |
| import base64, hmac, io, os, struct, time | |
| import face_recognition | |
| import numpy as np | |
| from fastapi import FastAPI, Header, HTTPException, Request | |
| from PIL import Image, ImageOps | |
| KEY = os.environ.get("FACE_KEY", "") | |
| MAX_BYTES = 20 * 1024 * 1024 | |
| app = FastAPI(title="FOAID face service", docs_url=None, redoc_url=None) | |
| def home(): | |
| return {"ok": True, "service": "foaid-face", "version": 1, "key_set": bool(KEY)} | |
| def _load(raw: bytes, max_side: int): | |
| try: | |
| im = Image.open(io.BytesIO(raw)) | |
| im = ImageOps.exif_transpose(im).convert("RGB") | |
| except Exception: | |
| raise HTTPException(400, "Not an image") | |
| scale = 1.0 | |
| if max(im.size) > max_side: | |
| scale = max_side / max(im.size) | |
| im = im.resize((round(im.width * scale), round(im.height * scale)), Image.LANCZOS) | |
| return np.asarray(im), scale | |
| async def encode(request: Request, mode: str = "photo", x_key: str = Header(default="")): | |
| if not KEY or not hmac.compare_digest(x_key, KEY): | |
| raise HTTPException(401, "Bad key") | |
| raw = await request.body() | |
| if not raw or len(raw) > MAX_BYTES: | |
| raise HTTPException(400, "Send the image bytes (max 20 MB)") | |
| t0 = time.time() | |
| selfie = mode == "selfie" | |
| img, scale = _load(raw, 1024 if selfie else 1600) | |
| # upsample once: finds smaller faces in group / crowd photos | |
| boxes = face_recognition.face_locations(img, number_of_times_to_upsample=1, model="hog") | |
| if selfie and boxes: | |
| boxes = [max(boxes, key=lambda b: (b[2] - b[0]) * (b[1] - b[3]))] # the biggest face = the person taking the selfie | |
| encs = face_recognition.face_encodings(img, boxes, num_jitters=3 if selfie else 1, model="large") | |
| faces = [] | |
| for (top, right, bottom, left), e in zip(boxes, encs): | |
| x, y, w, h = (round(v / scale) for v in (left, top, right - left, bottom - top)) | |
| faces.append({ | |
| "box": [x, y, w, h], | |
| "q": w, # face width in original pixels (small = far away = blurrier code) | |
| "enc": base64.b64encode(struct.pack("<128f", *e.astype(np.float32))).decode(), | |
| }) | |
| return {"faces": faces, "ms": round((time.time() - t0) * 1000)} | |