chrisjay commited on
Commit
14fef9c
1 Parent(s): b978930

initial commit

Browse files
Files changed (1) hide show
  1. app.py +127 -0
app.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
+ import torchvision
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.optim as optim
8
+
9
+ # This is just to show an interface where one draws a number and gets prediction.
10
+
11
+ n_epochs = 10
12
+ batch_size_train = 128
13
+ batch_size_test = 1000
14
+ learning_rate = 0.01
15
+ momentum = 0.5
16
+ log_interval = 10
17
+ random_seed = 1
18
+ TRAIN_CUTOFF = 10
19
+ MODEL_PATH = 'model'
20
+ METRIC_PATH = os.path.join(MODEL_PATH,'metrics.json')
21
+ MODEL_WEIGHTS_PATH = os.path.join(MODEL_PATH,'mnist_model.pth')
22
+ OPTIMIZER_PATH = os.path.join(MODEL_PATH,'optimizer.pth')
23
+ REPOSITORY_DIR = "data"
24
+ LOCAL_DIR = 'data_local'
25
+
26
+
27
+
28
+
29
+ HF_TOKEN = os.getenv("HF_TOKEN")
30
+ MODEL_REPO = 'mnist-adversarial-model'
31
+ HF_DATASET ="mnist-adversarial-dataset"
32
+ DATASET_REPO_URL = f"https://huggingface.co/datasets/chrisjay/{HF_DATASET}"
33
+ MODEL_REPO_URL = f"https://huggingface.co/model/chrisjay/{MODEL_REPO}"
34
+
35
+
36
+ torch.backends.cudnn.enabled = False
37
+ torch.manual_seed(random_seed)
38
+
39
+
40
+
41
+ TRAIN_TRANSFORM = torchvision.transforms.Compose([
42
+ torchvision.transforms.ToTensor(),
43
+ torchvision.transforms.Normalize(
44
+ (0.1307,), (0.3081,))
45
+ ])
46
+
47
+
48
+
49
+ # Source: https://nextjournal.com/gkoehler/pytorch-mnist
50
+ class MNIST_Model(nn.Module):
51
+ def __init__(self):
52
+ super(MNIST_Model, self).__init__()
53
+ self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
54
+ self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
55
+ self.conv2_drop = nn.Dropout2d()
56
+ self.fc1 = nn.Linear(320, 50)
57
+ self.fc2 = nn.Linear(50, 10)
58
+
59
+ def forward(self, x):
60
+ x = F.relu(F.max_pool2d(self.conv1(x), 2))
61
+ x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
62
+ x = x.view(-1, 320)
63
+ x = F.relu(self.fc1(x))
64
+ x = F.dropout(x, training=self.training)
65
+ x = self.fc2(x)
66
+ return F.log_softmax(x)
67
+
68
+
69
+
70
+
71
+ random_seed = 1
72
+ torch.backends.cudnn.enabled = False
73
+ torch.manual_seed(random_seed)
74
+
75
+ network = MNIST_Model() #Initialize the model with random weights
76
+ optimizer = optim.SGD(network.parameters(), lr=learning_rate,
77
+ momentum=momentum)
78
+
79
+
80
+ # Train
81
+ #train(n_epochs,network,optimizer)
82
+
83
+
84
+ def image_classifier(inp):
85
+ """
86
+ It takes an image as input and returns a dictionary of class labels and their corresponding
87
+ confidence scores.
88
+
89
+ :param inp: the image to be classified
90
+ :return: A dictionary of the class index and the confidence value.
91
+ """
92
+ input_image = torchvision.transforms.ToTensor()(inp).unsqueeze(0)
93
+ with torch.no_grad():
94
+
95
+ prediction = torch.nn.functional.softmax(network(input_image)[0], dim=0)
96
+ #pred_number = prediction.data.max(1, keepdim=True)[1]
97
+ sorted_prediction = torch.sort(prediction,descending=True)
98
+ confidences={}
99
+ for s,v in zip(sorted_prediction.indices.numpy().tolist(),sorted_prediction.values.numpy().tolist()):
100
+ confidences.update({s:v})
101
+ return confidences
102
+
103
+
104
+
105
+
106
+ def main():
107
+ block = gr.Blocks()
108
+
109
+ with block:
110
+
111
+ with gr.Row():
112
+
113
+
114
+ image_input =gr.inputs.Image(source="canvas",shape=(28,28),invert_colors=True,image_mode="L",type="pil")
115
+ label_output = gr.outputs.Label(num_top_classes=2)
116
+
117
+ image_input.change(image_classifier,inputs = [image_input],outputs=[label_output])
118
+
119
+
120
+
121
+ block.launch()
122
+
123
+
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()