File size: 20,662 Bytes
cb5e38e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
const p  = import('./persona.js')
const history = []
let personas = []
let voice = 'main'
let type = ''
let audio = 0
const vid = document.getElementById('virtual')

function build(v){
  for(const persona of personas){
    if(v == persona.voice){
      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.`
      //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.`
    }
  }
}


let isTTS = 1//= //document.querySelector('#MAIN input[name=m_tts]:checked').value
/*
var deferredPrompt;

window.addEventListener('beforeinstallprompt', function(e) {
  //alert('beforeinstallprompt Event fired');
  e.preventDefault();

  // Stash the event so it can be triggered later.
  deferredPrompt = e;

  return false;
})
*/

//function login(){

  //$.tts('μ•ˆλ…• λ‚˜λŠ” 데이빗이라고 ν•΄ λ§Œλ‚˜μ„œ λ°˜κ°€μ›Œ!')
  //document.body.requestFullscreen()
//  $.load('BOT')
//}


const urlParams = new URLSearchParams(window.location.search);
const mode = urlParams.get('mode')
if(mode){
  $.mode = mode

}

async function create(){
  remove()
  personas = (await p).personas
  console.log('persona',personas)
  type = build('main')

  fetch(`/v1/bot/morning`).then(async resp=>{
    const result = await resp.json()
    console.log('trend',result.data)
    
    document.querySelector('#MAIN ul[name=chats]').innerHTML = `<li class='chat user'>
      ${result.data.title}</br></br>${result.data.content}</br></br>${result.data.think}
    </li>`

  })  

}

async function init(){
  const list = []
  let param = `&service=ios`
  const resp = await fetch(`/v1/medias?${param}`)
  const items = await resp.json()

  console.log( items.length)

  for(const item of items){ // add filter for iphone
    //if(urlParams.get('service') == 'ios' && ["porn","hentai","sexy"].indexOf(item.nsfw) > -1 && item.conf > 0.4)
    //  continue
    console.log(item)

    //if(item.type == 'mp4')
    // 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>
    //else
      list.push(`<img class='item' src='/v1/media/${item.fileId}'></img>`)

  }

  //for(const item of list)
    document.querySelector('section[name=works]').innerHTML = list.join('')

}


async function init2(){
  const list = []
  let param = `&service=ios&userId=rippertnt`
  const resp = await fetch(`/v1/medias?${param}`)
  const items = await resp.json()

  console.log( items.length)

  for(const item of items){ // add filter for iphone
    //if(urlParams.get('service') == 'ios' && ["porn","hentai","sexy"].indexOf(item.nsfw) > -1 && item.conf > 0.4)
    //  continue
    console.log(item)

    if(item.type == 'mp4')
      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>
    else
      list.push(`<img class='item' src='/v1/media/${item.fileId}'></img>`)

  }

  //for(const item of list)
    document.querySelector('section[name=me]').innerHTML = list.join('')

}

//init()
//init2()

function home(){
  document.getElementById("LOGIN").style.display = 'none'
  document.getElementById("SIGNIN").style.display = 'none'

  if(_.id == 'MAIN')
    return

  const oldId = _.id
  document.getElementById(_.id).className = `animate__animated animate__fadeOut`
  document.getElementById("MAIN").style.display = 'block'
  document.getElementById("MAIN").className = `animate__animated animate__fadeIn`

  setTimeout(()=>{
    document.getElementById(oldId).style.display = 'none'
    //_.id = 'MAIN' 
  },1000)
  
  _.id = 'MAIN'
}


async function account(){
  if(_.userId != 'guest'){
    
    const isLogout = confirm(`Logout - ${_.userId}?`)

    if(isLogout){
      _.userId = 'guest'
      localStorage.setItem('email','')
      localStorage.setItem('userId','')
      document.querySelector('span[name=user]').innerText = 'guest'
    }

    return
  } else { // guest 이면 둜그인 정보λ₯Ό λ°›μ•„μ˜΄
    document.getElementById("LOGIN").style.display = 'block'
    return
  }
}

