-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
266 lines (251 loc) · 6.74 KB
/
index.js
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
import {
setupDailyControls,
setupStoreQuery,
setupUploadForm,
updateStatus,
updateUploadsPendingIndexing,
enableStoreControls,
setupIndexUploads,
disableIndexUploads,
disableStoreControls,
enableStoreQuery,
updateResponse,
enableIndexUploads,
updateUploadError,
disableStoreQuery,
updateUploadsInProgress,
disableUploadBtn,
enableUploadBtn,
} from './dom.js';
const apiURL = 'http://127.0.0.1:5000';
window.addEventListener('DOMContentLoaded', () => {
fetchCapabilities().then((capabilities) => {
if (capabilities.daily === true) {
setupDailyControls(indexDailyRecordings);
}
});
setupUploadForm(uploadFiles);
setupIndexUploads(indexUploads);
setupStoreQuery(runQuery);
pollVectorStoreStatus(1);
pollUploads(1);
});
/**
* Retrieve server capabilities
* In this case, the specific value we care about is whether a Daily API key is configured
* @returns {Promise<any>}
*/
function fetchCapabilities() {
return fetch(`${apiURL}/status/capabilities`, { method: 'GET' })
.then((res) => {
if (res.ok === false) {
throw Error(`Failed to fetch server capabilities: ${res.status}`);
}
return res.json();
})
.catch((e) => {
console.error('Failed to fetch app capabilities:', e);
});
}
/**
* Upload files to the server for future indexing
* @param files
*/
function uploadFiles(files) {
// Clear upload error for fresh upload.
updateUploadError('');
const errors = [];
disableUploadBtn();
for (let i = 0; i < files.length; i += 1) {
const file = files[i];
// Size sanity check; otherwise server will reject it anyway.
if (file.size > 1000000 * 60) {
errors.push(`File ${file.name} over 60MB size limit. Not uploading.`);
continue;
}
const formData = new FormData();
formData.append('file', file);
// Upload the selected file to the server. This will not start indexing,
// only prepare the files.
fetch(`${apiURL}/upload`, { method: 'POST', body: formData })
.then((res) => {
if (res.ok === false) {
throw Error(
`upload request failed for file: ${res.status} {${file.name}`,
);
}
})
.catch((e) => {
const msg = `Failed to upload file ${file.name}`;
console.error(msg, e);
errors.append(`${msg} - see console for details`);
enableUploadBtn();
})
.finally(() => {
// Fetch file uploads in progress immediately for faster UI update.
fetchUploads();
enableUploadBtn();
updateUploadError(errors.join(' '));
});
}
}
/**
* Index Daily recordings
* @param roomName
* @param maxRecordings
*/
function indexDailyRecordings(roomName, maxRecordings) {
const body = {
source: 'daily',
room_name: roomName,
max_recordings: maxRecordings,
};
doIndex(body);
}
/**
* Index manually-uploaded files that are already on the server
*/
function indexUploads() {
const body = {
source: 'uploads',
};
doIndex(body);
}
/**
* Instruct the server to commence index creation or update based on given configuration
* @param body
*/
function doIndex(body) {
fetch(`${apiURL}/db/index`, { method: 'POST', body: JSON.stringify(body) })
.then((res) => {
if (res.ok === false) {
throw Error(`Unexpected status code: ${res.status}`);
}
})
.catch((e) => {
console.error('Failed to initialize or update database:', e);
});
}
/**
* Queries the existing index with the given input.
* @param queryInput
*/
function runQuery(queryInput) {
disableStoreQuery(true);
fetch(`${apiURL}/db/query`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: queryInput,
}),
})
.then((res) => {
if (res.ok === false) {
throw Error(`Unexpected status code: ${res.status}`);
}
return res.json();
})
.then((res) => {
// Update the DOM with the retrieved response.
const { answer } = res;
updateResponse(answer);
enableStoreQuery();
})
.catch((e) => {
console.error('Failed to run query:', e);
});
}
/**
* Poll the status of the vector store
* @param timeoutMs
*/
function pollVectorStoreStatus(timeoutMs) {
setTimeout(() => {
// Fetch status of the given project from the server
fetch(`${apiURL}/status/db`)
.then((res) => {
if (!res.ok) {
throw Error(`status request failed: ${res.status}`);
}
return res.json();
})
.then((data) => {
const { state, message } = data;
switch (state) {
case 'uninitialized':
updateStatus(state, message);
enableStoreControls();
pollVectorStoreStatus(3000);
break;
case 'updating':
updateStatus(state, message, true);
enableStoreQuery();
pollVectorStoreStatus(3000);
break;
case 'ready':
updateStatus(state, message);
enableStoreQuery();
enableStoreControls();
// Poll less frequently if index is ready
pollVectorStoreStatus(10000);
break;
case 'failed':
updateStatus(state, message);
enableStoreControls();
pollVectorStoreStatus(3000);
break;
default:
updateStatus(state, message, true);
disableStoreControls();
pollVectorStoreStatus(3000);
break;
}
})
.catch((err) => {
console.error('failed to check project status: ', err);
pollVectorStoreStatus(3000);
});
}, timeoutMs);
}
/**
* Checks which manual uploads are pending indexing on the server.
* @param timeoutMs
*/
function pollUploads(timeoutMs) {
setTimeout(() => {
// Fetch status of the given project from the server
fetchUploads();
pollUploads(5000);
}, timeoutMs);
}
/**
* Fetches uploads in progress and pending indexing on the server
* and updates the DOM accordingly.
*/
function fetchUploads() {
fetch(`${apiURL}/status/uploads`)
.then((res) => {
if (!res.ok) {
throw Error(`upload retrieval request failed: ${res.status}`);
}
return res.json();
})
.then((uploads) => {
const { completed } = uploads;
// If there are no uploads to index, disable index button
if (completed.length === 0) {
disableIndexUploads();
} else {
enableIndexUploads();
}
// Update the DOM with the new uploaded file information
updateUploadsPendingIndexing(completed);
updateUploadsInProgress(uploads.in_progress);
})
.catch((err) => {
console.error('failed to check upload status: ', err);
});
}