Asadel Ann commited on
Commit
3cccebe
·
1 Parent(s): 59d11b0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import gradio as gr
4
+ import pathlib
5
+ import numpy as np
6
+ import tensorflow
7
+ import PIL.Image
8
+ from PIL import Image
9
+
10
+
11
+ class Model:
12
+ def __init__(self, model_filepath):
13
+ self.graph_def = tensorflow.compat.v1.GraphDef()
14
+ self.graph_def.ParseFromString(model_filepath.read_bytes())
15
+
16
+ input_names, self.output_names = self._get_graph_inout(self.graph_def)
17
+ assert len(input_names) == 1
18
+ self.input_name = input_names[0]
19
+ self.input_shape = self._get_input_shape(self.graph_def, self.input_name)
20
+
21
+ def predict(self, image_filepath):
22
+ image = Image.fromarray(image_filepath).resize(self.input_shape)
23
+ input_array = np.array(image, dtype=np.float32)[np.newaxis, :, :, :]
24
+
25
+ with tensorflow.compat.v1.Session() as sess:
26
+ tensorflow.import_graph_def(self.graph_def, name='')
27
+ out_tensors = [sess.graph.get_tensor_by_name(o + ':0') for o in self.output_names]
28
+ outputs = sess.run(out_tensors, {self.input_name + ':0': input_array})
29
+
30
+ return {name: outputs[i] for i, name in enumerate(self.output_names)}
31
+
32
+ @staticmethod
33
+ def _get_graph_inout(graph_def):
34
+ input_names = []
35
+ inputs_set = set()
36
+ outputs_set = set()
37
+
38
+ for node in graph_def.node:
39
+ if node.op == 'Placeholder':
40
+ input_names.append(node.name)
41
+
42
+ for i in node.input:
43
+ inputs_set.add(i.split(':')[0])
44
+ outputs_set.add(node.name)
45
+
46
+ output_names = list(outputs_set - inputs_set)
47
+ return input_names, output_names
48
+
49
+ @staticmethod
50
+ def _get_input_shape(graph_def, input_name):
51
+ for node in graph_def.node:
52
+ if node.name == input_name:
53
+ return [dim.size for dim in node.attr['shape'].shape.dim][1:3]
54
+
55
+
56
+ def print_outputs(outputs):
57
+ labelopen = open("labels.txt", 'r')
58
+ labels = [line.split(',') for line in labelopen.readlines()]
59
+ outputs = list(outputs.values())[0]
60
+ return str(labels[outputs[0].argmax()][0])
61
+
62
+
63
+ def main(gambar):
64
+ m = pathlib.Path("model.pb")
65
+ #i = pathlib.Path(gambar)
66
+
67
+ model = Model(m)
68
+ outputs = model.predict(gambar)
69
+ return print_outputs(outputs)
70
+ demo = gr.Interface(main, gr.Image(shape=(500, 500)), "text")
71
+ demo.launch()