async function login(){

  if(_.userId != 'guest'){
    
    const isLogout = confirm(`Logout - ${_.userId}?`)

    if(isLogout){
      _.userId = 'guest'
      localStorage.setItem('email','')
      localStorage.setItem('userId','')
      document.querySelector('span[name=user]').innerText = 'guest'
    }

    return
  } 
  
  const userId = document.querySelector('#LOGIN input[name=id]').value
  const pass = document.querySelector('#LOGIN input[name=pass]').value
  //
  const email = userId
  const user = email.split('@')[0]

  const resp = await fetch(`/v1/account?email=${email}&userId=${userId}&pass=${pass}`)
  const ret = await resp.json()
  console.log(ret.data)
  switch(ret.data){
    case 0: // fail
      alert('Wrong email or password. Check again!')
      break;
    case 1: // pass

      localStorage.setItem('email',email)
      localStorage.setItem('userId',user)

      _.userId = userId
      document.querySelector('span[name=user]').innerText = user
      //document.querySelector('span[name=id]').innerText = userId
      document.getElementById('LOGIN').style.display = 'none'
      break;
    case 2: // new
      admission(userId,pass)
  }
  
}

async function admission(userId, pass){
  document.getElementById("LOGIN").style.display = 'none'
  document.getElementById("SIGNIN").style.display = 'block'

  if(userId)
    document.querySelector('#SIGNIN input[name=id]').value = userId

  if(pass)
    document.querySelector('#SIGNIN input[name=pass]').value = pass
}

async function siginin(){
  const id = document.querySelector('#SIGNIN input[name=id]').value
  const pass = document.querySelector('#SIGNIN input[name=pass]').value
  const pass2 = document.querySelector('#SIGNIN input[name=confirm]').value

  const token = id.split('@')
  const userId = token[0]
  const email = id

  let resp = await fetch(`/v1/account?email=${email}&userId=${userId}&pass=${pass}`)
  let ret = await resp.json()

  if(pass != pass2){
    alert('Password and confirmation is not equal!')
    return
  }
  
  resp = await fetch(`/v1/signup?email=${email}&userId=${userId}&pass=${pass}`)
  ret = await resp.json()

  localStorage.setItem('email',email)
  localStorage.setItem('userId',userId)

  _.userId = userId
  document.querySelector('span[name=user]').innerText = userId
  //document.querySelector('span[name=id]').innerText = user
  //document.querySelector('div[name=login]').style.display = 'none'
  //document.querySelector('div[name=logout]').style.display = 'block'


  document.getElementById("SIGNIN").style.display = 'none'
}





const email = localStorage.getItem('email')

if(email && email != null && email !=''){
  const user = email.split('@')[0]
  _.userId = user
  document.querySelector('span[name=user]').innerText = user

  if($.getLanguage() == 'ko')
    document.querySelector('#MAIN .chat').innerText = `${user}λ‹˜, λ‹€μ‹œ λ§Œλ‚˜μ„œ λ°˜κ°€μ›Œμš”!`
  else
    document.querySelector('#MAIN .chat').innerText = `Welcome back, ${user}!`
  /*
  document.querySelector('span[name=user]').innerText = user
  document.querySelector('span[name=id]').innerText = user
  //document.querySelector('input[name=email]').value = email

  document.querySelector('div[name=login]').style.display = 'none'
  document.querySelector('div[name=logout]').style.display = 'block'
  */
}

function logout(){

  localStorage.setItem('email','')
  localStorage.setItem('userId','')
  _.userId = 'guest'
  document.querySelector('span[name=user]').innerText = _.userId

  document.querySelector('div[name=login]').style.display = 'block'
  document.querySelector('div[name=logout]').style.display = 'none'
}

function keypress(evt){
  console.log('main_key')
  if(evt.which == 13 && !evt.shiftKey)
    search()

  
}

let upload = 0
let isVideo = 0

function camera(evt){
  console.log('main_c')
  if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia ){
      // Navigator mediaDevices not supported
      alert("Media Device not supported")
      return;
  }
