Upload 4 files
Browse filesFiles changed (4)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import 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'face_cascade = cv2.CascadeClassifier(face_haar)eye_cascade = cv2.CascadeClassifier(eye_haar) # (not used, but kept as given)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# Return the face crop with maximum areaface_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 imagereturn requireddef _load_cached_model():"""Load and cache model on first call.Uses current_path + filename to be server-safe."""global _MODEL, _DEVICEif _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 = Nonefor fname in MODEL_CANDIDATES:p = os.path.join(current_path, fname)if os.path.exists(p):model_path = pbreakif 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#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 modelmodel, 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))# 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]with torch.no_grad():logits = model(x)pred_idx = int(torch.argmax(logits, dim=1).item())pred_label = classes.get(pred_idx, "UNKNOWN")return pred_label.capitalize()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import numpy(__file__))import numpy as np_MODEL = None_DEVICE = Nonedef _to_bgr_np(img):# filepathif isinstance(img, str):return cv2.imread(img)# PILif isinstance(img, Image.Image):rgb = np.array(img.convert("RGB"))return cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)# numpyif 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 RGBreturn imgreturn Nonedef 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 0gray = 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# choose max area facex, 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():global _MODEL, _DEVICEif _MODEL is not None:return _MODEL, _DEVICE_DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# Use the exact filename you committed to the repockpt_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, _DEVICEdef get_expression(img):model, device = _load_cached_model()img_bgr = _to_bgr_np(img)if img_bgr is None:return "UNKNOWN"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 = int(torch.argmax(logits, dim=1).item())return classes.get(pred, "UNKNOWN").capitalize()import cv2import torchfrom PIL import Imageimport osfrom .exp_recognition_model import trnscm, load_model, classes
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475761 unmodified line78798081828384858687888990919293949596979899import 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.classes = {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 = 100class facExpRec(nn.Module):"""Facial Expression Recognition model using ResNet18 backbone.Expects input: [B, 3, IMG_SIZE, IMG_SIZE]Output logits: [B, 7]"""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_featuresself.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 imagedef 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 linetransforms.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()1234567891011121314151617181920212223242526272829303132333435363738394041424344451 unmodified line47484950515253545556575859import osimport torchimport torch.nn as nnimport torchvision.models as modelsfrom torchvision import transformsfrom PIL import Image# Must match train_dataset.class_to_idxclasses = {0: "ANGER",1: "DISGUST",2: "FEAR",3: "HAPPINESS",4: "NEUTRAL",5: "SADNESS",6: "SURPRISE",}IMAGENET_MEAN = [0.485, 0.456, 0.406]IMAGENET_STD = [0.229, 0.224, 0.225]IMG_SIZE = 100class facExpRec(nn.Module):"""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__()self.backbone = models.resnet18(weights=None)in_features = self.backbone.fc.in_featuresself.backbone.fc = nn.Linear(in_features, num_classes)def forward(self, x):return self.backbone(x)def ensure_rgb(image: Image.Image) -> Image.Image:if image.mode != "RGB":image = image.convert("RGB")return imagedef get_transform(img_size: int = IMG_SIZE):return transforms.Compose([transforms.Lambda(ensure_rgb),transforms.Resize((img_size, img_size)),1 unmodified linetransforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),])trnscm = get_transform(IMG_SIZE)def load_model(checkpoint_path: str, device: str = "cpu", num_classes: int = 7) -> facExpRec: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()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211import 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 face_recognition_model while uploading to the server.from .face_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 = os.path.dirname(os.path.abspath(__file__))# Cache models so we load only once per container_SIAMESE = None_CLASSIFIER = None_DEVICE = Nonedef _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 stringif isinstance(img, str):arr = cv2.imread(img)return arr # may be None if path invalid# PIL Imageif isinstance(img, Image.Image):rgb = np.array(img.convert("RGB"))return cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)# numpy arrayif isinstance(img, np.ndarray):arr = img# If float image in [0,1], convert to uint8if 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 BGRif arr.ndim == 2:return cv2.cvtColor(arr, cv2.COLOR_GRAY2BGR)# RGBA (H, W, 4) -> drop alpha then RGB->BGRif arr.ndim == 3 and arr.shape[2] == 4:arr = arr[:, :, :3]# RGB (H, W, 3) -> BGRif arr.ndim == 3 and arr.shape[2] == 3:return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)return arrreturn Nonedef _load_models():"""Load Siamese + classifier once using current_path."""global _SIAMESE, _CLASSIFIER, _DEVICEif _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, classifierreturn _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 crashingif face_cascade.empty():return 0gray = 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 facemax_area = -1best = Nonefor (x, y, w, h) in faces:area = w * hif area > max_area:max_area = areabest = gray[y:y+h, x:x+w]if best is None:return 0return 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 arraysimg1_bgr = _to_bgr_np(img1)img2_bgr = _to_bgr_np(img2)if img1_bgr is None or img2_bgr is None:return 0.0det_img1 = detected_face(img1_bgr)det_img2 = detected_face(img2_bgr)# fallback if face not detectedif 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 tensorface1 = 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])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768%%writefile face_recognition_model.pyimport torchimport torch.nn as nnfrom torchvision import transformsfrom PIL import Imagedef ensure_gray(image: Image.Image) -> Image.Image:if image.mode != "L":image = image.convert("L")return imagetrnscm = 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 outdef 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"]
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import 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 imagetrnscm = 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 outdef 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']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import numpy as npimport cv2import torchfrom PIL import Imageimport osfrom .face_recognition_model import Siamese, FaceClassifier, trnscm, classescurrent_path = os.path.dirname(os.path.abspath(__file__))_SIAMESE = None_CLASSIFIER = None_DEVICE = Nonedef _to_bgr_np(img):if img is None:return Noneif 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 = imgif 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 arrreturn Nonedef _load_models():global _SIAMESE, _CLASSIFIER, _DEVICEif _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, classifierreturn _SIAMESE, _CLASSIFIER, _DEVICEdef 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 0gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)faces = face_cascade.detectMultiScale(gray, 1.3, 5)if faces is None or len(faces) == 0:return 0x, 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.0f1 = 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