Spaces:
Runtime error
Runtime error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914# app.py# Biometric Authentication Literature Survey + Interactive Demonstration# Designed for Hugging Face Spaces free CPU tier.## Educational scope:# - Fingerprint, iris, and optional face feature extraction# - Handcrafted features: minutiae-like, LBP, Gabor, SIFT-like# - Deep-feature simulation: CNN-like and deep embedding# - Enrollment vs verification matching# - Template protection demonstrations# - Attack/liveness simulation# - Survey comparison tables for all 4 assigned students## Important:# This is NOT a production biometric authentication system.# It stores no biometric database and performs session-only comparisons.
import base64import hashlibimport ioimport mathimport warningsfrom typing import Dict, List, Tuple
import gradio as grimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageOps
warnings.filterwarnings("ignore")
try: from cryptography.fernet import Fernet
HAS_CRYPTO = Trueexcept Exception: HAS_CRYPTO = False
try: import cv2
HAS_CV2 = Trueexcept Exception: HAS_CV2 = False
APP_TITLE = "Biometric Authentication Literature Survey & Interactive Demo"DEFAULT_SIZE = 128
# ---------------------------------------------------------------------# Utility helpers# ---------------------------------------------------------------------
def _safe_image(img): if img is None: return None if isinstance(img, Image.Image): return img.convert("RGB") return Image.fromarray(np.array(img)).convert("RGB")
def _array_to_pil(arr: np.ndarray) -> Image.Image: arr = np.asarray(arr) arr = np.nan_to_num(arr) if arr.max() <= 1.0: arr = arr * 255.0 arr = np.clip(arr, 0, 255).astype(np.uint8) return Image.fromarray(arr)
def _normalize01(arr: np.ndarray) -> np.ndarray: arr = np.asarray(arr, dtype=np.float32) mn, mx = float(arr.min()), float(arr.max()) if mx - mn < 1e-8: return np.zeros_like(arr, dtype=np.float32) return (arr - mn) / (mx - mn)
def _seed_from_key(key: str) -> int: key = key or "student-demo-key" digest = hashlib.sha256(key.encode("utf-8")).digest() return int.from_bytes(digest[:8], "little") % (2**32 - 1)
def _resize_gray(img: Image.Image, size: int = DEFAULT_SIZE) -> np.ndarray: img = _safe_image(img) gray = ImageOps.grayscale(img) gray = ImageOps.autocontrast(gray) gray = gray.resize((size, size)) return np.asarray(gray, dtype=np.float32) / 255.0
def _pad_or_trim(vec: np.ndarray, length: int) -> np.ndarray: vec = np.asarray(vec, dtype=np.float32).flatten() if len(vec) == length: return vec if len(vec) > length: return vec[:length] out = np.zeros(length, dtype=np.float32) out[:len(vec)] = vec return out
def _unit_vector(vec: np.ndarray) -> np.ndarray: vec = np.asarray(vec, dtype=np.float32).flatten() vec = np.nan_to_num(vec) norm = np.linalg.norm(vec) if norm < 1e-8: return vec return vec / norm
def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float: a = np.asarray(a, dtype=np.float32).flatten() b = np.asarray(b, dtype=np.float32).flatten() n = min(len(a), len(b)) if n == 0: return 0.0 a = _unit_vector(a[:n]) b = _unit_vector(b[:n]) score = float(np.dot(a, b)) return max(0.0, min(1.0, (score + 1.0) / 2.0))
def _hamming_similarity(a: np.ndarray, b: np.ndarray) -> float: a = np.asarray(a).flatten() > 0.5 b = np.asarray(b).flatten() > 0.5 n = min(len(a), len(b)) if n == 0: return 0.0 return float(1.0 - np.mean(a[:n] != b[:n]))
def _vector_preview(vec: np.ndarray, limit: int = 16) -> str: vec = np.asarray(vec).flatten() shown = vec[:limit] return np.array2string(shown, precision=4, separator=", ")
def _make_feature_dataframe(vec: np.ndarray, limit: int = 32) -> pd.DataFrame: vec = np.asarray(vec).flatten() rows = [] for i, v in enumerate(vec[:limit]): rows.append({"index": i, "value": float(v)}) return pd.DataFrame(rows)
def _fig_feature_bar(vec: np.ndarray, title: str = "Feature vector preview"): vec = np.asarray(vec).flatten() fig = plt.figure(figsize=(7, 3)) n = min(64, len(vec)) plt.bar(np.arange(n), vec[:n]) plt.title(title) plt.xlabel("Feature index") plt.ylabel("Value") plt.tight_layout() return fig
# ---------------------------------------------------------------------# Preprocessing# ---------------------------------------------------------------------
def preprocess_modality(img: Image.Image, modality: str) -> Tuple[np.ndarray, Image.Image, Dict]: img = _safe_image(img) if img is None: raise ValueError("Please upload an image.")
if modality == "Iris": # Educational iris approximation: # central crop + circular mask. This is not true iris segmentation. w, h = img.size side = min(w, h) left = (w - side) // 2 top = (h - side) // 2 crop = img.crop((left, top, left + side, top + side)) gray = ImageOps.grayscale(crop) gray = ImageOps.autocontrast(gray) gray = gray.resize((DEFAULT_SIZE, DEFAULT_SIZE)) arr = np.asarray(gray, dtype=np.float32) / 255.0
yy, xx = np.ogrid[:DEFAULT_SIZE, :DEFAULT_SIZE] center = (DEFAULT_SIZE - 1) / 2 radius_outer = DEFAULT_SIZE * 0.46 radius_inner = DEFAULT_SIZE * 0.12 dist = np.sqrt((xx - center) ** 2 + (yy - center) ** 2) mask = (dist <= radius_outer) & (dist >= radius_inner) masked = arr.copy() masked[~mask] = 0.0
meta = { "modality": modality, "preprocessing": "central crop, grayscale, autocontrast, circular iris-style mask", "note": "Educational approximation; not a clinical iris segmenter." } return masked, _array_to_pil(masked), meta
if modality == "Fingerprint": gray = _resize_gray(img) # Increase ridge visibility. pil = _array_to_pil(gray) pil = ImageEnhance.Contrast(pil).enhance(1.8) pil = pil.filter(ImageFilter.SHARPEN) arr = np.asarray(pil, dtype=np.float32) / 255.0 meta = { "modality": modality, "preprocessing": "grayscale, resize, autocontrast, contrast enhancement, sharpening" } return arr, pil, meta
# Face / generic biometric image. gray = _resize_gray(img) pil = _array_to_pil(gray) pil = ImageEnhance.Contrast(pil).enhance(1.25) arr = np.asarray(pil, dtype=np.float32) / 255.0 meta = { "modality": modality, "preprocessing": "grayscale, resize, autocontrast, light contrast enhancement" } return arr, pil, meta
# ---------------------------------------------------------------------# Feature extraction methods# ---------------------------------------------------------------------
def _conv2d_same(img: np.ndarray, kernel: np.ndarray) -> np.ndarray: img = np.asarray(img, dtype=np.float32) kernel = np.asarray(kernel, dtype=np.float32) kh, kw = kernel.shape ph, pw = kh // 2, kw // 2 padded = np.pad(img, ((ph, ph), (pw, pw)), mode="reflect")
try: windows = np.lib.stride_tricks.sliding_window_view(padded, (kh, kw)) return np.einsum("ijkl,kl->ij", windows, kernel) except Exception: out = np.zeros_like(img) for y in range(img.shape[0]): for x in range(img.shape[1]): out[y, x] = np.sum(padded[y:y + kh, x:x + kw] * kernel) return out
def gabor_kernel(size=21, sigma=4.0, theta=0.0, frequency=0.12, gamma=0.5): radius = size // 2 y, x = np.mgrid[-radius:radius + 1, -radius:radius + 1] x_theta = x * np.cos(theta) + y * np.sin(theta) y_theta = -x * np.sin(theta) + y * np.cos(theta)
gb = np.exp(-(x_theta ** 2 + gamma ** 2 * y_theta ** 2) / (2 * sigma ** 2)) gb *= np.cos(2 * np.pi * frequency * x_theta) gb -= gb.mean() return gb.astype(np.float32)
def extract_gabor(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]: orientations = [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4] responses = [] features = []
for theta in orientations: kernel = gabor_kernel(theta=theta) response = _conv2d_same(arr, kernel) responses.append(response) abs_resp = np.abs(response) features.extend([ float(abs_resp.mean()), float(abs_resp.std()), float(abs_resp.max()), float(np.percentile(abs_resp, 75)), ])
stacked = np.stack([np.abs(r) for r in responses], axis=0) visual = _normalize01(stacked.max(axis=0))
meta = { "method": "Gabor filters", "feature_type": "Handcrafted texture/ridge-frequency features", "feature_length": len(features), "advantages": "Good for ridge and iris texture enhancement; interpretable.", "limitations": "Sensitive to segmentation quality, rotation, scale, and chosen filter parameters." } return np.array(features, dtype=np.float32), _array_to_pil(visual), meta
def extract_lbp(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]: center = arr neighbors = [ np.roll(np.roll(arr, -1, axis=0), -1, axis=1), np.roll(arr, -1, axis=0), np.roll(np.roll(arr, -1, axis=0), 1, axis=1), np.roll(arr, 1, axis=1), np.roll(np.roll(arr, 1, axis=0), 1, axis=1), np.roll(arr, 1, axis=0), np.roll(np.roll(arr, 1, axis=0), -1, axis=1), np.roll(arr, -1, axis=1), ]
code = np.zeros_like(arr, dtype=np.uint8) for i, n in enumerate(neighbors): code += ((n >= center).astype(np.uint8) << i)
hist, _ = np.histogram(code.flatten(), bins=256, range=(0, 256), density=True) visual = code.astype(np.float32) / 255.0
meta = { "method": "Local Binary Pattern", "feature_type": "Handcrafted local texture histogram", "feature_length": len(hist), "advantages": "Fast, simple, strong texture descriptor.", "limitations": "Can be sensitive to noise and does not model global structure well." } return hist.astype(np.float32), _array_to_pil(visual), meta
def extract_sift_like(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]: if HAS_CV2: img8 = np.clip(arr * 255, 0, 255).astype(np.uint8) sift = None try: sift = cv2.SIFT_create() except Exception: sift = None
if sift is not None: keypoints, descriptors = sift.detectAndCompute(img8, None) if descriptors is None or len(descriptors) == 0: desc = np.zeros(128, dtype=np.float32) else: desc = descriptors.mean(axis=0).astype(np.float32) desc = _unit_vector(desc)
color = cv2.cvtColor(img8, cv2.COLOR_GRAY2RGB) drawn = cv2.drawKeypoints(color, keypoints[:80], None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) visual = Image.fromarray(drawn)
meta = { "method": "SIFT", "feature_type": "Keypoint descriptor", "feature_length": len(desc), "advantages": "Robust to scale/rotation changes when keypoints are stable.", "limitations": "Can fail on low-texture or poor-quality biometric images." } return desc.astype(np.float32), visual, meta
# Fallback SIFT-like descriptor: # 4x4 grid, 8-bin orientation histogram = 128 dims. gy, gx = np.gradient(arr) mag = np.sqrt(gx ** 2 + gy ** 2) ori = (np.arctan2(gy, gx) + np.pi) / (2 * np.pi)
cells = 4 bins = 8 h, w = arr.shape ch, cw = h // cells, w // cells feats = []
for cy in range(cells): for cx in range(cells): y0, y1 = cy * ch, (cy + 1) * ch x0, x1 = cx * cw, (cx + 1) * cw cell_ori = ori[y0:y1, x0:x1].flatten() cell_mag = mag[y0:y1, x0:x1].flatten() hist, _ = np.histogram(cell_ori, bins=bins, range=(0, 1), weights=cell_mag) feats.extend(hist.tolist())
feats = _unit_vector(np.array(feats, dtype=np.float32))
visual = Image.fromarray(np.uint8(np.stack([arr, arr, arr], axis=-1) * 255)) draw = ImageDraw.Draw(visual) # Draw top gradient points as pseudo-keypoints. flat_idx = np.argsort(mag.flatten())[-60:] for idx in flat_idx: y, x = divmod(int(idx), w) draw.ellipse((x - 1, y - 1, x + 1, y + 1), fill=(255, 0, 0))
meta = { "method": "SIFT-like fallback", "feature_type": "Educational gradient keypoint/orientation descriptor", "feature_length": len(feats), "advantages": "Demonstrates SIFT/SURF idea without heavy dependencies.", "limitations": "Not a full SIFT/SURF implementation unless OpenCV SIFT is available." } return feats.astype(np.float32), visual, meta
def extract_minutiae_like(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]: # Educational fingerprint minutiae approximation: # threshold ridges + estimate endpoints/bifurcations through neighbor counts. smooth = _conv2d_same(arr, np.ones((3, 3), dtype=np.float32) / 9.0) binary = smooth < np.percentile(smooth, 45)
# Remove border. binary[:2, :] = False binary[-2:, :] = False binary[:, :2] = False binary[:, -2:] = False
neighbor_count = np.zeros_like(binary, dtype=np.int32) for dy in [-1, 0, 1]: for dx in [-1, 0, 1]: if dy == 0 and dx == 0: continue neighbor_count += np.roll(np.roll(binary, dy, axis=0), dx, axis=1).astype(np.int32)
endpoints = binary & (neighbor_count == 1) bifurcations = binary & (neighbor_count >= 3)
# Spatial histograms. grid = 4 h, w = arr.shape feats = [ float(endpoints.sum()) / 1000.0, float(bifurcations.sum()) / 1000.0, float(binary.mean()), float(neighbor_count[binary].mean()) if binary.any() else 0.0, ]
for mask in [endpoints, bifurcations]: for gy in range(grid): for gx in range(grid): y0, y1 = gy * h // grid, (gy + 1) * h // grid x0, x1 = gx * w // grid, (gx + 1) * w // grid feats.append(float(mask[y0:y1, x0:x1].sum()) / 100.0)
visual = Image.fromarray(np.uint8(np.stack([arr, arr, arr], axis=-1) * 255)) draw = ImageDraw.Draw(visual) ey, ex = np.where(endpoints) by, bx = np.where(bifurcations)
for y, x in list(zip(ey, ex))[:120]: draw.ellipse((x - 2, y - 2, x + 2, y + 2), outline=(0, 255, 0), width=1) for y, x in list(zip(by, bx))[:120]: draw.rectangle((x - 2, y - 2, x + 2, y + 2), outline=(255, 0, 0), width=1)
meta = { "method": "Minutiae-like extraction", "feature_type": "Educational ridge endpoint/bifurcation approximation", "feature_length": len(feats), "advantages": "Explains classic fingerprint minutiae concepts visually.", "limitations": "Not a true skeletonization-based forensic minutiae extractor." } return np.array(feats, dtype=np.float32), visual, meta
def extract_cnn_like(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]: # Lightweight CNN-style embedding simulation: # edge responses + pooled statistics across multiple grid sizes. sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=np.float32) sobel_y = sobel_x.T gx = _conv2d_same(arr, sobel_x) gy = _conv2d_same(arr, sobel_y) edge = _normalize01(np.sqrt(gx ** 2 + gy ** 2))
feats = [] for grid in [2, 4, 8]: h, w = arr.shape for y in range(grid): for x in range(grid): y0, y1 = y * h // grid, (y + 1) * h // grid x0, x1 = x * w // grid, (x + 1) * w // grid patch = arr[y0:y1, x0:x1] epatch = edge[y0:y1, x0:x1] feats.extend([ float(patch.mean()), float(patch.std()), float(epatch.mean()), float(epatch.std()), ])
# Add global moments. feats.extend([ float(arr.mean()), float(arr.std()), float(edge.mean()), float(edge.std()), float(np.percentile(arr, 25)), float(np.percentile(arr, 50)), float(np.percentile(arr, 75)), ])
feats = _unit_vector(np.array(feats, dtype=np.float32))
meta = { "method": "CNN-like embedding", "feature_type": "Lightweight multiscale pooled edge/texture embedding", "feature_length": len(feats), "advantages": "Demonstrates deep-model-style hierarchical feature pooling on CPU.", "limitations": "Not trained; does not replace a real CNN biometric model." } return feats, _array_to_pil(edge), meta
def extract_deep_embedding(arr: np.ndarray, modality: str) -> Tuple[np.ndarray, Image.Image, Dict]: # Deterministic random projection of multiple handcrafted features. # This mimics a compact deep embedding for demonstration. gabor_vec, gabor_vis, _ = extract_gabor(arr) lbp_vec, _, _ = extract_lbp(arr) sift_vec, _, _ = extract_sift_like(arr) cnn_vec, cnn_vis, _ = extract_cnn_like(arr)
base = np.concatenate([ _pad_or_trim(gabor_vec, 32), _pad_or_trim(lbp_vec, 128), _pad_or_trim(sift_vec, 128), _pad_or_trim(cnn_vec, 128), ]) base = _unit_vector(base)
rng = np.random.default_rng(_seed_from_key("deep-" + modality)) projection = rng.normal(0, 1, size=(len(base), 128)).astype(np.float32) emb = base @ projection emb = _unit_vector(emb)
visual = cnn_vis
meta = { "method": "Deep embedding simulation", "feature_type": "Deterministic projected multimethod embedding", "feature_length": len(emb), "advantages": "Shows the idea of compact embeddings used by FaceNet/ArcFace/CNN systems.", "limitations": "Educational simulation; not trained on biometric identity labels." } return emb.astype(np.float32), visual, meta
def extract_features(img: Image.Image, modality: str, method: str): arr, preprocessed, pre_meta = preprocess_modality(img, modality)
if method == "Minutiae-like": vec, vis, meta = extract_minutiae_like(arr) elif method == "LBP": vec, vis, meta = extract_lbp(arr) elif method == "Gabor": vec, vis, meta = extract_gabor(arr) elif method == "SIFT/SURF-like": vec, vis, meta = extract_sift_like(arr) elif method == "CNN-like": vec, vis, meta = extract_cnn_like(arr) elif method == "Deep embedding": vec, vis, meta = extract_deep_embedding(arr, modality) else: vec, vis, meta = extract_gabor(arr)
full_meta = {**pre_meta, **meta} return vec.astype(np.float32), preprocessed, vis, full_meta
# ---------------------------------------------------------------------# Template protection# ---------------------------------------------------------------------
def _fernet_key(secret: str) -> bytes: digest = hashlib.sha256((secret or "demo-secret").encode()).digest() return base64.urlsafe_b64encode(digest)
def encrypted_preview(vec: np.ndarray, secret: str) -> str: raw = np.asarray(vec[:64], dtype=np.float32).tobytes() if HAS_CRYPTO: f = Fernet(_fernet_key(secret)) token = f.encrypt(raw) return token[:180].decode("utf-8") + "..." fallback = hashlib.sha256(raw + secret.encode()).hexdigest() return "cryptography package missing; SHA-256 preview only: " + fallback
def random_projection(vec: np.ndarray, secret: str, out_dim: int = 128) -> np.ndarray: vec = _unit_vector(vec) rng = np.random.default_rng(_seed_from_key(secret)) projection = rng.normal(0, 1, size=(len(vec), out_dim)).astype(np.float32) out = vec @ projection return _unit_vector(out)
def biohash(vec: np.ndarray, secret: str, out_dim: int = 128) -> np.ndarray: projected = random_projection(vec, secret, out_dim) return (projected > np.median(projected)).astype(np.float32)
def chaotic_permutation(vec: np.ndarray, secret: str) -> np.ndarray: vec = np.asarray(vec, dtype=np.float32).flatten() seed = _seed_from_key(secret) x = ((seed % 100000) + 1) / 100001.0 r = 3.99 chaotic = [] for _ in range(len(vec)): x = r * x * (1 - x) chaotic.append(x) perm = np.argsort(chaotic) return _unit_vector(vec[perm])
def fuzzy_bits(vec: np.ndarray, secret: str, out_dim: int = 128) -> np.ndarray: projected = random_projection(vec, secret, out_dim) return (projected > 0).astype(np.float32)
def protect_for_matching(vec: np.ndarray, method: str, secret: str) -> Tuple[np.ndarray, str, str]: vec = np.asarray(vec, dtype=np.float32).flatten()
if method == "Plain template": return _unit_vector(vec), "cosine", "Raw normalized template used for comparison."
if method == "Encrypted storage": # Real encrypted-template systems usually decrypt before matching # unless using special cryptographic protocols. return _unit_vector(vec), "cosine", ( "Template is encrypted at rest. For this demo, matching uses the decrypted vector. " "Encryption protects storage but does not provide cancelability by itself." )
if method == "Cancelable biometric": return random_projection(vec, secret), "cosine", ( "Feature vector is transformed using a secret-key random projection. " "Changing the key revokes and reissues a new template." )
if method == "BioHashing": return biohash(vec, secret), "hamming", ( "Projected features are binarized into a BioHash. " "Comparison uses Hamming similarity." )
if method == "Chaotic mapping": return chaotic_permutation(vec, secret), "cosine", ( "A logistic-map sequence permutes the feature vector. " "Changing the key changes the permutation." )
if method == "Fuzzy extractor simulation": return fuzzy_bits(vec, secret), "hamming", ( "Features are converted into stable binary helper-data-style bits. " "This demonstrates the concept; it is not a full fuzzy extractor implementation." )
if method == "Toy homomorphic encryption": return _unit_vector(vec), "cosine", ( "Conceptual demo only. Real homomorphic matching would compute on encrypted values " "with much higher cost." )
return _unit_vector(vec), "cosine", "Default normalized template."
def template_preview(vec: np.ndarray, method: str, secret: str) -> Tuple[str, pd.DataFrame]: protected, metric, explanation = protect_for_matching(vec, method, secret)
if method == "Encrypted storage": preview = encrypted_preview(vec, secret) df = pd.DataFrame({ "field": ["storage form", "matching metric", "revocation", "note"], "value": [ "ciphertext preview", metric, "possible by changing encryption key, but biometric itself is unchanged", explanation ] }) return preview, df
if method == "Toy homomorphic encryption": quantized = np.round(np.asarray(vec[:16]) * 1000).astype(int) preview = "Encrypted-integer toy preview: " + np.array2string(quantized, separator=", ") else: preview = _vector_preview(protected, 24)
df = pd.DataFrame({ "field": ["protected length", "matching metric", "revocability", "explanation"], "value": [ len(protected), metric, "Yes" if method in ["Cancelable biometric", "BioHashing", "Chaotic mapping", "Fuzzy extractor simulation"] else "Limited", explanation ] }) return preview, df
# ---------------------------------------------------------------------# Liveness and attacks# ---------------------------------------------------------------------
def liveness_metrics(img: Image.Image) -> Dict: arr, _, _ = preprocess_modality(img, "Face")
lap_kernel = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]], dtype=np.float32) lap = _conv2d_same(arr, lap_kernel) blur_var = float(lap.var())
# Frequency energy. fft = np.fft.fftshift(np.fft.fft2(arr)) mag = np.abs(fft) h, w = mag.shape cy, cx = h // 2, w // 2 yy, xx = np.ogrid[:h, :w] dist = np.sqrt((yy - cy) ** 2 + (xx - cx) ** 2) high_mask = dist > (min(h, w) * 0.18) high_freq_ratio = float(mag[high_mask].sum() / (mag.sum() + 1e-8))
lbp_vec, _, _ = extract_lbp(arr) entropy = float(-np.sum(lbp_vec * np.log2(lbp_vec + 1e-8))) entropy_score = min(1.0, entropy / 8.0)
contrast = float(arr.std()) brightness = float(arr.mean())
blur_score = min(1.0, blur_var * 120.0) freq_score = min(1.0, high_freq_ratio * 4.0) contrast_score = min(1.0, contrast * 4.0)
overall = 0.30 * blur_score + 0.30 * freq_score + 0.25 * entropy_score + 0.15 * contrast_score
suspicious_reasons = [] if blur_score < 0.18: suspicious_reasons.append("low sharpness") if freq_score < 0.18: suspicious_reasons.append("low high-frequency detail") if contrast < 0.05: suspicious_reasons.append("very low contrast") if brightness < 0.08 or brightness > 0.92: suspicious_reasons.append("extreme brightness")
return { "blur_score": round(blur_score, 4), "frequency_score": round(freq_score, 4), "texture_entropy_score": round(entropy_score, 4), "contrast_score": round(contrast_score, 4), "brightness": round(brightness, 4), "overall_liveness_score": round(float(overall), 4), "suspicious_reasons": ", ".join(suspicious_reasons) if suspicious_reasons else "none" }
def simulate_attack(img: Image.Image, attack: str, intensity: float) -> Image.Image: img = _safe_image(img) if img is None: raise ValueError("Please upload an image.") intensity = float(intensity)
if attack == "None": return img
if attack == "Blur / out-of-focus": return img.filter(ImageFilter.GaussianBlur(radius=0.5 + intensity * 5))
if attack == "Gaussian noise": arr = np.asarray(img).astype(np.float32) rng = np.random.default_rng(123) noise = rng.normal(0, 8 + intensity * 45, size=arr.shape) out = np.clip(arr + noise, 0, 255).astype(np.uint8) return Image.fromarray(out)
if attack == "Low-contrast print": out = ImageOps.grayscale(img).convert("RGB") out = ImageEnhance.Contrast(out).enhance(max(0.2, 1.0 - intensity * 0.8)) out = ImageEnhance.Brightness(out).enhance(0.85 + intensity * 0.15) return out
if attack == "Replay-screen scanlines": arr = np.asarray(img).astype(np.float32) step = max(2, int(8 - intensity * 5)) arr[::step, :, :] *= 0.55 arr[:, ::max(3, step + 1), :] *= 0.85 return Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8))
if attack == "Deepfake-like smoothing": out = img.filter(ImageFilter.MedianFilter(size=3)) out = out.filter(ImageFilter.GaussianBlur(radius=0.5 + intensity * 2.5)) out = ImageEnhance.Sharpness(out).enhance(0.5) return out
if attack == "Adversarial-style tiny noise": arr = np.asarray(img).astype(np.float32) rng = np.random.default_rng(999) pattern = rng.choice([-1, 1], size=arr.shape) * (2 + intensity * 12) out = np.clip(arr + pattern, 0, 255).astype(np.uint8) return Image.fromarray(out)
return img
# ---------------------------------------------------------------------# Gradio callback functions# ---------------------------------------------------------------------
def run_feature_lab(img, modality, method): if img is None: return None, None, None, pd.DataFrame(), {}, "Upload an image first."
try: vec, pre, vis, meta = extract_features(img, modality, method) fig = _fig_feature_bar(vec, f"{method} feature preview") df = _make_feature_dataframe(vec) explanation = f"""### Feature extraction result
**Modality:** {modality} **Method:** {meta.get("method")} **Feature type:** {meta.get("feature_type")} **Feature length:** {meta.get("feature_length")}
**Advantages:** {meta.get("advantages")}
**Limitations:** {meta.get("limitations")}
**Note:** The app is educational. For a final report, use exact metrics from the papers you review.""" return pre, vis, fig, df, meta, explanation except Exception as e: return None, None, None, pd.DataFrame(), {}, f"Error: {e}"
def run_verification(enroll_img, verify_img, modality, method, protection_method, secret_key, threshold): if enroll_img is None or verify_img is None: return "Upload both enrollment and verification images.", pd.DataFrame(), None, None
try: e_vec, e_pre, e_vis, e_meta = extract_features(enroll_img, modality, method) v_vec, v_pre, v_vis, v_meta = extract_features(verify_img, modality, method)
e_prot, metric, prot_explanation = protect_for_matching(e_vec, protection_method, secret_key) v_prot, _, _ = protect_for_matching(v_vec, protection_method, secret_key)
if metric == "hamming": similarity = _hamming_similarity(e_prot, v_prot) else: similarity = _cosine_similarity(e_prot, v_prot)
live = liveness_metrics(verify_img) liveness_score = live["overall_liveness_score"] is_live = liveness_score >= 0.35 accepted = similarity >= threshold and is_live
decision = "ACCEPTED" if accepted else "REJECTED" color = "green" if accepted else "red"
reason = [] if similarity < threshold: reason.append("similarity below threshold") if not is_live: reason.append("liveness score suspicious") if not reason: reason.append("similarity and liveness passed")
result_md = f"""## <span style='color:{color}'>{decision}</span>
| Check | Value ||---|---:|| Similarity score | **{similarity:.4f}** || Threshold | **{threshold:.4f}** || Matching metric | **{metric}** || Liveness score | **{liveness_score:.4f}** || Liveness verdict | **{"Live / acceptable" if is_live else "Suspicious"}** || Reason | **{", ".join(reason)}** |
**Template protection explanation:** {prot_explanation}
**Important:** This demo fails closed. If the image cannot be processed, it does not return fake success."""
metrics_df = pd.DataFrame([ {"metric": "similarity", "value": round(similarity, 4)}, {"metric": "threshold", "value": round(float(threshold), 4)}, {"metric": "liveness_score", "value": liveness_score}, {"metric": "blur_score", "value": live["blur_score"]}, {"metric": "frequency_score", "value": live["frequency_score"]}, {"metric": "texture_entropy_score", "value": live["texture_entropy_score"]}, {"metric": "contrast_score", "value": live["contrast_score"]}, ])
fig = plt.figure(figsize=(6, 3)) labels = ["similarity", "threshold", "liveness"] values = [similarity, threshold, liveness_score] plt.bar(labels, values) plt.ylim(0, 1) plt.title("Verification decision signals") plt.tight_layout()
return result_md, metrics_df, e_vis, v_vis
except Exception as e: return f"## REJECTED\n\nProcessing error: {e}", pd.DataFrame(), None, None
def run_template_lab(img, modality, feature_method, protection_method, secret_key): if img is None: return "Upload an image first.", pd.DataFrame(), pd.DataFrame(), None
try: vec, pre, vis, meta = extract_features(img, modality, feature_method) preview, info_df = template_preview(vec, protection_method, secret_key)
raw_df = pd.DataFrame({ "index": list(range(min(24, len(vec)))), "raw_feature_value": [float(x) for x in vec[:24]] })
md = f"""## Template protection preview
**Feature method:** {feature_method} **Protection method:** {protection_method} **Raw feature length:** {len(vec)}
### Protected / stored preview
```text{preview}app.pyAdded+914