-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
code.js
1444 lines (1387 loc) · 42.8 KB
/
code.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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { marked } from "https://esm.run/marked";
import { GoogleGenerativeAI } from "https://esm.run/@google/generative-ai";
const params = new URLSearchParams(window.location.search)
let API_KEY = params.get('key')
if (!API_KEY) {
API_KEY = window.localStorage.API_KEY
if (!API_KEY) {
API_KEY = prompt('Gemini API_KEY')
}
}
window.localStorage.API_KEY = API_KEY
let ytPlayer = null
async function initVideoPlayer(videoId) {
function onPlayerReady(event) {
ytPlayer = event.target;
}
function onPlayerStateChange(state) {
try {
// Disable captions completelly
ytPlayer.unloadModule("captions");
ytPlayer.unloadModule("cc");
} catch (e) { console.log(e)}
if (state.data === 1) {
setPlaying(true)
} else if (state.data === 2) {
setPlaying(false)
}
}
function onPlayerError(event) {
console.log('player error', event.data);
}
const tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
let firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubeIframeAPIReady = function() {
const ytPlayer = new YT.Player("player", {
height: "270",
width: "480",
host: 'https://www.youtube-nocookie.com',
videoId: videoId,
playerVars: {
playsinline: 1,
autoplay: 0,
loop: 0,
controls: 0,
disablekb: 0,
rel: 0,
},
events: {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange,
"onError": onPlayerError,
}
});
let iframeWindow = ytPlayer.getIframe().contentWindow;
window.addEventListener("message", function(event) {
if (event.source === iframeWindow) {
let data = JSON.parse(event.data);
if (data.event === "infoDelivery" && data.info) {
if (data.info.currentTime !== undefined) {
let time = data.info.currentTime
audioTimeUpdate(time)
}
}
}
});
}
}
let current = null
const followingAudio = true
let chapters = []
let jumped = null
let currentCaption = ['Click to play']
let transcribing = false
let worker = new Worker('scribe-worker.js', { type: 'module'})
worker.addEventListener('message', workerEvent)
function workerEvent(event) {
const message = event.data;
const type = message.type;
const data = message.data;
console.log(message)
if (type === 'update') {
transcribing = false
updateTTS(message.fulltext, data.chunks)
} else if (type === 'result') {
if (!data)
return;
updateTTS(data.text, data.chunks)
} else if (type === 'error') {
console.log('error TTS')
alert('Error' + data)
}
}
function updateTTS(text, chunks) {
console.log('updateTTS',text, chunks)
}
async function tts(videoId) {
try {
const sampling_rate = 16000;
const audioCTX = new AudioContext({ sampleRate: sampling_rate })
const response = await fetch('/audio?id=' + videoId);
const buffer = await response.arrayBuffer()
const audioData = await audioCTX.decodeAudioData(buffer)
let audio = null
if (audioData.numberOfChannels === 2) {
const SCALING_FACTOR = Math.sqrt(2)
let left = audioData.getChannelData(0)
let right = audioData.getChannelData(1)
audio = new Float32Array(left.length)
for (let i = 0; i < audioData.length; ++i) {
audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2
}
} else {
// If the audio is not stereo, we can just use the first channel:
audio = audioData.getChannelData(0)
}
worker.postMessage({ audio, type: 'speech-to-text' })
} catch (e) {
console.error('error tts',e);
}
}
window.tts = tts
function endOfSentence2(text) {
return text.endsWith('. ') || text.endsWith('? ') || text.endsWith('! ')
}
function findSentence(span) {
let elem = span || punctuated.querySelector('.highlighted')
if (!elem)
return ''
let text = ''
let prev = elem
elem = elem.previousElementSibling
while (elem && elem.tagName === 'SPAN') {
if (endOfSentence2(elem.textContent))
break
prev = elem
elem = elem.previousElementSibling
}
elem = prev
while (elem) {
text += elem.textContent
if (endOfSentence2(elem.textContent))
break
elem = elem.nextElementSibling
}
return text
}
let resetCaptions = false
let userJumps = false
function updateTimeCaption(timeSeconds) {
currentTime.textContent = msToTime(parseInt(timeSeconds * 1000)) + '/' + msToTime(videoDuration * 1000)
}
function audioTimeUpdate(timeSeconds) {
updateTimeCaption(timeSeconds)
let time = timeSeconds * 1000
timeline.value = time
let ps = punctuated.querySelectorAll('.p')
let last = -1
let lastHighlightedWord = null
let lastHighlightedParagraph = null
for (let i = 0; i < ps.length; i++) {
let p = ps[i]
if (p.start !== -1 && p.start <= time)
last = i
let words = p.querySelectorAll('span')
for (let w of words) {
if (!w.start)
continue
//const delta = 400
//const highlight = w.start >= (time - delta) && w.end <= time + delta * 3
const delta = 1000
const highlight = w.start >= (time - delta) && w.end <= time + delta
//let c = []
if (highlight && !w.classList.contains('highlighted')) {
w.classList.add('highlighted')
lastHighlightedWord = w
lastHighlightedParagraph = p
//console.log('highlight',w)
//c.push(w.textContent)
}
if (!highlight && w.classList.contains('highlighted'))
w.classList.remove('highlighted')
}
}
currentCaption = [...punctuated.querySelectorAll('.highlighted')].map(a => a.textContent)
if (currentCaption.length === 0 && !isPlaying())
currentCaption = ['Click to Play']
current = null
for (let i = 0; i < ps.length; i++) {
let p = ps[i]
if (i !== last) {
if (p.classList.contains('livep')) {
p.classList.remove('livep')
}
} else {
current = p
if (!p.classList.contains('livep')) {
p.classList.add('livep')
if (followingAudio) {
let y = p.getBoundingClientRect().top + window.pageYOffset - player.offsetHeight
if (jumped) {
y = jumped
jumped = null
}
if (userJumps) {
userJumps = false
window.scrollTo({left: 0, top: y, behavior: 'smooth'})
}
}
}
}
}
for (let c of chapters) {
c.currentChapter = false
}
for (let i = chapters.length - 1; i >= 0; --i) {
if (chapters[i].start <= time) {
chapters[i].currentChapter = true
break
}
}
}
function setPlaying(p) {
//console.log('setPlaying',p)
}
function getGenerativeModel(API_KEY, params) {
const genAI = new GoogleGenerativeAI(API_KEY);
return genAI.getGenerativeModel(params);
}
function chunkText(text, maxWords = 4000) {
const words = text.split(/\s+/); // Split the text into words
const chunks = [];
let currentChunk = [];
for (let i = 0; i < words.length; i++) {
currentChunk.push(words[i]);
if (currentChunk.length >= maxWords || i === words.length - 1) {
chunks.push(currentChunk.join(" "));
currentChunk = [];
}
}
return chunks;
}
const modelName = 'gemini-1.5-flash-8b'
//const modelName = 'gemini-1.5-flash-8b-latest'
const generationConfig = {
candidateCount: 1,
//stopSequences: ['x'],
//maxOutputTokens: 2000000,
temperature: 1.0,
}
const model = await getGenerativeModel(API_KEY, { model: modelName });
window.model = model
async function ytsr(q) {
if (!q)
return {}
let trimmed = q.trim()
if (!(trimmed.length > 0))
return {}
try {
let response = await fetchData('https://vercel-scribe.vercel.app/api/hello?url=' + encodeURIComponent('https://www.youtube.com/search?q=' + trimmed), true)
console.log('response=',response)
let html = response.data
let preamble = "var ytInitialData = {"
let idx1 = html.indexOf(preamble)
let sub = html.substring(idx1)
let idx2 = sub.indexOf("};")
let ytInitialData = sub.substring(0,idx2+1)
let jsonString = ytInitialData.substring(preamble.length-1)
let json = JSON.parse(jsonString)
let res = json.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer.contents
let results = []
for (let r of res) {
if (!(r.itemSectionRenderer && r.itemSectionRenderer.contents))
continue
let items = r.itemSectionRenderer.contents
for (let i of items) {
if (i.videoRenderer && i.videoRenderer.publishedTimeText) {
let r = i.videoRenderer
let obj = {id: r.videoId, name: r.title.runs[0].text, duration: r.lengthText.simpleText, publishedTimeText: r.publishedTimeText.simpleText}
results.push(obj)
}
}
}
return { items: results }
} catch (e) {
console.log('setSearch error',e)
return {}
}
}
async function search(q) {
let json = await ytsr(q)
if (json.error)
items.innerHTML = 'Error:' + json.error
else if (json.items) {
items.innerHTML = ''
for (let item of json.items) {
let d = document.createElement('div')
d.className = 'r'
d.innerHTML = `<a href="?id=${item.id}"><img src="https://img.youtube.com/vi/${item.id}/mqdefault.jpg"></a><div><a href="?id=${item.id}">${item.name || item.title}</a><div>${item.duration} - ${item.publishedTimeText || item.published}</div></div><br>`
items.appendChild(d)
}
}
}
const languages = {
ar: "Arabic",
bn: "Bengali",
bg: "Bulgarian",
zh: "Chinese",
hr: "Croatian",
cs: "Czech",
da: "Danish",
nl: "Dutch",
en: "English",
et: "Estonian",
fi: "Finnish",
fr: "French",
de: "German",
el: "Greek",
iw: "Hebrew",
hi: "Hindi",
hu: "Hungarian",
id: "Indonesian",
it: "Italian",
ja: "Japanese",
ko: "Korean",
lv: "Latvian",
lt: "Lithuanian",
no: "Norwegian",
pl: "Polish",
pt: "Portuguese",
ro: "Romanian",
ru: "Russian",
sr: "Serbian",
sk: "Slovak",
sl: "Slovenian",
es: "Spanish",
sw: "Swahili",
sv: "Swedish",
th: "Thai",
tr: "Turkish",
uk: "Ukrainian",
vi: "Vietnamese"
};
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let outputTokens = 0
let inputTokens = 0
let totalTokens = 0
const inputPrice = 0.0375 // 1 million tokens
const outputPrice = 0.15 // 1 million tokens
const simulatedUsers = 1
function computePrice(token, pricePerMillion) {
return token * pricePerMillion / 1000000 * simulatedUsers
}
function formatPrice(price) {
return price.toLocaleString('en-US',{minimumFractionDigits: 2, maximumFractionDigits: 5, style: "currency", currency: "USD"})
}
async function getModelAnswer(prompt, maxretry = 4) {
for (let i=0; i < maxretry; i++) {
try {
let res = await model.generateContent([prompt])
inputTokens += res.response.usageMetadata.promptTokenCount
outputTokens += res.response.usageMetadata.candidatesTokenCount
totalTokens += res.response.usageMetadata.totalTokenCount
const priceInput = computePrice(inputTokens, inputPrice)
const priceOutput = computePrice(outputTokens, outputPrice)
const priceTotal = priceInput + priceOutput
usageDiv.textContent = `for ${simulatedUsers.toLocaleString()} users: ${inputTokens} ${formatPrice(priceInput)} ${outputTokens} ${formatPrice(priceOutput)} ${totalTokens} ${formatPrice(priceTotal)}`
return res
} catch (error) {
console.log('error getting model, waiting for 2 seconds',error)
await timeout(2000)
}
}
}
async function getBestPassages(text) {
let res = await getModelAnswer('Please list, one per line without extra characters, the best segments in this transcript: ' + text)
let passages = res.response.text().split('\n')
return passages
}
function languageName(lang) {
let name = languages[lang]
console.error('************** languageName',lang, name)
return name ?? 'English'
}
const chunkSize = 512 // longer context makes the AI hallucinate more
async function punctuateText(c, vocab = '', lang = 'en', p = null) {
const prompt = `
- fix the grammar and typos of the given video text transcript
- do not rephrase: keep the original wording but fix errors
- write in the ${languageName(lang)} language
- please add paragraphs where appropriate
- do not add paragraphs numbers
- use this list of words as context to help you fix typos: """${vocab}""""
- answer with plain text only
Here is the video text transcript to fix:
"""${c}"""`
let finalPrompt = p ? p + c : prompt
if (p)
console.log('prompt=',p,c)
let res = await getModelAnswer(finalPrompt)
return new Promise((a,r) => {
let text = res.response.text()
if (text.indexOf(lang) === 0)
text = text.substring(lang.length)
a(text)
})
}
async function mergeSentences(a, b, vocab, languageCode = 'en') {
let res = await punctuateText(clean(a) + ' ' + clean(b), vocab, languageCode, `please fix this sentence, without paragraphrasing, write in ${languageName(languageCode)}: `)
res = res.replace(/\s+/g,' ')
console.log('merge=', res)
return res
}
function findChunkEnd(a) {
let sa = a.split(/\. /)
let s1 = sa.pop()
let start = a.substring(0, a.length - s1.length)
return {paragraph: start, end: s1}
}
function findChunkStart(b) {
let sb = b.split(/\. /)
let s2 = sb.shift()
let end = b.substring(s2.length)
return {paragraph: end, start: s2}
}
function clean(a) {
return a.toLowerCase().replace(/[^\w]/g, ' ')
}
function getWords(text) {
let paragraphs = text.split('\n')
let res = []
for (let p of paragraphs) {
// modern-day startups b1cicJ3OTvg
let words = p.split(/[\s-]+/).map(a => new Object({o: a, w: a.trim().toLowerCase().replace(/\W+/g,'')}))
//words = words.filter(w => w.o > '')
if (words.length > 0) {
words[0].p = true
}
res = res.concat(words)
}
//console.log(res)
return res
}
function prepareWords(chunks) {
let res = []
for (let c of chunks) {
let len = c.text.length
let start = c.start
let end = c.start + c.dur
let words = getWords(c.original)
let dur = end - start
if (words.length > 0) {
for (let w of words) {
const durWord = w.w.length * dur / len
let s = start
let e = Math.min(end,start + durWord)
start = Math.min(end,start+durWord)
s = parseInt(s)
e = parseInt(e)
let obj = {w:w.w,o:w.o,s,e}
res.push(obj)
}
}
}
return res
}
function testDiff(wordTimes = [], punctuated = '') {
let onea = wordTimes.map(item => item.w)
let one = onea.join('\n')
let othera = getWords(punctuated)
let other = othera.map(w => w.w).join('\n') + '\n'
let map = []
let diff = Diff.diffLines(one, other);
let source = 0
let removed = 0
let added = 0
for (let part of diff) {
const n = part.count
for (let i = 0; i < n; i++) {
if (part.removed) {
removed++
source++
} else if (part.added) {
added++
map.push(-1)
} else {
map.push(source)
source++
}
}
}
let idx = 0
for (let i of map) {
if (i !== -1) {
othera[idx].s = wordTimes[i].s
othera[idx].e = wordTimes[i].e
}
idx++
}
let prevStart = 0
let i = 0
while (i < othera.length) {
let prevEnd = 0
while (i < othera.length && othera[i].e !== undefined) {
prevEnd = othera[i].e
i++
}
while (i < othera.length && othera[i].s === undefined) {
//console.log('no start',othera[i].w)
othera[i].s = prevEnd
prevEnd += 200
othera[i].e = prevEnd
i++
}
}
othera.forEach(o => delete o.w)
return othera
}
let shownWords = {}
let startTime = 0
function absorb(evt) {
if (!evt)
return
evt.stopPropagation()
evt.preventDefault()
}
function insertPlaceholderChapter(p) {
let header = document.createElement('p')
header.start = p.start
header.className = 'header generating'
if (p.classList.contains('notpro'))
header.classList.add('notpro')
header.innerHTML = '<i class="spin spinsmall fa-solid fa-circle-notch"></i>'
p.chapter = 'generating'
p.parentElement.insertBefore(header,p)
}
function makeChapterContent(c) {
if (!c || !c.text)
return ''
let text = c.text.replace(/(\(?(?:https?|ftp):\/\/[\n\S]+\)?)/g, '').trim()
return `<div class="headername">${text}</div>`
}
function insertChapter(p,c) {
c.taken = true
let header = document.createElement('p')
header.className = 'header'
if (p.classList.contains('notpro'))
header.classList.add('notpro')
header.start = c.start
header.innerHTML = makeChapterContent(c)
p.chapter = c
p.header = header
//p.innerHTML = '<h4>' + c.text + '</h4>' + p.innerHTML
p.parentElement.insertBefore(header,p)
}
function endOfSentence(w) {
const ends = ['.','?','!']
if (!(w > ''))
return false
let lastChar = w[w.length-1]
return ends.indexOf(lastChar) !== -1
//return w > '' && w[w.length-1] === '.'
}
function msToTime(duration) {
if (!duration)
return '0:00'
let milliseconds = Math.floor((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
seconds = (seconds < 10) ? "0" + seconds : seconds;
if (hours > 0) {
minutes = (minutes < 10) ? "0" + minutes : minutes;
return hours + ":" + minutes + ":" + seconds
}
return minutes + ":" + seconds
}
function buildWords(words) {
let r = punctuated
let p = null
let end = false
for (let w of words) {
if (w.o === '.')
continue
const key = w.o + '-' + w.s
if (end) {
for (let c of chapters) {
if (!c.taken && c.start <= w.s + 1000 && !c.taken) {
w.p = true
}
}
}
end = endOfSentence(w.o)
if (shownWords[key]) {
continue;
}
shownWords[key] = true
if (w.p && w.o > '') {
p = document.createElement('p')
p.className = 'p'
p.start = w.s
let ts = document.createElement('div')
ts.className = 'ts'
ts.start = w.s
ts.textContent = msToTime(p.start)
ts.addEventListener('click',() => {
play(ts.start)
})
p.appendChild(ts)
r.appendChild(p)
for (let c of chapters) {
if (c.start <= w.s + 1000 && !c.taken) {
insertChapter(p,c)
}
}
}
if (w.o === '')
continue
let span = document.createElement('span')
span.textContent = w.o + ' '
/*if (w.o.indexOf('`') !== -1) {
span.innerHTML = '<code>' + w.o.replaceAll('`','') + '</code> '
}*/
if (w.s !== undefined) {
span.start = w.s
span.end = w.e
span.addEventListener('click',(evt) => {
absorb(evt)
if (span.classList.contains('highlighted'))
realplayer.pause()
else
play(span.start)
//let res = findSentence(evt.target)
//console.log(res)
})
/*span.addEventListener('mousemove',(evt) => {
absorb(evt)
if (evt.buttons && !span.classList.contains('yawas'))
span.classList.add('yawas')
})*/
}
if (p) {
p.appendChild(span)
}
}
if (!chapters || chapters.length === 0) {
let paragraphs = r.querySelectorAll('.p')
let idx = 0
for (let p of paragraphs) {
if (idx % 3 === 0 && !p.chapter) {
insertPlaceholderChapter(p)
}
idx += 1
}
}
updateHighlights()
}
function isPlaying() {
return ytPlayer? ytPlayer.getPlayerState() === 1 : !realplayer.paused
}
let lastStart = null
function play(start) {
console.log('play',start)
const playing = isPlaying()
if (!playing || start !== lastStart) {
ytPlayer ? ytPlayer.seekTo(start / 1000, /* allowSeekAhead */ true) : realplayer.currentTime = start / 1000
ytPlayer ? ytPlayer.playVideo() : realplayer.play()
} else {
ytPlayer ? ytPlayer.pauseVideo() : realplayer.pause()
}
if (!ytPlayer && isPlaying())
realplayer.muted = false
lastStart = start
}
function keepCharacters(t) {
return t.trim().toLowerCase().replace(/\W+/g,'')
}
function createChunks(chunks) {
chunks.forEach((c,idx) => {
let o = c.text
c.original = o
c.taken = false
c.text = keepCharacters(o)
c.end = c.start + c.dur
if (idx > 0 && c.start < chunks[idx-1].end) {
chunks[idx-1].end = c.start
chunks[idx-1].dur = chunks[idx-1].end - chunks[idx-1].start
}
})
return chunks.filter(c => c.text.length > 0)
}
function timeCodeToMs(time) {
const items = time.split(":");
return (
items.reduceRight(
(prev, curr, i, arr) =>
prev + parseInt(curr) * 60 ** (arr.length - 1 - i),
0
) * 1000
);
}
function computeChapters(description) {
if (!description)
return []
let res = []
let lines = description.split('\n')
const reg = new RegExp(/\(?((\d\d?:)?\d\d?:\d\d)\)? ?(-(\d\d?:)?\d\d?:\d\d)?/)
let idx = 0
for (let l of lines) {
let m = l.match(reg)
if (m) {
const lineNumber = idx
let ts = m[1].trim()
let start = timeCodeToMs(ts)
let text = l.replace(reg,'') // https://www.youtube.com/watch?v=SOxYgUIVq6g captions at the end
if (text.indexOf('- ') === 0)
text = text.substring(2)
text = text.replace(/[_\-:–]+/g,'').trim()
if (text.length === 0 && lineNumber < lines.length -1 && !lines[lineNumber+1].match(reg))
text = lines[lineNumber+1].trim()
res.push({text,start})
}
idx++
}
let uniques = []
for (let r of res) {
if (uniques.map(u => u.start).indexOf(r.start) === -1) {
uniques.push(r)
} else {
}
}
if (uniques.length >= 2)
return uniques
else
return []
}
function parseYTChapters(chapters) {
if (!chapters)
return []
let res = []
for (let c of chapters) {
let start = c.start ?? c.start_time * 1000
let text = c.title ?? c.text
res.push({text,start})
}
return res
}
async function convertAudioFromUrlToBase64(url) {
try {
const response = await fetch(url);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const res = reader.result
const prefix = ';base64,'
const idx = res.indexOf(prefix)
resolve(res.substring(idx + prefix.length));
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (error) {
console.error('Error fetching audio or converting to base64:', error);
}
}
async function transcribe() {
console.log('transcribe')
const prompt = "Generate audio diarization for this interview, and output a simple json format with keys: 'speaker', 'transcription', 'start', 'end'. If you can infer the speaker, please do. If not, use speaker A, speaker B, etc."
const b64 = await convertAudioFromUrlToBase64('/static/cached/5.m4a')
const result = await model.generateContent([
{
inlineData: {
mimeType: "audio/mp3",
data: b64
}
},
{ text: prompt },
]);
// Print the response.
let res = result.response.text()
console.log(res)
let s = res.indexOf('[')
let e = res.indexOf(']')
//console.log(res)
let payload = JSON.parse(res.substring(s,e+1))
console.log(payload)
}
async function chapterize(transcript) {
// examples from https://console.cloud.google.com/vertex-ai/publishers/google/model-garden/gemini-1.5-flash-001?hl=en
const chapterPrompt = `Chapterize the video content by grouping the video content into chapters and providing a name for each chapter with its timecode. Please only capture key events and highlights. If you are not sure about any info, please do not make it up. Return the result in the JSON format with keys 'chapterName' and 'timecode'. Here is the video content: `
//const result = await model.generateContent([`${chapterPrompt} ${transcript}`])
const result = await getModelAnswer(`${chapterPrompt} ${transcript}`)
let json = result.response.text()
console.log(json)
}
async function createVocabulary(videoId, description = '', languageCode = 'en') {
const key = languageCode + '-vocab-' + videoId
const prevVocab = await localforage.getItem(key)
if (prevVocab)
return prevVocab
if (!description || description.trim().length === 0)
return ''
//let res = await model.generateContent([`Return important words including names from this description and return as a simple list separated by commas: ${description}`])
let res = await getModelAnswer(`Return important words including names from this description and return as a simple list separated by commas: ${description}`)
let vocab = res.response.text().replace(/\s+/g,' ')
localforage.setItem(key, vocab)
return vocab
}
let ctx = canvas.getContext('2d')
let highlights = []
function addHighlight(evt) {
absorb(evt)
let s = window.getSelection().toString().trim()
if (s.length === 0) {
alert('Select the text you wish to highlight (expect paragraphs)')
return
}
let selection = highlightSelection()
if (selection) {
window.getSelection().removeAllRanges()
highlights.push(selection)
updateHighlights()
}
}
function updateHighlights() {
let r = punctuated
let paragraphs = r.querySelectorAll('p')
for (let h of highlights) {
if (h.start === null || h.end === null || h.start === undefined || h.end === undefined)
continue
let start = h.start
let end = h.end
start *= 100
end *= 100
for (let p of paragraphs) {
let spans = p.querySelectorAll('span')
let added = []
for (let s of spans) {
if (s.start >= start && s.end <= end) {
s.classList.add('yawas')
added.push(s)
}
}
}
}
}
canvas.onclick = () => {
realplayer.paused ? realplayer.play() : realplayer.pause()
if (isPlaying())
realplayer.muted = false
}
function highlightSelection() {
if (window.getSelection().rangeCount < 1)
return null
let range = window.getSelection().getRangeAt(0)
if (range) {
if (range.startContainer.parentNode.start === undefined)
return null
if (range.endContainer.parentNode.end === undefined)
return null
let start = Math.floor(range.startContainer.parentNode.start / 100)
let end = Math.round(range.endContainer.parentNode.end / 100)
if (end * 100 < range.endContainer.parentNode.end)
end += 1
return {start,end}
}
return null
}
// use font shadow like https://x.com/altryne/status/1848188194690408680?s=43&t=nMguAgZPu0YXUmgaqsct3w
function drawStrokedText(ctx, text, x, y, fill = 'yellow', baseline = 'bottom', blur = null)
{
let w = ctx.measureText(text).width
ctx.textBaseline = baseline
if (blur) {
ctx.save()
ctx.shadowBlur = blur.blur
ctx.shadowColor = blur.color
ctx.shadowOffsetX = blur.x
ctx.shadowOffsetX = blur.y
}
ctx.strokeStyle = outlinecolorpicker.value
ctx.lineWidth = 8;
ctx.lineJoin = "round";
ctx.miterLimit = 2;
ctx.strokeText(text, x, y);
ctx.fillStyle = fill
ctx.fillText(text, x, y);
//ctx.restore();
if (blur) {
ctx.restore()
}
}
function wrapText(ctx, text, x, maxWidth, maxHeight, lineHeight) {
if (!(text > ''))
return
let words = text.split(' ');
let line = '';
let lineWidth = 0;
//let y = 0
ctx.textBaseline = 'bottom'
let lines = []
//let w = 0
for(let n = 0; n < words.length; n++) {
let testLine = line + words[n] + ' ';
let w = ctx.measureText(testLine).width;
if (w > maxWidth) {
lines.push(line.trim())
//ctx.fillText(line, x, y);
line = words[n] + ' ';
lineWidth = ctx.measureText(line).width;
//y -= lineHeight;
} else {
line = testLine;
lineWidth = w;
}
}
lines.push(line.trim())
let y = maxHeight
//let x = 0
let w = 0
for (let line of lines.reverse()) {
w = Math.max(w, ctx.measureText(line).width)
//drawStrokedText(ctx, line, (maxWidth - w)/2, y)
y -= lineHeight
}
ctx.fillStyle = `rgba(0,0,0,${opacity.value/100})`
const pad = 32
const padv = 16
const corner = 18
roundRect(ctx,x + (maxWidth-w)/2-pad,y-padv,w+2*pad,maxHeight-y+2*padv, corner)
ctx.fillStyle = colorpicker.value
y = maxHeight
for (let line of lines.reverse()) {
const w = ctx.measureText(line).width
drawStrokedText(ctx, line, x + (maxWidth - w)/2, y, colorpicker.value)
//ctx.fillText(line,x + (maxWidth - w)/2, y)
y -= lineHeight
}
}
function roundRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
//ctx.stroke();