Certainly! Below is the improved version of your index.html and script.js files. The enhancements include:
- Modern UI with DaisyUI: Utilized DaisyUI components for a more polished and responsive design.
- Enhanced Audio Visualizer: Implemented a more dynamic and modern circle visualizer that reacts to audio playback.
- Floating Chat Button: Added a sliding chat button positioned at the bottom of the website for easy access.
- Updated Tailwind and DaisyUI Integration: Updated the CDN links to use the latest versions via script.
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 via CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- DaisyUI -->
<link href="https://cdn.jsdelivr.net/npm/daisyui@4.12.14/dist/full.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/daisyui@4.12.14/dist/full.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Amiri:wght@400;700&display=swap');
body {
font-family: 'Amiri', serif;
background-color: #1a1a1a;
}
/* Enhanced Audio Visualizer */
#circleVisualizer {
width: 120px;
height: 120px;
border-radius: 50%;
border: 5px solid #38bdf8;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
box-shadow: 0 0 20px rgba(56, 189, 248, 0.7);
animation: pulse 1.5s infinite;
display: none;
z-index: 10;
}
@keyframes pulse {
0% {
transform: translate(-50%, -50%) scale(0.8);
opacity: 1;
}
100% {
transform: translate(-50%, -50%) scale(1.4);
opacity: 0;
}
}
/* Chat Container Animation */
#chatContainer {
position: fixed;
bottom: 16px;
right: 16px;
width: 350px;
max-height: 500px;
background-color: #2d2d2d;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transform: translateY(100%);
transition: transform 0.3s ease-in-out;
z-index: 20;
display: flex;
flex-direction: column;
}
#chatContainer.open {
transform: translateY(0);
}
/* History Container Scrollbar */
#historyContainer::-webkit-scrollbar {
width: 6px;
}
#historyContainer::-webkit-scrollbar-thumb {
background-color: #4b5563;
border-radius: 3px;
}
/* Responsive Adjustments */
@media (max-width: 400px) {
#chatContainer {
width: 90%;
right: 5%;
bottom: 80px;
}
}
</style>
</head>
<body class="text-white flex items-center justify-center min-h-screen relative">
<h1 class="text-4xl mb-8">محادثة الذكاء الاصطناعي</h1>
<!-- Enhanced Audio Visualizer -->
<div id="circleVisualizer" class=""></div>
<!-- Floating Chat Button -->
<button id="chatButton" class="btn btn-primary btn-circle fixed bottom-4 right-4 z-30">
💬
</button>
<!-- Chat Container -->
<div id="chatContainer" class="p-4 bg-gray-800 rounded-lg overflow-hidden">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl">المحادثة</h2>
<button id="closeChatButton" class="btn btn-sm btn-square btn-ghost">
✖️
</button>
</div>
<!-- Conversation History -->
<div id="historyContainer" class="flex-1 overflow-auto mb-4 p-2 bg-gray-700 rounded">
<!-- الرسائل ستتم إضافتها هنا -->
</div>
<!-- Control Buttons -->
<div class="flex flex-col space-y-2">
<button id="talkButton" onclick="toggleChat()" class="btn btn-success w-full">
🎤 ابدأ المحادثة
</button>
<button id="stopButton" onclick="stopRecognition()" class="btn btn-error w-full hidden">
⛔ إيقاف المحادثة
</button>
</div>
</div>
<script src="/static/script.js" defer></script>
</body>
</html>
Key Changes:
- Tailwind and DaisyUI Integration: Loaded Tailwind via CDN script and included DaisyUI's full CSS and JS from CDN.
- Audio Visualizer Enhancement: Increased the size and added more prominent animations to the visualizer for better visibility.
- Floating Chat Button: Positioned a chat button fixed at the bottom-right corner, which toggles the chat container.
- Chat Container: Created a slide-up chat container with smooth transition effects for better user interaction.
- Responsive Design: Ensured that the chat container is responsive on smaller devices.
Updated script.js
const historyContainer = document.getElementById('historyContainer');
const talkButton = document.getElementById('talkButton');
const stopButton = document.getElementById('stopButton');
const circleVisualizer = document.getElementById('circleVisualizer');
const chatButton = document.getElementById('chatButton');
const closeChatButton = document.getElementById('closeChatButton');
const chatContainer = document.getElementById('chatContainer');
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';
// رسالة المستخدم
if (item.user) {
const userMessageDiv = document.createElement('div');
userMessageDiv.className = 'text-right';
const userMessageSpan = document.createElement('span');
userMessageSpan.className = 'badge badge-primary';
userMessageSpan.textContent = item.user;
userMessageDiv.appendChild(userMessageSpan);
messageDiv.appendChild(userMessageDiv);
}
// رسالة الذكاء الاصطناعي
if (item.ai) {
const aiMessageDiv = document.createElement('div');
aiMessageDiv.className = 'text-left mt-2';
const aiMessageSpan = document.createElement('span');
aiMessageSpan.className = 'badge badge-secondary';
aiMessageSpan.textContent = item.ai;
aiMessageDiv.appendChild(aiMessageSpan);
messageDiv.appendChild(aiMessageDiv);
}
historyContainer.appendChild(messageDiv);
});
// التمرير إلى الأسفل
historyContainer.scrollTop = historyContainer.scrollHeight;
}
// إعداد Web Speech API
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() {
circleVisualizer.style.display = 'block';
};
recognition.onend = function() {
circleVisualizer.style.display = 'none';
};
recognition.onresult = async function(event) {
const transcript = event.results[0][0].transcript.trim();
if (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 toggleChatListening() {
if (!recognition) initRecognition();
if (recognition) {
isListening = true;
talkButton.classList.add('hidden');
stopButton.classList.remove('hidden');
recognition.start();
}
}
// إيقاف المحادثة
function stopRecognition() {
isListening = false;
if (recognition) {
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 })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.response) {
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') {
if (conversationHistory.length > 0) {
conversationHistory[conversationHistory.length - 1].ai = message;
} else {
conversationHistory.push({ user: '', 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 })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.onplay = function() {
circleVisualizer.style.display = 'block';
};
audio.onended = function() {
circleVisualizer.style.display = 'none';
if (isListening) {
recognition.start();
}
};
await audio.play();
} catch (error) {
console.error('خطأ في تشغيل الصوت:', error);
}
}
// تحميل سجل المحادثة عند تحميل الصفحة
document.addEventListener('DOMContentLoaded', loadConversationHistory);
// Event Listeners for Chat Button
chatButton.addEventListener('click', () => {
chatContainer.classList.add('open');
chatButton.classList.add('hidden');
});
closeChatButton.addEventListener('click', () => {
chatContainer.classList.remove('open');
chatButton.classList.remove('hidden');
});
Key Changes:
- Modern UI Components: Utilized DaisyUI's
badge, btn, and other components for consistent styling.
- Floating Chat Functionality:
- Chat Button: A floating button (
💬) fixed at the bottom-right corner to toggle the chat container.
- Chat Container: The chat interface slides up from the bottom when the chat button is clicked and slides down when closed.
- Enhanced Audio Visualizer:
- Display Logic: The visualizer is shown when speech recognition starts or when audio playback begins, and hidden when they end.
- Error Handling: Improved error handling for speech recognition and fetch requests.
- Responsive Design: Ensured the chat container is responsive on various screen sizes.
- Code Optimization:
- Removed unnecessary global variables.
- Added event listeners for better separation of concerns.
- Ensured that the chat can be toggled independently of the conversation logic.
Additional Recommendations
-
Server-Side Handling:
- Ensure that your server has endpoints
/chat and /text-to-speech properly set up to handle the respective POST requests.
- Implement CORS policies if necessary, especially if your frontend and backend are hosted on different domains.
-
Security Considerations:
- Validate and sanitize all user inputs on the server side to prevent potential security vulnerabilities.
- Use HTTPS to secure data transmission between the client and server.
-
Performance Optimization:
- Lazy load assets if the application grows in complexity.
- Minify CSS and JS files in a production environment to reduce load times.
-
Accessibility:
- Ensure that all interactive elements are accessible via keyboard.
- Provide ARIA labels where necessary for screen readers.
-
Testing:
- Test the application across different browsers and devices to ensure compatibility.
- Implement unit and integration tests for critical functionalities.
With these enhancements, your application should offer a more modern, responsive, and user-friendly experience. Feel free to further customize the styles and functionalities to better suit your specific requirements.