-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.txt
699 lines (620 loc) · 21.5 KB
/
message.txt
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat with TTS and STT</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background: #f4f4f9;
color: #333;
}
.chat-container {
max-width: 600px;
margin: 20px auto;
padding: 10px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.chat-messages {
height: 400px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
background: #fafafa;
margin-bottom: 10px;
}
.message {
margin-bottom: 10px;
padding: 8px;
border-radius: 15px;
max-width: 80%;
position: relative;
}
.user-message {
background: #007AFF;
color: white;
margin-left: auto;
border-radius: 15px 15px 0 15px;
}
.ai-message {
background: #E9ECEF;
color: black;
margin-right: auto;
border-radius: 15px 15px 15px 0;
}
.replay-button {
position: absolute;
right: -30px;
top: 50%;
transform: translateY(-50%);
background: transparent;
border: none;
cursor: pointer;
padding: 5px;
display: none; /* Initially hidden */
}
.ai-message .replay-button {
display: block; /* Show for AI messages */
}
.replay-button:hover {
opacity: 0.7;
}
/* Speaker icon style */
.speaker-icon {
width: 20px;
height: 20px;
fill: #007bff;
}
.chat-input {
display: flex;
gap: 10px;
}
.chat-input input {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
.chat-input button {
padding: 10px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.chat-input button:hover {
background: #0056b3;
}
.chat-actions {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
.chat-actions button {
flex: 1;
padding: 10px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.chat-actions button.active {
background: #28a745;
}
.chat-actions button:hover {
background: #0056b3;
}
.voice-selector {
margin-bottom: 10px;
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.voice-settings {
display: flex;
align-items: center;
gap: 5px;
}
select {
padding: 5px;
border-radius: 4px;
border: 1px solid #ddd;
font-size: 14px;
}
.model-selector {
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="voice-selector">
<label for="voiceSelect">Select Voice:</label>
<select id="voiceSelect"></select>
</div>
<div class="model-selector">
<label for="modelSelect">Select Model:</label>
<select id="modelSelect">
<option value="openai">OpenAI</option>
<option value="evil">Evil</option>
<option value="unity">Unity</option>
</select>
</div>
<div class="chat-actions">
<button id="toggleSpeak" onclick="toggleSpeak()">TTS: OFF</button>
<button id="toggleListen" onclick="toggleListen()">STT: OFF</button>
</div>
<div class="chat-messages" id="chatMessages"></div>
<div class="chat-input">
<input type="text" id="messageInput" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script>
const API_ENDPOINT = 'https://hook.eu2.make.com/ihe5gs6mkcvoh55kc36m135mskbpw5s8';
const MAX_HISTORY = 10;
let ttsEnabled = false;
let sttEnabled = false;
let isSpeaking = false; // Prevents STT from listening during TTS
let recognition;
let currentPersona = null;
// Initialize TTS
const synthesis = window.speechSynthesis;
let selectedVoice = null;
// Disable STT for Firefox
const isFirefox = typeof InstallTrigger !== 'undefined';
const SPEECH_TIMEOUT = 1500; // 1.5 seconds pause tolerance
let speechTimer = null;
let currentUtterance = null;
const DEFAULT_SYSTEM_MESSAGE = "You are a friendly AI assistant who speaks casually and uses TTS for responses. Keep the chat short and friendly.";
let SYSTEM_MESSAGE = DEFAULT_SYSTEM_MESSAGE;
const MESSAGE_HISTORY = [{
role: "system",
content: "You are a friendly AI assistant who speaks casually and uses TTS for responses."
}];
const VOICE_PERSONAS = {
'Microsoft Zira - English (United States)': {
name: "Zira",
gender: "female",
location: "United States"
},
'Microsoft David - English (United States)': {
name: "David",
gender: "male",
location: "United States"
},
'Microsoft Catherine - English (Australia)': {
name: "Catherine",
gender: "female",
location: "Australia"
},
'Microsoft James - English (Australia)': {
name: "James",
gender: "male",
location: "Australia"
},
'Microsoft Linda - English (Canada)': {
name: "Linda",
gender: "female",
location: "Canada"
},
'Microsoft Richard - English (Canada)': {
name: "Richard",
gender: "male",
location: "Canada"
},
'Microsoft Mark - English (United States)': {
name: "Mark",
gender: "male",
location: "United States"
},
'Google UK English Female': {
name: "Emma",
gender: "female",
location: "United Kingdom"
},
'Google UK English Male': {
name: "James",
gender: "male",
location: "United Kingdom"
},
'Google US English': {
name: "Sarah",
gender: "female",
location: "United States"
}
};
function disableSTTForFirefox() {
if (isFirefox) {
const sttButton = document.getElementById('toggleListen');
sttButton.disabled = true;
sttButton.textContent = "STT: Not Supported in Firefox";
sttButton.title = "Use Chrome for Speech-to-Text functionality.";
}
}
// Function to generate a random seed
function getRandomSeed() {
return Math.floor(Math.random() * 999999) + 1; // Random number between 1 and 999,999
}
function updateAIPersona(voiceName) {
const personaEnabled = document.getElementById('enablePersona')?.checked;
const persona = VOICE_PERSONAS[voiceName];
let systemPrompt = "You are a friendly AI assistant who speaks casually and uses TTS for responses.";
if (personaEnabled && persona) {
systemPrompt = `You are ${persona.name}, a ${persona.gender} assistant from ${persona.location}. Always speak and act consistent with being ${persona.gender}. Keep responses tailored to users narrative at all times filling in any missing details.`;
}
MESSAGE_HISTORY[0] = { role: "system", content: systemPrompt };
}
function populateVoiceDropdown() {
const voiceSelect = document.getElementById('voiceSelect');
const voices = window.speechSynthesis.getVoices();
const isAndroidChrome = /Android/i.test(navigator.userAgent) && /Chrome/i.test(navigator.userAgent);
// Add persona checkbox if not already present
if (!document.getElementById('personaSettings')) {
const settingsDiv = document.createElement('div');
settingsDiv.id = 'personaSettings';
settingsDiv.className = 'voice-settings';
settingsDiv.innerHTML = `
<input type="checkbox" id="enablePersona" checked>
<label for="enablePersona">Enable Voice Persona</label>
`;
voiceSelect.parentElement.appendChild(settingsDiv);
// Add event listener for the persona checkbox
document.getElementById('enablePersona').addEventListener('change', () => {
if (selectedVoice) {
updateAIPersona(selectedVoice.name); // Use selected voice name directly
}
});
}
if (isAndroidChrome) {
console.warn("Android Chrome detected. Setting default voice.");
voiceSelect.innerHTML = '';
const option = document.createElement('option');
option.textContent = "DEFAULT ANDROID";
option.value = "default";
voiceSelect.appendChild(option);
selectedVoice = null;
updateAIPersona('DEFAULT ANDROID');
return;
}
if (!voices || voices.length === 0) {
setTimeout(populateVoiceDropdown, 200);
return;
}
voiceSelect.innerHTML = '';
// Filter for English voices and sort Microsoft first
const englishVoices = voices.filter(voice => /^en(-|$)/.test(voice.lang));
englishVoices.sort((a, b) => {
const aName = a.name.toLowerCase();
const bName = b.name.toLowerCase();
if (aName.includes('microsoft') && !bName.includes('microsoft')) return -1;
if (!aName.includes('microsoft') && bName.includes('microsoft')) return 1;
return aName.localeCompare(bName);
});
englishVoices.forEach((voice, index) => {
const option = document.createElement('option');
option.value = index;
option.textContent = voice.name;
voiceSelect.appendChild(option);
});
// Set initial voice preference order
selectedVoice = englishVoices.find(v => v.name.includes('Microsoft Zira')) ||
englishVoices.find(v => v.name.includes('Microsoft')) ||
englishVoices.find(v => /en[-_]US/i.test(v.lang)) ||
englishVoices[0];
if (selectedVoice) {
voiceSelect.value = englishVoices.indexOf(selectedVoice);
updateAIPersona(selectedVoice.name);
}
// Add change event listener for voice selection
voiceSelect.addEventListener('change', () => {
const selectedIndex = parseInt(voiceSelect.value, 10);
if (!isNaN(selectedIndex) && englishVoices[selectedIndex]) {
selectedVoice = englishVoices[selectedIndex];
updateAIPersona(selectedVoice.name); // Use selected voice name directly
// Cancel any ongoing speech when voice changes
synthesis.cancel();
isSpeaking = false;
if (sttEnabled && recognition) {
setTimeout(() => recognition.start(), 100);
}
}
});
}
// Ensure voices are loaded before populating
synthesis.onvoiceschanged = () => {
console.log("Voices changed event triggered. Populating dropdown.");
populateVoiceDropdown();
};
// Trigger manually to ensure the dropdown populates even if onvoiceschanged doesn't fire
populateVoiceDropdown();
// Toggle TTS
function toggleSpeak() {
ttsEnabled = !ttsEnabled;
const button = document.getElementById('toggleSpeak');
button.textContent = `TTS: ${ttsEnabled ? "ON" : "OFF"}`;
button.classList.toggle('active', ttsEnabled);
if (!ttsEnabled) {
if (currentUtterance) {
synthesis.cancel();
currentUtterance = null;
}
isSpeaking = false;
if (sttEnabled && recognition) {
recognition.start();
}
}
}
function toggleListen() {
// Disable listening in Firefox
if (isFirefox) {
alert("Speech-to-Text (STT) is not supported in Firefox. Please use Chrome.");
return;
}
// Toggle STT state
sttEnabled = !sttEnabled;
// Update button text and styling
const button = document.getElementById('toggleListen');
button.textContent = `STT: ${sttEnabled ? "ON" : "OFF"}`;
button.classList.toggle('active', sttEnabled);
// Start or stop recognition based on the new state
if (recognition && sttEnabled && !isSpeaking) {
recognition.start();
} else if (recognition) {
recognition.stop();
}
}
function speakText(text, messageElement = null) {
if (!ttsEnabled) return;
// Set speaking state and stop recognition FIRST
isSpeaking = true;
if (recognition) recognition.stop();
// THEN cancel any ongoing speech and clean up
synthesis.cancel();
if (currentUtterance) {
currentUtterance = null;
}
// Split text at punctuation and create separate utterances
const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];
sentences.forEach((sentence, index) => {
const utterance = new SpeechSynthesisUtterance(sentence.trim());
currentUtterance = utterance;
if (!selectedVoice) {
const voices = window.speechSynthesis.getVoices();
const isAndroid = /Android/i.test(navigator.userAgent);
selectedVoice = voices.find(v => /en[-_]US/i.test(v.lang) && v.localService) || voices[0];
}
utterance.voice = selectedVoice;
utterance.onstart = () => {
console.log(`Speech part ${index + 1} started:`, sentence);
};
utterance.onpause = () => {
console.log(`Speech part ${index + 1} paused`);
synthesis.resume();
};
utterance.onend = () => {
console.log(`Speech part ${index + 1} ended`);
if (index === sentences.length - 1) {
// Only reset speaking state after last sentence
isSpeaking = false;
currentUtterance = null;
if (sttEnabled) setTimeout(() => recognition.start(), 100);
}
};
utterance.onerror = (event) => {
console.error(`Speech error in part ${index + 1}:`, event);
if (index === sentences.length - 1) {
isSpeaking = false;
currentUtterance = null;
if (sttEnabled) setTimeout(() => recognition.start(), 100);
}
};
// Slower rate and added volume for better completion
utterance.rate = 0.9; // Made slightly slower
utterance.volume = 1.0; // Maximum volume
utterance.pitch = 1.0; // Normal pitch
synthesis.speak(utterance);
});
}
// Initialize STT
if ('webkitSpeechRecognition' in window) {
recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = false;
recognition.lang = 'en-US';
recognition.onstart = () => {
console.log("Recognition started");
};
recognition.onresult = async (event) => {
if (isSpeaking) return; // Ignore input while TTS is active
const transcript = event.results[event.results.length - 1][0].transcript.trim();
// Clear any existing timer
if (speechTimer) {
clearTimeout(speechTimer);
}
if (!transcript || transcript.length < 2) {
return;
}
// Set a timer to wait for more speech
speechTimer = setTimeout(async () => {
recognition.stop(); // Temporarily stop recognition
addMessageToChat(transcript, 'user');
MESSAGE_HISTORY.push({ role: "user", content: transcript });
trimHistory();
const response = await fetchAIResponse();
addMessageToChat(response, 'ai');
speakText(response);
}, SPEECH_TIMEOUT);
};
recognition.onend = () => {
if (sttEnabled && !isSpeaking) {
console.log("Restarting recognition...");
setTimeout(() => {
recognition.start();
}, 100); // Small delay before restarting
}
};
recognition.onerror = (event) => {
console.error("Recognition Error:", event.error);
if (sttEnabled && !isSpeaking) {
setTimeout(() => {
recognition.start();
}, 1000); // Longer delay after error
}
};
}
document.getElementById('messageInput').addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
sendMessage();
event.preventDefault(); // Prevent default behavior like newline
}
});
async function sendMessage() {
const input = document.getElementById('messageInput');
const userMessage = input.value.trim();
if (!userMessage) return;
addMessageToChat(userMessage, 'user');
MESSAGE_HISTORY.push({ role: "user", content: userMessage });
input.value = ''; // Clear input immediately
try {
const modelSelect = document.getElementById('modelSelect');
const response = modelSelect.value === 'openai'
? await fetchAIResponse()
: await fetchAlternativeAIResponse(userMessage);
addMessageToChat(response, 'ai');
MESSAGE_HISTORY.push({ role: "assistant", content: response });
if (ttsEnabled) {
speakText(response.replace(/https:\/\/image\.pollinations\.ai\/prompt\/[^\s]+/g, ''));
}
} catch (error) {
console.error('Error:', error);
addMessageToChat('Sorry, there was an error processing your request.', 'ai');
}
}
async function fetchAIResponse() {
const requestBody = {
messages: MESSAGE_HISTORY,
model: "openai",
seed: getRandomSeed(), // Use random seed
jsonMode: false
};
try {
const response = await fetch(API_ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
});
if (!response.ok) throw new Error(`Invalid response: ${response.statusText}`);
const aiMessage = await response.text();
MESSAGE_HISTORY.push({ role: "assistant", content: aiMessage.trim() });
trimHistory();
return aiMessage.trim();
} catch (error) {
console.error("Error fetching AI response:", error);
return "Error: Unable to fetch response from AI.";
}
}
function showError(message) {
addMessageToChat(`Error: ${message}`, 'ai');
}
async function fetchAlternativeAIResponse(userMessage) {
try {
const messages = [
{
role: 'user',
content: `Context: You are ${VOICE_PERSONAS[selectedVoice.name]?.name || 'Zira'}, a ${VOICE_PERSONAS[selectedVoice.name]?.gender || 'female'} AI assistant from ${VOICE_PERSONAS[selectedVoice.name]?.location || 'United States'}. Always speak and act consistent with being ${VOICE_PERSONAS[selectedVoice.name]?.gender || 'female'}. Keep responses friendly and casual.`
}
];
// Add conversation history
if (MESSAGE_HISTORY.length > 0) {
const trimmedHistory = MESSAGE_HISTORY
.filter(msg => msg.role !== 'system')
.slice(-10); // Keep last 10 messages
messages.push(...trimmedHistory);
}
// Add current message
messages.push({
role: 'user',
content: userMessage
});
const response = await fetch('https://text.pollinations.ai/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: messages,
model: document.getElementById('modelSelect').value,
seed: Math.floor(Math.random() * 1000000)
})
});
if (!response.ok) throw new Error('Network response was not ok');
return await response.text();
} catch (error) {
console.error('Error:', error);
return 'Sorry, there was an error processing your request.';
}
}
// Trim message history
function trimHistory() {
if (MESSAGE_HISTORY.length > MAX_HISTORY * 2) {
MESSAGE_HISTORY.splice(1, MESSAGE_HISTORY.length - (MAX_HISTORY * 2)); // Keep 10 user + 10 assistant
}
}
// Add a message to the chat
function addMessageToChat(content, type) {
const messagesDiv = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}-message`;
messageDiv.textContent = content;
// Add replay button for AI messages
if (type === 'ai') {
const replayButton = document.createElement('button');
replayButton.className = 'replay-button';
replayButton.innerHTML = `
<svg class="speaker-icon" viewBox="0 0 20 20">
<path d="M15.5,8.5c0-2.5-2-4.5-4.5-4.5S6.5,6,6.5,8.5s2,4.5,4.5,4.5S15.5,11,15.5,8.5z M16,8.5c0,2.8-2.2,5-5,5s-5-2.2-5-5s2.2-5,5-5 S16,5.7,16,8.5z M7.7,7.7L6.3,6.3C5.9,6.7,5.5,7.1,5.1,7.5l1.4,1.4C6.9,8.5,7.3,8.1,7.7,7.7z"/>
</svg>`;
replayButton.onclick = () => speakText(content, messageDiv);
messageDiv.appendChild(replayButton);
}
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
// Add event listener for voice selection change
document.getElementById('voiceSelect').addEventListener('change', () => {
// Cancel any ongoing speech when voice is changed
synthesis.cancel();
isSpeaking = false;
if (sttEnabled && recognition) {
recognition.start();
}
});
// Add keyboard shortcut to stop speech
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
synthesis.cancel();
isSpeaking = false;
if (sttEnabled && recognition) {
recognition.start();
}
}
});
// Disable STT for Firefox on page load
window.onload = () => {
disableSTTForFirefox(); // Handle Firefox STT limitations
populateVoiceDropdown(); // Populate the voice dropdown on load
};
</script>
</body>
</html>