Spaces:
Sleeping
Sleeping
Sync from GitHub via hub-sync
Browse filesFiles changed (7)
75 unmodified lines7677787980818214 unmodified lines97989910010110275 unmodified linesProtected endpoints require a bearer token. The default demo credentials are`demo` / `demo123`; override them with `FACEVERIFICATION_DEMO_USERNAME` and`FACEVERIFICATION_DEMO_PASSWORD` in `.env`.```bashcurl -X POST http://localhost:8000/auth/login \14 unmodified lines- `POST /persons`: enrolls a known person from an uploaded image and form `name`.- `POST /verify`: verifies whether an uploaded face matches a known person.## Deployment NotesFor API deployments, the recommended baseline is the FastAPI container running75 unmodified lines7677787980818283848586878889909114 unmodified lines10610710810911011111211311475 unmodified linesProtected endpoints require a bearer token. The default demo credentials are`demo` / `demo123`; override them with `FACEVERIFICATION_DEMO_USERNAME` and`FACEVERIFICATION_DEMO_PASSWORD` in `.env`. The JWT secret is also configurableand should be changed outside local demos.```envFACEVERIFICATION_DEMO_USERNAME=demoFACEVERIFICATION_DEMO_PASSWORD=demo123FACEVERIFICATION_JWT_SECRET_KEY=replace-this-with-a-long-random-secretFACEVERIFICATION_JWT_ACCESS_TOKEN_EXPIRE_MINUTES=60FACEVERIFICATION_MAX_UPLOAD_BYTES=5242880``````bashcurl -X POST http://localhost:8000/auth/login \14 unmodified lines- `POST /persons`: enrolls a known person from an uploaded image and form `name`.- `POST /verify`: verifies whether an uploaded face matches a known person.Both face endpoints return an annotated image by default. Add`?include_image=false` when the client only needs the JSON result.## Deployment NotesFor API deployments, the recommended baseline is the FastAPI container running
18 unmodified lines19202122232418 unmodified linesjwt_secret_key: str = "change-me-in-production-demo-secret-32-bytes-min"jwt_algorithm: str = "HS256"jwt_access_token_expire_minutes: int = 60model_config = SettingsConfigDict(env_file=".env",18 unmodified lines1920212223242518 unmodified linesjwt_secret_key: str = "change-me-in-production-demo-secret-32-bytes-min"jwt_algorithm: str = "HS256"jwt_access_token_expire_minutes: int = 60max_upload_bytes: int = 5 * 1024 * 1024model_config = SettingsConfigDict(env_file=".env",
12345678910 unmodified lines2021222324252627282930311 unmodified line3334353637383940414243444546474816 unmodified lines6566676869707172737475767778798010 unmodified lines919293949596979899100101102103104"""Face detection and embedding extraction utilities.This module centralizes the computer vision models used by the application:MTCNN detects faces and draws bounding boxes, while FaceNet converts a detectedface into a normalized embedding suitable for vector search."""from collections.abc import Sequence10 unmodified linesclass ImageProcessor:"""Detect faces and generate FaceNet embeddings.The processor owns the model lifecycle for MTCNN and InceptionResnetV1. Itaccepts explicit configuration for tests or experiments, and falls back toapplication settings when arguments are omitted."""def __init__(self,1 unmodified linemtcnn_thresholds: Sequence[float] | None = None,facenet_pretrained: str | None = None,):"""Initialize face detection and embedding models.Args:device: Device used for model inference. Use `"auto"` to selectCUDA when available, otherwise CPU.mtcnn_thresholds: Detection thresholds for the three MTCNN stages.facenet_pretrained: Pretrained FaceNet weights identifier.Raises:ValueError: If `device` is not `"auto"`, `"cpu"`, or `"cuda"`."""if device is None:device = settings.device16 unmodified linesself.facenet = InceptionResnetV1(pretrained=facenet_pretrained).eval().to(self.device)def get_embedding(self, image: Image.Image) -> torch.Tensor:"""Return a normalized embedding for the detected face in an image.Args:image: PIL image containing a face.Returns:A one-dimensional normalized FaceNet embedding tensor.Raises:FaceNotDetectedError: If no face can be detected in the image."""face_tensor = self.mtcnn(image)if face_tensor is None:10 unmodified linesreturn features.squeeze(0)def detect_faces(self, image: Image.Image) -> tuple[Image.Image, bool]:"""Draw detected face bounding boxes on an image.Args:image: PIL image to inspect and annotate.Returns:A tuple with the annotated image and a boolean indicating whether atleast one face was detected."""boxes, probs = self.mtcnn.detect(image)123410 unmodified lines151617181920211 unmodified line23242526272829303132333416 unmodified lines5152535455565758596061626364656610 unmodified lines77787980818283848586878889"""Face detection and FaceNet embedding utilities."""from collections.abc import Sequence10 unmodified linesclass ImageProcessor:"""Wrap MTCNN detection and FaceNet embedding extraction."""def __init__(self,1 unmodified linemtcnn_thresholds: Sequence[float] | None = None,facenet_pretrained: str | None = None,):"""Load models using explicit values or application settings.Args:device: Inference device. Use `"auto"` to prefer CUDA when available.mtcnn_thresholds: Detection thresholds for the three MTCNN stages.facenet_pretrained: Pretrained FaceNet weights name."""if device is None:device = settings.device16 unmodified linesself.facenet = InceptionResnetV1(pretrained=facenet_pretrained).eval().to(self.device)def get_embedding(self, image: Image.Image) -> torch.Tensor:"""Return a normalized FaceNet embedding for the detected face.Args:image: PIL image containing a detectable face.Returns:One normalized FaceNet embedding tensor.Raises:FaceNotDetectedError: If MTCNN cannot extract a face."""face_tensor = self.mtcnn(image)if face_tensor is None:10 unmodified linesreturn features.squeeze(0)def detect_faces(self, image: Image.Image) -> tuple[Image.Image, bool]:"""Draw face boxes and return whether any face was found.Args:image: PIL image to inspect and annotate.Returns:The annotated image and a flag indicating if at least one face was found."""boxes, probs = self.mtcnn.detect(image)
123456789107 unmodified lines181920212223242526272829301 unmodified line32333435363738394041424344454613 unmodified lines606162636465666768697071727 unmodified lines808182838485868788899091929394959697"""Vector database adapter for face embedding storage and lookup.This module wraps ChromaDB behind a small project-specific interface. The restof the application only needs to add face embeddings and query the neareststored embedding, while this class owns the Chroma collection setup and resultfiltering."""import uuidfrom collections.abc import Mapping7 unmodified linesclass VectorDB:"""Store and query face embeddings in a ChromaDB collection.The collection is configured with the selected HNSW distance metric and canrun either in memory or against a persistent directory when one is provided.Query results are post-processed with NumPy so the service layer receives asimple `(metadata, distance)` pair."""def __init__(self,1 unmodified linename_collection: str | None = None,persist_directory: str | None = None,):"""Initialize the ChromaDB client and face embeddings collection.Args:distance_metric: HNSW distance metric used by ChromaDB. Commonvalues are `"l2"`, `"cosine"`, and `"ip"`.name_collection: Name of the collection that stores faceembeddings.persist_directory: Optional directory where ChromaDB should persistdata. When omitted, the database runs in memory."""if distance_metric is None:distance_metric = settings.vector_db_distance_metric13 unmodified lines)def add_embedding(self, embedding: np.ndarray, metadata: Mapping[str, Any]) -> None:"""Add one face embedding and its metadata to the collection.Args:embedding: Face embedding vector produced by the face recognitionmodel.metadata: Metadata associated with the embedding, such as theperson's name."""self.collection.add(embeddings=[embedding],7 unmodified linesthreshold: float | None = None,n_results: int | None = None,) -> tuple[Mapping[str, Any] | None, float]:"""Find the closest stored embedding within the configured threshold.Args:embedding: Query embedding vector to compare against storedembeddings.threshold: Maximum Euclidean distance accepted as a match.n_results: Number of nearest ChromaDB candidates to inspect.Returns:A tuple containing the matched metadata and its distance. If nocandidate is within the threshold, metadata is `None` and the bestdistance is still returned."""if threshold is None:threshold = settings.face_match_threshold12347 unmodified lines121314151617181 unmodified line20212223242526272829303113 unmodified lines45464748495051525354557 unmodified lines63646566676869707172737475767778"""Small ChromaDB adapter for face embedding storage and lookup."""import uuidfrom collections.abc import Mapping7 unmodified linesclass VectorDB:"""Store face embeddings and query the nearest known identity."""def __init__(self,1 unmodified linename_collection: str | None = None,persist_directory: str | None = None,):"""Create an in-memory or persistent Chroma collection.Args:distance_metric: Chroma HNSW metric, such as `"l2"` or `"cosine"`.name_collection: Collection name for stored face embeddings.persist_directory: Directory for persistent storage, or `None` for memory."""if distance_metric is None:distance_metric = settings.vector_db_distance_metric13 unmodified lines)def add_embedding(self, embedding: np.ndarray, metadata: Mapping[str, Any]) -> None:"""Store one embedding with its metadata.Args:embedding: Face embedding vector.metadata: Data associated with the embedding, such as a person's name."""self.collection.add(embeddings=[embedding],7 unmodified linesthreshold: float | None = None,n_results: int | None = None,) -> tuple[Mapping[str, Any] | None, float]:"""Return matched metadata and distance, or `None` when outside threshold.Args:embedding: Query embedding vector.threshold: Maximum accepted distance for a match.n_results: Number of nearest Chroma candidates to inspect.Returns:Matched metadata and best distance. Metadata is `None` when nocandidate is close enough."""if threshold is None:threshold = settings.face_match_threshold
1234567891011121314151617181920212223242526272829303132333435363738394023 unmodified lines64656667686913 unmodified lines8384858687888990912 unmodified lines9495969798991001011021031044 unmodified lines1091101111121131141151161171181191201211221231241257 unmodified lines1331341351361371381391401411421431441451461471487 unmodified lines1561571581591601611621631641655 unmodified lines1711721731741751761771781791801811821832 unmodified lines1861871881891901911921931941951961971981992 unmodified lines20220320420520620720817 unmodified lines2262272282292302312326 unmodified lines2392402412422432447 unmodified lines2522532542552562572582592602612622632642652662672682692702712722732742752764 unmodified lines2812822832842852862872882892902912922932942952962972982999 unmodified lines3093103113123133143153163173183193203213223 unmodified lines3263273283293303313323333347 unmodified lines3423433443453463473483493503513523533543554 unmodified lines3603613623633643653663673683693703713723733743753763773783793803 unmodified lines384385386387388389390391392393394395396397398399400401402403404405406"""HTTP API for enrolling and verifying faces.The module exposes a small FastAPI application around the service layer:- ``POST /auth/login`` issues a short-lived JWT for the demo user.- ``POST /persons`` stores a known person embedding from an uploaded image.- ``POST /verify`` checks whether an uploaded face matches the local database.FastAPI uses the route metadata, Pydantic field descriptions, and endpointdocstrings below to build the interactive documentation at ``/docs`` and``/redoc``."""from base64 import b64encodefrom contextlib import asynccontextmanagerfrom datetime import UTC, datetime, timedeltafrom io import BytesIOfrom secrets import compare_digestfrom types import ModuleTypefrom typing import Annotatedimport jwtfrom fastapi import Depends, FastAPI, File, Form, HTTPException, Request, UploadFile, statusfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom jwt import ExpiredSignatureError, InvalidTokenErrorfrom PIL import Image, ImageOps, UnidentifiedImageErrorfrom pydantic import BaseModel, Fieldfrom faceverification.config import settingsfrom faceverification.core.image_processor import FaceNotDetectedErrorbearer_scheme = HTTPBearer(auto_error=False)DATA_URL_DESCRIPTION = ("PNG image encoded as a data URL. The image contains the service annotations ""for the detected face.")AUTH_RESPONSES = {status.HTTP_401_UNAUTHORIZED: {23 unmodified lines},},},status.HTTP_422_UNPROCESSABLE_CONTENT: {"description": "The request is valid, but no usable face or name was found.","content": {13 unmodified lines}@asynccontextmanagerasync def lifespan(app: FastAPI):"""Load the face verification service once when the API starts."""from faceverification.services import face_verificationapp.state.face_service = face_verification2 unmodified linesapp = FastAPI(title="Face Verification API",description=("Demo API for enrolling known people and verifying uploaded face images. ""Authenticate with `/auth/login`, then send the returned bearer token to ""the protected face-verification endpoints."),version="0.1.0",lifespan=lifespan,contact={4 unmodified linesclass HealthResponse(BaseModel):"""Health-check payload returned by the system endpoint."""status: str = Field(default="ok", description="Current API status.")class EnrollResponse(BaseModel):"""Response returned after a person is stored in the embeddings database."""message: str = Field(description="Human-readable result message.")name: str = Field(description="Normalized person name stored with the embedding.")annotated_image: str = Field(description=DATA_URL_DESCRIPTION)model_config = {"json_schema_extra": {7 unmodified linesclass VerifyResponse(BaseModel):"""Response returned after comparing an uploaded face against known people."""name: str = Field(description=("Matched person name. Returns `Unregistered Person` when the closest ""embedding is outside the configured match threshold."),)matched: bool = Field(description="Whether the uploaded face matched a known person.")annotated_image: str = Field(description=DATA_URL_DESCRIPTION)model_config = {"json_schema_extra": {7 unmodified linesclass TokenResponse(BaseModel):"""Bearer token returned by the demo authentication endpoint."""access_token: str = Field(description="JWT access token used in the Authorization header.")token_type: str = Field(default="bearer", description="OAuth2-compatible token type.")model_config = {"json_schema_extra": {5 unmodified lines}def get_face_service(request: Request) -> ModuleType:"""Return the service module stored during application startup."""return request.app.state.face_servicedef _unauthorized_error(detail: str = "Could not validate credentials.") -> HTTPException:"""Build a consistent 401 response with the bearer authentication challenge."""return HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail=detail,2 unmodified linesdef _create_access_token(username: str) -> str:"""Create a signed JWT for the authenticated demo user."""expires_at = datetime.now(UTC) + timedelta(minutes=settings.jwt_access_token_expire_minutes)payload = {"sub": username, "exp": expires_at}return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)def _authenticate_demo_user(username: str, password: str) -> bool:"""Validate demo credentials using constant-time comparisons."""valid_username = compare_digest(username, settings.demo_username)valid_password = compare_digest(password, settings.demo_password)return valid_username and valid_password2 unmodified linesdef get_current_username(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer_scheme)],) -> str:"""Decode the bearer token and return the authenticated username."""if credentials is None:raise _unauthorized_error("Not authenticated")17 unmodified linesasync def _read_image(upload: UploadFile) -> Image.Image:"""Read an uploaded image, apply EXIF orientation, and return it as RGB."""if upload.content_type and not upload.content_type.startswith("image/"):raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,6 unmodified linesstatus_code=status.HTTP_400_BAD_REQUEST,detail="Uploaded image is empty.",)try:image = Image.open(BytesIO(contents))7 unmodified linesdef _image_to_data_url(image: Image.Image) -> str:"""Serialize a PIL image as a PNG data URL for JSON responses."""buffer = BytesIO()image.save(buffer, format="PNG")encoded = b64encode(buffer.getvalue()).decode("ascii")return f"data:image/png;base64,{encoded}"def _service_error(exc: Exception) -> HTTPException:"""Map service-layer exceptions to API-friendly HTTP errors."""if isinstance(exc, FaceNotDetectedError):return HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,detail=str(exc),)if isinstance(exc, ValueError):return HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail=str(exc),)return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail="Face verification failed.",4 unmodified lines"/health",response_model=HealthResponse,summary="Check API health",response_description="The API is running.",tags=["system"],)def health() -> HealthResponse:"""Return a lightweight status response for uptime checks."""return HealthResponse()@app.post("/auth/login",response_model=TokenResponse,summary="Issue a demo access token",response_description="JWT bearer token for protected endpoints.",responses={status.HTTP_401_UNAUTHORIZED: {"description": "The username or password is incorrect.",9 unmodified linesdef login(username: Annotated[str,Form(description="Demo username configured with `FACEVERIFICATION_DEMO_USERNAME`."),],password: Annotated[str,Form(description="Demo password configured with `FACEVERIFICATION_DEMO_PASSWORD`."),],) -> TokenResponse:"""Authenticate the demo user and return a signed JWT access token."""if not _authenticate_demo_user(username, password):raise _unauthorized_error("Incorrect username or password.")3 unmodified lines@app.post("/persons",response_model=EnrollResponse,status_code=status.HTTP_201_CREATED,summary="Enroll a known person",response_description="The person was stored and the annotated upload is returned.",responses={**AUTH_RESPONSES, **IMAGE_ERROR_RESPONSES},tags=["face verification"],)7 unmodified linesForm(description="Person name to associate with the generated face embedding."),],current_username: Annotated[str, Depends(get_current_username)],service: Annotated[ModuleType, Depends(get_face_service)],) -> EnrollResponse:"""Store a new known person in the embeddings database.The endpoint extracts a face embedding from the uploaded image and stores itunder the submitted name. It returns the normalized name and a PNG data URLwith the annotated detection result."""cleaned_name = name.strip()if not cleaned_name:raise HTTPException(4 unmodified linespil_image = await _read_image(image)try:annotated_image = service.add_person(pil_image, cleaned_name)except Exception as exc:raise _service_error(exc) from excreturn EnrollResponse(message="Person added to the embeddings database.",name=cleaned_name,annotated_image=_image_to_data_url(annotated_image),)@app.post("/verify",response_model=VerifyResponse,summary="Verify an uploaded face",response_description="Best match result and the annotated upload.",responses={**AUTH_RESPONSES, **IMAGE_ERROR_RESPONSES},tags=["face verification"],)3 unmodified linesFile(description="Image containing one clear face to compare with known people."),],current_username: Annotated[str, Depends(get_current_username)],service: Annotated[ModuleType, Depends(get_face_service)],) -> VerifyResponse:"""Compare an uploaded face against the local embeddings database.A successful response always includes the closest label and whether it isconsidered a match according to the configured distance threshold."""pil_image = await _read_image(image)try:name, annotated_image = service.verify_person(pil_image)except Exception as exc:raise _service_error(exc) from excreturn VerifyResponse(name=name,matched=name != "Unregistered Person",annotated_image=_image_to_data_url(annotated_image),)12345678910111213141516171819202122232423 unmodified lines484950515253545556575859606113 unmodified lines75767778798081828384858687888990919293942 unmodified lines9798991001011021034 unmodified lines1081091101111121131141151161171181191207 unmodified lines1281291301311321331341351367 unmodified lines1441451461471481491501515 unmodified lines1571581591601611621631641651661672 unmodified lines1701711721731741751761771781791801812 unmodified lines18418518618718818917 unmodified lines2072082092102112122132142152162172182192202212222232246 unmodified lines2312322332342352362372382392402417 unmodified lines2492502512522532542552562572582592602612622632642652662672682692702712722732742752764 unmodified lines2812822832842852862872882892902912922932942952969 unmodified lines3063073083093103113123133143153163173183 unmodified lines3223233243253263273283293307 unmodified lines3383393403413423433443453463473483493504 unmodified lines3553563573583593603613623633643653663673683693703713723733743753763773783793 unmodified lines383384385386387388389390391392393394395396397398399400401402403404405406407408409import loggingfrom base64 import b64encodefrom contextlib import asynccontextmanagerfrom datetime import UTC, datetime, timedeltafrom io import BytesIOfrom secrets import compare_digestfrom typing import Annotated, Protocolimport jwtfrom fastapi import Depends, FastAPI, File, Form, HTTPException, Query, Request, UploadFile, statusfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom jwt import ExpiredSignatureError, InvalidTokenErrorfrom PIL import Image, ImageOps, UnidentifiedImageErrorfrom pydantic import BaseModelfrom faceverification.config import settingsfrom faceverification.core.image_processor import FaceNotDetectedErrorfrom faceverification.services.face_verification import UNREGISTERED_PERSONbearer_scheme = HTTPBearer(auto_error=False)logger = logging.getLogger(__name__)AUTH_RESPONSES = {status.HTTP_401_UNAUTHORIZED: {23 unmodified lines},},},status.HTTP_413_CONTENT_TOO_LARGE: {"description": "The uploaded image is too large.","content": {"application/json": {"example": {"detail": "Uploaded image is too large."},},},},status.HTTP_422_UNPROCESSABLE_CONTENT: {"description": "The request is valid, but no usable face or name was found.","content": {13 unmodified lines}class FaceService(Protocol):"""Service contract required by the HTTP layer.Implementations must accept normalized PIL images and return annotated PILimages for optional API responses."""def add_person(self, image: Image.Image, name: str) -> Image.Image: ...def verify_person(self, image: Image.Image) -> tuple[str, Image.Image]: ...@asynccontextmanagerasync def lifespan(app: FastAPI):from faceverification.services import face_verificationapp.state.face_service = face_verification2 unmodified linesapp = FastAPI(title="Face Verification API",description="Enroll known people and verify uploaded face images.",version="0.1.0",lifespan=lifespan,contact={4 unmodified linesclass HealthResponse(BaseModel):status: str = "ok"class EnrollResponse(BaseModel):message: strname: strannotated_image: str | None = Nonemodel_config = {"json_schema_extra": {7 unmodified linesclass VerifyResponse(BaseModel):name: strmatched: boolannotated_image: str | None = Nonemodel_config = {"json_schema_extra": {7 unmodified linesclass TokenResponse(BaseModel):access_token: strtoken_type: str = "bearer"model_config = {"json_schema_extra": {5 unmodified lines}def get_face_service(request: Request) -> FaceService:return request.app.state.face_servicedef _unauthorized_error(detail: str = "Could not validate credentials.") -> HTTPException:return HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail=detail,2 unmodified linesdef _create_access_token(username: str) -> str:expires_at = datetime.now(UTC) + timedelta(minutes=settings.jwt_access_token_expire_minutes)payload = {"sub": username, "exp": expires_at}return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)def _authenticate_demo_user(username: str, password: str) -> bool:valid_username = compare_digest(username, settings.demo_username)valid_password = compare_digest(password, settings.demo_password)return valid_username and valid_password2 unmodified linesdef get_current_username(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer_scheme)],) -> str:if credentials is None:raise _unauthorized_error("Not authenticated")17 unmodified linesasync def _read_image(upload: UploadFile) -> Image.Image:"""Validate an upload and return it as an RGB image.Args:upload: Multipart file received by FastAPI.Returns:RGB PIL image with EXIF orientation applied.Raises:HTTPException: If the file is not an image, is empty, too large, or invalid."""if upload.content_type and not upload.content_type.startswith("image/"):raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,6 unmodified linesstatus_code=status.HTTP_400_BAD_REQUEST,detail="Uploaded image is empty.",)if len(contents) > settings.max_upload_bytes:raise HTTPException(status_code=status.HTTP_413_CONTENT_TOO_LARGE,detail="Uploaded image is too large.",)try:image = Image.open(BytesIO(contents))7 unmodified linesdef _image_to_data_url(image: Image.Image) -> str:buffer = BytesIO()image.save(buffer, format="PNG")encoded = b64encode(buffer.getvalue()).decode("ascii")return f"data:image/png;base64,{encoded}"def _face_not_detected_error(exc: FaceNotDetectedError) -> HTTPException:return HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,detail=str(exc),)def _bad_service_request(exc: ValueError) -> HTTPException:return HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail=str(exc),)def _unexpected_service_error(exc: Exception) -> HTTPException:logger.exception("Face verification service failed")return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail="Face verification failed.",4 unmodified lines"/health",response_model=HealthResponse,summary="Check API health",tags=["system"],)def health() -> HealthResponse:return HealthResponse()@app.post("/auth/login",response_model=TokenResponse,summary="Log in",responses={status.HTTP_401_UNAUTHORIZED: {"description": "The username or password is incorrect.",9 unmodified linesdef login(username: Annotated[str,Form(),],password: Annotated[str,Form(),],) -> TokenResponse:if not _authenticate_demo_user(username, password):raise _unauthorized_error("Incorrect username or password.")3 unmodified lines@app.post("/persons",response_model=EnrollResponse,response_model_exclude_none=True,status_code=status.HTTP_201_CREATED,summary="Enroll a known person",responses={**AUTH_RESPONSES, **IMAGE_ERROR_RESPONSES},tags=["face verification"],)7 unmodified linesForm(description="Person name to associate with the generated face embedding."),],current_username: Annotated[str, Depends(get_current_username)],service: Annotated[FaceService, Depends(get_face_service)],include_image: Annotated[bool,Query(description="Include the annotated image as a base64 data URL."),] = True,) -> EnrollResponse:_ = current_usernamecleaned_name = name.strip()if not cleaned_name:raise HTTPException(4 unmodified linespil_image = await _read_image(image)try:annotated_image = service.add_person(pil_image, cleaned_name)except FaceNotDetectedError as exc:raise _face_not_detected_error(exc) from excexcept ValueError as exc:raise _bad_service_request(exc) from excexcept Exception as exc:raise _unexpected_service_error(exc) from excreturn EnrollResponse(message="Person added to the embeddings database.",name=cleaned_name,annotated_image=_image_to_data_url(annotated_image) if include_image else None,)@app.post("/verify",response_model=VerifyResponse,response_model_exclude_none=True,summary="Verify an uploaded face",responses={**AUTH_RESPONSES, **IMAGE_ERROR_RESPONSES},tags=["face verification"],)3 unmodified linesFile(description="Image containing one clear face to compare with known people."),],current_username: Annotated[str, Depends(get_current_username)],service: Annotated[FaceService, Depends(get_face_service)],include_image: Annotated[bool,Query(description="Include the annotated image as a base64 data URL."),] = True,) -> VerifyResponse:_ = current_usernamepil_image = await _read_image(image)try:name, annotated_image = service.verify_person(pil_image)except FaceNotDetectedError as exc:raise _face_not_detected_error(exc) from excexcept ValueError as exc:raise _bad_service_request(exc) from excexcept Exception as exc:raise _unexpected_service_error(exc) from excreturn VerifyResponse(name=name,matched=name != UNREGISTERED_PERSON,annotated_image=_image_to_data_url(annotated_image) if include_image else None,)
12345678910111213141516171819202122232425262728293031322 unmodified lines35363738394041424344454647484950515253545556575859601 unmodified line626364656667686970717273"""Application service functions for face enrollment and verification.This module coordinates image preprocessing, embedding extraction, and vectordatabase operations for the Gradio interface."""from PIL import Imagefrom faceverification.core.image_processor import FaceNotDetectedError, ImageProcessorfrom faceverification.core.vectordb import VectorDBimage_processor = ImageProcessor()vector_db = VectorDB()def add_person(image: Image.Image, name: str) -> Image.Image:"""Enroll a person by extracting and storing their face embedding.Args:image: Input image provided by the UI as a PIL image.name: Person name to store as embedding metadata.Returns:The input image annotated with detected face bounding boxes.Raises:FaceNotDetectedError: If no face is detected in the input image.TypeError: If embedding extraction does not return the expected tensor."""img, presence = image_processor.detect_faces(image)2 unmodified linesraise FaceNotDetectedError("No faces were detected in the image.")faces_pt = image_processor.get_embedding(img)if faces_pt is not None:vector_db.add_embedding(faces_pt.cpu().numpy(), {"name": name})else:raise TypeError("The extracted face embedding is not a torch.Tensor.")return imgdef verify_person(image: Image.Image) -> tuple[str, Image.Image]:"""Verify whether the input face matches a stored person.Args:image: Input image provided by the UI as a PIL image.Returns:A tuple with the matched person name, or `"Unregistered Person"` when no match isfound, and the image annotated with detected face bounding boxes.Raises:FaceNotDetectedError: If no face is detected in the input image."""detected_faces, presence = image_processor.detect_faces(image.copy())1 unmodified lineraise FaceNotDetectedError("No faces were detected in the image.")faces_pt = image_processor.get_embedding(image)if faces_pt is not None:metadata, _ = vector_db.query_embedding(faces_pt.cpu().numpy())if metadata:return metadata["name"], detected_facesreturn "Unregistered Person", detected_facesraise FaceNotDetectedError("No faces were detected in the image.")1234567891011121314151617181920212223242526272829302 unmodified lines33343536373839404142434445464748495051525354555657581 unmodified line606162636465666768697071"""Application service functions for face enrollment and verification."""from PIL import Imagefrom faceverification.core.image_processor import FaceNotDetectedError, ImageProcessorfrom faceverification.core.vectordb import VectorDBUNREGISTERED_PERSON = "Unregistered Person"image_processor = ImageProcessor()vector_db = VectorDB()def add_person(image: Image.Image, name: str) -> Image.Image:"""Store a person's face embedding and return the annotated image.Args:image: PIL image containing the person's face.name: Person name to store with the embedding.Returns:Image annotated with detected face boxes.Raises:FaceNotDetectedError: If no face is detected.TypeError: If embedding extraction returns an unexpected value."""img, presence = image_processor.detect_faces(image)2 unmodified linesraise FaceNotDetectedError("No faces were detected in the image.")faces_pt = image_processor.get_embedding(img)if faces_pt is None:raise TypeError("The extracted face embedding is not a torch.Tensor.")vector_db.add_embedding(faces_pt.cpu().numpy(), {"name": name})return imgdef verify_person(image: Image.Image) -> tuple[str, Image.Image]:"""Return the closest known person name and the annotated image.Args:image: PIL image containing the face to verify.Returns:Matched person name, or `UNREGISTERED_PERSON`, plus the annotated image.Raises:FaceNotDetectedError: If no face is detected.ValueError: If the vector database has no stored embeddings."""detected_faces, presence = image_processor.detect_faces(image.copy())1 unmodified lineraise FaceNotDetectedError("No faces were detected in the image.")faces_pt = image_processor.get_embedding(image)if faces_pt is None:raise FaceNotDetectedError("No faces were detected in the image.")metadata, _ = vector_db.query_embedding(faces_pt.cpu().numpy())if metadata:return metadata["name"], detected_facesreturn UNREGISTERED_PERSON, detected_faces
2 unmodified lines345678116 unmodified lines12512612712812913014 unmodified lines14514614714814915025 unmodified lines1761771782 unmodified linesfrom fastapi.testclient import TestClientfrom PIL import Imagefrom faceverification.core.image_processor import FaceNotDetectedErrorfrom faceverification.interfaces.fastapi_app import app, get_face_service116 unmodified linesassert body["annotated_image"].startswith("data:image/png;base64,")def test_verify_identity_returns_unprocessable_when_no_face_is_detected():class NoFaceService(FakeService):def verify_person(self, image):14 unmodified linesassert response.json() == {"detail": "No faces were detected in the image."}def test_enroll_person_rejects_blank_name():app.dependency_overrides[get_face_service] = lambda: FakeService()try:25 unmodified linesassert response.status_code == 415assert response.json() == {"detail": "Uploaded file must be an image."}2 unmodified lines3456789116 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814914 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618718818925 unmodified lines2152162172182192202212222232242252262272282292302312322332342 unmodified linesfrom fastapi.testclient import TestClientfrom PIL import Imagefrom faceverification.config import settingsfrom faceverification.core.image_processor import FaceNotDetectedErrorfrom faceverification.interfaces.fastapi_app import app, get_face_service116 unmodified linesassert body["annotated_image"].startswith("data:image/png;base64,")def test_verify_identity_can_skip_annotated_image():fake_service = FakeService()app.dependency_overrides[get_face_service] = lambda: fake_servicetry:client = TestClient(app)response = client.post("/verify?include_image=false",headers=_auth_headers(client),files={"image": ("face.png", _image_bytes(), "image/png")},)finally:app.dependency_overrides.clear()body = response.json()assert response.status_code == 200assert body == {"name": "Ada", "matched": True}def test_verify_identity_returns_unprocessable_when_no_face_is_detected():class NoFaceService(FakeService):def verify_person(self, image):14 unmodified linesassert response.json() == {"detail": "No faces were detected in the image."}def test_verify_identity_returns_internal_error_for_unexpected_service_failure():class BrokenService(FakeService):def verify_person(self, image):raise RuntimeError("model failed")app.dependency_overrides[get_face_service] = lambda: BrokenService()try:client = TestClient(app)response = client.post("/verify",headers=_auth_headers(client),files={"image": ("face.png", _image_bytes(), "image/png")},)finally:app.dependency_overrides.clear()assert response.status_code == 500assert response.json() == {"detail": "Face verification failed."}def test_enroll_person_rejects_blank_name():app.dependency_overrides[get_face_service] = lambda: FakeService()try:25 unmodified linesassert response.status_code == 415assert response.json() == {"detail": "Uploaded file must be an image."}def test_upload_rejects_large_image(monkeypatch):monkeypatch.setattr(settings, "max_upload_bytes", 1)app.dependency_overrides[get_face_service] = lambda: FakeService()try:client = TestClient(app)response = client.post("/verify",headers=_auth_headers(client),files={"image": ("face.png", _image_bytes(), "image/png")},)finally:app.dependency_overrides.clear()assert response.status_code == 413assert response.json() == {"detail": "Uploaded image is too large."}
README.md+13-1
src/faceverification/config.py+1
src/faceverification/core/image_processor.py+11-26
src/faceverification/core/vectordb.py+15-34
src/faceverification/interfaces/fastapi_app.py+100-97
src/faceverification/services/face_verification.py+23-25
test/test_fastapi_app.py+56