-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathclient.py
1303 lines (1096 loc) · 41.3 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
import json
import logging
import os
import zlib
from datetime import datetime
from logging import Logger
from pathlib import Path
from typing import Dict, Iterator, List, Optional, Union, cast
import requests
from requests import Response
from requests.adapters import HTTPAdapter
from requests.exceptions import HTTPError
from tenacity import (
RetryCallState,
retry,
retry_if_exception_type,
stop_after_attempt,
stop_after_delay,
wait_exponential_jitter,
)
from tenacity.wait import wait_exponential
from darwin.backend_v2 import BackendV2
from darwin.config import Config
from darwin.dataset.identifier import DatasetIdentifier
from darwin.dataset.remote_dataset import RemoteDataset
from darwin.dataset.remote_dataset_v2 import RemoteDatasetV2
from darwin.datatypes import (
AnnotatorReportGrouping,
DarwinVersionNumber,
Feature,
ObjectStore,
ReportJob,
Team,
UnknownType,
)
from darwin.exceptions import (
InsufficientStorage,
InvalidLogin,
MissingConfig,
NameTaken,
NotFound,
RequestEntitySizeExceeded,
Unauthorized,
ValidationError,
)
from darwin.future.core.client import ClientCore, DarwinConfig
from darwin.future.core.properties import create_property as create_property_future
from darwin.future.core.properties import (
get_team_full_properties as get_team_full_properties_future,
)
from darwin.future.core.properties import (
get_team_properties as get_team_properties_future,
)
from darwin.future.core.properties import update_property as update_property_future
from darwin.future.core.types.common import JSONDict
from darwin.future.data_objects.properties import FullProperty
from darwin.utils import (
get_response_content,
has_json_content_type,
is_project_dir,
urljoin,
)
from darwin.utils.get_item_count import get_item_count
INITIAL_WAIT = int(os.getenv("DARWIN_RETRY_INITIAL_WAIT", "60"))
MAX_WAIT = int(os.getenv("DARWIN_RETRY_MAX_WAIT", "300"))
MAX_RETRIES = int(os.getenv("DARWIN_RETRY_MAX_ATTEMPTS", "10"))
HOUR = 60 * 60
class JobPendingException(Exception):
"""Raised when a requested job is not finished or failed."""
def log_rate_limit_exceeded(retry_state: RetryCallState):
wait_time = retry_state.next_action.sleep
print(f"Rate limit exceeded. Retrying in {wait_time:.2f} seconds...")
def retry_if_status_code_429(retry_state: RetryCallState):
exception = retry_state.outcome.exception()
if isinstance(exception, HTTPError):
response: Response = exception.response
return response.status_code == 429
return False
def retry_if_status_code_429_or_5xx(retry_state: RetryCallState) -> bool:
"""
Determines if a request should be retried based on the response status code.
Retries on:
- Rate limit (429)
- Server errors (500, 502, 503, 504)
Parameters
----------
retry_state : RetryCallState
The current state of the retry mechanism
Returns
-------
bool
True if the request should be retried, False otherwise
"""
exception = retry_state.outcome.exception()
if isinstance(exception, HTTPError):
response: Response = exception.response
return response.status_code in {
429,
500,
502,
503,
504,
}
return False
def log_retry_error(retry_state: RetryCallState) -> None:
"""
Logs information about why a request is being retried.
Parameters
----------
retry_state : RetryCallState
The current state of the retry mechanism
"""
wait_time = retry_state.next_action.sleep
exception = retry_state.outcome.exception()
if isinstance(exception, HTTPError):
response: Response = exception.response
if response.status_code == 429:
print(f"Rate limit exceeded. Retrying in {wait_time:.2f} seconds...")
else:
print(
f"Server error {response.status_code}. Retrying in {wait_time:.2f} seconds..."
)
class Client:
def __init__(
self,
config: Config,
default_team: Optional[str] = None,
log: Optional[Logger] = None,
):
self.config: Config = config
self.url: str = config.get("global/api_endpoint")
self.base_url: str = config.get("global/base_url")
self.default_team: str = default_team or config.get("global/default_team")
self.features: Dict[str, List[Feature]] = {}
self._newer_version: Optional[DarwinVersionNumber] = None
self.session = requests.Session()
adapter = HTTPAdapter(pool_maxsize=100)
self.session.mount("https://", adapter)
if log is None:
self.log: Logger = logging.getLogger("darwin")
else:
self.log = log
@staticmethod
def _get_item_count(dataset_dict: Dict[str, UnknownType]) -> int:
"""
Returns the number of items in the dataset.
Parameters
----------
dataset_dict: Dict[str, UnknownType]
The dataset dictionary.
Returns
-------
int
The number of items in the dataset.
"""
num_items: Optional[int] = dataset_dict.get("num_items")
num_videos: Optional[int] = dataset_dict.get("num_videos")
num_images: Optional[int] = dataset_dict.get("num_images")
if num_items is not None:
return num_items
return (num_images or 0) + (num_videos or 0)
def list_local_datasets(self, team_slug: Optional[str] = None) -> Iterator[Path]:
"""
Returns a list of all local folders which are detected as dataset.
Parameters
----------
team_slug: Optional[str]
The team slug of the dataset. Defaults to None.
Returns
-------
Iterator[Path]
Iterator of all local datasets
"""
team_configs: List[Team] = []
if team_slug:
team_data: Optional[Team] = self.config.get_team(team_slug)
if team_data:
team_configs.append(team_data)
else:
team_configs = self.config.get_all_teams()
for team_config in team_configs:
projects_team: Path = Path(team_config.datasets_dir) / team_config.slug
for project_path in projects_team.glob("*"):
if project_path.is_dir() and is_project_dir(project_path):
yield Path(project_path)
def list_remote_datasets(
self, team_slug: Optional[str] = None
) -> Iterator[RemoteDatasetV2]:
"""
Returns a list of all available datasets with the team currently authenticated against.
Parameters
----------
team_slug: Optional[str]
The team slug of the dataset. Defaults to None.
Returns
-------
Iterator[RemoteDataset]
List of all remote datasets
"""
response: List[Dict[str, UnknownType]] = cast(
List[Dict[str, UnknownType]], self._get("/datasets/", team_slug=team_slug)
)
for dataset in response:
yield RemoteDatasetV2(
name=dataset["name"],
slug=dataset["slug"],
team=team_slug or self.default_team,
dataset_id=dataset["id"],
item_count=get_item_count(dataset),
progress=dataset["progress"],
client=self,
)
def get_remote_dataset(
self, dataset_identifier: Union[str, DatasetIdentifier]
) -> RemoteDatasetV2:
"""
Get a remote dataset based on its identifier.
Parameters
----------
dataset_identifier : Union[str, DatasetIdentifier]
Identifier of the dataset. Can be the string version or a DatasetIdentifier object.
Returns
-------
RemoteDataset
Initialized dataset.
Raises
-------
NotFound
If no dataset with the given identifier was found.
"""
parsed_dataset_identifier: DatasetIdentifier = DatasetIdentifier.parse(
dataset_identifier
)
if not parsed_dataset_identifier.team_slug:
parsed_dataset_identifier.team_slug = self.default_team
try:
matching_datasets: List[RemoteDatasetV2] = [
dataset
for dataset in self.list_remote_datasets(
team_slug=parsed_dataset_identifier.team_slug
)
if dataset.slug == parsed_dataset_identifier.dataset_slug
]
except Unauthorized:
# There is a chance that we tried to access an open dataset
dataset: Dict[str, UnknownType] = cast(
Dict[str, UnknownType],
self._get(
f"{parsed_dataset_identifier.team_slug}/{parsed_dataset_identifier.dataset_slug}"
),
)
# If there isn't a record of this team, create one.
if not self.config.get_team(
parsed_dataset_identifier.team_slug, raise_on_invalid_team=False
):
datasets_dir: Path = Path.home() / ".darwin" / "datasets"
self.config.set_team(
team=parsed_dataset_identifier.team_slug,
api_key="",
datasets_dir=str(datasets_dir),
)
return RemoteDatasetV2(
name=dataset["name"],
slug=dataset["slug"],
team=parsed_dataset_identifier.team_slug,
dataset_id=dataset["id"],
item_count=get_item_count(dataset),
progress=0,
client=self,
)
if not matching_datasets:
raise NotFound(str(parsed_dataset_identifier))
if parsed_dataset_identifier.version:
matching_datasets[0].release = parsed_dataset_identifier.version
return matching_datasets[0]
def create_dataset(
self, name: str, team_slug: Optional[str] = None
) -> RemoteDataset:
"""
Create a remote dataset.
Parameters
----------
name : str
Name of the dataset to create.
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
Returns
-------
RemoteDataset
The created dataset.
"""
dataset: Dict[str, UnknownType] = cast(
Dict[str, UnknownType],
self._post("/datasets", {"name": name}, team_slug=team_slug),
)
return RemoteDatasetV2(
name=dataset["name"],
team=team_slug or self.default_team,
slug=dataset["slug"],
dataset_id=dataset["id"],
item_count=get_item_count(dataset),
progress=0,
client=self,
)
def archive_remote_dataset(self, dataset_id: int, team_slug: str) -> None:
"""
Archive (soft delete) a remote dataset.
Parameters
----------
dataset_id: int
Id of the dataset to archive.
team_slug: str
Team slug of the dataset.
"""
self._put(f"datasets/{dataset_id}/archive", payload={}, team_slug=team_slug)
def fetch_remote_classes(
self, team_slug: Optional[str] = None
) -> List[Dict[str, UnknownType]]:
"""
Fetches all remote classes on the remote dataset.
Parameters
----------
team_slug: Optional[str]
The team slug of the dataset. Defaults to None.
Returns
-------
Dict[str, UnknownType]
None if no information about the team is found, a List of Annotation classes otherwise.
Raises
------
ValueError
If no team was found.
"""
the_team: Optional[Team] = self.config.get_team(team_slug or self.default_team)
if not the_team:
raise ValueError("No team was found.")
the_team_slug: str = the_team.slug
response: Dict[str, UnknownType] = cast(
Dict[str, UnknownType],
self._get(f"/teams/{the_team_slug}/annotation_classes?include_tags=true"),
)
return response["annotation_classes"]
def update_annotation_class(
self, class_id: int, payload: Dict[str, UnknownType]
) -> Dict[str, UnknownType]:
"""
Updates the AnnotationClass with the given id.
Parameters
----------
class_id: int
The id of the AnnotationClass to update.
payload: Dict[str, UnknownType]
A dictionary with the changes to perform.
Returns
-------
Dict[str, UnknownType]
A dictionary with the result of the operation.
"""
response: Dict[str, UnknownType] = cast(
Dict[str, UnknownType],
self._put(f"/annotation_classes/{class_id}", payload),
)
return response
def create_annotation_class(
self, dataset_id: int, type_ids: List[int], name: str
) -> Dict[str, UnknownType]:
"""
Creates an AnnotationClass.
Parameters
----------
dataset_id: int
The id of the dataset this AnnotationClass will belong to originaly.
type_ids: List[int]
A list of type ids for the annotations this class will hold.
name: str
The name of the annotation class.
Returns
-------
Dict[str, UnknownType]
A dictionary with the result of the operation.
"""
response: Dict[str, UnknownType] = cast(
Dict[str, UnknownType],
self._post(
"/annotation_classes",
payload={
"dataset_id": dataset_id,
"name": name,
"metadata": {"_color": "auto"},
"annotation_type_ids": type_ids,
"datasets": [{"id": dataset_id}],
},
),
)
return response
def fetch_remote_attributes(self, dataset_id: int) -> List[Dict[str, UnknownType]]:
"""
Fetches all attributes remotely.
Parameters
----------
dataset_id: int
The id of the dataset with the attributes we want to fetch.
Returns
-------
List[Dict[str, UnknownType]]
A List with the attributes, where each attribute is a dictionary.
"""
response: List[Dict[str, UnknownType]] = cast(
List[Dict[str, UnknownType]],
self._get(f"/datasets/{dataset_id}/attributes"),
)
return response
def load_feature_flags(self, team_slug: Optional[str] = None) -> None:
"""
Loads in memory the set of current features enabled for a team.
Parameters
----------
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
"""
the_team: Optional[Team] = self.config.get_team(team_slug or self.default_team)
if not the_team:
return None
the_team_slug: str = the_team.slug
self.features[the_team_slug] = self.get_team_features(the_team_slug)
def get_team_features(self, team_slug: str) -> List[Feature]:
"""
Gets all the features for the given team together with their statuses.
Parameters
----------
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
Returns
-------
List[Feature]
List of Features for the given team.
"""
response: List[Dict[str, UnknownType]] = cast(
List[Dict[str, UnknownType]], self._get(f"/teams/{team_slug}/features")
)
features: List[Feature] = []
for feature in response:
features.append(
Feature(name=str(feature["name"]), enabled=bool(feature["enabled"]))
)
return features
def feature_enabled(
self, feature_name: str, team_slug: Optional[str] = None
) -> bool:
"""
Returns whether or not a given feature is enabled for a team.
Parameters
----------
feature_name: str
The name of the feature.
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
Returns
-------
bool
False if the given feature is not enabled OR the team was not found. True otherwise.
"""
the_team: Optional[Team] = self.config.get_team(team_slug or self.default_team)
if not the_team:
return False
the_team_slug: str = the_team.slug
if the_team_slug not in self.features:
self.load_feature_flags(the_team_slug)
team_features: List[Feature] = self.features[the_team_slug]
for feature in team_features:
if feature.name == feature_name:
return feature.enabled
return False
def get_datasets_dir(self, team_slug: Optional[str] = None) -> str:
"""
Gets the dataset directory of the specified team or the default one
Parameters
----------
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
Returns
-------
str
Path of the datasets for the selected team or the default one, or None if the Team was
not found.
Raises
------
ValueError
If no team was found.
"""
the_team: Optional[Team] = self.config.get_team(team_slug or self.default_team)
if not the_team:
raise ValueError("No team was found.")
return the_team.datasets_dir
def set_datasets_dir(
self, datasets_dir: Path, team_slug: Optional[str] = None
) -> None:
"""
Sets the dataset directory of the specified team or the default one.
Parameters
----------
datasets_dir: Path
Path to set as dataset directory of the team.
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
"""
self.config.put(
f"teams/{team_slug or self.default_team}/datasets_dir", datasets_dir
)
def annotation_types(self) -> List[Dict[str, UnknownType]]:
"""
Returns a list of annotation types.
Returns
------
List[Dict[str, UnknownType]]
A list with the annotation types as dictionaries.
"""
response: List[Dict[str, UnknownType]] = cast(
List[Dict[str, UnknownType]], self._get("/annotation_types")
)
return response
def get_annotators_report(
self,
dataset_ids: list[int],
start: datetime,
stop: datetime,
group_by: list[AnnotatorReportGrouping],
team_slug: Optional[str] = None,
) -> Response:
"""
Gets annotators the report for the given dataset.
Parameters
----------
dataset_ids: int
Ids of the datasets to include in the report.
start : datetime.datetime
Timezone aware report start DateTime
stop : datetime.datetime
Timezone aware report end DateTime
group_by: list[AnnotatorReportGrouping]
Non-empty list of grouping options for the report.
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
Returns
------
Response
The raw response of the report (CSV format) or None if the Team was not found.
Raises
------
ValueError
If no team was found. If start or stop parameters are not timezone aware. If no group_by options provided.
"""
if start.utcoffset() is None or stop.utcoffset() is None:
raise ValueError(
"start and stop parameters must be timezone aware (e.g. 2024-11-04T00:00:00Z)"
)
if not group_by:
raise ValueError(
f"At least one group_by option is required, any of: {[option.value for option in AnnotatorReportGrouping]}"
)
the_team: Optional[Team] = self.config.get_team(team_slug or self.default_team)
if not the_team:
raise ValueError("No team was found.")
the_team_slug: str = the_team.slug
response_data = self._post(
f"/v3/teams/{the_team_slug}/reports/annotator/jobs",
{
"start": start.isoformat(timespec="seconds"),
"stop": stop.isoformat(timespec="seconds"),
"dataset_ids": dataset_ids,
"group_by": [option.value for option in group_by],
"format": "csv",
"metrics": [
"active_time",
"total_annotations",
"total_items_annotated",
"time_per_item",
"time_per_annotation",
"review_pass_rate",
],
},
the_team_slug,
)
report_job = ReportJob.model_validate(response_data)
finished_report_job = self.poll_pending_report_job(the_team_slug, report_job.id)
assert isinstance(finished_report_job.url, str)
return self._get_raw_from_full_url(finished_report_job.url, the_team_slug)
@retry(
reraise=True,
wait=wait_exponential(max=MAX_WAIT),
stop=stop_after_delay(2 * HOUR),
retry=retry_if_exception_type(JobPendingException),
)
def poll_pending_report_job(self, team_slug: str, job_id: str) -> ReportJob:
job_status_url = f"/v3/teams/{team_slug}/reports/annotator/jobs/{job_id}"
response_data = self._get(job_status_url, team_slug)
report_job = ReportJob.model_validate(response_data)
if report_job.status == "failed":
raise ValueError("Building an annotator report failed, try again later.")
if report_job.status != "finished":
raise JobPendingException(
f"Polling for generated report results timed out, job status can be requested manually: {urljoin(self.url, job_status_url)}"
)
return report_job
def fetch_binary(self, url: str) -> Response:
"""
Fetches binary data from the given url via a stream.
Parameters
----------
url: str
The full url to download the binary data.
Returns
-------
Response
``request``'s Response object.
"""
response: Response = self._get_raw_from_full_url(url, stream=True)
return response
@classmethod
def local(cls, team_slug: Optional[str] = None) -> "Client":
"""
Factory method to use the default configuration file to init the client
Parameters
----------
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
Returns
-------
Client
The initialized client.
"""
config_path: Path = Path.home() / ".darwin" / "config.yaml"
return Client.from_config(config_path, team_slug=team_slug)
@classmethod
def from_config(
cls, config_path: Path, team_slug: Optional[str] = None
) -> "Client":
"""
Factory method to create a client from the configuration file passed as parameter
Parameters
----------
config_path : str
Path to a configuration file to use to create the client
team_slug: Optional[str]
Team slug of the team the dataset will belong to. Defaults to None.
Returns
-------
Client
The initialized client.
"""
if not config_path.exists():
raise MissingConfig()
config = Config(config_path)
return cls(config=config, default_team=team_slug)
@classmethod
def from_guest(cls, datasets_dir: Optional[Path] = None) -> "Client":
"""
Factory method to create a client and access datasets as a guest.
Parameters
----------
datasets_dir : Optional[Path]
String where the client should be initialized from (aka the root path). Defaults to None.
Returns
-------
Client
The initialized client.
"""
if datasets_dir is None:
datasets_dir = Path.home() / ".darwin" / "datasets"
config: Config = Config(path=None)
config.set_global(
api_endpoint=Client.default_api_url(), base_url=Client.default_base_url()
)
return cls(config=config)
@classmethod
def from_api_key(
cls, api_key: str, datasets_dir: Optional[Path] = None
) -> "Client":
"""
Factory method to create a client given an API key.
Parameters
----------
api_key: str
API key to use to authenticate the client
datasets_dir : Optional[Path]
String where the client should be initialized from (aka the root path). Defaults to None.
Returns
-------
Client
The initialized client.
"""
if not datasets_dir:
datasets_dir = Path.home() / ".darwin" / "datasets"
headers: Dict[str, str] = {
"Content-Type": "application/json",
"Authorization": f"ApiKey {api_key}",
}
api_url: str = Client.default_api_url()
response: requests.Response = requests.get(
urljoin(api_url, "/users/token_info"), headers=headers
)
if not response.ok:
raise InvalidLogin()
data: Dict[str, UnknownType] = response.json()
team: str = data["selected_team"]["slug"]
config: Config = Config(path=None)
config.set_team(team=team, api_key=api_key, datasets_dir=str(datasets_dir))
config.set_global(api_endpoint=api_url, base_url=Client.default_base_url())
return cls(config=config, default_team=team)
@staticmethod
def default_api_url() -> str:
"""
Returns the default api url.
Returns
-------
str
The default api url.
"""
return f"{Client.default_base_url()}/api/"
@staticmethod
def default_base_url() -> str:
"""
Returns the default base url.
Returns
-------
str
The default base url.
"""
return os.getenv("DARWIN_BASE_URL", "https://darwin.v7labs.com")
def _get_headers(
self,
team_slug: Optional[str] = None,
compressed: bool = False,
auth_token: Optional[bool] = False,
) -> Dict[str, str]:
headers: Dict[str, str] = {"Content-Type": "application/json"}
if auth_token:
return headers
api_key: Optional[str] = None
team_config: Optional[Team] = self.config.get_team(
team_slug or self.default_team, raise_on_invalid_team=False
)
if team_config:
api_key = team_config.api_key
if api_key and len(api_key) > 0:
headers["Authorization"] = f"ApiKey {api_key}"
if compressed:
headers["X-Darwin-Payload-Compression-Version"] = "1"
from darwin.version import __version__
headers["User-Agent"] = f"darwin-py/{__version__}"
return headers
@retry(
wait=wait_exponential_jitter(initial=INITIAL_WAIT, max=MAX_WAIT),
stop=stop_after_attempt(MAX_RETRIES),
retry=retry_if_status_code_429_or_5xx,
before_sleep=log_retry_error,
)
def _get_raw_from_full_url(
self,
url: str,
team_slug: Optional[str] = None,
stream: bool = False,
auth_token: Optional[bool] = False,
) -> Response:
response: Response = self.session.get(
url,
headers=self._get_headers(team_slug, auth_token=auth_token),
stream=stream,
)
self.log.debug(
f"Client GET request response ({get_response_content(response)}) with status "
f"({response.status_code}). "
f"Client: ({self})"
f"Request: (url={url})"
)
self._raise_if_known_error(response, url)
response.raise_for_status()
return response
def _get_raw(
self,
endpoint: str,
team_slug: Optional[str] = None,
stream: bool = False,
) -> Response:
return self._get_raw_from_full_url(
urljoin(self.url, endpoint), team_slug, stream=stream
)
def _get(
self, endpoint: str, team_slug: Optional[str] = None
) -> Union[Dict[str, UnknownType], List[Dict[str, UnknownType]]]:
response = self._get_raw(endpoint, team_slug)
return self._decode_response(response)
@retry(
wait=wait_exponential_jitter(initial=INITIAL_WAIT, max=MAX_WAIT),
stop=stop_after_attempt(MAX_RETRIES),
retry=retry_if_status_code_429_or_5xx,
before_sleep=log_retry_error,
)
def _put_raw(
self,
endpoint: str,
payload: Dict[str, UnknownType],
team_slug: Optional[str] = None,
) -> Response:
response: requests.Response = self.session.put(
urljoin(self.url, endpoint),
json=payload,
headers=self._get_headers(team_slug),
)
self.log.debug(
f"Client PUT request got response ({get_response_content(response)}) with status "
f"({response.status_code}). "
f"Client: ({self})"
f"Request: (endpoint={endpoint}, payload={payload})"
)
self._raise_if_known_error(response, urljoin(self.url, endpoint))
response.raise_for_status()
return response
def _put(
self,
endpoint: str,
payload: Dict[str, UnknownType],
team_slug: Optional[str] = None,
) -> Union[Dict[str, UnknownType], List[Dict[str, UnknownType]]]:
response: Response = self._put_raw(endpoint, payload, team_slug)
return self._decode_response(response)
@retry(
wait=wait_exponential_jitter(initial=INITIAL_WAIT, max=MAX_WAIT),
stop=stop_after_attempt(MAX_RETRIES),
retry=retry_if_status_code_429_or_5xx,
before_sleep=log_retry_error,
)
def _post_raw(
self,
endpoint: str,
payload: Optional[Dict[str, UnknownType]] = None,
team_slug: Optional[str] = None,
) -> Response:
if payload is None:
payload = {}
compression_level = int(
self.config.get("global/payload_compression_level", "0")
)