-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcode.js
1650 lines (1548 loc) · 54 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"
import { OpenAI} from "https://cdn.jsdelivr.net/npm/[email protected]/+esm"
const geminiModels = ['gemini-1.5-flash-8b']
const geminiModel = geminiModels[0]
const groqModels = ['llama-3.1-8b-instant']
const deepInfraModels = ['meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo']
const API_KEY = window.localStorage.API_KEY
const jsonGenerationConfig = {
temperature: 0,
"response_mime_type": "application/json",
}
const model = await getGenerativeModel(API_KEY, { model: geminiModel, generationConfig: { temperature: 0.0 } });
const jsonModel = await getGenerativeModel(API_KEY, { model: geminiModel, generationConfig: jsonGenerationConfig });
const GROQ_API_KEY = window.localStorage.GROQ_API_KEY
let openai = null
const DEEP_INFRA_API_KEY = window.localStorage.DEEP_INFRA_API_KEY
if (DEEP_INFRA_API_KEY) {
openai = new OpenAI({
apiKey: DEEP_INFRA_API_KEY,
baseURL: 'https://api.deepinfra.com/v1/openai',
dangerouslyAllowBrowser: true,
});
}
const params = new URLSearchParams(window.location.search)
let currentProvider = params.get('model') || geminiModel
let languageCode = params.get('language')// || 'en'
const followingAudio = true
const chapterDelta = 1000
let chapters = []
let jumped = null
let userJumps = false
let videoId = params.get('id') || params.get('v')
let highlights = []
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: 1,
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)
}
}
}
});
}
}
function endOfSentence2(text) {
return text.endsWith('. ') || text.endsWith('? ') || text.endsWith('! ')
}
function audioTimeUpdate(timeSeconds) {
let time = timeSeconds * 1000
let ps = document.body.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 = 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
}
if (!highlight && w.classList.contains('highlighted'))
w.classList.remove('highlighted')
}
}
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 {
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;
}
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)
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 {}
}
}
function spin(text = '') {
return `<div class="simplerow"><i class="spinner fa-solid fa-circle-notch"></i> ${text}</div>`
}
function displayItems(jsonItems) {
items.innerHTML = ''
for (let item of jsonItems) {
let d = document.createElement('div')
d.className = 'r'
let duration = item.duration
if (typeof duration === 'number') {
duration = msToTime(duration * 1000)
}
d.innerHTML = `<a href="./?id=${item.id || item.videoId}"><img src="https://img.youtube.com/vi/${item.id || item.videoId}/mqdefault.jpg"></a><div><a href="?id=${item.id || item.videoId}">${item.name || item.title}</a><div>${duration} - ${item.publishedTimeText || item.published || new Date(item.publishDate).toLocaleDateString()}</div></div><br>`
items.appendChild(d)
}
items.style.display = 'flex'
}
async function search(q, redirect = true) {
if (redirect)
window.location.href = './?q=' + encodeURIComponent(q)
items.style.display = 'flex'
items.innerHTML = spin('Searching')
let json = await ytsr(q)
if (json.error)
items.innerHTML = 'Error: ' + json.error
else if (json.items) {
displayItems(json.items)
}
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let apiCalls = 0
let outputTokens = 0
let inputTokens = 0
let totalTokens = 0
let totalPrice = 0
const llmProviders = {
'gemini-1.5-flash-8b': {
inputPrice: 0.0375,
outputPrice: 0.15,
},
'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo': {
inputPrice: 0.05,
outputPrice: 0.05,
},
'llama-3.1-8b-instant': {
inputPrice: 0.05,
outputPrice: 0.08,
}/*,
'llama-3.2-1b-preview': {
inputPrice: 0.04,
outputPrice: 0.04,
},
'llama-3.2-3b-preview': {
inputPrice: 0.06,
outputPrice: 0.06,
}*/
}
function computePrice(token, pricePerMillion) {
return token * pricePerMillion / 1000000
}
function formatPrice(price) {
return price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 5, style: "currency", currency: "USD" })
}
async function llmChapters(text) {
let paragraphs = text.split('\n\n')
let items = paragraphs.map((p,idx) => idx + '=' + p.trim())
let res = await getJSONAnswer('Given the list of numbered paragraphs, group paragraphs into meaningful chapters and return a list with chapter_name and first_paragraph_number of that chapter. Chapters should always contain several paragraphs. Here is the list of numbered paragraphs: ' + items)
res = JSON.parse(res)
let elements = [...punctuatedDiv.querySelectorAll('.p')]
for (let item of res) {
const n = +item.first_paragraph_number
const name = item.chapter_name
const header = document.createElement('div')
header.className = 'header llm'
header.textContent = name
elements[n].parentElement.insertBefore(header, elements[n])
}
}
async function getChapters(chunks, languageCode = 'en') {
let lines = chunks.map(c => parseInt(c.start) + ": " + c.text.trim())
let transcript = lines.join('\n')
const chaptersPrompt = `
- Please break down the following transcript into topic changes, providing a concise title for each section.
- Make sure the sections are not too short.
- Please write the titles in ${languageName(json, languageCode)}.
- Please return the result as a JSON array with 'title', 'start'.
Here is the text:
${transcript}`
const result = await getJSONAnswer(chaptersPrompt)
if (!result)
return []
const chapters = JSON.parse(result)
const finalChapters = chapters.map(c => new Object({text: c.title, start: parseInt(c.start)})).sort((a,b) => a.start - b.start)
return finalChapters
}
window.llmChapters = () => llmChapters(json.en.punctuatedText)
window.getChapters = () => getChapters(json.en.chunks)
function updateEstimatedPrice( inputTokens, outputTokens, totalTokens) {
totalTokensSpan.textContent = totalTokens
const data = llmProviders[currentProvider]
if (!data) {
return
}
const priceInput = computePrice(inputTokens, data.inputPrice)
const priceOutput = computePrice(outputTokens, data.outputPrice)
const priceTotal = (priceInput + priceOutput)
costSpan.textContent = `${formatPrice(priceTotal)}`
}
const SYSTEM_PROMPT = 'You are a helpful assistant and only return the result without extra explanation.'
async function getDeepInfra(prompt, systemPrompt = SYSTEM_PROMPT) {
const completion = await openai.chat.completions.create({
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: prompt }
],
model: currentProvider,
stream: false,
});
let text = completion.choices[0].message.content
inputTokens += completion.usage.prompt_tokens
outputTokens += completion.usage.completion_tokens
totalTokens += completion.usage.total_tokens
totalPrice += completion.usage.estimated_cost
updateEstimatedPrice(inputTokens, outputTokens, totalTokens, totalPrice)
return text
}
async function getGroq(prompt, systemPrompt = SYSTEM_PROMPT) {
const obj = {
"messages": [
{
"role": "system",
"content": systemPrompt
},
{
"role": "user",
"content": prompt
}
],
"model": currentProvider,
"temperature": 0,
}
try {
let result = await fetch("https://api.groq.com/openai/v1/chat/completions",{
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + GROQ_API_KEY,
},
'body': JSON.stringify(obj)
});
let res = await result.json();
inputTokens += res.usage.prompt_tokens
outputTokens += res.usage.completion_tokens
totalTokens += res.usage.total_tokens
updateEstimatedPrice(inputTokens, outputTokens, totalTokens)
let text = res.choices[0].message.content
return text
} catch (e) {
console.log('error groq',e)
return null
}
}
window.getGroq = getGroq
async function getJSONAnswer(prompt) {
apiCalls++
apiCallsSpan.textContent = apiCalls
const res = await jsonModel.generateContent([prompt])
inputTokens += res.response.usageMetadata.promptTokenCount
outputTokens += res.response.usageMetadata.candidatesTokenCount
totalTokens += res.response.usageMetadata.totalTokenCount
updateEstimatedPrice(inputTokens, outputTokens, totalTokens)
return res.response.text()
}
async function getModelAnswer(prompt, maxretry = 4, retryDelayMs = 4000) {
if (!API_KEY) {
summary.innerHTML = '<p>Please set your API KEY on the <a href="./">home page</a><p>'
return null
}
for (let i = 0; i < maxretry; i++) {
apiCalls++
apiCallsSpan.textContent = apiCalls
try {
let res = null
if (deepInfraModels.indexOf(currentProvider) !== -1) {
return await getDeepInfra(prompt)
} else if (groqModels.indexOf(currentProvider) !== -1) {
return await getGroq(prompt)
} else {
res = await model.generateContent([prompt])
inputTokens += res.response.usageMetadata.promptTokenCount
outputTokens += res.response.usageMetadata.candidatesTokenCount
totalTokens += res.response.usageMetadata.totalTokenCount
updateEstimatedPrice(inputTokens, outputTokens, totalTokens)
return res.response.text()
}
} catch (error) {
console.log(error)
if (error.message && error.message.indexOf('API_KEY_INVALID') !== -1) {
console.log('error: API_KEY_INVALID')
return null
}
await timeout(retryDelayMs)
}
}
}
window.getModelAnswer = getModelAnswer
function languageName(json, lang) {
return json.translationLanguages[lang] || 'English'
}
const chunkSize = 512 // longer context makes the AI hallucinate more
//const chunkSize = 1200 // longer context makes the AI hallucinate more
async function punctuateText(json, c, vocab = '', lang = 'en', p = null) {
const oldprompt = `- 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(json, lang)} language
- 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}"""`
const prompt = `You are an AI assistant tasked with cleaning up raw ASR transcripts. Your goal is to add correct punctuation and capitalization while ensuring that you do not introduce or remove any information from the original text.
Guidelines:
Preserve Content: Do not add new words or alter the meaning of any phrases.
Punctuation: Insert periods, commas, and other punctuation marks where appropriate to improve readability.
Capitalization: Apply correct capitalization, especially at the beginning of sentences and for proper nouns.
Grammar: Correct minor grammatical issues if they clearly align with the spoken context, but avoid rephrasing.
No Hallucinations: If a word or phrase is unclear, retain the original text or indicate uncertainty rather than guessing.
Write in the ${languageName(json, lang)} language
Add paragraphs where appropriate, especially if a question is followed by an answer
Do not add paragraphs numbers
Use this list of words as context to help you fix typos: ${vocab}
Here is the ASR transcript to clean up:
${c}
`
let finalPrompt = p ? p + c : prompt
let res = await getModelAnswer(finalPrompt)
return new Promise((a, r) => {
if (!res)
a('')
let text = res
if (text.indexOf(lang) === 0)
text = text.substring(lang.length)
a(text)
})
}
async function mergeSentences(json, a, b, vocab, languageCode = 'en') {
const cleanA = clean(a)
const cleanB = clean(b)
let res = await punctuateText(json, cleanA + ' ' + cleanB, vocab, languageCode, `please fix this sentence, without paragraphrasing, write in ${languageName(json, languageCode)}: `)
res = res.replace(/\s+/g, ' ')
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, ' ').replace(/\s+/g,' ').trim()
}
function getWords(text) {
let paragraphs = text.split('\n').filter(p => p > '')
let res = []
for (let p of paragraphs) {
//let words = p.split(/[\s-]+/).map(a => new Object({ o: a, w: a.trim().toLowerCase().replace(/\W+/g, '') }))
let words = p.split(/[\s-]+/).map(a => new Object({ o: a, w: keepCharacters(a) }))
if (words.length > 0 && words[0].o > '') {
words[0].p = true
}
res = res.concat(words.filter(w => w.w > ''))
}
return res
}
function prepareWords(chunks) {
let res = []
for (let c of chunks) {
let len = c.cleanText.length
let start = c.start
let end = c.start + c.dur
let words = getWords(c.text)
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')
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++
}
}
}
console.log('added=',added, 'removed=', removed)
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 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) {
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 ''
const text = c.text.replace(/https?:\/\/(?:www\.)?([^\/?#]+).*/g, '$1');
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 numberedItem(w) {
if (w === '*')
return true
return w.match(/^\d\./g) !== null
}
function endOfSentence(w) {
const ends = ['.', '?', '!']
if (!(w > ''))
return false
let lastChar = w[w.length - 1]
return ends.indexOf(lastChar) !== -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, r = punctuatedDiv) {
chapters.forEach(c => c.taken = false)
let p = null
let end = false
//let inBold = false
let inCode = false
for (let w of words) {
if (w.o === '.')
continue
if (end) {
for (let c of chapters) {
if (!c.taken && c.start <= (w.s + chapterDelta) && !c.taken) {
w.p = true
}
}
}
end = endOfSentence(w.o)
if (w.p && w.o > '') {
if (!inCode) {
p = document.createElement('p')
p.className = 'p'
p.start = w.s
if (w.p && !numberedItem(w.o)) {
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)
} else {
p.classList.add('plist')
w.o = '- '
}
r.appendChild(p)
for (let c of chapters) {
if (c.start <= (w.s + chapterDelta) && !c.taken) {
insertChapter(p, c)
}
}
}
}
if (w.o === '')
continue
let span = document.createElement('span')
let codeDetected = false
//if (w.o.match(/^\*(.*)\*/)) {
// w.o = w.o.replaceAll('*','')
// span.classList.add('bold')
//}
/*if (w.o.indexOf('```') !== -1) {
codeDetected = true
if (!inCode)
p.classList.add('code')
inCode = !inCode
} else {
if (w.o.indexOf('`') === 0) {
w.o = w.o.substring(1)
inBold = true
}
if (w.o.indexOf('**') === 0) {
w.o = w.o.substring(2)
inBold = true
}
if (w.o.indexOf('*') === 0) {
w.o = w.o.substring(1)
inBold = true
}
if (inBold)
span.classList.add('bold')
if (w.o.indexOf('`') > 0) {
inBold = false
w.o = w.o.replaceAll('`','')
}
if (w.o.indexOf('**') > 0) {
inBold = false
w.o = w.o.replaceAll('**','')
}
if (inBold) {
let idx = w.o.indexOf('*')
let len = w.o.length
if (idx !== -1 && (idx === len - 1 || idx === len - 2)) {
w.o = w.o.replaceAll('*','')
inBold = false
}
}
}*/
const caption = w.o + ' '
const addPlay = true
span.textContent = caption
if (w.s !== undefined) {
span.o = w.o
span.start = w.s
span.end = w.e
if (addPlay) {
span.addEventListener('click', (evt) => {
absorb(evt)
if (span.classList.contains('highlighted'))
pause()
else
play(span.start)
})
}
}
if (p && !codeDetected) {
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 createToc(chapters) {
for (let c of chapters) {
let div = document.createElement('div')
div.className = 'tocitem'
div.innerHTML = `<div class="tocitemtitle">${c.text}</div><div>${msToTime(c.start)}</div>`
div.start = c.start
div.title = c.textContent
div.onclick = (evt) => {
evt.preventDefault()
evt.stopPropagation()
toggleToc()
play(div.start)
let header = Array.from(document.querySelectorAll('.header')).find(h => h.start === div.start)
if (header) {
let topPosition = window.scrollY + header.getBoundingClientRect().top - playercontainer.offsetHeight - 16
console.log('topPosition=',topPosition)
window.scrollTo({left: 0, top: topPosition, behavior: 'smooth'})
}
}
toc.appendChild(div)
}
}
function isPlaying() {
return ytPlayer ? ytPlayer.getPlayerState() === 1 : !realplayer.paused
}
let lastStart = null
function pause() {
ytPlayer ? ytPlayer.pauseVideo() === 1 : realplayer.pause()
}
function 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(original) {
const chunks = JSON.parse(JSON.stringify(original))
chunks.forEach((c, idx) => {
c.taken = false
c.cleanText = keepCharacters(c.text)
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
let previousStart = 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)
if (start < previousStart) {
continue; // e.g. V_0dNE-H2gw (text lookd like a timestamp "7:00 PM CDT")
}
previousStart = start
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() // removed - because Step-by-Step in wBpHQgMrSnE
text = text.replace(/\(?((\d\d?:)?\d\d?:\d\d)\)?/,'').trim() // remove second timestamp V_0dNE-H2gw
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 createVocabulary(json, videoId, description = '', languageCode = 'en') {
if (json && json[languageCode] && json[languageCode].vocabulary) {
const cachedVocab = json[languageCode].vocabulary
console.log('cached vocab', cachedVocab)
return cachedVocab
}
if (!description || description.trim().length === 0)
return ''
let res = await getModelAnswer(`Return important words including names from this description and return as a simple list separated by commas: ${description}`)
if (!res)
return ''
let vocabulary = res.replace(/\s+/g, ' ')
if (json[languageCode])
json[languageCode].vocabulary = vocabulary
else
json[languageCode] = { vocabulary }
localforage.setItem(videoId, json)
return vocabulary
}
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 = punctuatedDiv
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)
}
}
}
}
}
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 }