To modernize your AI chatbot interface, enhance the audio visualizer with Three.js, incorporate DaisyUI for improved UI components, and implement a sliding chat button at the bottom of the page, follow the updated code structure below.
Overview of Improvements
-
Modern UI Enhancements:
- DaisyUI Integration: Utilized DaisyUI components alongside Tailwind CSS for a more polished and consistent user interface.
- Sliding Chat Button: Added a responsive sliding button at the bottom of the page to toggle the chat window, providing a cleaner and more intuitive user experience.
-
Advanced Audio Visualizer:
- Three.js Implementation: Replaced the basic circle visualizer with a dynamic and interactive Three.js-based visualizer that responds to audio frequencies in real-time.
- Custom Shaders: Incorporated vertex and fragment shaders to create captivating visual effects influenced by audio input.
-
Code Modernization:
- Modular JavaScript: Organized the JavaScript code into modules for better maintainability and scalability.
- Improved Responsiveness: Enhanced the layout to ensure compatibility across various device sizes.
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 -->
<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>
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/three.min.js" integrity="sha512-ZrVrhpa+fM3VQYqkEjUeCH5dBAtwY4UaeTP6Igep6YeM3ukiQ1Hc1GNyV4MScvJ+kiNm4dy/Rmj92rE/ddMfjQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- Dat.GUI -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.min.js"></script>
<!-- Three.js Postprocessing -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/js/postprocessing/EffectComposer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/js/postprocessing/RenderPass.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/js/postprocessing/UnrealBloomPass.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/js/postprocessing/OutputPass.js"></script>
<style>
body {
font-family: 'Amiri', serif;
background-color: #1a1a1a;
margin: 0;
overflow: hidden;
}
/* Sliding Chat Button */
#chatToggle {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
}
/* Chat Container */
#chatContainer {
position: fixed;
bottom: 80px;
right: 20px;
width: 300px;
max-height: 500px;
background-color: #1f2937;
border-radius: 20px;
padding: 20px;
display: none;
flex-direction: column;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
z-index: 999;
}
/* Three.js Canvas Container */
#threeCanvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
/* Message Styles */
.user-message {
background-color: #3b82f6;
color: white;
padding: 10px 15px;
border-radius: 20px 20px 0px 20px;
display: inline-block;
max-width: 80%;
margin-bottom: 10px;
align-self: flex-end;
}
.ai-message {
background-color: #4b5563;
color: white;
padding: 10px 15px;
border-radius: 20px 20px 20px 0px;
display: inline-block;
max-width: 80%;
margin-bottom: 10px;
align-self: flex-start;
}
</style>
<!-- Vertex Shader -->
<script id="vertexshader" type="x-shader/x-vertex">
uniform float u_time;
uniform float u_frequency;
// Perlin noise functions
vec3 mod289(vec3 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec4 mod289(vec4 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec4 permute(vec4 x) {
return mod289(((x*34.0)+10.0)*x);
}
vec4 taylorInvSqrt(vec4 r) {
return 1.79284291400159 - 0.85373472095314 * r;
}
vec3 fade(vec3 t) {
return t*t*t*(t*(t*6.0-15.0)+10.0);
}
float pnoise(vec3 P, vec3 rep) {
vec3 Pi0 = mod(floor(P), rep);
vec3 Pi1 = mod(Pi0 + vec3(1.0), rep);
Pi0 = mod289(Pi0);
Pi1 = mod289(Pi1);
vec3 Pf0 = fract(P);
vec3 Pf1 = Pf0 - vec3(1.0);
vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x);
vec4 iy = vec4(Pi0.yy, Pi1.yy);
vec4 iz0 = Pi0.zzzz;
vec4 iz1 = Pi1.zzzz;
vec4 ixy = permute(permute(ix) + iy);
vec4 ixy0 = permute(ixy + iz0);
vec4 ixy1 = permute(ixy + iz1);
vec4 gx0 = ixy0 * (1.0 / 7.0);
vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;
gx0 = fract(gx0);
vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0);
vec4 sz0 = step(gz0, vec4(0.0));
gx0 -= sz0 * (step(0.0, gx0) - 0.5);
gy0 -= sz0 * (step(0.0, gy0) - 0.5);
vec4 gx1 = ixy1 * (1.0 / 7.0);
vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;
gx1 = fract(gx1);
vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1);
vec4 sz1 = step(gz1, vec4(0.0));
gx1 -= sz1 * (step(0.0, gx1) - 0.5);
gy1 -= sz1 * (step(0.0, gy1) - 0.5);
vec3 g000 = vec3(gx0.x,gy0.x,gz0.x);
vec3 g100 = vec3(gx0.y,gy0.y,gz0.y);
vec3 g010 = vec3(gx0.z,gy0.z,gz0.z);
vec3 g110 = vec3(gx0.w,gy0.w,gz0.w);
vec3 g001 = vec3(gx1.x,gy1.x,gz1.x);
vec3 g101 = vec3(gx1.y,gy1.y,gz1.y);
vec3 g011 = vec3(gx1.z,gy1.z,gz1.z);
vec3 g111 = vec3(gx1.w,gy1.w,gz1.w);
vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110)));
g000 *= norm0.x;
g010 *= norm0.y;
g100 *= norm0.z;
g110 *= norm0.w;
vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111)));
g001 *= norm1.x;
g011 *= norm1.y;
g101 *= norm1.z;
g111 *= norm1.w;
float n000 = dot(g000, Pf0);
float n100 = dot(g100, vec3(Pf1.x, Pf0.yz));
float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z));
float n110 = dot(g110, vec3(Pf1.xy, Pf0.z));
float n001 = dot(g001, vec3(Pf0.xy, Pf1.z));
float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z));
float n011 = dot(g011, vec3(Pf0.x, Pf1.yz));
float n111 = dot(g111, Pf1);
vec3 fade_xyz = fade(Pf0);
vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z);
vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y);
float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x);
return 2.2 * n_xyz;
}
void main() {
float noise = 3.0 * pnoise(position + u_time, vec3(10.0));
float displacement = (u_frequency / 30.0) * (noise / 10.0);
vec3 newPosition = position + normal * displacement;
gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
}
</script>
<!-- Fragment Shader -->
<script id="fragmentshader" type="x-shader/x-fragment">
uniform float u_red;
uniform float u_blue;
uniform float u_green;
void main() {
gl_FragColor = vec4(vec3(u_red, u_green, u_blue), 1.0);
}
</script>
</head>
<body>
<!-- Three.js Canvas -->
<div id="threeCanvas"></div>
<!-- Chat Toggle Button -->
<div id="chatToggle">
<button id="toggleButton" class="btn btn-primary rounded-full">
💬
</button>
</div>
<!-- Chat Container -->
<div id="chatContainer" class="flex flex-col">
<h2 class="text-2xl mb-4 text-center">محادثة الذكاء الاصطناعي</h2>
<!-- Message History -->
<div id="historyContainer" class="flex-1 mb-4 p-4 bg-gray-800 rounded overflow-auto max-h-60">
<!-- Messages will be appended here -->
</div>
<!-- Control Buttons -->
<div class="flex space-x-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>
<!-- Scripts -->
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/three.module.min.js';
import { GUI } from 'https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.min.js';
import { EffectComposer } from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/jsm/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/jsm/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.170.0/examples/jsm/postprocessing/OutputPass.js';
// Initialize Three.js Scene
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.getElementById('threeCanvas').appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(0, -2, 14);
camera.lookAt(0, 0, 0);
const params = {
red: 1.0,
green: 1.0,
blue: 1.0,
threshold: 0.5,
strength: 1.5,
radius: 0.8
}
renderer.outputColorSpace = THREE.SRGBColorSpace;
// Post-processing
const renderScene = new RenderPass(scene, camera);
const bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight));
bloomPass.threshold = params.threshold;
bloomPass.strength = params.strength;
bloomPass.radius = params.radius;
const bloomComposer = new EffectComposer(renderer);
bloomComposer.addPass(renderScene);
bloomComposer.addPass(bloomPass);
const outputPass = new OutputPass();
bloomComposer.addPass(outputPass);
// Shader Material
const uniforms = {
u_time: { value: 0.0 },
u_frequency: { value: 0.0 },
u_red: { value: 1.0 },
u_green: { value: 1.0 },
u_blue: { value: 1.0 }
}
const vertexShader = document.getElementById('vertexshader').textContent;
const fragmentShader = document.getElementById('fragmentshader').textContent;
const mat = new THREE.ShaderMaterial({
uniforms,
vertexShader,
fragmentShader
});
const geo = new THREE.IcosahedronGeometry(4, 30);
const mesh = new THREE.Mesh(geo, mat);
scene.add(mesh);
mesh.material.wireframe = true;
// Audio Setup
const listener = new THREE.AudioListener();
camera.add(listener);
const sound = new THREE.Audio(listener);
const audioLoader = new THREE.AudioLoader();
// Load a default audio file or handle dynamically as per your application
audioLoader.load('/static/assets/Beats.mp3', function(buffer) {
sound.setBuffer(buffer);
sound.setLoop(true);
sound.setVolume(0.5);
// Automatically play or add controls as needed
// sound.play();
});
const analyser = new THREE.AudioAnalyser(sound, 32);
// GUI Controls (Optional)
const gui = new GUI();
const colorsFolder = gui.addFolder('Colors');
colorsFolder.add(params, 'red', 0, 1).onChange(function(value) {
uniforms.u_red.value = Number(value);
});
colorsFolder.add(params, 'green', 0, 1).onChange(function(value) {
uniforms.u_green.value = Number(value);
});
colorsFolder.add(params, 'blue', 0, 1).onChange(function(value) {
uniforms.u_blue.value = Number(value);
});
const bloomFolder = gui.addFolder('Bloom');
bloomFolder.add(params, 'threshold', 0, 1).onChange(function(value) {
bloomPass.threshold = Number(value);
});
bloomFolder.add(params, 'strength', 0, 3).onChange(function(value) {
bloomPass.strength = Number(value);
});
bloomFolder.add(params, 'radius', 0, 1).onChange(function(value) {
bloomPass.radius = Number(value);
});
// Handle Mouse Movement for Camera
let mouseX = 0;
let mouseY = 0;
document.addEventListener('mousemove', function(e) {
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
mouseX = (e.clientX - windowHalfX) / 100;
mouseY = (e.clientY - windowHalfY) / 100;
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
uniforms.u_time.value = clock.getElapsedTime();
uniforms.u_frequency.value = analyser.getAverageFrequency();
bloomComposer.render();
}
animate();
// Handle Window Resize
window.addEventListener('resize', function() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
bloomComposer.setSize(window.innerWidth, window.innerHeight);
});
// Chat Functionality
const historyContainer = document.getElementById('historyContainer');
const talkButton = document.getElementById('talkButton');
const stopButton = document.getElementById('stopButton');
let recognition;
let isListening = false;
let conversationHistory = [];
// Load Conversation History
function loadConversationHistory() {
const history = localStorage.getItem('conversationHistory');
if (history) {
conversationHistory = JSON.parse(history);
displayConversationHistory();
}
}
// Save Conversation History
function saveConversationHistory() {
localStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
}
// Display Conversation History
function displayConversationHistory() {
historyContainer.innerHTML = '';
conversationHistory.forEach(item => {
const messageDiv = document.createElement('div');
// User Message
const userMessageDiv = document.createElement('div');
userMessageDiv.className = 'user-message';
userMessageDiv.textContent = item.user;
messageDiv.appendChild(userMessageDiv);
// AI Message
if (item.ai) {
const aiMessageDiv = document.createElement('div');
aiMessageDiv.className = 'ai-message';
aiMessageDiv.textContent = item.ai;
messageDiv.appendChild(aiMessageDiv);
}
historyContainer.appendChild(messageDiv);
});
// Scroll to bottom
historyContainer.scrollTop = historyContainer.scrollHeight;
}
// Initialize Speech 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 = function() {
// Optionally, indicate that the app is listening
};
recognition.onend = function() {
// Optionally, indicate that the app has stopped listening
};
recognition.onresult = async function(event) {
const transcript = event.results[0][0].transcript;
addMessageToHistory('user', transcript);
await sendMessage(transcript);
if (isListening) {
recognition.start();
}
};
recognition.onerror = function(event) {
console.error('خطأ في التعرف على الكلام:', event.error);
if (isListening) {
recognition.start();
}
};
}
// Start Listening
async function toggleChat() {
if (!recognition) initRecognition();
isListening = true;
talkButton.classList.add('hidden');
stopButton.classList.remove('hidden');
recognition.start();
sound.play(); // Play audio for visualization
}
// Stop Listening
function stopRecognition() {
isListening = false;
recognition.stop();
talkButton.classList.remove('hidden');
stopButton.classList.add('hidden');
sound.pause();
}
// Send Message to Server
async function sendMessage(message) {
try {
const response = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
});
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') {
conversationHistory[conversationHistory.length - 1].ai = message;
}
displayConversationHistory();
saveConversationHistory();
}
// Play Audio from Text
async function playAudio(text) {
try {
const response = await fetch('/text-to-speech', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: text })
});
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.onplay = function() {
sound.play();
};
audio.onended = function() {
sound.pause();
if (isListening) {
recognition.start();
}
};
await audio.play();
} catch (error) {
console.error('خطأ في تشغيل الصوت:', error);
}
}
// Load conversation history on page load
loadConversationHistory();
// Chat Toggle Button
const toggleButton = document.getElementById('toggleButton');
const chatContainer = document.getElementById('chatContainer');
toggleButton.addEventListener('click', () => {
if (chatContainer.style.display === 'flex') {
chatContainer.style.display = 'none';
} else {
chatContainer.style.display = 'flex';
}
});
</script>
</body>
</html>
Explanation of Key Components
-
Three.js Audio Visualizer:
- Scene Setup: Initializes a Three.js scene with a camera, renderer, and an icosahedron mesh that dynamically deforms based on audio frequencies.
- Shaders: The vertex shader uses Perlin noise to create organic deformations, while the fragment shader handles the coloring based on uniform values.
- Audio Integration: Utilizes
THREE.AudioListener and THREE.AudioAnalyser to capture and analyze audio data, driving the visualizer's responsiveness.
-
Chat Interface:
- Sliding Button: A floating chat button (
#chatToggle) is fixed at the bottom-right corner. Clicking this button toggles the visibility of the chat container (#chatContainer).
- Message Handling: Messages from the user and AI are displayed within the
#historyContainer div, with distinct styling for each.
- Speech Recognition: Implements the Web Speech API to capture user input through voice. The transcript is sent to the server, and the AI's response is played back using text-to-speech.
- Local Storage: Conversation history is saved and loaded from the browser's local storage, ensuring persistence across sessions.
-
UI Enhancements with DaisyUI:
- Buttons: Utilized DaisyUI's styled buttons (
btn btn-primary, btn btn-success, btn btn-error) for consistent and visually appealing controls.
- Layout: Leveraged Tailwind CSS and DaisyUI classes to create a responsive and modern layout.
-
Responsive Design:
- The visualizer and chat interface are designed to be responsive, adapting to various screen sizes and device orientations.
Required Server Endpoints
Ensure that your server handles the following endpoints to support the chatbot's functionality:
-
Chat Endpoint (/chat):
-
Text-to-Speech Endpoint (/text-to-speech):
Additional Considerations
- Audio File Path: Ensure that the path to the audio file (
./assets/Beats.mp3) is correct and the file is accessible on your server.
- Browser Compatibility: The Web Speech API may not be supported in all browsers. Implement fallback mechanisms or inform the user accordingly.
- Security: Validate and sanitize all inputs on the server side to prevent potential security vulnerabilities.
- Performance Optimization: Optimize Three.js settings and audio processing to ensure smooth performance, especially on lower-end devices.
Conclusion
By integrating Three.js for a sophisticated audio visualizer, utilizing DaisyUI for enhanced UI components, and implementing a sliding chat button, your AI chatbot interface is now more modern, interactive, and user-friendly. This setup not only provides a visually appealing experience but also ensures functional robustness and responsiveness across various devices.