Masterdqqq/Facial_Expression_Recognition
1
1"""2File: model.py3Author: Elena Ryumina and Dmitry Ryumin4Description: This module provides functions for loading and processing a pre-trained deep learning model5 for facial expression recognition.6License: MIT License7"""8 9import torch10import requests11from PIL import Image12from torchvision import transforms13from pytorch_grad_cam import GradCAM14 15# Importing necessary components for the Gradio app16from app.config import config_data17from app.model_architectures import ResNet50, LSTMPyTorch18 19 20def load_model(model_url, model_path):21 try:22 with requests.get(model_url, stream=True) as response:23 with open(model_path, "wb") as file:24 for chunk in response.iter_content(chunk_size=8192):25 file.write(chunk)26 return model_path27 except Exception as e:28 print(f"Error loading model: {e}")29 return None30 31path_static = load_model(config_data.model_static_url, config_data.model_static_path) 32pth_model_static = ResNet50(7, channels=3)33pth_model_static.load_state_dict(torch.load(path_static))34pth_model_static.eval()35 36path_dynamic = load_model(config_data.model_dynamic_url, config_data.model_dynamic_path) 37pth_model_dynamic = LSTMPyTorch()38pth_model_dynamic.load_state_dict(torch.load(path_dynamic))39pth_model_dynamic.eval()40 41target_layers = [pth_model_static.layer4]42cam = GradCAM(model=pth_model_static, target_layers=target_layers)43 44def pth_processing(fp):45 class PreprocessInput(torch.nn.Module):46 def init(self):47 super(PreprocessInput, self).init()48 49 def forward(self, x):50 x = x.to(torch.float32)51 x = torch.flip(x, dims=(0,))52 x[0, :, :] -= 91.495353 x[1, :, :] -= 103.882754 x[2, :, :] -= 131.091255 return x56 57 def get_img_torch(img, target_size=(224, 224)):58 transform = transforms.Compose([transforms.PILToTensor(), PreprocessInput()])59 img = img.resize(target_size, Image.Resampling.NEAREST)60 img = transform(img)61 img = torch.unsqueeze(img, 0)62 return img63 64 return get_img_torch(fp)65 