cleartechs's picture
Upload 5 files
ae095c3 verified
Raw History Blame Contribute Delete
21.3 kB
import os
import secrets
import hashlib
import json
import urllib.request
import urllib.error
import sys
import traceback
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv
load_dotenv()
# ── Safe Imports and Model Initialization ─────────────────────────────────────
try:
from fastapi import FastAPI, UploadFile, File, HTTPException, Depends, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import cv2
import numpy as np
app = FastAPI(title="CC Attendance Face Recognition API", version="2.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
yunet_path = os.path.join(BASE_DIR, "yunet.onnx")
sface_path = os.path.join(BASE_DIR, "sface.onnx")
detector = cv2.FaceDetectorYN.create(yunet_path, "", (320, 320), 0.6, 0.3, 5000)
recognizer = cv2.FaceRecognizerSF.create(sface_path, "")
except Exception as e:
print("!!! FATAL STARTUP ERROR !!!", file=sys.stderr, flush=True)
traceback.print_exc(file=sys.stderr)
sys.stderr.flush()
sys.exit(1)
SUPABASE_URL = os.getenv("SUPABASE_URL", "")
SUPABASE_KEY = os.getenv("SUPABASE_KEY", "") # anon key is fine β€” only reads profiles
API_AUTH_KEY = os.getenv("API_AUTH_KEY", "")
def verify_api_key(x_api_key: str = Header(None)):
if API_AUTH_KEY and x_api_key != API_AUTH_KEY:
raise HTTPException(401, detail="Unauthorized access")
def _sb_headers():
return {
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": "application/json",
}
def get_embedding(img: np.ndarray):
try:
shape = img.shape
h = shape[0]
w = shape[1]
if len(shape) == 2:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
elif len(shape) == 3 and shape[2] == 4:
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
detector.setInputSize((w, h))
_, faces = detector.detect(img)
if faces is not None and len(faces) > 0:
face_align = recognizer.alignCrop(img, faces[0])
feat = recognizer.feature(face_align)
return feat[0].tolist()
except Exception as e:
print(f"[Embedding] error: {e}")
return None
# ─────────────────────────────────────────────────────────────────────────────
# Root
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/")
def home():
return {"status": "running", "message": "CC Attendance API v2 πŸš€", "version": "2.0.0"}
# ─────────────────────────────────────────────────────────────────────────────
# Face: Extract embedding
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/v1/face/extract", dependencies=[Depends(verify_api_key)])
async def extract_face(file: UploadFile = File(...)):
contents = await file.read()
nparr = np.frombuffer(contents, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if img is None:
raise HTTPException(400, detail="Invalid image")
embedding = get_embedding(img)
if not embedding:
raise HTTPException(400, detail="No face detected")
return {"status": "success", "embedding": embedding}
# ─────────────────────────────────────────────────────────────────────────────
# Face: Anti-Spoofing check (DeepFace Silent Face Anti-Spoofing)
# Returns { "is_real": true/false, "score": 0.0-1.0 }
# Called by Flutter BEFORE face recognition to reject photos/screens.
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/v1/face/anti-spoof", dependencies=[Depends(verify_api_key)])
async def anti_spoof_check(file: UploadFile = File(...)):
import tempfile, os
contents = await file.read()
nparr = np.frombuffer(contents, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if img is None:
raise HTTPException(400, detail="Invalid image")
# Write to a temp file because DeepFace.extract_faces expects a file path or ndarray
tmp_path = None
try:
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
tmp_path = tmp.name
tmp.write(contents)
from deepface import DeepFace
# extract_faces with anti_spoofing=True runs the Silent Face Anti-Spoofing model
faces = DeepFace.extract_faces(
img_path=tmp_path,
detector_backend="opencv",
anti_spoofing=True,
enforce_detection=False,
)
if not faces:
raise HTTPException(400, detail="No face detected in image")
# DeepFace returns a list; take the first (largest) face
face_data = faces[0]
is_real = face_data.get("is_real", False)
score = float(face_data.get("antispoof_score", 0.0))
# Check blurriness of the face to detect if they are shaking a photo/screen
# to trick the liveness classifier
facial_area = face_data.get("facial_area", {})
x, y, w, h = facial_area.get("x", 0), facial_area.get("y", 0), facial_area.get("w", 0), facial_area.get("h", 0)
# Crop the face region if coordinates are valid, else use the whole image
if w > 0 and h > 0:
face_img = img[max(0, y):min(img.shape[0], y+h), max(0, x):min(img.shape[1], x+w)]
else:
face_img = img
gray_face = cv2.cvtColor(face_img, cv2.COLOR_BGR2GRAY)
blur_score = cv2.Laplacian(gray_face, cv2.CV_64F).var()
print(f"[AntiSpoof] Face blur score (Laplacian variance): {blur_score:.2f}")
# A low Laplacian variance indicates high blur. Shaking a photo results in low variance.
# Threshold of 55 is chosen as a safe but effective value.
if blur_score < 55.0:
return {
"is_real": False,
"score": 0.0,
"reason": "Image is too blurry. Please hold steady and try again."
}
return {"is_real": is_real, "score": round(score, 4)}
except HTTPException:
raise
except Exception as e:
print(f"[AntiSpoof] error: {e}")
# On error (DeepFace not installed yet / model not downloaded),
# return is_real=True so the app does not block legitimate users
# while the model downloads on first run.
return {"is_real": True, "score": 1.0, "warning": str(e)}
finally:
if tmp_path and os.path.exists(tmp_path):
os.remove(tmp_path)
# ─────────────────────────────────────────────────────────────────────────────
# NFC Token: Generate a secure token for an employee's NFC tag
# Called by admin during NFC enrollment
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/v1/nfc/generate-token", dependencies=[Depends(verify_api_key)])
async def generate_nfc_token(body: dict):
"""
Generates a secure token for an employee's NFC tag.
Input: { "employeeId": "emp_123456", "employeeCode": "EMP001" }
Output: { "token": "<hex>", "tokenHash": "<sha256>", "nfcPayload": { ... } }
NOTE: The token hash is NOT written to Supabase here.
Flutter saves it directly using the authenticated Supabase client,
so no service role key is needed.
"""
employee_id = body.get("employeeId")
employee_code = body.get("employeeCode")
if not employee_id or not employee_code:
raise HTTPException(400, detail="employeeId and employeeCode are required")
# Generate cryptographically secure random token
raw_token = secrets.token_hex(32)
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
# The JSON payload to be written to the NFC card's NDEF record
nfc_payload = {
"employeeId": employee_id,
"employeeCode": employee_code,
"token": raw_token,
"type": "attendance",
"issued": datetime.now(timezone.utc).isoformat(),
}
# Flutter will call Supabase directly to store token_hash in profiles
return {
"status": "success",
"token": raw_token,
"tokenHash": token_hash,
"nfcPayload": nfc_payload,
}
# ─────────────────────────────────────────────────────────────────────────────
# NFC Token: Verify token from a scanned NFC tag
# Called at check-in/check-out
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/v1/nfc/verify-token", dependencies=[Depends(verify_api_key)])
async def verify_nfc_token(body: dict):
"""
Verifies a token scanned from an NFC card.
Uses the anon key to read profiles β€” no service role needed.
Input: { "employeeId": "emp_123456", "token": "<raw_token>", "type": "attendance" }
Output: { "valid": true/false, "employeeId": "...", "message": "..." }
"""
employee_id = body.get("employeeId")
raw_token = body.get("token")
tag_type = body.get("type", "")
if not employee_id or not raw_token:
raise HTTPException(400, detail="employeeId and token are required")
if tag_type != "attendance":
return {"valid": False, "message": "Invalid NFC tag type"}
# Fetch the stored hash from Supabase using anon key (read-only)
stored_hash = None
if SUPABASE_URL and SUPABASE_KEY:
try:
url = f"{SUPABASE_URL}/rest/v1/profiles?id=eq.{employee_id}&select=nfc_token_hash,full_name"
req = urllib.request.Request(url, headers=_sb_headers())
with urllib.request.urlopen(req, timeout=10) as resp:
rows = json.loads(resp.read())
if rows:
stored_hash = rows[0].get("nfc_token_hash")
except Exception as e:
print(f"[NFC Verify] Supabase fetch error: {e}")
if not stored_hash:
# No token stored β†’ UID-only card, skip token check (treat as valid)
return {"valid": True, "employeeId": employee_id, "message": "No token registered β€” UID-only mode"}
# Constant-time comparison to prevent timing attacks
provided_hash = hashlib.sha256(raw_token.encode()).hexdigest()
is_valid = secrets.compare_digest(stored_hash, provided_hash)
if is_valid:
return {"valid": True, "employeeId": employee_id, "message": "Token verified"}
else:
return {"valid": False, "message": "Token mismatch β€” card may be cloned or corrupted"}
# Helper to parse timezone-aware datetime strings safely
def parse_datetime(dt_str):
if dt_str.endswith("Z"):
dt_str = dt_str[:-1] + "+00:00"
return datetime.fromisoformat(dt_str)
# ─────────────────────────────────────────────────────────────────────────────
# Attendance: Determine action automatically
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/v1/attendance/determine-action", dependencies=[Depends(verify_api_key)])
async def determine_attendance_action(body: dict):
"""
Input:
{
"employeeId": "emp_123456",
"currentTime": "2026-05-25T10:30:00+05:30",
"requestedAction": "auto" | "check_in" | "check_out" | "half_day" | "break"
}
"""
employee_id = body.get("employeeId")
current_time = body.get("currentTime")
requested_action = body.get("requestedAction", "auto").lower()
if not employee_id:
raise HTTPException(400, detail="employeeId is required")
now = parse_datetime(current_time) if current_time else datetime.now(timezone.utc)
tz_kolkata = timezone(timedelta(hours=5, minutes=30))
now_local = now.astimezone(tz_kolkata)
hour = now_local.hour
minute = now_local.minute
time_decimal = hour + minute / 60.0
# Retrieve dynamic shift configurations with fallback defaults
shift_start = body.get("shiftStart", 10.0)
shift_end = body.get("shiftEnd", 19.0)
half_day_hours = body.get("halfDayHours", 4.0)
late_grace = body.get("lateGrace", 0.0)
# ── Fetch today's logs from Supabase ─────────────────────────────────────
today_start = now_local.replace(hour=0, minute=0, second=0, microsecond=0).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
logs = []
if SUPABASE_URL and SUPABASE_KEY:
try:
url = (
f"{SUPABASE_URL}/rest/v1/attendance_logs"
f"?employee_id=eq.{employee_id}"
f"&timestamp=gte.{today_start}"
f"&order=timestamp.asc"
f"&select=type,timestamp"
)
req = urllib.request.Request(url, headers=_sb_headers())
with urllib.request.urlopen(req, timeout=10) as resp:
logs = json.loads(resp.read())
except Exception as e:
print(f"[Determine Action] Supabase error: {e}")
# Parse timestamps to tz-aware datetimes
for l in logs:
l["parsed_time"] = parse_datetime(l["timestamp"])
has_check_in = len(logs) > 0
# Check out logs (distinguish first-log half_day check-in vs subsequent checkout)
checkout_logs = []
for i, l in enumerate(logs):
if l["type"] == "check_out":
checkout_logs.append(l)
elif l["type"] == "half_day" and i > 0:
checkout_logs.append(l)
has_check_out = len(checkout_logs) > 0
break_ins = [l for l in logs if l["type"] == "break_in"]
break_outs = [l for l in logs if l["type"] == "break_out"]
currently_on_break = len(break_ins) > len(break_outs)
# 1. Grace Period for accidental Check-Out (30 minutes)
if has_check_out:
last_checkout_time = max(l["parsed_time"] for l in checkout_logs)
elapsed_seconds = (now_local - last_checkout_time).total_seconds()
# If they scan again within 30 minutes, they check back in
if elapsed_seconds <= 1800:
if requested_action in ("auto", "check_in"):
return {
"action": "CHECK_IN",
"reason": f"Accidental checkout detected ({int(elapsed_seconds/60)}m ago). Re-checked in successfully."
}
elif requested_action == "break":
action = "BREAK_OUT" if currently_on_break else "BREAK_IN"
return {
"action": action,
"reason": "Accidental checkout overridden for Break."
}
else:
# Over 30 minutes grace period, shift is closed
if requested_action in ("check_in", "auto"):
raise HTTPException(400, detail="Cannot check-in. The 30-minute accidental checkout grace period has expired.")
# 2. If requested action is specifically "break" (unified break mode)
if requested_action == "break":
if not has_check_in:
raise HTTPException(400, detail="Cannot take a break before checking in.")
action = "BREAK_OUT" if currently_on_break else "BREAK_IN"
return {
"action": action,
"reason": "Returning from break" if currently_on_break else "Starting break"
}
# 3. Handle manual overrides first to bypass strict time restrictions
if requested_action == "check_in":
if has_check_in:
raise HTTPException(400, detail="You are already logged in.")
else:
late_limit = shift_start + late_grace / 60.0
half_day_limit = 14.0 # 2:00 PM
if time_decimal > half_day_limit:
return {
"action": "HALF_DAY",
"reason": f"Manual check-in after half-day limit ({now_local.strftime('%I:%M %p')}) β€” marked as Half Day"
}
elif time_decimal > late_limit:
return {
"action": "LATE_MARK",
"reason": f"Manual late check-in ({now_local.strftime('%I:%M %p')}) β€” Late Mark recorded"
}
else:
return {
"action": "CHECK_IN",
"reason": f"Manual check-in at {now_local.strftime('%I:%M %p')}"
}
elif requested_action == "check_out":
if not has_check_in:
raise HTTPException(400, detail="Cannot check-out before checking in.")
return {
"action": "CHECK_OUT",
"reason": "Manual check-out recorded."
}
elif requested_action == "half_day":
if not has_check_in:
raise HTTPException(400, detail="Cannot mark Half Day checkout before checking in.")
return {
"action": "HALF_DAY",
"reason": "Manual Half Day checkout recorded."
}
# 4. If no check-in yet (auto mode fallback)
if not has_check_in:
cutoff = shift_end - half_day_hours
late_limit = shift_start + late_grace / 60.0
half_day_limit = 14.0 # 2:00 PM
if time_decimal > cutoff:
cutoff_hour = int(cutoff)
cutoff_minute = int((cutoff - cutoff_hour) * 60)
cutoff_str = f"{cutoff_hour:02d}:{cutoff_minute:02d}"
raise HTTPException(400, detail=f"Cannot check-in after {cutoff_str}. You must check in before {cutoff_str} to complete the minimum {int(half_day_hours)} hours required for a Half Day.")
elif time_decimal > half_day_limit:
return {
"action": "HALF_DAY",
"reason": f"Late check-in after shift limit ({now_local.strftime('%I:%M %p')}) β€” marked as Half Day"
}
elif time_decimal > late_limit:
return {
"action": "LATE_MARK",
"reason": f"Late check-in ({now_local.strftime('%I:%M %p')}) β€” Late Mark recorded"
}
else:
return {
"action": "CHECK_IN",
"reason": f"On-time check-in at {now_local.strftime('%I:%M %p')}"
}
# 5. Already checked in (and requested_action == "auto")
first_check_in = min(l["parsed_time"] for l in logs if l["type"] in ("check_in", "late_mark", "half_day"))
work_hours = (now_local - first_check_in).total_seconds() / 3600.0
# If scanning within 30 minutes of checking in, block it as duplicate
if work_hours < 0.5:
raise HTTPException(400, detail="You are already logged in. Please wait at least 30 minutes before checking out.")
# In auto mode, enforce shift duration relative to config
full_day_threshold = shift_end - shift_start - 1.0
if work_hours < full_day_threshold:
return {
"action": "HALF_DAY",
"reason": f"Checked out after {work_hours:.1f} hours of work (under {full_day_threshold:.1f} hours required for Full Day) β€” marked as Half Day"
}
else:
return {
"action": "CHECK_OUT",
"reason": f"Checked out after {work_hours:.1f} hours of work (Full Day)."
}
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port)