File size: 12,860 Bytes
f9f0fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61538ff
 
 
 
d01d0c9
61538ff
c466c0a
 
61538ff
 
 
 
f9f0fec
 
 
 
61538ff
 
 
d01d0c9
 
 
 
 
 
61538ff
f9f0fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c466c0a
 
 
f9f0fec
 
 
 
 
 
 
eb05599
4e136cd
 
eb05599
 
 
 
 
f9f0fec
d01d0c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9f0fec
f351f64
 
7c54356
eb05599
f351f64
7c54356
eb05599
f9f0fec
 
 
 
c466c0a
 
f9f0fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e5adb9
f9f0fec
61538ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9f0fec
 
61538ff
 
 
 
 
 
d01d0c9
61538ff
 
 
d01d0c9
61538ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d01d0c9
61538ff
 
 
 
 
 
 
 
 
 
 
f9f0fec
2e5adb9
f9f0fec
 
 
 
 
 
 
 
2e5adb9
f9f0fec
 
 
 
 
 
 
 
 
 
61538ff
f9f0fec
 
 
 
 
2e5adb9
f9f0fec
2e5adb9
f9f0fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1103cb
 
2e5adb9
f1103cb
 
d01d0c9
b11a2b4
d01d0c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2da380
 
d01d0c9
 
 
b2da380
 
d01d0c9
b2da380
d01d0c9
 
b2da380
d01d0c9
 
 
 
 
 
 
 
 
 
 
 
 
 
b11a2b4
31d1877
f1103cb
f9f0fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
let myCanvas
const arrows = []
let current_points = []
let t_size
let button
let isOnCanvas = false;
let socket;
let live = false;
let timer;
let capture;
let instructions;
let current_instructions;
let messages_list = []
let timerWaiting;
let waiting = false;

let active_rearcam = false;
let camConfig = "user";
let isOnMobile;
let camIsON = false;
let device_orientation;

let graphicsToSend;

function isMobileDevice() {
    return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
}

//-----------------------------------------------------
//-----------------------------------------------------

function preload(){

    isOnMobile = isMobileDevice()
    console.log("is on mobile ? " + isOnMobile)

    if(isOnMobile){
      device_orientation = screen.orientation.type;
    }


    
    // Socket events handlers
    socket = io();
    // client-side
    socket.on("connect", () => {
        console.log(socket.id);
    });
    
    socket.on("hello", (arg) => {
        let api_data_test = arg[1]
        console.log(api_data_test) 
    });  

    socket.on("api_error", (arg) => {
        let message = arg
        console.log(message) 
    }); 
    // ————————
}

function call_api(socket, instructions){
    console.log("Calling API ... ")
    waiting = true;
    show_loading()
    //cnv_data = myCanvas.elt.toDataURL('image/png');
    graphicsToSend.loadPixels()
    cnv_data = graphicsToSend.canvas.toDataURL('image/png');
    let data = [
        cnv_data,
        instructions
    ]
    socket.emit("ask_api", data);
}

function windowResized() {
    if(windowWidth <= 500){
        resizeCanvas(380, 380*320/576);
    } else {
        resizeCanvas(576, 320);
    }
}

