nomadro/apps/api/services/social_svc/face_check.py
Eric 499f2d3e26 Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 18:19:37 +08:00

493 lines
14 KiB
Python

"""Avatar face gate — detect + optional InsightFace RGB liveness.
Env / remote-config:
flags.socialAvatarFaceCheck admin SSE/WS switch (preferred)
SOCIAL_AVATAR_FACE_CHECK on|off env fallback (default off)
SOCIAL_AVATAR_FACE_ENGINE auto|insightface|opencv (default auto)
SOCIAL_AVATAR_FACE_STRICT fail closed when no engine (default off)
SOCIAL_AVATAR_FACE_MIN min faces (default 1)
SOCIAL_AVATAR_FACE_MAX max faces (default 1 — reject group photos)
SOCIAL_AVATAR_LIVENESS on|off (default on; InsightFace addon)
SOCIAL_AVATAR_LIVENESS_THRESHOLD 0..1 (default 0.5)
SOCIAL_AVATAR_INSIGHTFACE_MODEL buffalo_l|buffalo_sc (default buffalo_l)
"""
from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass
import cv2
import numpy as np
log = logging.getLogger("social_svc.face_check")
_lock = threading.Lock()
_insight_app = None
_insight_failed = False
_insight_liveness = False
@dataclass
class FaceCheckResult:
ok: bool
faces: int
engine: str
detail: str = ""
is_live: bool | None = None
live_score: float | None = None
def _env_bool(name: str, default: bool) -> bool:
raw = (os.getenv(name) or "").strip().lower()
if not raw:
return default
return raw in {"1", "true", "yes", "on"}
def face_check_enabled(purpose: str) -> bool:
if (purpose or "").strip().lower() not in {"avatar", "roster", "profile"}:
return False
# Remote-config (admin SSE/WS) wins when present; env is offline fallback.
try:
from social_svc.remote_flags import social_avatar_face_check_enabled
remote = social_avatar_face_check_enabled()
if remote is not None:
return bool(remote)
except Exception:
pass
# Default OFF for test phase; set SOCIAL_AVATAR_FACE_CHECK=on to force without admin.
return _env_bool("SOCIAL_AVATAR_FACE_CHECK", False)
def _engine_pref() -> str:
return (os.getenv("SOCIAL_AVATAR_FACE_ENGINE") or "auto").strip().lower()
def _min_faces() -> int:
try:
return max(1, int(os.getenv("SOCIAL_AVATAR_FACE_MIN") or "1"))
except ValueError:
return 1
def _max_faces() -> int:
try:
return max(_min_faces(), int(os.getenv("SOCIAL_AVATAR_FACE_MAX") or "1"))
except ValueError:
return 1
def _liveness_on() -> bool:
return _env_bool("SOCIAL_AVATAR_LIVENESS", True)
def _liveness_threshold() -> float:
try:
v = float(os.getenv("SOCIAL_AVATAR_LIVENESS_THRESHOLD") or "0.5")
except ValueError:
v = 0.5
return min(0.99, max(0.05, v))
def _decode_bgr(data: bytes):
arr = np.frombuffer(data, dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
return img
def _providers() -> list[str]:
providers = ["CPUExecutionProvider"]
try:
from onnxruntime import get_available_providers
avail = set(get_available_providers())
if "CUDAExecutionProvider" in avail:
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
except Exception:
pass
return providers
def _get_insightface():
global _insight_app, _insight_failed, _insight_liveness
if _insight_failed:
return None
if _insight_app is not None:
return _insight_app
with _lock:
if _insight_failed:
return None
if _insight_app is not None:
return _insight_app
try:
from insightface.app import FaceAnalysis
name = (os.getenv("SOCIAL_AVATAR_INSIGHTFACE_MODEL") or "buffalo_l").strip()
providers = _providers()
want_live = _liveness_on()
addons: tuple[str, ...] = ("liveness",) if want_live else ()
try:
app = FaceAnalysis(
name=name,
providers=providers,
addons=addons,
liveness_mode="normal",
liveness_threshold=_liveness_threshold(),
)
_insight_liveness = bool(addons) and "liveness" in app.addons
except Exception as live_exc:
# Model package without addon download — fall back to detection only
log.warning("insightface liveness init failed, detection-only: %s", live_exc)
app = FaceAnalysis(name=name, providers=providers)
_insight_liveness = False
ctx_id = 0 if providers[0].startswith("CUDA") else -1
app.prepare(ctx_id=ctx_id, det_size=(640, 640))
_insight_app = app
log.info(
"insightface ready model=%s providers=%s liveness=%s",
name,
providers,
_insight_liveness,
)
return _insight_app
except Exception as exc:
_insight_failed = True
log.warning("insightface unavailable: %s", exc)
return None
def _analyze_insightface(img) -> FaceCheckResult:
app = _get_insightface()
if app is None:
raise RuntimeError("insightface not loaded")
faces = app.get(img) or []
n = len(faces)
need = _min_faces()
cap = _max_faces()
if n < need:
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface",
detail="未检测到人脸,请上传本人清晰正脸照片",
)
if n > cap:
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface",
detail="请只上传一张本人正脸(不要合影)",
)
face = faces[0]
is_live = None
live_score = None
live = getattr(face, "liveness", None)
if live is not None:
is_live = getattr(live, "is_live", None)
try:
live_score = float(getattr(live, "live_score", None) or getattr(live, "score", 0) or 0)
except (TypeError, ValueError):
live_score = None
status = getattr(live, "status", None)
reason = getattr(live, "reason", None) or ""
if is_live is False:
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface+liveness",
detail="未通过真人检测,请用前置摄像头现场自拍(勿用网图/截图)",
is_live=False,
live_score=live_score,
)
if status == "input_rejected":
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface+liveness",
detail=str(reason) or "人脸区域不足,请靠近镜头、露出完整正脸再拍",
is_live=False,
live_score=live_score,
)
if _liveness_on() and _insight_liveness and is_live is not True:
# Addon loaded but face missing live flag — treat as fail-closed
return FaceCheckResult(
ok=False,
faces=n,
engine="insightface+liveness",
detail="真人检测未完成,请重新自拍一张正脸",
is_live=False,
live_score=live_score,
)
engine = "insightface+liveness" if is_live is True else "insightface"
return FaceCheckResult(
ok=True,
faces=n,
engine=engine,
is_live=is_live,
live_score=live_score,
)
def _haar_cascade_path() -> str:
from pathlib import Path
bundled = (
Path(__file__).resolve().parent
/ "assets"
/ "haarcascade_frontalface_default.xml"
)
if bundled.is_file():
return str(bundled)
data_dir = getattr(getattr(cv2, "data", None), "haarcascades", "") or ""
candidate = data_dir + "haarcascade_frontalface_default.xml"
if data_dir and Path(candidate).is_file():
return candidate
raise RuntimeError("haar cascade xml not found (bundle assets/)")
def _count_opencv(img) -> int:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
cascade = cv2.CascadeClassifier(_haar_cascade_path())
if cascade.empty():
raise RuntimeError("opencv haar cascade missing")
h, w = gray.shape[:2]
max_side = 960
if max(h, w) > max_side:
scale = max_side / float(max(h, w))
gray = cv2.resize(gray, (int(w * scale), int(h * scale)))
faces = cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(48, 48),
flags=cv2.CASCADE_SCALE_IMAGE,
)
return len(faces)
def check_face(
data: bytes,
*,
require_liveness: bool | None = None,
) -> FaceCheckResult:
"""Return face / liveness result; does not raise for soft failures.
require_liveness=None → follow SOCIAL_AVATAR_LIVENESS_REQUIRE (legacy).
Album upload should pass require_liveness=False (presence only).
Live challenge uses require_liveness=True.
"""
img = _decode_bgr(data)
if img is None or img.size == 0:
return FaceCheckResult(ok=False, faces=0, engine="none", detail="无法解码图片")
want_live = (
_liveness_on() and _env_bool("SOCIAL_AVATAR_LIVENESS_REQUIRE", True)
if require_liveness is None
else bool(require_liveness)
)
pref = _engine_pref()
engines: list[str] = []
if pref == "insightface":
engines = ["insightface"]
elif pref == "opencv":
engines = ["opencv"]
else:
engines = ["insightface", "opencv"]
last_err = ""
for eng in engines:
try:
if eng == "insightface":
result = _analyze_insightface(img)
if not want_live and result.faces >= _min_faces():
# Presence-only: keep face count even if RGB liveness failed
if not result.ok and result.faces > 0:
return FaceCheckResult(
ok=True,
faces=result.faces,
engine=result.engine or "insightface",
detail="人脸已识别,请继续现场实拍核验",
is_live=result.is_live,
live_score=result.live_score,
)
return result
n = _count_opencv(img)
need = _min_faces()
cap = _max_faces()
if n < need:
return FaceCheckResult(
ok=False,
faces=n,
engine="opencv",
detail="未检测到人脸,请上传本人清晰正脸照片",
)
if n > cap:
return FaceCheckResult(
ok=False,
faces=n,
engine="opencv",
detail="请只上传一张本人正脸(不要合影)",
)
if want_live and _liveness_on():
return FaceCheckResult(
ok=False,
faces=n,
engine="opencv",
detail="请用摄像头现场自拍以完成真人验证",
)
return FaceCheckResult(ok=True, faces=n, engine="opencv")
except Exception as exc:
last_err = str(exc)
log.warning("face engine %s failed: %s", eng, exc)
continue
# Fail closed: never stamp face_ok=true when no detector ran.
# Upload path still persists the file with face_ok=false when gate is off.
log.warning("face check unavailable (%s); marking no-face", last_err or "no engine")
return FaceCheckResult(
ok=False,
faces=0,
engine="none",
detail=f"人脸检测不可用: {last_err or 'no engine'}",
)
def assert_avatar_has_face(
data: bytes,
*,
require_liveness: bool | None = None,
) -> FaceCheckResult:
"""Raise ValueError when check fails."""
result = check_face(data, require_liveness=require_liveness)
if not result.ok:
raise ValueError(result.detail or "未检测到人脸")
return result
@dataclass
class ChallengeResult:
ok: bool
detail: str = ""
similarity: float | None = None
yaw_delta: float | None = None
front: FaceCheckResult | None = None
turn: FaceCheckResult | None = None
def _cosine(a, b) -> float:
a = np.asarray(a, dtype=np.float32).ravel()
b = np.asarray(b, dtype=np.float32).ravel()
denom = float(np.linalg.norm(a) * np.linalg.norm(b) + 1e-9)
return float(np.dot(a, b) / denom)
def _yaw_proxy(kps) -> float:
"""Nose offset vs eye midpoint, normalized by eye distance (≈ yaw proxy)."""
pts = np.asarray(kps, dtype=np.float32)
if pts.shape[0] < 3:
return 0.0
le, re, nose = pts[0], pts[1], pts[2]
mid_x = (float(le[0]) + float(re[0])) * 0.5
eye_w = abs(float(re[0]) - float(le[0])) + 1e-6
return (float(nose[0]) - mid_x) / eye_w
def _extract_face_features(data: bytes):
"""Return (FaceCheckResult, embedding|None, yaw|None)."""
img = _decode_bgr(data)
if img is None or img.size == 0:
return (
FaceCheckResult(ok=False, faces=0, engine="none", detail="无法解码图片"),
None,
None,
)
# Prefer insightface for embeddings; also runs liveness when enabled
try:
app = _get_insightface()
if app is None:
raise RuntimeError("insightface not loaded")
faces = app.get(img) or []
base = _analyze_insightface(img)
if not base.ok or not faces:
return base, None, None
face = faces[0]
emb = getattr(face, "normed_embedding", None)
if emb is None:
emb = getattr(face, "embedding", None)
yaw = _yaw_proxy(getattr(face, "kps", None)) if getattr(face, "kps", None) is not None else None
return base, emb, yaw
except Exception as exc:
log.warning("challenge feature extract failed: %s", exc)
# Fall back to presence-only (no identity match)
presence = check_face(data)
return presence, None, None
def verify_pose_challenge(front_bytes: bytes, turn_bytes: bytes) -> ChallengeResult:
"""Two-frame selfie: same person + measurable head turn + face/liveness gates."""
front, emb_a, yaw_a = _extract_face_features(front_bytes)
if not front.ok:
return ChallengeResult(ok=False, detail=front.detail or "正脸核验失败", front=front)
turn, emb_b, yaw_b = _extract_face_features(turn_bytes)
if not turn.ok:
return ChallengeResult(
ok=False,
detail=turn.detail or "转头照核验失败",
front=front,
turn=turn,
)
sim = None
if emb_a is not None and emb_b is not None:
sim = _cosine(emb_a, emb_b)
min_sim = 0.32
try:
min_sim = float(os.getenv("SOCIAL_AVATAR_CHALLENGE_MIN_SIM") or "0.32")
except ValueError:
pass
if sim < min_sim:
return ChallengeResult(
ok=False,
detail="两张照片不是同一个人,请本人连续自拍完成核验",
similarity=sim,
front=front,
turn=turn,
)
yaw_delta = None
if yaw_a is not None and yaw_b is not None:
yaw_delta = abs(float(yaw_a) - float(yaw_b))
min_yaw = 0.06
try:
min_yaw = float(os.getenv("SOCIAL_AVATAR_CHALLENGE_MIN_YAW") or "0.06")
except ValueError:
pass
if yaw_delta < min_yaw:
return ChallengeResult(
ok=False,
detail="转头幅度不够,请稍微左右转头后再拍第二张",
similarity=sim,
yaw_delta=yaw_delta,
front=front,
turn=turn,
)
return ChallengeResult(
ok=True,
detail="",
similarity=sim,
yaw_delta=yaw_delta,
front=front,
turn=turn,
)