-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1430 lines (1269 loc) · 48.9 KB
/
Copy pathscript.js
File metadata and controls
1430 lines (1269 loc) · 48.9 KB
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
// ---------------------------------------------------------------------
// Notecast frontend state machine
// Flow: upload -> extracting -> mode picker -> generating -> player
// ---------------------------------------------------------------------
const SUPPORTED_EXTENSIONS = ["pdf", "docx", "pptx", "txt", "md"];
// Vercel serverless functions have a hard 4.5MB request-body limit that
// can't be raised. We send files as base64 inside JSON, which inflates
// size by ~33%, so the real ceiling on the raw file is roughly 3.3MB.
// 3MB leaves a safety margin for the JSON wrapper overhead.
const MAX_FILE_BYTES = 3 * 1024 * 1024;
// fetch().json() throws a cryptic "Unexpected token... is not valid JSON"
// error whenever the server/platform returns plain text instead of JSON —
// e.g. Vercel's raw "Request Entity Too Large" or "A server error has
// occurred" pages for platform-level failures that never reach our own
// code. This wraps that so those cases produce a readable message instead.
async function parseJsonSafe(res) {
const raw = await res.text();
try {
return JSON.parse(raw);
} catch {
if (res.status === 413) {
throw new Error("That file is too large for the server to accept. Try a smaller file.");
}
throw new Error(
`The server sent back something unexpected (status ${res.status}). Please try again in a moment.`
);
}
}
const state = {
filename: null,
extractedText: null,
selection: {}, // { mode, voiceCount?, depth?, storyType?, quizMode? }
script: null, // [{ speaker, text }]
speakers: [],
playback: {
index: 0,
isPlaying: false,
isPaused: false,
voiceMap: {}, // speaker -> SpeechSynthesisVoice
},
quiz: {
questions: [],
currentIndex: 0,
score: 0,
wrongQuestions: [], // indices of wrong answers
isPaused: false,
answered: false,
mode: null, // 'multiple-choice', 'identification', 'enumeration', 'mixed'
selectedOption: null, // for MCQ
userInput: '', // for ID/Enum
timer: null, // { type: 'perQuestion', seconds } | { type: 'overall', minutes } | null
perQuestionRemaining: 0,
perQuestionIntervalId: null,
overallRemaining: 0,
overallIntervalId: null,
},
};
// --- DOM refs -----------------------------------------------------------
const sections = {
upload: document.getElementById("upload-section"),
extracting: document.getElementById("extracting-section"),
mode: document.getElementById("mode-section"),
generating: document.getElementById("generating-section"),
player: document.getElementById("player-section"),
quiz: document.getElementById("quiz-section"),
};
const dropzone = document.getElementById("dropzone");
const fileInput = document.getElementById("file-input");
const uploadError = document.getElementById("upload-error");
const extractingFilename = document.getElementById("extracting-filename");
const fileChipName = document.getElementById("file-chip-name");
const changeFileBtn = document.getElementById("change-file");
const generatingText = document.getElementById("generating-text");
const transcriptEl = document.getElementById("transcript");
const waveformEl = document.getElementById("waveform");
const playPauseBtn = document.getElementById("play-pause-btn");
const playIcon = document.getElementById("play-icon");
const pauseIcon = document.getElementById("pause-icon");
const playerStatus = document.getElementById("player-status");
const restartBtn = document.getElementById("restart-btn");
const homeBtn = document.getElementById("home-btn");
const backToUploadBtn = document.getElementById("back-to-upload");
const backToModesBtn = document.getElementById("back-to-modes");
const voicePickerEl = document.getElementById("voice-picker");
const voicePickerHint = document.getElementById("voice-picker-hint");
const modeTreeEl = document.getElementById("mode-tree");
const modeConfirmEl = document.getElementById("mode-confirm");
const modeConfirmText = document.getElementById("mode-confirm-text");
const confirmGenerateBtn = document.getElementById("confirm-generate-btn");
const confirmChangeBtn = document.getElementById("confirm-change-btn");
// --- Quiz DOM refs ---
const quizSection = document.getElementById("quiz-section");
const quizProgress = document.getElementById("quiz-progress");
const quizQuestion = document.getElementById("quiz-question");
const quizAnswerArea = document.getElementById("quiz-answer-area");
const quizFeedback = document.getElementById("quiz-feedback");
const quizSubmitBtn = document.getElementById("quiz-submit-btn");
const quizNextBtn = document.getElementById("quiz-next-btn");
const quizPauseBtn = document.getElementById("quiz-pause-btn");
const quizContinueBtn = document.getElementById("quiz-continue-btn");
const quizSummary = document.getElementById("quiz-summary");
const quizFinalScore = document.getElementById("quiz-final-score");
const quizStrongAreas = document.getElementById("quiz-strong-areas");
const quizWeakAreas = document.getElementById("quiz-weak-areas");
const quizSuggestion = document.getElementById("quiz-suggestion");
const quizDrillBtn = document.getElementById("quiz-drill-btn");
const quizSwitchModeBtn = document.getElementById("quiz-switch-mode-btn");
const quizStopBtn = document.getElementById("quiz-stop-btn");
const quizModeOptions = document.getElementById("quiz-mode-options");
const quizModeLoading = document.getElementById("quiz-mode-loading");
const backToModesFromQuiz = document.getElementById("back-to-modes-from-quiz");
const quizCountOptions = document.getElementById("quiz-count-options");
const quizTimerChoiceOptions = document.getElementById("quiz-timer-choice-options");
const quizTimerTypeOptions = document.getElementById("quiz-timer-type-options");
const quizPerQuestionOptions = document.getElementById("quiz-per-question-options");
const quizOverallTimerOptions = document.getElementById("quiz-overall-timer-options");
const quizCustomMinutesInput = document.getElementById("quiz-custom-minutes");
const quizCustomMinutesBtn = document.getElementById("quiz-custom-minutes-btn");
const quizTimerDisplay = document.getElementById("quiz-timer-display");
const quizScoreEl = document.getElementById("quiz-score");
function showSection(name) {
for (const key in sections) {
sections[key].dataset.state = key === name ? "active" : "hidden";
}
}
// --- Step 1: Upload ------------------------------------------------------
dropzone.addEventListener("click", () => fileInput.click());
dropzone.addEventListener("dragover", (e) => {
e.preventDefault();
dropzone.classList.add("dragover");
});
dropzone.addEventListener("dragleave", () => dropzone.classList.remove("dragover"));
dropzone.addEventListener("drop", (e) => {
e.preventDefault();
dropzone.classList.remove("dragover");
const file = e.dataTransfer.files[0];
if (file) handleFile(file);
});
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
if (file) handleFile(file);
});
function showUploadError(message) {
uploadError.textContent = message;
uploadError.hidden = false;
}
function clearUploadError() {
uploadError.hidden = true;
}
async function handleFile(file) {
clearUploadError();
const ext = file.name.split(".").pop().toLowerCase();
if (!SUPPORTED_EXTENSIONS.includes(ext)) {
showUploadError(
`"${ext}" isn't supported yet. Try a PDF, Word, or PowerPoint file.`
);
return;
}
if (file.size > MAX_FILE_BYTES) {
showUploadError("That file is over 3MB — the hosting platform caps uploads at that size. Try a smaller file, or export a version without large embedded images.");
return;
}
state.filename = file.name;
extractingFilename.textContent = file.name;
showSection("extracting");
try {
const base64 = await fileToBase64(file);
const res = await fetch("/api/extract", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ filename: file.name, fileData: base64 }),
});
const data = await parseJsonSafe(res);
if (!res.ok) {
throw new Error(data.error || "Couldn't read that file.");
}
state.extractedText = data.text;
fileChipName.textContent = file.name;
resetModePicker();
showSection("mode");
} catch (err) {
showSection("upload");
showUploadError(err.message || "Something went wrong reading that file.");
}
}
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
// reader.result is "data:<mime>;base64,<data>" — strip the prefix
const base64 = reader.result.split(",")[1];
resolve(base64);
};
reader.onerror = () => reject(new Error("Couldn't read that file."));
reader.readAsDataURL(file);
});
}
changeFileBtn.addEventListener("click", () => {
state.filename = null;
state.extractedText = null;
fileInput.value = "";
showSection("upload");
});
// --- Navigation: home + back buttons -----------------------------------
function goHome() {
window.speechSynthesis.cancel();
state.filename = null;
state.extractedText = null;
state.script = null;
state.speakers = [];
fileInput.value = "";
clearUploadError();
resetQuizState();
showSection("upload");
}
homeBtn.addEventListener("click", goHome);
backToUploadBtn.addEventListener("click", goHome);
backToModesBtn.addEventListener("click", () => {
window.speechSynthesis.cancel();
state.script = null;
resetModePicker();
showSection("mode");
});
// --- Step 2: Mode picker --------------------------------------------------
function resetModePicker() {
state.selection = {};
document.getElementById("mode-error").hidden = true;
modeConfirmEl.hidden = true;
modeTreeEl.hidden = false;
document.querySelectorAll(".mode-panel").forEach((p) => (p.hidden = true));
document.querySelectorAll(".mode-trigger").forEach((t) =>
t.setAttribute("aria-expanded", "false")
);
document.querySelectorAll(".option-btn.selected").forEach((b) =>
b.classList.remove("selected")
);
document.querySelectorAll('[data-step="depth"]').forEach((row) => (row.hidden = true));
// Reset quiz panel content
quizModeOptions.innerHTML = '';
quizModeLoading.hidden = true;
resetQuizPickerSteps();
resetQuizState();
}
// Hides and clears the question-count/timer sub-steps of the quiz
// picker, so re-opening quiz mode (or picking a different file) doesn't
// leave a stale selection lingering from a previous run.
function resetQuizPickerSteps() {
quizCountOptions.hidden = true;
quizTimerChoiceOptions.hidden = true;
quizTimerTypeOptions.hidden = true;
quizPerQuestionOptions.hidden = true;
quizOverallTimerOptions.hidden = true;
[quizCountOptions, quizTimerChoiceOptions, quizTimerTypeOptions, quizPerQuestionOptions, quizOverallTimerOptions]
.forEach((row) => row.querySelectorAll(".option-btn.selected").forEach((b) => b.classList.remove("selected")));
quizCustomMinutesInput.value = "";
}
document.querySelectorAll(".mode-trigger[data-target]").forEach((trigger) => {
trigger.addEventListener("click", () => {
const targetId = trigger.dataset.target;
const panel = document.getElementById(targetId);
const isOpen = !panel.hidden;
// accordion: close all other panels first
document.querySelectorAll(".mode-panel").forEach((p) => (p.hidden = true));
document.querySelectorAll(".mode-trigger[data-target]").forEach((t) =>
t.setAttribute("aria-expanded", "false")
);
if (!isOpen) {
panel.hidden = false;
trigger.setAttribute("aria-expanded", "true");
// If it's the quiz panel, analyse notes
if (targetId === "panel-quiz") {
analyseNotesForQuiz();
}
}
});
});
// Calm mode: single click, no sub-options, straight to confirmation
document.querySelector('[data-immediate="calm"]').addEventListener("click", () => {
state.selection = { mode: "calm" };
showModeConfirm();
});
// Discussion mode: voiceCount -> depth
const discussionPanel = document.getElementById("panel-discussion");
discussionPanel.querySelectorAll('[data-step="voiceCount"] .option-btn').forEach((btn) => {
btn.addEventListener("click", () => {
discussionPanel
.querySelectorAll('[data-step="voiceCount"] .option-btn')
.forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
state.selection = { mode: "discussion", voiceCount: btn.dataset.value };
discussionPanel.querySelector('[data-step="depth"]').hidden = false;
});
});
discussionPanel.querySelectorAll('[data-step="depth"] .option-btn').forEach((btn) => {
btn.addEventListener("click", () => {
discussionPanel
.querySelectorAll('[data-step="depth"] .option-btn')
.forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
state.selection.depth = btn.dataset.value;
showModeConfirm();
});
});
// Story mode: storyType only
const storyPanel = document.getElementById("panel-story");
storyPanel.querySelectorAll(".option-btn").forEach((btn) => {
btn.addEventListener("click", () => {
storyPanel.querySelectorAll(".option-btn").forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
state.selection = { mode: "story", storyType: btn.dataset.value };
showModeConfirm();
});
});
// --- Quiz analysis ---
async function analyseNotesForQuiz() {
quizModeLoading.hidden = false;
quizModeOptions.innerHTML = '';
resetQuizPickerSteps();
try {
const res = await fetch('/api/analyze-quiz', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: state.extractedText }),
});
const data = await parseJsonSafe(res);
if (!res.ok) throw new Error(data.error || 'Analysis failed');
const modes = data.modes || [];
if (!modes.length) {
quizModeOptions.innerHTML = '<p class="error-text">No quiz modes available for these notes.</p>';
return;
}
const modeLabels = {
'multiple-choice': 'Multiple Choice',
'identification': 'Identification',
'enumeration': 'Enumeration',
'mixed': 'Mixed Mode',
};
modes.forEach((mode) => {
const btn = document.createElement('button');
btn.className = 'option-btn';
btn.dataset.value = mode;
btn.textContent = modeLabels[mode] || mode;
btn.type = 'button';
btn.addEventListener('click', () => {
quizModeOptions.querySelectorAll('.option-btn').forEach(b => b.classList.remove('selected'));
btn.classList.add('selected');
state.selection = { mode: 'quiz', quizMode: mode };
// Reveal the next step (question count) instead of confirming
// right away — timer settings still need to be chosen first.
quizTimerChoiceOptions.hidden = true;
quizTimerTypeOptions.hidden = true;
quizPerQuestionOptions.hidden = true;
quizOverallTimerOptions.hidden = true;
quizCountOptions.hidden = false;
});
quizModeOptions.appendChild(btn);
});
} catch (err) {
quizModeOptions.innerHTML = `<p class="error-text">${err.message}</p>`;
} finally {
quizModeLoading.hidden = true;
}
}
// Question count -> reveal timer choice
quizCountOptions.querySelectorAll(".option-btn").forEach((btn) => {
btn.addEventListener("click", () => {
quizCountOptions.querySelectorAll(".option-btn").forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
state.selection.questionCount = Number(btn.dataset.value);
quizTimerTypeOptions.hidden = true;
quizPerQuestionOptions.hidden = true;
quizOverallTimerOptions.hidden = true;
quizTimerChoiceOptions.hidden = false;
});
});
// Timer choice: no timer -> confirm now; with timer -> reveal timer type
quizTimerChoiceOptions.querySelectorAll(".option-btn").forEach((btn) => {
btn.addEventListener("click", () => {
quizTimerChoiceOptions.querySelectorAll(".option-btn").forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
if (btn.dataset.value === "none") {
state.selection.timer = null;
showModeConfirm();
} else {
quizPerQuestionOptions.hidden = true;
quizOverallTimerOptions.hidden = true;
quizTimerTypeOptions.hidden = false;
}
});
});
// Timer type: per-question -> reveal seconds; overall -> reveal minutes picker
quizTimerTypeOptions.querySelectorAll(".option-btn").forEach((btn) => {
btn.addEventListener("click", () => {
quizTimerTypeOptions.querySelectorAll(".option-btn").forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
if (btn.dataset.value === "perQuestion") {
quizOverallTimerOptions.hidden = true;
quizPerQuestionOptions.hidden = false;
} else {
quizPerQuestionOptions.hidden = true;
quizOverallTimerOptions.hidden = false;
}
});
});
// Per-question seconds -> confirm
quizPerQuestionOptions.querySelectorAll(".option-btn").forEach((btn) => {
btn.addEventListener("click", () => {
quizPerQuestionOptions.querySelectorAll(".option-btn").forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
state.selection.timer = { type: "perQuestion", seconds: Number(btn.dataset.value) };
showModeConfirm();
});
});
// Overall quiz timer: preset minutes -> confirm
quizOverallTimerOptions.querySelectorAll(".option-btn").forEach((btn) => {
btn.addEventListener("click", () => {
quizOverallTimerOptions.querySelectorAll(".option-btn").forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
state.selection.timer = { type: "overall", minutes: Number(btn.dataset.value) };
showModeConfirm();
});
});
// Overall quiz timer: custom minutes -> confirm
quizCustomMinutesBtn.addEventListener("click", () => {
const minutes = Number(quizCustomMinutesInput.value);
if (!Number.isFinite(minutes) || minutes < 1 || minutes > 180) {
quizCustomMinutesInput.focus();
return;
}
quizOverallTimerOptions.querySelectorAll(".option-btn").forEach((b) => b.classList.remove("selected"));
state.selection.timer = { type: "overall", minutes };
showModeConfirm();
});
// --- Step 3: Confirmation (prevents an accidental tap from firing a
// real API call) --------------------------------------------------------
const MODE_LABELS = {
"discussion.oneVoice.inDepth": "a 1-voice, in-depth discussion",
"discussion.oneVoice.general": "a 1-voice, general discussion",
"discussion.twoVoice.inDepth": "a 2-voice, in-depth discussion",
"discussion.twoVoice.general": "a 2-voice, general discussion",
"story.bedtime": "a bedtime story",
"story.drama": "a drama",
calm: "calm mode",
};
function describeSelection(selection) {
if (selection.mode === "discussion") {
const key = `discussion.${selection.voiceCount}.${selection.depth}`;
return MODE_LABELS[key] || "a discussion";
}
if (selection.mode === "story") {
return MODE_LABELS[`story.${selection.storyType}`] || "a story";
}
if (selection.mode === "calm") {
return MODE_LABELS.calm;
}
if (selection.mode === "quiz") {
const quizModeLabels = {
'multiple-choice': 'Multiple Choice',
'identification': 'Identification',
'enumeration': 'Enumeration',
'mixed': 'Mixed Mode',
};
const base = `a ${selection.questionCount || 10}-question ${quizModeLabels[selection.quizMode] || 'quiz'} quiz`;
if (!selection.timer) return `${base}, no timer`;
if (selection.timer.type === "perQuestion") return `${base}, ${selection.timer.seconds}s per question`;
if (selection.timer.type === "overall") return `${base}, ${selection.timer.minutes}-minute overall timer`;
return base;
}
return "this mode";
}
function showModeConfirm() {
modeTreeEl.hidden = true;
modeConfirmText.innerHTML = `Generate <strong>${describeSelection(state.selection)}</strong> from "${state.filename}"?`;
modeConfirmEl.hidden = false;
}
confirmGenerateBtn.addEventListener("click", () => {
if (state.selection.mode === 'quiz') {
generateQuiz();
} else {
generateScript();
}
});
confirmChangeBtn.addEventListener("click", () => {
resetModePicker();
});
// --- Step 4: Generate script (audio) --------------------------------------
async function generateScript() {
document.getElementById("mode-error").hidden = true;
showSection("generating");
try {
const res = await fetch("/api/generate-script", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: state.extractedText,
...state.selection,
}),
});
const data = await parseJsonSafe(res);
if (!res.ok) {
throw new Error(data.error || "Couldn't generate a script for that.");
}
state.script = data.script;
state.speakers = data.speakers;
state.playback.baseStyle = data.voiceStyle || { rate: 1, pitch: 1 };
buildTranscript();
assignVoices();
showSection("player");
resetPlayback();
} catch (err) {
showSection("mode");
const errorEl = document.getElementById("mode-error");
errorEl.textContent = err.message || "Something went wrong generating the script.";
errorEl.hidden = false;
}
}
// --- Quiz generation -------------------------------------------------------
async function generateQuiz() {
document.getElementById('mode-error').hidden = true;
showSection('generating');
generatingText.textContent = 'Generating your quiz…';
try {
const res = await fetch('/api/generate-quiz', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: state.extractedText,
quizMode: state.selection.quizMode,
questionCount: state.selection.questionCount || 10,
}),
});
const data = await parseJsonSafe(res);
if (!res.ok) throw new Error(data.error || 'Could not generate quiz.');
state.quiz.questions = data.questions;
state.quiz.currentIndex = 0;
state.quiz.score = 0;
state.quiz.wrongQuestions = [];
state.quiz.answered = false;
state.quiz.isPaused = false;
state.quiz.mode = state.selection.quizMode;
state.quiz.timer = state.selection.timer || null;
showSection('quiz');
startOverallTimerIfNeeded();
renderQuizQuestion();
} catch (err) {
showSection('mode');
const errorEl = document.getElementById('mode-error');
errorEl.textContent = err.message || 'Something went wrong generating the quiz.';
errorEl.hidden = false;
} finally {
generatingText.textContent = 'Writing your script…'; // reset
}
}
// --- Step 4: Transcript + voices -------------------------------------------
function buildTranscript() {
transcriptEl.innerHTML = "";
state.script.forEach((line, i) => {
const row = document.createElement("div");
row.className = "transcript-line";
row.id = `line-${i}`;
row.innerHTML = `<span class="speaker-tag">${escapeHtml(line.speaker)}</span><span>${escapeHtml(line.text)}</span>`;
transcriptEl.appendChild(row);
});
}
function escapeHtml(str) {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML;
}
// Browsers don't expose real gender metadata for voices, but most
// system/Edge voice names follow known conventions. This is a rough
// label to help with picking, not a guarantee.
const MALE_NAME_HINTS = ["david", "mark", "guy", "ryan", "christopher", "eric", "james", "roger", "andrew", "george", "daniel", "tony"];
const FEMALE_NAME_HINTS = ["zira", "aria", "jenny", "michelle", "ana", "emma", "samantha", "susan", "karen", "victoria", "zoe", "sara", "catherine", "hazel", "linda", "female"];
function guessVoiceGender(voiceName) {
const lower = voiceName.toLowerCase();
if (MALE_NAME_HINTS.some((hint) => lower.includes(hint))) return "male-leaning";
if (FEMALE_NAME_HINTS.some((hint) => lower.includes(hint))) return "female-leaning";
return null;
}
// Maps each distinct speaker name to a distinct system voice. When a
// speaker's label hints at a gender (e.g. "man", "woman", or a
// recognizably gendered name from the script), we try to match a voice
// leaning that way first. Gendered speakers are matched BEFORE neutral
// ones (like "narrator") claim a voice, so a generic first-pass narrator
// doesn't accidentally take the only male- or female-leaning voice
// before the speakers who actually need it get a turn.
// Some browsers (notably Edge) expose noticeably more natural-sounding
// "Online (Natural)" neural voices alongside legacy robotic ones, through
// the exact same free API. When present, prefer them — costs nothing,
// sounds meaningfully better.
function voiceQualityScore(voice) {
const name = voice.name.toLowerCase();
if (name.includes("online") || name.includes("natural")) return 2;
if (name.includes("neural")) return 2;
return 0;
}
function assignVoices() {
const voices = window.speechSynthesis.getVoices();
const englishVoices = voices.filter((v) => v.lang.startsWith("en"));
const unsorted = englishVoices.length ? englishVoices : voices;
const pool = [...unsorted].sort((a, b) => voiceQualityScore(b) - voiceQualityScore(a));
state.playback.voicePool = pool;
state.playback.voiceMap = {};
const usedVoiceNames = new Set();
const gendered = state.speakers.filter((s) => guessSpeakerGender(s));
const neutral = state.speakers.filter((s) => !guessSpeakerGender(s));
const orderedSpeakers = [...gendered, ...neutral];
orderedSpeakers.forEach((speaker) => {
const wantedGender = guessSpeakerGender(speaker);
let chosen = null;
if (wantedGender) {
chosen = pool.find(
(v) => !usedVoiceNames.has(v.name) && guessVoiceGender(v.name) === wantedGender
);
}
if (!chosen) {
chosen = pool.find((v) => !usedVoiceNames.has(v.name)) || pool[0] || null;
}
if (chosen) usedVoiceNames.add(chosen.name);
const originalIndex = state.speakers.indexOf(speaker);
state.playback.voiceMap[speaker] = {
voice: chosen,
pitchDelta: originalIndex % 2 === 0 ? 0 : 0.15, // fallback differentiator if voices repeat
};
});
buildVoicePicker();
}
// Guesses a speaker's intended gender from their script label (e.g.
// "man", "woman", "narrator" -> null since narrators are neutral).
function guessSpeakerGender(speakerLabel) {
const lower = speakerLabel.toLowerCase();
if (["man", "male", "father", "husband", "boy", "king", "he"].some((w) => lower.includes(w))) {
return "male-leaning";
}
if (["woman", "female", "mother", "wife", "girl", "queen", "she"].some((w) => lower.includes(w))) {
return "female-leaning";
}
return null;
}
function buildVoicePicker() {
const pool = state.playback.voicePool || [];
voicePickerEl.innerHTML = "";
if (!pool.length) {
voicePickerHint.hidden = true;
return; // no voices loaded yet
}
voicePickerHint.hidden = false;
state.speakers.forEach((speaker) => {
const row = document.createElement("div");
row.className = "voice-picker-row";
const label = document.createElement("label");
label.textContent = speaker;
label.setAttribute("for", `voice-select-${speaker}`);
const select = document.createElement("select");
select.id = `voice-select-${speaker}`;
pool.forEach((voice, i) => {
const option = document.createElement("option");
option.value = i;
const gender = guessVoiceGender(voice.name);
option.textContent = gender ? `${voice.name} (${gender})` : voice.name;
const current = state.playback.voiceMap[speaker]?.voice;
if (current && current.name === voice.name && current.lang === voice.lang) {
option.selected = true;
}
select.appendChild(option);
});
select.addEventListener("change", () => {
state.playback.voiceMap[speaker].voice = pool[Number(select.value)];
});
row.appendChild(label);
row.appendChild(select);
voicePickerEl.appendChild(row);
});
}
// speechSynthesis.getVoices() can load asynchronously on first page load
if ("speechSynthesis" in window) {
window.speechSynthesis.onvoiceschanged = () => {
if (state.script) assignVoices();
};
}
// Splits a line of text into individual sentences so each one can get
// its own brief pause and its own intonation, instead of the whole line
// being read as one flat, unbroken block — a big source of the "robotic"
// feel even with a good voice. Ellipses are protected from being split
// mid-way (so "..." stays one pause-beat, not three fragments).
function splitIntoSentences(text) {
const ELLIPSIS_TOKEN = "\u0000";
const protectedText = text.replace(/\.\.\./g, ELLIPSIS_TOKEN);
const rawParts = protectedText.split(/(?<=[.!?])\s+/);
return rawParts
.map((p) => p.replace(new RegExp(ELLIPSIS_TOKEN, "g"), "..."))
.map((p) => p.trim())
.filter(Boolean);
}
// Adjusts rate/pitch per sentence based on punctuation (question lift,
// exclamation energy), dramatic pause-beats (slower), and a small
// rhythmic wobble across consecutive sentences so pacing doesn't sound
// perfectly metronomic — real speech never holds one exact pace.
function sentenceStyle(sentence, baseStyle, pitchDelta, sentenceIndex) {
let rate = baseStyle.rate;
let pitch = baseStyle.pitch + (pitchDelta || 0);
const trimmed = sentence.trim();
if (trimmed.endsWith("?")) pitch += 0.06;
if (trimmed.endsWith("!")) {
rate += 0.05;
pitch += 0.04;
}
if (/^\.\.\.+$/.test(trimmed) || trimmed.startsWith("...")) {
rate -= 0.15; // pause-beat lines land slower and heavier
}
const wobble = ((sentenceIndex % 3) - 1) * 0.015; // -0.015, 0, +0.015 cycling
rate += wobble;
return {
rate: Math.min(2, Math.max(0.1, rate)),
pitch: Math.min(2, Math.max(0, pitch)),
};
}
// --- Step 5: Playback -------------------------------------------------------
function resetPlayback() {
window.speechSynthesis.cancel();
state.playback.index = 0;
state.playback.isPlaying = false;
state.playback.isPaused = false;
state.playback.resumeFn = null;
updatePlayerUI();
clearHighlight();
}
function updatePlayerUI() {
const { isPlaying } = state.playback;
playIcon.hidden = isPlaying;
pauseIcon.hidden = !isPlaying;
playPauseBtn.setAttribute("aria-label", isPlaying ? "Pause" : "Play");
waveformEl.classList.toggle("speaking", isPlaying);
if (state.playback.index >= state.script.length) {
playerStatus.textContent = "Finished";
} else if (isPlaying) {
playerStatus.textContent = `Reading line ${state.playback.index + 1} of ${state.script.length}`;
} else if (state.playback.isPaused) {
playerStatus.textContent = "Paused";
} else {
playerStatus.textContent = "Ready";
}
}
function clearHighlight() {
document.querySelectorAll(".transcript-line.current").forEach((el) =>
el.classList.remove("current")
);
}
function highlightLine(i) {
clearHighlight();
const el = document.getElementById(`line-${i}`);
if (el) {
el.classList.add("current");
el.scrollIntoView({ block: "nearest", behavior: "smooth" });
}
}
// Speaks one sentence, then (after a natural pause — longer for dramatic
// beats) moves to the next. Stores a resume point on state.playback so
// pausing mid-gap between sentences can be resumed correctly rather than
// silently stalling.
function speakSentenceQueue(sentences, chunkIndex, voiceConfig, baseStyle, onDone) {
if (chunkIndex >= sentences.length) {
onDone();
return;
}
const sentence = sentences[chunkIndex];
const utterance = new SpeechSynthesisUtterance(sentence);
if (voiceConfig.voice) utterance.voice = voiceConfig.voice;
const style = sentenceStyle(sentence, baseStyle, voiceConfig.pitchDelta, chunkIndex);
utterance.rate = style.rate;
utterance.pitch = style.pitch;
utterance.onend = () => {
if (!state.playback.isPlaying) return; // paused mid-utterance
const isPauseBeat = /^\.\.\.+$/.test(sentence.trim()) || sentence.trim().startsWith("...");
const gapMs = isPauseBeat ? 550 : 130;
state.playback.resumeFn = () =>
speakSentenceQueue(sentences, chunkIndex + 1, voiceConfig, baseStyle, onDone);
setTimeout(() => {
if (!state.playback.isPlaying) return; // paused during the gap
state.playback.resumeFn = null;
speakSentenceQueue(sentences, chunkIndex + 1, voiceConfig, baseStyle, onDone);
}, gapMs);
};
utterance.onerror = () => {
state.playback.isPlaying = false;
updatePlayerUI();
};
window.speechSynthesis.speak(utterance);
}
function speakLine(i) {
if (i >= state.script.length) {
state.playback.isPlaying = false;
updatePlayerUI();
return;
}
const line = state.script[i];
const voiceConfig = state.playback.voiceMap[line.speaker] || {};
const baseStyle = state.playback.baseStyle || { rate: 1, pitch: 1 };
const sentences = splitIntoSentences(line.text);
const chunks = sentences.length ? sentences : [line.text];
highlightLine(i);
updatePlayerUI();
speakSentenceQueue(chunks, 0, voiceConfig, baseStyle, () => {
if (!state.playback.isPlaying) return;
state.playback.index = i + 1;
speakLine(state.playback.index);
});
}
playPauseBtn.addEventListener("click", () => {
const { isPlaying, isPaused } = state.playback;
if (isPlaying) {
// pause — native pause handles the common case (mid-utterance);
// resumeFn (set in speakSentenceQueue) covers the rarer case of
// pausing during the brief gap between sentences.
window.speechSynthesis.pause();
state.playback.isPlaying = false;
state.playback.isPaused = true;
updatePlayerUI();
return;
}
if (isPaused) {
state.playback.isPlaying = true;
state.playback.isPaused = false;
if (state.playback.resumeFn) {
// We were paused during the brief gap between sentences —
// continue from exactly there, regardless of what
// speechSynthesis.paused reports (it can be unreliable when
// nothing was actually mid-utterance).
const fn = state.playback.resumeFn;
state.playback.resumeFn = null;
fn();
} else if (window.speechSynthesis.paused) {
window.speechSynthesis.resume();
} else {
speakLine(state.playback.index); // safety net fallback
}
updatePlayerUI();
return;
}
// start fresh (or continue after finishing)
if (state.playback.index >= state.script.length) {
state.playback.index = 0;
}
state.playback.isPlaying = true;
speakLine(state.playback.index);
});
restartBtn.addEventListener("click", () => {
resetPlayback();
});
// ==================== QUIZ LOGIC ====================
function resetQuizState() {
stopAllQuizTimers();
state.quiz = {
questions: [],
currentIndex: 0,
score: 0,
wrongQuestions: [],
isPaused: false,
answered: false,
mode: null,
selectedOption: null,
userInput: '',
timer: null,
perQuestionRemaining: 0,
perQuestionIntervalId: null,
overallRemaining: 0,
overallIntervalId: null,
};
quizTimerDisplay.hidden = true;
quizTimerDisplay.classList.remove("urgent");
quizScoreEl.textContent = '';
}
// --- Timer engine -----------------------------------------------------
function formatTimerText(totalSeconds) {
const m = Math.floor(totalSeconds / 60);
const s = totalSeconds % 60;
return `⏱ ${m}:${String(s).padStart(2, "0")}`;
}
function stopPerQuestionTimer() {
if (state.quiz.perQuestionIntervalId) {
clearInterval(state.quiz.perQuestionIntervalId);
state.quiz.perQuestionIntervalId = null;
}