// رسالة المستخدم
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 })
});
document.addEventListener('DOMContentLoaded', () => {
const historyContainer = document.getElementById('historyContainer');
const talkButton = document.getElementById('talkButton');
const stopButton = document.getElementById('stopButton');
const fabButton = document.getElementById('fabButton');
const chatPanel = document.getElementById('chatPanel');
const closeChat = document.getElementById('closeChat');
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const visualizerContainer = document.getElementById('visualizerContainer');
const visualizer = document.getElementById('visualizer');
let recognition;
let isListening = false;
// Conversation history
let conversationHistory = [];
// Initialize
loadConversationHistory();
initRecognition();
initVisualizer();
// Event Listeners
fabButton.addEventListener('click', () => {
chatPanel.classList.toggle('open');
});
closeChat.addEventListener('click', () => {
chatPanel.classList.remove('open');
});
sendButton.addEventListener('click', () => {
const message = userInput.value.trim();
if (message) {
addMessageToHistory('user', message);
sendMessage(message);
userInput.value = '';
}
});
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendButton.click();
}
});
talkButton.addEventListener('click', startRecognition);
stopButton.addEventListener('click', stopRecognition);
// Load conversation history from Local Storage
function loadConversationHistory() {
const history = localStorage.getItem('conversationHistory');
if (history) {
conversationHistory = JSON.parse(history);
displayConversationHistory();
}
}
// Save conversation history to Local Storage
function saveConversationHistory() {
localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
}
// Display conversation history
function displayConversationHistory() {
historyContainer.innerHTML = '';
conversationHistory.forEach(item => {
// User Message
if (item.user) {
const userDiv = document.createElement('div');
userDiv.className = 'flex justify-end mb-2';
const userMsg = document.createElement('div');
userMsg.className = 'bg-primary text-white px-4 py-2 rounded-lg max-w-xs break-words';
userMsg.textContent = item.user;
userDiv.appendChild(userMsg);
historyContainer.appendChild(userDiv);
}
// AI Message
if (item.ai) {
const aiDiv = document.createElement('div');
aiDiv.className = 'flex justify-start mb-2';
const aiMsg = document.createElement('div');
aiMsg.className = 'bg-gray-700 text-white px-4 py-2 rounded-lg max-w-xs break-words';
aiMsg.textContent = item.ai;
aiDiv.appendChild(aiMsg);
historyContainer.appendChild(aiDiv);
}
});
historyContainer.scrollTop = historyContainer.scrollHeight;
}
// Initialize Web Speech API Recognition
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 = () => {
isListening = true;
visualizerContainer.classList.remove('hidden');
talkButton.classList.add('hidden');
stopButton.classList.remove('hidden');
};
recognition.onend = () => {
isListening = false;
visualizerContainer.classList.add('hidden');
talkButton.classList.remove('hidden');
stopButton.classList.add('hidden');
};
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);
recognition.stop();
};
}
// Start Speech Recognition
function startRecognition() {
if (!recognition) return;
recognition.start();
}
// Stop Speech Recognition
function stopRecognition() {
if (recognition && isListening) {
recognition.stop();
}
}
// Send message to the server
async function sendMessage(message) {
try {
const response = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message })
});
if (!response.ok) throw new Error('Network response was not ok');
const result = await response.json();
addMessageToHistory('ai', result.response);
await playAudio(result.response);
} catch (error) {
console.error('خطأ في إرسال الرسالة:', error);
}
}
// Add message to history
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();
}
// Play audio response using Text-to-Speech
async function playAudio(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('Network response was not ok');
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.onplay = () => {
visualizerContainer.classList.remove('hidden');
};
audio.onended = () => {
visualizerContainer.classList.add('hidden');
};
await audio.play();
} catch (error) {
console.error('خطأ في تشغيل الصوت:', error);
}
}
// Initialize Audio Visualizer
function initVisualizer() {
const canvasCtx = visualizer.getContext('2d');
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
let analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
let dataArray = new Uint8Array(analyser.frequencyBinCount);
// Create a dummy oscillator for visualizer demo
let oscillator = audioContext.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(0, audioContext.currentTime); // Silence
oscillator.connect(analyser);
analyser.connect(audioContext.destination);
oscillator.start();
function draw() {
requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = '#1a1a1a';
canvasCtx.fillRect(0, 0, visualizer.width, visualizer.height);
let barWidth = (visualizer.width / analyser.frequencyBinCount) * 2.5;
let barHeight;
let x = 0;
for(let i = 0; i < analyser.frequencyBinCount; i++) {
barHeight = dataArray[i];
const r = barHeight + 25 * (i / analyser.frequencyBinCount);
const g = 250 * (i / analyser.frequencyBinCount);
const b = 50;
canvasCtx.fillStyle = `rgb(${r},${g},${b})`;
canvasCtx.fillRect(x, visualizer.height - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
}
// Resize canvas to fit container
function resizeCanvas() {
visualizer.width = visualizerContainer.clientWidth;
visualizer.height = visualizerContainer.clientHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
draw();
}
});