FACE_ID_IRON / app.py
Alexpro1213's picture
Update app.py
b8d9366 verified
Raw History Blame Contribute Delete
22.3 kB
import os
import cv2
import numpy as np
import math
import json
import base64
import urllib.request
import torch
import spaces
from fastapi import Request
from fastapi.responses import JSONResponse
import gradio as gr
# =====================================================================
# 1. ЗАВАНТАЖЕННЯ МОДЕЛЕЙ OPENCV 3D AI
# =====================================================================
YUNET_URL = "https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx"
SFACE_URL = "https://github.com/opencv/opencv_zoo/raw/main/models/face_recognition_sface/face_recognition_sface_2021dec.onnx"
def download_model(url, filename):
if not os.path.exists(filename):
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req) as resp, open(filename, 'wb') as f:
f.write(resp.read())
download_model(YUNET_URL, "face_detection_yunet_2023mar.onnx")
download_model(SFACE_URL, "face_recognition_sface_2021dec.onnx")
detector = cv2.FaceDetectorYN.create("face_detection_yunet_2023mar.onnx", "", (320, 320), 0.6, 0.3, 5000)
recognizer = cv2.FaceRecognizerSF.create("face_recognition_sface_2021dec.onnx", "")
MODEL_POINTS_3D = np.array([
(-30.0, 30.0, -30.0), (30.0, 30.0, -30.0), (0.0, 0.0, 0.0),
(-25.0, -40.0, -25.0), (25.0, -40.0, -25.0)
], dtype=np.float64)
REFERENCE_FEATURE = None
# =====================================================================
# 2. ZEROGPU ПРОГРІВ
# =====================================================================
@spaces.GPU
def gpu_warmup():
device = "cuda" if torch.cuda.is_available() else "cpu"
t = torch.ones((1, 1), device=device)
return str(t.device)
try:
gpu_warmup()
except:
pass
def get_3d_head_pose(landmarks_5, img_w, img_h):
focal = img_w
cam_mat = np.array([[focal, 0, img_w/2], [0, focal, img_h/2], [0, 0, 1]], dtype=np.float64)
success, rvec, _ = cv2.solvePnP(MODEL_POINTS_3D, np.array(landmarks_5, dtype=np.float64), cam_mat, np.zeros((4, 1)), flags=cv2.SOLVEPNP_EPNP)
if not success: return 0.0, 0.0, 0.0
rmat, _ = cv2.Rodrigues(rvec)
angles, _, _, _, _, _ = cv2.RQDecomp3x3(rmat)
return float(angles[1]), float(angles[0]), float(angles[2])
def check_anti_spoof(frame, box, landmarks_5):
x, y, w, h = box
re, le, nose, _, _ = landmarks_5
dist_r = math.hypot(nose[0] - re[0], nose[1] - re[1])
dist_l = math.hypot(nose[0] - le[0], nose[1] - le[1])
eye_span = math.hypot(le[0] - re[0], le[1] - re[1]) or 1.0
depth_score = (abs(dist_r - dist_l) / (eye_span * 0.4)) * 100.0
pad = int(w * 0.25)
ih, iw = frame.shape[:2]
roi = frame[max(0, y-pad):min(ih, y+h+pad), max(0, x-pad):min(iw, x+w+pad)]
bezel = False
if roi.size > 0:
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 70, 190)
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 85, minLineLength=int(w*0.55), maxLineGap=10)
if lines is not None and len(lines) >= 3:
bezel = True
return bezel, float(depth_score), "Виявлено рамку екрана!" if bezel else ""
# =====================================================================
# 3. HTML ІНТЕРФЕЙСУ
# =====================================================================
HTML_UI = """
<div id="faceid-root" style="max-width:960px; margin:0 auto; font-family:-apple-system, BlinkMacSystemFont, sans-serif; color:#fff;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
<div>
<h2 style="margin:0; font-size:22px; font-weight:700;">Apple Face ID 3D Pro</h2>
<p style="margin:4px 0 0; font-size:13px; color:rgba(255,255,255,0.6);">Hugging Face ZeroGPU AI Core</p>
</div>
<div style="background:rgba(255,255,255,0.08); border:1px solid rgba(255,255,255,0.15); padding:6px 14px; border-radius:999px; font-size:13px; display:flex; align-items:center; gap:8px;">
<span id="faceid-ws-dot" style="width:8px; height:8px; border-radius:50%; background:#ffd60a; transition:all 0.3s;"></span>
<span id="faceid-ws-text">З'єднання...</span>
</div>
</div>
<div style="display:grid; grid-template-columns:1fr 1.35fr; gap:16px;">
<div style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.12); border-radius:20px; padding:16px; display:flex; flex-direction:column; gap:12px;">
<div style="display:flex; justify-content:space-between; align-items:center;">
<h3 style="margin:0; font-size:15px;">Еталонний профіль</h3>
<span id="faceid-ref-tag" style="font-size:11px; padding:2px 8px; border-radius:999px; background:rgba(255,255,255,0.1);">Не встановлено</span>
</div>
<div style="position:relative; width:100%; aspect-ratio:4/3; background:#08080c; border-radius:14px; overflow:hidden; display:flex; align-items:center; justify-content:center; border:1px solid rgba(255,255,255,0.08);">
<img id="faceid-ref-preview" style="max-width:100%; max-height:100%; object-fit:contain; display:none; border-radius:10px;">
<span id="faceid-ref-ph" style="color:rgba(255,255,255,0.4); font-size:13px; text-align:center; padding:16px;">Завантажте фото або зніміть з камери</span>
</div>
<div style="display:flex; gap:8px;">
<label style="flex:1; background:rgba(255,255,255,0.08); border:1px solid rgba(255,255,255,0.12); padding:10px; border-radius:999px; text-align:center; font-size:13px; font-weight:600; cursor:pointer;">
З файлу
<input type="file" id="faceid-file-input" accept="image/*" style="display:none;">
</label>
<button id="faceid-btn-capture" style="flex:1; background:rgba(255,255,255,0.08); color:#fff; border:1px solid rgba(255,255,255,0.12); padding:10px; border-radius:999px; font-size:13px; font-weight:600; cursor:pointer;">
З камери
</button>
</div>
</div>
<div style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.12); border-radius:20px; padding:16px; display:flex; flex-direction:column; gap:12px;">
<h3 style="margin:0; font-size:15px;">3D Сенсор Face ID</h3>
<div style="position:relative; width:100%; aspect-ratio:4/3; background:#08080c; border-radius:14px; overflow:hidden; display:flex; align-items:center; justify-content:center; border:1px solid rgba(255,255,255,0.08);">
<video id="faceid-video" autoplay playsinline muted style="position:absolute; width:100%; height:100%; object-fit:cover; transform:scaleX(-1);"></video>
<canvas id="faceid-overlay" style="position:absolute; inset:0; width:100%; height:100%; pointer-events:none; z-index:10;"></canvas>
<div id="faceid-island" style="position:absolute; top:12px; left:50%; transform:translateX(-50%); background:rgba(20,20,28,0.95); border:1px solid rgba(255,255,255,0.2); padding:6px 16px; border-radius:999px; font-size:12px; font-weight:500; z-index:20; white-space:nowrap; transition:all 0.25s;">
Очікування запуску...
</div>
</div>
<div style="display:grid; grid-template-columns:1fr 1fr; gap:8px; padding:10px; background:rgba(255,255,255,0.03); border-radius:12px; font-size:12px;">
<div>3D Ракурс: <strong id="faceid-t-pose" style="color:#0a84ff;">0° / 0°</strong></div>
<div>3D Глибина: <strong id="faceid-t-depth">0%</strong></div>
<div>Анти-спуфінг: <strong id="faceid-t-spoof" style="color:#30d158;">Живе 3D</strong></div>
<div>Статус: <strong id="faceid-t-status" style="color:#ffd60a;">Очікування</strong></div>
</div>
<button id="faceid-btn-cam" style="background:#ffffff; color:#000000; border:none; padding:12px; border-radius:999px; font-weight:600; font-size:14px; cursor:pointer;">
Запустити камеру
</button>
</div>
</div>
<canvas id="faceid-hidden" style="display:none;"></canvas>
</div>
"""
# =====================================================================
# 4. JAVASCRIPT ЛОГІКА
# =====================================================================
JS_RUNNER = """
() => {
function initFaceID() {
const video = document.getElementById('faceid-video');
const overlay = document.getElementById('faceid-overlay');
const hiddenCanvas = document.getElementById('faceid-hidden');
const wsDot = document.getElementById('faceid-ws-dot');
const wsText = document.getElementById('faceid-ws-text');
const island = document.getElementById('faceid-island');
const btnToggleCam = document.getElementById('faceid-btn-cam');
const btnCaptureRef = document.getElementById('faceid-btn-capture');
const fileInput = document.getElementById('faceid-file-input');
const refPreview = document.getElementById('faceid-ref-preview');
const refPh = document.getElementById('faceid-ref-ph');
const refTag = document.getElementById('faceid-ref-tag');
const tPose = document.getElementById('faceid-t-pose');
const tDepth = document.getElementById('faceid-t-depth');
const tSpoof = document.getElementById('faceid-t-spoof');
const tStatus = document.getElementById('faceid-t-status');
if (!video || !btnToggleCam) {
setTimeout(initFaceID, 100);
return;
}
let cameraActive = false;
let isSending = false;
async function checkHealth() {
try {
const res = await fetch('/api/health');
if (res.ok) {
wsDot.style.background = '#30d158';
wsDot.style.boxShadow = '0 0 10px #30d158';
wsText.textContent = "ZeroGPU онлайн";
island.textContent = "Подивіться в камеру";
} else {
throw new Error();
}
} catch {
wsDot.style.background = '#ffd60a';
wsText.textContent = "З'єднання...";
setTimeout(checkHealth, 2000);
}
}
function renderFrame(d) {
const ctx = overlay.getContext('2d');
ctx.clearRect(0, 0, overlay.width, overlay.height);
if (!d.detected) {
island.style.borderColor = 'rgba(255,255,255,0.2)';
island.style.color = '#fff';
island.textContent = "Подивіться в камеру";
tStatus.textContent = "Пошук...";
return;
}
tPose.textContent = `${d.pose.yaw}° / ${d.pose.pitch}°`;
tDepth.textContent = `${d.depth_score}%`;
tStatus.textContent = d.status;
if (d.is_spoof) {
tSpoof.textContent = "ПІДРОБКА";
tSpoof.style.color = "#ff453a";
island.style.borderColor = "#ff453a";
island.style.color = "#ff453a";
island.textContent = d.status;
} else {
tSpoof.textContent = "Живе 3D";
tSpoof.style.color = "#30d158";
island.style.borderColor = d.verified ? "#30d158" : "rgba(255,255,255,0.2)";
island.style.color = d.verified ? "#30d158" : "#fff";
island.textContent = d.status;
}
const [x, y, w, h] = d.box;
const sx = overlay.width / video.videoWidth;
const sy = overlay.height / video.videoHeight;
const rx = overlay.width - (x + w) * sx;
const ry = y * sy;
const rw = w * sx;
const rh = h * sy;
ctx.strokeStyle = d.verified ? '#30d158' : (d.is_spoof ? '#ff453a' : '#0a84ff');
ctx.lineWidth = 3.5;
ctx.strokeRect(rx, ry, rw, rh);
if (d.verified && window.confetti) {
window.confetti({ particleCount: 35, spread: 60, origin: { y: 0.6 } });
}
}
async function startCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: 'user' }
});
video.srcObject = stream;
cameraActive = true;
btnToggleCam.textContent = "Зупинити камеру";
btnToggleCam.style.background = "#ff453a";
btnToggleCam.style.color = "#fff";
video.onloadedmetadata = () => {
overlay.width = video.videoWidth;
overlay.height = video.videoHeight;
hiddenCanvas.width = 480;
hiddenCanvas.height = 360;
sendFrameLoop();
};
} catch {
alert("Дозвольте браузеру доступ до камери!");
}
}
function sendFrameLoop() {
if (!cameraActive) return;
if (!isSending) {
isSending = true;
const hCtx = hiddenCanvas.getContext('2d');
hCtx.drawImage(video, 0, 0, hiddenCanvas.width, hiddenCanvas.height);
hiddenCanvas.toBlob(async (blob) => {
if (blob && cameraActive) {
try {
const res = await fetch('/api/process_frame', {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: blob
});
if (res.ok) {
const data = await res.json();
renderFrame(data);
}
} catch {}
}
isSending = false;
if (cameraActive) requestAnimationFrame(sendFrameLoop);
}, 'image/jpeg', 0.65);
} else {
requestAnimationFrame(sendFrameLoop);
}
}
btnToggleCam.onclick = () => {
if (cameraActive) {
cameraActive = false;
if (video.srcObject) video.srcObject.getTracks().forEach(t => t.stop());
btnToggleCam.textContent = "Запустити камеру";
btnToggleCam.style.background = "#ffffff";
btnToggleCam.style.color = "#000000";
} else {
startCamera();
}
};
async function uploadReference(base64Data) {
try {
const res = await fetch('/api/set_reference', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ image: base64Data })
});
const ans = await res.json();
if (ans.success) {
refTag.textContent = "Збережено";
refTag.style.background = "rgba(48,209,88,0.2)";
refTag.style.color = "#30d158";
alert("3D-еталон успішно збережено!");
} else {
const errMsg = ans.error || ans.detail || ans.message || "Помилка збереження";
alert("Помилка: " + errMsg);
}
} catch (err) {
alert("Помилка зв'язку: " + err.message);
}
}
fileInput.onchange = (e) => {
const file = e.target.files[0];
if (!file) return;
const r = new FileReader();
r.onload = async ev => {
refPreview.src = ev.target.result;
refPreview.style.display = 'block';
refPh.style.display = 'none';
await uploadReference(ev.target.result);
};
r.readAsDataURL(file);
};
btnCaptureRef.onclick = async () => {
if (!cameraActive) return alert("Спочатку запустіть камеру!");
const c = document.createElement('canvas');
c.width = video.videoWidth;
c.height = video.videoHeight;
c.getContext('2d').drawImage(video, 0, 0);
const b64 = c.toDataURL('image/jpeg');
refPreview.src = b64;
refPreview.style.display = 'block';
refPh.style.display = 'none';
await uploadReference(b64);
};
checkHealth();
}
initFaceID();
}
"""
# =====================================================================
# 5. GRADIO BLOCKS
# =====================================================================
with gr.Blocks(title="Apple Face ID 3D Pro") as demo:
gr.HTML(HTML_UI)
demo.load(None, None, None, js=JS_RUNNER)
app = demo.app
# Реєстрація ендпоінтів у просторі /api/ (з підтримкою обох методів GET/POST)
@app.api_route("/api/health", methods=["GET", "POST"])
def health():
return JSONResponse({"status": "ok", "backend": "ZeroGPU"})
@app.api_route("/api/process_frame", methods=["GET", "POST"])
async def process_frame(request: Request):
global REFERENCE_FEATURE
if request.method == "GET":
return JSONResponse({"status": "ready"})
try:
data = await request.body()
frame = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
if frame is None:
return JSONResponse({"detected": False, "status": "Помилка кадру"})
h, w = frame.shape[:2]
detector.setInputSize((w, h))
_, faces = detector.detect(frame)
res = {
"detected": False,
"box": None,
"pose": {"yaw": 0, "pitch": 0, "roll": 0},
"depth_score": 0,
"is_spoof": False,
"verified": False,
"status": "Пошук обличчя..."
}
if faces is not None and len(faces) > 0:
f = faces[0]
box = [int(f[0]), int(f[1]), int(f[2]), int(f[3])]
lm5 = [
(float(f[4]), float(f[5])), (float(f[6]), float(f[7])),
(float(f[8]), float(f[9])), (float(f[10]), float(f[11])),
(float(f[12]), float(f[13]))
]
res["detected"] = True
res["box"] = box
yaw, pitch, roll = get_3d_head_pose(lm5, w, h)
res["pose"] = {"yaw": round(yaw, 1), "pitch": round(pitch, 1), "roll": round(roll, 1)}
spoof, depth, reason = check_anti_spoof(frame, box, lm5)
res["depth_score"] = round(depth, 1)
res["is_spoof"] = spoof
aligned = recognizer.alignCrop(frame, f)
feat = recognizer.feature(aligned)
if spoof:
res["status"] = f"⚠️ ЗАХИСТ: {reason}"
else:
if abs(yaw) < 10 and abs(pitch) < 14:
res["status"] = "Поверніть голову вправо ➡️"
elif yaw >= 14:
res["status"] = "Звірка біометрії..."
if REFERENCE_FEATURE is not None:
dist = round(float(1.0 - recognizer.match(REFERENCE_FEATURE, feat, cv2.FaceRecognizerSF_FR_COSINE)), 3)
if dist < 0.63:
res["verified"] = True
res["status"] = "Доступ відкрито!"
else:
res["status"] = "Відхилено: інша особа"
else:
res["status"] = "3D-живість OK (додайте еталон)"
else:
res["status"] = "1/2 Подивіться прямо"
return JSONResponse(res)
except Exception as e:
return JSONResponse({"detected": False, "status": str(e)})
@app.api_route("/api/set_reference", methods=["GET", "POST"])
async def set_ref(request: Request):
global REFERENCE_FEATURE
if request.method == "GET":
return JSONResponse({"status": "ready"})
try:
payload = await request.json()
data_url = payload.get("image", "")
if "," in data_url:
data_url = data_url.split(",")[1]
img_bytes = base64.b64decode(data_url)
img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR)
if img is None:
return JSONResponse({"success": False, "error": "Не вдалося розпізнати зображення"})
h, w = img.shape[:2]
max_dim = 640
if max(h, w) > max_dim:
scale = max_dim / max(h, w)
img = cv2.resize(img, (int(w * scale), int(h * scale)))
h, w = img.shape[:2]
detector.setInputSize((w, h))
_, faces = detector.detect(img)
if faces is None or len(faces) == 0:
return JSONResponse({"success": False, "error": "Обличчя на фото не виявлено"})
aligned = recognizer.alignCrop(img, faces[0])
REFERENCE_FEATURE = recognizer.feature(aligned)
return JSONResponse({"success": True})
except Exception as e:
return JSONResponse({"success": False, "error": str(e)})
head_code = '<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.min.js"></script>'
if __name__ == "__main__":
demo.launch(head=head_code)