fizzarif7 commited on
Commit
e21f265
·
verified ·
1 Parent(s): ce4fe6e

Update script.js

Browse files
Files changed (1) hide show
  1. script.js +233 -106
script.js CHANGED
@@ -1,106 +1,233 @@
1
- // Handle Generate button click
2
- document.getElementById("generateBtn").addEventListener("click", async () => {
3
- const question = document.getElementById("questionInput").value.trim();
4
- const responseBox = document.getElementById("responseOutput");
5
- const historyBox = document.getElementById("history");
6
-
7
- if (!question) {
8
- responseBox.value = "Please enter your legal question.";
9
- return;
10
- }
11
-
12
- responseBox.value = "Generating...";
13
-
14
- try {
15
- const res = await fetch("/answer", {
16
- method: "POST",
17
- headers: { "Content-Type": "application/json" },
18
- body: JSON.stringify({ question })
19
- });
20
-
21
- const data = await res.json();
22
- const answer = data.answer || "No answer received.";
23
-
24
- responseBox.value = answer;
25
-
26
- // Update top label
27
- document.getElementById("topLabel").innerText = question;
28
-
29
- // Update history
30
- historyBox.value += `\n\nYou: ${question}\nBot: ${answer}`;
31
- } catch (err) {
32
- responseBox.value = `Error: ${err}`;
33
- }
34
- });
35
-
36
- // Handle Reset button
37
- function resetApp() {
38
- document.getElementById("questionInput").value = "";
39
- document.getElementById("responseOutput").value = "";
40
- document.getElementById("topLabel").innerText = "Dictate your legal question!";
41
- }
42
-
43
- // Handle Read Aloud
44
- function readAloud() {
45
- const text = document.getElementById("responseOutput").value;
46
- if (!text.trim()) return;
47
- const synth = window.speechSynthesis;
48
- const utterance = new SpeechSynthesisUtterance(text);
49
- synth.speak(utterance);
50
- }
51
-
52
- // Handle Save
53
- function saveQA() {
54
- const question = document.getElementById("questionInput").value.trim();
55
- const answer = document.getElementById("responseOutput").value.trim();
56
-
57
- if (!question || !answer) {
58
- alert("Nothing to save.");
59
- return;
60
- }
61
-
62
- const blob = new Blob([`Question:\n${question}\n\nAnswer:\n${answer}`], { type: "text/plain" });
63
- const link = document.createElement("a");
64
- link.href = URL.createObjectURL(blob);
65
- link.download = "QnA.txt";
66
- document.body.appendChild(link);
67
- link.click();
68
- document.body.removeChild(link);
69
- }
70
-
71
- // Handle Upload MP3 (Disabled in web)
72
- function uploadMP3() {
73
- alert("📁 MP3 upload is only supported in the desktop assistant.");
74
- }
75
-
76
- // Handle Dictate (Web Speech API)
77
- function handleDictate() {
78
- if (!('webkitSpeechRecognition' in window)) {
79
- alert("Speech recognition not supported in this browser. Use Chrome.");
80
- return;
81
- }
82
-
83
- const recognition = new webkitSpeechRecognition();
84
- recognition.lang = "en-US";
85
- recognition.interimResults = false;
86
- recognition.maxAlternatives = 1;
87
-
88
- document.getElementById("topLabel").innerText = "Listening... 🎙";
89
-
90
- recognition.onresult = function (event) {
91
- const transcript = event.results[0][0].transcript;
92
- document.getElementById("questionInput").value = transcript;
93
- document.getElementById("topLabel").innerText = transcript;
94
- };
95
-
96
- recognition.onerror = function (event) {
97
- console.error("Speech recognition error:", event.error);
98
- document.getElementById("topLabel").innerText = "Could not recognize speech.";
99
- };
100
-
101
- recognition.onend = function () {
102
- console.log("Speech recognition ended.");
103
- };
104
-
105
- recognition.start();
106
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Function to update the top label
2
+ function updateTopLabel(text) {
3
+ document.getElementById("topLabel").innerText = text;
4
+ }
5
+
6
+ // Function to update the history textarea
7
+ function updateHistory(userQuestion, botAnswer) {
8
+ const historyBox = document.getElementById("history");
9
+ const timestamp = new Date().toLocaleTimeString();
10
+ historyBox.value += `\n\n[${timestamp}] You: ${userQuestion}\n[${timestamp}] Bot: ${botAnswer}`;
11
+ historyBox.scrollTop = historyBox.scrollHeight; // Scroll to bottom
12
+ }
13
+
14
+ // Handle Generate button click
15
+ document.getElementById("generateBtn").addEventListener("click", async () => {
16
+ const questionInput = document.getElementById("question"); // Changed from questionInput
17
+ const answerOutput = document.getElementById("answer"); // Changed from responseOutput
18
+ const question = questionInput.value.trim();
19
+
20
+ if (!question) {
21
+ answerOutput.value = "Please enter your legal question.";
22
+ return;
23
+ }
24
+
25
+ answerOutput.value = "Generating...";
26
+ updateTopLabel("Generating answer...");
27
+
28
+ try {
29
+ const res = await fetch("/answer", {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/json" },
32
+ body: JSON.stringify({ question })
33
+ });
34
+
35
+ if (!res.ok) {
36
+ const errorData = await res.json();
37
+ throw new Error(errorData.answer || "Failed to generate answer.");
38
+ }
39
+
40
+ const data = await res.json();
41
+ const answer = data.answer || "No answer received.";
42
+
43
+ answerOutput.value = answer;
44
+ updateTopLabel(question); // Update top label with the question
45
+ updateHistory(question, answer); // Update history with Q&A
46
+
47
+ } catch (err) {
48
+ answerOutput.value = `Error: ${err.message || err}`;
49
+ updateTopLabel("Error generating answer.");
50
+ }
51
+ });
52
+
53
+ // Handle Reset button
54
+ function resetApp() {
55
+ document.getElementById("question").value = "";
56
+ document.getElementById("answer").value = "";
57
+ document.getElementById("topLabel").innerText = "Dictate your legal question!";
58
+ document.getElementById("history").value = ""; // Clear history on reset
59
+ }
60
+
61
+ // Handle Read Aloud (using Web Speech API)
62
+ function readAloud() {
63
+ const text = document.getElementById("answer").value;
64
+ if (!text.trim()) {
65
+ alert("No answer to read aloud.");
66
+ return;
67
+ }
68
+ const synth = window.speechSynthesis;
69
+ // Stop any ongoing speech before starting a new one
70
+ synth.cancel();
71
+ const utterance = new SpeechSynthesisUtterance(text);
72
+ synth.speak(utterance);
73
+ }
74
+
75
+ // Handle Save/Print
76
+ function saveQA() {
77
+ const question = document.getElementById("question").value.trim();
78
+ const answer = document.getElementById("answer").value.trim();
79
+
80
+ if (!question || !answer) {
81
+ alert("Nothing to save.");
82
+ return;
83
+ }
84
+
85
+ const blob = new Blob([`Question:\n${question}\n\nAnswer:\n${answer}`], { type: "text/plain" });
86
+ const link = document.createElement("a");
87
+ link.href = URL.createObjectURL(blob);
88
+ link.download = "Legal_Assistant_QnA.txt";
89
+ document.body.appendChild(link);
90
+ link.click();
91
+ document.body.removeChild(link);
92
+ URL.revokeObjectURL(link.href); // Clean up the URL object
93
+ }
94
+
95
+ // Handle Upload MP3
96
+ async function uploadMP3() {
97
+ const fileInput = document.createElement('input');
98
+ fileInput.type = 'file';
99
+ fileInput.accept = '.mp3';
100
+ fileInput.onchange = async (e) => {
101
+ const file = e.target.files[0];
102
+ if (!file) {
103
+ document.getElementById("answer").value = "No file selected.";
104
+ return;
105
+ }
106
+
107
+ document.getElementById("answer").value = "Uploading and transcribing MP3...";
108
+ updateTopLabel("Processing MP3...");
109
+
110
+ const formData = new FormData();
111
+ formData.append('file', file);
112
+
113
+ try {
114
+ const res = await fetch("/upload-mp3", {
115
+ method: "POST",
116
+ body: formData
117
+ });
118
+
119
+ if (!res.ok) {
120
+ const errorData = await res.json();
121
+ throw new Error(errorData.message || "Failed to upload and transcribe MP3.");
122
+ }
123
+
124
+ const data = await res.json();
125
+ const transcription = data.transcription || "Could not transcribe audio.";
126
+
127
+ updateTopLabel(transcription);
128
+ document.getElementById("question").value = transcription; // Put transcription in question box
129
+ document.getElementById("answer").value = "Transcription complete. You can now summarize or generate an answer.";
130
+
131
+ // Optional: Prompt user to summarize or generate an answer
132
+ const summarizeConfirm = confirm("MP3 transcribed. Do you want to summarize it?");
133
+ if (summarizeConfirm) {
134
+ const summaryRes = await fetch("/summarize", {
135
+ method: "POST",
136
+ headers: { "Content-Type": "application/json" },
137
+ body: JSON.stringify({ text: transcription })
138
+ });
139
+ const summaryData = await summaryRes.json();
140
+ if (summaryRes.ok) {
141
+ document.getElementById("question").value = summaryData.summary;
142
+ document.getElementById("answer").value = "Summary pasted in question box. You can now generate an answer.";
143
+ updateTopLabel("Summary ready.");
144
+ } else {
145
+ document.getElementById("answer").value = `Error summarizing: ${summaryData.summary}`;
146
+ }
147
+ } else {
148
+ const generateConfirm = confirm("Do you want to generate an answer from the full transcription?");
149
+ if (generateConfirm) {
150
+ // Trigger generateAnswer function with the transcription
151
+ document.getElementById("generateBtn").click(); // Simulate click on generate button
152
+ }
153
+ }
154
+
155
+ } catch (err) {
156
+ document.getElementById("answer").value = `Error: ${err.message || err}`;
157
+ updateTopLabel("Error processing MP3.");
158
+ }
159
+ };
160
+ fileInput.click(); // Open file dialog
161
+ }
162
+
163
+ // Handle Dictate (Web Speech API)
164
+ let recognition; // Keep recognition object in scope to stop it
165
+
166
+ function handleDictate() {
167
+ if (!('webkitSpeechRecognition' in window)) {
168
+ alert("Speech recognition not supported in this browser. Use Chrome.");
169
+ return;
170
+ }
171
+
172
+ // If already listening, stop it
173
+ if (recognition && (recognition.recognizing || recognition.continuous)) {
174
+ recognition.stop();
175
+ document.getElementById("topLabel").innerText = "Dictate your legal question!";
176
+ // If you want to automatically trigger answer generation after stopping dictation:
177
+ // document.getElementById("generateBtn").click();
178
+ return;
179
+ }
180
+
181
+ recognition = new webkitSpeechRecognition();
182
+ recognition.lang = "en-US";
183
+ recognition.interimResults = false;
184
+ recognition.maxAlternatives = 1;
185
+ // recognition.continuous = true; // For continuous listening
186
+
187
+ document.getElementById("topLabel").innerText = "Listening... 🎙 (Click Dictate again to stop)";
188
+ document.getElementById("question").value = ""; // Clear previous question
189
+
190
+ recognition.onresult = function (event) {
191
+ const transcript = event.results[0][0].transcript;
192
+ document.getElementById("question").value = transcript;
193
+ updateTopLabel(transcript);
194
+ // Automatically generate answer after dictation
195
+ document.getElementById("generateBtn").click();
196
+ };
197
+
198
+ recognition.onerror = function (event) {
199
+ console.error("Speech recognition error:", event.error);
200
+ document.getElementById("topLabel").innerText = "Could not recognize speech or an error occurred.";
201
+ };
202
+
203
+ recognition.onend = function () {
204
+ console.log("Speech recognition ended.");
205
+ // Only revert label if not actively listening or if an error occurred during listening
206
+ if (!recognition.recognizing) {
207
+ document.getElementById("topLabel").innerText = "Dictate your legal question!";
208
+ }
209
+ };
210
+
211
+ recognition.start();
212
+ }
213
+
214
+
215
+ // Event listeners (ensure they are properly mapped to the new HTML IDs)
216
+ document.addEventListener("DOMContentLoaded", () => {
217
+ // The existing event listener for "generateBtn" is already set up.
218
+ // Ensure the button IDs in HTML match what's used in JS.
219
+ // current IDs:
220
+ // Dictate: handleDictate()
221
+ // Generate Response: generateAnswer() -> now mapped to generateBtn click event
222
+ // Read Aloud: readAloud()
223
+ // Upload MP3: uploadMP3()
224
+ // Save/Print: saveQA()
225
+ // Reset: resetApp()
226
+
227
+ // Add event listeners for other buttons if they don't have inline onclick
228
+ // For example, if you replace onclick="generateAnswer()" with id="generateBtn"
229
+ // then the document.getElementById("generateBtn").addEventListener("click", ...) handles it.
230
+
231
+ // If your HTML buttons use onclick, make sure the function names match these JS functions.
232
+ // Example: <button onclick="handleDictate()">
233
+ });