// {video: {width: {exact: 512}, height: {exact: 512}}
  navigator.mediaDevices.getUserMedia({video: {width: {exact: 1024}, height: {exact: 512}}}).then(stream=>{
    document.getElementById("capture").style.display = 'none'
    document.getElementById("cam").style.display = 'block'
    const cam = document.getElementById("cam")
    cam.srcObject = stream
    console.log(cam.height, cam.width)
    //cam.play()
    isVideo = true
  }).catch(err=>{
    alert("Permission faield :", err)
  });

}

function image(evt){
  isVideo = 0
  console.log('main_i')
  document.getElementById("capture").style.display = 'block'
  document.getElementById("cam").style.display = 'none'
  const gallary = document.getElementById('gallary')
  gallary.click()
}

function remove(evt){
  document.getElementById("capture").style.display = 'block'
  document.getElementById("cam").style.display = 'none'

  isVideo = false

  //const canvas = document.getElementById('capture')
  //context.clearRect(0, 0, canvas.width, canvas.height)
  
  var img = new Image()
  img.src = '/image/import.gif'
  img.onload = function() {
    canvas = document.getElementById('capture')
    ctx = canvas.getContext("2d")
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img,0,0)
  }
    
  upload = 0
}

function setImage(url){
  var img = new Image()
  img.crossOrigin = 'Anonymous';
  img.src = url
  //img.crossOrigin = 'Anonymous';
  img.onload = function(){
    canvas = document.getElementById('capture')
    ctx = canvas.getContext("2d")
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img,0,0)

    canvas.toBlob(function(blob) {
      const form = new FormData();
      form.append('file', blob, Date.now());
      upload = form
    })

  }
}

function listen(evt){
  console.log('main_l')

  if(audio)
    audio.pause()

  $.listen()
  $.query('input[name=prompt]').className = 'listen'
}

async function processImage(event){

  //document.querySelector('aside[name=generate]').style.visibility = 'visible'
  //document.querySelector('aside[name=generate] input').value = ''
  //document.querySelector('aside[name=generate] input').focus()
  console.log('process image')
  const files = event.target.files;

  const reader = new FileReader()
  reader.readAsDataURL(files[0]);  
  reader.onload = function(e){
    var img = new Image()
    img.src = e.target.result
    img.onload = function(){
      canvas = document.getElementById('capture')
      ctx = canvas.getContext("2d")
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img,0,0)
      //const cam = document.getElementById("cam")
      //cam.poster = img
    }
  }
 
  form = new FormData()
  form.append('file', files[0])
  upload = form

  /*
  EXIF.getData(files[0], function() {
    var allMetaData = EXIF.getAllTags(this)
    console.log('exif',allMetaData)
  })
  */  
}


function getType(){
  if(voice == 'woman1')
    return 'counselor'
  else if (voice == 'man1' )
    return 'teacher'
  else 
    return 'assist'
}

function persona(v){
  voice = $.query('select[name=persona]').value
  //voice = v

  type = build(voice)

  document.getElementById('virtual').poster = `/image/${voice}.gif`

  const elem = document.querySelector('#MAIN ul[name=chats]')

  const bot = document.createElement('li')
  bot.className = 'chat user'
  bot.innerHTML = type.replace('Your','My')

  elem.appendChild(bot)
  elem.scroll({ top: elem.scrollHeight }) //, behavior: "smooth"})
}

function human(){
  if(isTTS){
    document.querySelector("#INDEX video.output").classList.add('gray')
    isTTS = 0
  } else {
    document.querySelector("#INDEX video.output").classList.remove('gray')
    isTTS = 1
  }
}

const bots =  [
  'news',    'trend',
  'weather', 'dust',
  'music',   'letter',
  'book', 'movie', 'image'
]

function checkBot(cmd){
  console.log(`checkbot [${cmd}]`)
  for(const bot of bots){
    if(cmd.indexOf(bot) > -1)
      return bot
  }

  

  return false
}



