To modernize your AI conversation web application and enhance the visualizer, we'll implement the following improvements:
- Upgrade Tailwind CSS: Update to the latest version of Tailwind CSS for improved utility classes and features.
- Enhanced Audio Visualizer: Replace the existing pulsing circle with a dynamic frequency bars visualizer using the Web Audio API for a more engaging user experience.
- Modern JavaScript Practices: Refactor the JavaScript code to utilize modern ES6+ features, improve readability, and ensure better performance.
- Responsive Design Enhancements: Improve the layout and responsiveness to ensure the application looks great on all devices.
Below are the updated index.html and script.js files with detailed explanations.
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>
<!-- Updated Tailwind CSS to version 3.3.2 -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@3.3.2/dist/tailwind.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;
}
/* أنماط الرسائل */
.user-message {
background-color: #2563eb;
color: white;
padding: 10px 15px;
border-radius: 20px 20px 0px 20px;
display: inline-block;
max-width: 80%;
margin-bottom: 10px;
}
.ai-message {
background-color: #374151;
color: white;
padding: 10px 15px;
border-radius: 20px 20px 20px 0px;
display: inline-block;
max-width: 80%;
margin-bottom: 10px;
}
/* أنماط المرئي */
#visualizerContainer {
width: 100%;
max-width: 600px;
height: 150px;
margin: 0 auto;
position: relative;
background-color: #2d2d2d;
border-radius: 10px;
overflow: hidden;
}
#visualizer {
width: 100%;
height: 100%;
display: block;
}
</style>
</head>
<body class="text-white flex flex-col items-center justify-center min-h-screen p-4">
<h1 class="text-4xl mb-8">محادثة الذكاء الاصطناعي</h1>
<!-- مرئي التحدث -->
<div id="visualizerContainer" class="mb-8">
<canvas id="visualizer"></canvas>
</div>
<!-- التحكم في المحادثة -->
<div class="w-full max-w-md flex flex-col items-center">
<button id="talkButton" onclick="toggleChat()"
class="bg-green-500 px-6 py-3 mt-4 rounded hover:bg-green-700 w-full transition-colors duration-300">
🎤 ابدأ المحادثة
</button>
<button id="stopButton" onclick="stopRecognition()"
class="bg-red-500 px-6 py-3 mt-4 rounded hover:bg-red-700 w-full transition-colors duration-300 hidden">
⛔ إيقاف المحادثة
</button>
</div>
<!-- سجل المحادثة -->
<div id="historyContainer" class="mt-8 p-4 bg-gray-800 rounded w-full max-w-md overflow-auto max-h-96">
<!-- ستتم إضافة الرسائل هنا -->
</div>
<script src="/static/script.js" defer></script>
</body>
</html>
Key Changes:
-
Tailwind CSS Upgrade:
- Updated the Tailwind CSS CDN link to the latest version (
3.3.2) to leverage new features and utilities.
-
Responsive Design:
- Wrapped the main content in a
p-4 padding for better spacing on smaller screens.
- Set maximum widths for containers (
max-w-md for a maximum width of 28rem) to ensure the layout looks good on larger screens while maintaining responsiveness.
-
Enhanced Visualizer Container:
- Replaced the pulsing circle with a
canvas element inside a styled container (#visualizerContainer) that will host the dynamic frequency bars visualizer.
-
Button Enhancements:
- Added smooth transition effects (
transition-colors duration-300) for better interactivity on hover.
- Adjusted margins to ensure consistent spacing.
Updated script.js
// Select DOM elements
const historyContainer = document.getElementById('historyContainer');
const talkButton = document.getElementById('talkButton');
const stopButton = document.getElementById('stopButton');
const visualizerCanvas = document.getElementById('visualizer');
const canvasCtx = visualizerCanvas.getContext('2d');
let recognition;
let isListening = false;
// Conversation history
let conversationHistory = [];
// Web Audio API variables
let audioContext;
let analyzer;
let source;
let animationId;
// Load and display conversation history
const loadConversationHistory = () => {
const history = localStorage.getItem('conversationHistory');
if (history) {
conversationHistory = JSON.parse(history);
displayConversationHistory();
}
};
// Save conversation history to Local Storage
const saveConversationHistory = () => {
localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
};
// Display conversation history on the page
const displayConversationHistory = () => {
historyContainer.innerHTML = '';
conversationHistory.forEach(item => {
const messageDiv = document.createElement('div');
messageDiv.className = 'mb-4';
// User message
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);
// AI message
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);
});
// Scroll to the bottom
historyContainer.scrollTop = historyContainer.scrollHeight;
};
// Initialize Speech Recognition
const 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 = () => {
toggleButtons(true);
};
recognition.onend = () => {
toggleButtons(false);
if (isListening) {
recognition.start();
}
};
recognition.onresult = async (event) => {
const transcript = event.results[0][0].transcript.trim();
if (transcript) {
addMessageToHistory('user', transcript);
await sendMessage(transcript);
}
};
recognition.onerror = (event) => {
console.error('خطأ في التعرف على الكلام:', event.error);
if (isListening) {
recognition.stop();
}
};
};
// Toggle button visibility
const toggleButtons = (isRecording) => {
if (isRecording) {
talkButton.classList.add('hidden');
stopButton.classList.remove('hidden');
} else {
talkButton.classList.remove('hidden');
stopButton.classList.add('hidden');
}
};
// Start the chat
const toggleChat = () => {
isListening = true;
if (!recognition) initRecognition();
recognition.start();
};
// Stop the chat
const stopRecognition = () => {
isListening = false;
if (recognition) recognition.stop();
};
// Send message to the server and handle the response
const sendMessage = async (message) => {
try {
const response = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message })
});
if (!response.ok) {
throw new Error('فشل في إرسال الرسالة');
}
const result = await response.json();
addMessageToHistory('ai', result.response);
await playAudio(result.response);
} catch (error) {
console.error(error);
}
};
// Add messages to the conversation history
const addMessageToHistory = (sender, message) => {
if (sender === 'user') {
conversationHistory.push({ user: message, ai: '' });
} else if (sender === 'ai') {
conversationHistory[conversationHistory.length - 1].ai = message;
}
displayConversationHistory();
saveConversationHistory();
};
// Play audio using Text-to-Speech
const playAudio = async (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('فشل في تحويل النص إلى كلام');
}
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
// Initialize Web Audio API for visualization
setupAudioContext(audio);
await audio.play();
} catch (error) {
console.error(error);
}
};
// Setup Web Audio API for audio visualization
const setupAudioContext = (audio) => {
// Cancel any existing animation
if (animationId) {
cancelAnimationFrame(animationId);
}
// Initialize AudioContext if not already done
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
// Create source and analyser nodes
source = audioContext.createMediaElementSource(audio);
analyzer = audioContext.createAnalyser();
analyzer.fftSize = 256;
// Connect nodes
source.connect(analyzer);
analyzer.connect(audioContext.destination);
// Start visualizing
visualize();
};
// Visualize audio frequency data
const visualize = () => {
const bufferLength = analyzer.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
visualizerCanvas.width = visualizerCanvas.clientWidth;
visualizerCanvas.height = visualizerCanvas.clientHeight;
const WIDTH = visualizerCanvas.width;
const HEIGHT = visualizerCanvas.height;
const barWidth = (WIDTH / bufferLength) * 2.5;
let x = 0;
const draw = () => {
animationId = requestAnimationFrame(draw);
analyzer.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = '#2d2d2d';
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
x = 0;
for (let i = 0; i < bufferLength; i++) {
const barHeight = dataArray[i] / 2;
const r = barHeight + 25;
const g = 250 * (i / bufferLength);
const b = 50;
canvasCtx.fillStyle = `rgb(${r},${g},${b})`;
canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
};
draw();
};
// Initialize the application
document.addEventListener('DOMContentLoaded', loadConversationHistory);
Key Improvements:
-
Enhanced Audio Visualizer with Web Audio API:
-
Modern JavaScript Practices:
-
Arrow Functions: Utilizes arrow functions for cleaner and more concise syntax.
-
Async/Await: Implements async/await for asynchronous operations, improving readability over traditional .then() and .catch() promise chains.
-
Error Handling: Enhanced error handling to provide better feedback in case of failures during speech recognition or audio playback.
-
Constant and Let Declarations: Uses const and let appropriately to define variables with block scope, enhancing code safety and predictability.
-
Improved UI Interactions:
-
Button State Management: The toggleButtons function manages the visibility of the "Start" and "Stop" buttons based on the speech recognition state, providing clear user feedback.
-
Responsive Canvas: Adjusts the canvas size dynamically based on its container to ensure the visualizer looks good on all screen sizes.
-
Performance Optimizations:
-
Animation Control: Cancels any existing animation frames before starting a new visualization to prevent multiple overlapping animations.
-
Efficient Rendering: Limits the fftSize to 256 for a balance between performance and visual detail.
-
Code Organization and Readability:
Additional Recommendations
-
Secure Server Endpoints:
- Ensure that your server endpoints (
/chat and /text-to-speech) are secure and handle edge cases appropriately to prevent potential security vulnerabilities.
-
Cross-Browser Compatibility:
- Test the application across different browsers to ensure the Web Speech API and Web Audio API functionalities work consistently.
-
Accessibility Enhancements:
- Consider adding accessibility features such as ARIA labels and keyboard navigation to make the application more inclusive.
-
Progressive Enhancement:
- Implement fallback mechanisms for browsers that do not support certain APIs, ensuring a basic level of functionality is always available.
-
Optimize Tailwind CSS:
- For production, consider using Tailwind's Just-In-Time (JIT) mode and purging unused styles to reduce the CSS bundle size.
By implementing these enhancements, your AI conversation application will offer a more modern and engaging user experience, both visually and functionally. The dynamic audio visualizer not only improves aesthetics but also provides real-time feedback, making interactions more immersive.