15
15
import requests
16
16
import requests .exceptions
17
17
from google .api_core import retry
18
+ from lbox .exceptions import (
19
+ InternalServerError ,
20
+ LabelboxError ,
21
+ ResourceNotFoundError ,
22
+ TimeoutError ,
23
+ )
18
24
from lbox .request_client import RequestClient
19
25
20
26
from labelbox import __version__ as SDK_VERSION
@@ -112,7 +118,7 @@ def __init__(
112
118
enable_experimental (bool): Indicates whether or not to use experimental features
113
119
app_url (str) : host url for all links to the web app
114
120
Raises:
115
- lbox.exceptions. AuthenticationError: If no `api_key`
121
+ AuthenticationError: If no `api_key`
116
122
is provided as an argument or via the environment
117
123
variable.
118
124
"""
@@ -200,7 +206,7 @@ def upload_file(self, path: str) -> str:
200
206
Returns:
201
207
str, the URL of uploaded data.
202
208
Raises:
203
- lbox.exceptions. LabelboxError: If upload failed.
209
+ LabelboxError: If upload failed.
204
210
"""
205
211
content_type , _ = mimetypes .guess_type (path )
206
212
filename = os .path .basename (path )
@@ -209,9 +215,7 @@ def upload_file(self, path: str) -> str:
209
215
content = f .read (), filename = filename , content_type = content_type
210
216
)
211
217
212
- @retry .Retry (
213
- predicate = retry .if_exception_type (lbox .exceptions .InternalServerError )
214
- )
218
+ @retry .Retry (predicate = retry .if_exception_type (InternalServerError ))
215
219
def upload_data (
216
220
self ,
217
221
content : bytes ,
@@ -231,7 +235,7 @@ def upload_data(
231
235
str, the URL of uploaded data.
232
236
233
237
Raises:
234
- lbox.exceptions. LabelboxError: If upload failed.
238
+ LabelboxError: If upload failed.
235
239
"""
236
240
237
241
request_data = {
@@ -272,18 +276,16 @@ def upload_data(
272
276
273
277
if response .status_code == 502 :
274
278
error_502 = "502 Bad Gateway"
275
- raise lbox . exceptions . InternalServerError (error_502 )
279
+ raise InternalServerError (error_502 )
276
280
elif response .status_code == 503 :
277
- raise lbox . exceptions . InternalServerError (response .text )
281
+ raise InternalServerError (response .text )
278
282
elif response .status_code == 520 :
279
- raise lbox . exceptions . InternalServerError (response .text )
283
+ raise InternalServerError (response .text )
280
284
281
285
try :
282
286
file_data = response .json ().get ("data" , None )
283
287
except ValueError as e : # response is not valid JSON
284
- raise lbox .exceptions .LabelboxError (
285
- "Failed to upload, unknown cause" , e
286
- )
288
+ raise LabelboxError ("Failed to upload, unknown cause" , e )
287
289
288
290
if not file_data or not file_data .get ("uploadFile" , None ):
289
291
try :
@@ -293,9 +295,7 @@ def upload_data(
293
295
)
294
296
except Exception :
295
297
error_msg = "Unknown error"
296
- raise lbox .exceptions .LabelboxError (
297
- "Failed to upload, message: %s" % error_msg
298
- )
298
+ raise LabelboxError ("Failed to upload, message: %s" % error_msg )
299
299
300
300
return file_data ["uploadFile" ]["url" ]
301
301
@@ -308,15 +308,15 @@ def _get_single(self, db_object_type, uid):
308
308
Returns:
309
309
Object of `db_object_type`.
310
310
Raises:
311
- lbox.exceptions. ResourceNotFoundError: If there is no object
311
+ ResourceNotFoundError: If there is no object
312
312
of the given type for the given ID.
313
313
"""
314
314
query_str , params = query .get_single (db_object_type , uid )
315
315
316
316
res = self .execute (query_str , params )
317
317
res = res and res .get (utils .camel_case (db_object_type .type_name ()))
318
318
if res is None :
319
- raise lbox . exceptions . ResourceNotFoundError (db_object_type , params )
319
+ raise ResourceNotFoundError (db_object_type , params )
320
320
else :
321
321
return db_object_type (self , res )
322
322
@@ -330,7 +330,7 @@ def get_project(self, project_id) -> Project:
330
330
Returns:
331
331
The sought Project.
332
332
Raises:
333
- lbox.exceptions. ResourceNotFoundError: If there is no
333
+ ResourceNotFoundError: If there is no
334
334
Project with the given ID.
335
335
"""
336
336
return self ._get_single (Entity .Project , project_id )
@@ -345,7 +345,7 @@ def get_dataset(self, dataset_id) -> Dataset:
345
345
Returns:
346
346
The sought Dataset.
347
347
Raises:
348
- lbox.exceptions. ResourceNotFoundError: If there is no
348
+ ResourceNotFoundError: If there is no
349
349
Dataset with the given ID.
350
350
"""
351
351
return self ._get_single (Entity .Dataset , dataset_id )
@@ -471,7 +471,7 @@ def _create(self, db_object_type, data, extra_params={}):
471
471
)
472
472
473
473
if not res :
474
- raise lbox . exceptions . LabelboxError (
474
+ raise LabelboxError (
475
475
"Failed to create %s" % db_object_type .type_name ()
476
476
)
477
477
res = res ["create%s" % db_object_type .type_name ()]
@@ -529,9 +529,7 @@ def delete_model_config(self, id: str) -> bool:
529
529
params = {"id" : id }
530
530
result = self .execute (query , params )
531
531
if not result :
532
- raise lbox .exceptions .ResourceNotFoundError (
533
- Entity .ModelConfig , params
534
- )
532
+ raise ResourceNotFoundError (Entity .ModelConfig , params )
535
533
return result ["deleteModelConfig" ]["success" ]
536
534
537
535
def create_dataset (
@@ -590,7 +588,7 @@ def create_dataset(
590
588
)
591
589
592
590
if not validation_result ["validateDataset" ]["valid" ]:
593
- raise lbox . exceptions . LabelboxError (
591
+ raise LabelboxError (
594
592
"IAMIntegration was not successfully added to the dataset."
595
593
)
596
594
except Exception as e :
@@ -902,7 +900,7 @@ def get_data_row_by_global_key(self, global_key: str) -> DataRow:
902
900
"""
903
901
res = self .get_data_row_ids_for_global_keys ([global_key ])
904
902
if res ["status" ] != "SUCCESS" :
905
- raise lbox . exceptions . ResourceNotFoundError (
903
+ raise ResourceNotFoundError (
906
904
Entity .DataRow , {global_key : global_key }
907
905
)
908
906
data_row_id = res ["results" ][0 ]
@@ -930,7 +928,7 @@ def get_model(self, model_id) -> Model:
930
928
Returns:
931
929
The sought Model.
932
930
Raises:
933
- lbox.exceptions. ResourceNotFoundError: If there is no
931
+ ResourceNotFoundError: If there is no
934
932
Model with the given ID.
935
933
"""
936
934
return self ._get_single (Entity .Model , model_id )
@@ -1176,7 +1174,7 @@ def delete_unused_feature_schema(self, feature_schema_id: str) -> None:
1176
1174
response = self .connection .delete (endpoint )
1177
1175
1178
1176
if response .status_code != requests .codes .no_content :
1179
- raise lbox . exceptions . LabelboxError (
1177
+ raise LabelboxError (
1180
1178
"Failed to delete the feature schema, message: "
1181
1179
+ str (response .json ()["message" ])
1182
1180
)
@@ -1197,7 +1195,7 @@ def delete_unused_ontology(self, ontology_id: str) -> None:
1197
1195
response = self .connection .delete (endpoint )
1198
1196
1199
1197
if response .status_code != requests .codes .no_content :
1200
- raise lbox . exceptions . LabelboxError (
1198
+ raise LabelboxError (
1201
1199
"Failed to delete the ontology, message: "
1202
1200
+ str (response .json ()["message" ])
1203
1201
)
@@ -1227,7 +1225,7 @@ def update_feature_schema_title(
1227
1225
if response .status_code == requests .codes .ok :
1228
1226
return self .get_feature_schema (feature_schema_id )
1229
1227
else :
1230
- raise lbox . exceptions . LabelboxError (
1228
+ raise LabelboxError (
1231
1229
"Failed to update the feature schema, message: "
1232
1230
+ str (response .json ()["message" ])
1233
1231
)
@@ -1263,7 +1261,7 @@ def upsert_feature_schema(self, feature_schema: Dict) -> FeatureSchema:
1263
1261
if response .status_code == requests .codes .ok :
1264
1262
return self .get_feature_schema (response .json ()["schemaId" ])
1265
1263
else :
1266
- raise lbox . exceptions . LabelboxError (
1264
+ raise LabelboxError (
1267
1265
"Failed to upsert the feature schema, message: "
1268
1266
+ str (response .json ()["message" ])
1269
1267
)
@@ -1291,7 +1289,7 @@ def insert_feature_schema_into_ontology(
1291
1289
)
1292
1290
response = self .connection .post (endpoint , json = {"position" : position })
1293
1291
if response .status_code != requests .codes .created :
1294
- raise lbox . exceptions . LabelboxError (
1292
+ raise LabelboxError (
1295
1293
"Failed to insert the feature schema into the ontology, message: "
1296
1294
+ str (response .json ()["message" ])
1297
1295
)
@@ -1316,7 +1314,7 @@ def get_unused_ontologies(self, after: str = None) -> List[str]:
1316
1314
if response .status_code == requests .codes .ok :
1317
1315
return response .json ()
1318
1316
else :
1319
- raise lbox . exceptions . LabelboxError (
1317
+ raise LabelboxError (
1320
1318
"Failed to get unused ontologies, message: "
1321
1319
+ str (response .json ()["message" ])
1322
1320
)
@@ -1341,7 +1339,7 @@ def get_unused_feature_schemas(self, after: str = None) -> List[str]:
1341
1339
if response .status_code == requests .codes .ok :
1342
1340
return response .json ()
1343
1341
else :
1344
- raise lbox . exceptions . LabelboxError (
1342
+ raise LabelboxError (
1345
1343
"Failed to get unused feature schemas, message: "
1346
1344
+ str (response .json ()["message" ])
1347
1345
)
@@ -1637,12 +1635,12 @@ def _format_failed_rows(
1637
1635
elif (
1638
1636
res ["assignGlobalKeysToDataRowsResult" ]["jobStatus" ] == "FAILED"
1639
1637
):
1640
- raise lbox . exceptions . LabelboxError (
1638
+ raise LabelboxError (
1641
1639
"Job assign_global_keys_to_data_rows failed."
1642
1640
)
1643
1641
current_time = time .time ()
1644
1642
if current_time - start_time > timeout_seconds :
1645
- raise lbox . exceptions . TimeoutError (
1643
+ raise TimeoutError (
1646
1644
"Timed out waiting for assign_global_keys_to_data_rows job to complete."
1647
1645
)
1648
1646
time .sleep (sleep_time )
@@ -1746,12 +1744,10 @@ def _format_failed_rows(
1746
1744
1747
1745
return {"status" : status , "results" : results , "errors" : errors }
1748
1746
elif res ["dataRowsForGlobalKeysResult" ]["jobStatus" ] == "FAILED" :
1749
- raise lbox .exceptions .LabelboxError (
1750
- "Job dataRowsForGlobalKeys failed."
1751
- )
1747
+ raise LabelboxError ("Job dataRowsForGlobalKeys failed." )
1752
1748
current_time = time .time ()
1753
1749
if current_time - start_time > timeout_seconds :
1754
- raise lbox . exceptions . TimeoutError (
1750
+ raise TimeoutError (
1755
1751
"Timed out waiting for get_data_rows_for_global_keys job to complete."
1756
1752
)
1757
1753
time .sleep (sleep_time )
@@ -1850,12 +1846,10 @@ def _format_failed_rows(
1850
1846
1851
1847
return {"status" : status , "results" : results , "errors" : errors }
1852
1848
elif res ["clearGlobalKeysResult" ]["jobStatus" ] == "FAILED" :
1853
- raise lbox .exceptions .LabelboxError (
1854
- "Job clearGlobalKeys failed."
1855
- )
1849
+ raise LabelboxError ("Job clearGlobalKeys failed." )
1856
1850
current_time = time .time ()
1857
1851
if current_time - start_time > timeout_seconds :
1858
- raise lbox . exceptions . TimeoutError (
1852
+ raise TimeoutError (
1859
1853
"Timed out waiting for clear_global_keys job to complete."
1860
1854
)
1861
1855
time .sleep (sleep_time )
@@ -1920,14 +1914,14 @@ def is_feature_schema_archived(
1920
1914
if filtered_feature_schema_nodes :
1921
1915
return bool (filtered_feature_schema_nodes [0 ]["archived" ])
1922
1916
else :
1923
- raise lbox . exceptions . LabelboxError (
1917
+ raise LabelboxError (
1924
1918
"The specified feature schema was not in the ontology."
1925
1919
)
1926
1920
1927
1921
elif response .status_code == 404 :
1928
- raise lbox . exceptions . ResourceNotFoundError (Ontology , ontology_id )
1922
+ raise ResourceNotFoundError (Ontology , ontology_id )
1929
1923
else :
1930
- raise lbox . exceptions . LabelboxError (
1924
+ raise LabelboxError (
1931
1925
"Failed to get the feature schema archived status."
1932
1926
)
1933
1927
@@ -1954,7 +1948,7 @@ def get_model_slice(self, slice_id) -> ModelSlice:
1954
1948
"""
1955
1949
res = self .execute (query_str , {"id" : slice_id })
1956
1950
if res is None or res ["getSavedQuery" ] is None :
1957
- raise lbox . exceptions . ResourceNotFoundError (ModelSlice , slice_id )
1951
+ raise ResourceNotFoundError (ModelSlice , slice_id )
1958
1952
1959
1953
return Entity .ModelSlice (self , res ["getSavedQuery" ])
1960
1954
@@ -2001,7 +1995,7 @@ def delete_feature_schema_from_ontology(
2001
1995
result .deleted = bool (response_json ["deleted" ])
2002
1996
return result
2003
1997
else :
2004
- raise lbox . exceptions . LabelboxError (
1998
+ raise LabelboxError (
2005
1999
"Failed to remove feature schema from ontology, message: "
2006
2000
+ str (response .json ()["message" ])
2007
2001
)
@@ -2029,11 +2023,9 @@ def unarchive_feature_schema_node(
2029
2023
response = self .connection .patch (ontology_endpoint )
2030
2024
if response .status_code == requests .codes .ok :
2031
2025
if not bool (response .json ()["unarchived" ]):
2032
- raise lbox .exceptions .LabelboxError (
2033
- "Failed unarchive the feature schema."
2034
- )
2026
+ raise LabelboxError ("Failed unarchive the feature schema." )
2035
2027
else :
2036
- raise lbox . exceptions . LabelboxError (
2028
+ raise LabelboxError (
2037
2029
"Failed unarchive the feature schema node, message: " ,
2038
2030
response .text ,
2039
2031
)
@@ -2262,7 +2254,7 @@ def get_embedding_by_name(self, name: str) -> Embedding:
2262
2254
for e in embeddings :
2263
2255
if e .name == name :
2264
2256
return e
2265
- raise lbox . exceptions . ResourceNotFoundError (Embedding , dict (name = name ))
2257
+ raise ResourceNotFoundError (Embedding , dict (name = name ))
2266
2258
2267
2259
def upsert_label_feedback (
2268
2260
self , label_id : str , feedback : str , scores : Dict [str , float ]
@@ -2385,7 +2377,7 @@ def get_task_by_id(self, task_id: str) -> Union[Task, DataUpsertTask]:
2385
2377
result = self .execute (query , {"userId" : user .uid , "taskId" : task_id })
2386
2378
data = result .get ("user" , {}).get ("createdTasks" , [])
2387
2379
if not data :
2388
- raise lbox . exceptions . ResourceNotFoundError (
2380
+ raise ResourceNotFoundError (
2389
2381
message = f"The task { task_id } does not exist."
2390
2382
)
2391
2383
task_data = data [0 ]
0 commit comments