-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
588 lines (537 loc) · 19.2 KB
/
script.js
File metadata and controls
588 lines (537 loc) · 19.2 KB
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
var cities = [
"Paris",
"Marseille",
"Lyon",
"Toulouse",
"Nice",
"Nantes",
"Strasbourg",
"Montpellier",
"Bordeaux",
"Lille",
"Rennes",
"Reims",
"Le Havre",
"Cergy-Pontoise",
"Saint-Étienne",
"Toulon",
"Angers",
"Grenoble",
"Dijon",
"Nîmes",
"Aix-en-Provence",
"Saint-Quentin-en-Yvelines",
"Brest",
"Le Mans",
"Amiens",
"Tours",
"Limoges",
"Clermont-Ferrand",
"Villeurbanne",
"Besançon",
"Orléans",
"Metz",
"Rouen",
"Mulhouse",
"Perpignan",
"Caen",
"Boulogne-Billancourt",
"Nancy",
"Argenteuil",
"Saint-Denis",
"Roubaix",
"Tourcoing",
"Montreuil",
"Avignon",
"Nanterre",
"Vitry-sur-Seine",
"Créteil",
"Poitiers",
"Aubervilliers",
"Versailles",
"Colombes",
"Asnières-sur-Seine",
"Saint-Pierre",
"Courbevoie",
"Rueil-Malmaison",
"Champigny-sur-Marne",
"Antibes",
"La Rochelle",
"Saint-Maur-des-Fossés",
"Calais",
"Cannes",
"Saint-Nazaire",
"Mérignac",
"Drancy",
"Colmar",
"Ajaccio",
"Bourges",
"Levallois-Perret",
"La Seyne-sur-Mer",
"Quimper",
"Noisy-le-Grand",
"Villeneuve-d'Ascq",
"Valence",
"Antony",
"Cergy",
"Pessac",
"Ivry-sur-Seine",
"Clichy",
"Chambéry",
"Les Abymes",
"Niort",
"Belfort",
"La Roche-sur-Yon",
"Saint-Quentin",
"Sarcelles",
"Évry",
"Istres",
"Le Blanc-Mesnil",
"Vénissieux",
"Troyes",
"Clichy-sous-Bois",
"Lorient",
"Sartrouville",
"Pontoise",
"Saint-André",
"Hyères",
"Beauvais",
"Épinay-sur-Seine",
"Cholet",
"Meaux",
"Chelles",
"Pantin",
"Évry-Courcouronnes",
"Saint-Louis",
"La Rochelle",
"La Seyne-sur-Mer",
"Laval",
"Villejuif",
"Sevran",
"Albi",
"Charleville-Mézières",
"Bondy",
"Fréjus",
"Arles",
"Clamart",
"Vannes",
"Sarcelles",
"Corbeil-Essonnes",
"Saint-Ouen-sur-Seine",
"Cagnes-sur-Mer",
"Massy",
"Grasse",
"Montrouge",
"Vincennes",
"Mantes-la-Jolie",
"Alfortville",
"Martigues",
"Saint-Brieuc",
"Saint-Malo",
"Chalon-sur-Saône",
"Sète",
"Meudon",
"Épinay-sur-Seine",
"Saint-Germain-en-Laye",
"Saint-Herblain",
"Évreux",
"Brive-la-Gaillarde",
"L'Ile-Saint-Denis",
"Villeneuve-Saint-Georges",
"Puteaux",
"Rosny-sous-Bois",
"Livry-Gargan",
"Saint-Laurent-du-Maroni",
"Saint-Joseph",
"Saint-Paul",
"Bron",
"La Courneuve",
"Saint-Germain-en-Laye",
"Saint-Priest",
];
let state = 'askingDay';
let day, city, sexe, saison;
document.getElementById('user-input').addEventListener('keyup', function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
sendMessage();
}
});
async function sendMessage() {
const userInput = document.getElementById('user-input');
const message = userInput.value;
userInput.value = '';
if (state === 'askingDay') {
if (message === '0' || 'aujourd\'hui' === message.toLowerCase()) {
day = '0';
await addMessageToChatBox('Vous avez choisi la météo pour aujourd\'hui.');
await addMessageToChatBox(`Pour quelle ville souhaitez-vous connaître la météo?`);
state = 'askingCity';
}
else if (message === '1' || 'demain' === message.toLowerCase()) {
day = '1';
await addMessageToChatBox('Vous avez choisi la météo pour demain.');
await addMessageToChatBox(`Pour quelle ville souhaitez-vous connaître la météo?`);
state = 'askingCity';
}
else {
document.getElementById('chat-box').innerHTML = '';
await addMessageToChatBox('Entrée invalide. Veuillez entrer 0 pour aujourd\'hui ou 1 pour demain.');
await addMessageToChatBox('Pour quel jour souhaitez-vous connaître la meilleure tenue vestimentaire au vu de la météo? ⠀⠀ (0: aujourd\'hui, 1: demain)');
state = 'askingDay';
}
} else if (state === 'askingCity') {
if (cities.includes(message)) {
city = message;
await addMessageToChatBox(`Vous avez choisi la ville : ${city}`);
await addMessageToChatBox('Quel est votre sexe ? (0: Femme, 1: Homme)');
state = 'askingSexe';
} else {
document.getElementById('chat-box').innerHTML = '';
await addMessageToChatBox('Ville invalide. Veuillez choisir une ville de la liste.');
state = 'askingCity';
}
} else if (state === 'askingSexe') {
if (message === '0' || 'femme' === message.toLowerCase()) {
sexe = '0';
await addMessageToChatBox(`Vous avez choisi : Femme`);
await addMessageToChatBox('Quelle est la saison ? (1: printemps / 2: été / 3: automne / 4: hiver)');
state = 'askingSaison';
} else if (message === '1' || 'homme' === message.toLowerCase()) {
sexe = '1';
await addMessageToChatBox(`Vous avez choisi : Homme`);
await addMessageToChatBox('Quelle est la saison ? (1: printemps / 2: été / 3: automne / 4: hiver)');
state = 'askingSaison';
} else {
document.getElementById('chat-box').innerHTML = '';
await addMessageToChatBox('Entrée invalide. Veuillez entrer 0 pour Femme ou 1 pour Homme.');
await addMessageToChatBox('Quel est votre sexe ? (0: Femme, 1: Homme)');
state = 'askingSexe';
}
} else if (state === 'askingSaison') {
if (message === '1' || message === '2' || message === '3' || message === '4' || 'printemps' === message.toLowerCase() || 'été' === message.toLowerCase() || 'automne' === message.toLowerCase() || 'hiver' === message.toLowerCase()){
if (message === '1' || 'printemps' === message.toLowerCase()) {
saison = '1';
}
else if (message === '2' || 'été' === message.toLowerCase()) {
saison = '2';
}
else if (message === '3' || 'automne' === message.toLowerCase()) {
saison = '3';
}
else if (message === '4' || 'hiver' === message.toLowerCase()) {
saison = '4';
}
await addMessageToChatBox(`Vous avez choisi : ${saison}`);
state = 'done';
console.log(typeof day, city, sexe, saison);
sendQuestionnaire(day, city, sexe, saison);
} else {
document.getElementById('chat-box').innerHTML = '';
await addMessageToChatBox('Entrée invalide. Veuillez entrer 1 pour printemps, 2 pour été, 3 pour automne, ou 4 pour hiver.');
state = 'askingSaison';
}
}
// Set the focus back to the text input field
userInput.focus();
}
var startDelay = 0;
var messageCount = 0;
var baseDelay = 0;
function addMessageToChatBox(message) {
return new Promise((resolve) => {
// Create a new div for the message
var messageDiv = document.createElement('div');
messageDiv.classList.add('chat-message', 'bot-message');
document.getElementById('chat-box').appendChild(messageDiv);
// Create a new Typed instance for the message
var options = {
strings: [message],
typeSpeed: 15,
startDelay: startDelay,
showCursor: false,
onComplete: resolve // Resolve the Promise when the typing animation is finished
};
var typed = new Typed(messageDiv, options);
// Increase the message count
messageCount++;
// If this is the second message, reset the start delay and the message count
if (messageCount === 2) {
startDelay = 0;
messageCount = 0;
} else {
// Otherwise, increase the start delay for the next message
startDelay += message.length * options.typeSpeed + baseDelay;
}
});
}
function appendMessage(sender, message) {
var chatBox = document.getElementById("chat-box");
var messageElement = document.createElement("div");
messageElement.classList.add("chat-message");
if (sender === 'user') {
messageElement.classList.add("user-message");
} else if (sender === 'bot') {
messageElement.classList.add("bot-message");
}
messageElement.innerText = message;
chatBox.appendChild(messageElement);
}
function getWeather() {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
fetch(`https://api.opencagedata.com/geocode/v1/json?q=${lat}+${lon}&key=db63742015484084bca52473d6341c10`)
.then(response => response.json())
.then(data => {
var city = data.results[0].components.city;
fetch(`http://localhost:5000/weather`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ "city": city })
})
.then(response => response.json())
.then(data => {
if (data.error) {
console.error(data.error);
} else {
console.log(data.weather);
console.log(city);
document.getElementById('weather').innerText = data.weather;
document.getElementById('location').innerText = city;
}
})
.catch(error => console.error('Erreur:', error));
})
.catch(error => console.error('Erreur:', error));
});
}
document.addEventListener('DOMContentLoaded', getWeather);
function sendQuestionnaire(day, city, sexe, saison) {
fetch('http://localhost:5000/questionnaire', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
jourInput: parseInt(day),
cityInput: city,
sexeInput: sexe,
saisonInput: saison
})
})
.then(response => response.json())
.then(data => {
console.log('Response data:', data);
// Select the div and update its content
const outfitDiv = document.getElementById('outfit');
let html = '';
const order = ['Haut', 'Bas', 'Chaussures'];
for (let outfit in data) {
for (let tenue in data[outfit]) {
const imageUrl = data[outfit][tenue]['imageURL']; // Store the imageURL in a variable
html += `<div class="tenue p-6 max-w-sm bg-white rounded-xl shadow-md space-y-4 hover:bg-gray-100 transition-colors duration-200 ease-in-out" data-image-url="${imageUrl}">`; // Add the imageURL as a data attribute to the div
html += `<div class="text-xl font-medium text-black">${tenue}</div>`;
for (let item of order) {
if (data[outfit][tenue][item]) {
html += `<p class="text-gray-500">${item}: ${data[outfit][tenue][item]}</p>`;
}
}
html += `</div>`;
}
}
// Define the mystery outfits
const mysteryOutfits = [
{
haut: 'Rien - À POIL !',
bas: 'Rien - À POIL !',
chaussures: 'Rien - À POIL !',
imageURL: 'https://i.ibb.co/ydWVzjt/Group-466apoil.png'
},
{
haut: 'Perruque de clown',
bas: 'Salopette',
chaussures: 'Parpaings sur-mesure',
imageURL: 'https://i.ibb.co/XCz3wP7/image-269clown.png'
},
{
haut: 'Casque de moto',
bas: 'Short de bain',
chaussures: 'Tongs',
imageURL: 'https://i.ibb.co/s3r4bWF/image-268moto.png'
},
{
haut: 'Chemise hawaïenne',
bas: 'Pantalon de jogging',
chaussures: 'Crocs',
imageURL: 'https://i.ibb.co/r765WtD/image-270hawai.png'
},
];
// Generate a random number between 0 and 100
let randNum = Math.floor(Math.random() * 100);
let selectedOutfit = null;
// If the random number is less than or equal to 15 (15% chance), add the mystery outfit to the html
if (randNum <= 100) {
// Select a random mystery outfit
const randomIndex = Math.floor(Math.random() * mysteryOutfits.length);
selectedOutfit = mysteryOutfits[randomIndex];
html += `<div id="tenueM" class="p-6 max-w-sm bg-white rounded-xl shadow-md space-y-4 hover:bg-gray-100 transition-colors duration-200 ease-in-out" data-image-url="${selectedOutfit.imageURL}">`;
html += `<div class="text-xl font-medium text-black">Mystery Outfit Challenge !!</div>`;
html += `<button id="revealButton" class="reveal-button">Click to reveal</button>`;
html += `<div id="mysteryOutfit" class="mystery-outfit hidden">`;
html += `<p class="text-gray-500">Haut: ${selectedOutfit.haut}</p>`;
html += `<p class="text-gray-500">Bas: ${selectedOutfit.bas}</p>`;
html += `<p class="text-gray-500">Chaussures: ${selectedOutfit.chaussures}</p>`;
html += `</div></div>`;
}
outfitDiv.innerHTML = html;
// Add event listener to the reveal button
const revealButton = document.getElementById('revealButton');
if (revealButton) {
revealButton.addEventListener('click', function() {
const mysteryOutfit = document.getElementById('mysteryOutfit');
const tenueM = document.getElementById('tenueM');
mysteryOutfit.style.display = 'block'; // Show the div
mysteryOutfit.classList.add('visible'); // Add class to trigger animation
this.style.display = 'none'; // Hide the button
tenueM.className = 'tenue ' + tenueM.className;
// Listen for the end of the animation
mysteryOutfit.addEventListener('animationend', function() {
// Add event listener to the mystery outfit div after the animation has ended
tenueM.addEventListener('click', function() {
modal.style.display = "block";
img.src = selectedOutfit.imageURL;
});
});
});
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// Get all the divs of tenue
var tenueDivs = document.getElementsByClassName('tenue');
// Get the img element in the modal
var img = modal.getElementsByTagName('img')[0];
// Add event listener to all divs of tenue
for (let i = 0; i < tenueDivs.length; i++) {
tenueDivs[i].addEventListener('click', function() {
modal.style.display = "block";
img.src = this.dataset.imageUrl;
});
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
})
.catch(error => console.error('Error:', error));
}
function refreshWindow() {
window.location.reload();
}
var options1 = {
strings: ['Bonjour, je suis TooBo, votre Bonobo Assistant Vestimentaire!'],
typeSpeed: 15,
showCursor: false
};
var options2 = {
strings: ['Pour quel jour souhaitez-vous connaître la meilleure tenue vestimentaire au vu de la météo? ⠀⠀ (0: aujourd\'hui, 1: demain)'],
typeSpeed: 15,
startDelay: 2500,
showCursor: false
};
var typed1 = new Typed('#message1', options1);
var typed2 = new Typed('#message2', options2);
$("#user-input").autocomplete({
source: function(request, response) {
if (state === 'askingCity') {
var filteredCities = $.ui.autocomplete.filter(cities, request.term);
response(filteredCities);
} else {
response([]);
}
},
autoFocus: true
});
// Get the microphone button element
var microphoneButton = document.getElementById('microphone-button');
var userInputBar = document.getElementById('user-input');
// Disable the button initially
microphoneButton.disabled = true;
userInputBar.disabled = true;
// Enable the button 4 seconds after the page has loaded
window.onload = function() {
setTimeout(function() {
microphoneButton.disabled = false;
microphoneButton.classList.remove('disabled');
userInputBar.disabled = false;
}, 6000);
};
let chunks = [];
let mediaRecorder;
let isRecording = false;
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = e => {
chunks.push(e.data);
};
mediaRecorder.onstop = e => {
const blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
chunks = [];
// Create a File object from the Blob
const audioFile = new File([blob], "recording.ogg", { type: 'audio/ogg; codecs=opus' });
const formData = new FormData();
formData.append('audio', audioFile);
fetch('http://localhost:5000/transcribe', { method: 'POST', body: formData })
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
var inputElement = document.getElementById('user-input');
inputElement.value = data.transcription;
// Focus on the input element
inputElement.focus();
})
.catch(error => {
console.error('Error:', error);
// Handle the error here instead of throwing
});
};
});
// Combined event listener
microphoneButton.addEventListener('click', function(event) {
event.preventDefault();
event.stopPropagation();
// If the button has the 'active' class
if (microphoneButton.classList.contains('active')) {
// Remove the 'active' class
microphoneButton.classList.remove('active');
} else {
// Otherwise, add the 'active' class
microphoneButton.classList.add('active');
}
if (!isRecording) {
mediaRecorder.start();
isRecording = true;
} else {
mediaRecorder.stop();
isRecording = false;
}
});