অধ্যায়Phase 8 · রিয়েল-ওয়ার্ল্ড প্রজেক্ট
8.1 25 মিনিট পড়া

Face Recognition Attendance System

অফিস attendance automation।

🎬 গল্প দিয়ে শুরু
অফিস/স্কুলে কার্ড punch বা fingerprint-এর দিন শেষ। মুখ দেখিয়েই attendance — contactless, fast, tamper-proof। এই প্রজেক্টে শূন্য থেকে production-ready face attendance system বানাবো।

System architecture

text
Camera ─► Face Detect (YOLOv8-face / MTCNN)
       ─► Align + Crop (112x112)
       ─► Embedding (ArcFace / FaceNet) → 512-d vector
       ─► Cosine search in FAISS / pgvector
            │
            ├─ match (sim > 0.6) → log attendance
            └─ no match           → "unknown" alert
       ─► FastAPI dashboard + DB

Tech stack

  • InsightFace (buffalo_l) — SOTA detection + ArcFace embedding।
  • FAISS — fast vector search (millions of faces / ms)।
  • PostgreSQL + pgvector — persistent storage।
  • FastAPI — REST + websocket dashboard।
  • OpenCV — camera ingest, anti-spoofing।

১. Enrollment — নতুন employee যোগ

bash
pip install insightface onnxruntime-gpu faiss-cpu opencv-python sqlalchemy
python
enroll.py
from insightface.app import FaceAnalysis
import cv2, numpy as np

app = FaceAnalysis(name="buffalo_l", providers=["CUDAExecutionProvider"])
app.prepare(ctx_id=0, det_size=(640, 640))

def embed(image_path):
    img   = cv2.imread(image_path)
    faces = app.get(img)
    if not faces: raise ValueError("no face")
    return faces[0].normed_embedding   # (512,) float32

# 3–5 ছবি average → robust embedding
emb = np.mean([embed(p) for p in glob("sadiq/*.jpg")], axis=0)
emb /= np.linalg.norm(emb)
save_to_db(user_id="EMP001", name="Sadiqul Islam", embedding=emb)

২. Recognition — live attendance

python
recognize.py
import faiss, numpy as np, cv2, time
from datetime import datetime

index   = faiss.IndexFlatIP(512)        # cosine = inner product (normalized)
ids, names = load_all_from_db(index)
THRESHOLD  = 0.5

cap = cv2.VideoCapture(0)
seen_today = set()

while True:
    ok, frame = cap.read()
    if not ok: break
    for f in app.get(frame):
        q = f.normed_embedding.reshape(1, -1).astype("float32")
        sim, idx = index.search(q, 1)
        if sim[0][0] > THRESHOLD:
            uid = ids[idx[0][0]]
            if uid not in seen_today:
                mark_attendance(uid, datetime.now())
                seen_today.add(uid)
                cv2.putText(frame, names[idx[0][0]],
                            (int(f.bbox[0]), int(f.bbox[1])-10),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2)
    cv2.imshow("Attendance", frame)
    if cv2.waitKey(1) == 27: break

৩. Anti-spoofing (photo / video attack ঠেকানো)

  • Eye-blink detection (MediaPipe FaceMesh — EAR ratio)।
  • Depth check — phone screen flat, real face 3D (passive)।
  • Texture model — Silent-Face-Anti-Spoofing (MiniFASNet)।
  • Challenge — "head turn" / "smile" prompt।

৪. Database schema

sql
CREATE EXTENSION vector;

CREATE TABLE employees (
  id           TEXT PRIMARY KEY,
  name         TEXT NOT NULL,
  embedding    VECTOR(512) NOT NULL,
  enrolled_at  TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE attendance (
  id           BIGSERIAL PRIMARY KEY,
  employee_id  TEXT REFERENCES employees(id),
  ts           TIMESTAMPTZ DEFAULT NOW(),
  camera_id    TEXT,
  confidence   REAL
);

CREATE INDEX ON employees USING ivfflat (embedding vector_cosine_ops);

৫. Dashboard endpoints

python
@app.post("/enroll")        # multipart photo upload
@app.get ("/attendance")    # date range query
@app.get ("/today")         # live attendance feed
@app.ws  ("/stream")        # websocket — real-time camera tile

Production checklist

  • GDPR/privacy — consent, retention policy, encrypted embedding।
  • Edge deployment — Jetson Nano পর্যন্ত যথেষ্ট।
  • Multi-camera sync — NTP time + camera_id।
  • Late entry / early leave rule engine।
  • Daily CSV export + email report।
প্র্যাকটিস টাস্ক
  1. ৫ জন colleague enroll করে real-time attendance app বানান।
  2. Anti-spoofing হিসেবে eye-blink challenge add করুন।
  3. Monthly attendance PDF report auto-generate করুন।