Spaces:
Sleeping
Sleeping
Sync from GitHub via hub-sync
Browse filesFiles changed (13)
- .dockerignoreAdded+19
- DockerfileAdded+30
- README.md+138
- docker-compose.persist.ymlAdded+15
- docker-compose.ymlAdded+33
- docker/constraints.txtAdded+2
- pyproject.toml+9-8
- requirements.txt+40-20
- src/faceverification/config.py+6
- src/faceverification/interfaces/fastapi_app.pyAdded+414
- src/faceverification/interfaces/gradio_app.py+1-1
- test/test_fastapi_app.pyAdded+178
- uv.lock
12345678910111213141516171819.git.github.pytest_cache.ruff_cache.uv-cache.venv__pycache__*.py[cod]*.egg-info.coveragecoverage.xmlhtmlcov.env.envrc.vscodenotebookstestDockerfiledocker-compose*.yml123456789101112131415161718192021222324252627282930FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=1 \ PYTHONPATH=/app/src \ FACEVERIFICATION_DEVICE=cpu
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \ libgl1 \ libglib2.0-0 \ && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY pyproject.toml README.md ./COPY src ./src
RUN useradd --create-home --shell /usr/sbin/nologin appuser \ && mkdir -p /data/chroma \ && chown -R appuser:appuser /app /data
USER appuser
EXPOSE 8000 7860
CMD ["uvicorn", "faceverification.interfaces.fastapi_app:app", "--host", "0.0.0.0", "--port", "8000"]55 unmodified lines56575859606155 unmodified linespython app.py```## Project Structure```text55 unmodified lines565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819955 unmodified linespython app.py```## FastAPI InterfaceThe project also includes an HTTP API for the same enroll-and-verify workflow.Run it locally with:```bashuv run uvicorn faceverification.interfaces.fastapi_app:app --host 0.0.0.0 --port 8000```Interactive API documentation is available at:- Swagger UI: http://localhost:8000/docs- ReDoc: http://localhost:8000/redoc### AuthenticationProtected 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 \-F "username=demo" \-F "password=demo123"```Use the returned token in the `Authorization` header:```bashAuthorization: Bearer <access_token>```### Endpoints- `GET /health`: returns API status.- `POST /auth/login`: returns a JWT access token for the demo user.- `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 a containerized deployment, the recommended baseline is the FastAPIcontainer running Uvicorn:```bashuvicorn faceverification.interfaces.fastapi_app:app --host 0.0.0.0 --port 8000```This keeps the demo lightweight and avoids loading the FaceNet/MTCNN models inmultiple worker processes unnecessarily. Because each worker can hold its ownmodel instance in memory, increasing worker count should be done only afterchecking available RAM and expected traffic.Gunicorn with Uvicorn workers and an Nginx reverse proxy are valid productionoptions, but they are intentionally not required for the baseline deployment:- Use Gunicorn/Uvicorn workers when the service needs a traditional processmanager or multiple worker processes.- Use Nginx when deploying on a self-managed VM that needs TLS termination,upload-size limits, reverse proxy routing, compression, or centralized accesslogs.- On managed platforms such as Render, Railway, Fly.io, Cloud Run, or similar,the platform usually provides the external reverse proxy and TLS layer, sorunning Uvicorn directly inside the application container is sufficient.### DockerBuild and run the FastAPI service:```bashdocker compose up --build api```The API will be available at:- http://localhost:8000/health- http://localhost:8000/docsRun the optional Gradio interface:```bashdocker compose --profile gradio up --build```The Gradio UI will be available at http://localhost:7860.Both services use the same image. By default, ChromaDB runs in memory, soenrolled faces are ephemeral and disappear when the container restarts. This isintentional for the demo baseline.To persist embeddings to disk, provide a database name:```bashFACEVERIFICATION_VECTOR_DB_NAME=local-demo \docker compose -f docker-compose.yml -f docker-compose.persist.yml up --build api```The base `docker-compose.yml` does not mount any volume, so the defaultdeployment stays ephemeral. The optional `docker-compose.persist.yml` overridemounts the `faceverification-data` volume at `/data` and translates`FACEVERIFICATION_VECTOR_DB_NAME` into`FACEVERIFICATION_VECTOR_DB_PERSIST_DIRECTORY=/data/chroma/<name>` before theapplication starts. The application itself still defaults to in-memory ChromaDBunless `FACEVERIFICATION_VECTOR_DB_PERSIST_DIRECTORY` is explicitly provided.The default container configuration sets `FACEVERIFICATION_DEVICE=cpu` to keepdeployment portable.The shared local ChromaDB volume is intended for a small demo deployment when apersist name is enabled. For a multi-container production setup with concurrentwriters or multiple replicas, use an external database/vector-store service ormake one service the clear owner of writes.For production deployments, override at least:```bashFACEVERIFICATION_DEMO_USERNAMEFACEVERIFICATION_DEMO_PASSWORDFACEVERIFICATION_JWT_SECRET_KEY```Example enrollment request:```bashcurl -X POST http://localhost:8000/persons \-H "Authorization: Bearer <access_token>" \-F "name=Ada Lovelace" \-F "image=@test/images/person_anchor.jpg"```Example verification request:```bashcurl -X POST http://localhost:8000/verify \-H "Authorization: Bearer <access_token>" \-F "image=@test/images/person_positive.jpg"```## Project Structure```text
123456789101112131415services: api: environment: FACEVERIFICATION_VECTOR_DB_PERSIST_DIRECTORY: ${FACEVERIFICATION_VECTOR_DB_NAME:+/data/chroma/${FACEVERIFICATION_VECTOR_DB_NAME}} volumes: - faceverification-data:/data
gradio: environment: FACEVERIFICATION_VECTOR_DB_PERSIST_DIRECTORY: ${FACEVERIFICATION_VECTOR_DB_NAME:+/data/chroma/${FACEVERIFICATION_VECTOR_DB_NAME}} volumes: - faceverification-data:/data
volumes: faceverification-data:123456789101112131415161718192021222324252627282930313233services: api: build: context: . image: faceverification command: uvicorn faceverification.interfaces.fastapi_app:app --host 0.0.0.0 --port 8000 ports: - "8000:8000" environment: FACEVERIFICATION_DEVICE: cpu FACEVERIFICATION_DEMO_USERNAME: ${FACEVERIFICATION_DEMO_USERNAME:-demo} FACEVERIFICATION_DEMO_PASSWORD: ${FACEVERIFICATION_DEMO_PASSWORD:-demo123} FACEVERIFICATION_JWT_SECRET_KEY: ${FACEVERIFICATION_JWT_SECRET_KEY:-change-me-in-production-demo-secret-32-bytes-min} healthcheck: test: [ "CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=5)" ] interval: 30s timeout: 10s retries: 3 start_period: 60s
gradio: build: context: . image: faceverification command: python -m faceverification.interfaces.gradio_app profiles: - gradio ports: - "7860:7860" environment: FACEVERIFICATION_DEVICE: cpu GRADIO_SERVER_NAME: 0.0.0.0 GRADIO_SERVER_PORT: 786012torch==2.11.0+cputorchvision==0.26.0+cpu2 unmodified lines34567892 unmodified lines12131415161718192021222324257 unmodified lines33343536373839404142434412 unmodified lines575859602 unmodified linesversion = "0.1.0"description = "Face verification demo using FaceNet embeddings, ChromaDB vector search, and CI/CD pipeline."readme = "README.md"requires-python = ">=3.11"dependencies = ["numpy>=1.24,<2.0","datasets>=4.8.5",2 unmodified lines"huggingface-hub>=1.14.0","python-dotenv>=1.2.2","pydantic-settings>=2.14.1","torch>=2.11.0","torchvision>=0.26.0","chromadb>=1.5.9","pytest>=9.0.3","pytest-cov>=7.1.0","fastapi>=0.136.1","uvicorn[standard]>=0.46.0","ruff>=0.15.13",][project.scripts]7 unmodified lineswhere = ["src"][tool.uv.sources]torch = { index = "pytorch-cu126" }torchvision = { index = "pytorch-cu126" }[[tool.uv.index]]name = "pytorch-cu126"url = "https://download.pytorch.org/whl/cu126"explicit = true[tool.pytest.ini_options]12 unmodified lines[tool.ruff.lint]select = ["E", "F", "I", "B", "UP", "SIM"]2 unmodified lines34567892 unmodified lines121314151617181920212223242526277 unmodified lines35363738394041424344454612 unmodified lines5960612 unmodified linesversion = "0.1.0"description = "Face verification demo using FaceNet embeddings, ChromaDB vector search, and CI/CD pipeline."readme = "README.md"requires-python = ">=3.11,<3.14"dependencies = ["numpy>=1.24,<2.0","datasets>=4.8.5",2 unmodified lines"huggingface-hub>=1.14.0","python-dotenv>=1.2.2","pydantic-settings>=2.14.1","chromadb>=1.5.9","pytest>=9.0.3","pytest-cov>=7.1.0","fastapi>=0.136.1","pyjwt>=2.10.1","python-multipart>=0.0.28","uvicorn[standard]>=0.46.0","ruff>=0.15.13","torch>=2.12.0","torchvision>=0.27.0",][project.scripts]7 unmodified lineswhere = ["src"][tool.uv.sources]torch = { index = "pytorch-cpu" }torchvision = { index = "pytorch-cpu" }[[tool.uv.index]]name = "pytorch-cpu"url = "https://download.pytorch.org/whl/cpu"explicit = true[tool.pytest.ini_options]12 unmodified lines[tool.ruff.lint]select = ["E", "F", "I", "B", "UP", "SIM"]
12345639 unmodified lines464748495051525354555657585 unmodified lines64656667686970143 unmodified lines2142152162172182192202212222232243 unmodified lines2282292302312322332347 unmodified lines2422432442452462472482492502512522532545 unmodified lines2602612622632642652662672682692705 unmodified lines27627727827928028128228328428528622 unmodified lines30931031131231331416 unmodified lines3313323333343353363373383393403413423432 unmodified lines34634734834935035135235325 unmodified lines3793803813823833843852 unmodified lines388389390391392393# This file was autogenerated by uv via the following command:# uv export --locked --no-hashes --format requirements.txt --output-file requirements.txt--extra-index-url https://download.pytorch.org/whl/cpuaiohappyeyeballs==2.6.1# via aiohttpaiohttp==3.13.539 unmodified lines# via# typer# uvicorncolorama==0.4.6 ; os_name == 'nt' or sys_platform == 'win32'# via# build# click# pytest# tqdm# uvicorndatasets==4.8.5# via faceverificationdill==0.4.15 unmodified linesfacenet-pytorch==2.5.3# via faceverificationfastapi==0.136.1# via gradiofilelock==3.29.0# via# datasets143 unmodified lines# huggingface-hub# onnxruntime# pytestpandas==2.3.3 ; python_full_version >= '3.14'# via# datasets# gradiopandas==3.0.2 ; python_full_version < '3.14'# via# datasets# gradio3 unmodified lines# gradio# torchvisionpluggy==1.6.0# via pytestpropcache==0.5.2# via# aiohttp7 unmodified lines# via datasetspybase64==1.4.3# via chromadbpydantic==2.12.5# via# chromadb# fastapi# gradio# pydantic-settingspydantic-core==2.41.5# via pydanticpydantic-settings==2.14.1# via5 unmodified lines# via# pytest# richpypika==0.51.1# via chromadbpyproject-hooks==1.2.0# via buildpytest==9.0.3# via faceverificationpython-dateutil==2.9.0.post0# via5 unmodified lines# pydantic-settings# uvicornpython-multipart==0.0.28# via gradiopytz==2026.2# via# gradio# pandaspyyaml==6.0.3# via# chromadb22 unmodified lines# via# jsonschema# referencingsafehttpx==0.1.7# via gradiosemantic-version==2.10.016 unmodified lines# via chromadbtokenizers==0.23.1# via chromadbtomlkit==0.14.0# via gradiotorch==2.11.0+cpu# via# faceverification# torchvisiontorchvision==0.26.0+cpu# via# facenet-pytorch# faceverification2 unmodified lines# chromadb# datasets# huggingface-hubtriton==3.6.0 ; sys_platform == 'linux'# via torchtyper==0.25.1# via# chromadb25 unmodified lines# fastapi# pydantic# pydantic-settingstzdata==2026.2 ; python_full_version >= '3.14' or sys_platform == 'emscripten' or sys_platform == 'win32'# via pandasurllib3==2.7.0# via2 unmodified linesuvicorn==0.46.0# via# chromadb# gradiouvloop==0.22.1 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'# via uvicorn123456739 unmodified lines4748495051525354555657585960615 unmodified lines676869707172737475143 unmodified lines2192202212222232242253 unmodified lines2292302312322332342352362377 unmodified lines2452462472482492502512522532542552562575 unmodified lines2632642652662672682692702712722732742752762772782795 unmodified lines28528628728828929029129229329429522 unmodified lines31831932032132232332432516 unmodified lines3423433443453463473483493503513523533543553563573583593603613623633642 unmodified lines36736836937037137225 unmodified lines3983994004014024034042 unmodified lines407408409410411412413# This file was autogenerated by uv via the following command:# uv --cache-dir .uv-cache export --locked --no-hashes --no-emit-project --format requirements.txt --output-file requirements.txt--find-links https://download.pytorch.org/whl/cpu/torch/--find-links https://download.pytorch.org/whl/cpu/torchvision/aiohappyeyeballs==2.6.1# via aiohttpaiohttp==3.13.539 unmodified lines# via# typer# uvicorncolorama==0.4.6 ; (os_name != 'nt' and sys_platform == 'win32') or (os_name == 'nt' and sys_platform != 'darwin')# via# build# click# pytest# tqdm# uvicorncoverage==7.14.0# via pytest-covdatasets==4.8.5# via faceverificationdill==0.4.15 unmodified linesfacenet-pytorch==2.5.3# via faceverificationfastapi==0.136.1# via# faceverification# gradiofilelock==3.29.0# via# datasets143 unmodified lines# huggingface-hub# onnxruntime# pytestpandas==3.0.2# via# datasets# gradio3 unmodified lines# gradio# torchvisionpluggy==1.6.0# via# pytest# pytest-covpropcache==0.5.2# via# aiohttp7 unmodified lines# via datasetspybase64==1.4.3# via chromadbpydantic==2.13.4# via# chromadb# fastapi# gradio# pydantic-settingspydantic-core==2.46.4# via pydanticpydantic-settings==2.14.1# via5 unmodified lines# via# pytest# richpyjwt==2.12.1# via faceverificationpypika==0.51.1# via chromadbpyproject-hooks==1.2.0# via buildpytest==9.0.3# via# faceverification# pytest-covpytest-cov==7.1.0# via faceverificationpython-dateutil==2.9.0.post0# via5 unmodified lines# pydantic-settings# uvicornpython-multipart==0.0.28# via# faceverification# gradiopytz==2026.2# via gradiopyyaml==6.0.3# via# chromadb22 unmodified lines# via# jsonschema# referencingruff==0.15.13# via faceverificationsafehttpx==0.1.7# via gradiosemantic-version==2.10.016 unmodified lines# via chromadbtokenizers==0.23.1# via chromadbtomli==2.4.1 ; python_full_version <= '3.11'# via coveragetomlkit==0.14.0# via gradiotorch==2.12.0 ; sys_platform == 'darwin'# via# faceverification# torchvisiontorch==2.12.0+cpu ; sys_platform != 'darwin'# via# faceverification# torchvisiontorchvision==0.27.0 ; sys_platform == 'darwin'# via# facenet-pytorch# faceverificationtorchvision==0.27.0+cpu ; sys_platform != 'darwin'# via# facenet-pytorch# faceverification2 unmodified lines# chromadb# datasets# huggingface-hubtyper==0.25.1# via# chromadb25 unmodified lines# fastapi# pydantic# pydantic-settingstzdata==2026.2 ; sys_platform == 'emscripten' or sys_platform == 'win32'# via pandasurllib3==2.7.0# via2 unmodified linesuvicorn==0.46.0# via# chromadb# faceverification# gradiouvloop==0.22.1 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'# via uvicorn
13 unmodified lines14151617181913 unmodified linesmtcnn_thresholds: tuple[float, float, float] = (0.6, 0.7, 0.95)facenet_pretrained: str = "vggface2"model_config = SettingsConfigDict(env_file=".env",env_prefix="FACEVERIFICATION_",13 unmodified lines14151617181920212223242513 unmodified linesmtcnn_thresholds: tuple[float, float, float] = (0.6, 0.7, 0.95)facenet_pretrained: str = "vggface2"demo_username: str = "demo"demo_password: str = "demo123"jwt_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",env_prefix="FACEVERIFICATION_",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414"""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 Annotated
import 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, Field
from faceverification.config import settingsfrom faceverification.core.image_processor import FaceNotDetectedError
bearer_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: { "description": "The request is missing a bearer token or the token is invalid.", "content": { "application/json": { "example": {"detail": "Not authenticated"}, }, }, },}
IMAGE_ERROR_RESPONSES = { status.HTTP_400_BAD_REQUEST: { "description": "The uploaded file is empty, invalid, or rejected by the service.", "content": { "application/json": { "example": {"detail": "Uploaded file is not a valid image."}, }, }, }, status.HTTP_415_UNSUPPORTED_MEDIA_TYPE: { "description": "The uploaded file content type is not an image.", "content": { "application/json": { "example": {"detail": "Uploaded file must be an image."}, }, }, }, status.HTTP_422_UNPROCESSABLE_CONTENT: { "description": "The request is valid, but no usable face or name was found.", "content": { "application/json": { "example": {"detail": "No faces were detected in the image."}, }, }, }, status.HTTP_500_INTERNAL_SERVER_ERROR: { "description": "The face verification pipeline failed unexpectedly.", "content": { "application/json": { "example": {"detail": "Face verification failed."}, }, }, },}
@asynccontextmanagerasync def lifespan(app: FastAPI): """Load the face verification service once when the API starts.""" from faceverification.services import face_verification
app.state.face_service = face_verification yield
app = 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={ "name": "Leandro", "url": "https://github.com/leandrodevai/faceverification", },)
class 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": { "example": { "message": "Person added to the embeddings database.", "name": "Ada Lovelace", "annotated_image": "data:image/png;base64,iVBORw0KGgo...", }, }, }
class 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": { "example": { "name": "Ada Lovelace", "matched": True, "annotated_image": "data:image/png;base64,iVBORw0KGgo...", }, }, }
class 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": { "example": { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "bearer", }, }, }
def get_face_service(request: Request) -> ModuleType: """Return the service module stored during application startup.""" return request.app.state.face_service
def _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, headers={"WWW-Authenticate": "Bearer"}, )
def _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_password
def 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")
try: token = credentials.credentials payload = jwt.decode( token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm], ) except ExpiredSignatureError as exc: raise _unauthorized_error("Token has expired.") from exc except InvalidTokenError as exc: raise _unauthorized_error() from exc
username = payload.get("sub") if not isinstance(username, str) or not username: raise _unauthorized_error()
return username
async 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, detail="Uploaded file must be an image.", )
contents = await upload.read() if not contents: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Uploaded image is empty.", )
try: image = Image.open(BytesIO(contents)) image = ImageOps.exif_transpose(image) return image.convert("RGB") except (UnidentifiedImageError, OSError) as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Uploaded file is not a valid image.", ) from exc
def _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.", )
@app.get( "/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.", "content": { "application/json": { "example": {"detail": "Incorrect username or password."}, }, }, }, }, tags=["auth"],)def 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.")
return TokenResponse(access_token=_create_access_token(username))
@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"],)async def enroll_person( image: Annotated[ UploadFile, File(description="Image containing one clear face to enroll."), ], name: Annotated[ str, Form(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 it under the submitted name. It returns the normalized name and a PNG data URL with the annotated detection result. """ cleaned_name = name.strip() if not cleaned_name: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail="Person name is required.", )
pil_image = await _read_image(image) try: annotated_image = service.add_person(pil_image, cleaned_name) except Exception as exc: raise _service_error(exc) from exc
return 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"],)async def verify_identity( image: Annotated[ UploadFile, File(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 is considered 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 exc
return VerifyResponse( name=name, matched=name != "Unregistered Person", annotated_image=_image_to_data_url(annotated_image), )
def main() -> None: import uvicorn
uvicorn.run("faceverification.interfaces.fastapi_app:app", host="0.0.0.0", port=8000)
if __name__ == "__main__": main()53 unmodified lines5455565758596053 unmodified linesdef main():FV_gr.launch()if __name__ == "__main__":53 unmodified lines5455565758596053 unmodified linesdef main():FV_gr.launch(server_name="0.0.0.0", server_port=7860)if __name__ == "__main__":
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178from io import BytesIO
from fastapi.testclient import TestClientfrom PIL import Image
from faceverification.core.image_processor import FaceNotDetectedErrorfrom faceverification.interfaces.fastapi_app import app, get_face_service
def _image_bytes() -> bytes: buffer = BytesIO() Image.new("RGB", (12, 12), "white").save(buffer, format="PNG") return buffer.getvalue()
class FakeService: def __init__(self): self.add_person_calls = [] self.verify_person_calls = []
def add_person(self, image, name): self.add_person_calls.append((image, name)) return Image.new("RGB", image.size, "black")
def verify_person(self, image): self.verify_person_calls.append(image) return "Ada", Image.new("RGB", image.size, "black")
def _auth_headers(client: TestClient) -> dict[str, str]: response = client.post( "/auth/login", data={"username": "demo", "password": "demo123"}, ) token = response.json()["access_token"] return {"Authorization": f"Bearer {token}"}
def test_health_returns_ok(): client = TestClient(app)
response = client.get("/health")
assert response.status_code == 200 assert response.json() == {"status": "ok"}
def test_login_returns_access_token(): client = TestClient(app)
response = client.post( "/auth/login", data={"username": "demo", "password": "demo123"}, )
body = response.json() assert response.status_code == 200 assert body["token_type"] == "bearer" assert body["access_token"]
def test_login_rejects_invalid_credentials(): client = TestClient(app)
response = client.post( "/auth/login", data={"username": "demo", "password": "wrong"}, )
assert response.status_code == 401 assert response.json() == {"detail": "Incorrect username or password."}
def test_verify_identity_requires_token(): client = TestClient(app)
response = client.post( "/verify", files={"image": ("face.png", _image_bytes(), "image/png")}, )
assert response.status_code == 401 assert response.json() == {"detail": "Not authenticated"}
def test_enroll_person_calls_service_and_returns_annotated_image(): fake_service = FakeService() app.dependency_overrides[get_face_service] = lambda: fake_service try: client = TestClient(app) response = client.post( "/persons", headers=_auth_headers(client), data={"name": " Ada "}, files={"image": ("face.png", _image_bytes(), "image/png")}, ) finally: app.dependency_overrides.clear()
body = response.json() assert response.status_code == 201 assert body["name"] == "Ada" assert body["message"] == "Person added to the embeddings database." assert body["annotated_image"].startswith("data:image/png;base64,") assert fake_service.add_person_calls[0][1] == "Ada"
def test_verify_identity_returns_match_result(): fake_service = FakeService() app.dependency_overrides[get_face_service] = lambda: fake_service 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()
body = response.json() assert response.status_code == 200 assert body["name"] == "Ada" assert body["matched"] is True assert 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): raise FaceNotDetectedError("No faces were detected in the image.")
app.dependency_overrides[get_face_service] = lambda: NoFaceService() 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 == 422 assert 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: client = TestClient(app) response = client.post( "/persons", headers=_auth_headers(client), data={"name": " "}, files={"image": ("face.png", _image_bytes(), "image/png")}, ) finally: app.dependency_overrides.clear()
assert response.status_code == 422 assert response.json() == {"detail": "Person name is required."}
def test_upload_rejects_non_image_content_type(): app.dependency_overrides[get_face_service] = lambda: FakeService() try: client = TestClient(app) response = client.post( "/verify", headers=_auth_headers(client), files={"image": ("face.txt", b"hello", "text/plain")}, ) finally: app.dependency_overrides.clear()
assert response.status_code == 415 assert response.json() == {"detail": "Uploaded file must be an image."}.dockerignoreAdded+19
DockerfileAdded+30
README.md+138
docker-compose.persist.ymlAdded+15
docker-compose.ymlAdded+33
docker/constraints.txtAdded+2
pyproject.toml+9-8
requirements.txt+40-20
src/faceverification/config.py+6
src/faceverification/interfaces/fastapi_app.pyAdded+414
src/faceverification/interfaces/gradio_app.py+1-1
test/test_fastapi_app.pyAdded+178
uv.lock