Spaces:
Sleeping
Sleeping
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>CogniChat - Chat with your Documents</title> | |
| <script src="https://cdn.tailwindcss.com"></script> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> | |
| <link href="https://fonts.googleapis.com/css2?family=Google+Sans:wght@400;500;700&family=Roboto:wght@400;500&display=swap" rel="stylesheet"> | |
| <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> | |
| <style> | |
| :root { | |
| --background: #f0f4f9; | |
| --foreground: #1f1f1f; | |
| --primary: #1a73e8; | |
| --primary-hover: #1867cf; | |
| --card: #ffffff; | |
| --card-border: #dadce0; | |
| --input-bg: #e8f0fe; | |
| --user-bubble: #d9e7ff; | |
| --bot-bubble: #f1f3f4; | |
| } | |
| /* Dark mode styles */ | |
| .dark { | |
| --background: #202124; | |
| --foreground: #e8eaed; | |
| --primary: #8ab4f8; | |
| --primary-hover: #99bdfa; | |
| --card: #303134; | |
| --card-border: #5f6368; | |
| --input-bg: #303134; | |
| --user-bubble: #3c4043; | |
| --bot-bubble: #3c4043; | |
| } | |
| body { | |
| font-family: 'Google Sans', 'Roboto', sans-serif; | |
| background-color: var(--background); | |
| color: var(--foreground); | |
| overflow: hidden; | |
| } | |
| #chat-window::-webkit-scrollbar { width: 8px; } | |
| #chat-window::-webkit-scrollbar-track { background: transparent; } | |
| #chat-window::-webkit-scrollbar-thumb { background-color: #bdc1c6; border-radius: 20px; } | |
| .dark #chat-window::-webkit-scrollbar-thumb { background-color: #5f6368; } | |
| .drop-zone--over { | |
| border-color: var(--primary); | |
| box-shadow: 0 0 15px rgba(26, 115, 232, 0.3); | |
| } | |
| /* Loading Spinner */ | |
| .loader { | |
| width: 48px; | |
| height: 48px; | |
| border: 3px solid var(--card-border); | |
| border-radius: 50%; | |
| display: inline-block; | |
| position: relative; | |
| box-sizing: border-box; | |
| animation: rotation 1s linear infinite; | |
| } | |
| .loader::after { | |
| content: ''; | |
| box-sizing: border-box; | |
| position: absolute; | |
| left: 50%; | |
| top: 50%; | |
| transform: translate(-50%, -50%); | |
| width: 56px; | |
| height: 56px; | |
| border-radius: 50%; | |
| border: 3px solid; | |
| border-color: var(--primary) transparent; | |
| } | |
| @keyframes rotation { | |
| 0% { transform: rotate(0deg); } | |
| 100% { transform: rotate(360deg); } | |
| } | |
| /* Typing Indicator Animation */ | |
| .typing-indicator span { | |
| height: 10px; | |
| width: 10px; | |
| background-color: #9E9E9E; | |
| border-radius: 50%; | |
| display: inline-block; | |
| animation: bounce 1.4s infinite ease-in-out both; | |
| } | |
| .typing-indicator span:nth-child(1) { animation-delay: -0.32s; } | |
| .typing-indicator span:nth-child(2) { animation-delay: -0.16s; } | |
| @keyframes bounce { | |
| 0%, 80%, 100% { transform: scale(0); } | |
| 40% { transform: scale(1.0); } | |
| } | |
| /* Enhanced Markdown Styling for better readability and aesthetics */ | |
| .markdown-content p { | |
| margin-bottom: 1rem; | |
| line-height: 1.75; | |
| } | |
| .markdown-content h1, .markdown-content h2, .markdown-content h3, .markdown-content h4 { | |
| font-family: 'Google Sans', sans-serif; | |
| font-weight: 700; | |
| margin-top: 1.75rem; | |
| margin-bottom: 1rem; | |
| line-height: 1.3; | |
| } | |
| .markdown-content h1 { font-size: 1.75em; border-bottom: 1px solid var(--card-border); padding-bottom: 0.5rem; } | |
| .markdown-content h2 { font-size: 1.5em; } | |
| .markdown-content h3 { font-size: 1.25em; } | |
| .markdown-content h4 { font-size: 1.1em; } | |
| .markdown-content ul, .markdown-content ol { | |
| padding-left: 1.75rem; | |
| margin-bottom: 1rem; | |
| } | |
| .markdown-content li { | |
| margin-bottom: 0.5rem; | |
| } | |
| .dark .markdown-content ul > li::marker { color: var(--primary); } | |
| .markdown-content ul > li::marker { color: var(--primary); } | |
| .markdown-content a { | |
| color: var(--primary); | |
| text-decoration: none; | |
| font-weight: 500; | |
| border-bottom: 1px solid transparent; | |
| transition: all 0.2s ease-in-out; | |
| } | |
| .markdown-content a:hover { | |
| border-bottom-color: var(--primary-hover); | |
| } | |
| .markdown-content blockquote { | |
| margin: 1.5rem 0; | |
| padding-left: 1.5rem; | |
| border-left: 4px solid var(--card-border); | |
| color: #6c757d; | |
| font-style: italic; | |
| } | |
| .dark .markdown-content blockquote { | |
| color: #adb5bd; | |
| } | |
| .markdown-content hr { | |
| border: none; | |
| border-top: 1px solid var(--card-border); | |
| margin: 2rem 0; | |
| } | |
| .markdown-content table { | |
| width: 100%; | |
| border-collapse: collapse; | |
| margin: 1.5rem 0; | |
| font-size: 0.9em; | |
| box-shadow: 0 1px 3px rgba(0,0,0,0.05); | |
| border-radius: 8px; | |
| overflow: hidden; | |
| } | |
| .markdown-content th, .markdown-content td { | |
| border: 1px solid var(--card-border); | |
| padding: 0.75rem 1rem; | |
| text-align: left; | |
| } | |
| .markdown-content th { | |
| background-color: var(--bot-bubble); | |
| font-weight: 500; | |
| } | |
| .markdown-content code { | |
| background-color: rgba(0,0,0,0.05); | |
| padding: 0.2rem 0.4rem; | |
| border-radius: 0.25rem; | |
| font-family: 'Roboto Mono', monospace; | |
| font-size: 0.9em; | |
| } | |
| .dark .markdown-content code { | |
| background-color: rgba(255,255,255,0.1); | |
| } | |
| .markdown-content pre { | |
| position: relative; | |
| background-color: #f8f9fa; | |
| border: 1px solid var(--card-border); | |
| border-radius: 0.5rem; | |
| margin-bottom: 1rem; | |
| } | |
| .dark .markdown-content pre { | |
| background-color: #2e2f32; | |
| } | |
| .markdown-content pre code { | |
| background: none; | |
| padding: 1rem; | |
| display: block; | |
| overflow-x: auto; | |
| } | |
| .markdown-content pre .copy-code-btn { | |
| position: absolute; | |
| top: 0.5rem; | |
| right: 0.5rem; | |
| background-color: #e8eaed; | |
| border: 1px solid #dadce0; | |
| color: #5f6368; | |
| padding: 0.3rem 0.6rem; | |
| border-radius: 0.25rem; | |
| cursor: pointer; | |
| opacity: 0; | |
| transition: opacity 0.2s; | |
| font-size: 0.8em; | |
| } | |
| .dark .markdown-content pre .copy-code-btn { | |
| background-color: #3c4043; | |
| border-color: #5f6368; | |
| color: #e8eaed; | |
| } | |
| .markdown-content pre:hover .copy-code-btn { | |
| opacity: 1; | |
| } | |
| /* Spinner for the TTS button */ | |
| .tts-button-loader { | |
| width: 16px; | |
| height: 16px; | |
| border: 2px solid currentColor; /* Use button's text color */ | |
| border-radius: 50%; | |
| display: inline-block; | |
| box-sizing: border-box; | |
| animation: rotation 0.8s linear infinite; | |
| border-bottom-color: transparent; /* Makes it a half circle spinner */ | |
| } | |
| </style> | |
| </head> | |
| <body class="w-screen h-screen dark"> | |
| <main id="main-content" class="h-full flex flex-col transition-opacity duration-500"> | |
| <div id="chat-container" class="hidden flex-1 flex flex-col w-full mx-auto overflow-hidden"> | |
| <header class="text-center p-4 border-b border-[var(--card-border)] flex-shrink-0"> | |
| <h1 class="text-xl font-medium">Chat with your Docs</h1> | |
| <p id="chat-filename" class="text-xs text-gray-500 dark:text-gray-400 mt-1"></p> | |
| </header> | |
| <div id="chat-window" class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-10"> | |
| <div id="chat-content" class="max-w-4xl mx-auto space-y-8"> | |
| </div> | |
| </div> | |
| <div class="p-4 flex-shrink-0 bg-[var(--background)] border-t border-[var(--card-border)]"> | |
| <form id="chat-form" class="max-w-4xl mx-auto bg-[var(--card)] rounded-full p-2 flex items-center shadow-sm border border-transparent focus-within:border-[var(--primary)] transition-colors"> | |
| <input type="text" id="chat-input" placeholder="Ask a question about your documents..." class="flex-grow bg-transparent focus:outline-none px-4 text-sm" autocomplete="off"> | |
| <button type="submit" id="chat-submit-btn" class="bg-[var(--primary)] hover:bg-[var(--primary-hover)] text-white p-2 rounded-full transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-gray-500" title="Send"> | |
| <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3.49941 11.5556L11.555 3.5L12.4438 4.38889L6.27721 10.5556H21.9994V11.5556H6.27721L12.4438 17.7222L11.555 18.6111L3.49941 10.5556V11.5556Z" transform="rotate(180, 12.7497, 11.0556)" fill="currentColor"></path></svg> | |
| </button> | |
| </form> | |
| </div> | |
| </div> | |
| <div id="upload-container" class="flex-1 flex flex-col items-center justify-center p-8 transition-opacity duration-300"> | |
| <div class="text-center"> | |
| <h1 class="text-5xl font-medium mb-4">Upload docs to chat</h1> | |
| <div id="drop-zone" class="w-full max-w-lg text-center border-2 border-dashed border-[var(--card-border)] rounded-2xl p-10 transition-all duration-300 cursor-pointer bg-[var(--card)] hover:border-[var(--primary)]"> | |
| <input id="file-upload" type="file" class="hidden" accept=".pdf,.txt,.docx,.jpg,.jpeg,.png" multiple title="input"> | |
| <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" ><path stroke-linecap="round" stroke-linejoin="round" d="M12 16.5V9.75m0 0l3-3m-3 3l-3 3M6.75 19.5a4.5 4.5 0 01-1.41-8.775 5.25 5.25 0 0110.233-2.33 3 3 0 013.758 3.848A3.752 3.752 0 0118 19.5H6.75z"></path></svg> | |
| <p class="mt-4 text-sm font-medium">Drag & drop files or click to upload</p> | |
| <p id="file-name" class="mt-2 text-xs text-gray-500"></p> | |
| </div> | |
| </div> | |
| </div> | |
| <div id="loading-overlay" class="hidden fixed inset-0 bg-[var(--background)] bg-opacity-80 backdrop-blur-sm flex flex-col items-center justify-center z-50 text-center p-4"> | |
| <div class="loader"></div> | |
| <p id="loading-text" class="mt-6 text-sm font-medium"></p> | |
| <p id="loading-subtext" class="mt-2 text-xs text-gray-500 dark:text-gray-400"></p> | |
| </div> | |
| </main> | |
| <script> | |
| document.addEventListener('DOMContentLoaded', () => { | |
| const uploadContainer = document.getElementById('upload-container'); | |
| const chatContainer = document.getElementById('chat-container'); | |
| const dropZone = document.getElementById('drop-zone'); | |
| const fileUploadInput = document.getElementById('file-upload'); | |
| const fileNameSpan = document.getElementById('file-name'); | |
| const loadingOverlay = document.getElementById('loading-overlay'); | |
| const loadingText = document.getElementById('loading-text'); | |
| const loadingSubtext = document.getElementById('loading-subtext'); | |
| const chatForm = document.getElementById('chat-form'); | |
| const chatInput = document.getElementById('chat-input'); | |
| const chatSubmitBtn = document.getElementById('chat-submit-btn'); | |
| const chatWindow = document.getElementById('chat-window'); | |
| const chatContent = document.getElementById('chat-content'); | |
| const chatFilename = document.getElementById('chat-filename'); | |
| let sessionId = null; | |
| const storedSessionId = sessionStorage.getItem('cognichat_session_id'); | |
| if (storedSessionId) { | |
| sessionId = storedSessionId; | |
| console.debug('Restored session ID from storage:', sessionId); | |
| } | |
| // --- File Upload Logic --- | |
| dropZone.addEventListener('click', () => fileUploadInput.click()); | |
| ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { | |
| dropZone.addEventListener(eventName, preventDefaults, false); | |
| document.body.addEventListener(eventName, preventDefaults, false); | |
| }); | |
| ['dragenter', 'dragover'].forEach(eventName => { | |
| dropZone.addEventListener(eventName, () => dropZone.classList.add('drop-zone--over')); | |
| }); | |
| ['dragleave', 'drop'].forEach(eventName => { | |
| dropZone.addEventListener(eventName, () => dropZone.classList.remove('drop-zone--over')); | |
| }); | |
| dropZone.addEventListener('drop', (e) => { | |
| const files = e.dataTransfer.files; | |
| if (files.length > 0) handleFiles(files); | |
| }); | |
| fileUploadInput.addEventListener('change', (e) => { | |
| if (e.target.files.length > 0) handleFiles(e.target.files); | |
| }); | |
| function preventDefaults(e) { e.preventDefault(); e.stopPropagation(); } | |
| async function handleFiles(files) { | |
| const formData = new FormData(); | |
| let fileNames = []; | |
| for (const file of files) { | |
| formData.append('file', file); | |
| fileNames.push(file.name); | |
| } | |
| fileNameSpan.textContent = `Selected: ${fileNames.join(', ')}`; | |
| await uploadAndProcessFiles(formData, fileNames); | |
| } | |
| async function uploadAndProcessFiles(formData, fileNames) { | |
| loadingOverlay.classList.remove('hidden'); | |
| loadingText.textContent = `Processing ${fileNames.length} document(s)...`; | |
| loadingSubtext.textContent = "🤓Creating a knowledge base may take a minute or two. So please hold on tight"; | |
| try { | |
| const response = await fetch('/upload', { method: 'POST', body: formData }); | |
| const result = await response.json(); | |
| if (!response.ok) throw new Error(result.message || 'Unknown error occurred.'); | |
| if (result.session_id) { | |
| sessionId = result.session_id; | |
| sessionStorage.setItem('cognichat_session_id', sessionId); | |
| console.debug('Stored session ID from upload:', sessionId); | |
| } else { | |
| console.warn('Upload response missing session_id field.'); | |
| } | |
| chatFilename.textContent = `Chatting with: ${result.filename}`; | |
| uploadContainer.classList.add('hidden'); | |
| chatContainer.classList.remove('hidden'); | |
| appendMessage("I've analyzed your documents. What would you like to know?", "bot"); | |
| } catch (error) { | |
| console.error('Upload error:', error); | |
| alert(`Error: ${error.message}`); | |
| } finally { | |
| loadingOverlay.classList.add('hidden'); | |
| loadingSubtext.textContent = ''; | |
| fileNameSpan.textContent = ''; | |
| fileUploadInput.value = ''; | |
| } | |
| } | |
| // --- Chat Logic --- | |
| chatForm.addEventListener('submit', async (e) => { | |
| e.preventDefault(); | |
| const question = chatInput.value.trim(); | |
| if (!question) return; | |
| appendMessage(question, 'user'); | |
| chatInput.value = ''; | |
| chatInput.disabled = true; | |
| chatSubmitBtn.disabled = true; | |
| const typingIndicator = showTypingIndicator(); | |
| let botMessageContainer = null; | |
| let contentDiv = null; | |
| try { | |
| const requestBody = { question: question }; | |
| if (sessionId) { | |
| requestBody.session_id = sessionId; | |
| } | |
| const response = await fetch('/chat', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(requestBody), | |
| }); | |
| if (!response.ok) throw new Error(`Server error: ${response.statusText}`); | |
| // ============================ MODIFICATION START ============================== | |
| // Parse the JSON response instead of reading a stream | |
| const result = await response.json(); | |
| const answer = result.answer; // Extract the 'answer' field | |
| if (!answer) { | |
| throw new Error("Received an empty or invalid response from the server."); | |
| } | |
| typingIndicator.remove(); | |
| botMessageContainer = appendMessage('', 'bot'); | |
| contentDiv = botMessageContainer.querySelector('.markdown-content'); | |
| // Use the extracted answer for rendering | |
| contentDiv.innerHTML = marked.parse(answer); | |
| contentDiv.querySelectorAll('pre').forEach(addCopyButton); | |
| scrollToBottom(); // Scroll after content is added | |
| // Use the extracted answer for TTS | |
| addTextToSpeechControls(botMessageContainer, answer); | |
| // ============================ MODIFICATION END ============================== | |
| } catch (error) { | |
| console.error('Chat error:', error); | |
| if (typingIndicator) typingIndicator.remove(); | |
| if (contentDiv) { | |
| contentDiv.innerHTML = `<p class="text-red-500">Error: ${error.message}</p>`; | |
| } else { | |
| appendMessage(`Error: ${error.message}`, 'bot'); | |
| } | |
| } finally { | |
| chatInput.disabled = false; | |
| chatSubmitBtn.disabled = false; | |
| chatInput.focus(); | |
| } | |
| }); | |
| // --- UI Helper Functions --- | |
| function appendMessage(text, sender) { | |
| const messageWrapper = document.createElement('div'); | |
| messageWrapper.className = `flex items-start gap-4`; | |
| const iconSVG = sender === 'user' | |
| ? `<div class="bg-blue-100 dark:bg-gray-700 p-2.5 rounded-full flex-shrink-0 mt-1"><svg class="w-5 h-5 text-blue-600 dark:text-blue-300" viewBox="0 0 24 24"><path fill="currentColor" d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"></path></svg></div>` | |
| : `<div class="bg-gray-200 dark:bg-gray-700 rounded-full flex-shrink-0 mt-1 text-xl flex items-center justify-center w-10 h-10">✨</div>`; | |
| const messageBubble = document.createElement('div'); | |
| messageBubble.className = `flex-1 pt-1`; | |
| const senderName = document.createElement('p'); | |
| senderName.className = 'font-medium text-sm mb-1'; | |
| senderName.textContent = sender === 'user' ? 'You' : 'CogniChat'; | |
| const contentDiv = document.createElement('div'); | |
| contentDiv.className = 'text-base markdown-content'; | |
| // Only parse if text is not empty | |
| if (text) { | |
| contentDiv.innerHTML = marked.parse(text); | |
| } | |
| const controlsContainer = document.createElement('div'); | |
| controlsContainer.className = 'tts-controls mt-2'; | |
| messageBubble.appendChild(senderName); | |
| messageBubble.appendChild(contentDiv); | |
| messageBubble.appendChild(controlsContainer); | |
| messageWrapper.innerHTML = iconSVG; | |
| messageWrapper.appendChild(messageBubble); | |
| chatContent.appendChild(messageWrapper); | |
| scrollToBottom(); | |
| return messageBubble; | |
| } | |
| function showTypingIndicator() { | |
| const indicatorWrapper = document.createElement('div'); | |
| indicatorWrapper.className = `flex items-start gap-4`; | |
| indicatorWrapper.id = 'typing-indicator'; | |
| const iconSVG = `<div class="bg-gray-200 dark:bg-gray-700 rounded-full flex-shrink-0 mt-1 text-xl flex items-center justify-center w-10 h-10">✨</div>`; | |
| const messageBubble = document.createElement('div'); | |
| messageBubble.className = 'flex-1 pt-1'; | |
| const senderName = document.createElement('p'); | |
| senderName.className = 'font-medium text-sm mb-1'; | |
| senderName.textContent = 'CogniChat is thinking...'; | |
| const indicator = document.createElement('div'); | |
| indicator.className = 'typing-indicator'; | |
| indicator.innerHTML = '<span></span><span></span><span></span>'; | |
| messageBubble.appendChild(senderName); | |
| messageBubble.appendChild(indicator); | |
| indicatorWrapper.innerHTML = iconSVG; | |
| indicatorWrapper.appendChild(messageBubble); | |
| chatContent.appendChild(indicatorWrapper); | |
| scrollToBottom(); | |
| return indicatorWrapper; | |
| } | |
| function scrollToBottom() { | |
| chatWindow.scrollTo({ | |
| top: chatWindow.scrollHeight, | |
| behavior: 'smooth' | |
| }); | |
| } | |
| function addCopyButton(pre) { | |
| const button = document.createElement('button'); | |
| button.className = 'copy-code-btn'; | |
| button.textContent = 'Copy'; | |
| pre.appendChild(button); | |
| button.addEventListener('click', () => { | |
| const code = pre.querySelector('code').innerText; | |
| navigator.clipboard.writeText(code).then(() => { | |
| button.textContent = 'Copied!'; | |
| setTimeout(() => button.textContent = 'Copy', 2000); | |
| }); | |
| }); | |
| } | |
| // --- Text-to-Speech Logic --- | |
| let currentAudio = null; | |
| let currentPlayingButton = null; | |
| const playIconSVG = `<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>`; | |
| const pauseIconSVG = `<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>`; | |
| function addTextToSpeechControls(messageBubble, text) { | |
| const ttsControls = messageBubble.querySelector('.tts-controls'); | |
| if (text.trim().length > 0) { | |
| const speakButton = document.createElement('button'); | |
| speakButton.className = 'speak-btn px-4 py-2 bg-blue-700 text-white rounded-full text-sm font-medium hover:bg-blue-800 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed'; | |
| speakButton.title = 'Listen to this message'; | |
| speakButton.setAttribute('data-state', 'play'); | |
| speakButton.innerHTML = `${playIconSVG} <span>Play</span>`; | |
| ttsControls.appendChild(speakButton); | |
| speakButton.addEventListener('click', () => handleTTS(text, speakButton)); | |
| } | |
| } | |
| async function handleTTS(text, button) { | |
| if (button === currentPlayingButton) { | |
| if (currentAudio && !currentAudio.paused) { | |
| currentAudio.pause(); | |
| button.setAttribute('data-state', 'paused'); | |
| button.innerHTML = `${playIconSVG} <span>Play</span>`; | |
| } else if (currentAudio && currentAudio.paused) { | |
| currentAudio.play(); | |
| button.setAttribute('data-state', 'playing'); | |
| button.innerHTML = `${pauseIconSVG} <span>Pause</span>`; | |
| } | |
| return; | |
| } | |
| resetAllSpeakButtons(); | |
| currentPlayingButton = button; | |
| button.setAttribute('data-state', 'loading'); | |
| button.innerHTML = `<div class="tts-button-loader"></div> <span>Loading...</span>`; | |
| button.disabled = true; | |
| try { | |
| const response = await fetch('/tts', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ text: text }) | |
| }); | |
| if (!response.ok) throw new Error('Failed to generate audio.'); | |
| const blob = await response.blob(); | |
| const audioUrl = URL.createObjectURL(blob); | |
| currentAudio = new Audio(audioUrl); | |
| currentAudio.play(); | |
| button.setAttribute('data-state', 'playing'); | |
| button.innerHTML = `${pauseIconSVG} <span>Pause</span>`; | |
| currentAudio.onended = () => { | |
| button.setAttribute('data-state', 'play'); | |
| button.innerHTML = `${playIconSVG} <span>Play</span>`; | |
| currentAudio = null; | |
| currentPlayingButton = null; | |
| }; | |
| } catch (error) { | |
| console.error('TTS Error:', error); | |
| button.setAttribute('data-state', 'error'); | |
| button.innerHTML = `${playIconSVG} <span>Error</span>`; | |
| alert('Failed to play audio. Please try again.'); | |
| resetAllSpeakButtons(); | |
| } finally { | |
| button.disabled = false; | |
| } | |
| } | |
| function resetAllSpeakButtons() { | |
| document.querySelectorAll('.speak-btn').forEach(btn => { | |
| btn.setAttribute('data-state', 'play'); | |
| btn.innerHTML = `${playIconSVG} <span>Play</span>`; | |
| btn.disabled = false; | |
| }); | |
| if (currentAudio) { | |
| currentAudio.pause(); | |
| currentAudio = null; | |
| } | |
| currentPlayingButton = null; | |
| } | |
| }); | |
| </script> | |
| </body> | |
| </html> |