-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
260 lines (227 loc) · 5.77 KB
/
main.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
variables
*/
var model;
var canvas;
var classNames = [];
var canvas;
var coords = [];
var mousePressed = false;
var mode;
/*
prepare the drawing canvas
*/
$(function() {
canvas = window._canvas = new fabric.Canvas('canvas');
canvas.backgroundColor = '#ffffff';
canvas.isDrawingMode = 0;
canvas.freeDrawingBrush.color = "black";
canvas.freeDrawingBrush.width = 10;
canvas.renderAll();
//setup listeners
canvas.on('mouse:up', function(e) {
getFrame();
mousePressed = false
});
canvas.on('mouse:down', function(e) {
mousePressed = true
});
canvas.on('mouse:move', function(e) {
recordCoor(e)
});
})
/*
set the table of the predictions
*/
function setTable(top5, probs) {
//loop over the predictions
for (var i = 0; i < top5.length; i++) {
let sym = document.getElementById('sym' + (i + 1))
let prob = document.getElementById('prob' + (i + 1))
sym.innerHTML = top5[i]
prob.innerHTML = Math.round(probs[i] * 100)
}
//create the pie
createPie(".pieID.legend", ".pieID.pie");
}
/*
record the current drawing coordinates
*/
function recordCoor(event) {
var pointer = canvas.getPointer(event.e);
var posX = pointer.x;
var posY = pointer.y;
if (posX >= 0 && posY >= 0 && mousePressed) {
coords.push(pointer)
}
}
/*
get the best bounding box by trimming around the drawing
*/
function getMinBox() {
//get coordinates
var coorX = coords.map(function(p) {
return p.x
});
var coorY = coords.map(function(p) {
return p.y
});
//find top left and bottom right corners
var min_coords = {
x: Math.min.apply(null, coorX),
y: Math.min.apply(null, coorY)
}
var max_coords = {
x: Math.max.apply(null, coorX),
y: Math.max.apply(null, coorY)
}
//return as strucut
return {
min: min_coords,
max: max_coords
}
}
/*
get the current image data
*/
function getImageData() {
//get the minimum bounding box around the drawing
const mbb = getMinBox()
//get image data according to dpi
const dpi = window.devicePixelRatio
const imgData = canvas.contextContainer.getImageData(mbb.min.x * dpi, mbb.min.y * dpi,
(mbb.max.x - mbb.min.x) * dpi, (mbb.max.y - mbb.min.y) * dpi);
return imgData
}
/*
get the prediction
*/
function getFrame() {
//make sure we have at least two recorded coordinates
if (coords.length >= 2) {
//get the image data from the canvas
const imgData = getImageData()
//get the prediction
const pred = model.predict(preprocess(imgData)).dataSync()
//find the top 5 predictions
const indices = findIndicesOfMax(pred, 5)
const probs = findTopValues(pred, 5)
const names = getClassNames(indices)
//set the table
setTable(names, probs)
}
}
/*
get the the class names
*/
function getClassNames(indices) {
var outp = []
for (var i = 0; i < indices.length; i++)
outp[i] = classNames[indices[i]]
return outp
}
/*
load the class names
*/
async function loadDict() {
if (mode == 'ar')
loc = 'model2/class_names_ar.txt'
else
loc = 'model2/class_names.txt'
await $.ajax({
url: loc,
dataType: 'text',
}).done(success);
}
/*
load the class names
*/
function success(data) {
const lst = data.split(/\n/)
for (var i = 0; i < lst.length - 1; i++) {
let symbol = lst[i]
classNames[i] = symbol
}
}
/*
get indices of the top probs
*/
function findIndicesOfMax(inp, count) {
var outp = [];
for (var i = 0; i < inp.length; i++) {
outp.push(i); // add index to output array
if (outp.length > count) {
outp.sort(function(a, b) {
return inp[b] - inp[a];
}); // descending sort the output array
outp.pop(); // remove the last index (index of smallest element in output array)
}
}
return outp;
}
/*
find the top 5 predictions
*/
function findTopValues(inp, count) {
var outp = [];
let indices = findIndicesOfMax(inp, count)
// show 5 greatest scores
for (var i = 0; i < indices.length; i++)
outp[i] = inp[indices[i]]
return outp
}
/*
preprocess the data
*/
function preprocess(imgData) {
return tf.tidy(() => {
//convert to a tensor
let tensor = tf.fromPixels(imgData, numChannels = 1)
//resize
const resized = tf.image.resizeBilinear(tensor, [28, 28]).toFloat()
//normalize
const offset = tf.scalar(255.0);
const normalized = tf.scalar(1.0).sub(resized.div(offset));
//We add a dimension to get a batch shape
const batched = normalized.expandDims(0)
return batched
})
}
/*
load the model
*/
async function start(cur_mode) {
//arabic or english
mode = cur_mode
//load the model
model = await tf.loadModel('model2/model.json')
//warm up
model.predict(tf.zeros([1, 28, 28, 1]))
//allow drawing on the canvas
allowDrawing()
//load the class names
await loadDict()
}
/*
allow drawing on canvas
*/
function allowDrawing() {
canvas.isDrawingMode = 1;
if (mode == 'en')
document.getElementById('status').innerHTML = 'Model Loaded';
else
document.getElementById('status').innerHTML = 'تم التحميل';
$('button').prop('disabled', false);
var slider = document.getElementById('myRange');
slider.oninput = function() {
canvas.freeDrawingBrush.width = this.value;
};
}
/*
clear the canvs
*/
function erase() {
canvas.clear();
canvas.backgroundColor = '#ffffff';
coords = [];
}