etemkocaaslan commited on
Commit
2c85ae1
1 Parent(s): 0d9aeae

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+ import torchvision.models as models
4
+ from torchvision import transforms
5
+ import requests
6
+
7
+ preprocess = transforms.Compose([
8
+ transforms.Resize(256),
9
+ transforms.CenterCrop(224),
10
+ transforms.ToTensor(),
11
+ transforms.Normalize(
12
+ mean=[0.485, 0.456 , 0.406],
13
+ std=[0.229, 0.224, 0.225]
14
+ )
15
+ ])
16
+
17
+ response = requests.get("https://git.io/JJkYN")
18
+ labels = response.text.split("\n")
19
+
20
+ image_prediction_models = {
21
+ 'resnet': models.resnet50,
22
+ 'alexnet': models.alexnet,
23
+ 'vgg': models.vgg16,
24
+ 'squeezenet': models.squeezenet1_0,
25
+ 'densenet': models.densenet161,
26
+ 'inception': models.inception_v3,
27
+ 'googlenet': models.googlenet,
28
+ 'shufflenet': models.shufflenet_v2_x1_0,
29
+ 'mobilenet': models.mobilenet_v2,
30
+ 'resnext': models.resnext50_32x4d,
31
+ 'wide_resnet': models.wide_resnet50_2,
32
+ 'mnasnet': models.mnasnet1_0,
33
+ 'efficientnet': models.efficientnet_b0,
34
+ 'regnet': models.regnet_y_400mf,
35
+ 'vit': models.vit_b_16,
36
+ 'convnext': models.convnext_tiny
37
+ }
38
+
39
+ def load_pretrained_model(model_name):
40
+ model_name_lower = model_name.lower()
41
+ if model_name_lower in image_prediction_models:
42
+ model_class = image_prediction_models[model_name_lower]
43
+ model = model_class(pretrained=True)
44
+ return model
45
+ else:
46
+ raise ValueError(f"Model {model_name} is not available for image prediction in torchvision.models")
47
+
48
+ def get_model_names(models_dict):
49
+ return [name.capitalize() for name in models_dict.keys()]
50
+
51
+ model_list = get_model_names(image_prediction_models)
52
+
53
+ def classify_image(input_image, selected_model):
54
+ input_tensor = preprocess(input_image)
55
+ input_batch = input_tensor.unsqueeze(0)
56
+ model = load_pretrained_model(selected_model)
57
+ if torch.cuda.is_available():
58
+ input_batch = input_batch.to('cuda')
59
+
60
+ with torch.no_grad():
61
+ output = model(input_batch)
62
+
63
+ probabilities = F.softmax(input = output[0] , dim = 0)
64
+ top_prob, top_catid = torch.topk(probabilities, 5)
65
+ confidences = {labels[top_catid[i].item()]: top_prob[i].item() for i in range(top_prob.size(0))}
66
+ return confidences
67
+
68
+ import gradio as gr
69
+
70
+ interface = gr.Interface(
71
+ fn=classify_image,
72
+ inputs= [gr.Image(type='pil'),
73
+ gr.Dropdown(model_list)],
74
+ outputs=gr.Label(num_top_classes=5))
75
+ interface.launch()