chat with book html: {% extends "dashboardlayout.html" %} {% block dashboardcontent %}…
- User
chat with book html: {% extends "dashboard_layout.html" %}
{% block dashboard_content %}
code - Assistant
chat with book html: {% extends "dashboard_layout.html" %}
{% block dashboard_content %}
<!-- Chat Messages -->
<div id="chat-messages" class="flex-1 overflow-y-auto p-4 space-y-4">
{% if messages %}
{% for message in messages %}
<div class="chat {% if message.role == 'user' %}chat-end{% else %}chat-start{% endif %}">
<div class="chat-image avatar placeholder">
<div class="bg-neutral text-neutral-content rounded-full w-10">
<i class="fas {% if message.role == 'user' %}fa-user{% else %}fa-book{% endif %}"></i>
</div>
</div>
<div class="chat-header">
{% if message.role == 'user' %}
أنت
{% else %}
{{ book.name }}
{% endif %}
<time class="text-xs opacity-50 mr-2">{{ message.timestamp.strftime('%I:%M %p') if message.timestamp }}</time>
</div>
<div class="chat-bubble {% if message.role == 'user' %}chat-bubble-primary{% endif %}">
{% if message.message_type == 'voice' %}
<div class="flex items-center gap-2">
<button class="btn btn-circle btn-xs" onclick="playVoiceMessage(this)" data-audio-url="{{ message.audio_url }}">
<i class="fas fa-play"></i>
</button>
<span class="text-sm">رسالة صوتية</span>
</div>
{% else %}
{{ message.content }}
{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<div class="hero min-h-[50vh]">
<div class="hero-content text-center">
<div class="max-w-md">
<h2 class="text-2xl font-bold mb-4">ابدأ محادثة مع {{ book.name }}</h2>
<p class="text-base-content/70">اسأل أي سؤال عن الكتاب وسأساعدك في فهمه بشكل أفضل.</p>
</div>
</div>
</div>
{% endif %}
<!-- Loading Indicator -->
<div id="loading-indicator" class="hidden chat chat-start">
<div class="chat-image avatar placeholder">
<div class="bg-neutral text-neutral-content rounded-full w-10">
<i class="fas fa-book"></i>
</div>
</div>
<div class="chat-bubble">
<span class="loading loading-dots loading-md"></span>
</div>
</div>
</div>
<!-- Chat Input -->
<div class="p-4 bg-base-200">
<form id="chat-form" class="flex gap-2 items-end">
<button type="button" id="voice-record-btn" class="btn btn-circle btn-ghost">
<i class="fas fa-microphone"></i>
</button>
<div class="form-control flex-1">
<textarea
id="message-input"
class="textarea textarea-bordered min-h-12"
placeholder="اكتب رسالتك هنا..."
rows="1"
required
></textarea>
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-paper-plane"></i>
</button>
</form>
<!-- Recording Status -->
<div id="recording-status" class="hidden mt-2 text-sm text-error">
<div class="flex items-center gap-2">
<span class="loading loading-spinner loading-sm"></span>
<span>جاري التسجيل...</span>
<span id="recording-time">00:00</span>
</div>
</div>
</div>
{% endblock %}
please make it conmvert voice to text arabic to send it to ai and fix all bugs and add animations
Certainly! I'll help you enhance your "Chat with Book" HTML template by implementing the following features:
Below is the updated code with detailed explanations of the changes made:
{% extends "dashboard_layout.html" %}
{% block dashboard_content %}
<div class="flex flex-col h-screen">
<!-- Header -->
<div class="navbar bg-base-200 shadow-lg">
<div class="flex-1">
<div class="flex items-center gap-4">
<div class="avatar">
<div class="w-12 h-16 rounded">
<img
src="{{ book.image_url }}"
alt="{{ book.name }}"
class="transition-transform duration-300 transform hover:scale-110"
>
</div>
</div>
<div>
<h1 class="text-xl font-bold">{{ book.name }}</h1>
</div>
</div>
</div>
<div class="flex-none">
<a href="{{ url_for('books_list') }}" class="btn btn-ghost btn-circle focus:outline-none" aria-label="Close Chat">
<i class="fas fa-times"></i>
</a>
</div>
</div>
<!-- Chat Messages -->
<div id="chat-messages" class="flex-1 overflow-y-auto p-4 space-y-4 animate-fade-in">
{% if messages %}
{% for message in messages %}
<div class="chat {% if message.role == 'user' %}chat-end{% else %}chat-start{% endif %} animate-slide-in">
<div class="chat-image avatar placeholder">
<div class="bg-neutral text-neutral-content rounded-full w-10 h-10 flex items-center justify-center">
<i class="fas {% if message.role == 'user' %}fa-user{% else %}fa-book{% endif %}"></i>
</div>
</div>
<div class="chat-header">
{% if message.role == 'user' %}
أنت
{% else %}
{{ book.name }}
{% endif %}
<time class="text-xs opacity-50 mr-2">{{ message.timestamp.strftime('%I:%M %p') if message.timestamp }}</time>
</div>
<div class="chat-bubble {% if message.role == 'user' %}chat-bubble-primary{% endif %} animate-zoom-in">
{% if message.message_type == 'voice' %}
<div class="flex items-center gap-2">
<button class="btn btn-circle btn-xs" onclick="playVoiceMessage(this)" data-audio-url="{{ message.audio_url }}" aria-label="Play Voice Message">
<i class="fas fa-play"></i>
</button>
<span class="text-sm">رسالة صوتية</span>
</div>
{% else %}
{{ message.content }}
{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<div class="hero min-h-[50vh]">
<div class="hero-content text-center">
<div class="max-w-md">
<h2 class="text-2xl font-bold mb-4">ابدأ محادثة مع {{ book.name }}</h2>
<p class="text-base-content/70">اسأل أي سؤال عن الكتاب وسأساعدك في فهمه بشكل أفضل.</p>
</div>
</div>
</div>
{% endif %}
<!-- Loading Indicator -->
<div id="loading-indicator" class="hidden chat chat-start">
<div class="chat-image avatar placeholder">
<div class="bg-neutral text-neutral-content rounded-full w-10 h-10 flex items-center justify-center">
<i class="fas fa-book"></i>
</div>
</div>
<div class="chat-bubble">
<span class="loading loading-dots loading-md"></span>
</div>
</div>
</div>
<!-- Chat Input -->
<div class="p-4 bg-base-200 shadow-inner">
<form id="chat-form" class="flex gap-2 items-end" autocomplete="off">
<button type="button" id="voice-record-btn" class="btn btn-circle btn-ghost transform hover:scale-110 transition-transform duration-200" aria-label="Record Voice">
<i class="fas fa-microphone"></i>
</button>
<div class="form-control flex-1">
<textarea
id="message-input"
class="textarea textarea-bordered min-h-12 resize-none focus:outline-none focus:ring-2 focus:ring-primary transition duration-300"
placeholder="اكتب رسالتك هنا..."
rows="1"
required
></textarea>
</div>
<button type="submit" class="btn btn-primary transform hover:scale-105 transition-transform duration-200" aria-label="Send Message">
<i class="fas fa-paper-plane"></i>
</button>
</form>
<!-- Recording Status -->
<div id="recording-status" class="hidden mt-2 text-sm text-error flex items-center gap-2 animate-pulse">
<span class="loading loading-spinner loading-sm"></span>
<span>جاري التسجيل...</span>
<span id="recording-time">00:00</span>
</div>
</div>
</div>
<!-- Animations -->
<style>
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideIn {
from { transform: translateX(-20px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes zoomIn {
from { transform: scale(0.8); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.animate-fade-in {
animation: fadeIn 0.5s ease-in-out;
}
.animate-slide-in {
animation: slideIn 0.5s ease-out;
}
.animate-zoom-in {
animation: zoomIn 0.3s ease-out;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
const chatMessages = document.getElementById('chat-messages');
const chatForm = document.getElementById('chat-form');
const messageInput = document.getElementById('message-input');
const loadingIndicator = document.getElementById('loading-indicator');
const voiceRecordBtn = document.getElementById('voice-record-btn');
const recordingStatus = document.getElementById('recording-status');
const recordingTime = document.getElementById('recording-time');
let mediaRecorder = null;
let audioChunks = [];
let recordingInterval = null;
let recordingStartTime = null;
let isRecording = false;
let currentAudio = null;
// Initialize Speech Recognition
let recognition = null;
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'ar-SA';
recognition.onresult = async function(event) {
const transcript = event.results[0][0].transcript.trim();
if (transcript) {
messageInput.value = transcript;
await sendMessage(transcript);
}
};
recognition.onerror = function(event) {
console.error('Speech recognition error:', event.error);
alert('حدث خطأ أثناء التعرف على الصوت. الرجاء المحاولة مرة أخرى.');
};
} else {
console.warn('Speech recognition is not supported in this browser.');
voiceRecordBtn.style.display = 'none'; // Hide voice button if not supported
}
// Function to append messages with animation
function appendMessage(message, isUser = false) {
const messageDiv = document.createElement('div');
messageDiv.className = `chat ${isUser ? 'chat-end' : 'chat-start'} animate-slide-in`;
const avatarDiv = document.createElement('div');
avatarDiv.className = 'chat-image avatar placeholder';
avatarDiv.innerHTML = `
<div class="bg-neutral text-neutral-content rounded-full w-10 h-10 flex items-center justify-center">
<i class="fas ${isUser ? 'fa-user' : 'fa-book'}"></i>
</div>
`;
const headerDiv = document.createElement('div');
headerDiv.className = 'chat-header';
headerDiv.innerHTML = `
${isUser ? 'أنت' : '{{ book.name }}'}
<time class="text-xs opacity-50 mr-2">${new Date().toLocaleTimeString('ar-SA', { hour: '2-digit', minute: '2-digit' })}</time>
`;
const bubbleDiv = document.createElement('div');
bubbleDiv.className = `chat-bubble ${isUser ? 'chat-bubble-primary' : ''} animate-zoom-in`;
if (message.message_type === 'voice') {
bubbleDiv.innerHTML = `
<div class="flex items-center gap-2">
<button class="btn btn-circle btn-xs" onclick="playVoiceMessage(this)" data-audio-url="${message.audio_url}" aria-label="Play Voice Message">
<i class="fas fa-play"></i>
</button>
<span class="text-sm">رسالة صوتية</span>
</div>
`;
} else {
bubbleDiv.textContent = message.content;
}
messageDiv.appendChild(avatarDiv);
messageDiv.appendChild(headerDiv);
messageDiv.appendChild(bubbleDiv);
// Add entry animation
chatMessages.appendChild(messageDiv);
setTimeout(() => {
messageDiv.classList.remove('animate-slide-in');
}, 500);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Function to send text message
async function sendMessage(message) {
if (!message.trim()) return;
// Clear input and show user message
messageInput.value = '';
appendMessage({ content: message, message_type: 'text' }, true);
// Show loading indicator
loadingIndicator.classList.remove('hidden');
try {
const response = await fetch(window.location.pathname, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: message })
});
const data = await response.json();
if (data.success) {
appendMessage(data.message, false);
} else {
throw new Error(data.error || 'حدث خطأ أثناء إرسال الرسالة');
}
} catch (error) {
console.error('Error:', error);
alert('حدث خطأ أثناء إرسال الرسالة. الرجاء المحاولة مرة أخرى.');
} finally {
loadingIndicator.classList.add('hidden');
}
}
// Handle form submission for sending text messages
chatForm.addEventListener('submit', function(e) {
e.preventDefault();
const message = messageInput.value.trim();
sendMessage(message);
});
// Voice Recording Functionality
async function setupVoiceRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
await sendVoiceMessage(audioBlob);
audioChunks = [];
};
return true;
} catch (error) {
console.error('Error accessing microphone:', error);
alert('غير قادر على الوصول إلى الميكروفون. الرجاء التأكد من الأذونات.');
return false;
}
}
function updateRecordingTime() {
if (!recordingStartTime) return;
const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
const seconds = (elapsed % 60).toString().padStart(2, '0');
recordingTime.textContent = `${minutes}:${seconds}`;
}
voiceRecordBtn.addEventListener('click', async function() {
if (recognition && !recognition.active && !isRecording) {
// Start speech recognition
recognition.start();
voiceRecordBtn.classList.add('btn-active'); // Add active state
return;
}
if (isRecording) {
// Stop audio recording
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
if (recordingInterval) {
clearInterval(recordingInterval);
recordingInterval = null;
}
}
recordingStatus.classList.add('hidden');
voiceRecordBtn.querySelector('i').classList.remove('text-error');
isRecording = false;
} else {
// Start audio recording
if (!mediaRecorder && !(await setupVoiceRecording())) {
return;
}
audioChunks = [];
mediaRecorder.start();
recordingStartTime = Date.now();
recordingInterval = setInterval(updateRecordingTime, 1000);
recordingStatus.classList.remove('hidden');
voiceRecordBtn.querySelector('i').classList.add('text-error');
isRecording = true;
}
});
// Function to send voice message to the server
async function sendVoiceMessage(audioBlob) {
// Show loading indicator
loadingIndicator.classList.remove('hidden');
const formData = new FormData();
formData.append('audio', audioBlob);
try {
const response = await fetch(window.location.pathname, {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.success && data.message) {
// Add voice message to chat
appendMessage({ audio_url: data.message.audio_url, message_type: 'voice' }, true);
// Append AI response
appendMessage(data.message, false);
} else {
throw new Error(data.error || 'حدث خطأ أثناء إرسال الرسالة الصوتية');
}
} catch (error) {
console.error('Error sending voice message:', error);
alert('حدث خطأ أثناء إرسال الرسالة الصوتية. الرجاء المحاولة مرة أخرى.');
} finally {
loadingIndicator.classList.add('hidden');
}
}
// Voice message playback
window.playVoiceMessage = function(button) {
const audioUrl = button.getAttribute('data-audio-url');
const icon = button.querySelector('i');
if (!audioUrl) {
console.error('No audio URL found');
return;
}
// Stop any currently playing audio
if (currentAudio && currentAudio.src !== audioUrl) {
currentAudio.pause();
currentAudio = null;
// Reset all play buttons
document.querySelectorAll('.btn-circle').forEach(btn => {
const btnIcon = btn.querySelector('i');
btnIcon.classList.remove('fa-pause');
btnIcon.classList.add('fa-play');
});
}
try {
if (currentAudio && currentAudio.src === audioUrl) {
if (currentAudio.paused) {
currentAudio.play();
icon.classList.remove('fa-play');
icon.classList.add('fa-pause');
} else {
currentAudio.pause();
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
}
} else {
const audio = new Audio(audioUrl);
audio.onplay = function() {
icon.classList.remove('fa-play');
icon.classList.add('fa-pause');
};
audio.onpause = function() {
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
};
audio.onended = function() {
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
currentAudio = null;
};
currentAudio = audio;
audio.play().catch(error => {
console.error('Error playing audio:', error);
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
currentAudio = null;
});
}
} catch (error) {
console.error('Error creating audio:', error);
}
};
});
</script>
{% endblock %}
Voice-to-Text Conversion in Arabic:
SpeechRecognition API with lang set to 'ar-SA' for Arabic.webkitSpeechRecognition and SpeechRecognition.sendMessage function.Voice Recording Functionality:
sendVoiceMessage function to append both the voice message and the AI's response to the chat.Bug Fixes:
currentAudio variable effectively.aria-labels to buttons for better accessibility support.Animations:
fadeIn, slideIn, and zoomIn animations.Backend Integration:
Browser Compatibility:
SpeechRecognition API is not supported in all browsers. Encourage users to use compatible browsers like Google Chrome for the best experience.Security Considerations:
Performance Optimizations:
By implementing these changes, your chat interface will be more robust, user-friendly, and visually appealing. Users will benefit from seamless voice-to-text capabilities in Arabic, intuitive interactions, and engaging animations that enhance the overall experience.
Not yet included in a published release.
UI/UX Enhancements:
Accessibility Improvements:
aria-label attributes to buttons to aid screen readers and improve accessibility.