Spaces:
Sleeping
Sleeping
| import torch | |
| import torchvision | |
| from torch import nn | |
| from timeit import default_timer as timer | |
| from typing import Tuple,Dict | |
| import os | |
| from model import create_effnetb2 | |
| # gettingthe classnames | |
| class_names = ["pizza","steak","sushi"] | |
| #lets verify if we can get list of example | |
| foodvision_mini_examples_path = "examples/" | |
| example_list = ["examples/" + example for example in os.listdir(foodvision_mini_examples_path)] | |
| # getting model and its trasofrm | |
| effnetb2_2, effnetb2_transforms_2 = create_effnetb2() # we dont need "model.craete_effnetb2" as its directly imported by us | |
| # load the saved weigths | |
| effnetb2_2.load_state_dict( | |
| torch.load( | |
| f = "09_pretrained_effnetb2_feature_extractor_20_percent.pth", | |
| map_location= torch.device("cpu") | |
| ) | |
| ) | |
| # craeting the predict function | |
| def predict(img) -> Tuple[Dict,float]: | |
| # start a timer | |
| start_time = timer() | |
| # transfomr the input image for use with EffNetB2 | |
| transformed_img = effnetb2_transforms_2(img).unsqueeze(0).to("cpu") | |
| # put the mdoel to eva; mode and make predictions | |
| effnetb2_2.eval() | |
| with torch.inference_mode(): | |
| logits = effnetb2_2(transformed_img) | |
| pred_probs = torch.softmax(logits, dim = 1) | |
| # print(pred_probs) | |
| pred_class = class_names[torch.argmax(pred_probs, dim = 1)] | |
| pred_labels_and_probs = {class_names[i] : float(pred_probs[0][i]) for i in range(len(class_names))} | |
| # calculate pred time | |
| end_time = timer() | |
| pred_time = round(end_time - start_time, 4) | |
| # return pred dict AND PRED TIME | |
| return pred_labels_and_probs, pred_time | |
| # interface zone | |
| import gradio as gr | |
| # craete title , description and article | |
| title = "Food Vision Mini ππ₯©π£" | |
| description = "An [EfficientNetB2 Feature Extractor Computer Vision Model](https://pytorch.org/vision/main/models/generated/torchvision.models.efficientnet_b2.html) to classify images as pizza, steak and sushi" | |
| article = "Created at [09 PyTorch model deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)" | |
| # craeting gradio demo | |
| demo = gr.Interface(fn = predict,inputs = gr.Image(type = "pil"), | |
| outputs = [gr.Label(num_top_classes=3, label = "predictions") , gr.Number(label = "prediciton time(s)")], | |
| examples = example_list, | |
| title = title , description = description, article = article) | |
| demo.launch() # to avoid showing of error, we dont need share = true as it cant be handled by higging face spaces | |