Spaces:
Running
Running
Oliver Nitsche Claude Sonnet 4.6 commited on
Commit ·
77c6ffa
1
Parent(s): 715f41e
Replace face-recognition/dlib with AWS Rekognition
Browse filesEliminates the ~15-minute dlib compilation on Raspberry Pi. boto3 and
Pillow (pure Python, pre-built wheels) replace the face-recognition
package. Face embeddings are now stored in an AWS Rekognition collection
instead of a local face_db.json file; existing enrolled faces will need
to be re-registered.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (4)
- CLAUDE.md+17-2
- pyproject.toml+2-1
- recognizer/face_db.py+72-38
- recognizer/main.py+27-38
19 unmodified lines20212223242526272843 unmodified lines7273747576777819 unmodified lines```bashsudo apt-get install espeak-ng # text-to-speech synthesispip install face-recognition # compiles dlib from source (~15 min on Pi)```## Running the AppRun directly (connects to a live Reachy Mini robot):43 unmodified lines- **ENROLLING**: robot has detected an unrecognised face; waits for name to be submitted via the web UI (`POST /set_name`). Stores encoding in `face_db.json`, says "Nice to meet you, <name>!", then sleeps.**Helper modules**:- `recognizer/face_db.py` — load/save/query face encodings. Database at `recognizer/face_db.json` (gitignored). `find_match()` tolerance = 0.55.- `recognizer/tts.py` — synthesises text via `espeak-ng -s 140 -w <tmp.wav>`, plays via `media.play_sound()`, then sleeps to let playback finish.**Settings UI** (`recognizer/static/`):19 unmodified lines20212223242526272829303132333435363738394041424343 unmodified lines8788899091929319 unmodified lines```bashsudo apt-get install espeak-ng # text-to-speech synthesis```### AWS Rekognition credentialsFace recognition is handled by AWS Rekognition (no local compilation required).Set credentials on the robot before running:```bashexport AWS_ACCESS_KEY_ID=...export AWS_SECRET_ACCESS_KEY=...export AWS_DEFAULT_REGION=us-east-1 # or your preferred region```Or use `aws configure` if the AWS CLI is installed. The app auto-creates aRekognition collection named `reachy-mini-recognizer` on first run.The IAM user/role needs: `rekognition:CreateCollection`,`rekognition:IndexFaces`, `rekognition:SearchFacesByImage`.## Running the AppRun directly (connects to a live Reachy Mini robot):43 unmodified lines- **ENROLLING**: robot has detected an unrecognised face; waits for name to be submitted via the web UI (`POST /set_name`). Stores encoding in `face_db.json`, says "Nice to meet you, <name>!", then sleeps.**Helper modules**:- `recognizer/face_db.py` — AWS Rekognition wrapper. `load()` creates/opens the collection and returns its ID. `find_match(frame_bgr, collection_id)` returns the name or None (raises `NoFaceDetected` if no face present). `add_face(name, frame_bgr, collection_id)` enrolls a face. Similarity threshold = 85 (0–100 scale).- `recognizer/tts.py` — synthesises text via `espeak-ng -s 140 -w <tmp.wav>`, plays via `media.play_sound()`, then sleeps to let playback finish.**Settings UI** (`recognizer/static/`):
10 unmodified lines1112131415161710 unmodified linesrequires-python = ">=3.10"dependencies = ["reachy-mini","face-recognition","scipy",]keywords = ["reachy-mini-app", "reachy-mini"]10 unmodified lines111213141516171810 unmodified linesrequires-python = ">=3.10"dependencies = ["reachy-mini","boto3","Pillow","scipy",]keywords = ["reachy-mini-app", "reachy-mini"]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Face database: persist face encodings keyed by name."""import jsonfrom pathlib import Pathfrom typing import Optionalimport numpy as nptry:import face_recognitionexcept ImportError as exc:raise ImportError("face-recognition is required: pip install face-recognition") from excDB_PATH = Path(__file__).parent / "face_db.json"def load() -> dict[str, list[list[float]]]:if DB_PATH.exists():return json.loads(DB_PATH.read_text())return {}def save(db: dict[str, list[list[float]]]) -> None:DB_PATH.write_text(json.dumps(db, indent=2))def find_match(encoding: np.ndarray,db: dict[str, list[list[float]]],tolerance: float = 0.55,) -> Optional[str]:for name, enc_list in db.items():known = [np.array(e) for e in enc_list]if any(face_recognition.compare_faces(known, encoding, tolerance=tolerance)):return namereturn Nonedef add_face(name: str,encoding: np.ndarray,db: dict[str, list[list[float]]],max_per_person: int = 5,) -> None:if name not in db:db[name] = []if len(db[name]) < max_per_person:db[name].append(encoding.tolist())save(db)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""Face database: backed by AWS Rekognition.Requires boto3 and AWS credentials configured (e.g. via environment variablesAWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION, or an IAM role)."""import ioimport loggingfrom typing import Optionalimport boto3from botocore.exceptions import BotoCoreError, ClientErrorfrom PIL import Imagelogger = logging.getLogger(__name__)COLLECTION_ID = "reachy-mini-recognizer"class NoFaceDetected(Exception):"""Raised when no face is found in the provided image."""def _client():return boto3.client("rekognition")def _to_jpeg(frame_bgr) -> bytes:rgb = frame_bgr[:, :, ::-1]buf = io.BytesIO()Image.fromarray(rgb).save(buf, format="JPEG")return buf.getvalue()def load() -> str:"""Ensure the Rekognition collection exists; return its ID."""client = _client()try:client.create_collection(CollectionId=COLLECTION_ID)logger.info("Created Rekognition collection '%s'", COLLECTION_ID)except client.exceptions.ResourceAlreadyExistsException:passreturn COLLECTION_IDdef find_match(frame_bgr,collection_id: str,threshold: float = 85.0,) -> Optional[str]:"""Search for a face in frame_bgr against the collection.Returns the matched name if recognised, None if a face is present butunknown. Raises NoFaceDetected if no face appears in the image at all."""client = _client()try:resp = client.search_faces_by_image(CollectionId=collection_id,Image={"Bytes": _to_jpeg(frame_bgr)},FaceMatchThreshold=threshold,MaxFaces=1,)matches = resp.get("FaceMatches", [])if matches:return matches[0]["Face"]["ExternalImageId"]return None # face detected but not in collectionexcept client.exceptions.InvalidParameterException:raise NoFaceDetected()except (BotoCoreError, ClientError) as exc:logger.warning("Rekognition error: %s", exc)raise NoFaceDetected()def add_face(name: str, frame_bgr, collection_id: str) -> None:"""Index the face in frame_bgr under name in the collection."""client = _client()resp = client.index_faces(CollectionId=collection_id,Image={"Bytes": _to_jpeg(frame_bgr)},ExternalImageId=name,MaxFaces=1,DetectionAttributes=[],)if not resp.get("FaceRecords"):raise ValueError("No face detected in enrollment image")
17 unmodified lines181920212223242526272829303132333414 unmodified lines495051525354555618 unmodified lines7576777879808182838485868750 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017111 unmodified lines18318418518618718818919017 unmodified linesfrom pydantic import BaseModelfrom reachy_mini import ReachyMini, ReachyMiniAppfrom recognizer.face_db import add_face, find_matchfrom recognizer.face_db import load as load_face_dbfrom recognizer.tts import speaktry:import face_recognition # noqa: F401 – checked at import timeexcept ImportError as exc:raise ImportError("face-recognition is required: pip install face-recognition") from exclogger = logging.getLogger(__name__)ACTIVE_TIMEOUT = 15.0 # seconds before returning to sleep with no face14 unmodified linesrequest_media_backend: str | None = Nonedef run(self, reachy_mini: ReachyMini, stop_event: threading.Event) -> None:import face_recognition as fr# --- Shared mutable state (main loop ↔ FastAPI handlers) ---_lock = threading.Lock()_shared: dict = {18 unmodified linesreturn {"state": _shared["state"]}# --- Initialise ---face_db = load_face_db()state = State.SLEEPINGdoa_angle = math.pi / 2 # default: facing frontspeech_count = 0active_start = 0.0last_face_check = 0.0pending_enc: Optional[np.ndarray] = Nonescan_t0 = 0.0 # reference time for head-scan idle animationreachy_mini.goto_sleep()50 unmodified lineshead=_look_direction(1.0, y_scan, 0.0))# Throttled face recognitionif now - last_face_check >= FACE_INTERVAL:last_face_check = nowframe = reachy_mini.media.get_frame()if frame is not None:rgb = frame[::2, ::2, ::-1] # 2× downsample + BGR→RGBlocs = fr.face_locations(rgb, model="hog")if locs:# Scale locations back to full-res for accurate encodingfull_locs = [(t*2, r*2, b*2, l*2) for t, r, b, l in locs]encs = fr.face_encodings(frame[:, :, ::-1], full_locs)if encs:enc = encs[0]name = find_match(enc, face_db)if name:speak(f"Hi {name}!", reachy_mini)reachy_mini.goto_sleep()state = State.SLEEPINGelse:speak("I don't know you yet. ""Please enter your name on the control panel.",reachy_mini,)pending_enc = encwith _lock:_shared["pending_name"] = Nonestate = State.ENROLLING# Timeout: nobody showed upif state == State.ACTIVE and time.time() - active_start > ACTIVE_TIMEOUT:11 unmodified linesif name:with _lock:_shared["pending_name"] = Noneif pending_enc is not None:add_face(name, pending_enc, face_db)speak(f"Nice to meet you, {name}!", reachy_mini)reachy_mini.goto_sleep()state = State.SLEEPING17 unmodified lines1819202122232425262714 unmodified lines42434445464718 unmodified lines6667686970717273747576777850 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115215315415515615711 unmodified lines16917017117217317417517617717817917 unmodified linesfrom pydantic import BaseModelfrom reachy_mini import ReachyMini, ReachyMiniAppfrom recognizer.face_db import NoFaceDetected, add_face, find_matchfrom recognizer.face_db import load as load_face_dbfrom recognizer.tts import speaklogger = logging.getLogger(__name__)ACTIVE_TIMEOUT = 15.0 # seconds before returning to sleep with no face14 unmodified linesrequest_media_backend: str | None = Nonedef run(self, reachy_mini: ReachyMini, stop_event: threading.Event) -> None:# --- Shared mutable state (main loop ↔ FastAPI handlers) ---_lock = threading.Lock()_shared: dict = {18 unmodified linesreturn {"state": _shared["state"]}# --- Initialise ---collection_id = load_face_db()state = State.SLEEPINGdoa_angle = math.pi / 2 # default: facing frontspeech_count = 0active_start = 0.0last_face_check = 0.0pending_frame: Optional[np.ndarray] = Nonescan_t0 = 0.0 # reference time for head-scan idle animationreachy_mini.goto_sleep()50 unmodified lineshead=_look_direction(1.0, y_scan, 0.0))# Throttled face recognition via AWS Rekognitionif now - last_face_check >= FACE_INTERVAL:last_face_check = nowframe = reachy_mini.media.get_frame()if frame is not None:try:name = find_match(frame, collection_id)if name:speak(f"Hi {name}!", reachy_mini)reachy_mini.goto_sleep()state = State.SLEEPINGelse:speak("I don't know you yet. ""Please enter your name on the control panel.",reachy_mini,)pending_frame = framewith _lock:_shared["pending_name"] = Nonestate = State.ENROLLINGexcept NoFaceDetected:pass # no face in frame yet, keep scanning# Timeout: nobody showed upif state == State.ACTIVE and time.time() - active_start > ACTIVE_TIMEOUT:11 unmodified linesif name:with _lock:_shared["pending_name"] = Noneif pending_frame is not None:try:add_face(name, pending_frame, collection_id)except ValueError as exc:logger.warning("Enrollment failed: %s", exc)speak(f"Nice to meet you, {name}!", reachy_mini)reachy_mini.goto_sleep()state = State.SLEEPING
CLAUDE.md+17-2
pyproject.toml+2-1
recognizer/face_db.py+72-38
recognizer/main.py+27-38