File size: 9,275 Bytes
e21f265 0bcda00 e21f265 0bcda00 e21f265 0bcda00 e21f265 0bcda00 e21f265 0bcda00 e21f265 0bcda00 e21f265 |
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 |
// Function to update the top label
function updateTopLabel(text) {
document.getElementById("topLabel").innerText = text;
}
// Function to update the history textarea
function updateHistory(userQuestion, botAnswer) {
const historyBox = document.getElementById("history");
const timestamp = new Date().toLocaleTimeString();
historyBox.value += `\n\n[${timestamp}] You: ${userQuestion}\n[${timestamp}] Bot: ${botAnswer}`;
historyBox.scrollTop = historyBox.scrollHeight; // Scroll to bottom
}
// Handle Generate button click
document.getElementById("generateBtn").addEventListener("click", async () => {
const questionInput = document.getElementById("question");
const answerOutput = document.getElementById("answer");
const question = questionInput.value.trim();
if (!question) {
answerOutput.value = "Please enter your legal question.";
return;
}
answerOutput.value = "Generating...";
updateTopLabel("Generating answer...");
try {
const res = await fetch("/answer", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question })
});
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.answer || "Failed to generate answer.");
}
const data = await res.json();
const answer = data.answer || "No answer received.";
answerOutput.value = answer;
updateTopLabel(question); // Update top label with the question
updateHistory(question, answer); // Update history with Q&A
} catch (err) {
answerOutput.value = `Error: ${err.message || err}`;
updateTopLabel("Error generating answer.");
}
});
// Handle Reset button
function resetApp() {
document.getElementById("question").value = "";
document.getElementById("answer").value = "";
document.getElementById("topLabel").innerText = "Dictate your legal question!";
document.getElementById("history").value = ""; // Clear history on reset
// Stop any ongoing speech or recognition
if (window.speechSynthesis && window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
}
if (window.recognition && (window.recognition.recognizing || window.recognition.continuous)) {
window.recognition.stop();
}
}
// Handle Read Aloud (using Web Speech API)
function readAloud() {
const text = document.getElementById("answer").value;
if (!text.trim()) {
alert("No answer to read aloud.");
return;
}
const synth = window.speechSynthesis;
// Stop any ongoing speech before starting a new one
synth.cancel();
const utterance = new SpeechSynthesisUtterance(text);
synth.speak(utterance);
}
// Handle Save/Print with confirmation dialog
function saveQA() {
const question = document.getElementById("question").value.trim();
const answer = document.getElementById("answer").value.trim();
if (!question || !answer) {
alert("Nothing to save.");
return;
}
// Ask for confirmation
const confirmSave = confirm("Are you sure you want to save this Q&A?");
if (confirmSave) {
const blob = new Blob([`Question:\n${question}\n\nAnswer:\n${answer}`], { type: "text/plain" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "Legal_Assistant_QnA.txt";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href); // Clean up the URL object
alert("Q&A saved successfully!");
} else {
alert("Save operation cancelled.");
}
}
// Handle Upload MP3
async function uploadMP3() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.mp3';
fileInput.onchange = async (e) => {
const file = e.target.files[0];
if (!file) {
document.getElementById("answer").value = "No file selected.";
return;
}
document.getElementById("answer").value = "Uploading and transcribing MP3...";
updateTopLabel("Processing MP3...");
const formData = new FormData();
formData.append('file', file);
try {
const res = await fetch("/upload-mp3", {
method: "POST",
body: formData
});
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.message || "Failed to upload and transcribe MP3.");
}
const data = await res.json();
const transcription = data.transcription || "Could not transcribe audio.";
updateTopLabel(transcription);
document.getElementById("question").value = transcription; // Put transcription in question box
document.getElementById("answer").value = "Transcription complete. You can now summarize or generate an answer.";
// Prompt user to summarize or generate an answer
const summarizeConfirm = confirm("MP3 transcribed. Do you want to summarize it?");
if (summarizeConfirm) {
const summaryRes = await fetch("/summarize", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: transcription })
});
const summaryData = await summaryRes.json();
if (summaryRes.ok) {
document.getElementById("question").value = summaryData.summary;
document.getElementById("answer").value = "Summary pasted in question box. You can now generate an answer.";
updateTopLabel("Summary ready.");
} else {
document.getElementById("answer").value = `Error summarizing: ${summaryData.summary}`;
}
} else {
const generateConfirm = confirm("Do you want to generate an answer from the full transcription?");
if (generateConfirm) {
// Trigger generateAnswer function with the transcription
document.getElementById("generateBtn").click(); // Simulate click on generate button
}
}
} catch (err) {
document.getElementById("answer").value = `Error: ${err.message || err}`;
updateTopLabel("Error processing MP3.");
}
};
fileInput.click(); // Open file dialog
}
// Handle Dictate (Web Speech API)
let recognition; // Keep recognition object in scope to stop it
function handleDictate() {
if (!('webkitSpeechRecognition' in window)) {
alert("Speech recognition not supported in this browser. Use Chrome.");
return;
}
// If already listening, stop it
if (recognition && (recognition.recognizing || recognition.continuous)) {
recognition.stop();
document.getElementById("topLabel").innerText = "Dictate your legal question!";
return;
}
recognition = new webkitSpeechRecognition();
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;
// recognition.continuous = true; // For continuous listening
document.getElementById("topLabel").innerText = "Listening... π (Click Dictate again to stop)";
document.getElementById("question").value = ""; // Clear previous question
recognition.onresult = function (event) {
const transcript = event.results[0][0].transcript;
document.getElementById("question").value = transcript;
updateTopLabel(transcript);
// Automatically generate answer after dictation
document.getElementById("generateBtn").click();
};
recognition.onerror = function (event) {
console.error("Speech recognition error:", event.error);
document.getElementById("topLabel").innerText = "Could not recognize speech or an error occurred.";
};
recognition.onend = function () {
console.log("Speech recognition ended.");
// Only revert label if not actively listening or if an error occurred during listening
if (!recognition.recognizing) {
document.getElementById("topLabel").innerText = "Dictate your legal question!";
}
};
recognition.start();
}
// Event listeners (ensure they are properly mapped to the new HTML IDs)
document.addEventListener("DOMContentLoaded", () => {
// The existing event listener for "generateBtn" is already set up.
// Ensure the button IDs in HTML match what's used in JS.
// If your HTML buttons use onclick, make sure the function names match these JS functions.
// The current index.html uses onclick for all buttons:
// <button onclick="handleDictate()">π Dictate</button>
// <button onclick="generateAnswer()">π§Ύ Generate Response</button>
// <button onclick="readAloud()">π Read Aloud</button>
// <button onclick="uploadMP3()">π΅ Upload MP3</button>
// <button onclick="saveQA()">π¨ Save/Print</button>
// <button onclick="resetApp()">π§Ή Reset</button>
// Important: Your index.html currently has `onclick="generateAnswer()"`.
// For the `document.getElementById("generateBtn").addEventListener("click", ...)`
// in script.js to work, you need to change the HTML button to have an `id="generateBtn"`
// instead of `onclick="generateAnswer()"`.
// So, in index.html, change:
// <button onclick="generateAnswer()">π§Ύ Generate Response</button>
// TO:
// <button id="generateBtn">π§Ύ Generate Response</button>
// The current script.js is already set up to listen to an ID.
}); |