// تحميل سجل المحادثة من 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';
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// إرسال الرسالة إلى الخادم والحصول على الرد
async function sendMessage(message) {
try {
const response = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
});
code
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 })
});
Used max-w-md and w-full to ensure the layout adapts to various screen sizes.
Added padding to the body for better spacing on smaller screens.
Enhanced Visualizer:
Replaced the simple pulsing circle with a canvas-based audio visualizer.
The visualizer container is hidden by default and displayed only when audio is playing or speech is recognized.
User Experience:
Added smooth transitions to buttons for better interactivity.
Ensured messages wrap correctly with word-wrap: break-word.
script.js
javascript
Improvements:
Modern JavaScript Practices:
Wrapped the entire script inside a DOMContentLoaded event to ensure the DOM is fully loaded before executing scripts.
Used const and let appropriately for variable declarations.
Employed async/await for asynchronous operations for better readability.
Enhanced Error Handling:
Added checks to ensure the browser supports the SpeechRecognition API.
Displayed alerts to inform the user of unsupported features or errors during speech recognition and audio playback.
Dynamic Audio Visualizer:
Implemented a more dynamic and visually appealing audio visualizer using the Web Audio API.
Utilized the Canvas API to draw frequency bars that respond to the AI's audio response.
The visualizer is now more engaging and provides real-time feedback based on the audio being played.
Performance Optimization:
Ensured that the visualizer stops when not needed to prevent unnecessary CPU usage.
Resized the canvas dynamically to fit the container, ensuring the visualizer looks good on all screen sizes.
User Experience Enhancements:
Disabled the talk button if the browser doesn't support speech recognition.
Ensured smooth transitions between starting and stopping the recognition.
Automatically resumes listening if the app is still in listening mode after the recognition ends.
Code Organization:
Organized functions logically for better maintainability.
Added comments for clarity and easier understanding of the code flow.
Additional Recommendations
Server-Side Enhancements:
Ensure that your server endpoints /chat and /text-to-speech are correctly implemented to handle the requests and provide appropriate responses.
Implement rate limiting and security measures to protect your endpoints.
Accessibility:
Add ARIA labels and roles to improve accessibility for users relying on screen readers.
Ensure sufficient color contrast for users with visual impairments.
Fallbacks:
Provide fallback options for browsers that do not support the SpeechRecognition or Web Audio APIs.
For example, allow users to type their messages if speech is not supported.
Caching and Performance:
Use service workers to cache static assets for faster load times and offline capabilities.
Optimize assets like images and fonts to reduce load times.
Testing:
Test the application across different browsers and devices to ensure compatibility.
Implement automated testing to catch potential bugs early in the development process.
By implementing these improvements, your AI chat application will be more robust, modern, and user-friendly, providing an engaging experience for your users.