Download script.js from fizzarif7/assistant: direct link, hf CLI and curl.
- Browser
- Download file 9.28 kB
-
https://huggingface.co/spaces/fizzarif7/assistant/resolve/main/script.js
- Command line
-
hf download hf://spaces/fizzarif7/assistant/script.js
-
curl -L -o script.js https://huggingface.co/spaces/fizzarif7/assistant/resolve/main/script.js
9.28 kB
| // 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. | |
| }); |