-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
2008 lines (1647 loc) · 67.5 KB
/
main.py
File metadata and controls
2008 lines (1647 loc) · 67.5 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
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
import os
import uuid
import threading
import copy
import requests
import json
import logging
import logging.config
import secrets
from urllib.parse import urlsplit, urlencode, quote
import importlib
import hmac
from concurrent.futures import ThreadPoolExecutor, as_completed
from flask import (
Flask,
Response,
render_template,
request,
make_response,
session,
jsonify,
redirect,
flash,
url_for,
abort,
send_from_directory,
abort,
)
from flask_login import (
LoginManager,
UserMixin,
login_user,
logout_user,
current_user,
login_required,
)
from flask_session import Session
from werkzeug.middleware.proxy_fix import ProxyFix
from config import Config
from chatbot import chatbot
from objects import Article
import utils
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
logging.config.fileConfig(os.getenv("LOGGING_FILE_CONFIG", "./logging.conf"))
logger = logging.getLogger("nfdi_search_engine")
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1) # If you have one proxy
limiter = Limiter(
utils.get_client_ip,
app=app,
default_limits=["500 per day", "120 per hour"],
storage_uri="memory://",
# Redis
# storage_uri="redis://localhost:6379",
# Redis cluster
# storage_uri="redis+cluster://localhost:7000,localhost:7001,localhost:70002",
# Memcached
# storage_uri="memcached://localhost:11211",
# Memcached Cluster
# storage_uri="memcached://localhost:11211,localhost:11212,localhost:11213",
# MongoDB
# storage_uri="mongodb://localhost:27017",
strategy="fixed-window", # or "moving-window", or "sliding-window-counter"
)
app.config.from_object(Config)
Session(app)
login_manager = LoginManager(app)
login_manager.login_view = "login"
# region MODELS
from typing import Optional
from werkzeug.security import generate_password_hash, check_password_hash
from pydantic.dataclasses import dataclass
from dataclasses import fields, field
from flask_login import UserMixin
# ...
@dataclass
class User(UserMixin):
id: str = ""
first_name: str = ""
last_name: str = ""
email: str = ""
password_hash: str = ""
oauth_source: str = "self"
included_data_sources: str = ""
excluded_data_sources: str = ""
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
def __repr__(self):
return "{} {}".format(self.first_name, self.last_name)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def get_id(self):
return self.id
@login_manager.user_loader
def load_user(id):
user = User()
user.id = id
user = utils.get_user_by_id(user)
return user
# endregion
# region FORMS
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, widgets
from wtforms.validators import (
ValidationError,
DataRequired,
Email,
EqualTo,
StopValidation,
)
from wtforms.fields import SelectMultipleField
class LoginForm(FlaskForm):
email = StringField("Email", validators=[DataRequired()])
password = PasswordField("Password", validators=[DataRequired()])
remember_me = BooleanField("Remember Me")
submit = SubmitField("Login")
class RegistrationForm(FlaskForm):
first_name = StringField("First Name", validators=[DataRequired()])
last_name = StringField("Last Name", validators=[DataRequired()])
email = StringField("Email", validators=[DataRequired(), Email()])
password = PasswordField("Password", validators=[DataRequired()])
password2 = PasswordField(
"Repeat Password", validators=[DataRequired(), EqualTo("password")]
)
submit = SubmitField("Register")
# def validate_username(self, username):
# user = db.session.scalar(sa.select(User).where(
# User.username == username.data))
# if user is not None:
# raise ValidationError('Please use a different username.')
# def validate_email(self, email):
# user = db.session.scalar(sa.select(User).where(
# User.email == email.data))
# if user is not None:
# raise ValidationError('Please use a different email address.')
class ProfileForm(FlaskForm):
first_name = StringField("First Name", validators=[DataRequired()])
last_name = StringField("Last Name", validators=[DataRequired()])
email = StringField(
"Email",
render_kw={"disabled": "disabled"},
)
submit = SubmitField("Save")
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(html_tag="ol", prefix_label=False)
option_widget = widgets.CheckboxInput()
class MultiCheckboxAtLeastOne:
def __init__(self, message=None):
if not message:
message = "At least one option must be selected."
self.message = message
def __call__(self, form, field):
if len(field.data) == 0:
raise StopValidation(self.message)
class PreferencesForm(FlaskForm):
data_sources = MultiCheckboxField(
"Data Sources", validators=[MultiCheckboxAtLeastOne()], coerce=str
)
submit = SubmitField("Save")
# endregion
# region JINJA2 FILTERS
from jinja2.filters import FILTERS
from urllib.parse import quote, unquote
FILTERS["quote"] = lambda x: quote(str(x), safe="")
import json
import time
import base64
# encode the value for the URL
def url_encode(value: str | bytes | None) -> str:
if not value:
return ""
# ensure str for quote()
if isinstance(value, bytes):
value = value.decode()
encoded = quote(str(value), safe="") # '/' -> %2F, space -> %20, ...
return encoded.replace("%2F", "%252F") # double-encode slash
def format_digital_obj_url(obj, *fields) -> str:
"""
Jinja usage examples
{{ resource | format_digital_obj_url('identifier', 'source_id') }}
{{ resource | format_digital_obj_url(['identifier', 'source_id']) }}
"""
# accept either *fields or a single iterable
if len(fields) == 1 and isinstance(fields[0], (list, tuple)):
fields = fields[0]
# implement special cases here
def _get(field: str) -> str | None:
match field:
case "source-id":
# if a source identifier is available, use it, otherwise 'na'
if getattr(obj, "source", "") and getattr(
obj.source[0], "identifier", ""
):
val = obj.source[0].identifier
else:
val = "na"
case "source-name":
val = obj.source[0].name if getattr(obj, "source", "") else "na"
case "doi" | "orcid":
val = obj.identifier if getattr(obj, "identifier", "") else "na"
case _:
val = getattr(obj, field, "")
# print(f"{field=}, {val=}")
return val
parts = [f"{f}:{url_encode(_get(f))}" for f in fields if _get(f)]
current_timestamp = str(time.time())
timestamp_signature = (
base64.urlsafe_b64encode(current_timestamp.encode())
.rstrip(b"=")
.decode("utf-8")
)
parts.append(f"ts:{timestamp_signature}")
return "/".join(parts)
def get_researcher_url(person, external=True) -> str:
"""
Jinja usage example
{{ person | get_researcher_url }}
"""
if getattr(person, "additionalType", "").lower() != "person":
return ""
if not getattr(person, "identifier", None):
return ""
orcid_id = str(person.identifier).split("/")[-1]
if (
getattr(person, "source", None)
and person.source
and getattr(person.source[0], "identifier", None)
):
src_name = person.source[0].name
src_id = person.source[0].identifier
else:
src_name = "na" # source name is 'na' if not available
src_id = orcid_id
current_timestamp = str(time.time())
timestamp_signature = (
base64.urlsafe_b64encode(current_timestamp.encode())
.rstrip(b"=")
.decode("utf-8")
)
return url_for(
"researcher_details",
source_name=f"source-name:{url_encode(src_name)}",
source_id=f"source-id:{url_encode(src_id)}",
orcid=f"orcid:{url_encode(orcid_id)}",
ts=f"ts:{url_encode(timestamp_signature)}",
_external=external,
)
# Flask‐Jinja registration
FILTERS["get_researcher_url"] = get_researcher_url
FILTERS["format_digital_obj_url"] = format_digital_obj_url
def format_authors_for_citations(value):
authors = ""
for author in value:
authors += author.name + " and "
return authors.rstrip(" and ") + "."
FILTERS["format_authors_for_citations"] = format_authors_for_citations
import re
def regex_replace(s, find, replace):
"""A less non-optimal implementation of a regex filter"""
if s is None:
s_str = ""
elif isinstance(s, (bytes, bytearray)):
s_str = s.decode("utf-8", errors="replace")
else:
s_str = str(s)
try:
out = re.sub(find, replace, s_str)
except re.error:
out = s_str
return out
FILTERS["regex_replace"] = regex_replace
# endregion
# region ROUTES
@app.route("/robots.txt")
def robots():
return send_from_directory(app.static_folder, "robots.txt", mimetype="text/plain")
@app.route("/ping")
@limiter.limit("1 per 15 seconds")
def ping():
# check if all the environment variables are set
for env_variable in [
"SECRET_KEY",
"IEEE_API_KEY",
"CLIENT_ID_GOOGLE",
"CLIENT_SECRET_GOOGLE",
"CLIENT_ID_GITHUB",
"CLIENT_SECRET_GITHUB",
"CLIENT_ID_ORCID",
"CLIENT_SECRET_ORCID",
"OPENAI_API_KEY",
"LLAMA3_USERNAME",
"LLAMA3_PASSWORD",
"ELASTIC_SERVER",
"ELASTIC_USERNAME", #'ELASTIC_PASSWORD',
"CHATBOT_SERVER",
]:
if os.environ.get(env_variable, "") == "":
return make_response(
render_template(
"error.html",
error_message=f"Environment variable '{env_variable}' is not set.",
)
)
# check if the chatbot flag is enabled
if app.config["CHATBOT"]["chatbot_enable"] == False:
return make_response(
render_template("error.html", error_message=f"chatbot is not enabled.")
)
# check if all the indices exist; if any of the indices doesn't exist, create it
for idx in utils.ES_Index:
if not utils.es_client.indices.exists(index=idx.name):
try:
utils.es_client.indices.create(index=idx.name)
except Exception as ex:
return make_response(
render_template(
"error.html",
error_message=f"Elastic error while creating '{idx.name}': {ex.error}",
)
)
return jsonify(ping="NFDI4DS Gateway is up and running :) ")
@app.route("/login", methods=["GET", "POST"])
@limiter.limit("1 per minute")
def login():
if current_user.is_authenticated:
session["current-user-email"] = current_user.email
return redirect(session.get("back-url", url_for("index")))
# return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User()
user.email = form.email.data
res_flag, user = utils.get_user_by_email(user)
if not res_flag or not user.check_password(form.password.data):
flash("Invalid email or password", "danger")
return redirect(url_for("login"))
login_user(user, remember=form.remember_me.data)
session["current-user-email"] = user.email
next_page = request.args.get("next")
if not next_page or urlsplit(next_page).netloc != "":
next_page = session.get("back-url", url_for("index")) # url_for('index')
return redirect(next_page)
return render_template("login.html", title="Login", form=form)
@app.route("/logout")
@login_required
def logout():
logout_user()
flash("You have been logged out.", "info")
return redirect(session.get("back-url", url_for("index")))
@app.route("/register", methods=["GET", "POST"])
@limiter.limit("1 per minute")
def register():
if current_user.is_authenticated:
return redirect(url_for("index"))
form = RegistrationForm()
if form.validate_on_submit():
user = User()
user.first_name = form.first_name.data
user.last_name = form.last_name.data
user.email = form.email.data
user.set_password(form.password.data)
utils.add_user(user)
flash("Congratulations, you are now a registered user!", "success")
return redirect(url_for("login"))
return render_template("register.html", title="Register", form=form)
# authization code copied from https://github.com/miguelgrinberg/flask-oauth-example
@app.route("/authorize/<provider>")
def oauth2_authorize(provider):
if not current_user.is_anonymous:
return redirect(url_for("index"))
provider_data = app.config["OAUTH2_PROVIDERS"].get(provider)
if provider_data is None:
abort(404)
# generate a random string for the state parameter
session["oauth2_state"] = secrets.token_urlsafe(16)
# create a query string with all the OAuth2 parameters
qs = urlencode(
{
"client_id": provider_data["client_id"],
"redirect_uri": url_for(
"oauth2_callback",
provider=provider,
_external=True,
_scheme=os.environ.get("PREFERRED_URL_SCHEME", "https"),
),
"response_type": "code",
"scope": " ".join(provider_data["scopes"]),
"state": session["oauth2_state"],
}
)
# redirect the user to the OAuth2 provider authorization URL
return redirect(provider_data["authorize_url"] + "?" + qs)
@app.route("/callback/<provider>")
def oauth2_callback(provider):
if not current_user.is_anonymous:
return redirect(url_for("index"))
provider_data = app.config["OAUTH2_PROVIDERS"].get(provider)
if provider_data is None:
abort(404)
# if there was an authentication error, flash the error messages and exit
if "error" in request.args:
for k, v in request.args.items():
if k.startswith("error"):
flash(f"{k}: {v}")
return redirect(url_for("index"))
# make sure that the state parameter matches the one we created in the
# authorization request
if request.args["state"] != session.get("oauth2_state"):
abort(401)
# make sure that the authorization code is present
if "code" not in request.args:
abort(401)
# exchange the authorization code for an access token
response = requests.post(
provider_data["token_url"],
data={
"client_id": provider_data["client_id"],
"client_secret": provider_data["client_secret"],
"code": request.args["code"],
"grant_type": "authorization_code",
"redirect_uri": url_for(
"oauth2_callback",
provider=provider,
_external=True,
_scheme=os.environ.get("PREFERRED_URL_SCHEME", "https"),
),
},
headers={"Accept": "application/json"},
)
if response.status_code != 200:
abort(401)
oauth2_token = response.json().get("access_token")
if not oauth2_token:
abort(401)
# use the access token to get the user's email address
response = requests.get(
provider_data["userinfo"]["url"],
headers={
"Authorization": "Bearer " + oauth2_token,
"Accept": "application/json",
},
)
if response.status_code != 200:
abort(401)
email = provider_data["userinfo"]["email"](response.json())
# find or create the user in the database
user = User()
user.email = email
# extract the local part of the email and derive the name from it
full_name = email.split("@")[0]
full_name_with_spaces = (
full_name.replace("-", " ").replace(".", " ").replace("_", " ")
)
full_name_tokens = full_name_with_spaces.split(" ")
if len(full_name_tokens) > 1:
user.first_name = full_name_tokens[0]
user.last_name = full_name_tokens[1]
else:
user.first_name = full_name
response_flag, user = utils.get_user_by_email(user)
if response_flag: # user (email) already exists
if provider != user.oauth_source:
user.oauth_source = provider
utils.update_user(user)
else:
utils.add_user(user)
# log the user in
login_user(user)
return redirect(url_for("index"))
@app.route("/profile", methods=["GET", "POST"])
@limiter.limit("10 per minute")
@login_required
def profile():
form = ProfileForm()
if form.validate_on_submit():
current_user.first_name = form.first_name.data
current_user.last_name = form.last_name.data
# current_user.email = form.email.data
utils.update_user(current_user)
flash("Your changes have been saved.", "success")
return redirect(url_for("profile"))
elif request.method == "GET":
form.first_name.data = current_user.first_name
form.last_name.data = current_user.last_name
form.email.data = current_user.email
return render_template(
"profile.html",
title="Profile",
form=form,
back_url=session.get("back-url", url_for("index")),
)
@app.route("/preferences", methods=["GET", "POST"])
@limiter.limit("10 per minute")
@login_required
def preferences():
form = PreferencesForm()
# populate the forms dynamically with the values in the configuration and database
data_sources_list = app.config["DATA_SOURCES"]
form.data_sources.choices = sorted(
[(source, source) for source in app.config["DATA_SOURCES"].keys()]
)
# if it's a post request and we validated successfully
if request.method == "POST" and form.validate_on_submit():
# get our choices again, could technically cache these in a list if we wanted but w/e
all_sources = app.config["DATA_SOURCES"].keys()
# need a list to hold the selections
included_data_sources = []
excluded_data_sources = []
# looping through the choices, we check the choice ID against what was passed in the form
for source in all_sources:
# when we find a match, we then append the Choice object to our list
if source in form.data_sources.data:
included_data_sources.append(source)
else:
excluded_data_sources.append(source)
# now all we have to do is update the users choices records
current_user.included_data_sources = "; ".join(included_data_sources)
current_user.excluded_data_sources = "; ".join(excluded_data_sources)
utils.update_user_preferences_data_sources(current_user)
flash("Your preferences have been saved.", "success")
else:
# tell the form what's already selected
form.data_sources.data = [
source for source in current_user.included_data_sources.split("; ")
]
return render_template(
"preferences.html",
title="Preferences",
form=form,
back_url=session.get("back-url", url_for("index")),
)
@app.route("/")
@limiter.limit("10 per minute")
@utils.set_cookies
def index():
session["back-url"] = request.url
sources = []
for module in app.config["DATA_SOURCES"]:
sources.append(app.config["DATA_SOURCES"][module].get("logo", {}))
# remove duplicates
sources = [dict(t) for t in {tuple(d.items()) for d in sources}]
template_response = render_template("index.html", sources=sources)
return template_response
@app.route("/update-visitor-id", methods=["GET"])
@utils.timeit
def update_visitor_id():
visitor_id = request.args.get("visitor_id")
print(f"{visitor_id=}")
utils.update_visitor_id(visitor_id)
return str(True)
@app.route("/results", methods=["GET"])
@limiter.limit("3 per minute")
@utils.timeit
@utils.set_cookies
def search_results():
search_term = request.args.get("txtSearchTerm", "")
session["search-term"] = search_term
session["back-url"] = request.url
utils.log_activity(f"loading search results for {search_term}")
utils.log_search_term(search_term)
CATEGORIES = [
"publications",
"researchers",
"resources",
"organizations",
"events",
"projects",
"others",
]
results = {c: [] for c in CATEGORIES}
sources = []
failed_sources = []
excluded_sources = set()
if not current_user.is_anonymous:
excluded_sources = set((current_user.excluded_data_sources or "").split('; '))
# Load all the sources from config.py used to harvest data related to search term
for module in app.config["DATA_SOURCES"]:
if (
app.config["DATA_SOURCES"][module]
.get("search-endpoint", "")
.strip() != ""
and module not in excluded_sources
):
sources.append(module)
# for now this wraps the in-reference editing
# can be simplified once the refactoring is completed,
# including having the modules return values
# and handling failing sources outside the retriever
def search_source(source, module_name, search_term) -> tuple[Optional[dict], Optional[Exception]]:
mod = importlib.import_module(f"sources.{module_name}")
partial = {c: [] for c in CATEGORIES}
failed_sources = []
try:
mod.search(source, search_term, partial, failed_sources)
if failed_sources:
return None, Exception(f"Failed to harvest {source}")
return partial, None
except Exception as e:
return None, e
max_workers = min(16, len(sources) or 1)
with ThreadPoolExecutor(max_workers=max_workers) as ex:
futures = {
ex.submit(search_source, source, app.config["DATA_SOURCES"][source]["module"], search_term): source
for source in sources
}
for fut in as_completed(futures):
source = futures[fut]
partial, err = fut.result()
if err:
failed_sources.append(source)
logger.warning("Source failed: %s: %s", source, err)
continue
for k in CATEGORIES:
results[k].extend(partial[k])
# sort all the results in each category
for k in CATEGORIES:
results[k] = utils.sort_search_results(search_term, results[k])
if len(failed_sources) > 0:
flash(
f"Following sources could not be harvested: {', '.join(failed_sources)}",
category="error",
)
# store the search results in the session
session["search-results"] = copy.deepcopy(results)
# Chatbot - push search results to chatbot server for embeddings generation
if app.config["CHATBOT"]["chatbot_enable"]:
# Convert a UUID to a 32-character hexadecimal string
search_uuid = uuid.uuid4().hex
session["search_uuid"] = search_uuid
chatbot_server = app.config["CHATBOT"]["chatbot_server"]
save_docs_with_embeddings = app.config["CHATBOT"][
"endpoint_save_docs_with_embeddings"
]
request_url = (
f"{chatbot_server}{save_docs_with_embeddings}/{search_uuid}"
)
results_json = json.dumps(results, default=vars)
def send_search_results_to_chatbot(request_url: str, payload_json: str):
response = requests.post(
request_url,
json=payload_json,
)
response.raise_for_status()
print("request completed")
# create a new daemon thread
chatbot_thread = threading.Thread(
target=send_search_results_to_chatbot, args=(request_url,results_json),
daemon=True,
)
# start the new thread
chatbot_thread.start()
# on the first page load, only push top XX records in each category
n = int(app.config["NUMBER_OF_RECORDS_TO_SHOW_ON_PAGE_LOAD"])
total_results = {} # the dict to keep the number of search results
displayed_results = {} # the dict to keep the number of search results currently displayed to the user
for k, v in results.items():
logger.info(f"Got {len(v)} {k}")
total_results[k] = len(v)
results[k] = v[:n]
displayed_results[k] = len(results[k])
session["total_search_results"] = total_results
session["displayed_search_results"] = displayed_results
template_response = render_template(
"results.html",
results=results,
total_results=total_results,
search_term=search_term,
)
logger.info("search server call completed - after render call")
return template_response
@app.route(
"/update_search_result/<string:source>/<string:source_identifier>/<path:doi>",
methods=["GET"],
)
def update_search_result(source: str, source_identifier: str, doi):
module_name = app.config["DATA_SOURCES"][source].get("module", "")
resource = importlib.import_module(f"sources.{module_name}").get_resource(
source, source_identifier, doi.replace("DOI:", "")
)
return render_template(
f"partials/search-results/resource-block.html", resource=resource
)
@app.route("/load-more/<string:object_type>", methods=["GET"])
def load_more(object_type):
utils.log_activity(f"loading more {object_type}")
# define a new results dict for publications to take new publications from the search results stored in the session
results = {}
results[object_type] = session["search-results"][object_type]
total_search_results = session["total_search_results"][object_type]
displayed_search_results = session["displayed_search_results"][object_type]
number_of_records_to_append_on_lazy_load = int(
app.config["NUMBER_OF_RECORDS_TO_APPEND_ON_LAZY_LOAD"]
)
results[object_type] = results[object_type][
displayed_search_results : displayed_search_results
+ number_of_records_to_append_on_lazy_load
]
session["displayed_search_results"][object_type] = (
displayed_search_results + number_of_records_to_append_on_lazy_load
)
return render_template(
f"partials/search-results/{object_type}.html", results=results
)
@app.route("/are-embeddings-generated", methods=["GET"])
@utils.timeit
def are_embeddings_generated():
# Check the embeddings readiness only if the chatbot feature is enabled otherwise return False
if app.config["CHATBOT"]["chatbot_enable"]:
print("are_embeddings_generated")
uuid = session["search_uuid"]
chatbot_server = app.config["CHATBOT"]["chatbot_server"]
are_embeddings_generated = app.config["CHATBOT"][
"endpoint_are_embeddings_generated"
]
request_url = f"{chatbot_server}{are_embeddings_generated}/{uuid}"
headers = {"Content-Type": "application/json"}
response = requests.request("GET", request_url, headers=headers)
json_response = response.json()
print("json_response:", json_response)
return str(json_response["file_exists"])
else:
return str(True)
@app.route("/get-chatbot-answer", methods=["GET"])
@utils.timeit
def get_chatbot_answer():
question = request.args.get("question")
utils.log_activity(f"User asked the chatbot: {question}")
search_uuid = session["search_uuid"]
answer = chatbot.getAnswer(app=app, question=question, search_uuid=search_uuid)
return answer
@app.route("/publication-details/get-dois-references/<path:doi>", methods=["POST"])
@limiter.limit("10 per minute")
def get_publication_dois_references(doi):
"""
Endpoint to get a list of references for a given DOI.
Uses the .get_dois_references() method from the modules.
"""
# uses get_dois_references() from these sources:
references_sources = {
"CROSSREF - Publications": "crossref_publications",
"OpenCitations": "opencitations",
}
found_dois = set()
for source, module_name in references_sources.items():
# request reference data from these endpoints
dois = importlib.import_module(f"sources.{module_name}").get_dois_references(
source=source, doi=doi
)
dois = [d.lower() for d in dois] # ensure DOIs are lowercase
print(f"found {len(dois)} DOIs in {source} for {doi}")
found_dois.update(dois)
return jsonify({"dois": list(found_dois)})
@app.route("/publication-details/get-dois-citations/<path:doi>", methods=["POST"])
@limiter.limit("10 per minute")
def get_publication_citations_dois(doi):
"""
Endpoint to get a list of citations for a given DOI.
Uses the .get_dois_citations() method from the modules.
"""
# uses get_dois_citations() from these sources:
citation_sources = {
"SEMANTIC SCHOLAR - Publications": "semanticscholar_publications",
"OpenCitations": "opencitations",
}
found_dois = set()
for source, module_name in citation_sources.items():
# request citation data from these endpoints
dois = importlib.import_module(f"sources.{module_name}").get_dois_citations(
source=source, doi=doi
)
dois = [d.lower() for d in dois] # ensure DOIs are lowercase
print(f"found {len(dois)} DOIs in {source} for {doi}")
found_dois.update(dois)
return jsonify({"dois": list(found_dois)})
@app.route("/publication-details/get-metadata/", methods=["POST"])
@limiter.limit("10 per minute")
def get_publication_metadata():
"""
Endpoint to get metadata for a list of DOIs.
Uses the .get_publication_metadata() method from the modules.
"""
# add more metadata sources here
# uses get_publication_metadata() from their modules
metadata_sources = {
"OpenCitations": "opencitations",
}
dois = request.json.get("dois", [])
print(f"Received {len(dois)} DOIs for metadata retrieval")
if not dois:
return jsonify({"error": "No DOIs provided"}), 400
# collect articles keyed by DOI
collected: dict[str, Article] = {}
for module_name in metadata_sources.values():
articles = importlib.import_module(f"sources.{module_name}").get_batch_articles(
dois=dois
)
# get all lowercase titles and DOIs from the collected articles
list_title = [article.name.lower() for article in collected.values()]
list_doi = [article.identifier.lower() for article in collected.values()]
for article in articles:
# deduplicate and add to publication_list
# check if the article title or DOI already exists
if (
article.name.lower() not in list_title
and article.identifier.lower() not in list_doi
):
# article does not already exist, add it
doi = article.identifier.lower()
if doi and doi not in collected:
collected[doi] = article
# create stub for every unresolved DOI
for doi in dois:
if doi not in collected:
stub = Article(
identifier=doi, partiallyLoaded=True
) # an Article with only a DOI, set flag partiallyLoaded=True
collected[doi.lower()] = stub
# serialize all Article objects to json
payload = [
art.model_dump(mode="python", exclude_none=True) for art in collected.values()
]
return jsonify({"publications": payload})
@app.route(