CoolFace
Apppublic

bijankn/Facial_Expression_Recognition

sourceHugging Facemitupdated 2y agoView on Hugging Face
1likes
app.py76 linesDownload Raw Back to root
1### 1. Imports and class names setup ### 2import gradio as gr3import os4import torch5import torchvision6import torch.nn as nn7from torchvision import transforms8 9from timeit import default_timer as timer10from typing import Tuple, Dict11 12# Setup class names13class_names = ["angry", "disgust", "fear", "happy", "neutral", "sad", "surprise"]14 15model = torchvision.models.efficientnet_b2()16 17model.classifier = nn.Sequential(18    nn.Dropout(p=0.3, inplace=True),19    nn.Linear(in_features=1408, out_features=7),20)21 22 23for param in model.parameters():24   param.requires_grad = False25 26model.load_state_dict(27    torch.load(28        f="trained_model.pt",29        map_location=torch.device("cpu"),30    )31)32 33def preprocessImg(img):34   transform = transforms.Compose([35    #    transforms.Grayscale(),36       transforms.Resize((256,256)),37       transforms.ToTensor(),38       transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),39   ])40   img = transform(img)41   return img42 43def predict(img) -> Tuple[Dict, float]:44    """Transforms and performs a prediction on img and returns prediction and time taken.45    """46    start_time = timer()47    48    img = preprocessImg(img).unsqueeze(0)49 50    model.eval()51    with torch.inference_mode():52        pred_probs = torch.softmax(model(img), dim=1)53    54    pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}55    56    pred_time = round(timer() - start_time, 5)57    58    return pred_labels_and_probs, pred_time59 60 61title = "Facial Expression Classifier"62description = "An EfficientNetB2 feature extractor computer vision model to classify images of facial expressions"63article = "for source code you can visit [my github](https://github.com/Bijan-K/Pytorch-Facial-Expression-Recognition)."64 65example_list = [["examples/" + example] for example in os.listdir("examples")]66 67demo = gr.Interface(fn=predict,68                    inputs=gr.Image(type="pil"), 69                    outputs=[gr.Label(num_top_classes=3, label="Predictions"), 70                             gr.Number(label="Prediction time (s)")],71                    examples=example_list, 72                    title=title,73                    description=description,74                    article=article)75 76demo.launch()