Repository navigation
Expand file tree
/
Copy pathhttp.py
More file actions
1046 lines (898 loc) · 41.9 KB
/
Copy pathhttp.py
File metadata and controls
1046 lines (898 loc) · 41.9 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
8000
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 base64
import copy
import datetime
import hashlib
import logging
import os
import random
import socket
import threading
import time
from enum import Enum
from functools import lru_cache
from http.client import HTTPConnection
from json import dumps
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urljoin
import jwt
import pandas as pd
import requests
from pydantic import BaseModel
from pythonjsonlogger import jsonlogger
from requests.exceptions import RequestException
from upgini.__about__ import __version__
from upgini.errors import (
HttpError,
UnauthorizedError,
UpginiConnectionError,
ValidationError,
)
from upgini.metadata import (
FileColumnMeaningType,
FileMetadata,
FileMetrics,
ProviderTaskMetadataV2,
SearchCustomization,
)
from upgini.resource_bundle import bundle
from upgini.utils.track_info import get_track_metrics
UPGINI_URL: str = "UPGINI_URL"
UPGINI_API_KEY: str = "UPGINI_API_KEY"
DEMO_API_KEY: str = "Aa4BPwGFbn1zNEXIkZ-NbhsRk0ricN6puKuga1-O5lM"
TRACK_METRICS_TIMEOUT_SECONDS: int = 10
refresh_token_lock = threading.Lock()
def debug_requests_on():
"""Switches on logging of the requests module."""
HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
class FileColumn:
def __init__(self, column_json: dict):
self.index = column_json["columnIndex"]
if "fileColumnMeaningType" in column_json:
self.meaning_type = column_json["fileColumnMeaningType"]
self.data_type = column_json["fileColumnDataType"]
self.name = column_json["columnName"]
self.sample = column_json["sampleValues"]
def to_json(self) -> dict:
return {
"columnIndex": self.index,
"fileColumnMeaningType": self.meaning_type,
"fileColumnDataType": self.data_type,
"initialColumnName": self.name,
}
def __repr__(self) -> str:
return self.name
class FileUploadResponse:
def __init__(self, response_json: dict):
self.file_upload_task_id = response_json["fileUploadTaskId"]
self.file_name = response_json["fileName"]
self.columns = []
for column_json in response_json["fileColumns"]["columns"]:
self.columns.append(FileColumn(column_json))
class SearchTaskResponse:
def __init__(self, response: dict):
self.file_upload_id = response["fileUploadId"]
self.search_task_id = response["searchTaskId"]
self.initial_search_task_id = response.get("initialSearchTaskId")
self.search_type = response["searchType"]
self.status = response["status"]
self.extract_features = response["extractFeatures"]
self.return_scores = response["returnScores"]
self.created_at = response["createdAt"]
# class ModelEvalSet(BaseModel):
# eval_set_index: int
# hit_rate: float
# uplift: Optional[float]
# auc: Optional[float]
# gini: Optional[float]
# rmse: Optional[float]
# accuracy: Optional[float]
class ProviderTaskSummary:
def __init__(self, response: dict):
self.ads_search_task_id = response["adsSearchTaskId"]
self.search_task_id = response["searchTaskId"]
self.status = response["taskStatus"]
self.error_message = response.get("errorMessage")
self.unused_features_for_generation = response.get("unusedFeaturesForGeneration")
class SearchTaskSummary:
def __init__(self, response: dict):
self.search_task_id = response["searchTaskId"]
self.file_upload_id = response["fileUploadTaskId"]
self.status = response["searchTaskStatus"]
# self.features_found = response["featuresFoundCount"]
# self.providers_checked = response["providersCheckedCount"]
# self.important_providers_count = response["importantProvidersCount"]
# self.important_features_count = response["importantFeaturesCount"]
self.initial_important_providers = [
ProviderTaskSummary(provider_response) for provider_response in response["importantProviders"]
]
self.validation_important_providers = [
ProviderTaskSummary(provider_response) for provider_response in response["validationImportantProviders"]
]
self.created_at = response["createdAt"]
class SearchProgress:
def __init__(self, *args):
# (response: dict)
if len(args) == 1 and isinstance(args[0], dict):
response: Dict[str, Any] = args[0]
self.stage = response["currentStage"]
self.percent = float(response["percent"])
self.eta: Optional[int] = None
self.error = response.get("errorCode")
self.error_message = response.get("errorMessage")
# (percent: float, stage: ProgressStage)
elif len(args) == 2 and isinstance(args[0], float) and isinstance(args[1], ProgressStage):
self.percent = args[0]
self.stage = args[1].value
self.eta: Optional[int] = None
self.error = None
self.error_message = None
# (percent: float, stage: ProgressStage, eta: int)
elif (
len(args) == 3
and isinstance(args[0], float)
and isinstance(args[1], ProgressStage)
and isinstance(args[2], float)
):
self.percent = args[0]
self.stage = args[1].value
seconds_left = args[2]
self.eta = int(seconds_left * (100 - self.percent) / self.percent)
self.error = None
self.error_message = None
else:
raise RuntimeError("Unsupported arguments for SearchProgress constructor")
def recalculate_eta(self, seconds_left: int):
self.eta = int(seconds_left * (100 - self.percent) / self.percent)
def update_eta(self, seconds: int):
# temporary workaround - add 5 minutes if time is over
if seconds <= 0:
self.eta = 5 * 60
else:
self.eta = seconds
def eta_time(self) -> str:
return str(datetime.timedelta(seconds=self.eta))
def to_progress_bar(self) -> Tuple[int, str]:
text = bundle.get(self.stage)
eta = ""
if self.eta is not None:
eta = f"Approximately {self.eta_time()} remaining"
return (int(self.percent), text, eta)
def copy(self) -> "SearchProgress":
return copy.deepcopy(self)
class ProgressStage(Enum):
START_FIT = "START_FIT"
START_TRANSFORM = "START_TRANSFORM"
CREATING_FIT = "CREATING_FIT"
CREATING_TRANSFORM = "CREATING_TRANSFORM"
MATCHING = "MATCHING"
AUTOFE = "AUTOFE"
SEARCHING = "SEARCHING"
ENRICHING = "ENRICHING"
GENERATING_REPORT = "GENERATING_REPORT"
DOWNLOADING = "DOWNLOADING"
RETRIEVING_CACHE = "RETRIEVING_CACHE"
FINISHED = "FINISHED"
FAILED = "FAILED"
class LogEvent(BaseModel):
source: str
tags: str
service: str
hostname: str
message: str
class TransformUsage:
def __init__(self, json: dict):
self.transformed_rows = json.get("transformedRows")
self.rest_rows = json.get("restRows")
self.limit = json.get("limit")
self.has_limit = json.get("hasLimit")
def __str__(self):
return (
f"TransformUsage(transformed_rows={self.transformed_rows}, "
f"rest_rows={self.rest_rows}, limit={self.limit}, "
f"has_limit={self.has_limit})"
)
class _RestClient:
PROD_BACKEND_URL = "https://search.upgini.com"
SERVICE_ROOT = "public/api/v1/"
SERVICE_ROOT_V2 = "public/api/v2/"
REFRESH_TOKEN_URI_FMT = "private/api/v2/security/refresh_access_token"
# V2
CHECK_UPLOADED_FILE_URL_FMT_V2 = SERVICE_ROOT_V2 + "search/check-file?fileUploadId={0}"
INITIAL_SEARCH_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/initial"
INITIAL_SEARCH_WITHOUT_UPLOAD_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/initial-without-upload?fileUploadId={0}"
VALIDATION_SEARCH_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/validation?initialSearchTaskId={0}"
VALIDATION_SEARCH_WITHOUT_UPLOAD_URI_FMT_V2 = (
SERVICE_ROOT_V2 + "search/validation-without-upload?fileUpload_id={0}&initialSearchTask={1}"
)
SEARCH_TASK_SUMMARY_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/{0}"
SEARCH_TASK_PROGRESS_URI_FMT = SERVICE_ROOT_V2 + "search/{0}/progress"
STOP_SEARCH_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/{0}/stop"
SEARCH_MODELS_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/models/{0}"
SEARCH_SCORES_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/scores/{0}"
SEARCH_FEATURES_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/rawfeatures/{0}?metricsCalculation={1}"
SEARCH_TARGET_OUTLIERS_URI_FMT = SERVICE_ROOT_V2 + "search/target-outliers/{0}"
SEARCH_MODEL_FILE_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/models/{0}/file"
SEARCH_SCORES_FILE_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/scores/{0}/file"
SEARCH_FEATURES_FILE_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/rawfeatures/{0}/file?metricsCalculation={1}"
SEARCH_TARGET_OUTLIERS_FILE_URI_FMT = SERVICE_ROOT_V2 + "search/target-outliers/{0}/file"
SEARCH_FILE_METADATA_URI_FMT_V2 = SERVICE_ROOT_V2 + "search/{0}/metadata"
SEARCH_TASK_METADATA_FMT_V3 = SERVICE_ROOT_V2 + "search/metadata-v2/{0}"
SEARCH_DUMP_INPUT_FMT_V2 = SERVICE_ROOT_V2 + "search/dump-input"
TRANSFORM_USAGE_FMT = SERVICE_ROOT_V2 + "user/transform-usage"
UPLOAD_USER_ADS_URI = SERVICE_ROOT + "ads/upload"
SEND_LOG_EVENT_URI = "private/api/v2/events/send"
REGISTER_ADS_URI = "private/api/v2/ads/register"
ACTIVATE_ADS_URI = "private/api/v2/ads/activate"
DEACTIVATE_ADS_URI = "private/api/v2/ads/deactivate"
TOGGLE_ADS_URI_FMT = "private/api/v2/ads/{0}/toggle"
DELETE_ADS_URI_FMT = "private/api/v2/ads/{0}"
REANNOUNCE_ALL_ADS_URI_FMT = "private/api/v2/ads/reannounce-all-ads"
POLL_ADS_MANAGEMENT_STATUS_URI_FMT = "private/api/v2/ads/management-task/{0}"
GET_ADS_DESCRIPTION_URI_FMT = "private/api/v2/ads/{0}"
GET_ALL_ADS_DESCRIPTIONS_URI = "private/api/v2/ads/descriptions"
GET_ACTIVE_ADS_DEFINITIONS_URI = "private/api/v2/ads/definitions"
UPLOAD_ONLINE_URI = "private/api/v2/ads/upload-online"
STOP_ADS_MANAGEMENT_TASK_URI_FMT = "private/api/v2/ads/management-task/{0}/stop"
UNION_SEARCH_TASKS_URI_FMT = SERVICE_ROOT_V2 + "search/merge"
ACCESS_TOKEN_HEADER_NAME = "Authorization"
CONTENT_TYPE_HEADER_NAME = "Content-Type"
CONTENT_TYPE_HEADER_VALUE_JSON = "application/json;charset=UTF8"
TRACE_ID_HEADER_NAME = "Trace-Id"
CHUNK_SIZE = 0x200000
DEFAULT_OWNER = "Python SDK"
USER_AGENT_HEADER_NAME = "User-Agent"
USER_AGENT_HEADER_VALUE = "pyupgini/" + __version__
SEARCH_KEYS_HEADER_NAME = "Search-Keys"
def __init__(self, service_endpoint, refresh_token, client_ip=None, client_visitorid=None):
# debug_requests_on()
self._service_endpoint = service_endpoint
self._refresh_token = refresh_token
# self.silent_mode = silent_mode
self.client_ip = client_ip
self.client_visitorid = client_visitorid
self._access_token = self._refresh_access_token()
# self._access_token: Optional[str] = None # self._refresh_access_token()
self.last_refresh_time = time.time()
def _refresh_access_token(self, retry_attempts_rest=5) -> str:
api_path = self.REFRESH_TOKEN_URI_FMT
try:
response = requests.post(
url=urljoin(self._service_endpoint, api_path),
json={"refreshToken": self._refresh_token},
)
if response.status_code >= 400:
raise HttpError(response.text, response.status_code)
self._access_token = response.json()["access_token"]
return self._access_token
except requests.exceptions.ConnectionError:
if retry_attempts_rest > 0:
time.sleep(5)
return self._refresh_access_token(retry_attempts_rest - 1)
try:
local_ip = socket.gethostbyname(socket.gethostname())
except Exception:
local_ip = ""
try:
requests.get("https://pypi.org")
raise UpginiConnectionError(bundle.get("no_connection_to_upgini").format(local_ip))
except requests.exceptions.ConnectionError:
raise UpginiConnectionError(bundle.get("no_internet_connection").format(local_ip))
def _syncronized_refresh_access_token(self) -> str:
with refresh_token_lock:
now = time.time()
if (now - self.last_refresh_time) > 60 or self._access_token is None:
self._access_token = self._refresh_access_token()
self.last_refresh_time = now
return self._access_token
def _get_access_token(self) -> str:
if self._access_token is not None:
return self._access_token
else:
return self._syncronized_refresh_access_token()
def _with_unauth_retry(self, request, try_number: int = 0, need_connection_retry: bool = True):
try:
return request()
except RequestException as e:
if need_connection_retry:
print(bundle.get("connection_error_with_retry"))
time.sleep(10)
return self._with_unauth_retry(request)
else:
print(e)
show_status_error()
raise e
except UnauthorizedError:
self._syncronized_refresh_access_token()
return request()
except HttpError as e:
if (e.status_code == 429 or e.status_code >= 500) and try_number < 3:
time.sleep(random.randint(1, 10))
return self._with_unauth_retry(request, try_number + 1)
elif e.status_code == 400 and "MD5Exception".lower() in e.message.lower() and try_number < 3:
# TODO send log
# print(bundle.get("upload_file_checksum_fail").format(e.message))
return self._with_unauth_retry(request, try_number + 1)
elif e.status_code == 403:
raise ValidationError(bundle.get("access_denied"))
elif "more than one concurrent search request" in e.message.lower():
raise ValidationError(bundle.get("concurrent_request"))
else:
print(e)
show_status_error()
raise e
@staticmethod
def meaning_type_by_name(name: str, metadata: FileMetadata) -> Optional[FileColumnMeaningType]:
for c in metadata.columns:
if c.name == name:
return c.meaningType
return None
@staticmethod
def search_keys_meaning_types(metadata: FileMetadata) -> List[str]:
search_key_names = {key for keys in metadata.searchKeys for key in keys}
meaning_types = [_RestClient.meaning_type_by_name(name, metadata) for name in search_key_names]
return [meaning_type.value for meaning_type in meaning_types if meaning_type is not None]
def dump_input_files(
self,
trace_id: str,
x_path: str,
y_path: Optional[str] = None,
eval_x_path: Optional[str] = None,
eval_y_path: Optional[str] = None,
):
api_path = self.SEARCH_DUMP_INPUT_FMT_V2
files = {}
with open(x_path, "rb") as x_file:
files["x"] = ("x.pickle", x_file, "application/octet-stream")
if y_path:
with open(y_path, "rb") as y_file:
files["y"] = ("y.pickle", y_file, "application/octet-stream")
if eval_x_path and eval_y_path:
with open(eval_x_path, "rb") as eval_x_file, open(eval_y_path, "rb") as eval_y_file:
files["eval_x"] = ("eval_x.pickle", eval_x_file, "application/octet-stream")
files["eval_y"] = ("eval_y.pickle", eval_y_file, "application/octet-stream")
self._with_unauth_retry(
lambda: self._send_post_file_req_v2(
api_path, files, trace_id=trace_id, need_json_response=False
)
)
else:
self._with_unauth_retry(
lambda: self._send_post_file_req_v2(
api_path, files, trace_id=trace_id, need_json_response=False
)
)
else:
self._with_unauth_retry(
lambda: self._send_post_file_req_v2(api_path, files, trace_id=trace_id, need_json_response=False)
)
def initial_search_v2(
self,
trace_id: str,
file_path: str,
metadata: FileMetadata,
metrics: FileMetrics,
search_customization: Optional[SearchCustomization],
) -> SearchTaskResponse:
api_path = self.INITIAL_SEARCH_URI_FMT_V2
track_metrics = get_track_metrics(self.client_ip, self.client_visitorid)
def open_and_send():
md5_hash = hashlib.md5()
with open(file_path, "rb") as file:
content = file.read()
md5_hash.update(content)
digest = md5_hash.hexdigest()
metadata_with_md5 = metadata.copy(update={"checksumMD5": digest})
digest_sha256 = hashlib.sha256(
pd.util.hash_pandas_object(pd.read_parquet(file_path, engine="fastparquet")).values
).hexdigest()
metadata_with_md5 = metadata_with_md5.copy(update={"digest": digest_sha256})
with open(file_path, "rb") as file:
files = {
"metadata": (
"metadata.json",
metadata_with_md5.json(exclude_none=True).encode(),
"application/json",
),
"tracking": (
"tracking.json",
dumps(track_metrics).encode(),
"application/json",
),
"metrics": (
"metrics.json",
metrics.json(exclude_none=True).encode(),
"application/json",
),
"file": (metadata_with_md5.name, file, "application/octet-stream"),
}
if search_customization is not None:
files["customization"] = (
"customization.json",
search_customization.json(exclude_none=True).encode(),
"application/json",
)
additional_headers = {self.SEARCH_KEYS_HEADER_NAME: ",".join(self.search_keys_meaning_types(metadata))}
return self._send_post_file_req_v2(
api_path, files, trace_id=trace_id, additional_headers=additional_headers
)
response = self._with_unauth_retry(open_and_send)
return SearchTaskResponse(response)
def check_uploaded_file_v2(self, trace_id: str, file_upload_id: str, metadata: FileMetadata) -> bool:
api_path = self.CHECK_UPLOADED_FILE_URL_FMT_V2.format(file_upload_id)
response = self._with_unauth_retry(
lambda: self._send_post_req(api_path, trace_id, metadata.json(exclude_none=True))
)
return bool(response)
def initial_search_without_upload_v2(
self,
trace_id: str,
file_upload_id: str,
metadata: FileMetadata,
metrics: FileMetrics,
search_customization: Optional[SearchCustomization],
) -> SearchTaskResponse:
api_path = self.INITIAL_SEARCH_WITHOUT_UPLOAD_URI_FMT_V2.format(file_upload_id)
files = {
"metadata": ("metadata.json", metadata.json(exclude_none=True).encode(), "application/json"),
"metrics": ("metrics.json", metrics.json(exclude_none=True).encode(), "application/json"),
}
if search_customization is not None:
files["customization"] = search_customization.json(exclude_none=True).encode()
additional_headers = {self.SEARCH_KEYS_HEADER_NAME: ",".join(self.search_keys_meaning_types(metadata))}
response = self._with_unauth_retry(
lambda: self._send_post_file_req_v2(
api_path, files, trace_id=trace_id, additional_headers=additional_headers
)
)
return SearchTaskResponse(response)
def validation_search_v2(
self,
trace_id: str,
file_path: str,
initial_search_task_id: str,
metadata: FileMetadata,
metrics: FileMetrics,
search_customization: Optional[SearchCustomization],
) -> SearchTaskResponse:
api_path = self.VALIDATION_SEARCH_URI_FMT_V2.format(initial_search_task_id)
def open_and_send():
md5_hash = hashlib.md5()
with open(file_path, "rb") as file:
content = file.read()
md5_hash.update(content)
digest = md5_hash.hexdigest()
metadata_with_md5 = metadata.copy(update={"checksumMD5": digest})
digest_sha256 = hashlib.sha256(
pd.util.hash_pandas_object(pd.read_parquet(file_path, engine="fastparquet")).values
).hexdigest()
metadata_with_md5 = metadata_with_md5.copy(update={"digest": digest_sha256})
with open(file_path, "rb") as file:
files = {
"metadata": (
"metadata.json",
metadata_with_md5.json(exclude_none=True).encode(),
"application/json",
),
"tracking": (
"tracking.json",
dumps(get_track_metrics(self.client_ip, self.client_visitorid)).encode(),
"application/json",
),
"metrics": (
"metrics.json",
metrics.json(exclude_none=True).encode(),
"application/json",
),
"file": (metadata_with_md5.name, file, "application/octet-stream"),
}
if search_customization is not None:
files["customization"] = (
"customization.json",
search_customization.json(exclude_none=True).encode(),
"application/json",
)
additional_headers = {self.SEARCH_KEYS_HEADER_NAME: ",".join(self.search_keys_meaning_types(metadata))}
return self._send_post_file_req_v2(
api_path, files, trace_id=trace_id, additional_headers=additional_headers
)
response = self._with_unauth_retry(open_and_send)
return SearchTaskResponse(response)
def validation_search_without_upload_v2(
self,
trace_id: str,
file_upload_id: str,
initial_search_task_id: str,
metadata: FileMetadata,
metrics: FileMetrics,
search_customization: Optional[SearchCustomization],
) -> SearchTaskResponse:
api_path = self.VALIDATION_SEARCH_WITHOUT_UPLOAD_URI_FMT_V2.format(file_upload_id, initial_search_task_id)
files = {
"metadata": ("metadata.json", metadata.json(exclude_none=True).encode(), "application/json"),
"metrics": ("metrics.json", metrics.json(exclude_none=True).encode(), "application/json"),
}
if search_customization is not None:
files["customization"] = search_customization.json(exclude_none=True).encode()
additional_headers = {self.SEARCH_KEYS_HEADER_NAME: ",".join(self.search_keys_meaning_types(metadata))}
response = self._with_unauth_retry(
lambda: self._send_post_file_req_v2(
api_path, files, trace_id=trace_id, additional_headers=additional_headers
)
)
return SearchTaskResponse(response)
def search_task_summary_v2(self, trace_id: str, search_task_id: str) -> SearchTaskSummary:
api_path = self.SEARCH_TASK_SUMMARY_URI_FMT_V2.format(search_task_id)
response = self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
return SearchTaskSummary(response)
def get_search_progress(self, trace_id: str, search_task_id: str) -> SearchProgress:
api_path = self.SEARCH_TASK_PROGRESS_URI_FMT.format(search_task_id)
response = self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
return SearchProgress(response)
def stop_search_task_v2(self, trace_id: str, search_task_id: str):
api_path = self.STOP_SEARCH_URI_FMT_V2.format(search_task_id)
self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id=trace_id))
def get_search_models_v2(self, trace_id: str, search_task_id: str):
api_path = self.SEARCH_MODELS_URI_FMT_V2.format(search_task_id)
return self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
def get_search_model_file_v2(self, trace_id: str, trained_model_id: str):
api_path = self.SEARCH_MODEL_FILE_URI_FMT_V2.format(trained_model_id)
return self._with_unauth_retry(lambda: self._send_get_file_req(api_path, trace_id))
def get_search_scores_v2(self, trace_id: str, search_task_id: str):
api_path = self.SEARCH_SCORES_URI_FMT_V2.format(search_task_id)
return self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
def get_search_scores_file_v2(self, trace_id: str, ads_scores_id: str):
api_path = self.SEARCH_SCORES_FILE_URI_FMT_V2.format(ads_scores_id)
return self._with_unauth_retry(lambda: self._send_get_file_req(api_path, trace_id))
def get_search_features_v2(self, trace_id: str, search_task_id: str, metrics_calculation: bool):
api_path = self.SEARCH_FEATURES_URI_FMT_V2.format(search_task_id, str(metrics_calculation).lower())
return self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
def get_search_features_file_v2(self, trace_id: str, ads_features_id: str, metrics_calculation: bool) -> bytes:
api_path = self.SEARCH_FEATURES_FILE_URI_FMT_V2.format(ads_features_id, str(metrics_calculation).lower())
return self._with_unauth_retry(lambda: self._send_get_file_req(api_path, trace_id))
def get_search_target_outliners(self, trace_id: str, search_task_id: str):
api_path = self.SEARCH_TARGET_OUTLIERS_URI_FMT.format(search_task_id)
return self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
def get_search_target_outliners_file(self, trace_id: str, ads_target_outliers_id: str) -> bytes:
api_path = self.SEARCH_TARGET_OUTLIERS_FILE_URI_FMT.format(ads_target_outliers_id)
return self._with_unauth_retry(lambda: self._send_get_file_req(api_path, trace_id))
def upload_user_ads(self, file_path: str, metadata: FileMetadata):
api_path = self.UPLOAD_USER_ADS_URI
def open_and_send():
with open(file_path, "rb") as file:
files = {
"file": (metadata.name, file, "application/octet-stream"),
"metadata": (
"metadata.json",
metadata.json(exclude_none=True).encode(),
"application/json",
),
}
return self._send_post_file_req_v2(api_path, files)
return self._with_unauth_retry(lambda: open_and_send())
def get_search_file_metadata(self, search_task_id: str, trace_id: str) -> FileMetadata:
api_path = self.SEARCH_FILE_METADATA_URI_FMT_V2.format(search_task_id)
response = self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
return FileMetadata.parse_obj(response)
def get_provider_search_metadata_v3(self, provider_search_task_id: str, trace_id: str) -> ProviderTaskMetadataV2:
api_path = self.SEARCH_TASK_METADATA_FMT_V3.format(provider_search_task_id)
response = self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
return ProviderTaskMetadataV2.parse_obj(response)
def get_current_transform_usage(self, trace_id) -> TransformUsage:
track_metrics = get_track_metrics(self.client_ip, self.client_visitorid)
visitor_id = track_metrics.get("visitorId")
response = self._with_unauth_retry(
lambda: self._send_get_req(
self.TRANSFORM_USAGE_FMT, trace_id, additional_headers={"Visitor-Id": visitor_id}
)
)
return TransformUsage(response)
def send_log_event(self, log_event: LogEvent):
api_path = self.SEND_LOG_EVENT_URI
try:
self._with_unauth_retry(
lambda: self._send_post_req(
api_path,
trace_id=None,
json_data=log_event.dict(exclude_none=True),
content_type="application/json",
result_format="text",
silent=True,
),
need_connection_retry=False,
)
except Exception:
self.send_log_event_unauth(log_event)
@staticmethod
def send_log_event_unauth(log_event: LogEvent):
api_path = _RestClient.SEND_LOG_EVENT_URI
try:
requests.post(
url=urljoin(_RestClient.PROD_BACKEND_URL, api_path),
json=log_event.dict(exclude_none=True),
headers=_RestClient._get_base_headers(content_type="application/json"),
)
except Exception:
pass
# ADS management
def register_ads(self, request: Dict, trace_id: str) -> str:
api_path = self.REGISTER_ADS_URI
response = self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id, request))
return response["adsManagementTaskId"]
def delete_ads(self, ads_definition_id: str, trace_id: str) -> str:
api_path = self.DELETE_ADS_URI_FMT.format(ads_definition_id)
response = self._with_unauth_retry(lambda: self._send_delete_req(api_path, trace_id))
return response["adsManagementTaskId"]
def activate_datatables(self, request: Dict, trace_id: str):
api_path = self.ACTIVATE_ADS_URI
self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id, request, result_format=None))
def deactivate_data_tables(self, request: Dict, trace_id: str):
api_path = self.DEACTIVATE_ADS_URI
self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id, request, result_format=None))
def reannounce_all_ads(self, trace_id: str) -> str:
api_path = self.REANNOUNCE_ALL_ADS_URI_FMT
response = self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id))
return response["adsManagementTaskId"]
def toggle_ads(self, ads_definition_id: str, trace_id: str):
api_path = self.TOGGLE_ADS_URI_FMT.format(ads_definition_id)
return self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id))
def poll_ads_management_task_status(self, ads_management_task_id: str, trace_id: str) -> Dict[str, str]:
api_path = self.POLL_ADS_MANAGEMENT_STATUS_URI_FMT.format(ads_management_task_id)
response = self._with_unauth_retry(lambda: self._send_get_req(api_path, trace_id))
return response
def get_ads_description(self, ads_definition_id: str):
api_path = self.GET_ADS_DESCRIPTION_URI_FMT.format(ads_definition_id)
response = self._with_unauth_retry(lambda: self._send_get_req(api_path, None))
return response
def get_all_ads_descriptions(self):
return self._with_unauth_retry(lambda: self._send_get_req(self.GET_ALL_ADS_DESCRIPTIONS_URI, None))
def get_active_ads_definitions(self):
return self._with_unauth_retry(lambda: self._send_get_req(self.GET_ACTIVE_ADS_DEFINITIONS_URI, None))
def get_current_email(self) -> Optional[str]:
try:
return jwt.decode(self._get_access_token(), options={"verify_signature": False})["sub"]
except Exception:
return None
def upload_online(self, request: dict, trace_id: str):
api_path = self.UPLOAD_ONLINE_URI
response = self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id, request))
return response["adsManagementTaskId"]
def stop_ads_management_task(self, ads_management_task_id: str, trace_id: str):
api_path = self.STOP_ADS_MANAGEMENT_TASK_URI_FMT.format(ads_management_task_id)
self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id))
def union_search_tasks(self, request: dict, trace_id: str):
api_path = self.UNION_SEARCH_TASKS_URI_FMT
return self._with_unauth_retry(lambda: self._send_post_req(api_path, trace_id, request, result_format=None))
# ---
def _send_get_req(self, api_path: str, trace_id: Optional[str], additional_headers: Optional[dict] = None):
response = requests.get(
url=urljoin(self._service_endpoint, api_path),
headers=self._get_headers(trace_id=trace_id, additional_headers=additional_headers),
)
if response.status_code >= 400:
raise HttpError(response.text, status_code=response.status_code)
return response.json()
def _send_get_file_req(self, api_path: str, trace_id: Optional[str]):
response = requests.get(
url=urljoin(self._service_endpoint, api_path), headers=self._get_headers(trace_id=trace_id)
)
if response.status_code >= 400:
raise HttpError(response.text, status_code=response.status_code)
return response.content
def _send_post_req(
self,
api_path: str,
trace_id: Optional[str],
json_data=None,
data=None,
content_type=None,
result_format="json",
silent=False,
):
response = requests.post(
url=urljoin(self._service_endpoint, api_path),
data=data,
json=json_data,
headers=self._get_headers(content_type, trace_id=trace_id),
)
if response.status_code >= 400:
if not silent and response.status_code != 401:
logging.error(f"Failed to execute request to {api_path}: {response}")
raise HttpError(response.text, status_code=response.status_code)
if result_format == "json":
return response.json()
else:
return response.text
def _send_delete_req(
self,
api_path: str,
trace_id: Optional[str],
content_type=None,
result_format="json",
silent=False,
):
response = requests.delete(
url=urljoin(self._service_endpoint, api_path),
headers=self._get_headers(content_type, trace_id=trace_id),
)
if response.status_code >= 400:
if not silent and response.status_code != 401:
logging.error(f"Failed to execute request to {api_path}: {response}")
raise HttpError(response.text, status_code=response.status_code)
if result_format == "json":
return response.json()
else:
return response.text
def _send_post_file_req_v2(
self,
api_path,
files,
data=None,
trace_id: Optional[str] = None,
additional_headers: Optional[Dict[str, str]] = None,
need_json_response=True,
):
additional_headers = additional_headers or {}
response = requests.post(
url=urljoin(self._service_endpoint, api_path),
data=data,
files=files,
headers=self._get_headers(trace_id=trace_id, additional_headers=additional_headers),
)
if response.status_code >= 400:
raise HttpError(response.text, status_code=response.status_code)
if need_json_response:
return response.json()
else:
return response
@staticmethod
def _get_base_headers(
content_type: Optional[str] = None,
trace_id: Optional[str] = None,
additional_headers: Optional[Dict[str, str]] = None,
) -> Dict[str, str]:
additional_headers = additional_headers or {}
headers = {
_RestClient.USER_AGENT_HEADER_NAME: _RestClient.USER_AGENT_HEADER_VALUE,
}
if content_type:
headers[_RestClient.CONTENT_TYPE_HEADER_NAME] = content_type
if trace_id:
headers[_RestClient.TRACE_ID_HEADER_NAME] = trace_id
for header_key, header_value in additional_headers.items():
headers[header_key] = header_value
return headers
def _get_headers(
self,
content_type: Optional[str] = None,
trace_id: Optional[str] = None,
additional_headers: Optional[Dict[str, str]] = None,
):
headers = self._get_base_headers(content_type, trace_id, additional_headers or {})
headers[self.ACCESS_TOKEN_HEADER_NAME] = "Bearer " + self._get_access_token()
return headers
@staticmethod
def _update_columns_request(update_columns):
return {"columns": [x.to_json() for x in update_columns]}
def _resolve_backend_url(backend_url: Optional[str]) -> str:
if backend_url is not None:
return backend_url
elif UPGINI_URL in os.environ and os.environ[UPGINI_URL]:
return os.environ[UPGINI_URL]
else:
return _RestClient.PROD_BACKEND_URL
def resolve_api_token(api_token: Optional[str]) -> str:
if api_token is not None:
return api_token
elif UPGINI_API_KEY in os.environ and os.environ[UPGINI_API_KEY]:
return os.environ[UPGINI_API_KEY]
else:
return DEMO_API_KEY
def get_rest_client(
backend_url: Optional[str] = None,
api_token: Optional[str] = None,
client_ip: Optional[str] = None,
client_visitorid: Optional[str] = None,
) -> _RestClient:
url = _resolve_backend_url(backend_url)
token = resolve_api_token(api_token)
return _get_rest_client(url, token, client_ip, client_visitorid)
def is_demo_api_key(api_token: Optional[str]) -> bool:
return api_token is None or api_token == "" or api_token == DEMO_API_KEY
@lru_cache
def _get_rest_client(
backend_url: str, api_token: str, client_ip: Optional[str] = None, client_visitorid: Optional[str] = None
) -> _RestClient:
return _RestClient(backend_url, api_token, client_ip, client_visitorid)
class BackendLogHandler(logging.Handle
6458
r):
def __init__(
self,
rest_client: _RestClient,
client_ip: Optional[str] = None,
client_visitorid: Optional[str] = None,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.rest_client = rest_client
self.track_metrics = None
self.hostname = "0.0.0.0"
self.client_ip = client_ip
self.client_visitorid = client_visitorid
def emit(self, record: logging.LogRecord) -> None:
def task():
try:
if self.track_metrics is None or len(self.track_metrics) == 0:
self.track_metrics = get_track_metrics(self.client_ip, self.client_visitorid)
self.hostname = self.track_metrics.get("ip") or "0.0.0.0"
text = self.format(record)
tags = self.track_metrics
tags["version"] = __version__
log_event = LogEvent(
source="python",
tags=",".join([f"{k}:{v}" for k, v in tags.items()]),
hostname=self.hostname,
message=text,
service="PyLib",
)
self.rest_client.send_log_event(log_event)
except Exception:
pass
thread = threading.Thread(target=task)
thread.start()
class LoggerFactory:
_instance = None
_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not cls._instance:
with cls._lock:
# another thread could have created the instance
# before we acquired the lock. So check that the
# instance is still nonexistent.
if not cls._instance:
cls._instance = super(LoggerFactory, cls).__new__(cls)
return cls._instance