File size: 23,087 Bytes
076b6ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
035bfeb
076b6ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// advanced.math.js
import * as webllm from "https://esm.run/@mlc-ai/web-llm";

// Ensure the script runs after the DOM is fully loaded
document.addEventListener("DOMContentLoaded", () => {
  // Initialize the Advanced Mathematics & Problem Solving section
  const mathMessages = [
    {
      content: "You are Aged Guru, an intelligent assistant skilled in advanced mathematics and problem solving. Provide insightful and comprehensive answers to complex mathematical questions.",
      role: "system"
    }
  ];

  const mathAvailableModels = webllm.prebuiltAppConfig.model_list.map(
    (m) => m.model_id
  );
  let mathSelectedModel = "Qwen2.5-Math-1.5B-Instruct-q4f16_1-MLC"; // Default model

  function mathUpdateEngineInitProgressCallback(report) {
    console.log("Advanced Math Initialize", report.progress);
    // Instead of updating a status span, log the progress
    logMessage(`Model Initialization Progress: ${report.text}`, "system");
  }

  const mathEngine = new webllm.MLCEngine();
  mathEngine.setInitProgressCallback(mathUpdateEngineInitProgressCallback);

  let mathIsGenerating = false; // Flag to prevent multiple generations

  async function mathInitializeWebLLMEngine() {
    logMessage("Model initialization started.", "system");
    document.getElementById("math-loading-spinner").classList.remove("hidden"); // Show spinner
    mathSelectedModel = document.getElementById("math-model-selection").value;
    const config = {
      temperature: 0.7, // Adjusted for more precise answers
      top_p: 0.9
    };
    try {
      await mathEngine.reload(mathSelectedModel, config);
      document.getElementById("math-selected-model").textContent = mathSelectedModel;
      document.getElementById("math-start_button").disabled = false;
      document.getElementById("math-text-input").disabled = false; // Enable text input after initialization
      document.getElementById("math-submit-button").disabled = false; // Enable submit button after initialization
      document.getElementById("math-speech-controls").disabled = false; // Enable speech controls after initialization
      document.getElementById("math-configuration").classList.remove("hidden");
      logMessage("Model initialized successfully.", "system");
    } catch (error) {
      console.error("Error initializing the model:", error);
      alert("Failed to initialize the model. Please try again.");
      logMessage("Failed to initialize the model.", "error");
    } finally {
      document.getElementById("math-loading-spinner").classList.add("hidden"); // Hide spinner
    }
  }

  async function mathStreamingGenerating(messages, onUpdate, onFinish, onError) {
    if (mathIsGenerating) {
      console.warn("Advanced Math Generation already in progress.");
      return;
    }
    mathIsGenerating = true;
    try {
      let curMessage = "";
      const completion = await mathEngine.chat.completions.create({
        stream: true,
        messages
      });
      for await (const chunk of completion) {
        const curDelta = chunk.choices[0].delta.content;
        if (curDelta) {
          curMessage += curDelta;
        }
        onUpdate(curMessage);
      }
      const finalMessage = await mathEngine.getMessage();
      console.log(`Advanced Math Generated final message: ${finalMessage}`); // Debugging
      onFinish(finalMessage);
      logMessage("Response generated successfully.", "system");
    } catch (err) {
      console.error(err);
      onError(err);
      logMessage("An error occurred during response generation.", "error");
    } finally {
      mathIsGenerating = false;
    }
  }

  // Flag to track the last input method
  let mathLastInputWasVoice = false;

  function mathAppendMessage(message) {
    console.log(`Advanced Math Appending message: ${message.content} (Role: ${message.role})`); // Debugging
    const mathChatBox = document.getElementById("math-chat-box");

    // Check if the assistant's message is already appended to avoid duplication
    if (message.role === "assistant") {
      const existingMessages = mathChatBox.querySelectorAll(".message");
      const lastMessage = existingMessages[existingMessages.length - 1];
      if (lastMessage && lastMessage.textContent === message.content) {
        console.warn("Duplicate assistant message detected in Advanced Math section, skipping append.");

        // Only trigger TTS for assistant messages if the last input was via voice
        if (message.role === "assistant" && message.content !== "typing..." && mathLastInputWasVoice) {
          mathSpeak(message.content);
        }

        return; // Exit to avoid appending the same message twice
      }
    }

    const container = document.createElement("div");
    container.classList.add("message-container");
    const newMessage = document.createElement("div");
    newMessage.classList.add("message");
    newMessage.textContent = message.content;

    if (message.role === "user") {
      container.classList.add("user");
    } else {
      container.classList.add("assistant");
    }

    container.appendChild(newMessage);
    mathChatBox.appendChild(container);
    mathChatBox.scrollTop = mathChatBox.scrollHeight;

    // Only trigger TTS for assistant messages if the last input was via voice
    if (message.role === "assistant" && message.content !== "typing..." && mathLastInputWasVoice) {
      mathSpeak(message.content);
    }
  }

  function mathUpdateLastMessage(content) {
    const messageDoms = document.getElementById("math-chat-box").querySelectorAll(".message");
    const lastMessageDom = messageDoms[messageDoms.length - 1];
    lastMessageDom.textContent = content;
  }

  function mathOnSpeechRecognized(transcript) {
    const input = transcript.trim();
    const message = {
      content: input,
      role: "user"
    };
    if (input.length === 0) {
      return;
    }
    mathLastInputWasVoice = true; // Set flag as voice input
    console.log(`Advanced Math Voice input received: ${input}`); // Debugging
    document.getElementById("math-start_button").disabled = true;
    document.getElementById("math-submit-button").disabled = true; // Disable submit button during processing

    mathMessages.push(message);
    mathAppendMessage(message);
    logMessage(`User (Voice): ${input}`, "user");

    // Append "typing..." placeholder
    const aiPlaceholder = {
      content: "typing...",
      role: "assistant"
    };
    mathAppendMessage(aiPlaceholder);
    logMessage("AdvancedMathBot is typing...", "system");

    const onFinishGenerating = (finalMessage) => {
      console.log(`Advanced Math Finishing generation with message: ${finalMessage}`); // Debugging
      // Remove the "typing..." placeholder
      const mathChatBox = document.getElementById("math-chat-box");
      const lastMessageContainer = mathChatBox.lastElementChild;
      if (lastMessageContainer && lastMessageContainer.querySelector(".message").textContent === "typing...") {
        mathChatBox.removeChild(lastMessageContainer);
      }

      // Append the final message
      const aiMessage = {
        content: finalMessage,
        role: "assistant"
      };
      mathAppendMessage(aiMessage);
      logMessage(`AdvancedMathBot: ${finalMessage}`, "assistant");

      document.getElementById("math-start_button").disabled = false;
      document.getElementById("math-submit-button").disabled = false; // Re-enable submit button after processing
      mathEngine.runtimeStatsText().then((statsText) => {
        document.getElementById("math-chat-stats").classList.remove("hidden");
        document.getElementById("math-chat-stats").textContent = statsText;
        logMessage(`Runtime Stats: ${statsText}`, "system");
      });
    };

    mathStreamingGenerating(
      mathMessages,
      mathUpdateLastMessage,
      onFinishGenerating,
      (err) => {
        console.error(err);
        alert("An error occurred while generating the response. Please try again.");
        logMessage("Error during response generation.", "error");
        document.getElementById("math-start_button").disabled = false;
        document.getElementById("math-submit-button").disabled = false;
      }
    );
  }

  // Speech Recognition Code for Advanced Math
  let mathRecognizing = false;
  let mathIgnore_onend;
  let mathFinal_transcript = '';
  let mathRecognition;

  function mathStartButton(event) {
    if (mathRecognizing) {
      mathRecognition.stop();
      return;
    }
    mathFinal_transcript = '';
    mathRecognition.lang = 'en-US';
    mathRecognition.start();
    mathIgnore_onend = false;
    document.getElementById("math-start_button").classList.add("mic-animate");
    logMessage("Voice input started.", "system");
  }

  if (!('webkitSpeechRecognition' in window)) {
    alert("Web Speech API is not supported by this browser.");
    logMessage("Web Speech API not supported by this browser.", "error");
  } else {
    mathRecognition = new webkitSpeechRecognition();
    mathRecognition.continuous = false; // Non-continuous recognition
    mathRecognition.interimResults = false; // Get only final results

    mathRecognition.onstart = function() {
      mathRecognizing = true;
      logMessage("Speech recognition started.", "system");
    };

    mathRecognition.onerror = function(event) {
      if (event.error == 'no-speech') {
        document.getElementById("math-start_button").classList.remove("mic-animate");
        alert('No speech was detected in Advanced Mathematics section.');
        logMessage("No speech detected.", "error");
        mathIgnore_onend = true;
      }
      if (event.error == 'audio-capture') {
        document.getElementById("math-start_button").classList.remove("mic-animate");
        alert('No microphone was found in Advanced Mathematics section.');
        logMessage("No microphone found.", "error");
        mathIgnore_onend = true;
      }
      if (event.error == 'not-allowed') {
        alert('Permission to use microphone was denied in Advanced Mathematics section.');
        logMessage("Microphone permission denied.", "error");
        mathIgnore_onend = true;
      }
    };

    mathRecognition.onend = function() {
      mathRecognizing = false;
      document.getElementById("math-start_button").classList.remove("mic-animate");
      logMessage("Speech recognition ended.", "system");
      if (mathIgnore_onend) {
        return;
      }
      if (!mathFinal_transcript) {
        logMessage("No transcript captured.", "error");
        return;
      }
      // Process the final transcript
      mathOnSpeechRecognized(mathFinal_transcript);
    };

    mathRecognition.onresult = function(event) {
      for (let i = event.resultIndex; i < event.results.length; ++i) {
        if (event.results[i].isFinal) {
          mathFinal_transcript += event.results[i][0].transcript;
        }
      }
      mathFinal_transcript = mathFinal_transcript.trim();
      logMessage(`Recognized Speech: ${mathFinal_transcript}`, "user");
    };
  }

  document.getElementById("math-start_button").addEventListener("click", function(event) {
    mathStartButton(event);
  });

  // Initialize Model Selection
  mathAvailableModels.forEach((modelId) => {
    const option = document.createElement("option");
    option.value = modelId;
    option.textContent = modelId;
    document.getElementById("math-model-selection").appendChild(option);
  });
  document.getElementById("math-model-selection").value = mathSelectedModel;

  // **Enable the Download Model button after models are loaded**
  document.getElementById("math-download").disabled = false;

  document.getElementById("math-download").addEventListener("click", function () {
    mathInitializeWebLLMEngine().then(() => {
      document.getElementById("math-start_button").disabled = false;
      // Enable speech controls after model initialization
      document.getElementById("math-speech-rate").disabled = false;
      document.getElementById("math-speech-pitch").disabled = false;
      logMessage("Model download initiated.", "system");
    });
  });

  document.getElementById("math-clear-logs").addEventListener("click", function () {
    document.getElementById("math-logs").innerHTML = '';
    logMessage("Logs cleared.", "system");
  });

  // ===== TTS Integration =====

  // Initialize Speech Synthesis
  let mathSpeech = new SpeechSynthesisUtterance();
  mathSpeech.lang = "en";

  let mathVoices = [];

  // Use addEventListener instead of directly assigning to onvoiceschanged
  window.speechSynthesis.addEventListener("voiceschanged", () => {
    mathVoices = window.speechSynthesis.getVoices();
    mathPopulateVoices();
  });

  function mathPopulateVoices() {
    const voiceSelect = document.getElementById("math-tools");
    voiceSelect.innerHTML = ''; // Clear existing options
    mathVoices.forEach((voice, i) => {
      const option = new Option(voice.name, i);
      voiceSelect.appendChild(option);
    });
    if (mathVoices.length > 0) {
      const savedVoice = localStorage.getItem("mathSelectedVoice");
      if (savedVoice !== null && mathVoices[savedVoice]) {
        mathSpeech.voice = mathVoices[savedVoice];
        voiceSelect.value = savedVoice;
      } else {
        mathSpeech.voice = mathVoices[0];
      }
    }
  }

  // Voice Selection Event Listener
  document.getElementById("math-tools").addEventListener("change", () => {
    const selectedVoiceIndex = document.getElementById("math-tools").value;
    mathSpeech.voice = mathVoices[selectedVoiceIndex];
    // Save to localStorage
    localStorage.setItem("mathSelectedVoice", selectedVoiceIndex);
    logMessage(`Voice changed to: ${mathVoices[selectedVoiceIndex].name}`, "system");
  });

  // Function to Speak Text with Voice Selection and Handling Large Texts
  function mathSpeak(text) {
    if (!window.speechSynthesis) {
      console.warn("Speech Synthesis not supported in this browser for Advanced Mathematics section.");
      logMessage("Speech Synthesis not supported in this browser.", "error");
      return;
    }

    // Show spinner and enable Stop button
    document.getElementById("math-loading-spinner").classList.remove("hidden");
    document.getElementById("math-stop_button").disabled = false;
    logMessage("TTS started.", "system");

    // Retrieve the currently selected voice
    const selectedVoice = mathSpeech.voice;

    // Split the text into sentences to manage large texts
    const sentences = text.match(/[^\.!\?]+[\.!\?]+/g) || [text];

    let utterancesCount = sentences.length;

    sentences.forEach(sentence => {
      const utterance = new SpeechSynthesisUtterance(sentence.trim());

      // Assign the selected voice to the utterance
      if (selectedVoice) {
        utterance.voice = selectedVoice;
      }

      // Assign rate and pitch from sliders
      const rate = parseFloat(document.getElementById("math-speech-rate").value);
      const pitch = parseFloat(document.getElementById("math-speech-pitch").value);
      utterance.rate = rate; // Adjust the speaking rate (0.1 to 10)
      utterance.pitch = pitch; // Adjust the pitch (0 to 2)

      // Add event listeners for debugging or additional functionality
      utterance.onstart = () => {
        console.log("Speech started:", sentence);
        logMessage(`TTS started: ${sentence.trim()}`, "system");
      };

      utterance.onend = () => {
        console.log("Speech ended:", sentence);
        logMessage(`TTS ended: ${sentence.trim()}`, "system");
        utterancesCount--;
        if (utterancesCount === 0) {
          // Hide spinner and disable Stop button when all utterances have been spoken
          document.getElementById("math-loading-spinner").classList.add("hidden");
          document.getElementById("math-stop_button").disabled = true;
          logMessage("All TTS messages have been spoken.", "system");
        }
      };

      utterance.onerror = (e) => {
        console.error("Speech Synthesis Error:", e);
        alert("An error occurred during speech synthesis. Please try again.");
        logMessage("Speech synthesis encountered an error.", "error");
        utterancesCount = 0;
        document.getElementById("math-loading-spinner").classList.add("hidden");
        document.getElementById("math-stop_button").disabled = true;
      };

      window.speechSynthesis.speak(utterance);
    });
  }

  // ===== New: Stop Speech Functionality =====

  /**
   * Stops any ongoing speech synthesis.
   */
  function mathStopSpeech() {
    if (window.speechSynthesis.speaking) {
      window.speechSynthesis.cancel();
      document.getElementById("math-loading-spinner").classList.add("hidden");
      document.getElementById("math-stop_button").disabled = true;
      logMessage("Speech synthesis stopped by user.", "system");
    }
  }

  // Event Listener for Stop Button
  document.getElementById("math-stop_button").addEventListener("click", function () {
    mathStopSpeech();
  });

  // ===== New: Text Input Handling =====

  // Function to Handle Text Submission
  function mathHandleTextSubmit() {
    const textInput = document.getElementById("math-text-input");
    const input = textInput.value.trim();
    if (input.length === 0) {
      return;
    }
    textInput.value = ''; // Clear the input field
    const message = {
      content: input,
      role: "user" // Ensure this is correctly set
    };
    console.log(`Advanced Math Text input received: ${input}`); // Debugging
    logMessage(`User: ${input}`, "user");

    mathLastInputWasVoice = false; // Set flag as text input
    document.getElementById("math-submit-button").disabled = true; // Disable to prevent multiple submissions

    mathMessages.push(message);
    mathAppendMessage(message);

    // Append "typing..." placeholder
    const aiPlaceholder = {
      content: "typing...",
      role: "assistant"
    };
    mathAppendMessage(aiPlaceholder);
    logMessage("AdvancedMathBot is typing...", "system");

    const onFinishGenerating = (finalMessage) => {
      console.log(`Advanced Math Finishing generation with message: ${finalMessage}`); // Debugging
      // Remove the "typing..." placeholder
      const mathChatBox = document.getElementById("math-chat-box");
      const lastMessageContainer = mathChatBox.lastElementChild;
      if (lastMessageContainer && lastMessageContainer.querySelector(".message").textContent === "typing...") {
        mathChatBox.removeChild(lastMessageContainer);
      }

      // Append the final message
      const aiMessage = {
        content: finalMessage,
        role: "assistant"
      };
      mathAppendMessage(aiMessage);
      logMessage(`AdvancedMathBot: ${finalMessage}`, "assistant");

      // Trigger TTS for assistant messages if required
      if (mathLastInputWasVoice) {
        mathSpeak(finalMessage);
      }

      document.getElementById("math-submit-button").disabled = false; // Re-enable submit button after processing
      mathEngine.runtimeStatsText().then((statsText) => {
        document.getElementById("math-chat-stats").classList.remove("hidden");
        document.getElementById("math-chat-stats").textContent = statsText;
        logMessage(`Runtime Stats: ${statsText}`, "system");
      });
    };

    mathStreamingGenerating(
      mathMessages,
      mathUpdateLastMessage,
      onFinishGenerating,
      (err) => {
        console.error(err);
        alert("An error occurred while generating the response. Please try again.");
        logMessage("Error during response generation.", "error");
        document.getElementById("math-submit-button").disabled = false;
      }
    );
  }

  // Event Listener for Submit Button
  document.getElementById("math-submit-button").addEventListener("click", function () {
    mathHandleTextSubmit();
  });

  // Event Listener for Enter Key in Text Input
  document.getElementById("math-text-input").addEventListener("keypress", function (e) {
    if (e.key === 'Enter') {
      mathHandleTextSubmit();
    }
  });

  // ===== Persisting User Preferences =====

  // Load Preferences on Initialization
  window.addEventListener("load", () => {
    const savedVoice = localStorage.getItem("mathSelectedVoice");
    if (savedVoice !== null && mathVoices[savedVoice]) {
      document.getElementById("math-tools").value = savedVoice;
      mathSpeech.voice = mathVoices[savedVoice];
      logMessage(`Loaded saved voice: ${mathVoices[savedVoice].name}`, "system");
    }

    const savedRate = localStorage.getItem("mathSpeechRate");
    if (savedRate !== null) {
      document.getElementById("math-speech-rate").value = savedRate;
      mathSpeech.rate = parseFloat(savedRate);
      logMessage(`Loaded saved speech rate: ${savedRate}`, "system");
    }

    const savedPitch = localStorage.getItem("mathSpeechPitch");
    if (savedPitch !== null) {
      document.getElementById("math-speech-pitch").value = savedPitch;
      mathSpeech.pitch = parseFloat(savedPitch);
      logMessage(`Loaded saved speech pitch: ${savedPitch}`, "system");
    }
  });

  // Save Speech Rate
  document.getElementById("math-speech-rate").addEventListener("input", (e) => {
    const rate = e.target.value;
    mathSpeech.rate = parseFloat(rate);
    localStorage.setItem("mathSpeechRate", rate);
    logMessage(`Speech rate changed to: ${rate}`, "system");
  });

  // Save Speech Pitch
  document.getElementById("math-speech-pitch").addEventListener("input", (e) => {
    const pitch = e.target.value;
    mathSpeech.pitch = parseFloat(pitch);
    localStorage.setItem("mathSpeechPitch", pitch);
    logMessage(`Speech pitch changed to: ${pitch}`, "system");
  });

  // ===== Logging Function =====

  /**
   * Logs messages to the #math-logs container.
   * @param {string} message - The message to log.
   * @param {string} type - The type of message: 'user', 'assistant', 'system', 'error'.
   */
  function logMessage(message, type) {
    const mathLogs = document.getElementById("math-logs");
    const logEntry = document.createElement("div");
    logEntry.classList.add("log-entry");
    logEntry.textContent = `[${type.toUpperCase()}] ${message}`;

    // Style log entries based on type
    switch(type) {
      case 'user':
        logEntry.style.color = "#00796B";
        break;
      case 'assistant':
        logEntry.style.color = "#004D40";
        break;
      case 'system':
        logEntry.style.color = "#555555";
        break;
      case 'error':
        logEntry.style.color = "#E53935";
        break;
      default:
        logEntry.style.color = "#000000";
    }

    mathLogs.appendChild(logEntry);
    mathLogs.scrollTop = mathLogs.scrollHeight;
  }

  // ===== TTS Integration Continued =====

  // Optional: Global Listener to Detect When All Speech Has Finished
  window.speechSynthesis.addEventListener('end', () => {
    console.log("All advanced math speech has been spoken.");
    logMessage("All TTS messages have been spoken.", "system");
    // Ensure Stop button is disabled after speech ends
    document.getElementById("math-stop_button").disabled = true;
  });
});