function setup() {

    screen.orientation.addEventListener("change", function(e) {
      device_orientation = screen.orientation.type
      console.log(device_orientation)
      if(camIsON){
                if(capture){
                    capture.remove()
                    capture = undefined
                  }
            
                  if(active_rearcam == true){
                    let new_constraints = {
                          audio: false,
                          video: {
                            facingMode:  {
                              exact: "environment"
                            }
                          }    
                        };
                    capture = createCapture(new_constraints)
                    capture.hide()
                  } else {
                    let new_constraints = {
                          audio: false,
                          video: {
                            facingMode:  "user"
                          }
                          //video: {
                            //facingMode: "user"
                          //} 
                        };
                    capture = createCapture(new_constraints)
                    capture.hide()
                  }
                }
    });
    pixelDensity(1)
    if(windowWidth <= 500){
        myCanvas = createCanvas(380, 380*320/576);
        
    } else {
        myCanvas = createCanvas(576, 320);
        
    }
    background(220)
    myCanvas.id('myCanvas')
    myCanvas.parent("canvas-container")

    graphicsToSend = createGraphics(myCanvas.width, myCanvas.height)

    socket.on("api_response", (response) => {
        waiting = false;
        clearTimeout(timerWaiting)
        
        
        vision_text = response[0]
        console.log(vision_text)
        messages_list.push(vision_text)
 
        if(live === true){
            loadingDiv = document.getElementById("loading-div")
            loadingDiv.innerHTML = "_"
            display_messages()
            console.log("Sending new requestion in 3 seconds")
            
            timer = setTimeout(() => {
                console.log(current_instructions)
                call_api(socket, current_instructions)
            }, 3000)
        }
    });
    
    // Watch if cursor is above canvas or not
    let getCanvas = document.getElementById('myCanvas');

    getCanvas.addEventListener("pointerdown", (e) => {
        //console.log("pointerDown");
        getCanvas.setPointerCapture(e.pointerId);
        isOnCanvas = true;
    }, false);

    getCanvas.addEventListener("pointerup", (e) => {
        //console.log("pointerUp");

        if (isOnCanvas) {
        getCanvas.releasePointerCapture(e.pointerId);
        isOnCanvas = false;
        }
    }, false);
    //—————————
  
    // Buttons 
    start_capture_button=createButton("打开摄像头")
    start_capture_button.mousePressed(() => {
        camIsON = true;
        if(!active_rearcam){
            camConfig = "user"
        } else {
            camConfig = {
                exact: "environment"
            }
        }
        let constraints = {
            audio: false,
            video: {
              facingMode:  camConfig
            }    
          };
        capture = createCapture(constraints);
        capture.hide();
    })

    if(isOnMobile){
        checkbox_rearcam = createCheckbox("switch to rear cam");
        checkbox_rearcam.parent("checkbox-rear");
    
        checkbox_rearcam.mousePressed( () => {
          
            if(active_rearcam == false){
                active_rearcam = true;
            } else {
                active_rearcam = false
            }
            
            if(camIsON){
                if(capture){
                    capture.remove()
                    capture = undefined
                  }
            
                  if(active_rearcam == true){
                    let new_constraints = {
                          audio: false,
                          video: {
                            facingMode:  {
                              exact: "environment"
                            }
                          }    
                        };
                    capture = createCapture(new_constraints)
                    capture.hide()
                  } else {
                    let new_constraints = {
                          audio: false,
                          video: {
                            facingMode:  "user"
                          }
                          //video: {
                            //facingMode: "user"
                          //} 
                        };
                    capture = createCapture(new_constraints)
                    capture.hide()
                  }
                }
            })
          
    }
    
    start_button = createButton('开启实时视觉识别');
    start_button.mousePressed(() => {
        live = true;
        current_instructions = input_instructions.value()
        console.log("Live in ON")
        console.log(current_instructions)
        call_api(socket, current_instructions)
    })
    
    stop_button = createButton('停止');
    stop_button.mousePressed(() => {
        live = false;
        waiting = false;
        // Abort the timer
        clearTimeout(timer);
        clearTimeout(timerWaiting)
        loadingDiv.innerHTML = "_"
        if(capture){
            capture.remove();
            capture = undefined
            camIsON = false;
        }
        console.log("live is OFF")
        //redraw()
    })
    
    input_instructions = createInput("镜头前发生什么了? ")

    change_instructions = createButton("更改指示")
    change_instructions.mousePressed(() => {
        current_instructions = input_instructions.value()
    })

    start_capture_button.parent("buttons-container")
    start_button.parent("buttons-container")
    stop_button.parent("buttons-container")
    input_instructions.parent("instructions-container")
    change_instructions.parent("instructions-container")

    loadingDiv = document.getElementById("loading-div")

}

