-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathclient.py
1347 lines (1137 loc) · 49.5 KB
/
client.py
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
"""This module provides classes to interface with the Materials Project REST
API v3 to enable the creation of data structures and pymatgen objects using
Materials Project data.
"""
from __future__ import annotations
import inspect
import itertools
import json
import os
import platform
import sys
import warnings
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from copy import copy
from datetime import datetime
from functools import cache
from importlib.metadata import PackageNotFoundError, version
from json import JSONDecodeError
from math import ceil
from typing import TYPE_CHECKING, Generic, TypeVar
from urllib.parse import quote, urljoin
import requests
from bson import json_util
from emmet.core.utils import jsanitize
from monty.json import MontyDecoder
from pydantic import BaseModel, create_model
from requests.adapters import HTTPAdapter
from requests.exceptions import RequestException
from smart_open import open
from tqdm.auto import tqdm
from urllib3.util.retry import Retry
from mp_api.client.core.settings import MAPIClientSettings
from mp_api.client.core.utils import api_sanitize, validate_ids
try:
import boto3
from botocore import UNSIGNED
from botocore.config import Config
except ImportError:
boto3 = None
try:
import flask
except ImportError:
flask = None
if TYPE_CHECKING:
from typing import Any, Callable
try:
__version__ = version("mp_api")
except PackageNotFoundError: # pragma: no cover
__version__ = os.getenv("SETUPTOOLS_SCM_PRETEND_VERSION")
SETTINGS = MAPIClientSettings() # type: ignore
T = TypeVar("T")
class BaseRester(Generic[T]):
"""Base client class with core stubs."""
suffix: str = ""
document_model: BaseModel = None # type: ignore
supports_versions: bool = False
primary_key: str = "material_id"
def __init__(
self,
api_key: str | None = None,
endpoint: str | None = None,
include_user_agent: bool = True,
session: requests.Session | None = None,
s3_client: Any | None = None,
debug: bool = False,
monty_decode: bool = True,
use_document_model: bool = True,
timeout: int = 20,
headers: dict | None = None,
mute_progress_bars: bool = SETTINGS.MUTE_PROGRESS_BARS,
):
"""Initialize the REST API helper class.
Arguments:
api_key: A String API key for accessing the MaterialsProject
REST interface. Please obtain your API key at
https://www.materialsproject.org/dashboard. If this is None,
the code will check if there is a "PMG_MAPI_KEY" setting.
If so, it will use that environment variable. This makes
easier for heavy users to simply add this environment variable to
their setups and MPRester can then be called without any arguments.
endpoint: Url of endpoint to access the MaterialsProject REST
interface. Defaults to the standard Materials Project REST
address at "https://api.materialsproject.org", but
can be changed to other urls implementing a similar interface.
include_user_agent: If True, will include a user agent with the
HTTP request including information on pymatgen and system version
making the API request. This helps MP support pymatgen users, and
is similar to what most web browsers send with each page request.
Set to False to disable the user agent.
session: requests Session object with which to connect to the API, for
advanced usage only.
s3_client: boto3 S3 client object with which to connect to the object stores.ct to the object stores.ct to the object stores.
debug: if True, print the URL for every request
monty_decode: Decode the data using monty into python objects
use_document_model: If False, skip the creating the document model and return data
as a dictionary. This can be simpler to work with but bypasses data validation
and will not give auto-complete for available fields.
timeout: Time in seconds to wait until a request timeout error is thrown
headers: Custom headers for localhost connections.
mute_progress_bars: Whether to disable progress bars.
"""
# TODO: think about how to migrate from PMG_MAPI_KEY
self.api_key = api_key or os.getenv("MP_API_KEY")
self.base_endpoint = self.endpoint = endpoint or os.getenv(
"MP_API_ENDPOINT", "https://api.materialsproject.org/"
)
self.debug = debug
self.include_user_agent = include_user_agent
self.monty_decode = monty_decode
self.use_document_model = use_document_model
self.timeout = timeout
self.headers = headers or {}
self.mute_progress_bars = mute_progress_bars
self.db_version = BaseRester._get_database_version(self.endpoint)
if self.suffix:
self.endpoint = urljoin(self.endpoint, self.suffix)
if not self.endpoint.endswith("/"):
self.endpoint += "/"
if session:
self._session = session
else:
self._session = None # type: ignore
if s3_client:
self._s3_client = s3_client
else:
self._s3_client = None
self.document_model = (
api_sanitize(self.document_model) # type: ignore
if self.document_model is not None
else None # type: ignore
)
@property
def session(self) -> requests.Session:
if not self._session:
self._session = self._create_session(
self.api_key, self.include_user_agent, self.headers
)
return self._session
@property
def s3_client(self):
if boto3 is None:
raise MPRestError(
"boto3 not installed. To query charge density, "
"band structure, or density of states data first "
"install with: 'pip install boto3'"
)
if not self._s3_client:
self._s3_client = boto3.client(
"s3",
config=Config(signature_version=UNSIGNED), # type: ignore
)
return self._s3_client
@staticmethod
def _create_session(api_key, include_user_agent, headers):
session = requests.Session()
session.headers = {"x-api-key": api_key}
session.headers.update(headers)
if include_user_agent:
mp_api_info = "mp-api/" + __version__ if __version__ else None
python_info = f"Python/{sys.version.split()[0]}"
platform_info = f"{platform.system()}/{platform.release()}"
user_agent = f"{mp_api_info} ({python_info} {platform_info})"
session.headers["user-agent"] = user_agent
settings = MAPIClientSettings() # type: ignore
max_retry_num = settings.MAX_RETRIES
retry = Retry(
total=max_retry_num,
read=max_retry_num,
connect=max_retry_num,
respect_retry_after_header=True,
status_forcelist=[429, 504, 502], # rate limiting
backoff_factor=settings.BACKOFF_FACTOR,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def __enter__(self): # pragma: no cover
"""Support for "with" context."""
return self
def __exit__(self, exc_type, exc_val, exc_tb): # pragma: no cover
"""Support for "with" context."""
if self.session is not None:
self.session.close()
self._session = None
@staticmethod
@cache
def _get_database_version(endpoint):
"""The Materials Project database is periodically updated and has a
database version associated with it. When the database is updated,
consolidated data (information about "a material") may and does
change, while calculation data about a specific calculation task
remains unchanged and available for querying via its task_id.
The database version is set as a date in the format YYYY_MM_DD,
where "_DD" may be optional. An additional numerical suffix
might be added if multiple releases happen on the same day.
Returns: database version as a string
"""
date_str = requests.get(url=endpoint + "heartbeat").json()["db_version"]
# Convert the string to a datetime object
date_obj = datetime.strptime(date_str, "%Y.%m.%d")
# Format the datetime object as a string
formatted_date = date_obj.strftime("%Y.%m.%d")
return formatted_date
def _post_resource(
self,
body: dict | None = None,
params: dict | None = None,
suburl: str | None = None,
use_document_model: bool | None = None,
) -> dict:
"""Post data to the endpoint for a Resource.
Arguments:
body: body json to send in post request
params: extra params to send in post request
suburl: make a request to a specified sub-url
use_document_model: if None, will defer to the self.use_document_model attribute
Returns:
A Resource, a dict with two keys, "data" containing a list of documents, and
"meta" containing meta information, e.g. total number of documents
available.
"""
if use_document_model is None:
use_document_model = self.use_document_model
payload = jsanitize(body)
try:
url = self.endpoint
if suburl:
url = urljoin(self.endpoint, suburl)
if not url.endswith("/"):
url += "/"
response = self.session.post(url, json=payload, verify=True, params=params)
if response.status_code == 200:
if self.monty_decode:
data = json.loads(response.text, cls=MontyDecoder)
else:
data = json.loads(response.text)
if self.document_model and use_document_model:
if isinstance(data["data"], dict):
data["data"] = self.document_model.model_validate(data["data"]) # type: ignore
elif isinstance(data["data"], list):
data["data"] = [
self.document_model.model_validate(d) for d in data["data"]
] # type: ignore
return data
else:
try:
data = json.loads(response.text)["detail"]
except (JSONDecodeError, KeyError):
data = f"Response {response.text}"
if isinstance(data, str):
message = data
else:
try:
message = ", ".join(
f"{entry['loc'][1]} - {entry['msg']}" for entry in data
)
except (KeyError, IndexError):
message = str(data)
raise MPRestError(
f"REST post query returned with error status code {response.status_code} "
f"on URL {response.url} with message:\n{message}"
)
except RequestException as ex:
raise MPRestError(str(ex))
def _patch_resource(
self,
body: dict | None = None,
params: dict | None = None,
suburl: str | None = None,
use_document_model: bool | None = None,
) -> dict:
"""Patch data to the endpoint for a Resource.
Arguments:
body: body json to send in patch request
params: extra params to send in patch request
suburl: make a request to a specified sub-url
use_document_model: if None, will defer to the self.use_document_model attribute
Returns:
A Resource, a dict with two keys, "data" containing a list of documents, and
"meta" containing meta information, e.g. total number of documents
available.
"""
if use_document_model is None:
use_document_model = self.use_document_model
payload = jsanitize(body)
try:
url = self.endpoint
if suburl:
url = urljoin(self.endpoint, suburl)
if not url.endswith("/"):
url += "/"
response = self.session.patch(url, json=payload, verify=True, params=params)
if response.status_code == 200:
if self.monty_decode:
data = json.loads(response.text, cls=MontyDecoder)
else:
data = json.loads(response.text)
if self.document_model and use_document_model:
if isinstance(data["data"], dict):
data["data"] = self.document_model.model_validate(data["data"]) # type: ignore
elif isinstance(data["data"], list):
data["data"] = [
self.document_model.model_validate(d) for d in data["data"]
] # type: ignore
return data
else:
try:
data = json.loads(response.text)["detail"]
except (JSONDecodeError, KeyError):
data = f"Response {response.text}"
if isinstance(data, str):
message = data
else:
try:
message = ", ".join(
f"{entry['loc'][1]} - {entry['msg']}" for entry in data
)
except (KeyError, IndexError):
message = str(data)
raise MPRestError(
f"REST post query returned with error status code {response.status_code} "
f"on URL {response.url} with message:\n{message}"
)
except RequestException as ex:
raise MPRestError(str(ex))
def _query_open_data(
self,
bucket: str,
key: str,
decoder: Callable,
) -> tuple[list[dict] | list[bytes], int]:
"""Query and deserialize Materials Project AWS open data s3 buckets.
Args:
bucket (str): Materials project bucket name
key (str): Key for file including all prefixes
decoder(Callable): Callable used to deserialize data
Returns:
dict: MontyDecoded data
"""
file = open(
f"s3://{bucket}/{key}",
encoding="utf-8",
transport_params={"client": self.s3_client},
)
if "jsonl" in key:
decoded_data = [decoder(jline) for jline in file.read().splitlines()]
else:
decoded_data = decoder(file.read())
if not isinstance(decoded_data, list):
decoded_data = [decoded_data]
return decoded_data, len(decoded_data) # type: ignore
def _query_resource(
self,
criteria: dict | None = None,
fields: list[str] | None = None,
suburl: str | None = None,
use_document_model: bool | None = None,
parallel_param: str | None = None,
num_chunks: int | None = None,
chunk_size: int | None = None,
timeout: int | None = None,
) -> dict:
"""Query the endpoint for a Resource containing a list of documents
and meta information about pagination and total document count.
For the end-user, methods .search() and .count() are intended to be
easier to use.
Arguments:
criteria: dictionary of criteria to filter down
fields: list of fields to return
suburl: make a request to a specified sub-url
use_document_model: if None, will defer to the self.use_document_model attribute
parallel_param: parameter used to make parallel requests
num_chunks: Maximum number of chunks of data to yield. None will yield all possible.
chunk_size: Number of data entries per chunk.
timeout : Time in seconds to wait until a request timeout error is thrown
Returns:
A Resource, a dict with two keys, "data" containing a list of documents, and
"meta" containing meta information, e.g. total number of documents
available.
"""
if use_document_model is None:
use_document_model = self.use_document_model
if timeout is None:
timeout = self.timeout
if criteria:
criteria = {k: v for k, v in criteria.items() if v is not None}
else:
criteria = {}
# Query s3 if no query is passed and all documents are asked for
# TODO also skip fields set to same as their default
no_query = not {field for field in criteria if field[0] != "_"}
query_s3 = no_query and num_chunks is None
if fields:
if isinstance(fields, str):
fields = [fields]
if not suburl:
invalid_fields = [
f for f in fields if f.split(".", 1)[0] not in self.available_fields
]
if invalid_fields:
raise MPRestError(
f"invalid fields requested: {invalid_fields}. Available fields: {self.available_fields}"
)
criteria["_fields"] = ",".join(fields)
try:
url = self.endpoint
if suburl:
url = urljoin(self.endpoint, suburl)
if not url.endswith("/"):
url += "/"
if query_s3:
db_version = self.db_version.replace(".", "-")
if "/" not in self.suffix:
suffix = self.suffix
elif self.suffix == "molecules/summary":
suffix = "molecules"
else:
infix, suffix = self.suffix.split("/", 1)
suffix = infix if suffix == "core" else suffix
suffix = suffix.replace("_", "-")
# Paginate over all entries in the bucket.
# TODO: change when a subset of entries needed from DB
if "tasks" in suffix:
bucket_suffix, prefix = "parsed", "tasks_atomate2"
else:
bucket_suffix = "build"
prefix = f"collections/{db_version}/{suffix}"
bucket = f"materialsproject-{bucket_suffix}"
paginator = self.s3_client.get_paginator("list_objects_v2")
pages = paginator.paginate(Bucket=bucket, Prefix=prefix)
keys = []
for page in pages:
for obj in page.get("Contents", []):
key = obj.get("Key")
if key and "manifest" not in key:
keys.append(key)
if len(keys) < 1:
return self._submit_requests(
url=url,
criteria=criteria,
use_document_model=use_document_model,
parallel_param=parallel_param,
num_chunks=num_chunks,
chunk_size=chunk_size,
timeout=timeout,
)
if fields:
warnings.warn(
"Ignoring `fields` argument: All fields are always included when no query is provided."
)
decoder = (
MontyDecoder().decode if self.monty_decode else json_util.loads
)
# Multithreaded function inputs
s3_params_list = {
key: {
"bucket": bucket,
"key": key,
"decoder": decoder,
}
for key in keys
}
# Setup progress bar
pbar_message = ( # type: ignore
f"Retrieving {self.document_model.__name__} documents" # type: ignore
if self.document_model is not None
else "Retrieving documents"
)
num_docs_needed = int(self.count())
pbar = (
tqdm(
desc=pbar_message,
total=num_docs_needed,
)
if not self.mute_progress_bars
else None
)
byte_data = self._multi_thread(
self._query_open_data,
list(s3_params_list.values()),
pbar, # type: ignore
)
unzipped_data = []
for docs, _, _ in byte_data:
unzipped_data.extend(docs)
data = {"data": unzipped_data, "meta": {}}
if self.use_document_model:
data["data"] = self._convert_to_model(data["data"])
data["meta"]["total_doc"] = len(data["data"])
else:
data = self._submit_requests(
url=url,
criteria=criteria,
use_document_model=not query_s3 and use_document_model,
parallel_param=parallel_param,
num_chunks=num_chunks,
chunk_size=chunk_size,
timeout=timeout,
)
return data
except RequestException as ex:
raise MPRestError(str(ex))
def _submit_requests( # noqa
self,
url,
criteria,
use_document_model,
chunk_size,
parallel_param=None,
num_chunks=None,
timeout=None,
) -> dict:
"""Handle submitting requests. Parallel requests supported if possible.
Parallelization will occur either over the largest list of supported
query parameters used and/or over pagination.
The number of threads is chosen by NUM_PARALLEL_REQUESTS in settings.
Arguments:
criteria: dictionary of criteria to filter down
url: url used to make request
use_document_model: if None, will defer to the self.use_document_model attribute
parallel_param: parameter to parallelize requests with
num_chu: fieldsnky: Maximum number of chunks of data to yield. None will yield all possible.
chunk_size: Number of data entries per chunk.
timeout: Time in seconds to wait until a request timeout error is thrown
Returns:
Dictionary containing data and metadata
"""
# Generate new sets of criteria dicts to be run in parallel
# with new appropriate limit values. New limits obtained from
# trying to evenly divide num_chunks by the total number of new
# criteria dicts.
if parallel_param is not None:
# Determine slice size accounting for character maximum in HTTP URL
# First get URl length without parallel param
url_string = ""
for key, value in criteria.items():
if key != parallel_param:
parsed_val = quote(str(value))
url_string += f"{key}={parsed_val}&"
bare_url_len = len(url_string)
max_param_str_length = (
MAPIClientSettings().MAX_HTTP_URL_LENGTH - bare_url_len # type: ignore
)
# Next, check if default number of parallel requests works.
# If not, make slice size the minimum number of param entries
# contained in any substring of length max_param_str_length.
param_length = len(criteria[parallel_param].split(","))
slice_size = (
int(param_length / MAPIClientSettings().NUM_PARALLEL_REQUESTS) or 1 # type: ignore
)
url_param_string = quote(criteria[parallel_param])
parallel_param_str_chunks = [
url_param_string[i : i + max_param_str_length]
for i in range(0, len(url_param_string), max_param_str_length)
if (i + max_param_str_length) <= len(url_param_string)
]
if len(parallel_param_str_chunks) > 0:
params_min_chunk = min(
parallel_param_str_chunks, key=lambda x: len(x.split("%2C"))
)
num_params_min_chunk = len(params_min_chunk.split("%2C"))
if num_params_min_chunk < slice_size:
slice_size = num_params_min_chunk or 1
new_param_values = [
entry
for entry in (
criteria[parallel_param].split(",")[i : (i + slice_size)]
for i in range(0, param_length, slice_size)
)
if entry != []
]
# Get new limit values that sum to chunk_size
num_new_params = len(new_param_values)
q = int(chunk_size / num_new_params) # quotient
r = chunk_size % num_new_params # remainder
new_limits = []
for _ in range(num_new_params):
val = q + 1 if r > 0 else q if q > 0 else 1
new_limits.append(val)
r -= 1
# Split list and generate multiple criteria
new_criteria = [
{
**{
key: criteria[key]
for key in criteria
if key not in [parallel_param, "_limit"]
},
parallel_param: ",".join(list_chunk),
"_limit": new_limits[list_num],
}
for list_num, list_chunk in enumerate(new_param_values)
]
else:
# Only parallelize over pagination parameters
new_criteria = [criteria]
new_limits = [chunk_size]
total_num_docs = 0
total_data = {"data": []} # type: dict
# Obtain first page of results and get pagination information.
# Individual total document limits (subtotal) will potentially
# be used for rebalancing should one new of the criteria
# queries result in a smaller amount of docs compared to the
# new limit value we assigned.
subtotals = []
remaining_docs_avail = {}
initial_params_list = [
{
"url": url,
"verify": True,
"params": copy(crit),
"use_document_model": use_document_model,
"timeout": timeout,
}
for crit in new_criteria
]
initial_data_tuples = self._multi_thread(
self._submit_request_and_process, initial_params_list
)
for data, subtotal, crit_ind in initial_data_tuples:
subtotals.append(subtotal)
sub_diff = subtotal - new_limits[crit_ind]
remaining_docs_avail[crit_ind] = sub_diff
total_data["data"].extend(data["data"])
last_data_entry = initial_data_tuples[-1][0]
# Rebalance if some parallel queries produced too few results
if len(remaining_docs_avail) > 1 and len(total_data["data"]) < chunk_size:
remaining_docs_avail = dict(
sorted(remaining_docs_avail.items(), key=lambda item: item[1])
)
# Redistribute missing docs from initial chunk among queries
# which have head room with respect to remaining document number.
fill_docs = 0
rebalance_params = []
for crit_ind, amount_avail in remaining_docs_avail.items():
if amount_avail <= 0:
fill_docs += abs(amount_avail)
new_limits[crit_ind] = 0
else:
crit = new_criteria[crit_ind]
crit["_skip"] = crit["_limit"]
if fill_docs == 0:
continue
if fill_docs >= amount_avail:
crit["_limit"] = amount_avail
new_limits[crit_ind] += amount_avail
fill_docs -= amount_avail
else:
crit["_limit"] = fill_docs
new_limits[crit_ind] += fill_docs
fill_docs = 0
rebalance_params.append(
{
"url": url,
"verify": True,
"params": copy(crit),
"use_document_model": use_document_model,
"timeout": timeout,
}
)
new_criteria[crit_ind]["_skip"] += crit["_limit"]
new_criteria[crit_ind]["_limit"] = chunk_size
# Obtain missing initial data after rebalancing
if len(rebalance_params) > 0:
rebalance_data_tuples = self._multi_thread(
self._submit_request_and_process, rebalance_params
)
for data, _, _ in rebalance_data_tuples:
total_data["data"].extend(data["data"])
last_data_entry = rebalance_data_tuples[-1][0]
total_num_docs = sum(subtotals)
if "meta" in last_data_entry:
last_data_entry["meta"]["total_doc"] = total_num_docs
total_data["meta"] = last_data_entry["meta"]
# Get max number of response pages
max_pages = (
num_chunks if num_chunks is not None else ceil(total_num_docs / chunk_size)
)
# Get total number of docs needed
num_docs_needed = min((max_pages * chunk_size), total_num_docs)
# Setup progress bar
pbar_message = ( # type: ignore
f"Retrieving {self.document_model.__name__} documents" # type: ignore
if self.document_model is not None
else "Retrieving documents"
)
pbar = (
tqdm(
desc=pbar_message,
total=num_docs_needed,
)
if not self.mute_progress_bars
else None
)
initial_data_length = len(total_data["data"])
# If we have all the results in a single page, return directly
if initial_data_length >= num_docs_needed or num_chunks == 1:
new_total_data = copy(total_data)
new_total_data["data"] = total_data["data"][:num_docs_needed]
if pbar is not None:
pbar.update(num_docs_needed)
pbar.close()
return new_total_data
# otherwise, prepare to paginate in parallel
if chunk_size is None:
raise ValueError("A chunk size must be provided to enable pagination")
if pbar is not None:
pbar.update(initial_data_length)
# Warning to select specific fields only for many results
if criteria.get("_all_fields", False) and (total_num_docs / chunk_size > 10):
warnings.warn(
f"Use the 'fields' argument to select only fields of interest to speed "
f"up data retrieval for large queries. "
f"Choose from: {self.available_fields}"
)
# Get all pagination input params for parallel requests
params_list = []
doc_counter = 0
for crit_num, crit in enumerate(new_criteria):
remaining = remaining_docs_avail[crit_num]
if "_skip" not in crit:
crit["_skip"] = chunk_size if "_limit" not in crit else crit["_limit"]
while remaining > 0:
if doc_counter == (num_docs_needed - initial_data_length):
break
if remaining < chunk_size:
crit["_limit"] = remaining
doc_counter += remaining
else:
n = chunk_size - (doc_counter % chunk_size)
crit["_limit"] = n
doc_counter += n
params_list.append(
{
"url": url,
"verify": True,
"params": {**crit, "_skip": crit["_skip"]},
"use_document_model": use_document_model,
"timeout": timeout,
}
)
crit["_skip"] += crit["_limit"]
remaining -= crit["_limit"]
# Submit requests and process data
data_tuples = self._multi_thread(
self._submit_request_and_process, params_list, pbar
)
for data, _, _ in data_tuples:
total_data["data"].extend(data["data"])
if data_tuples and "meta" in data_tuples[0][0]:
total_data["meta"]["time_stamp"] = data_tuples[0][0]["meta"]["time_stamp"]
total_data["meta"]["facets"] = data_tuples[0][0]["meta"].get("facet", None)
if pbar is not None:
pbar.close()
return total_data
def _multi_thread(
self,
func: Callable,
params_list: list[dict],
progress_bar: tqdm | None = None,
):
"""Handles setting up a threadpool and sending parallel requests.
Arguments:
func (Callable): Callable function to multi
params_list (list): list of dictionaries containing url and params for each request
progress_bar (tqdm): progress bar to update with progress
Returns:
Tuples with data, total number of docs in matching the query in the database,
and the index of the criteria dictionary in the provided parameter list
"""
return_data = []
params_gen = iter(
params_list
) # Iter necessary for islice to keep track of what has been accessed
params_ind = 0
with ThreadPoolExecutor(
max_workers=MAPIClientSettings().NUM_PARALLEL_REQUESTS # type: ignore
) as executor:
# Get list of initial futures defined by max number of parallel requests
futures = set()
for params in itertools.islice(
params_gen,
MAPIClientSettings().NUM_PARALLEL_REQUESTS, # type: ignore
):
future = executor.submit(
func,
**params,
)
future.crit_ind = params_ind # type: ignore
futures.add(future)
params_ind += 1
while futures:
# Wait for at least one future to complete and process finished
finished, futures = wait(futures, return_when=FIRST_COMPLETED)
for future in finished:
data, subtotal = future.result()
if progress_bar is not None:
if isinstance(data, dict):
size = len(data["data"])
elif isinstance(data, list):
size = len(data)
else:
size = 1
progress_bar.update(size)
return_data.append((data, subtotal, future.crit_ind)) # type: ignore
# Populate more futures to replace finished
for params in itertools.islice(params_gen, len(finished)):
new_future = executor.submit(
func,
**params,
)
new_future.crit_ind = params_ind # type: ignore
futures.add(new_future)
params_ind += 1
return return_data
def _submit_request_and_process(
self,
url: str,
verify: bool,
params: dict,
use_document_model: bool,
timeout: int | None = None,
) -> tuple[dict, int]:
"""Submits GET request and handles the response.
Arguments:
url: URL to send request to
verify: whether to verify the server's TLS certificate
params: dictionary of parameters to send in the request
use_document_model: if None, will defer to the self.use_document_model attribute
timeout: Time in seconds to wait until a request timeout error is thrown
Returns:
Tuple with data and total number of docs in matching the query in the database.
"""
headers = None
if flask is not None and flask.has_request_context():
headers = flask.request.headers
try:
response = self.session.get(
url=url,
verify=verify,