Upload 4 files
Browse filesFiles changed (4)
1223456789101112131415161718192021222324345282930313233343536678910111213141516171819202122232425262738282930403132423334354647484950515253545556575836373839404161626364426643444546477273747576777879808182838485868788899091929394484950515253545597989910056102103104575810710810911059606162112113114636465666768691187071727374757677787980120121import numpy(__file__))import numpy as np
import numpy as npimport cv2from matplotlib import pyplot as pltimport torch
# In the below line,remove '.' while working on your local system.# However Make sure that '.' is present before exp_recognition_model while uploading to the server.from .exp_recognition_model import *
from PIL import Imageimport base64import ioimport os
############################################################################################################################## Caution: Don't change any of the filenames, function names and definitions ## Always use the current_path + file_name for refering any files, without it we cannot access files on the server ##############################################################################################################################
# Current_path stores absolute path of the file from where it runs.current_path = os.path.dirname(os.path.abspath(__file__))
# Cache model so we load only once_MODEL = None_DEVICE = None
#1) The below function is used to detect faces in the given image.#2) It returns only one image which has maximum area out of all the detected faces in the photo.#3) If no face is detected,then it returns zero(0).
def detected_face(image): eye_haar = current_path + '/haarcascade_eye.xml' face_haar = current_path + '/haarcascade_frontalface_default.xml'
def _to_bgr_np(img): # filepath if isinstance(img, str): return cv2.imread(img) # PIL if isinstance(img, Image.Image): rgb = np.array(img.convert("RGB")) return cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) # numpy if isinstance(img, np.ndarray): if img.ndim == 2: return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) if img.ndim == 3 and img.shape[2] == 4: img = img[:, :, :3] if img.ndim == 3 and img.shape[2] == 3: return cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # gradio numpy is RGB return img return None
def detected_face(image_bgr): face_haar = os.path.join(current_path, "haarcascade_frontalface_default.xml") face_cascade = cv2.CascadeClassifier(face_haar) eye_cascade = cv2.CascadeClassifier(eye_haar) # (not used, but kept as given) if face_cascade.empty(): return 0
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5)
if faces is None or len(faces) == 0: return 0
# Return the face crop with maximum area face_areas = [] face_imgs = []
for (x, y, w, h) in faces: face_cropped = gray[y:y+h, x:x+w] face_areas.append(w * h) face_imgs.append(face_cropped)
required = face_imgs[int(np.argmax(face_areas))] required = Image.fromarray(required) # PIL grayscale image return required
# choose max area face x, y, w, h = max(faces, key=lambda f: f[2] * f[3]) crop = gray[y:y+h, x:x+w] return Image.fromarray(crop)
def _load_cached_model(): """ Load and cache model on first call. Uses current_path + filename to be server-safe. """ global _MODEL, _DEVICE
if _MODEL is not None: return _MODEL, _DEVICE
_DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Try common model checkpoint names (place weights in same folder as this script) MODEL_CANDIDATES = [ "best_resnet18_expression.pt", "exp_recognition_net.pt", "exp_recognition_net.pth", "exp_recognition_net.t7" ]
model_path = None for fname in MODEL_CANDIDATES: p = os.path.join(current_path, fname) if os.path.exists(p): model_path = p break
if model_path is None: raise FileNotFoundError( f"No model checkpoint found in {current_path}. " f"Place one of these files there: {MODEL_CANDIDATES}" )
_MODEL = load_model(model_path, device=str(_DEVICE), num_classes=len(classes)) return _MODEL, _DEVICE # Use the exact filename you committed to the repo ckpt_path = os.path.join(current_path, "best_resnet18_expression.pt") if not os.path.exists(ckpt_path): raise FileNotFoundError(f"Missing checkpoint: {ckpt_path}")
_MODEL = load_model(ckpt_path, device=str(_DEVICE), num_classes=len(classes)) return _MODEL, _DEVICE
#1) Define an object to your network here in the function and load the weight from the trained network, set it in evaluation mode.#2) Perform necessary transformations to the input(detected face using the above function), this should return the Expression in string form ex: "Anger"#3) For loading your model use the current_path+'your model file name'##Caution: Don't change the definition or function name; for loading the model use the current_pathdef get_expression(img): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Load cached model model, device = _load_cached_model()
# Detect face crop (PIL grayscale). If no face, fallback to full grayscale frame. face = detected_face(img) if face == 0: face = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)) img_bgr = _to_bgr_np(img) if img_bgr is None: return "UNKNOWN"
# Apply transform from exp_recognition_model.py (ensures RGB + normalization) x = trnscm(face) # [3, H, W] x = x.unsqueeze(0).to(device) # [1, 3, H, W] face = detected_face(img_bgr) if face == 0: face = Image.fromarray(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY))
x = trnscm(face).unsqueeze(0).to(device) # [1,3,H,W] with torch.no_grad(): logits = model(x) pred_idx = int(torch.argmax(logits, dim=1).item()) pred = int(torch.argmax(logits, dim=1).item())
return classes.get(pred, "UNKNOWN").capitalize()
import cv2import torchfrom PIL import Imageimport os
from .exp_recognition_model import trnscm, load_model, classes
pred_label = classes.get(pred_idx, "UNKNOWN") return pred_label.capitalize()1123456789101112131489161718192021221011121314151617182519202829212232232435363725262728294142433045313233343536525354553757585960383940416542676869707172734344451 unmodified line47484981825051855287888990539254555696575859
import osimport torchimport torch.nn as nnimport torchvision.models as modelsfrom torchvision import transformsfrom PIL import Image
##################################################################################################################### Define your model and transform and all necessary helper functions here ## They will be imported to the exp_recognition.py file #####################################################################################################################
# IMPORTANT:# Ensure this mapping matches train_dataset.class_to_idx used during training.# Must match train_dataset.class_to_idxclasses = { 0: 'ANGER', 1: 'DISGUST', 2: 'FEAR', 3: 'HAPPINESS', 4: 'NEUTRAL', 5: 'SADNESS', 6: 'SURPRISE' 0: "ANGER", 1: "DISGUST", 2: "FEAR", 3: "HAPPINESS", 4: "NEUTRAL", 5: "SADNESS", 6: "SURPRISE",}
# ImageNet normalization (required for pretrained backbones)IMAGENET_MEAN = [0.485, 0.456, 0.406]IMAGENET_STD = [0.229, 0.224, 0.225]
# Must match training preprocessing sizeIMG_SIZE = 100
class facExpRec(nn.Module): """ Facial Expression Recognition model using ResNet18 backbone. Expects input: [B, 3, IMG_SIZE, IMG_SIZE] Output logits: [B, 7] ResNet18 backbone with custom fc for 7 expressions. Deployment-safe: weights=None, we load your checkpoint. """ def __init__(self, num_classes: int = 7): super().__init__()
# weights=None to avoid downloading during deployment runtime. # We load trained weights from checkpoint using load_model(). self.backbone = models.resnet18(weights=None)
in_features = self.backbone.fc.in_features self.backbone.fc = nn.Linear(in_features, num_classes)
def forward(self, x): return self.backbone(x)
# -----------------------------# Helper functions# -----------------------------def ensure_rgb(image: Image.Image) -> Image.Image: """ Ensure PIL image is RGB (3-channel). If grayscale, convert to RGB. """ if image.mode != "RGB": image = image.convert("RGB") return image
def get_transform(img_size: int = IMG_SIZE): """ Transform pipeline for inference. Must match training: - ensure RGB - resize - tensor - ImageNet normalize """ return transforms.Compose([ transforms.Lambda(ensure_rgb), transforms.Resize((img_size, img_size)),1 unmodified line transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), ])
# The transform object expected by exp_recognition.pytrnscm = get_transform(IMG_SIZE)
def load_model(checkpoint_path: str, device: str = "cpu", num_classes: int = 7) -> facExpRec: """ Loads model weights and returns eval-ready model. checkpoint_path should contain a state_dict (or a dict with 'state_dict'). """ model = facExpRec(num_classes=num_classes)
state = torch.load(checkpoint_path, map_location=device) if isinstance(state, dict) and "state_dict" in state: state = state["state_dict"]
model.load_state_dict(state, strict=True) model.to(device) model.eval()1234126789103451213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820962117891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
import numpy as npimport cv2from matplotlib import pyplot as plt%%writefile face_recognition_model.pyimport torch
# In the below line, remove '.' while working on your local system.# However Make sure that '.' is present before face_recognition_model while uploading to the server.from .face_recognition_model import *
import torch.nn as nnfrom torchvision import transformsfrom PIL import Imageimport base64import ioimport os
############################################################################################################################################ Caution: Don't change any of the filenames, function names and definitions ## Always use the current_path + file_name for refering any files, without it we cannot access files on the server ############################################################################################################################################
current_path = os.path.dirname(os.path.abspath(__file__))
# Cache models so we load only once per container_SIAMESE = None_CLASSIFIER = None_DEVICE = None
def _to_bgr_np(img): """ Convert various possible inputs -> OpenCV BGR numpy array. Gradio may pass PIL, numpy RGB, numpy RGBA, grayscale numpy, or filepath. """ if img is None: return None
# filepath string if isinstance(img, str): arr = cv2.imread(img) return arr # may be None if path invalid
# PIL Image if isinstance(img, Image.Image): rgb = np.array(img.convert("RGB")) return cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
# numpy array if isinstance(img, np.ndarray): arr = img
# If float image in [0,1], convert to uint8 if arr.dtype in (np.float32, np.float64): # Heuristic: if max <= 1.0 assume [0,1] if np.nanmax(arr) <= 1.0: arr = (arr * 255.0).clip(0, 255).astype(np.uint8) else: arr = arr.clip(0, 255).astype(np.uint8)
# Grayscale (H, W) -> convert to BGR if arr.ndim == 2: return cv2.cvtColor(arr, cv2.COLOR_GRAY2BGR)
# RGBA (H, W, 4) -> drop alpha then RGB->BGR if arr.ndim == 3 and arr.shape[2] == 4: arr = arr[:, :, :3]
# RGB (H, W, 3) -> BGR if arr.ndim == 3 and arr.shape[2] == 3: return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
return arr
return None
def _load_models(): """ Load Siamese + classifier once using current_path. """ global _SIAMESE, _CLASSIFIER, _DEVICE
if _SIAMESE is not None and _CLASSIFIER is not None: return _SIAMESE, _CLASSIFIER, _DEVICE
_DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# --- Load Siamese --- siamese_path = os.path.join(current_path, "siamese_model.t7") if not os.path.exists(siamese_path): raise FileNotFoundError(f"Missing siamese model: {siamese_path}")
siamese = Siamese().to(_DEVICE) ckpt = torch.load(siamese_path, map_location=_DEVICE)
# Your training saved: state = {'net_dict': net.state_dict()} if isinstance(ckpt, dict) and "net_dict" in ckpt: siamese.load_state_dict(ckpt["net_dict"], strict=True) else: siamese.load_state_dict(ckpt, strict=True)
siamese.eval()
# --- Load Classifier --- clf_path = os.path.join(current_path, "face_classifier_model.pth") if not os.path.exists(clf_path): raise FileNotFoundError(f"Missing classifier model: {clf_path}")
classifier = FaceClassifier(input_dim=5, num_classes=len(classes)).to(_DEVICE) clf_state = torch.load(clf_path, map_location=_DEVICE) classifier.load_state_dict(clf_state, strict=True) classifier.eval()
_SIAMESE, _CLASSIFIER = siamese, classifier return _SIAMESE, _CLASSIFIER, _DEVICE
# 1) Detect faces from image and return max-area face crop as PIL grayscale. Else return 0.def detected_face(image): eye_haar = os.path.join(current_path, "haarcascade_eye.xml") face_haar = os.path.join(current_path, "haarcascade_frontalface_default.xml")
face_cascade = cv2.CascadeClassifier(face_haar) eye_cascade = cv2.CascadeClassifier(eye_haar) # kept (not used)
# If cascade files are missing or failed to load, avoid crashing if face_cascade.empty(): return 0
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5)
if faces is None or len(faces) == 0: return 0
# Select max-area face max_area = -1 best = None for (x, y, w, h) in faces: area = w * h if area > max_area: max_area = area best = gray[y:y+h, x:x+w]
if best is None: return 0
return Image.fromarray(best) # PIL grayscale
# ---------------------------------------------------------------------------------------------------# get_similarity(img1, img2):# returns Euclidean distance between embeddings (smaller means more similar)# ---------------------------------------------------------------------------------------------------def get_similarity(img1, img2): siamese, classifier, device = _load_models()
# Convert inputs to OpenCV BGR arrays img1_bgr = _to_bgr_np(img1) img2_bgr = _to_bgr_np(img2)
if img1_bgr is None or img2_bgr is None: return 0.0
det_img1 = detected_face(img1_bgr) det_img2 = detected_face(img2_bgr)
# fallback if face not detected if det_img1 == 0: det_img1 = Image.fromarray(cv2.cvtColor(img1_bgr, cv2.COLOR_BGR2GRAY)) if det_img2 == 0: det_img2 = Image.fromarray(cv2.cvtColor(img2_bgr, cv2.COLOR_BGR2GRAY))
# Transform to tensor face1 = trnscm(det_img1).unsqueeze(0).to(device) # [1,1,100,100] face2 = trnscm(det_img2).unsqueeze(0).to(device)
with torch.no_grad(): emb1 = siamese.forward_once(face1) emb2 = siamese.forward_once(face2)
dist = torch.nn.functional.pairwise_distance(emb1, emb2).item()
return float(dist)
# ---------------------------------------------------------------------------------------------------# get_face_class(img1):# returns predicted class name string using embedding + classifier# ---------------------------------------------------------------------------------------------------def get_face_class(img1): siamese, classifier, device = _load_models()
img_bgr = _to_bgr_np(img1) if img_bgr is None: return "UNKNOWN"
det_img1 = detected_face(img_bgr) if det_img1 == 0: det_img1 = Image.fromarray(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY))
face = trnscm(det_img1).unsqueeze(0).to(device) # [1,1,100,100]
with torch.no_grad(): emb = siamese.forward_once(face) # [1,5] logits = classifier(emb) # [1,num_classes] pred_idx = int(torch.argmax(logits, dim=1).item())
if pred_idx < 0 or pred_idx >= len(classes): return "UNKNOWN"
return str(classes[pred_idx])def ensure_gray(image: Image.Image) -> Image.Image: if image.mode != "L": image = image.convert("L") return image
trnscm = transforms.Compose([ transforms.Lambda(ensure_gray), transforms.Resize((100, 100)), transforms.ToTensor(),])
class Siamese(nn.Module): def __init__(self): super().__init__() self.cnn1 = nn.Sequential( nn.ReflectionPad2d(1), nn.Conv2d(1, 4, kernel_size=3), nn.ReLU(inplace=True), nn.BatchNorm2d(4),
nn.ReflectionPad2d(1), nn.Conv2d(4, 8, kernel_size=3), nn.ReLU(inplace=True), nn.BatchNorm2d(8),
nn.ReflectionPad2d(1), nn.Conv2d(8, 8, kernel_size=3), nn.ReLU(inplace=True), nn.BatchNorm2d(8), ) self.fc1 = nn.Sequential( nn.Linear(8 * 100 * 100, 500), nn.ReLU(inplace=True), nn.Linear(500, 500), nn.ReLU(inplace=True), nn.Linear(500, 5), )
def forward_once(self, x): out = self.cnn1(x) out = out.view(out.size(0), -1) out = self.fc1(out) return out
def forward(self, x1, x2): return self.forward_once(x1), self.forward_once(x2)
class FaceClassifier(nn.Module): def __init__(self, input_dim=5, num_classes=7): super().__init__() self.fc = nn.Sequential( nn.Linear(input_dim, 128), nn.ReLU(inplace=True), nn.Dropout(0.5), nn.Linear(128, num_classes), )
def forward(self, x): return self.fc(x)
# Update to match your captured_face_images ImageFolder orderclasses = ["person1","person2","person3","person4","person5","person6","person7"]11233454789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919256789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
import numpy as npimport cv2import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision import transformsfrom PIL import Image
# -----------------------------# Transform (must match training)# You trained classifier using Grayscale(1), Resize(100,100), ToTensor()# -----------------------------def ensure_gray(image: Image.Image) -> Image.Image: if image.mode != "L": image = image.convert("L") return image
trnscm = transforms.Compose([ transforms.Lambda(ensure_gray), transforms.Resize((100, 100)), transforms.ToTensor(),])
# -----------------------------# Siamese Network (same as training)# -----------------------------class Siamese(nn.Module): def __init__(self): super(Siamese, self).__init__()
self.cnn1 = nn.Sequential( nn.ReflectionPad2d(1), nn.Conv2d(1, 4, kernel_size=3), nn.ReLU(inplace=True), nn.BatchNorm2d(4),
nn.ReflectionPad2d(1), nn.Conv2d(4, 8, kernel_size=3), nn.ReLU(inplace=True), nn.BatchNorm2d(8),
nn.ReflectionPad2d(1), nn.Conv2d(8, 8, kernel_size=3), nn.ReLU(inplace=True), nn.BatchNorm2d(8), )
self.fc1 = nn.Sequential( nn.Linear(8 * 100 * 100, 500), nn.ReLU(inplace=True),
nn.Linear(500, 500), nn.ReLU(inplace=True),
nn.Linear(500, 5) )
def forward_once(self, x): out = self.cnn1(x) out = out.view(out.size(0), -1) out = self.fc1(out) return out
def forward(self, input1, input2): out1 = self.forward_once(input1) out2 = self.forward_once(input2) return out1, out2
# -----------------------------# Classifier model (same as training)# Input: 5-d embedding -> output: num_classes logits# -----------------------------class FaceClassifier(nn.Module): def __init__(self, input_dim=5, num_classes=7): super(FaceClassifier, self).__init__() self.fc = nn.Sequential( nn.Linear(input_dim, 128), nn.ReLU(inplace=True), nn.Dropout(0.5), nn.Linear(128, num_classes) )
def forward(self, x): return self.fc(x)
# -----------------------------# Classes list# IMPORTANT: set this to match your captured_face_images folder names order.# Ideally keep it same as ImageFolder sorts (alphabetical).# -----------------------------classes = ['person1', 'person2', 'person3', 'person4', 'person5', 'person6', 'person7']import os
from .face_recognition_model import Siamese, FaceClassifier, trnscm, classes
current_path = os.path.dirname(os.path.abspath(__file__))
_SIAMESE = None_CLASSIFIER = None_DEVICE = None
def _to_bgr_np(img): if img is None: return None if isinstance(img, str): return cv2.imread(img) if isinstance(img, Image.Image): rgb = np.array(img.convert("RGB")) return cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) if isinstance(img, np.ndarray): arr = img if arr.ndim == 2: return cv2.cvtColor(arr, cv2.COLOR_GRAY2BGR) if arr.ndim == 3 and arr.shape[2] == 4: arr = arr[:, :, :3] if arr.ndim == 3 and arr.shape[2] == 3: return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR) return arr return None
def _load_models(): global _SIAMESE, _CLASSIFIER, _DEVICE if _SIAMESE is not None and _CLASSIFIER is not None: return _SIAMESE, _CLASSIFIER, _DEVICE
_DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
siamese_path = os.path.join(current_path, "siamese_model.t7") clf_path = os.path.join(current_path, "face_classifier_model.pth")
if not os.path.exists(siamese_path): raise FileNotFoundError(f"Missing siamese model: {siamese_path}") if not os.path.exists(clf_path): raise FileNotFoundError(f"Missing classifier model: {clf_path}")
siamese = Siamese().to(_DEVICE) ckpt = torch.load(siamese_path, map_location=_DEVICE) if isinstance(ckpt, dict) and "net_dict" in ckpt: siamese.load_state_dict(ckpt["net_dict"], strict=True) else: siamese.load_state_dict(ckpt, strict=True) siamese.eval()
classifier = FaceClassifier(input_dim=5, num_classes=len(classes)).to(_DEVICE) classifier.load_state_dict(torch.load(clf_path, map_location=_DEVICE), strict=True) classifier.eval()
_SIAMESE, _CLASSIFIER = siamese, classifier return _SIAMESE, _CLASSIFIER, _DEVICE
def detected_face(image_bgr): face_haar = os.path.join(current_path, "haarcascade_frontalface_default.xml") face_cascade = cv2.CascadeClassifier(face_haar) if face_cascade.empty(): return 0
gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) if faces is None or len(faces) == 0: return 0
x, y, w, h = max(faces, key=lambda f: f[2]*f[3]) crop = gray[y:y+h, x:x+w] return Image.fromarray(crop)
def get_similarity(img1, img2): siamese, classifier, device = _load_models()
i1 = _to_bgr_np(img1) i2 = _to_bgr_np(img2) if i1 is None or i2 is None: return 0.0
f1 = detected_face(i1) f2 = detected_face(i2)
if f1 == 0: f1 = Image.fromarray(cv2.cvtColor(i1, cv2.COLOR_BGR2GRAY)) if f2 == 0: f2 = Image.fromarray(cv2.cvtColor(i2, cv2.COLOR_BGR2GRAY))
t1 = trnscm(f1).unsqueeze(0).to(device) t2 = trnscm(f2).unsqueeze(0).to(device)
with torch.no_grad(): e1 = siamese.forward_once(t1) e2 = siamese.forward_once(t2) dist = torch.nn.functional.pairwise_distance(e1, e2).item()
return float(dist)
def get_face_class(img1): siamese, classifier, device = _load_models()
i1 = _to_bgr_np(img1) if i1 is None: return "UNKNOWN"
f1 = detected_face(i1) if f1 == 0: f1 = Image.fromarray(cv2.cvtColor(i1, cv2.COLOR_BGR2GRAY))
t1 = trnscm(f1).unsqueeze(0).to(device)
with torch.no_grad(): emb = siamese.forward_once(t1) logits = classifier(emb) pred = int(torch.argmax(logits, dim=1).item())
if pred < 0 or pred >= len(classes): return "UNKNOWN" return str(classes[pred])app/Hackathon_setup/exp_recognition.py+52-93
app/Hackathon_setup/exp_recognition_model.py+11-51
app/Hackathon_setup/face_recognition.py+65-208
app/Hackathon_setup/face_recognition_model.py+123-90