entri-proctor-api / test_ai_engine.py
DhyandevP's picture
Upgrade face detector to OpenCV YuNet ONNX and bundle model
c8084d0
Raw History Blame Contribute Delete
4.47 kB
"""
Test suite for AIEngine face detection and violation logic.
"""
import os
import sys
import cv2
import numpy as np
# Ensure midend_api directory is in sys.path
sys.path.insert(0, os.path.dirname(__file__))
from ai_engine import AIEngine
def create_test_face_crop():
"""Extract candidate face crop from user uploaded screenshot if available, or create synthetic test."""
screenshot_path = "/home/dhyandevp/.gemini/antigravity/brain/286e7b13-8376-4f09-9437-cb36e645b7a5/.user_uploaded/media_1792030194478.png"
if os.path.exists(screenshot_path):
img = cv2.imread(screenshot_path)
# Crop the webcam frame inside the test interface
return img[177:495, 180:663]
return None
def test_ai_engine_initialization():
print("[TEST] Initializing AIEngine...")
engine = AIEngine()
assert engine.face_detector is not None, "YuNet face detector should be initialized"
print(" -> PASS: Engine initialized successfully.")
return engine
def test_real_candidate_face_detected(engine):
print("[TEST] Testing real candidate face detection...")
face_img = create_test_face_crop()
if face_img is None:
print(" -> SKIP: User screenshot not found.")
return
success, buf = cv2.imencode(".jpg", face_img)
assert success, "Image encode should succeed"
result = engine.analyze(buf.tobytes())
print(" -> Result:", result)
assert result["face_detected"] is True, f"Expected face_detected=True, got {result}"
assert result["multiple_faces_detected"] is False, f"Expected single face, got {result}"
assert result["partial_face_detected"] is False, f"Expected full centered face, got {result}"
print(" -> PASS: Candidate face successfully detected!")
def test_blank_image_no_face(engine):
print("[TEST] Testing blank image (no face)...")
blank = np.zeros((300, 300, 3), dtype=np.uint8)
_, buf = cv2.imencode(".jpg", blank)
result = engine.analyze(buf.tobytes())
print(" -> Result:", result)
assert result["face_detected"] is False, "Expected no face on blank image"
assert result["multiple_faces_detected"] is False
assert result["partial_face_detected"] is False
print(" -> PASS: Blank image correctly identified as no face.")
def test_multiple_faces_detection(engine):
print("[TEST] Testing multiple faces detection...")
face_img = create_test_face_crop()
if face_img is None:
print(" -> SKIP: User screenshot not found.")
return
# Resize and place two faces side by side
face_small = cv2.resize(face_img, (240, 240))
two_faces = np.hstack([face_small, face_small])
_, buf = cv2.imencode(".jpg", two_faces)
result = engine.analyze(buf.tobytes())
print(" -> Result:", result)
assert result["face_detected"] is True
assert result["multiple_faces_detected"] is True, f"Expected multiple faces, got {result}"
print(" -> PASS: Multiple faces correctly detected!")
def test_partial_face_detection(engine):
print("[TEST] Testing partial face (edge cutoff)...")
face_img = create_test_face_crop()
if face_img is None:
print(" -> SKIP: User screenshot not found.")
return
# Shift the face so it sits right against the extreme top/left boundary
h, w = face_img.shape[:2]
shifted = np.zeros((h, w, 3), dtype=np.uint8)
half_w = w // 2
shifted[:, : (w - half_w)] = face_img[:, half_w :]
_, buf = cv2.imencode(".jpg", shifted)
result = engine.analyze(buf.tobytes())
print(" -> Result:", result)
assert result["partial_face_detected"] is True or result["face_detected"] is False
print(" -> PASS: Boundary margin check handled.")
def test_invalid_input(engine):
print("[TEST] Testing invalid input handling...")
try:
engine.analyze(b"")
assert False, "Should have raised ValueError on empty bytes"
except ValueError:
pass
try:
engine.analyze(b"not an image")
assert False, "Should have raised ValueError on corrupt image bytes"
except ValueError:
pass
print(" -> PASS: Invalid inputs properly rejected.")
if __name__ == "__main__":
engine = test_ai_engine_initialization()
test_real_candidate_face_detected(engine)
test_blank_image_no_face(engine)
test_multiple_faces_detection(engine)
test_partial_face_detection(engine)
test_invalid_input(engine)
print("\n[ALL TESTS PASSED SUCCESSFULLY!]")