// رسالة المستخدم
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;
// إرسال الرسالة إلى الخادم والحصول على الرد
async function sendMessage(message) {
try {
const response = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
});
// إضافة الرسائل إلى السجل
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 })
});
// script.js
document.addEventListener('DOMContentLoaded', () => {
const historyContainer = document.getElementById('historyContainer');
const talkButton = document.getElementById('talkButton');
const stopButton = document.getElementById('stopButton');
const visualizer = document.getElementById('visualizer');
let recognition;
let isListening = false;
let conversationHistory = [];
// Audio Context and Analyzer for Visualizer
let audioContext;
let analyzer;
let dataArray;
let animationId;
// Load conversation history from LocalStorage
const loadConversationHistory = () => {
const history = localStorage.getItem('conversationHistory');
if (history) {
conversationHistory = JSON.parse(history);
displayConversationHistory();
}
};
// Save conversation history to LocalStorage
const saveConversationHistory = () => {
localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
};
// Display the conversation history in the UI
const displayConversationHistory = () => {
historyContainer.innerHTML = '';
conversationHistory.forEach(item => {
const messageDiv = document.createElement('div');
messageDiv.className = 'mb-4';
// User Message
if (item.user) {
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);
messageDiv.appendChild(userMessageDiv);
}
// AI Message
if (item.ai) {
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(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('متصفحك لا يدعم ميزة التعرف على الصوت. يرجى استخدام متصفح آخر.');
talkButton.disabled = true;
return;
}
recognition = new SpeechRecognition();
recognition.lang = 'ar-SA';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.onstart = () => {
isListening = true;
startVisualizer();
talkButton.classList.add('hidden');
stopButton.classList.remove('hidden');
};
recognition.onend = () => {
isListening = false;
stopVisualizer();
talkButton.classList.remove('hidden');
stopButton.classList.add('hidden');
};
recognition.onresult = async (event) => {
const transcript = event.results[0][0].transcript.trim();
addMessage('user', transcript);
await sendMessage(transcript);
// Restart recognition if still listening
if (isListening) {
recognition.start();
}
};
recognition.onerror = (event) => {
console.error('Speech Recognition Error:', event.error);
if (isListening) {
recognition.stop();
}
};
};
// Start Speech Recognition
const startRecognition = () => {
if (!recognition) initRecognition();
if (recognition) {
isListening = true;
recognition.start();
}
};
// Stop Speech Recognition
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(`Server Error: ${response.status}`);
}
const result = await response.json();
if (result.response) {
addMessage('ai', result.response);
await playAudio(result.response);
} else {
throw new Error('Invalid response from server.');
}
} catch (error) {
console.error('Error sending message:', error);
addMessage('ai', 'عذرًا، حدث خطأ في تلقي الرد.');
}
};
// Add message to the conversation history
const addMessage = (sender, message) => {
if (sender === 'user') {
conversationHistory.push({ user: message, ai: '' });
} else if (sender === 'ai') {
if (conversationHistory.length === 0) {
conversationHistory.push({ user: '', ai: message });
} else {
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(`Text-to-Speech Server Error: ${response.status}`);
}
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.onplay = () => {
startVisualizer();
};
audio.onended = () => {
stopVisualizer();
if (isListening) {
recognition.start();
}
};
await audio.play();
} catch (error) {
console.error('Error playing audio:', error);
addMessage('ai', 'عذرًا، حدث خطأ في تشغيل الصوت.');
}
};
// Initialize Audio Visualizer
const initVisualizer = () => {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyzer = audioContext.createAnalyser();
analyzer.fftSize = 256;
const bufferLength = analyzer.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
// Create a dummy oscillator as placeholder
const oscillator = audioContext.createOscillator();
oscillator.frequency.setValueAtTime(0, audioContext.currentTime);
oscillator.connect(analyzer);
oscillator.start();
};
// Start the visualizer animation
const startVisualizer = () => {
if (!analyzer) initVisualizer();
const canvasCtx = visualizer.getContext('2d');
const WIDTH = visualizer.width = visualizer.offsetWidth;
const HEIGHT = visualizer.height = visualizer.offsetHeight;
const draw = () => {
animationId = requestAnimationFrame(draw);
analyzer.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = '#111827'; // Background color
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / dataArray.length) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < dataArray.length; i++) {
barHeight = dataArray[i];
const r = barHeight + (25 * (i / dataArray.length));
const g = 250 * (i / dataArray.length);
const b = 50;
canvasCtx.fillStyle = `rgb(${r},${g},${b})`;
canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
};
draw();
};
// Stop the visualizer animation
const stopVisualizer = () => {
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
const canvasCtx = visualizer.getContext('2d');
canvasCtx.clearRect(0, 0, visualizer.width, visualizer.height);
};
// Event Listeners for Buttons
const debounce = (func, delay) => {
let debounceTimer;
return function () {
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
};
};
talkButton.addEventListener('click', debounce(() => {
startRecognition();
}, 300));
stopButton.addEventListener('click', debounce(() => {
stopRecognition();
}, 300));
// Initialize everything on load
loadConversationHistory();
});