TANMIHA commited on
Commit
56c96bd
·
verified ·
1 Parent(s): b4dd494

Update static/script.js

Browse files
Files changed (1) hide show
  1. static/script.js +103 -99
static/script.js CHANGED
@@ -1,10 +1,6 @@
1
  let lightMode = true;
2
- let recorder = null;
3
- let recording = false;
4
  const responses = [];
5
- const botRepeatButtonIDToIndexMap = {};
6
- const userRepeatButtonIDToRecordingMap = {};
7
- const baseUrl = window.location.origin
8
 
9
  async function showBotLoadingAnimation() {
10
  await sleep(200);
@@ -14,21 +10,11 @@ async function showBotLoadingAnimation() {
14
 
15
  function hideBotLoadingAnimation() {
16
  $(".loading-animation")[1].style.display = "none";
17
- if(!isFirstMessage){
18
  document.getElementById('send-button').disabled = false;
19
  }
20
  }
21
 
22
- async function showUserLoadingAnimation() {
23
- await sleep(100);
24
- $(".loading-animation")[0].style.display = "flex";
25
- }
26
-
27
- function hideUserLoadingAnimation() {
28
- $(".loading-animation")[0].style.display = "none";
29
- }
30
-
31
-
32
  const processUserMessage = async (userMessage) => {
33
  let response = await fetch(baseUrl + "/process-message", {
34
  method: "POST",
@@ -36,38 +22,32 @@ const processUserMessage = async (userMessage) => {
36
  body: JSON.stringify({ userMessage: userMessage }),
37
  });
38
  response = await response.json();
39
- console.log(response);
40
  return response;
41
  };
42
 
43
  const cleanTextInput = (value) => {
44
  return value
45
- .trim() // remove starting and ending spaces
46
- .replace(/[\n\t]/g, "") // remove newlines and tabs
47
- .replace(/<[^>]*>/g, "") // remove HTML tags
48
- .replace(/[<>&;]/g, ""); // sanitize inputs
49
  };
50
 
51
  const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));
52
 
53
  const scrollToBottom = () => {
54
- // Scroll the chat window to the bottom
55
  $("#chat-window").animate({
56
  scrollTop: $("#chat-window")[0].scrollHeight,
57
  });
58
  };
59
 
60
- const populateUserMessage = (userMessage, userRecording) => {
61
- // Clear the input field
62
  $("#message-input").val("");
63
-
64
- // Append the user's message to the message list
65
- $("#message-list").append(
66
- `<div class='message-line my-text'><div class='message-box my-text${
67
- !lightMode ? " dark" : ""
68
- }'><div class='me'>${userMessage}</div></div></div>`
69
- );
70
-
71
  scrollToBottom();
72
  };
73
 
@@ -75,125 +55,149 @@ let isFirstMessage = true;
75
 
76
  const populateBotResponse = async (userMessage) => {
77
  await showBotLoadingAnimation();
78
-
79
  let response;
80
  let uploadButtonHtml = '';
81
-
82
  if (isFirstMessage) {
83
  response = { botResponse: "Hello there! I'm your friendly data assistant, ready to answer any questions regarding your data. Could you please upload a PDF file for me to analyze?"};
84
- uploadButtonHtml = `
85
- <input type="file" id="file-upload" accept=".pdf" hidden>
86
- <button id="upload-button" class="btn btn-primary btn-sm">Upload File</button>
87
  `;
88
-
89
  } else {
90
  response = await processUserMessage(userMessage);
91
  }
 
92
 
93
- renderBotResponse(response, uploadButtonHtml)
94
-
95
- // Event listener for file upload
96
  if (isFirstMessage) {
97
  $("#upload-button").on("click", function () {
98
  $("#file-upload").click();
99
  });
100
-
101
  $("#file-upload").on("change", async function () {
102
  const file = this.files[0];
103
-
104
  await showBotLoadingAnimation();
105
-
106
- // Create a new FormData instance
107
  const formData = new FormData();
108
-
109
- // Append the file to the FormData instance
110
  formData.append('file', file);
111
-
112
- // Now send this data to /process-document endpoint
113
  let response = await fetch(baseUrl + "/process-document", {
114
  method: "POST",
115
- headers: { Accept: "application/json" }, // "Content-Type" should not be explicitly set here, the browser will automatically set it to "multipart/form-data"
116
- body: formData, // send the FormData instance as the body
117
  });
118
-
119
  if (response.status !== 400) {
120
- document.querySelector('#upload-button').disabled = true;
121
  }
122
-
123
  response = await response.json();
124
- console.log('/process-document', response)
125
- renderBotResponse(response, '')
126
  });
 
 
 
127
 
128
-
129
- isFirstMessage = false; // after the first message, set this to false
 
 
 
 
 
130
  }
131
  };
132
 
133
  const renderBotResponse = (response, uploadButtonHtml) => {
134
  responses.push(response);
135
-
136
  hideBotLoadingAnimation();
 
137
 
138
  $("#message-list").append(
139
- `<div class='message-line'><div class='message-box${!lightMode ? " dark" : ""}'>${response.botResponse.trim()}<br>${uploadButtonHtml}</div></div>`
 
 
 
 
 
 
 
140
  );
141
-
142
  scrollToBottom();
143
- }
144
-
145
- populateBotResponse()
146
 
 
147
 
148
  $(document).ready(function () {
149
-
150
- //start the chat with send button disabled
151
  document.getElementById('send-button').disabled = true;
152
 
153
- // Listen for the "Enter" key being pressed in the input field
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  $("#message-input").keyup(function (event) {
155
  let inputVal = cleanTextInput($("#message-input").val());
156
-
157
  if (event.keyCode === 13 && inputVal != "") {
158
  const message = inputVal;
159
-
160
- populateUserMessage(message, null);
161
  populateBotResponse(message);
162
  }
163
-
164
- inputVal = $("#message-input").val();
165
  });
166
 
167
- // When the user clicks the "Send" button
168
  $("#send-button").click(async function () {
169
- // Get the message the user typed in
170
- const message = cleanTextInput($("#message-input").val());
171
-
172
- populateUserMessage(message, null);
173
- populateBotResponse(message);
174
-
175
  });
176
 
177
- //reset chat
178
- // When the user clicks the "Reset" button
179
- $("#reset-button").click(async function () {
180
- // Clear the message list
181
- $("#message-list").empty();
182
-
183
- // Reset the responses array
184
- responses.length = 0;
185
-
186
- // Reset isFirstMessage flag
187
- isFirstMessage = true;
188
-
189
- document.querySelector('#upload-button').disabled = false;
190
-
191
- // Start over
192
- populateBotResponse();
193
- });
194
-
195
 
196
- // handle the event of switching light-dark mode
197
  $("#light-dark-mode-switch").change(function () {
198
  $("body").toggleClass("dark-mode");
199
  $(".message-box").toggleClass("dark");
@@ -201,4 +205,4 @@ $(document).ready(function () {
201
  $(".dot").toggleClass("dark-dot");
202
  lightMode = !lightMode;
203
  });
204
- });
 
1
  let lightMode = true;
 
 
2
  const responses = [];
3
+ const baseUrl = window.location.origin;
 
 
4
 
5
  async function showBotLoadingAnimation() {
6
  await sleep(200);
 
10
 
11
  function hideBotLoadingAnimation() {
12
  $(".loading-animation")[1].style.display = "none";
13
+ if (!isFirstMessage) {
14
  document.getElementById('send-button').disabled = false;
15
  }
16
  }
17
 
 
 
 
 
 
 
 
 
 
 
18
  const processUserMessage = async (userMessage) => {
19
  let response = await fetch(baseUrl + "/process-message", {
20
  method: "POST",
 
22
  body: JSON.stringify({ userMessage: userMessage }),
23
  });
24
  response = await response.json();
 
25
  return response;
26
  };
27
 
28
  const cleanTextInput = (value) => {
29
  return value
30
+ .trim()
31
+ .replace(/[\n\t]/g, "")
32
+ .replace(/<[^>]*>/g, "")
33
+ .replace(/[<>&;]/g, "");
34
  };
35
 
36
  const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));
37
 
38
  const scrollToBottom = () => {
 
39
  $("#chat-window").animate({
40
  scrollTop: $("#chat-window")[0].scrollHeight,
41
  });
42
  };
43
 
44
+ const populateUserMessage = (userMessage) => {
 
45
  $("#message-input").val("");
46
+ $("#message-list").append(
47
+ `<div class='message-line my-text'><div class='message-box my-text${
48
+ !lightMode ? " dark" : ""
49
+ }'><div class='me'>${userMessage}</div></div></div>`
50
+ );
 
 
 
51
  scrollToBottom();
52
  };
53
 
 
55
 
56
  const populateBotResponse = async (userMessage) => {
57
  await showBotLoadingAnimation();
 
58
  let response;
59
  let uploadButtonHtml = '';
 
60
  if (isFirstMessage) {
61
  response = { botResponse: "Hello there! I'm your friendly data assistant, ready to answer any questions regarding your data. Could you please upload a PDF file for me to analyze?"};
62
+ uploadButtonHtml = `
63
+ <input type="file" id="file-upload" accept=".pdf" hidden>
64
+ <button id="upload-button" class="btn btn-primary btn-sm">Upload File</button>
65
  `;
 
66
  } else {
67
  response = await processUserMessage(userMessage);
68
  }
69
+ renderBotResponse(response, uploadButtonHtml);
70
 
 
 
 
71
  if (isFirstMessage) {
72
  $("#upload-button").on("click", function () {
73
  $("#file-upload").click();
74
  });
 
75
  $("#file-upload").on("change", async function () {
76
  const file = this.files[0];
 
77
  await showBotLoadingAnimation();
 
 
78
  const formData = new FormData();
 
 
79
  formData.append('file', file);
80
+
 
81
  let response = await fetch(baseUrl + "/process-document", {
82
  method: "POST",
83
+ headers: { Accept: "application/json" },
84
+ body: formData,
85
  });
 
86
  if (response.status !== 400) {
87
+ document.querySelector('#upload-button').disabled = true;
88
  }
 
89
  response = await response.json();
90
+ renderBotResponse(response, '');
 
91
  });
92
+ isFirstMessage = false;
93
+ }
94
+ };
95
 
96
+ // Text-to-Speech (TTS)
97
+ const speakText = (text) => {
98
+ if ('speechSynthesis' in window) {
99
+ window.speechSynthesis.cancel();
100
+ const utterance = new SpeechSynthesisUtterance(text);
101
+ utterance.lang = 'en-IN';
102
+ window.speechSynthesis.speak(utterance);
103
  }
104
  };
105
 
106
  const renderBotResponse = (response, uploadButtonHtml) => {
107
  responses.push(response);
 
108
  hideBotLoadingAnimation();
109
+ const botText = response.botResponse.trim();
110
 
111
  $("#message-list").append(
112
+ `<div class='message-line'>
113
+ <div class='message-box${!lightMode ? " dark" : ""}'>
114
+ ${botText}<br>${uploadButtonHtml}
115
+ <button class="btn btn-sm btn-link speak-btn p-0 mt-2" onclick="speakText('${botText.replace(/'/g, "\\'")}')">
116
+ <i class="fa fa-volume-up"></i> Listen
117
+ </button>
118
+ </div>
119
+ </div>`
120
  );
 
121
  scrollToBottom();
122
+ speakText(botText);
123
+ };
 
124
 
125
+ populateBotResponse();
126
 
127
  $(document).ready(function () {
 
 
128
  document.getElementById('send-button').disabled = true;
129
 
130
+ // Speech-to-Text (STT) Integration
131
+ const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
132
+ if (SpeechRecognition) {
133
+ const recognition = new SpeechRecognition();
134
+ recognition.continuous = false;
135
+ recognition.interimResults = false;
136
+ recognition.lang = 'en-IN';
137
+
138
+ $("#mic-button").click(function () {
139
+ try {
140
+ recognition.start();
141
+ } catch (e) {
142
+ console.log("Recognition already started");
143
+ }
144
+ });
145
+
146
+ recognition.onstart = function () {
147
+ $("#mic-button").addClass("listening");
148
+ $("#message-input").attr("placeholder", "Listening...");
149
+ };
150
+
151
+ recognition.onresult = function (event) {
152
+ const transcript = event.results[0][0].transcript;
153
+ $("#message-input").val(transcript);
154
+ };
155
+
156
+ recognition.onerror = function (event) {
157
+ console.error("Speech recognition error", event.error);
158
+ $("#mic-button").removeClass("listening");
159
+ $("#message-input").attr("placeholder", "Type or speak your message...");
160
+ };
161
+
162
+ recognition.onend = function () {
163
+ $("#mic-button").removeClass("listening");
164
+ $("#message-input").attr("placeholder", "Type or speak your message...");
165
+
166
+ const inputVal = cleanTextInput($("#message-input").val());
167
+ if (inputVal !== "") {
168
+ populateUserMessage(inputVal);
169
+ populateBotResponse(inputVal);
170
+ }
171
+ };
172
+ } else {
173
+ $("#mic-button").hide();
174
+ }
175
+
176
  $("#message-input").keyup(function (event) {
177
  let inputVal = cleanTextInput($("#message-input").val());
 
178
  if (event.keyCode === 13 && inputVal != "") {
179
  const message = inputVal;
180
+ populateUserMessage(message);
 
181
  populateBotResponse(message);
182
  }
 
 
183
  });
184
 
 
185
  $("#send-button").click(async function () {
186
+ const message = cleanTextInput($("#message-input").val());
187
+ if (message !== "") {
188
+ populateUserMessage(message);
189
+ populateBotResponse(message);
190
+ }
 
191
  });
192
 
193
+ $("#reset-button").click(async function () {
194
+ $("#message-list").empty();
195
+ responses.length = 0;
196
+ isFirstMessage = true;
197
+ document.querySelector('#upload-button').disabled = false;
198
+ populateBotResponse();
199
+ });
 
 
 
 
 
 
 
 
 
 
 
200
 
 
201
  $("#light-dark-mode-switch").change(function () {
202
  $("body").toggleClass("dark-mode");
203
  $(".message-box").toggleClass("dark");
 
205
  $(".dot").toggleClass("dark-dot");
206
  lightMode = !lightMode;
207
  });
208
+ });