Spaces:
Running
Running
File size: 16,973 Bytes
b15f4c6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voice Chat Bot with Advanced Echo Cancellation</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@ricky0123/[email protected]/dist/bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@xenova/[email protected]"></script>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 20px;
background-color: #1a1a1a;
color: #f0f0f0;
}
.container {
max-width: 800px;
margin: 0 auto;
}
h1 {
color: #ffd700;
text-align: center;
margin-bottom: 10px;
}
.subtitle {
text-align: center;
color: #ffd700;
margin-bottom: 20px;
}
#chat-container {
display: flex;
flex-direction: column;
height: 70vh;
}
#conversation {
flex-grow: 1;
border: 1px solid #444;
padding: 10px;
overflow-y: scroll;
background-color: #2a2a2a;
border-radius: 5px;
margin-bottom: 20px;
}
#controls {
display: flex;
justify-content: center;
margin-bottom: 20px;
}
button {
font-size: 18px;
padding: 10px 20px;
background-color: #ffd700;
color: #1a1a1a;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #ffec8b;
}
button:disabled {
background-color: #666;
cursor: not-allowed;
}
#visualizer {
width: 100%;
height: 100px;
background-color: #2a2a2a;
border-radius: 5px;
overflow: hidden;
margin-bottom: 20px;
}
.bar {
width: 5px;
height: 100%;
background-color: #ffd700;
display: inline-block;
margin-right: 1px;
}
#loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.spinner {
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #ffd700;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
#configuration {
margin-bottom: 20px;
}
select {
width: 100%;
padding: 10px;
font-size: 16px;
background-color: #2a2a2a;
color: #f0f0f0;
border: 1px solid #444;
border-radius: 5px;
}
#model-info {
margin-top: 10px;
font-size: 14px;
color: #aaa;
}
#logs {
background-color: #2a2a2a;
border: 1px solid #444;
border-radius: 5px;
padding: 10px;
height: 200px;
overflow-y: scroll;
font-family: monospace;
font-size: 14px;
}
#clear-logs {
margin-top: 10px;
font-size: 14px;
padding: 5px 10px;
}
#localVideo, #remoteVideo {
display: none;
}
</style>
</head>
<body>
<div id="loading">
<div class="spinner"></div>
</div>
<div class="container">
<h1>Digital Human Voice Chat</h1>
<p class="subtitle">For best results, use headphones.</p>
<div id="chat-container">
<div id="controls">
<button id="startButton" disabled>Begin Call</button>
</div>
<div id="configuration">
<select id="configSelect">
<option value="fastest">Fastest</option>
<option value="balanced">Balanced</option>
<option value="quality">Highest Quality</option>
</select>
<div id="model-info">
TTS: Xenova/mms-tts-eng / STT: Xenova/whisper-tiny.en / LLM: Placeholder
</div>
</div>
<div id="visualizer"></div>
<div id="conversation"></div>
</div>
<h2>Logs</h2>
<div id="logs"></div>
<button id="clear-logs">Clear</button>
</div>
<video id="localVideo" autoplay></video>
<video id="remoteVideo" autoplay></video>
<script type="module">
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/[email protected]';
env.localModelPath = './models';
//BELOW 5 statements added by RAHUL
// Configure environment before initializing pipelines
env.backends = ['wasm'];
env.wasm = env.wasm || {};
env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/@xenova/[email protected]/'; // Ensure correct WASM paths
env.wasm.simd = true; // Enable SIMD if available
env.numThreads = navigator.hardwareConcurrency || 4; // Use available CPU cores
const conversationDiv = document.getElementById('conversation');
const startButton = document.getElementById('startButton');
const visualizer = document.getElementById('visualizer');
const loadingDiv = document.getElementById('loading');
const logsDiv = document.getElementById('logs');
const clearLogsButton = document.getElementById('clear-logs');
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
let myvad;
let sttPipeline;
let ttsPipeline;
let audioContext;
let analyser;
let dataArray;
let bars;
let animationId;
let isListening = false;
let microphoneStream;
let isSpeaking = false;
let currentAudioSource = null;
let rtcConnection = null;
let rtcLoopbackConnection = null;
let loopbackStream = new MediaStream();
function createVisualizer() {
const barCount = 64;
for (let i = 0; i < barCount; i++) {
const bar = document.createElement('div');
bar.className = 'bar';
visualizer.appendChild(bar);
}
bars = visualizer.getElementsByClassName('bar');
}
function updateVisualizer() {
analyser.getByteFrequencyData(dataArray);
for (let i = 0; i < bars.length; i++) {
const barHeight = dataArray[i] / 2;
bars[i].style.height = barHeight + 'px';
}
// Use setTimeout instead of requestAnimationFrame to reduce update frequency - RAHUL ATLURY
animationId = setTimeout(updateVisualizer, 50); // Update every 50ms - RAHUL ATLURY
//animationId = requestAnimationFrame(updateVisualizer);
}
async function initializePipelines() {
try {
//sttPipeline = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en', { quantized: true }); // added , { quantized: true }
//ttsPipeline = await pipeline('text-to-speech', 'Xenova/mms-tts-eng', {
// quantized: true, //changed to true - RAHUL ATLURY
//});
[sttPipeline, ttsPipeline] = await Promise.all([
pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en', { quantized: true }),
pipeline('text-to-speech', 'Xenova/mms-tts-eng', { quantized: true })
]);
addLog('System: Digital Human Voice Chat initialized. Click "Begin Call" to start.');
startButton.disabled = false;
loadingDiv.style.display = 'none';
} catch (error) {
console.error('Error initializing pipelines:', error);
addLog('System: Error initializing Digital Human Voice Chat. Please check the console for details.');
loadingDiv.style.display = 'none';
}
}
async function processSpeech(audio) {
try {
if (!sttPipeline || !ttsPipeline) {
throw new Error('Pipelines not initialized');
}
const transcription = await sttPipeline(audio);
addLog(`User: ${transcription.text}`);
const botResponse = `I heard you say: "${transcription.text}".`;
addLog(`Bot: ${botResponse}`);
isSpeaking = true;
const speechOutput = await ttsPipeline(botResponse);
await playAudio(speechOutput.audio);
isSpeaking = false;
} catch (error) {
console.error('Error processing speech:', error);
addLog('System: Error processing speech. Please try again.');
}
}
function addLog(message) {
const now = new Date();
const timestamp = now.toLocaleTimeString();
const logMessage = `[${timestamp}] ${message}`;
const messageElement = document.createElement('div');
messageElement.textContent = logMessage;
logsDiv.appendChild(messageElement);
logsDiv.scrollTop = logsDiv.scrollHeight;
}
function playAudio(audioArray) {
return new Promise((resolve) => {
const audioBuffer = audioContext.createBuffer(1, audioArray.length, 16000);
const channelData = audioBuffer.getChannelData(0);
channelData.set(audioArray);
const source = audioContext.createBufferSource();
currentAudioSource = source;
source.buffer = audioBuffer;
source.connect(analyser);
analyser.connect(audioContext.destination);
source.start();
source.onended = () => {
currentAudioSource = null;
resolve();
};
});
}
function stopCurrentAudio() {
if (currentAudioSource) {
currentAudioSource.stop();
currentAudioSource = null;
}
}
async function toggleListening() {
if (isListening) {
await stopListening();
} else {
await startListening();
}
}
async function startListening() {
try {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
analyser.fftSize = 128;
dataArray = new Uint8Array(analyser.frequencyBinCount);
localVideo.volume = 0;
localVideo.muted = true;
document.getElementById('localVideo').volume = 0;
remoteVideo.volume = 0;
remoteVideo.muted = true;
document.getElementById('remoteVideo').volume = 0;
// Request both audio and video streams
microphoneStream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: { width: 1, height: 1 } // Minimal video for echo cancellation
});
localVideo.srcObject = microphoneStream;
await localVideo.play();
console.log('Active constraints:', microphoneStream.getAudioTracks()[0].getConstraints());
console.log('Microphone stream settings:', microphoneStream.getAudioTracks()[0].getSettings());
// Implement loopback hack for improved echo cancellation
const offerOptions = {
offerToReceiveAudio: true,
offerToReceiveVideo: false,
};
rtcConnection = new RTCPeerConnection();
rtcLoopbackConnection = new RTCPeerConnection();
rtcConnection.onicecandidate = e => e.candidate && rtcLoopbackConnection.addIceCandidate(new RTCIceCandidate(e.candidate));
rtcLoopbackConnection.onicecandidate = e => e.candidate && rtcConnection.addIceCandidate(new RTCIceCandidate(e.candidate));
rtcLoopbackConnection.ontrack = e => e.streams[0].getTracks().forEach(track => loopbackStream.addTrack(track));
microphoneStream.getTracks().forEach(track => rtcConnection.addTrack(track, microphoneStream));
const offer = await rtcConnection.createOffer(offerOptions);
await rtcConnection.setLocalDescription(offer);
await rtcLoopbackConnection.setRemoteDescription(offer);
const answer = await rtcLoopbackConnection.createAnswer();
await rtcLoopbackConnection.setLocalDescription(answer);
await rtcConnection.setRemoteDescription(answer);
// Use the loopback stream for audio processing
const source = audioContext.createMediaStreamSource(loopbackStream);
source.connect(analyser);
myvad = await vad.MicVAD.new({
noiseSuppression: true, ///Added by RAHUL Atlury
aggressiveness: 3, // Higher value for more aggressive detection Added by RAHUL ATLURY
onSpeechStart: () => {
addLog('--- Voice activity: speech start');
updateVisualizer();
if (isSpeaking) {
addLog('User interrupted. Stopping bot speech.');
stopCurrentAudio();
isSpeaking = false;
}
},
onSpeechEnd: (audio) => {
addLog('--- Voice activity: speech end');
cancelAnimationFrame(animationId);
processSpeech(audio);
}
});
await myvad.start();
startButton.textContent = 'End Call';
isListening = true;
addLog('System: Listening...');
} catch (error) {
console.error('Error starting voice activity:', error);
addLog('System: Error starting voice detection. Please check your microphone and try again.');
}
}
async function stopListening() {
if (myvad) {
try {
await myvad.destroy();
} catch (error) {
console.error('Error stopping voice activity:', error);
}
myvad = null;
}
if (microphoneStream) {
microphoneStream.getTracks().forEach(track => track.stop());
microphoneStream = null;
}
if (audioContext) {
await audioContext.close();
audioContext = null;
}
if (localVideo) {
localVideo.srcObject = null;
}
if (remoteVideo) {
remoteVideo.srcObject = null;
}
if (rtcConnection) {
rtcConnection.close();
rtcConnection = null;
}
if (rtcLoopbackConnection) {
rtcLoopbackConnection.close();
rtcLoopbackConnection = null;
}
loopbackStream = new MediaStream();
stopCurrentAudio();
startButton.textContent = 'Begin Call';
isListening = false;
addLog('System: Stopped listening.');
cancelAnimationFrame(animationId);
addLog('System: Microphone closed');
}
startButton.addEventListener('click', toggleListening);
clearLogsButton.addEventListener('click', () => {
logsDiv.innerHTML = '';
});
createVisualizer();
initializePipelines();
</script>
</body>
</html> |