-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
1515 lines (1290 loc) · 44.4 KB
/
index.mjs
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/* ----##### Import packages BELOW #####---- */
// import { createApp } from 'vue'
import tippy from 'tippy.js'
import 'tippy.js/dist/tippy.css'
import Swal from 'sweetalert2'
import flatpickr from "flatpickr";
import "flatpickr/dist/flatpickr.min.css";
// let wsUrl = "ws://localhost:8000/stream_answer";
let wsUrl = "ws://localhost:8000/ws";
// let wsUrl = "wss://www.weiseeule.info/ws";
let ws; // Declare WebSocket variable outside to manage its state
let count_next = 0;
let count_prev = 0;
let count = 0;
let tableCounter = 0; // Counter to ensure unique table IDs
/* ----##### USER DEFINED FUNCTIONS START #####---- */
function appendDataFrame(df) {
const parsedData = JSON.parse(df);
var modal = document.getElementById("dataModal");
var span = document.getElementById("dataModal-close");
span.onclick = function () {
modal.style.display = "none";
$('#dataTable').off('click', 'tbody tr');
}
// Check and Destroy Previous DataTable Instances
if ($.fn.DataTable.isDataTable('#dataTable')) {
$('#dataTable').DataTable().destroy();
$('#dataTable tbody').empty();
$('#dataTableHeaders').empty();
}
// Use parsedData.columns directly since it's already an array
var columnsDef = parsedData.columns.map(col => ({ title: col }));
// Dynamically generate table headers
parsedData.columns.forEach(col => {
$('#dataTableHeaders').append('<th>' + col.replace(/_/g, ' ').charAt(0).toUpperCase() + col.slice(1) + '</th>');
});
// Initialize DataTable
var table = $('#dataTable').DataTable({
data: parsedData.data,
columns: columnsDef,
order: [],
responsive: true
});
/* Show the modal upon successful DataFrame reception */
// modal.style.display = "block";
// $('#dataModal').show();
/* In the updated code hide the DataFrame */
$('#dataModal').hide();
}
/* #################################################### */
/* Append search DataFrame as DataTable separately for each question */
function appendSearchDataFrame(df, container, query) {
const parsedData = JSON.parse(df);
// Increment the table counter to create a unique ID
tableCounter++;
const tableId = `dataTableSearch${tableCounter}`;
// Create table structure
const table = document.createElement('table');
table.id = tableId;
table.className = 'display'; // Only use display class if necessary
const thead = document.createElement('thead');
const tr = document.createElement('tr');
// Add a header for the checkbox column
const thCheckbox = document.createElement('th');
thCheckbox.innerHTML = '';
tr.appendChild(thCheckbox);
parsedData.columns.forEach(col => {
const th = document.createElement('th');
th.textContent = col.replace(/_/g, ' ').charAt(0).toUpperCase() + col.slice(1);
tr.appendChild(th);
});
thead.appendChild(tr);
table.appendChild(thead);
const tbody = document.createElement('tbody');
table.appendChild(tbody);
container.appendChild(table);
// Map data to match DataTables format and add checkboxes
const data = parsedData.data.map(row => {
return ['', ...row];
});
// Initialize DataTable with unique ID
$(`#${tableId}`).DataTable({
data: data,
columns: [
{ title: '', orderable: false }, // Checkbox column
...parsedData.columns.map(col => ({ title: col }))
],
columnDefs: [
{
orderable: false,
render: DataTable.render.select(),
targets: 0
}
],
order: [],
fixedColumns: {
start: 2
},
select: {
style: 'multi',
selector: 'td:first-child'
},
responsive: true,
layout: {
topStart: {
buttons: [
{
text: 'Summarize',
action: function () {
// Create a div to display the PMIDs
const summaryDiv = document.createElement('div');
summaryDiv.id = `summaryDiv${tableCounter}`;
container.appendChild(summaryDiv);
var my_table = $(`#${tableId}`).DataTable();
let count = my_table.rows({ selected: true }).count();
let selected_data = my_table.rows({ selected: true }).data();
console.log(count + ' row(s) selected');
// Initialize the new array to store the extracted numbers
let extractedNumbers = [];
// Iterate through each element in the selected_data array
for (var i = 0; i < selected_data.length; i++) {
console.log('selected_data[' + i + ']:- ', selected_data[i]);
console.log('selected_data[' + i + '][1]:- ', selected_data[i][1]);
let parts = selected_data[i][1].split('>');
if (parts.length > 1) {
let numberPart = parts[1].split('<')[0];
console.log('numberPart:-', numberPart);
extractedNumbers.push(numberPart);
}
}
// Output the new array
console.log('extractedNumbers:-', extractedNumbers); // Output: ["34000094", "34000005"]
// Send the selected PMIDs to the backend for processing
sendPMIDsToBackend(extractedNumbers.join(','), `summaryDiv${tableCounter}`, query);
}
}
]
}
}
});
// Add dynamic CSS rules
addDynamicTableStyles(tableId);
}
// Function to send PMIDs to python backend based on checkbox selection
function sendPMIDsToBackend(pmids, summaryDivId, query) {
var llm = document.getElementById('select_llm').value;
ws = new WebSocket(wsUrl + "/summarize_abstracts");
const params = {
llm: llm,
pmids: pmids,
query: query
}
ws.onopen = () => {
console.log("WebSocket connection opened.");
ws.send(JSON.stringify(params));
// Clear the previous summary content below the "Summary:" heading
const summaryDiv = document.getElementById(summaryDivId);
summaryDiv.innerHTML = "<strong>Summary:</strong><br>";
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
const { summary, error, end_summary } = data;
if (error) {
console.error(error);
Swal.fire({
icon: 'error',
title: "Error in summarization",
text: error,
allowOutsideClick: false
});
return;
}
if (summary) {
document.getElementById(summaryDivId).innerHTML += summary;
}
if (end_summary) {
console.log("End of Summary");
ws.close();
}
};
ws.onclose = () => {
console.log("WebSocket connection closed.");
};
ws.onerror = (error) => {
console.error("WebSocket error:", error);
ws.close();
};
}
/* #################################################### */
function addDynamicTableStyles(tableId) {
const style = document.createElement('style');
// style.type = 'text/css';
style.innerHTML = `
#${tableId} {
width: 100% !important;
border-collapse: collapse !important;
}
#${tableId} th {
background-color: #7491c4;
color: black;
}
#${tableId} tbody tr:nth-child(odd) {
background-color: #c2b4d2;
}
#${tableId} tbody tr:nth-child(even) {
background-color: rgb(222, 206, 235);
}
#${tableId} tbody tr:hover {
background-color: #9bbffc;
}
#${tableId} th, #${tableId} td {
padding: 8px;
// border: 1px solid #005eff;
border: 1px solid #A0AFB7;
text-align: left;
}
`;
document.getElementsByTagName('head')[0].appendChild(style);
}
/* #################################################### */
function setupChatElements(ws, params) {
// Prepare message containers for chat
const elements = createMessageContainerElements('chat-area');
ws.chatArea = elements.chatArea;
ws.messageContainer = elements.messageContainer;
const userElements = createUserMessageElements();
ws.userMessageContainer = userElements.userMessageContainer;
ws.userMessage = userElements.userMessage;
const botElements = createBotMessageElements();
ws.botMessageContainer = botElements.botMessageContainer;
ws.botMessage = botElements.botMessage;
// Display user's query
ws.userMessage.textContent = params.query;
ws.userMessageContainer.appendChild(ws.userMessage);
ws.messageContainer.appendChild(ws.userMessageContainer);
let formattedMessage = "<b>Answer:</b><br>";
ws.botMessage.innerHTML += formattedMessage;
ws.botMessageContainer.appendChild(ws.botMessage);
ws.messageContainer.appendChild(ws.botMessageContainer);
}
function setupSearchElements(ws, params) {
// Prepare message containers for search
const elements = createMessageContainerElements('search-area');
ws.searchArea = elements.chatArea;
ws.messageContainer = elements.messageContainer;
const userElements = createUserMessageElements();
ws.userMessageContainer = userElements.userMessageContainer;
ws.userMessage = userElements.userMessage;
const botElements = createBotMessageElements();
ws.botMessageContainer = botElements.botMessageContainer;
ws.botMessage = botElements.botMessage;
// Display user's query
ws.userMessage.textContent = params.query;
ws.userMessageContainer.appendChild(ws.userMessage);
ws.messageContainer.appendChild(ws.userMessageContainer);
let formattedMessage = "<b>Top 10 Relevant PMIDs:</b><br><br>";
ws.botMessage.innerHTML += formattedMessage;
ws.botMessageContainer.appendChild(ws.botMessage);
ws.messageContainer.appendChild(ws.botMessageContainer);
}
/* #################################################### */
function handleSearchPubmedMessage(event, ws, params) {
/* Stop loader on first message */
Swal.close();
/* Scroll search area top to make strem visble continuously */
ws.searchArea.scrollTop = ws.searchArea.scrollHeight;
const data = JSON.parse(event.data);
const { content, citation, last_content, error, df } = data;
if (error) {
console.error(error);
Swal.fire({
icon: 'error',
title: "Error in PubMed Search",
text: error,
allowOutsideClick: false
});
ws.close();
// return;
}
let formattedMessage = "";
if (citation) {
formattedMessage = "<br><br><b>Citation:</b><br>" + citation;
ws.botMessage.innerHTML += formattedMessage;
}
if (content) {
ws.botMessage.innerHTML += content;
}
if (df) {
console.log('Received dataframe:');
appendSearchDataFrame(df, ws.botMessage, params.query);
}
if (last_content) {
ws.close();
}
}
/* #################################################### */
/* JavaScript function to toggle the context visibility */
function toggleContext(contextId) {
const contextDiv = document.getElementById(contextId);
const toggleSymbol = contextDiv.previousElementSibling;
if (contextDiv.style.display === "none") {
contextDiv.style.display = "block";
toggleSymbol.textContent = "[-]";
} else {
contextDiv.style.display = "none";
toggleSymbol.textContent = "[+]";
}
}
function handleStreamAnswerMessage(event, ws, params) {
/* Stop loader on first message */
Swal.close();
/* Scroll chat area top to make strem visble continuously */
ws.chatArea.scrollTop = ws.chatArea.scrollHeight;
const data = JSON.parse(event.data);
const { content, citation, context, last_context, error, df } = data;
if (error) {
console.error(error);
Swal.fire({
icon: 'error',
title: "Error in chat completion",
text: error,
allowOutsideClick: false
});
ws.close();
return;
}
let formattedMessage = "";
if (citation) {
formattedMessage = "<br><br><b>Citation:</b><br>" + citation;
ws.botMessage.innerHTML += formattedMessage;
}
/* Working */
if (context) {
// Create a toggle container for the context
const contextId = `context-${Date.now()}`; // Unique ID for each context
// Append HTML for context with toggle functionality
formattedMessage = `
<br><br>
<b>Context:</b>
<span class="toggle-symbol" data-toggle-id="${contextId}">[+]</span>
<div id="${contextId}" class="context-content" style="display: none;">${context}</div>
`;
ws.botMessage.innerHTML += formattedMessage;
// Add event listener to toggle the visibility
const toggleSymbol = document.querySelector(`.toggle-symbol[data-toggle-id="${contextId}"]`);
toggleSymbol.addEventListener('click', function () {
toggleContext(contextId, toggleSymbol);
});
if (params.answer_per_paper === 'True') {
formattedMessage = "<br><b>Answer:</b><br>";
ws.botMessage.innerHTML += formattedMessage;
} else if (params.rerank == 'False') {
ws.close();
}
}
if (last_context) {
const lastContextId = `last-context-${Date.now()}`;
formattedMessage = `
<br><br>
<b>Context:</b>
<span class="toggle-symbol" data-toggle-id="${lastContextId}">[+]</span>
<div id="${lastContextId}" class="context-content" style="display: none;">${last_context}</div>
`;
// formattedMessage = "<br><br><b>Context:</b><br>" + last_context;
ws.botMessage.innerHTML += formattedMessage;
// Add event listener to toggle the visibility
const toggleSymbol = document.querySelector(`.toggle-symbol[data-toggle-id="${lastContextId}"]`);
toggleSymbol.addEventListener('click', function () {
toggleContext(lastContextId, toggleSymbol);
});
if (params.rerank == 'False') {
ws.close();
}
}
if (content) {
ws.botMessage.innerHTML += content;
}
if (df) {
appendDataFrame(df);
ws.close();
}
}
/* #################################################### */
function openWebSocket(end_point, params, setupElements, messageHandler) {
ws = new WebSocket(wsUrl + end_point);
ws.onopen = () => {
console.log("WebSocket connection opened.");
// Send params only when WebSocket connection is open
ws.send(JSON.stringify(params));
console.log('Params sent to WebSocket: ', JSON.stringify(params));
setupElements(ws, params);
};
ws.onmessage = (event) => {
messageHandler(event, ws, params);
};
ws.onclose = () => {
console.log("WebSocket connection closed.");
};
ws.onerror = (error) => {
console.error("WebSocket error:", error);
ws.close();
};
}
function serverError(error_message) {
Swal.fire({
icon: 'error',
title: 'Server Error',
text: `Could not communicate with the server. ${error_message}`,
customClass: {
container: 'my-swal'
},
});
}
function createMessageContainerElements(id_div) {
let chatArea = document.getElementById(id_div);
let messageContainer = document.getElementById(`${id_div}-message-container`);
if (!messageContainer) {
messageContainer = document.createElement('div');
messageContainer.id = `${id_div}-message-container`;
chatArea.insertBefore(messageContainer, chatArea.firstChild);
}
return { chatArea, messageContainer };
}
function createUserMessageElements() {
let userMessageContainer = document.createElement('div');
userMessageContainer.className = 'message-container user-message-container';
let userIcon = document.createElement('div');
userIcon.className = 'user-icon';
userMessageContainer.appendChild(userIcon);
let userMessage = document.createElement('div');
userMessage.className = 'message user-message';
return { userMessageContainer, userIcon, userMessage };
}
function createBotMessageElements() {
let botMessageContainer = document.createElement('div');
botMessageContainer.className = 'message-container bot-message-container';
let botIcon = document.createElement('div');
botIcon.className = 'bot-icon';
botMessageContainer.appendChild(botIcon);
let botMessage = document.createElement('div');
botMessage.className = 'message bot-message';
return { botMessageContainer, botIcon, botMessage };
}
// New function to handle login
async function handleLogin(e) {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// Validate username and password
if (!username || !password) {
Swal.fire({
icon: 'error',
title: 'Empty Fields',
text: 'Username and password must not be empty',
customClass: {
container: 'my-swal'
},
});
return true; // Keep the Swal open
}
// You can send this data to your server for authentication
try {
const response = await fetch('/api/validate_user/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Now the response is already a JSON object, so no need for JSON.parse
const result = await response.json();
console.log("Printing result below:");
console.log(result);
// Handle the response based on the result
if (result.code === "success") {
Swal.fire({
icon: 'success',
title: 'Successfully logged in!',
text: '',
customClass: {
container: 'my-swal'
},
});
// If authentication is successful
$('#loginModal').hide();
} else {
Swal.fire({
icon: 'error',
title: 'Authentication Failed',
text: result.message,
customClass: {
container: 'my-swal'
},
allowOutsideClick: false
});
}
} catch (error) {
serverError(error.message);
}
return true; // Keep the Swal open in case of an error
}
/* ----##### USER DEFINED FUNCTIONS END #####---- */
/* Handle datatable modal */
$(document).ready(function () {
// Hide datatable modal on page load
$('#dataModal').hide();
});
/* Handle login modal */
$(document).ready(function () {
// Show login modal on page load
$('#loginModal').show();
// Attach the login event handler
// $('#login-button').click(handleLogin);
// $('#login-button').click(showLoader(handleLogin));
$('#login-button').on('click', function (e) {
// showLoader(handleLogin, e);
showLoader(handleLogin, "Validating login ...", e);
});
// Event handler when the 'Enter' key is pressed
$(document).on('keypress', '#username, #password', function (e) {
if (e.which === 13) { // 13 is the key code for the 'Enter' key
// handleLogin(e);
// showLoader(handleLogin, e);
showLoader(handleLogin, "Validating login ...", e);
}
});
});
/* Show/Hide datatable modal
(useful when changing parameters like `One paper` or `All paper` after getting the datatable from python code)
*/
$(document).ready(function () {
let button_show_datatable = document.getElementById('show_datatable');
button_show_datatable.addEventListener('click', async () => {
if ($('#dataModal').is(':hidden')) {
$('#dataModal').show();
} else {
$('#dataModal').hide();
}
});
});
/* Handle params modal */
$(document).ready(function () {
let button_adv_params = document.getElementById('button_adv_params');
button_adv_params.addEventListener('click', async () => {
$("#setParametersModal").modal('show');
});
});
$(document).ready(function () {
// Hide all tab content initially
// $('#chat_panel').hide();
$('#search_panel').hide();
$('#pdf_panel').hide();
// Event listener for tab click
$('#tab_panels a').click(function (e) {
e.preventDefault();
// Get the target panel from the clicked tab's href attribute
var targetPanel = $(this).attr('href');
// Hide all panel contents
$('#chat_panel').hide();
$('#search_panel').hide();
$('#pdf_panel').hide();
// Show the targeted panel content
$(targetPanel).show();
// Set the clicked tab as active
$(this).tab('show');
});
});
$(document).ready(function () {
// Calculate the heights of the header and footer
var headerHeight = $("nav.main-header").outerHeight();
var footerHeight = $("footer.main-footer").outerHeight();
headerHeight += 100;
// Include paddings into the calculation
var paddingTop = parseFloat($('#container_fluid_outer').css('padding-top'));
// var paddingBot = parseFloat($('#container_fluid_outer').css('padding-bottom'));
headerHeight += paddingTop - 15;
// footerHeight += paddingBot;
// Calculate the appropriate height for #fluid_container1
var fluidContainerHeight = "calc(100vh - " + headerHeight + "px - " + footerHeight + "px)";
// console.log("fluidContainerHeight = " + fluidContainerHeight);
// Apply this height to #fluid_container1
$("#fluid_container1").css("height", fluidContainerHeight);
$("#fluid_container2").css("height", fluidContainerHeight);
// Calculate the appropriate height for #viewerContainer
var tabPanelsHeight = $("#tab_panels").outerHeight();
var pdfPanelsHeight = $("#pdf_panel").outerHeight();
var pdfPanelNavBarHeight = $("#navigation-bar").outerHeight();
// Reset the headerHeight to actual header height and then and required offsets
headerHeight = $("nav.main-header").outerHeight();
// console.log("headerHeight = " + headerHeight);
// console.log("tabPanelsHeight = " + tabPanelsHeight);
// console.log("pdfPanelsHeight = " + pdfPanelsHeight);
// console.log("pdfPanelNavBarHeight = " + pdfPanelNavBarHeight);
headerHeight += tabPanelsHeight + pdfPanelsHeight;
footerHeight += 8;
var viewerContainerHeight = "calc(100vh - " + headerHeight + "px - " + footerHeight + "px)";
$("#viewerContainer").css("margin-top", pdfPanelsHeight + 10);
// $("#pdf_area").css("margin-top", pdfPanelsHeight + 10);
// var marginTop = parseFloat($('#viewerContainer').css('margin-top'));
// console.log("marginTop = " + marginTop);
// Apply this height to #viewerContainer
// $("#viewerContainer").css("height", viewerContainerHeight);
$("#pdf_area").css("height", viewerContainerHeight);
});
/* ----##### Set tooltips for params #####---- */
tippy('#tooltip_select_llm', {
content: 'Select an LLM, GPT-3.5 is much cheaper but less powerful than GPT-4. \
For complex queries GPT-4 performs significantly better.',
theme: 'my-tippy-theme'
});
tippy('#tooltip_select_namespace', {
content: 'Select a relevant namespace. \
A relevant namespace is the one that contains matching contexts to your query. \
Selecting irrelevant namespace might result in sub-optimal answer and hence \
waste tokens/money unnecessarily.',
theme: 'my-tippy-theme'
});
// tippy('#tooltip_review_mode', {
// content: 'Search PubMed for relevant hits. \
// Set this to `True` when you want to find article relevant to you keyword or query. \
// Use `Search` panel to type your keyword when using this feature.',
// theme: 'my-tippy-theme'
// });
tippy('#tooltip_search_namespace', {
content: 'Enter a valid PubMed ID to be searched in the selected namespace.',
theme: 'my-tippy-theme'
});
tippy('#tooltip_advanced_params', {
content: 'Advanced params are used to configure the app for more sophistcated search.',
theme: 'my-tippy-theme'
});
tippy('#tooltip_show_datatable', {
content: 'Show/Hide datatable modal (obtained after re-ranking chunks by keyword frequencies).',
theme: 'my-tippy-theme'
});
tippy('#tooltip_top_k', {
content: 'Enter how many relevant (to query) chunks to be retrieved from vector DB. \
The minimum is 1 and the maximum depends on the LLM selected. \
Roughly, for GPT-3.5 it is 7 and for GPT-4 it is 15.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_temp', {
content: 'Select sampling temperature to use (between 0-2). \
Higher values like 0.8 will make the output more random, \
while lower values close to 0 will make it more focused and deterministic. \
In most of the cases you do not need to change this parameter.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_embedd_model', {
content: 'Select the embedding model used to convert text into numbers (during namespace generation). \
We used `biobert` for text embedding and is the only option provided in this version',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_paper_id', {
content: 'Provide a valid paper ID from the re-ranking table to limit the answer \
generated using the chunks of that paper only.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_rerank', {
content: 'Select True, if you want to re-rank chunks \
based on keyword frequencies. By default, this option is on.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_fix_keyword', {
content: 'Activate only with `Rerank = True` to use primary keywords \
to guide re-ranking. See documentation for the algorithm.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_template', {
content: 'This is field is optional and blank by default. Here you can input further \
information that you think might help the model to generate mode precise \
response to your query. Once set, remember to change/clear this field once you move on to a \
different query where the current template is not relevant.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_answer_per_paper', {
content: 'Enable for answers from individual chunks. \
By default, answers use information from the entire prompt.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_chunks_from_one_paper', {
content: 'Set to `True` to confine answers to a selected paper, ensuring `paper_id` is set. \
Off by default.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_select_rows_table', {
content: 'Enable to choose specific rows from the re-ranking table. \
Defaults: top 5 for GPT3.5, top 10 for GPT-4.',
zIndex: 10001,
theme: 'my-tippy-theme'
});
tippy('#tooltip_keywords', {
content: 'Enter keywords to be searched in titles/abstracts',
theme: 'my-tippy-theme'
});
// tippy('#tooltip_template', {
// content: 'Enter a template to be prefixed with your prompt',
// theme: 'my-tippy-theme'
// });
tippy('#tooltip_date', {
content: 'Select date ranges',
theme: 'my-tippy-theme'
});
/* ----##### Dynamically add namespaces #####---- */
window.onload = async function () {
// Fetch the namespaces from the server-side
let response = await fetch('/api/getNamespaces');
let namespaces = await response.json();
const select = document.getElementById('select_namespace');
// List of options you want to add
// let options = Object.keys(namespaces);
let options = namespaces;
// Dynamically creating options and appending to select
options.forEach(optionValue => {
// console.log("optionValue = " + optionValue);
let option = document.createElement('option');
option.value = optionValue;
option.text = optionValue;
select.appendChild(option);
});
}
/* ----##### side window date picker #####---- */
let startDate;
let endDate;
const startInput = document.querySelector("#start-date");
const endInput = document.querySelector("#end-date");
const startPicker = flatpickr(startInput, {
dateFormat: "Y/m/d",
onChange: function (selectedDates, dateStr, instance) {
startDate = selectedDates[0];
if (endPicker) {
endPicker.set('minDate', startDate);
}
},
});
const endPicker = flatpickr(endInput, {
dateFormat: "Y/m/d",
maxDate: new Date(), // set maxDate to current date
onChange: function (selectedDates, dateStr, instance) {
endDate = selectedDates[0];
if (startPicker) {
startPicker.set('maxDate', endDate);
}
},
});
/* ----##### calling python from JS #####---- */
/* Search namespace */
var button_search_namespace = document.getElementById('button_search_namespace');
button_search_namespace.addEventListener('click', async () => {
const namespace = document.getElementById('select_namespace').value;
const pmid = document.getElementById('search_namespace').value;
console.log("Selected namespace = " + namespace);
console.log("Entered PMID = " + pmid);
const params = {
namespace: namespace,
pmid: pmid
}
// Show intermediate progress bar
document.getElementById('progress-container').classList.remove('hidden');
const end_point = "/search_PMID_in_namespace";
ws = new WebSocket(wsUrl + end_point);
ws.onopen = () => {
console.log("WebSocket connection opened.");
ws.send(JSON.stringify(params));
};
ws.onmessage = (event) => {
console.log('event.data = ', event.data);
const result = JSON.parse(event.data);
document.getElementById('progress-container').classList.add('hidden');
// Handle the response based on the result
if (result.code === "failure") {
console.error(result.code);
Swal.fire({
icon: 'error',
title: 'Namespace search failed',
html: result.msg,
customClass: {
container: 'my-swal'
},
allowOutsideClick: false
});
return;
}
if (result.code === "not found") {
console.error(result.code);
Swal.fire({
icon: 'warning',
title: 'PMID not found',
html: result.msg,
customClass: {
container: 'my-swal'
},
allowOutsideClick: false
});
return;
}
if (result.code === "success") {
console.error(result.code);
Swal.fire({
icon: 'success',
title: 'Search succeeded',
html: result.msg,
customClass: {
container: 'my-swal'
},
allowOutsideClick: false
});
return;
}
};
ws.onerror = (error) => {
console.error("WebSocket error:", error);
ws.close();
};
ws.onclose = () => {
console.log("WebSocket connection closed.");
};
});
/* PMC article downloader params (WebSocket version) */
var button_fetch_articles = document.getElementById('button_fetch_articles');
button_fetch_articles.addEventListener('click', async () => {
const embedd_model = document.getElementById('select_embedd_model').value;