rippertnt commited on
Commit
cb5e38e
·
verified ·
1 Parent(s): 0792a03

Create tablet.js

Browse files
Files changed (1) hide show
  1. tablet.js +766 -0
tablet.js ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const p = import('./persona.js')
2
+ const history = []
3
+ let personas = []
4
+ let voice = 'main'
5
+ let type = ''
6
+ let audio = 0
7
+ const vid = document.getElementById('virtual')
8
+
9
+ function build(v){
10
+ for(const persona of personas){
11
+ if(v == persona.voice){
12
+ return `Your name is ${persona.name} who is ${persona.age} years old and ${persona.gender}. Your role is an english teacher on elementary school for beginner learning english and answer ${persona.traits} and like human.`
13
+ //return `Your name is ${persona.name} who is ${persona.age} years old and ${persona.gender}. Your role is ${persona.role} for ${persona.description} and answer ${persona.traits} and like human.`
14
+ }
15
+ }
16
+ }
17
+
18
+
19
+ let isTTS = 1//= //document.querySelector('#MAIN input[name=m_tts]:checked').value
20
+ /*
21
+ var deferredPrompt;
22
+
23
+ window.addEventListener('beforeinstallprompt', function(e) {
24
+ //alert('beforeinstallprompt Event fired');
25
+ e.preventDefault();
26
+
27
+ // Stash the event so it can be triggered later.
28
+ deferredPrompt = e;
29
+
30
+ return false;
31
+ })
32
+ */
33
+
34
+ //function login(){
35
+
36
+ //$.tts('안녕 나는 데이빗이라고 해 만나서 반가워!')
37
+ //document.body.requestFullscreen()
38
+ // $.load('BOT')
39
+ //}
40
+
41
+
42
+ const urlParams = new URLSearchParams(window.location.search);
43
+ const mode = urlParams.get('mode')
44
+ if(mode){
45
+ $.mode = mode
46
+
47
+ }
48
+
49
+ async function create(){
50
+ remove()
51
+ personas = (await p).personas
52
+ console.log('persona',personas)
53
+ type = build('main')
54
+
55
+ fetch(`/v1/bot/morning`).then(async resp=>{
56
+ const result = await resp.json()
57
+ console.log('trend',result.data)
58
+
59
+ document.querySelector('#MAIN ul[name=chats]').innerHTML = `<li class='chat user'>
60
+ ${result.data.title}</br></br>${result.data.content}</br></br>${result.data.think}
61
+ </li>`
62
+
63
+ })
64
+
65
+ }
66
+
67
+ async function init(){
68
+ const list = []
69
+ let param = `&service=ios`
70
+ const resp = await fetch(`/v1/medias?${param}`)
71
+ const items = await resp.json()
72
+
73
+ console.log( items.length)
74
+
75
+ for(const item of items){ // add filter for iphone
76
+ //if(urlParams.get('service') == 'ios' && ["porn","hentai","sexy"].indexOf(item.nsfw) > -1 && item.conf > 0.4)
77
+ // continue
78
+ console.log(item)
79
+
80
+ //if(item.type == 'mp4')
81
+ // list.push(`<div class='item'><video controlsList="nodownload" controls id='_${item.fileId}' preload='auto' class='square' src='/v1/media/${item.fileId}?type=mp4&length=${item.length}'></video></div>`) // <p class='black'>${item.prompt}</p>
82
+ //else
83
+ list.push(`<img class='item' src='/v1/media/${item.fileId}'></img>`)
84
+
85
+ }
86
+
87
+ //for(const item of list)
88
+ document.querySelector('section[name=works]').innerHTML = list.join('')
89
+
90
+ }
91
+
92
+
93
+ async function init2(){
94
+ const list = []
95
+ let param = `&service=ios&userId=rippertnt`
96
+ const resp = await fetch(`/v1/medias?${param}`)
97
+ const items = await resp.json()
98
+
99
+ console.log( items.length)
100
+
101
+ for(const item of items){ // add filter for iphone
102
+ //if(urlParams.get('service') == 'ios' && ["porn","hentai","sexy"].indexOf(item.nsfw) > -1 && item.conf > 0.4)
103
+ // continue
104
+ console.log(item)
105
+
106
+ if(item.type == 'mp4')
107
+ list.push(`<div class='item'><video controlsList="nodownload" controls id='_${item.fileId}' preload='auto' class='square' src='/v1/media/${item.fileId}?type=mp4&length=${item.length}'></video></div>`) // <p class='black'>${item.prompt}</p>
108
+ else
109
+ list.push(`<img class='item' src='/v1/media/${item.fileId}'></img>`)
110
+
111
+ }
112
+
113
+ //for(const item of list)
114
+ document.querySelector('section[name=me]').innerHTML = list.join('')
115
+
116
+ }
117
+
118
+ //init()
119
+ //init2()
120
+
121
+ function home(){
122
+ document.getElementById("LOGIN").style.display = 'none'
123
+ document.getElementById("SIGNIN").style.display = 'none'
124
+
125
+ if(_.id == 'MAIN')
126
+ return
127
+
128
+ const oldId = _.id
129
+ document.getElementById(_.id).className = `animate__animated animate__fadeOut`
130
+ document.getElementById("MAIN").style.display = 'block'
131
+ document.getElementById("MAIN").className = `animate__animated animate__fadeIn`
132
+
133
+ setTimeout(()=>{
134
+ document.getElementById(oldId).style.display = 'none'
135
+ //_.id = 'MAIN'
136
+ },1000)
137
+
138
+ _.id = 'MAIN'
139
+ }
140
+
141
+
142
+ async function account(){
143
+ if(_.userId != 'guest'){
144
+
145
+ const isLogout = confirm(`Logout - ${_.userId}?`)
146
+
147
+ if(isLogout){
148
+ _.userId = 'guest'
149
+ localStorage.setItem('email','')
150
+ localStorage.setItem('userId','')
151
+ document.querySelector('span[name=user]').innerText = 'guest'
152
+ }
153
+
154
+ return
155
+ } else { // guest 이면 로그인 정보를 받아옴
156
+ document.getElementById("LOGIN").style.display = 'block'
157
+ return
158
+ }
159
+ }
160
+
161
+ async function login(){
162
+
163
+ if(_.userId != 'guest'){
164
+
165
+ const isLogout = confirm(`Logout - ${_.userId}?`)
166
+
167
+ if(isLogout){
168
+ _.userId = 'guest'
169
+ localStorage.setItem('email','')
170
+ localStorage.setItem('userId','')
171
+ document.querySelector('span[name=user]').innerText = 'guest'
172
+ }
173
+
174
+ return
175
+ }
176
+
177
+ const userId = document.querySelector('#LOGIN input[name=id]').value
178
+ const pass = document.querySelector('#LOGIN input[name=pass]').value
179
+ //
180
+ const email = userId
181
+ const user = email.split('@')[0]
182
+
183
+ const resp = await fetch(`/v1/account?email=${email}&userId=${userId}&pass=${pass}`)
184
+ const ret = await resp.json()
185
+ console.log(ret.data)
186
+ switch(ret.data){
187
+ case 0: // fail
188
+ alert('Wrong email or password. Check again!')
189
+ break;
190
+ case 1: // pass
191
+
192
+ localStorage.setItem('email',email)
193
+ localStorage.setItem('userId',user)
194
+
195
+ _.userId = userId
196
+ document.querySelector('span[name=user]').innerText = user
197
+ //document.querySelector('span[name=id]').innerText = userId
198
+ document.getElementById('LOGIN').style.display = 'none'
199
+ break;
200
+ case 2: // new
201
+ admission(userId,pass)
202
+ }
203
+
204
+ }
205
+
206
+ async function admission(userId, pass){
207
+ document.getElementById("LOGIN").style.display = 'none'
208
+ document.getElementById("SIGNIN").style.display = 'block'
209
+
210
+ if(userId)
211
+ document.querySelector('#SIGNIN input[name=id]').value = userId
212
+
213
+ if(pass)
214
+ document.querySelector('#SIGNIN input[name=pass]').value = pass
215
+ }
216
+
217
+ async function siginin(){
218
+ const id = document.querySelector('#SIGNIN input[name=id]').value
219
+ const pass = document.querySelector('#SIGNIN input[name=pass]').value
220
+ const pass2 = document.querySelector('#SIGNIN input[name=confirm]').value
221
+
222
+ const token = id.split('@')
223
+ const userId = token[0]
224
+ const email = id
225
+
226
+ let resp = await fetch(`/v1/account?email=${email}&userId=${userId}&pass=${pass}`)
227
+ let ret = await resp.json()
228
+
229
+ if(pass != pass2){
230
+ alert('Password and confirmation is not equal!')
231
+ return
232
+ }
233
+
234
+ resp = await fetch(`/v1/signup?email=${email}&userId=${userId}&pass=${pass}`)
235
+ ret = await resp.json()
236
+
237
+ localStorage.setItem('email',email)
238
+ localStorage.setItem('userId',userId)
239
+
240
+ _.userId = userId
241
+ document.querySelector('span[name=user]').innerText = userId
242
+ //document.querySelector('span[name=id]').innerText = user
243
+ //document.querySelector('div[name=login]').style.display = 'none'
244
+ //document.querySelector('div[name=logout]').style.display = 'block'
245
+
246
+
247
+ document.getElementById("SIGNIN").style.display = 'none'
248
+ }
249
+
250
+
251
+
252
+
253
+
254
+ const email = localStorage.getItem('email')
255
+
256
+ if(email && email != null && email !=''){
257
+ const user = email.split('@')[0]
258
+ _.userId = user
259
+ document.querySelector('span[name=user]').innerText = user
260
+
261
+ if($.getLanguage() == 'ko')
262
+ document.querySelector('#MAIN .chat').innerText = `${user}님, 다시 만나서 반가워요!`
263
+ else
264
+ document.querySelector('#MAIN .chat').innerText = `Welcome back, ${user}!`
265
+ /*
266
+ document.querySelector('span[name=user]').innerText = user
267
+ document.querySelector('span[name=id]').innerText = user
268
+ //document.querySelector('input[name=email]').value = email
269
+
270
+ document.querySelector('div[name=login]').style.display = 'none'
271
+ document.querySelector('div[name=logout]').style.display = 'block'
272
+ */
273
+ }
274
+
275
+ function logout(){
276
+
277
+ localStorage.setItem('email','')
278
+ localStorage.setItem('userId','')
279
+ _.userId = 'guest'
280
+ document.querySelector('span[name=user]').innerText = _.userId
281
+
282
+ document.querySelector('div[name=login]').style.display = 'block'
283
+ document.querySelector('div[name=logout]').style.display = 'none'
284
+ }
285
+
286
+ function keypress(evt){
287
+ console.log('main_key')
288
+ if(evt.which == 13 && !evt.shiftKey)
289
+ search()
290
+
291
+
292
+ }
293
+
294
+ let upload = 0
295
+ let isVideo = 0
296
+
297
+ function camera(evt){
298
+ console.log('main_c')
299
+ if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia ){
300
+ // Navigator mediaDevices not supported
301
+ alert("Media Device not supported")
302
+ return;
303
+ }
304
+ // {video: {width: {exact: 512}, height: {exact: 512}}
305
+ navigator.mediaDevices.getUserMedia({video: {width: {exact: 1024}, height: {exact: 512}}}).then(stream=>{
306
+ document.getElementById("capture").style.display = 'none'
307
+ document.getElementById("cam").style.display = 'block'
308
+ const cam = document.getElementById("cam")
309
+ cam.srcObject = stream
310
+ console.log(cam.height, cam.width)
311
+ //cam.play()
312
+ isVideo = true
313
+ }).catch(err=>{
314
+ alert("Permission faield :", err)
315
+ });
316
+
317
+ }
318
+
319
+ function image(evt){
320
+ isVideo = 0
321
+ console.log('main_i')
322
+ document.getElementById("capture").style.display = 'block'
323
+ document.getElementById("cam").style.display = 'none'
324
+ const gallary = document.getElementById('gallary')
325
+ gallary.click()
326
+ }
327
+
328
+ function remove(evt){
329
+ document.getElementById("capture").style.display = 'block'
330
+ document.getElementById("cam").style.display = 'none'
331
+
332
+ isVideo = false
333
+
334
+ //const canvas = document.getElementById('capture')
335
+ //context.clearRect(0, 0, canvas.width, canvas.height)
336
+
337
+ var img = new Image()
338
+ img.src = '/image/import.gif'
339
+ img.onload = function() {
340
+ canvas = document.getElementById('capture')
341
+ ctx = canvas.getContext("2d")
342
+ canvas.width = img.width;
343
+ canvas.height = img.height;
344
+ ctx.drawImage(img,0,0)
345
+ }
346
+
347
+ upload = 0
348
+ }
349
+
350
+ function setImage(url){
351
+ var img = new Image()
352
+ img.crossOrigin = 'Anonymous';
353
+ img.src = url
354
+ //img.crossOrigin = 'Anonymous';
355
+ img.onload = function(){
356
+ canvas = document.getElementById('capture')
357
+ ctx = canvas.getContext("2d")
358
+ canvas.width = img.width;
359
+ canvas.height = img.height;
360
+ ctx.drawImage(img,0,0)
361
+
362
+ canvas.toBlob(function(blob) {
363
+ const form = new FormData();
364
+ form.append('file', blob, Date.now());
365
+ upload = form
366
+ })
367
+
368
+ }
369
+ }
370
+
371
+ function listen(evt){
372
+ console.log('main_l')
373
+
374
+ if(audio)
375
+ audio.pause()
376
+
377
+ $.listen()
378
+ $.query('input[name=prompt]').className = 'listen'
379
+ }
380
+
381
+ async function processImage(event){
382
+
383
+ //document.querySelector('aside[name=generate]').style.visibility = 'visible'
384
+ //document.querySelector('aside[name=generate] input').value = ''
385
+ //document.querySelector('aside[name=generate] input').focus()
386
+ console.log('process image')
387
+ const files = event.target.files;
388
+
389
+ const reader = new FileReader()
390
+ reader.readAsDataURL(files[0]);
391
+ reader.onload = function(e){
392
+ var img = new Image()
393
+ img.src = e.target.result
394
+ img.onload = function(){
395
+ canvas = document.getElementById('capture')
396
+ ctx = canvas.getContext("2d")
397
+ canvas.width = img.width;
398
+ canvas.height = img.height;
399
+ ctx.drawImage(img,0,0)
400
+ //const cam = document.getElementById("cam")
401
+ //cam.poster = img
402
+ }
403
+ }
404
+
405
+ form = new FormData()
406
+ form.append('file', files[0])
407
+ upload = form
408
+
409
+ /*
410
+ EXIF.getData(files[0], function() {
411
+ var allMetaData = EXIF.getAllTags(this)
412
+ console.log('exif',allMetaData)
413
+ })
414
+ */
415
+ }
416
+
417
+
418
+ function getType(){
419
+ if(voice == 'woman1')
420
+ return 'counselor'
421
+ else if (voice == 'man1' )
422
+ return 'teacher'
423
+ else
424
+ return 'assist'
425
+ }
426
+
427
+ function persona(v){
428
+ voice = $.query('select[name=persona]').value
429
+ //voice = v
430
+
431
+ type = build(voice)
432
+
433
+ document.getElementById('virtual').poster = `/image/${voice}.gif`
434
+
435
+ const elem = document.querySelector('#MAIN ul[name=chats]')
436
+
437
+ const bot = document.createElement('li')
438
+ bot.className = 'chat user'
439
+ bot.innerHTML = type.replace('Your','My')
440
+
441
+ elem.appendChild(bot)
442
+ elem.scroll({ top: elem.scrollHeight }) //, behavior: "smooth"})
443
+ }
444
+
445
+ function human(){
446
+ if(isTTS){
447
+ document.querySelector("#INDEX video.output").classList.add('gray')
448
+ isTTS = 0
449
+ } else {
450
+ document.querySelector("#INDEX video.output").classList.remove('gray')
451
+ isTTS = 1
452
+ }
453
+ }
454
+
455
+ const bots = [
456
+ 'news', 'trend',
457
+ 'weather', 'dust',
458
+ 'music', 'letter',
459
+ 'book', 'movie', 'image'
460
+ ]
461
+
462
+ function checkBot(cmd){
463
+ console.log(`checkbot [${cmd}]`)
464
+ for(const bot of bots){
465
+ if(cmd.indexOf(bot) > -1)
466
+ return bot
467
+ }
468
+
469
+
470
+
471
+ return false
472
+ }
473
+
474
+
475
+
476
+ async function search(isSkip=false){
477
+ let pos = 0
478
+ let lang = 'en'
479
+
480
+ let prompt = document.querySelector('#MAIN [name=prompt]').value + ""
481
+
482
+ if(prompt.length < 1) // too short
483
+ return
484
+
485
+ let query = prompt
486
+ let org = prompt
487
+
488
+ const temp = 0.5 //= //document.querySelector('#MAIN input[name=m_temp]:checked').value
489
+ //const isTTS = 1//= //document.querySelector('#MAIN input[name=m_tts]:checked').value
490
+
491
+ document.querySelector('#MAIN [name=prompt]').value = ''
492
+
493
+ const user = document.createElement('li')
494
+ user.className = 'chat bot'
495
+ user.innerHTML = prompt.replace(/\n/gi, "</br>")
496
+
497
+ const elem = document.querySelector('#MAIN ul[name=chats]')
498
+ elem.appendChild(user)
499
+
500
+ const bot = document.createElement('span')
501
+ bot.className = 'chat user'
502
+ bot.textContent = '...'
503
+ elem.appendChild(bot)
504
+ elem.scroll({ top: elem.scrollHeight })//, behavior: "smooth"})
505
+
506
+ const td = new TextDecoder() // lang auto
507
+
508
+ const form = new FormData()
509
+ form.append('prompt',prompt.replace(/\n/gi, ""))
510
+
511
+
512
+ if(query.toLowerCase().startsWith('draw') || query.toLowerCase().startsWith('paint') ){
513
+ bot.textContent = 'Drawing the image...'
514
+ setImage(`${lb.getGen()}/v1/txt2photo?sentence=${query}&w=512&h=512`)
515
+ } else if(upload == 0 && isVideo == 0){
516
+ console.log('------------------------ chat....--------------')
517
+
518
+ bot.textContent = 'waiting answer...'
519
+ fetch(`/v1/chat`,{
520
+ method : "POST",
521
+ headers : {
522
+ "Content-Type" : 'application/json'
523
+ }, // prompt=${query}&temp=${temp}&lang=en`
524
+ body : JSON.stringify({
525
+ prompt : query.replace(/\n/gi, ""),
526
+ history : [],//history.slice(-2),
527
+ type,
528
+ pos,
529
+ org,
530
+ temp : temp,
531
+ lang : 'en'
532
+ })
533
+
534
+ }).then(async resp=>{
535
+ const reader = resp.body.getReader()
536
+ const chunks = []
537
+
538
+ let done, value, result
539
+ while(!done) {
540
+ ({value, done} = await reader.read())
541
+ if(done){
542
+ console.log('finish2', bot.innerHTML.replace(/\n/gi, "</br>"))
543
+
544
+
545
+ bot.innerHTML = chunks.join('') //.replace(/\n/gi, "</br>")
546
+ history.push(`${query}|${chunks.join('')}`)
547
+
548
+ const form = new FormData()
549
+ form.append('prompt',prompt)
550
+ form.append('data',chunks.join(''))
551
+
552
+ const res = await fetch(`/v1/t/text?prompt=${prompt}&model=chat&userId=${_.userId}`, {
553
+ method: "POST", // or 'PUT'
554
+ //headers: { "application/json" },
555
+ body: form //JSON.stringify({ data : prompt + chunks.join('') }),
556
+ })
557
+
558
+ if(isTTS == 1){
559
+ if(audio)
560
+ audio.pause()
561
+ vid.src = `${lb.getGen()}/v1/txt2human?text=${bot.innerHTML.replace(/<\/br>/gi, "")}&lang=${lang}&voice=${voice}`
562
+ }
563
+
564
+ }
565
+
566
+
567
+ vid.onended = ()=>{
568
+ vid.src = ''
569
+ }
570
+
571
+ vid.oncanplaythrough = ()=>{
572
+
573
+ }
574
+
575
+ //document.getElementById('virtual').src = `/v1/v/human?prompt=${bot.innerHTML.replace(/<\/br>/gi, "")}&lang=${lang}`
576
+
577
+
578
+ bot.onclick = ()=>{
579
+ if(audio)
580
+ audio.pause()
581
+ audio = new Audio(`${lb.getGen()}/v1/tts?text=${bot.innerHTML}&lang=${lang}&voice=main`)
582
+ audio.play()
583
+ }
584
+
585
+
586
+ elem.scroll({ top: elem.scrollHeight })//, behavior: "smooth"})
587
+
588
+ break
589
+
590
+ chunks.push(td.decode(value))
591
+ //console.log(value,td.decode(value))
592
+ //console.log(value.indexOf('\n') > -1, td.decode(value).indexOf('\n') > -1)
593
+ bot.innerHTML = chunks.join('').replace(/\n/gi, "</br>") //.replace(/\n/gi, "</br>")
594
+ elem.scroll({ top :9999999 }) // behavior:"smooth"
595
+ }
596
+
597
+ }).catch(e=>{
598
+ console.error(e)
599
+ return
600
+ })
601
+
602
+ } else {
603
+ bot.textContent = 'waiting answer...'
604
+
605
+ if(isVideo){
606
+ const cam = document.getElementById("cam")
607
+ const canvas = document.getElementById('capture')
608
+ ctx = canvas.getContext("2d")
609
+ //canvas.width = cam.width;
610
+ //canvas.height = cam.height;
611
+ console.log(cam, cam.width)
612
+
613
+ ctx.drawImage(cam,0,0,512,512)
614
+
615
+ const blob = await new Promise(resolve => canvas.toBlob(resolve))
616
+ console.log(blob)
617
+ const form = new FormData();
618
+ form.append('file', blob, Date.now())
619
+ upload = form
620
+ }
621
+
622
+ upload.append('prompt',query)
623
+ upload.append('temp',temp)
624
+ upload.append('lang','en')
625
+
626
+ fetch(`/v1/i/chat`,{ //?prompt=${query}&temp=${temp}&lang=en
627
+ method: 'POST',
628
+ body: upload
629
+ }).then(async resp=>{
630
+ const reader = resp.body.getReader()
631
+ const chunks = []
632
+
633
+ let done, value, result
634
+ while(!done) {
635
+ ({value, done} = await reader.read())
636
+
637
+ if(done){
638
+ if(lang == 'ko'){
639
+ const form = new FormData()
640
+ form.append('prompt',bot.innerHTML)
641
+ const resp = await fetch(`/v1/t/trans?model=en2ko&userId=${_.userId}&skip=1`, {
642
+ method: "POST",
643
+ body: form
644
+ })
645
+ const result = await resp.json()
646
+ console.log(result)
647
+ bot.innerHTML = result.data.replace(/\n/gi, "</br>")
648
+ } else {
649
+ bot.innerHTML = chunks.join('').replace(/\n/gi, "<br>")
650
+ }
651
+
652
+ bot.onclick = ()=>{
653
+ if(audio)
654
+ audio.pause()
655
+ audio = new Audio(`${lb.getGen()}/v1/tts?text=${bot.innerHTML}&lang=${lang}&voice=${voice}`)
656
+ audio.play()
657
+ }
658
+
659
+ if(isTTS == 1){
660
+ if(audio)
661
+ audio.pause()
662
+ document.getElementById('virtual').src = `${lb.getGen()}/v1/txt2human?text=${bot.innerHTML.replace(/<\/br>/gi, "")}&lang=${lang}&voice=${voice}`
663
+
664
+ //audio = new Audio(`${lb.getGen()}/v1/tts?text=${bot.innerHTML}&lang=${lang}&voice=main`)
665
+ //audio.play()
666
+ }
667
+
668
+ elem.scroll({ top: elem.scrollHeight })//, behavior: "smooth"})
669
+
670
+ break
671
+ }
672
+ chunks.push(td.decode(value))
673
+ console.log('chunk',td.decode(value))
674
+ bot.innerHTML = chunks.join('').replace(/\n/gi, "</br>")
675
+ elem.scroll({ top :9999999, behavior:"smooth"})
676
+ }
677
+ }).catch(e=>{
678
+ console.error(e)
679
+ return
680
+ })
681
+ }
682
+
683
+ setTimeout(function() {
684
+ document.querySelector('#MAIN [name=prompt]').focus();
685
+ }, 100);
686
+ }
687
+
688
+ setTimeout(function() {
689
+ document.querySelector('#MAIN [name=prompt]').focus();
690
+ }, 100);
691
+
692
+ function full(){
693
+ if (document.documentElement.requestFullscreen) {
694
+ alert('full page')
695
+ document.documentElement.requestFullscreen()
696
+ } else [
697
+ alert('not allowed')
698
+ ]
699
+ }
700
+
701
+ function listen(){
702
+ document.documentElement.requestFullscreen()
703
+ $.listen()
704
+ $.query('[name=prompt]').className = 'listen'
705
+ }
706
+
707
+ function dragOverHandler(ev) {
708
+ console.log("File(s) in drop zone");
709
+
710
+ // Prevent default behavior (Prevent file from being opened)
711
+ ev.preventDefault();
712
+ }
713
+
714
+ async function dropHandler(ev) {
715
+ ev.preventDefault()
716
+ console.log("File(s) dropped",ev.dataTransfer.items);
717
+
718
+
719
+ const file = ev.dataTransfer.files[0]
720
+ console.log(file)
721
+
722
+ var img = new Image()
723
+ img.src = URL.createObjectURL(file)
724
+ //img.crossOrigin = 'Anonymous';
725
+ img.onload = function(){
726
+ canvas = document.getElementById('capture')
727
+ ctx = canvas.getContext("2d")
728
+ canvas.width = img.width;
729
+ canvas.height = img.height;
730
+ ctx.drawImage(img,0,0)
731
+
732
+ canvas.toBlob(function(blob) {
733
+ const form = new FormData();
734
+ form.append('file', blob, Date.now());
735
+ upload = form
736
+ })
737
+
738
+ }
739
+
740
+
741
+ }
742
+
743
+ _.script['MAIN'] = {
744
+ listening : text=>{
745
+ $.query('[name=prompt]').value = text
746
+ },
747
+ listened : ()=>{
748
+ $.query('[name=prompt]').className = ''
749
+
750
+ if($.query('[name=prompt]').value.length > 0)
751
+ search()
752
+ }
753
+ }
754
+
755
+ if($.getLanguage() == 'ko')
756
+ $.templete('/js/index.json','INDEX')
757
+
758
+ create()
759
+
760
+ document.querySelectorAll('nav button').forEach(elem=>{
761
+ elem.addEventListener("click", ev=>{
762
+ if(document.querySelector('nav button.clicked'))
763
+ document.querySelector('nav button.clicked').classList.remove('clicked')
764
+ elem.classList.add('clicked')
765
+ })
766
+ })