async function search(isSkip=false){
  let pos = 0
  let lang = 'en'
  
  let prompt = document.querySelector('#MAIN [name=prompt]').value + ""

  if(prompt.length < 1) // too short
    return

  let query = prompt
  let org = prompt

  const temp =  0.5 //= //document.querySelector('#MAIN input[name=m_temp]:checked').value
  //const isTTS = 1//= //document.querySelector('#MAIN input[name=m_tts]:checked').value

  document.querySelector('#MAIN [name=prompt]').value = ''

  const user = document.createElement('li')
  user.className = 'chat bot'
  user.innerHTML = prompt.replace(/\n/gi, "</br>")

  const elem = document.querySelector('#MAIN ul[name=chats]')
  elem.appendChild(user)

  const bot = document.createElement('span')
  bot.className = 'chat user'
  bot.textContent = '...'
  elem.appendChild(bot)
  elem.scroll({ top: elem.scrollHeight })//, behavior: "smooth"})

  const td = new TextDecoder() // lang auto

  const form = new FormData()
  form.append('prompt',prompt.replace(/\n/gi, ""))

   
  if(query.toLowerCase().startsWith('draw') || query.toLowerCase().startsWith('paint') ){
    bot.textContent = 'Drawing the image...'
    setImage(`${lb.getGen()}/v1/txt2photo?sentence=${query}&w=512&h=512`)
  } else if(upload == 0 && isVideo == 0){
    console.log('------------------------ chat....--------------')

    bot.textContent = 'waiting answer...'
    fetch(`/v1/chat`,{
      method : "POST",
      headers : {
        "Content-Type" : 'application/json'
      }, // prompt=${query}&temp=${temp}&lang=en`
      body : JSON.stringify({
        prompt : query.replace(/\n/gi, ""),
        history : [],//history.slice(-2),
        type,
        pos,
        org, 
        temp : temp,
        lang : 'en'
      })

    }).then(async resp=>{
      const reader = resp.body.getReader()
      const chunks = []
  
      let done, value, result
      while(!done) {
        ({value, done} = await reader.read())
        if(done){
          console.log('finish2', bot.innerHTML.replace(/\n/gi, "</br>"))
          

          bot.innerHTML = chunks.join('') //.replace(/\n/gi, "</br>")
          history.push(`${query}|${chunks.join('')}`)

          const form = new FormData()
          form.append('prompt',prompt)
          form.append('data',chunks.join(''))

          const res = await fetch(`/v1/t/text?prompt=${prompt}&model=chat&userId=${_.userId}`, {
            method: "POST", // or 'PUT'
            //headers: { "application/json" },
            body: form //JSON.stringify({ data : prompt + chunks.join('') }),
          })

          if(isTTS == 1){
            if(audio)
              audio.pause()   
            vid.src = `${lb.getGen()}/v1/txt2human?text=${bot.innerHTML.replace(/<\/br>/gi, "")}&lang=${lang}&voice=${voice}`    
          }

        }


        vid.onended = ()=>{
          vid.src = ''
        }

        vid.oncanplaythrough = ()=>{
          
        }

        //document.getElementById('virtual').src = `/v1/v/human?prompt=${bot.innerHTML.replace(/<\/br>/gi, "")}&lang=${lang}`

        
        bot.onclick = ()=>{
          if(audio)
            audio.pause()
          audio = new Audio(`${lb.getGen()}/v1/tts?text=${bot.innerHTML}&lang=${lang}&voice=main`)
          audio.play()
        } 
      

        elem.scroll({ top: elem.scrollHeight })//, behavior: "smooth"})

        break
        
        chunks.push(td.decode(value))
        //console.log(value,td.decode(value))
        //console.log(value.indexOf('\n') > -1, td.decode(value).indexOf('\n') > -1)
        bot.innerHTML = chunks.join('').replace(/\n/gi, "</br>") //.replace(/\n/gi, "</br>")
        elem.scroll({ top :9999999 }) // behavior:"smooth"
      }
      
    }).catch(e=>{
      console.error(e)
      return
    })

   } else {
    bot.textContent = 'waiting answer...'
    
    if(isVideo){
      const cam = document.getElementById("cam")
      const canvas = document.getElementById('capture')
      ctx = canvas.getContext("2d")
      //canvas.width = cam.width;
      //canvas.height = cam.height;
      console.log(cam, cam.width)
      
      ctx.drawImage(cam,0,0,512,512)

      const blob = await new Promise(resolve => canvas.toBlob(resolve))
      console.log(blob)
      const form = new FormData();
      form.append('file', blob, Date.now())
      upload = form 
    }

    upload.append('prompt',query)
    upload.append('temp',temp)
    upload.append('lang','en')

    fetch(`/v1/i/chat`,{ //?prompt=${query}&temp=${temp}&lang=en
      method: 'POST',
      body: upload
    }).then(async resp=>{
      const reader = resp.body.getReader()
      const chunks = []
  
      let done, value, result
      while(!done) {
        ({value, done} = await reader.read())

        if(done){
          if(lang == 'ko'){
            const form = new FormData()
            form.append('prompt',bot.innerHTML)
            const resp = await fetch(`/v1/t/trans?model=en2ko&userId=${_.userId}&skip=1`, {
              method: "POST",
              body: form
            })
            const result = await resp.json()
            console.log(result)     
            bot.innerHTML = result.data.replace(/\n/gi, "</br>")
          } else {
            bot.innerHTML = chunks.join('').replace(/\n/gi, "<br>")
          }

          bot.onclick = ()=>{
            if(audio)
              audio.pause()
            audio = new Audio(`${lb.getGen()}/v1/tts?text=${bot.innerHTML}&lang=${lang}&voice=${voice}`)
            audio.play()
          } 
  
          if(isTTS == 1){
            if(audio)
              audio.pause()
            document.getElementById('virtual').src = `${lb.getGen()}/v1/txt2human?text=${bot.innerHTML.replace(/<\/br>/gi, "")}&lang=${lang}&voice=${voice}` 

            //audio = new Audio(`${lb.getGen()}/v1/tts?text=${bot.innerHTML}&lang=${lang}&voice=main`)
            //audio.play()          
          }
  
          elem.scroll({ top: elem.scrollHeight })//, behavior: "smooth"})

          break
        }
        chunks.push(td.decode(value))
        console.log('chunk',td.decode(value))
        bot.innerHTML = chunks.join('').replace(/\n/gi, "</br>")
        elem.scroll({ top :9999999, behavior:"smooth"})
      }
    }).catch(e=>{
      console.error(e)
      return
    })    
   }

  setTimeout(function() {
    document.querySelector('#MAIN [name=prompt]').focus();
  }, 100);
}

