index.html: <!DOCTYPE html> <html lang="ar"> <head> <meta charset="UTF-8"> <meta…
- User
index.html:
<!-- مرئي التحدث --> <div id="visualizerContainer" class="mb-8"> <canvas id="visualizer"></canvas> <div id="circleVisualizer" class="circle hidden"></div> </div> <!-- التحكم في المحادثة --> <div class="w-2/3 flex flex-col items-center"> <button id="talkButton" onclick="toggleChat()" class="bg-green-500 px-6 py-3 mt-6 rounded hover:bg-green-700 w-full"> 🎤 ابدأ المحادثة </button> <button id="stopButton" onclick="stopRecognition()" class="bg-red-500 px-6 py-3 mt-4 rounded hover:bg-red-700 w-full hidden"> ⛔ إيقاف المحادثة </button> </div> <!-- سجل المحادثة --> <div id="historyContainer" class="mt-8 p-4 bg-gray-800 rounded w-2/3 overflow-auto max-h-96"> <!-- ستتم إضافة الرسائل هنا --> </div> <script src="/static/script.js" defer></script>script.js: const historyContainer = document.getElementById('historyContainer'); const talkButton = document.getElementById('talkButton'); const stopButton = document.getElementById('stopButton'); const circleVisualizer = document.getElementById('circleVisualizer');
let recognition; let isListening = false;
// سجل المحادثة let conversationHistory = [];
// تحميل سجل المحادثة من Local Storage function loadConversationHistory() { const history = localStorage.getItem('conversationHistory'); if (history) { conversationHistory = JSON.parse(history); displayConversationHistory(); } }
// حفظ سجل المحادثة إلى Local Storage function saveConversationHistory() { localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory)); }
// عرض سجل المحادثة function displayConversationHistory() { historyContainer.innerHTML = ''; conversationHistory.forEach(item => { const messageDiv = document.createElement('div'); messageDiv.className = 'mb-4';
// رسالة المستخدم const userMessageDiv = document.createElement('div'); userMessageDiv.className = 'text-right'; const userMessageSpan = document.createElement('span'); userMessageSpan.className = 'user-message'; userMessageSpan.textContent = item.user; userMessageDiv.appendChild(userMessageSpan); // رسالة الذكاء الاصطناعي const aiMessageDiv = document.createElement('div'); aiMessageDiv.className = 'text-left'; const aiMessageSpan = document.createElement('span'); aiMessageSpan.className = 'ai-message'; aiMessageSpan.textContent = item.ai; aiMessageDiv.appendChild(aiMessageSpan); messageDiv.appendChild(userMessageDiv); messageDiv.appendChild(aiMessageDiv); historyContainer.appendChild(messageDiv); }); // التمرير إلى الأسفل historyContainer.scrollTop = historyContainer.scrollHeight;}
// إعداد Web Speech API function initRecognition() { recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)(); recognition.lang = 'ar-SA'; recognition.interimResults = false; recognition.maxAlternatives = 1;
recognition.onstart = function() { circleVisualizer.classList.remove('hidden'); }; recognition.onend = function() { circleVisualizer.classList.add('hidden'); }; recognition.onresult = async function(event) { const transcript = event.results[0][0].transcript; addMessageToHistory('user', transcript); await sendMessage(transcript); if (isListening) { recognition.start(); } }; recognition.onerror = function(event) { console.error('خطأ في التعرف على الكلام:', event.error); if (isListening) { recognition.start(); } };}
// بدء المحادثة async function toggleChat() { isListening = true; talkButton.classList.add('hidden'); stopButton.classList.remove('hidden');
if (!recognition) initRecognition(); recognition.start();}
// إيقاف المحادثة function stopRecognition() { isListening = false; recognition.stop(); talkButton.classList.remove('hidden'); stopButton.classList.add('hidden'); }
// إرسال الرسالة إلى الخادم والحصول على الرد async function sendMessage(message) { try { const response = await fetch('/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: message }) });
const result = await response.json(); addMessageToHistory('ai', result.response); // تشغيل الرد باستخدام تحويل النص إلى كلام await playAudio(result.response); } catch (error) { console.error('خطأ في إرسال الرسالة:', error); }}
// إضافة الرسائل إلى السجل function addMessageToHistory(sender, message) { if (sender === 'user') { conversationHistory.push({ user: message, ai: '' }); } else if (sender === 'ai') { conversationHistory[conversationHistory.length - 1].ai = message; } displayConversationHistory(); saveConversationHistory(); }
// تحويل النص إلى كلام وتشغيله async function playAudio(text) { try { const response = await fetch('/text-to-speech', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: text }) });
const audioBlob = await response.blob(); const audioUrl = URL.createObjectURL(audioBlob); const audio = new Audio(audioUrl); audio.onplay = function() { circleVisualizer.classList.remove('hidden'); }; audio.onended = function() { circleVisualizer.classList.add('hidden'); if (isListening) { recognition.start(); } }; await audio.play(); } catch (error) { console.error('خطأ في تشغيل الصوت:', error); }}
// تحميل سجل المحادثة عند تحميل الصفحة loadConversationHistory();
improve this code make it more modern and make circle visualizer visualize with audio more modern ok chat show with button slide button under the website and also use daisyui use
- Assistant
Certainly! Let's enhance your AI chat application by modernizing the UI, improving the audio visualizer, and incorporating DaisyUI for streamlined component styling. Below are the updated
index.htmlandscript.jsfiles with detailed explanations of the changes made.
Updated
index.html<!DOCTYPE html> <html lang="ar"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>محادثة الذكاء الاصطناعي</title> <!-- Tailwind CSS with DaisyUI --> <script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.jsdelivr.net/npm/daisyui@4.12.14/dist/full.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/daisyui@4.12.14/dist/full.min.css" rel="stylesheet"> <style> @import url('https://fonts.googleapis.com/css2?family=Amiri:wght@400;700&display=swap'); body { font-family: 'Amiri', serif; background-color: #1a1a1a; } /* Improved Audio Visualizer Styles */ #visualizerContainer { width: 150px; height: 150px; margin: 0 auto; position: relative; } canvas { width: 100%; height: 100%; border-radius: 50%; background: transparent; } /* Message Styles with DaisyUI */ .user-message { @apply bg-primary text-white p-3 rounded-tr-xl rounded-br-xl rounded-bl-xl max-w-3/4; } .ai-message { @apply bg-secondary text-white p-3 rounded-tl-xl rounded-bl-xl rounded-br-xl max-w-3/4; } /* Slide Button Styles */ #slideButton { position: fixed; bottom: 4rem; right: 1rem; z-index: 50; } </style> </head> <body class="text-white flex flex-col items-center justify-center min-h-screen relative"> <h1 class="text-4xl mb-8">محادثة الذكاء الاصطناعي</h1> <!-- Audio Visualizer --> <div id="visualizerContainer" class="mb-8"> <canvas id="visualizer"></canvas> </div> <!-- Control Buttons --> <div class="flex flex-col items-center w-2/3"> <button id="talkButton" onclick="toggleChat()" class="btn btn-success btn-wide mb-4"> 🎤 ابدأ المحادثة </button> <button id="stopButton" onclick="stopRecognition()" class="btn btn-error btn-wide hidden"> ⛔ إيقاف المحادثة </button> </div> <!-- Chat History --> <div id="historyContainer" class="mt-8 p-4 bg-base-300 rounded w-2/3 overflow-auto max-h-96"> <!-- Messages will be appended here --> </div> <!-- Slide Button --> <button id="slideButton" class="btn btn-primary"> 💬 المحادثة </button> <script src="/static/script.js" defer></script> </body> </html>Key Enhancements:
-
Tailwind CSS and DaisyUI Integration:
- Included Tailwind CSS and DaisyUI via CDN for utility-first styling and pre-designed components, respectively.
- Utilized DaisyUI classes like
btn,btn-success,btn-error, andbtn-primaryfor consistent and responsive button designs.
-
Modern Audio Visualizer:
- Replaced the CSS-based circle visualizer with a canvas-based visualizer that reacts to actual audio input, providing a more dynamic and engaging experience.
-
Responsive Slide Button:
- Added a fixed slide button at the bottom-right corner using DaisyUI styles, allowing users to toggle the chat interface easily.
-
Enhanced Message Styling:
- Utilized Tailwind's
@applydirective with DaisyUI classes to style user and AI messages, ensuring a modern and cohesive look.
- Utilized Tailwind's
Updated
script.js// Select DOM elements const historyContainer = document.getElementById('historyContainer'); const talkButton = document.getElementById('talkButton'); const stopButton = document.getElementById('stopButton'); const slideButton = document.getElementById('slideButton'); const visualizer = document.getElementById('visualizer'); let recognition; let isListening = false; // Conversation History let conversationHistory = []; // Load Conversation History from Local Storage function loadConversationHistory() { const history = localStorage.getItem('conversationHistory'); if (history) { conversationHistory = JSON.parse(history); displayConversationHistory(); } } // Save Conversation History to Local Storage function saveConversationHistory() { localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory)); } // Display Conversation History function displayConversationHistory() { historyContainer.innerHTML = ''; conversationHistory.forEach(item => { // User Message if (item.user) { const userDiv = document.createElement('div'); userDiv.className = 'text-right mb-2'; const userSpan = document.createElement('span'); userSpan.className = 'user-message'; userSpan.textContent = item.user; userDiv.appendChild(userSpan); historyContainer.appendChild(userDiv); } // AI Message if (item.ai) { const aiDiv = document.createElement('div'); aiDiv.className = 'text-left mb-2'; const aiSpan = document.createElement('span'); aiSpan.className = 'ai-message'; aiSpan.textContent = item.ai; aiDiv.appendChild(aiSpan); historyContainer.appendChild(aiDiv); } }); // Scroll to Bottom historyContainer.scrollTop = historyContainer.scrollHeight; } // Initialize Speech Recognition function initRecognition() { const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SpeechRecognition) { alert('متصفحك لا يدعم التعرف على الكلام.'); return; } recognition = new SpeechRecognition(); recognition.lang = 'ar-SA'; recognition.interimResults = false; recognition.maxAlternatives = 1; recognition.onstart = function() { isListening = true; updateButtons(); startVisualizer(); }; recognition.onend = function() { isListening = false; updateButtons(); stopVisualizer(); if (isListening) { recognition.start(); } }; recognition.onresult = async function(event) { const transcript = event.results[0][0].transcript.trim(); addMessageToHistory('user', transcript); await sendMessage(transcript); }; recognition.onerror = function(event) { console.error('خطأ في التعرف على الكلام:', event.error); stopRecognition(); }; } // Toggle Chat (Start Listening) function toggleChat() { if (!recognition) initRecognition(); if (!isListening) { recognition.start(); } } // Stop Recognition function stopRecognition() { if (recognition && isListening) { recognition.stop(); } } // Update Button Visibility function updateButtons() { if (isListening) { talkButton.classList.add('hidden'); stopButton.classList.remove('hidden'); } else { talkButton.classList.remove('hidden'); stopButton.classList.add('hidden'); } } // Send Message to Server and Handle Response async function sendMessage(message) { try { const response = await fetch('/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message }) }); if (!response.ok) throw new Error('Network response was not ok.'); const result = await response.json(); addMessageToHistory('ai', result.response); await playAudio(result.response); } catch (error) { console.error('خطأ في إرسال الرسالة:', error); } } // Add Messages to History function addMessageToHistory(sender, message) { if (sender === 'user') { conversationHistory.push({ user: message, ai: '' }); } else if (sender === 'ai') { conversationHistory[conversationHistory.length - 1].ai = message; } displayConversationHistory(); saveConversationHistory(); } // Text-to-Speech Playback async function playAudio(text) { try { const response = await fetch('/text-to-speech', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) }); if (!response.ok) throw new Error('Network response was not ok.'); const audioBlob = await response.blob(); const audioUrl = URL.createObjectURL(audioBlob); const audio = new Audio(audioUrl); audio.onplay = function() { startVisualizer(); }; audio.onended = function() { stopVisualizer(); if (isListening) { recognition.start(); } }; await audio.play(); } catch (error) { console.error('خطأ في تشغيل الصوت:', error); } } // Audio Visualizer Using Web Audio API let audioContext; let analyser; let dataArray; let animationId; function startVisualizer() { if (!audioContext) { audioContext = new (window.AudioContext || window.webkitAudioContext)(); analyser = audioContext.createAnalyser(); analyser.fftSize = 256; const bufferLength = analyser.frequencyBinCount; dataArray = new Uint8Array(bufferLength); } // Create a silent oscillator for visualization const source = audioContext.createMediaElementSource(new Audio()); source.connect(analyser); analyser.connect(audioContext.destination); const canvasCtx = visualizer.getContext('2d'); const WIDTH = visualizer.width; const HEIGHT = visualizer.height; function draw() { animationId = requestAnimationFrame(draw); analyser.getByteFrequencyData(dataArray); canvasCtx.fillStyle = 'transparent'; canvasCtx.clearRect(0, 0, WIDTH, HEIGHT); const radius = WIDTH / 4; const barCount = 64; const step = Math.PI * 2 / barCount; for(let i = 0; i < barCount; i++) { const amplitude = dataArray[i] / 255; const barHeight = amplitude * radius; const angle = step * i; const x = WIDTH / 2 + Math.cos(angle) * (radius - barHeight); const y = HEIGHT / 2 + Math.sin(angle) * (radius - barHeight); canvasCtx.beginPath(); canvasCtx.moveTo(WIDTH / 2, HEIGHT / 2); canvasCtx.lineTo(x, y); canvasCtx.strokeStyle = `rgba(56, 189, 248, ${amplitude + 0.2})`; canvasCtx.lineWidth = 2; canvasCtx.stroke(); } } draw(); } function stopVisualizer() { if (animationId) { cancelAnimationFrame(animationId); animationId = null; } if (visualizer.getContext) { const canvasCtx = visualizer.getContext('2d'); canvasCtx.clearRect(0, 0, visualizer.width, visualizer.height); } } // Slide Button Functionality slideButton.addEventListener('click', () => { historyContainer.classList.toggle('hidden'); visualizer.classList.toggle('hidden'); slideButton.classList.toggle('active'); slideButton.textContent = historyContainer.classList.contains('hidden') ? '💬' : '🔒'; }); // Load Conversation History on Page Load document.addEventListener('DOMContentLoaded', loadConversationHistory);Key Enhancements:
-
Modern Audio Visualizer:
- Web Audio API Integration: Utilized the Web Audio API to create a dynamic audio visualizer that reacts to actual speech input and audio playback.
- Canvas-based Visualization: Implemented a circular bar visualizer that provides a more engaging and visually appealing representation of audio.
-
Enhanced Speech Recognition Handling:
- Error Handling: Added alerts to notify users if their browser doesn't support the Speech Recognition API.
- Continuous Listening: Ensured that the recognizer continues to listen as long as the user hasn't stopped the conversation.
-
DaisyUI Components:
- Button Enhancements: Replaced traditional buttons with DaisyUI's
btnclasses for better styling and responsiveness. - Visibility Toggles: Managed button visibility based on the listening state to provide clear user feedback.
- Button Enhancements: Replaced traditional buttons with DaisyUI's
-
Slide Button Functionality:
- Toggle Chat Interface: Added a slide button that allows users to hide/show the chat history and visualizer, providing a cleaner interface when needed.
- Responsive Icons: Changed the button icon based on the chat's visibility state for intuitive interaction.
-
Optimized Message Handling:
- Conditional Rendering: Ensured that messages are only displayed if they exist, preventing empty message bubbles.
- Scroll Management: Automatically scrolls to the latest message to keep the conversation in view.
-
Code Optimization and Cleanup:
- Consistent Naming Conventions: Ensured variable and function names are consistent and descriptive.
- Removed Redundant Code: Streamlined functions to avoid unnecessary operations and improve performance.
Additional Recommendations
To further enhance your application, consider implementing the following features:
-
Responsive Design:
- Ensure that the application is fully responsive across different devices and screen sizes.
-
Error Notifications:
- Implement user-friendly error notifications instead of just logging errors to the console.
-
Loading Indicators:
- Add loading spinners or indicators while awaiting responses from the server to improve user experience.
-
Security Measures:
- If deploying publicly, ensure that your server endpoints (
/chatand/text-to-speech) are secured to prevent unauthorized access or misuse.
- If deploying publicly, ensure that your server endpoints (
-
Accessibility:
- Incorporate accessibility best practices, such as ARIA labels and keyboard navigation support, to make the application usable for all users.
-
Customization Options:
- Allow users to customize themes, font sizes, or visualizer styles to personalize their experience.
Feel free to integrate these enhancements into your project. If you encounter any issues or need further assistance, don't hesitate to ask!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.