File size: 1,867 Bytes
44d3940
 
 
2900533
44d3940
 
 
 
 
f6d05cd
44d3940
 
 
 
 
 
 
 
68f7e9f
44d3940
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217aa89
44d3940
 
 
 
 
98aadeb
 
70bd8bc
98aadeb
44d3940
 
 
 
 
 
 
 
 
 
98aadeb
 
44d3940
 
 
fadbdd8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

import torch
import torchvision
import os
import gradio as gr
from model import create_vit_b16

# loading the classnames
class_names = []
with open("class_names.txt", "r") as f:
  for cls in f.readlines():
    class_names.append(cls[:-1])

# creating a ViT model
vit_b16_model, vit_transforms = create_vit_b16(num_classes=len(class_names))

vit_b16_model.load_state_dict(
    torch.load(
        f="ViT_B16_510_classes.pth",
        map_location=torch.device("cpu")
    )
)

# creating a predict function
def predict(img):
  """
  Makes prediction on the given image
  """

  img = vit_transforms(img).unsqueeze(dim=0)

  vit_b16_model.eval()
  with torch.inference_mode():
    pred_logits = vit_b16_model(img)
    preds = torch.softmax(pred_logits, dim=1)
    
    # Create a prediction label and prediction probability dictionary for each prediction class
    pred_and_prob_labels = {class_names[i]: preds[0][i].item() for i in range(len(class_names))}

  return pred_and_prob_labels

# creating title, description for the webpage
title = "Birds Classifier 🪶"
description = "Classifies an Image of a Bird to any one of the [510 species](https://huggingface.co/spaces/Kathir0011/Birds_Classification/blob/main/class_names.txt)."
article = "Other Projects:\n"\
"💰 [US Health Insurance Cost Prediction](http://health-insurance-cost-predictor-k19.streamlit.app/)\n"\
"📰 [Fake News Detector](https://fake-news-detector-k19.streamlit.app/)"
# creating examples list
examples_list = [["examples/" + img] for img in os.listdir("examples")]

# Building a gradio app
bird_classification = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs=gr.Label(num_top_classes=3, label="Prediction"),
    examples = examples_list,
    title=title,
    description=description,
    article=article
)

# launching the web app
bird_classification.launch()