setTimeout(function() {
  document.querySelector('#MAIN [name=prompt]').focus();
}, 100);

function full(){
  if (document.documentElement.requestFullscreen) {
    alert('full page')
    document.documentElement.requestFullscreen()
 } else [
    alert('not allowed')
 ]
}

function listen(){
  document.documentElement.requestFullscreen()
  $.listen()
  $.query('[name=prompt]').className = 'listen'
}

function dragOverHandler(ev) {
  console.log("File(s) in drop zone");

  // Prevent default behavior (Prevent file from being opened)
  ev.preventDefault();
}

async function dropHandler(ev) {
  ev.preventDefault()
  console.log("File(s) dropped",ev.dataTransfer.items);

  
  const file =  ev.dataTransfer.files[0]
  console.log(file)

  var img = new Image()
  img.src = URL.createObjectURL(file)
  //img.crossOrigin = 'Anonymous';
  img.onload = function(){
    canvas = document.getElementById('capture')
    ctx = canvas.getContext("2d")
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img,0,0)

    canvas.toBlob(function(blob) {
      const form = new FormData();
      form.append('file', blob, Date.now());
      upload = form
    })

  }


}

_.script['MAIN'] = {
  listening : text=>{
    $.query('[name=prompt]').value = text
  },
  listened : ()=>{
    $.query('[name=prompt]').className = ''

    if($.query('[name=prompt]').value.length > 0)
      search()
  }
}

if($.getLanguage() == 'ko')
  $.templete('/js/index.json','INDEX')

create()

document.querySelectorAll('nav button').forEach(elem=>{
  elem.addEventListener("click", ev=>{
    if(document.querySelector('nav button.clicked'))
      document.querySelector('nav button.clicked').classList.remove('clicked')
    elem.classList.add('clicked')
  })
})