|
|
|
import gradio as gr |
|
import os |
|
import torch |
|
|
|
from torchvision import transforms |
|
from timeit import default_timer as timer |
|
from typing import Tuple, Dict |
|
|
|
|
|
|
|
|
|
model = torch.load(f="smile_classifier.pth") |
|
|
|
transform = transforms.Compose([ |
|
transforms.CenterCrop(size=[178, 178]), |
|
transforms.Resize(size=[64, 64]), |
|
transforms.ToTensor() |
|
]) |
|
|
|
|
|
|
|
|
|
def predict(img) -> Tuple[Dict, float]: |
|
"""Transforms and performs a prediction on img and returns prediction and time taken. |
|
""" |
|
|
|
start_time = timer() |
|
|
|
|
|
img = transform(img).unsqueeze(0) |
|
|
|
|
|
model.eval() |
|
with torch.inference_mode(): |
|
|
|
pred_probs = model(img)[:, 0] |
|
|
|
|
|
if pred_probs >= 0.5: |
|
pred_labels_and_probs = {"Smiling": f"{pred_probs.item()}"} |
|
else: |
|
pred_labels_and_probs = {"Not Smiling": f"{pred_probs.item()}"} |
|
|
|
|
|
pred_time = round(timer() - start_time, 5) |
|
|
|
|
|
return pred_labels_and_probs, pred_time |
|
|
|
|
|
|
|
|
|
title = "Smile Classifier πππ" |
|
description = "A Smile classifier computer vision model (trained on [celebA](https://pytorch.org/vision/main/generated/torchvision.datasets.CelebA.html) data) to classify images of people and identify if they are smiling or not." |
|
article = "Please select an image from provided examples and submit, the model will predict if the person in the image \ |
|
is smiling or not and will also provide prediction probabilities." |
|
|
|
|
|
example_list = [["examples/" + example] for example in os.listdir("examples")] |
|
|
|
|
|
demo = gr.Interface(fn=predict, |
|
inputs=gr.Image(type="pil"), |
|
outputs=[gr.Label(num_top_classes=2, label="Predictions"), |
|
gr.Number(label="Prediction time (s)")], |
|
|
|
examples=example_list, |
|
title=title, |
|
description=description, |
|
article=article) |
|
|
|
|
|
demo.launch() |
|
|