function draw() {
    background(220);
    textAlign(CENTER);
    text('打开你的网络摄像头', width/2, height/2);
    
    if(capture != undefined){
      
      if(!active_rearcam){
          
        
        if(isOnMobile){
          if(device_orientation == "portrait" || device_orientation == "portrait-primary" || device_orientation == "portrait-secondary"){
            graphicsToSend.image(capture,(myCanvas.width/2)-(capture.width/2), -(capture.height/4))
            push()
          //move image by the width of image to the left
            translate(myCanvas.width, 0);
          //then scale push()
          //move image by the width of image to the left
          //to flip the image
            scale(-1, 1);
            image(capture,(myCanvas.width/2)-(capture.width/2), -(capture.height/4))
            pop()
          } else {
            graphicsToSend.image(capture, 0, 0)
            push()
          //move image by the width of image to the left
          translate(myCanvas.width, 0);
          //then scale push()
          //move image by the width of image to the left
          //to flip the image
            scale(-1, 1);
            image(capture, 0, 0)
            pop()
          }
        } else {
          graphicsToSend.image(capture, 0, 0)
          push()
          //move image by the width of image to the left
          translate(myCanvas.width, 0);
          //then scale push()
          //move image by the width of image to the left
          //to flip the image
          scale(-1, 1);
          image(capture, 0, 0)
          pop()
        }          
      
      } else {
          if(isOnMobile){
            if(device_orientation == "portrait" || device_orientation == "portrait-primary" || device_orientation == "portrait-secondary"){
              graphicsToSend.image(capture,(myCanvas.width/2)-(capture.width/2), -(capture.height/4))
              image(capture,(myCanvas.width/2)-(capture.width/2), -(capture.height/4))
            } else {
                graphicsToSend.image(capture, 0, 0)
                image(capture, 0, 0)
              
              
            }
          } else {
            graphicsToSend.image(capture, 0, 0)
            image(capture, 0, 0)
          }
      }
    
    }
}

function display_messages(){
    visionDiv = document.getElementById("vision-text-container")
    visionDiv.innerHTML = ""
    //for(i=0; i < messages_list.length - 1; i++){
    //    newNode = document.createElement('div');
    //    newNode.classList.add('text-msg')
    //    newNode.innerHTML = messages_list[i]; 
    //    visionDiv.appendChild(newNode);  
    //}
    newNode_last = document.createElement('div'); 
    newNode_last.classList.add('text-msg')
    visionDiv.appendChild(newNode_last);
    const text_msg = messages_list[messages_list.length - 1]
    const words = text_msg.split(" "); // splits the text into an array of words

    // Function that returns a promise which resolves after a specified number of milliseconds
    function wait(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }

    async function streamText(words) {
        for (let word of words) {
            //console.log(word);
            newNode_last.innerHTML += " " + word;
            //visionDiv.scrollTop = visionDiv.scrollHeight;
            await wait(30); // Wait for 1 second before logging next word
        }
    }

    streamText(words);
    
}

function clean(){
    if(waiting == true){
        loadingDiv.innerHTML = ""
        timerWaiting = setTimeout(show_loading, 500)
    } else {
        loadingDiv.innerHTML = "_"
    }
    
}

function show_loading(){
    
    if(waiting == true){
        loadingDiv.innerHTML = ""
        loading_text = ". . ."
    } else {
        loading_text = "_"
    }
    
    const dots = loading_text.split(" "); // splits the text into an array of words

    // Function that returns a promise which resolves after a specified number of milliseconds
    function wait(ms) {
        if(waiting == true){
            
            return new Promise((resolve) => resolveTimer = setTimeout(resolve, ms));
        } else {
            clearTimeout(resolveTimer)
            loadingDiv.innerHTML = "_"
        }
        
    }

    async function streamDots(words) {
        
        if(waiting == true){
            
            for (let word of words) {
                //console.log(word);
                loadingDiv.innerHTML += " " + word;
                //visionDiv.scrollTop = visionDiv.scrollHeight;
                await wait(500); // Wait for 1 second before logging next word
            }
        
            
            //console.log("ENLEVE")
            
            //timerWaiting = setTimeout(show_loading, 500)
            clean()
        } else {
            clearTimeout(timerWaiting)
            //loadingDiv.innerHTML = "_"
        }
    }

    streamDots(dots);
    
    
}