Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161712202132345675 unmodified lines13141535161718192021422223242547262728293053313233563435363738613940416465424344674546474849505152735354755556575859606181826263646566678788686970717273747595969798991001011021031041051067677781097980818283841158586878889909192939495969798991211221231241001011021031041051271061071081092 unmodified lines1121131141361151161381391171181191421201211441451461471221231241501251261521271281291301313 unmodified lines1351361371631381391401661671411421431441451461721731471481495 unmodified lines1551561571851861871881891901911921581591601611621631641651961661671981681691702012022031711721731741753 unmodified lines1791801812132142151821831841851864 unmodified lines19119219322619419519622919719819920020120223520320420510 unmodified lines2162172182522532542552562192202212222232242592252262272622632282292652662672682692702712722732742752762772782302312322332342352362812822832842372382392402412862422432442892452462472485 unmodified lines2542552563012572582593052603073082612623112632643133142652662673162682692703192712722732741 unmodified line2762772783272792802812822833333343352842852863383392872883422892903443452912922933472942953493502962972983542993003013583023603033043633643653663673053063073083093103113123133693703143713153163743753173183193783793203213813823223233243843253263273283293303903913923933313323333953963343353363373384023393403413423434074084094103443454124134143463473483493503514193523534213543553563573585 unmodified lines3643653664333673683691 unmodified line3713723734413743754434443763773784463793803814494504514523823833844544554564573853863873883893904604614624634643913923933943953964674684694704714724734743973984764774784794804814823994004014844854024864034044894054064914074084094944104114124974984995004134144154164175044185065075085094194204214224235115125134244254265155165175185194274284295224304315244324334345274354364375304384395324404414428 unmodified lines4514524535475485494544554564574584594605565574614624634644655614664674685645654694705675684714724734745715725734754764774785755764794804815794824834844854865844874885864894904915894924935915925935944944954964974984995975005015025035046025055066045076066075085096096106116126136146155105116176186196206215125136236246256266275145156296306316326335165176356366376386395185196416426436446456465205215225236495245256515266536546556566576586596606616626636646656666675275285295305316696706716725325335345355365375386776785395405416805425435445455465475486875495506896906915515525536945545555565575585597015605615625632 unmodified lines5665675687105695705717145725737175745757195765777215785797235805817255825835847287297307317325855865875885895907345915925935947387395955965975985996006016027466037487496046056066076087547557566096106116126136147626156166176186196207696216226236246257756266276286297807817826306316326336347876356366376386396407936416427967977987998008018028038048058068078088098108118126436446456466476486496506516526536546556566576586598198206606618228238248256626636646658276668296676688316696706718348358368376726736746758396768418428436776786796808458468478488498508518528538548558568578588598608618628638648658668678686816826836846856866876886896906916926936946956966976986997008707017027037047057067078768778788798808818828838848857088867097107111 unmodified line713714715716717718719720721722723724725726727728729730731732733734735736737738739896897740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878899900901902879880881904905882907908909883884885886887888889890911891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102191391410221023# 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, Tuplefrom typing import Dict, Tuple
import gradio as grimport matplotlib.pyplot as plt5 unmodified lines
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# General helpers# ---------------------------------------------------------------------
def _safe_image(img):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") return Image.fromarray(np.asarray(img)).convert("RGB")
def _array_to_pil(arr: np.ndarray) -> Image.Image: arr = np.asarray(arr)def array_to_pil(arr): arr = np.asarray(arr, dtype=np.float32) arr = np.nan_to_num(arr) if arr.max() <= 1.0: if arr.size == 0: arr = np.zeros((DEFAULT_SIZE, DEFAULT_SIZE), dtype=np.float32) if float(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:def normalize01(arr): arr = np.asarray(arr, dtype=np.float32) mn, mx = float(arr.min()), float(arr.max()) mn = float(arr.min()) mx = 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"def seed_from_key(key): key = str(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)def resize_gray(img, size=DEFAULT_SIZE): 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:def unit_vector(vec): vec = np.asarray(vec, dtype=np.float32).flatten() vec = np.nan_to_num(vec) norm = np.linalg.norm(vec) norm = float(np.linalg.norm(vec)) if norm < 1e-8: return vec return vec / norm
def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:def pad_or_trim(vec, length): vec = np.asarray(vec, dtype=np.float32).flatten() if len(vec) >= length: return vec[:length] out = np.zeros(length, dtype=np.float32) out[: len(vec)] = vec return out
def cosine_similarity(a, b): 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)) a = unit_vector(a[:n]) b = unit_vector(b[:n]) raw = float(np.dot(a, b)) return max(0.0, min(1.0, (raw + 1.0) / 2.0))
def _hamming_similarity(a: np.ndarray, b: np.ndarray) -> float:def hamming_similarity(a, b): a = np.asarray(a).flatten() > 0.5 b = np.asarray(b).flatten() > 0.5 n = min(len(a), len(b))2 unmodified lines return float(1.0 - np.mean(a[:n] != b[:n]))
def _vector_preview(vec: np.ndarray, limit: int = 16) -> str:def vector_preview(vec, limit=24): vec = np.asarray(vec).flatten() shown = vec[:limit] return np.array2string(shown, precision=4, separator=", ") return np.array2string(vec[:limit], precision=4, separator=", ")
def _make_feature_dataframe(vec: np.ndarray, limit: int = 32) -> pd.DataFrame:def feature_df(vec, limit=40): vec = np.asarray(vec).flatten() rows = [] for i, v in enumerate(vec[:limit]): rows.append({"index": i, "value": float(v)}) return pd.DataFrame(rows) return pd.DataFrame({"index": list(range(min(limit, len(vec)))), "value": [float(v) for v in vec[:limit]]})
def _fig_feature_bar(vec: np.ndarray, title: str = "Feature vector preview"):def feature_plot(vec, title): vec = np.asarray(vec).flatten() fig = plt.figure(figsize=(7, 3)) n = min(64, len(vec)) fig = plt.figure(figsize=(7, 3)) plt.bar(np.arange(n), vec[:n]) plt.title(title) plt.xlabel("Feature index")3 unmodified lines
# ---------------------------------------------------------------------# Preprocessing# Image preprocessing# ---------------------------------------------------------------------
def preprocess_modality(img: Image.Image, modality: str) -> Tuple[np.ndarray, Image.Image, Dict]: img = _safe_image(img)def preprocess_modality(img, modality): 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) // 25 unmodified lines 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
c = (DEFAULT_SIZE - 1) / 2 dist = np.sqrt((xx - c) ** 2 + (yy - c) ** 2) mask = (dist <= DEFAULT_SIZE * 0.46) & (dist >= DEFAULT_SIZE * 0.12) arr2 = arr.copy() arr2[~mask] = 0.0 meta = { "modality": modality, "preprocessing": "central crop, grayscale, autocontrast, circular iris-style mask", "note": "Educational approximation; not a clinical iris segmenter." "note": "Educational approximation; not a true iris segmentation algorithm." } return masked, _array_to_pil(masked), meta return arr2, array_to_pil(arr2), meta
if modality == "Fingerprint": gray = _resize_gray(img) # Increase ridge visibility. pil = _array_to_pil(gray) arr = resize_gray(img) pil = array_to_pil(arr) pil = ImageEnhance.Contrast(pil).enhance(1.8) pil = pil.filter(ImageFilter.SHARPEN) arr = np.asarray(pil, dtype=np.float32) / 255.03 unmodified lines } return arr, pil, meta
# Face / generic biometric image. gray = _resize_gray(img) pil = _array_to_pil(gray) arr = resize_gray(img) pil = array_to_pil(arr) pil = ImageEnhance.Contrast(pil).enhance(1.25) arr = np.asarray(pil, dtype=np.float32) / 255.0 meta = {4 unmodified lines
# ---------------------------------------------------------------------# Feature extraction methods# Feature extraction# ---------------------------------------------------------------------
def _conv2d_same(img: np.ndarray, kernel: np.ndarray) -> np.ndarray:def conv2d_same(img, kernel): 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)10 unmodified lines 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) kernel = np.exp(-(x_theta ** 2 + gamma ** 2 * y_theta ** 2) / (2 * sigma ** 2)) kernel *= np.cos(2 * np.pi * frequency * x_theta) kernel -= kernel.mean() return kernel.astype(np.float32)
def extract_gabor(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]:def extract_gabor(arr): orientations = [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4] responses = [] features = []
feats = [] 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))
resp = conv2d_same(arr, gabor_kernel(theta=theta)) responses.append(resp) a = np.abs(resp) feats.extend([float(a.mean()), float(a.std()), float(a.max()), float(np.percentile(a, 75))]) visual = normalize01(np.stack([np.abs(r) for r in responses], axis=0).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." "feature_type": "handcrafted texture and ridge-frequency descriptor", "feature_length": len(feats), "advantages": "Interpretable and useful for fingerprint ridges and iris texture.", "limitations": "Sensitive to segmentation, rotation, scale, and manually chosen parameters." } return np.array(features, dtype=np.float32), _array_to_pil(visual), meta return np.asarray(feats, dtype=np.float32), array_to_pil(visual), meta
def extract_lbp(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]:def extract_lbp(arr): center = arr neighbors = [ np.roll(np.roll(arr, -1, axis=0), -1, axis=1),5 unmodified lines 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_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." "advantages": "Fast, simple, and useful for texture-based biometric patterns.", "limitations": "Sensitive to noise and weaker for global structure." } return hist.astype(np.float32), _array_to_pil(visual), meta return hist.astype(np.float32), array_to_pil(code.astype(np.float32) / 255.0), meta
def extract_sift_like(arr: np.ndarray) -> Tuple[np.ndarray, Image.Image, Dict]:def extract_sift_like(arr): if HAS_CV2: img8 = np.clip(arr * 255, 0, 255).astype(np.uint8) sift = None1 unmodified line 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)
desc = unit_vector(descriptors.mean(axis=0).astype(np.float32)) 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_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." "advantages": "Robust to scale and rotation when stable keypoints exist.", "limitations": "Can be sparse on low-texture or poor-quality biometric images." } return desc.astype(np.float32), visual, meta return desc.astype(np.float32), Image.fromarray(drawn), 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) y0, y1 = cy * h // cells, (cy + 1) * h // cells x0, x1 = cx * w // cells, (cx + 1) * w // cells hist, _ = np.histogram( ori[y0:y1, x0:x1].flatten(), bins=bins, range=(0, 1), weights=mag[y0:y1, x0:x1].flatten() ) feats.extend(hist.tolist())
feats = _unit_vector(np.array(feats, dtype=np.float32)) feats = unit_vector(np.asarray(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:] flat_idx = np.argsort(mag.flatten())[-70:] 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))
draw.ellipse((x - 1, y - 1, x + 1, y + 1), outline=(255, 0, 0)) meta = { "method": "SIFT-like fallback", "feature_type": "Educational gradient keypoint/orientation descriptor", "method": "SIFT/SURF-like fallback", "feature_type": "educational gradient orientation descriptor", "feature_length": len(feats), "advantages": "Demonstrates SIFT/SURF idea without heavy dependencies.", "advantages": "Demonstrates local keypoint/gradient-descriptor ideas without heavy models.", "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)def extract_minutiae_like(arr): 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) ncount = 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) ncount += np.roll(np.roll(binary, dy, axis=0), dx, axis=1).astype(np.int32)
# Spatial histograms. grid = 4 h, w = arr.shape endpoints = binary & (ncount == 1) bifurcations = binary & (ncount >= 3) 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, float(ncount[binary].mean()) if binary.any() else 0.0, ]
grid = 4 h, w = arr.shape for mask in [endpoints, bifurcations]: for gy in range(grid): for gx in range(grid):5 unmodified lines 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]:1 unmodified line
meta = { "method": "Minutiae-like extraction", "feature_type": "Educational ridge endpoint/bifurcation approximation", "feature_type": "educational endpoint and bifurcation approximation", "feature_length": len(feats), "advantages": "Explains classic fingerprint minutiae concepts visually.", "limitations": "Not a true skeletonization-based forensic minutiae extractor." "advantages": "Visually explains classic fingerprint minutiae concepts.", "limitations": "Not a true forensic minutiae extractor; segmentation and thinning are simplified." } return np.array(feats, dtype=np.float32), visual, meta return np.asarray(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)def extract_cnn_like(arr): sobel_x = np.asarray([[-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))
gx = conv2d_same(arr, sobel_x) gy = conv2d_same(arr, sobel_y) edge = normalize01(np.sqrt(gx ** 2 + gy ** 2)) feats = [] h, w = arr.shape 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 for yy in range(grid): for xx in range(grid): y0, y1 = yy * h // grid, (yy + 1) * h // grid x0, x1 = xx * w // grid, (xx + 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(patch.mean()), float(patch.std()), float(epatch.mean()), float(epatch.std())]) 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)), 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)) feats = unit_vector(np.asarray(feats, dtype=np.float32))
meta = { "method": "CNN-like embedding", "feature_type": "Lightweight multiscale pooled edge/texture embedding", "feature_type": "lightweight multiscale pooled edge and texture embedding", "feature_length": len(feats), "advantages": "Demonstrates deep-model-style hierarchical feature pooling on CPU.", "advantages": "Demonstrates hierarchical feature pooling on CPU.", "limitations": "Not trained; does not replace a real CNN biometric model." } return feats, _array_to_pil(edge), meta return feats.astype(np.float32), 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)def extract_deep_embedding(arr, modality): gabor_vec, _, _ = 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), 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)) base = unit_vector(base) rng = np.random.default_rng(seed_from_key("deep-" + str(modality))) projection = rng.normal(0, 1, size=(len(base), 128)).astype(np.float32) emb = base @ projection emb = _unit_vector(emb)
visual = cnn_vis
emb = unit_vector(base @ projection) meta = { "method": "Deep embedding simulation", "feature_type": "Deterministic projected multimethod embedding", "feature_type": "deterministic projected multimethod embedding", "feature_length": len(emb), "advantages": "Shows the idea of compact embeddings used by FaceNet/ArcFace/CNN systems.", "advantages": "Shows the idea of compact embeddings used by FaceNet, ArcFace, and CNN systems.", "limitations": "Educational simulation; not trained on biometric identity labels." } return emb.astype(np.float32), visual, meta return emb.astype(np.float32), cnn_vis, meta
def extract_features(img: Image.Image, modality: str, method: str):def extract_features(img, modality, method): arr, preprocessed, pre_meta = preprocess_modality(img, modality)
if method == "Minutiae-like": vec, vis, meta = extract_minutiae_like(arr) elif method == "LBP":8 unmodified lines 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 return vec.astype(np.float32), preprocessed, vis, {**pre_meta, **meta}
# ---------------------------------------------------------------------# Template protection# ---------------------------------------------------------------------
def _fernet_key(secret: str) -> bytes: digest = hashlib.sha256((secret or "demo-secret").encode()).digest()def fernet_key(secret): digest = hashlib.sha256(str(secret or "demo-secret").encode("utf-8")).digest() return base64.urlsafe_b64encode(digest)
def encrypted_preview(vec: np.ndarray, secret: str) -> str:def encrypted_storage_preview(vec, secret): raw = np.asarray(vec[:64], dtype=np.float32).tobytes() if HAS_CRYPTO: f = Fernet(_fernet_key(secret)) token = f.encrypt(raw) token = Fernet(fernet_key(secret)).encrypt(raw) return token[:180].decode("utf-8") + "..." fallback = hashlib.sha256(raw + secret.encode()).hexdigest() return "cryptography package missing; SHA-256 preview only: " + fallback digest = hashlib.sha256(raw + str(secret).encode("utf-8")).hexdigest() return "cryptography package missing; SHA-256 preview only: " + digest
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))def random_projection(vec, secret, out_dim=128): 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) return unit_vector(vec @ projection)
def biohash(vec: np.ndarray, secret: str, out_dim: int = 128) -> np.ndarray:def biohash(vec, secret, out_dim=128): 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:def chaotic_mapping(vec, secret): vec = np.asarray(vec, dtype=np.float32).flatten() seed = _seed_from_key(secret) seed = seed_from_key(secret) x = ((seed % 100000) + 1) / 100001.0 r = 3.99 chaotic = [] seq = [] for _ in range(len(vec)): x = r * x * (1 - x) chaotic.append(x) perm = np.argsort(chaotic) return _unit_vector(vec[perm]) x = r * x * (1.0 - x) seq.append(x) perm = np.argsort(seq) return unit_vector(vec[perm])
def fuzzy_bits(vec: np.ndarray, secret: str, out_dim: int = 128) -> np.ndarray:def fuzzy_bits(vec, secret, out_dim=128): 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]:def protect_for_matching(vec, method, secret): vec = np.asarray(vec, dtype=np.float32).flatten()
if method == "Plain template": return _unit_vector(vec), "cosine", "Raw normalized template used for comparison."
return unit_vector(vec), "cosine", "Raw normalized template. Fast but unsafe if stolen." 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." )
return unit_vector(vec), "cosine", "Encrypted at rest. Matching uses decrypted vector in this demo." 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." )
return random_projection(vec, secret), "cosine", "Secret-key random projection. Change key to revoke/reissue template." if method == "BioHashing": return biohash(vec, secret), "hamming", ( "Projected features are binarized into a BioHash. " "Comparison uses Hamming similarity." )
return biohash(vec, secret), "hamming", "Random projection plus binarization. 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." )
return chaotic_mapping(vec, secret), "cosine", "Logistic-map sequence permutes the template using a key." 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." )
return fuzzy_bits(vec, secret), "hamming", "Simulated stable binary helper-data-style output." 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." return unit_vector(vec), "cosine", "Conceptual placeholder. Real homomorphic matching is much more expensive." return unit_vector(vec), "cosine", "Default normalized template."
def template_preview(vec: np.ndarray, method: str, secret: str) -> Tuple[str, pd.DataFrame]:def template_preview(vec, method, secret): 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=", ") preview = encrypted_storage_preview(vec, secret) elif method == "Toy homomorphic encryption": q = np.round(np.asarray(vec[:16]) * 1000).astype(int) preview = "Toy encrypted-integer preview: " + np.array2string(q, separator=", ") else: preview = _vector_preview(protected, 24)
df = pd.DataFrame({ "field": ["protected length", "matching metric", "revocability", "explanation"], preview = vector_preview(protected, 24) info = pd.DataFrame({ "property": ["protected length", "matching metric", "revocation capability", "explanation"], "value": [ len(protected), metric, "Yes" if method in ["Cancelable biometric", "BioHashing", "Chaotic mapping", "Fuzzy extractor simulation"] else "Limited", explanation ] explanation, ], }) return preview, df return preview, info
# ---------------------------------------------------------------------# Liveness and attacks# ---------------------------------------------------------------------
def liveness_metrics(img: Image.Image) -> Dict:def liveness_metrics(img): 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) lap = conv2d_same(arr, np.asarray([[0, 1, 0], [1, -4, 1], [0, 1, 0]], dtype=np.float32)) 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_mask = dist > min(h, w) * 0.18 high_freq_ratio = float(mag[high_mask].sum() / (mag.sum() + 1e-8))
lbp_vec, _, _ = extract_lbp(arr)2 unmodified lines
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 = [] reasons = [] if blur_score < 0.18: suspicious_reasons.append("low sharpness") reasons.append("low sharpness") if freq_score < 0.18: suspicious_reasons.append("low high-frequency detail") reasons.append("low high-frequency detail") if contrast < 0.05: suspicious_reasons.append("very low contrast") reasons.append("very low contrast") if brightness < 0.08 or brightness > 0.92: suspicious_reasons.append("extreme brightness") 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), "blur_score": round(float(blur_score), 4), "frequency_score": round(float(freq_score), 4), "texture_entropy_score": round(float(entropy_score), 4), "contrast_score": round(float(contrast_score), 4), "brightness": round(float(brightness), 4), "overall_liveness_score": round(float(overall), 4), "suspicious_reasons": ", ".join(suspicious_reasons) if suspicious_reasons else "none" "suspicious_reasons": ", ".join(reasons) if reasons else "none", }
def simulate_attack(img: Image.Image, attack: str, intensity: float) -> Image.Image: img = _safe_image(img)def simulate_attack(img, attack, intensity): 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))
return img.filter(ImageFilter.GaussianBlur(radius=0.5 + intensity * 5.0)) 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)
return Image.fromarray(np.clip(arr + noise, 0, 255).astype(np.uint8)) 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 Image.fromarray(np.clip(arr + pattern, 0, 255).astype(np.uint8)) return img
# ---------------------------------------------------------------------# Gradio callback functions# Gradio callbacks# ---------------------------------------------------------------------
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 explanation = ( "### Feature extraction result\n\n" f"**Modality:** {modality}\n\n" f"**Method:** {meta.get('method')}\n\n" f"**Feature type:** {meta.get('feature_type')}\n\n" f"**Feature length:** {meta.get('feature_length')}\n\n" f"**Advantages:** {meta.get('advantages')}\n\n" f"**Limitations:** {meta.get('limitations')}\n\n" "This is an educational demonstration. The final report should cite actual paper metrics." ) return pre, vis, feature_plot(vec, f"{method} feature preview"), feature_df(vec), 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
return "## REJECTED\n\nUpload 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) e_vec, _, e_vis, _ = extract_features(enroll_img, modality, method) v_vec, _, v_vis, _ = extract_features(verify_img, modality, method) e_prot, metric, 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) similarity = hamming_similarity(e_prot, v_prot) else: similarity = _cosine_similarity(e_prot, v_prot) 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
live_score = float(live["overall_liveness_score"]) is_live = live_score >= 0.35 accepted = similarity >= float(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") reasons = [] if similarity < float(threshold): reasons.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)}, reasons.append("liveness score suspicious") if not reasons: reasons.append("similarity and liveness passed")
result = ( f"## {decision}\n\n" "| Check | Value |\n" "|---|---:|\n" f"| Similarity score | **{similarity:.4f}** |\n" f"| Threshold | **{float(threshold):.4f}** |\n" f"| Matching metric | **{metric}** |\n" f"| Liveness score | **{live_score:.4f}** |\n" f"| Liveness verdict | **{'Live / acceptable' if is_live else 'Suspicious'}** |\n" f"| Reason | **{', '.join(reasons)}** |\n\n" f"**Template protection note:** {explanation}\n\n" "The demo fails closed: no image or processing failure means no authentication success." ) metrics = pd.DataFrame([ {"metric": "similarity", "value": round(float(similarity), 4)}, {"metric": "threshold", "value": round(float(threshold), 4)}, {"metric": "liveness_score", "value": liveness_score}, {"metric": "liveness_score", "value": live_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"]}, {"metric": "suspicious_reasons", "value": live["suspicious_reasons"]}, ])
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 return result, metrics, e_vis, v_vis
except Exception as e: return f"## REJECTED\n\nProcessing error: {e}", pd.DataFrame(), None, None
1 unmodified linedef 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, _, vis, _ = extract_features(img, modality, feature_method) preview, info = template_preview(vec, protection_method, secret_key) raw = pd.DataFrame({"index": list(range(min(32, len(vec)))), "raw_feature_value": [float(x) for x in vec[:32]]}) md = ( "## Template protection preview\n\n" f"**Feature method:** {feature_method}\n\n" f"**Protection method:** {protection_method}\n\n" f"**Raw feature length:** {len(vec)}\n\n" "### Protected / stored preview\n\n" f"`{preview}`\n\n" "### Key concept\n\n" "Encryption protects storage. Cancelable biometrics and BioHashing make templates revocable by changing the secret key. " "Fuzzy extractors aim to generate stable keys from noisy biometric samples. Homomorphic encryption is conceptually powerful but computationally expensive." ) return md, raw, info, vis except Exception as e: return f"Error: {e}", pd.DataFrame(), pd.DataFrame(), None
def run_attack_lab(img, attack, intensity): if img is None: return None, pd.DataFrame(), "Upload an image first." try: vec, pre, vis, meta = extract_features(img, modality, feature_method) preview, info_df = template_preview(vec, protection_method, secret_key) attacked = simulate_attack(img, attack, intensity) metrics = liveness_metrics(attacked) verdict = "Live / acceptable" if metrics["overall_liveness_score"] >= 0.35 else "Suspicious / possible spoof" df = pd.DataFrame([{"metric": k, "value": v} for k, v in metrics.items()]) md = ( f"## {verdict}\n\n" f"**Attack simulation:** {attack}\n\n" f"**Intensity:** {float(intensity):.2f}\n\n" "This demonstrates basic liveness/PAD ideas using blur, texture, contrast, and frequency cues. " "It is not a production anti-spoofing detector." ) return attacked, df, md except Exception as e: return None, pd.DataFrame(), f"Error: {e}"
# ---------------------------------------------------------------------# Tables and static content# ---------------------------------------------------------------------
def model_comparison_table(): rows = [ ["Shallow CNN", "Small convolution + pooling stack", "0.1M-2M", "Low", "Medium", "Fast on CPU", "Good", "May underfit complex variations"], ["ResNet", "Residual CNN blocks", "11M+ for ResNet-18", "Medium/high", "High with data", "Medium", "Moderate", "Heavier than MobileNet"], ["MobileNet", "Depthwise separable CNN", "3M-5M", "Low", "Good", "Fast", "Excellent", "May lose accuracy on difficult data"], ["Vision Transformer", "Patch tokens + self-attention", "High", "High", "High with large data", "Slow on CPU", "Weak/moderate", "Data hungry and heavy"], ["Autoencoder", "Encoder learns compressed representation", "Variable", "Medium", "Task-dependent", "Medium", "Moderate", "Embedding may not be discriminative"], ["FaceNet / ArcFace-style", "Metric-learning embedding", "Medium/high", "Medium/high", "Very strong for face", "Medium", "Depends on backbone", "Needs threshold and liveness checks"], ] cols = ["Model", "Architecture idea", "Approx. params", "Approx. FLOPs", "Accuracy tendency", "Inference time", "Edge suitability", "Limitation"] return pd.DataFrame(rows, columns=cols)
def model_notes(selected): notes = { "Shallow CNN": "Useful for a student demo. Low complexity but limited robustness.", "ResNet": "Good baseline for fingerprint or face feature learning. Residual connections help deeper CNN training.", "MobileNet": "Best example for edge deployment because it is designed for efficient inference.", "Vision Transformer": "Useful for modern attention-based model discussion, but heavy for free CPU deployment.", "Autoencoder": "Useful for representation learning or anomaly detection, but not automatically strong for identity verification.", "FaceNet / ArcFace-style": "Best conceptual model for verification: extract embedding, compare with cosine similarity, tune threshold." } return f"### {selected}\n\n{notes.get(selected, 'Select a model.')}"
def survey_table(topic): if topic == "Student 1 - Feature Extraction": rows = [ ["Hong, Wan & Jain, 1998", "Fingerprint", "Gabor/ridge enhancement", "Fingerprint images", "Enhancement/matching improvement", "Improves ridge clarity", "Parameter-sensitive"], ["Jain, Prabhakar & Hong, 1999", "Fingerprint", "Filterbank features", "Fingerprint databases", "Recognition/matching rate", "Strong handcrafted baseline", "Needs alignment"], ["Maio & Maltoni, 1997", "Fingerprint", "Minutiae extraction", "Fingerprint images", "Minutiae accuracy", "Classic approach", "False minutiae in poor images"], ["Ratha et al., 1996", "Fingerprint", "Ridge flow + minutiae", "Fingerprint images", "Verification metrics", "End-to-end pipeline", "Segmentation-sensitive"], ["Ojala et al., 2002", "Texture", "LBP", "Texture datasets", "Classification rate", "Fast descriptor", "Weak global structure"], ["Ahonen et al., 2006", "Face", "LBP face descriptor", "Face datasets", "Recognition rate", "Simple/interpretable", "Pose and illumination issues"], ["Lowe, 2004", "General vision", "SIFT", "Image datasets", "Keypoint matching", "Scale/rotation robust", "Sparse on some biometrics"], ["Bay et al., 2008", "General vision", "SURF", "Image datasets", "Speed/matching", "Faster than SIFT", "Less common in modern biometrics"], ["Daugman, 1993", "Iris", "Gabor iris code", "Iris images", "False match rates", "Foundational iris method", "Needs accurate segmentation"], ["Wildes, 1997", "Iris", "Iris texture matching", "Iris images", "Recognition performance", "Strong iris pipeline", "Controlled imaging needed"], ["Masek & Kovesi, 2003", "Iris", "Segmentation + encoding", "CASIA-style iris data", "Recognition metrics", "Useful baseline", "Older pipeline"], ["Schroff et al., 2015", "Face", "FaceNet embedding", "Large face data", "Verification accuracy", "Strong deep embedding", "Needs large training data"], ["Deng et al., 2019", "Face", "ArcFace embedding", "Face datasets", "Verification accuracy", "Discriminative loss", "Heavy training"], ["CNN iris studies", "Iris", "CNN features", "Iris datasets", "Accuracy/EER", "Learns features", "Dataset bias risk"], ["DeepPrint-style work", "Fingerprint", "Deep embedding", "Fingerprint datasets", "Verification accuracy", "Robust representation", "Needs careful evaluation"], ] cols = ["Paper", "Modality", "Method", "Dataset", "Accuracy / metric", "Advantages", "Limitations"] return pd.DataFrame(rows, columns=cols)
if topic == "Student 2 - Template Protection": rows = [ ["Ratha et al., 2001", "Cancelable biometrics", "Non-invertible transform", "Medium", "Medium", "Low/medium", "Yes"], ["Teoh et al., 2004", "BioHashing", "Random projection + binarization", "Medium/high", "Medium", "Low", "Yes"], ["Juels & Wattenberg, 1999", "Fuzzy commitment", "Bind key with noisy biometric", "High", "Medium", "Medium", "Possible"], ["Juels & Sudan, 2002", "Fuzzy vault", "Hide secret among chaff points", "High", "Medium", "Medium/high", "Possible"], ["Dodis et al., 2004", "Fuzzy extractor", "Stable key from noisy input", "High", "Medium", "Medium", "Yes"], ["Clancy et al., 2003", "Fingerprint vault", "Minutiae cryptosystem", "High", "Medium", "Medium/high", "Possible"], ["Uludag et al., 2004", "Biometric cryptosystem", "Key binding/generation", "High", "Medium", "Medium", "Depends"], ["Nandakumar et al., 2007", "Fingerprint fuzzy vault", "Vault for minutiae", "High", "Medium", "Medium/high", "Yes"], ["Jain, Nandakumar & Nagar, 2008", "Survey", "Template security comparison", "N/A", "N/A", "N/A", "N/A"], ["Nagar et al., 2010", "Multibiometric cryptosystem", "Fusion + protection", "High", "High", "High", "Possible"], ["Rathgeb & Uhl, 2011", "Survey", "Protection taxonomy", "N/A", "N/A", "N/A", "N/A"], ["Gomez-Barrero et al., 2017", "Evaluation", "Unlinkability/reversibility", "High", "Medium", "Medium", "Yes"], ["Chaotic map approaches", "Chaotic mapping", "Permutation/substitution", "Medium", "Medium", "Low/medium", "Yes"], ["ECC-based approaches", "Error correction", "Correct biometric noise", "High", "Medium", "Medium", "Possible"], ["Homomorphic matching", "Homomorphic encryption", "Compute on encrypted template", "Very high", "High", "High", "Yes"], ] cols = ["Paper", "Technique", "Core idea", "Security", "Complexity", "Computational cost", "Template revocation"] return pd.DataFrame(rows, columns=cols)
if topic == "Student 3 - Deep Learning": rows = [ ["DeepFace, 2014", "Deep CNN", "Face", "High", "High", "High", "Medium/slow"], ["DeepID, 2014", "CNN embedding", "Face", "Medium/high", "High", "High", "Medium"], ["VGGFace, 2015", "VGG-style CNN", "Face", "High", "High", "High", "Slow"], ["FaceNet, 2015", "Triplet-loss embedding", "Face", "High", "Very high", "Very high", "Medium"], ["SphereFace, 2017", "Angular-margin loss", "Face", "High", "Very high", "High", "Medium"], ["CosFace, 2018", "Cosine-margin loss", "Face", "High", "Very high", "High", "Medium"], ["ArcFace, 2019", "Additive angular margin", "Face", "High", "Very high", "High", "Medium"], ["MobileFaceNets, 2018", "Mobile CNN", "Face", "Low/medium", "High", "Low", "Fast"], ["FingerNet-style work", "CNN", "Fingerprint", "Medium", "Good", "Medium", "Medium"], ["DeepPrint-style work", "Deep embedding", "Fingerprint", "Medium/high", "High", "Medium/high", "Medium"], ["Iris CNN studies", "CNN", "Iris", "Medium", "Good/high", "Medium", "Medium"], ["Autoencoder biometric work", "Autoencoder", "Multiple", "Variable", "Task-dependent", "Medium", "Medium"], ["Vision Transformer, 2020", "ViT", "Adapted biometrics", "High", "High with data", "High", "Slow on CPU"], ["Swin Transformer", "Hierarchical ViT", "Face/iris", "High", "High", "High", "Medium/slow"], ["MobileNet biometric work", "Efficient CNN", "Face/fingerprint", "Low", "Good", "Low", "Fast"], ] cols = ["Paper/model", "Architecture", "Modality", "Parameters", "Accuracy tendency", "FLOPs", "Inference time"] return pd.DataFrame(rows, columns=cols)
rows = [ ["Printed photo attack", "Presentation attack", "Face/fingerprint", "False acceptance", "Texture/liveness/challenge-response"], ["Replay-screen attack", "Presentation attack", "Face", "Bypass camera login", "Screen artifact detection/challenge-response"], ["Silicone fingerprint", "Presentation attack", "Fingerprint", "Fake finger accepted", "Perspiration/pulse/texture PAD"], ["Deepfake face", "Synthetic attack", "Face", "Video impersonation", "Deepfake detection + active challenge"], ["Adversarial perturbation", "Model attack", "Any deep model", "Model misclassification", "Adversarial training"], ["Template inversion", "Template attack", "Stored embeddings", "Recover biometric information", "Cancelable templates/encryption"], ["Hill-climbing attack", "Matcher attack", "Score-based systems", "Score optimization", "Limit score leakage/rate limiting"], ["Replay of stored template", "Database attack", "Template storage", "Identity compromise", "Template protection/key binding"], ["Texture PAD studies", "Anti-spoofing", "Face", "Photo attack detection", "LBP/texture features"], ["Replay-Attack dataset studies", "Dataset/PAD", "Face", "Replay/photo detection", "Standardized PAD evaluation"], ["CASIA-FASD studies", "Dataset/PAD", "Face", "Video/photo attack detection", "Motion/texture cues"], ["LivDet studies", "Fingerprint PAD", "Fingerprint", "Fake fingerprint detection", "Benchmark anti-spoofing"], ["Depth-based PAD", "Anti-spoofing", "Face", "Flat photo rejection", "Depth camera / 3D cues"], ["rPPG liveness", "Anti-spoofing", "Face", "Detect pulse signal", "Needs video and lighting quality"], ["Multimodal PAD", "Defense", "Multiple", "Improved robustness", "Higher cost and complexity"], ] cols = ["Paper / attack", "Category", "Modality", "Risk", "Defense"] return pd.DataFrame(rows, columns=cols)
def survey_notes(topic): return ( f"### {topic}\n\n" "This is a starter comparison matrix for the literature survey. " "Before final submission, replace qualitative entries with exact metrics from your selected papers: " "dataset, accuracy/EER/FAR/FRR/APCER/BPCER, computational cost, advantages, and limitations." )
raw_df = pd.DataFrame({ "index": list(range(min(24, len(vec)))), "raw_feature_value": [float(x) for x in vec[:24]] })def update_survey(topic): return survey_notes(topic), survey_table(topic)
md = f"""## Template protection preview
**Feature method:** {feature_method} **Protection method:** {protection_method} **Raw feature length:** {len(vec)} # ---------------------------------------------------------------------# Gradio UI# ---------------------------------------------------------------------
CSS = """.gradio-container { max-width: 1200px !important; }"""
### Protected / stored previewwith gr.Blocks(title=APP_TITLE, css=CSS) as demo: gr.Markdown( "# " + APP_TITLE + "\n\n" "This is a professor-facing educational demo for a biometric authentication literature-survey project.\n\n" "It demonstrates feature extraction, template protection, deep-learning trade-offs, verification, attacks, liveness, and survey tables.\n\n" "**Security note:** This is not a production biometric login system. It stores no permanent biometric database." )
with gr.Tab("1. Project Overview"): gr.Markdown( "## Biometric authentication pipeline\n\n" "Biometric input -> preprocessing -> feature extraction -> template generation -> template protection -> matching -> liveness check -> accept/reject\n\n" "## Student-wise mapping\n\n" "| Student | Assignment area | App tabs |\n" "|---|---|---|\n" "| Student 1 | Feature extraction | Feature Extraction Lab |\n" "| Student 2 | Template protection | Template Protection Lab |\n" "| Student 3 | Deep learning | Deep Model Comparison |\n" "| Student 4 | Attacks and liveness | Attacks & Liveness |\n\n" "The app is designed to fail closed. It does not return fake authentication success if real processing fails." )
with gr.Tab("2. Feature Extraction Lab"): with gr.Row(): with gr.Column(): feat_img = gr.Image(label="Upload biometric image", type="pil") feat_modality = gr.Dropdown(["Fingerprint", "Iris", "Face"], value="Fingerprint", label="Biometric modality") feat_method = gr.Dropdown(["Minutiae-like", "LBP", "Gabor", "SIFT/SURF-like", "CNN-like", "Deep embedding"], value="Gabor", label="Feature extraction method") feat_btn = gr.Button("Extract features") with gr.Column(): feat_pre = gr.Image(label="Preprocessed image") feat_vis = gr.Image(label="Feature visualization") feat_plot_out = gr.Plot(label="Feature vector plot") feat_df_out = gr.Dataframe(label="Feature vector preview") feat_json_out = gr.JSON(label="Method metadata") feat_md_out = gr.Markdown() feat_btn.click(run_feature_lab, [feat_img, feat_modality, feat_method], [feat_pre, feat_vis, feat_plot_out, feat_df_out, feat_json_out, feat_md_out])
with gr.Tab("3. Enrollment & Verification Demo"): gr.Markdown( "Upload one image as the enrolled template and another image as the verification attempt. " "The app extracts features from both, applies the selected template protection transform, then compares similarity." ) with gr.Row(): enroll_img = gr.Image(label="Enrollment image", type="pil") verify_img = gr.Image(label="Verification image", type="pil") with gr.Row(): verify_modality = gr.Dropdown(["Fingerprint", "Iris", "Face"], value="Fingerprint", label="Modality") verify_method = gr.Dropdown(["Minutiae-like", "LBP", "Gabor", "SIFT/SURF-like", "CNN-like", "Deep embedding"], value="Gabor", label="Feature method") with gr.Row(): verify_protection = gr.Dropdown(["Plain template", "Encrypted storage", "Cancelable biometric", "BioHashing", "Chaotic mapping", "Fuzzy extractor simulation", "Toy homomorphic encryption"], value="Cancelable biometric", label="Template protection") secret_key = gr.Textbox(value="student-demo-key", label="Secret key / transform key") threshold = gr.Slider(0.0, 1.0, value=0.75, step=0.01, label="Decision threshold") verify_btn = gr.Button("Run verification") verify_result = gr.Markdown() verify_metrics = gr.Dataframe(label="Decision metrics") with gr.Row(): enroll_feat_vis = gr.Image(label="Enrollment feature visualization") verify_feat_vis = gr.Image(label="Verification feature visualization") verify_btn.click(run_verification, [enroll_img, verify_img, verify_modality, verify_method, verify_protection, secret_key, threshold], [verify_result, verify_metrics, enroll_feat_vis, verify_feat_vis])
with gr.Tab("4. Template Protection Lab"): with gr.Row(): with gr.Column(): tpl_img = gr.Image(label="Upload biometric image", type="pil") tpl_modality = gr.Dropdown(["Fingerprint", "Iris", "Face"], value="Fingerprint", label="Modality") tpl_feature = gr.Dropdown(["Minutiae-like", "LBP", "Gabor", "SIFT/SURF-like", "CNN-like", "Deep embedding"], value="Deep embedding", label="Feature method") tpl_protection = gr.Dropdown(["Plain template", "Encrypted storage", "Cancelable biometric", "BioHashing", "Chaotic mapping", "Fuzzy extractor simulation", "Toy homomorphic encryption"], value="BioHashing", label="Protection method") tpl_secret = gr.Textbox(value="student-demo-key", label="Secret key") tpl_btn = gr.Button("Generate protected template") with gr.Column(): tpl_vis = gr.Image(label="Feature visualization") tpl_md = gr.Markdown() tpl_raw_df = gr.Dataframe(label="Raw feature preview") tpl_info_df = gr.Dataframe(label="Protection properties") tpl_btn.click(run_template_lab, [tpl_img, tpl_modality, tpl_feature, tpl_protection, tpl_secret], [tpl_md, tpl_raw_df, tpl_info_df, tpl_vis])
with gr.Tab("5. Deep Model Comparison"): gr.Markdown( "This tab supports Student 3's literature review. It compares CNN, ResNet, MobileNet, Vision Transformer, Autoencoder, and FaceNet/ArcFace-style embeddings." ) gr.Dataframe(value=model_comparison_table(), label="Deep learning model comparison") selected_model = gr.Dropdown(["Shallow CNN", "ResNet", "MobileNet", "Vision Transformer", "Autoencoder", "FaceNet / ArcFace-style"], value="MobileNet", label="Select model") model_md = gr.Markdown(value=model_notes("MobileNet")) selected_model.change(model_notes, [selected_model], [model_md])
with gr.Tab("6. Attacks & Liveness"): gr.Markdown( "This tab supports Student 4's survey on attacks and anti-spoofing. " "It simulates common input attacks and estimates a basic liveness score." ) with gr.Row(): with gr.Column(): attack_img = gr.Image(label="Upload image", type="pil") attack_type = gr.Dropdown(["None", "Blur / out-of-focus", "Gaussian noise", "Low-contrast print", "Replay-screen scanlines", "Deepfake-like smoothing", "Adversarial-style tiny noise"], value="Low-contrast print", label="Attack simulation") attack_intensity = gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Attack intensity") attack_btn = gr.Button("Simulate attack + check liveness") with gr.Column(): attacked_img = gr.Image(label="Attacked / modified image") attack_md = gr.Markdown() attack_df = gr.Dataframe(label="Liveness metrics") attack_btn.click(run_attack_lab, [attack_img, attack_type, attack_intensity], [attacked_img, attack_df, attack_md]) gr.Markdown( "## Attack-defense taxonomy\n\n" "| Attack | Description | Typical defense |\n" "|---|---|---|\n" "| Presentation attack | Fake biometric shown to sensor | Liveness / PAD |\n" "| Replay attack | Photo or video on screen | Challenge-response |\n" "| Deepfake attack | Synthetic face/video | Deepfake detector + temporal cues |\n" "| Adversarial attack | Small perturbation fools model | Robust training |\n" "| Template attack | Stored template stolen | Cancelable biometrics + encryption |" )
with gr.Tab("7. Literature Survey Tables"): survey_topic = gr.Dropdown(["Student 1 - Feature Extraction", "Student 2 - Template Protection", "Student 3 - Deep Learning", "Student 4 - Attacks & Liveness"], value="Student 1 - Feature Extraction", label="Select student topic") survey_md = gr.Markdown(value=survey_notes("Student 1 - Feature Extraction")) survey_df = gr.Dataframe(value=survey_table("Student 1 - Feature Extraction"), label="Survey comparison table") survey_topic.change(update_survey, [survey_topic], [survey_md, survey_df])
with gr.Tab("8. Viva / Explanation Script"): gr.Markdown( "## 2-minute explanation for professor\n\n" "Our project is a literature-survey-based biometric authentication demo. The biometric pipeline starts with image acquisition. " "Preprocessing improves the image quality. Then features are extracted using handcrafted methods such as minutiae, LBP, Gabor filters, and SIFT/SURF-like descriptors, or deep-feature ideas such as CNN-style embeddings.\n\n" "The extracted vector is called a biometric template. A raw template is risky because if it is stolen, the user cannot change their fingerprint or iris. Therefore, the template protection tab demonstrates encryption, cancelable biometrics, BioHashing, chaotic mapping, fuzzy-extractor simulation, and homomorphic-encryption concepts.\n\n" "The verification tab compares an enrolled image with a verification image using similarity scores. The system accepts only when the score is above a threshold and the liveness score is acceptable.\n\n" "The attack tab demonstrates spoofing and presentation attack ideas. It shows how blur, print-like low contrast, replay-screen scanlines, deepfake-like smoothing, and adversarial noise can affect the biometric input.\n\n" "The deep-learning tab compares CNN, ResNet, MobileNet, Vision Transformers, Autoencoders, and FaceNet/ArcFace-style embeddings in terms of parameters, FLOPs, accuracy tendency, inference time, and edge deployment.\n\n" "This is an educational demonstration, not a production security system. Its purpose is to connect the literature survey with visible working examples." )
```text{preview}if __name__ == "__main__": demo.launch()app.py+545-436