1515import requests
1616import requests .exceptions
1717from google .api_core import retry
18+ from lbox .exceptions import (
19+ InternalServerError ,
20+ LabelboxError ,
21+ ResourceNotFoundError ,
22+ TimeoutError ,
23+ )
1824from lbox .request_client import RequestClient
1925
2026from labelbox import __version__ as SDK_VERSION
@@ -112,7 +118,7 @@ def __init__(
112118 enable_experimental (bool): Indicates whether or not to use experimental features
113119 app_url (str) : host url for all links to the web app
114120 Raises:
115- lbox.exceptions. AuthenticationError: If no `api_key`
121+ AuthenticationError: If no `api_key`
116122 is provided as an argument or via the environment
117123 variable.
118124 """
@@ -200,7 +206,7 @@ def upload_file(self, path: str) -> str:
200206 Returns:
201207 str, the URL of uploaded data.
202208 Raises:
203- lbox.exceptions. LabelboxError: If upload failed.
209+ LabelboxError: If upload failed.
204210 """
205211 content_type , _ = mimetypes .guess_type (path )
206212 filename = os .path .basename (path )
@@ -209,9 +215,7 @@ def upload_file(self, path: str) -> str:
209215 content = f .read (), filename = filename , content_type = content_type
210216 )
211217
212- @retry .Retry (
213- predicate = retry .if_exception_type (lbox .exceptions .InternalServerError )
214- )
218+ @retry .Retry (predicate = retry .if_exception_type (InternalServerError ))
215219 def upload_data (
216220 self ,
217221 content : bytes ,
@@ -231,7 +235,7 @@ def upload_data(
231235 str, the URL of uploaded data.
232236
233237 Raises:
234- lbox.exceptions. LabelboxError: If upload failed.
238+ LabelboxError: If upload failed.
235239 """
236240
237241 request_data = {
@@ -272,18 +276,16 @@ def upload_data(
272276
273277 if response .status_code == 502 :
274278 error_502 = "502 Bad Gateway"
275- raise lbox . exceptions . InternalServerError (error_502 )
279+ raise InternalServerError (error_502 )
276280 elif response .status_code == 503 :
277- raise lbox . exceptions . InternalServerError (response .text )
281+ raise InternalServerError (response .text )
278282 elif response .status_code == 520 :
279- raise lbox . exceptions . InternalServerError (response .text )
283+ raise InternalServerError (response .text )
280284
281285 try :
282286 file_data = response .json ().get ("data" , None )
283287 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 )
287289
288290 if not file_data or not file_data .get ("uploadFile" , None ):
289291 try :
@@ -293,9 +295,7 @@ def upload_data(
293295 )
294296 except Exception :
295297 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 )
299299
300300 return file_data ["uploadFile" ]["url" ]
301301
@@ -308,15 +308,15 @@ def _get_single(self, db_object_type, uid):
308308 Returns:
309309 Object of `db_object_type`.
310310 Raises:
311- lbox.exceptions. ResourceNotFoundError: If there is no object
311+ ResourceNotFoundError: If there is no object
312312 of the given type for the given ID.
313313 """
314314 query_str , params = query .get_single (db_object_type , uid )
315315
316316 res = self .execute (query_str , params )
317317 res = res and res .get (utils .camel_case (db_object_type .type_name ()))
318318 if res is None :
319- raise lbox . exceptions . ResourceNotFoundError (db_object_type , params )
319+ raise ResourceNotFoundError (db_object_type , params )
320320 else :
321321 return db_object_type (self , res )
322322
@@ -330,7 +330,7 @@ def get_project(self, project_id) -> Project:
330330 Returns:
331331 The sought Project.
332332 Raises:
333- lbox.exceptions. ResourceNotFoundError: If there is no
333+ ResourceNotFoundError: If there is no
334334 Project with the given ID.
335335 """
336336 return self ._get_single (Entity .Project , project_id )
@@ -345,7 +345,7 @@ def get_dataset(self, dataset_id) -> Dataset:
345345 Returns:
346346 The sought Dataset.
347347 Raises:
348- lbox.exceptions. ResourceNotFoundError: If there is no
348+ ResourceNotFoundError: If there is no
349349 Dataset with the given ID.
350350 """
351351 return self ._get_single (Entity .Dataset , dataset_id )
@@ -471,7 +471,7 @@ def _create(self, db_object_type, data, extra_params={}):
471471 )
472472
473473 if not res :
474- raise lbox . exceptions . LabelboxError (
474+ raise LabelboxError (
475475 "Failed to create %s" % db_object_type .type_name ()
476476 )
477477 res = res ["create%s" % db_object_type .type_name ()]
@@ -529,9 +529,7 @@ def delete_model_config(self, id: str) -> bool:
529529 params = {"id" : id }
530530 result = self .execute (query , params )
531531 if not result :
532- raise lbox .exceptions .ResourceNotFoundError (
533- Entity .ModelConfig , params
534- )
532+ raise ResourceNotFoundError (Entity .ModelConfig , params )
535533 return result ["deleteModelConfig" ]["success" ]
536534
537535 def create_dataset (
@@ -590,7 +588,7 @@ def create_dataset(
590588 )
591589
592590 if not validation_result ["validateDataset" ]["valid" ]:
593- raise lbox . exceptions . LabelboxError (
591+ raise LabelboxError (
594592 "IAMIntegration was not successfully added to the dataset."
595593 )
596594 except Exception as e :
@@ -902,7 +900,7 @@ def get_data_row_by_global_key(self, global_key: str) -> DataRow:
902900 """
903901 res = self .get_data_row_ids_for_global_keys ([global_key ])
904902 if res ["status" ] != "SUCCESS" :
905- raise lbox . exceptions . ResourceNotFoundError (
903+ raise ResourceNotFoundError (
906904 Entity .DataRow , {global_key : global_key }
907905 )
908906 data_row_id = res ["results" ][0 ]
@@ -930,7 +928,7 @@ def get_model(self, model_id) -> Model:
930928 Returns:
931929 The sought Model.
932930 Raises:
933- lbox.exceptions. ResourceNotFoundError: If there is no
931+ ResourceNotFoundError: If there is no
934932 Model with the given ID.
935933 """
936934 return self ._get_single (Entity .Model , model_id )
@@ -1176,7 +1174,7 @@ def delete_unused_feature_schema(self, feature_schema_id: str) -> None:
11761174 response = self .connection .delete (endpoint )
11771175
11781176 if response .status_code != requests .codes .no_content :
1179- raise lbox . exceptions . LabelboxError (
1177+ raise LabelboxError (
11801178 "Failed to delete the feature schema, message: "
11811179 + str (response .json ()["message" ])
11821180 )
@@ -1197,7 +1195,7 @@ def delete_unused_ontology(self, ontology_id: str) -> None:
11971195 response = self .connection .delete (endpoint )
11981196
11991197 if response .status_code != requests .codes .no_content :
1200- raise lbox . exceptions . LabelboxError (
1198+ raise LabelboxError (
12011199 "Failed to delete the ontology, message: "
12021200 + str (response .json ()["message" ])
12031201 )
@@ -1227,7 +1225,7 @@ def update_feature_schema_title(
12271225 if response .status_code == requests .codes .ok :
12281226 return self .get_feature_schema (feature_schema_id )
12291227 else :
1230- raise lbox . exceptions . LabelboxError (
1228+ raise LabelboxError (
12311229 "Failed to update the feature schema, message: "
12321230 + str (response .json ()["message" ])
12331231 )
@@ -1263,7 +1261,7 @@ def upsert_feature_schema(self, feature_schema: Dict) -> FeatureSchema:
12631261 if response .status_code == requests .codes .ok :
12641262 return self .get_feature_schema (response .json ()["schemaId" ])
12651263 else :
1266- raise lbox . exceptions . LabelboxError (
1264+ raise LabelboxError (
12671265 "Failed to upsert the feature schema, message: "
12681266 + str (response .json ()["message" ])
12691267 )
@@ -1291,7 +1289,7 @@ def insert_feature_schema_into_ontology(
12911289 )
12921290 response = self .connection .post (endpoint , json = {"position" : position })
12931291 if response .status_code != requests .codes .created :
1294- raise lbox . exceptions . LabelboxError (
1292+ raise LabelboxError (
12951293 "Failed to insert the feature schema into the ontology, message: "
12961294 + str (response .json ()["message" ])
12971295 )
@@ -1316,7 +1314,7 @@ def get_unused_ontologies(self, after: str = None) -> List[str]:
13161314 if response .status_code == requests .codes .ok :
13171315 return response .json ()
13181316 else :
1319- raise lbox . exceptions . LabelboxError (
1317+ raise LabelboxError (
13201318 "Failed to get unused ontologies, message: "
13211319 + str (response .json ()["message" ])
13221320 )
@@ -1341,7 +1339,7 @@ def get_unused_feature_schemas(self, after: str = None) -> List[str]:
13411339 if response .status_code == requests .codes .ok :
13421340 return response .json ()
13431341 else :
1344- raise lbox . exceptions . LabelboxError (
1342+ raise LabelboxError (
13451343 "Failed to get unused feature schemas, message: "
13461344 + str (response .json ()["message" ])
13471345 )
@@ -1637,12 +1635,12 @@ def _format_failed_rows(
16371635 elif (
16381636 res ["assignGlobalKeysToDataRowsResult" ]["jobStatus" ] == "FAILED"
16391637 ):
1640- raise lbox . exceptions . LabelboxError (
1638+ raise LabelboxError (
16411639 "Job assign_global_keys_to_data_rows failed."
16421640 )
16431641 current_time = time .time ()
16441642 if current_time - start_time > timeout_seconds :
1645- raise lbox . exceptions . TimeoutError (
1643+ raise TimeoutError (
16461644 "Timed out waiting for assign_global_keys_to_data_rows job to complete."
16471645 )
16481646 time .sleep (sleep_time )
@@ -1746,12 +1744,10 @@ def _format_failed_rows(
17461744
17471745 return {"status" : status , "results" : results , "errors" : errors }
17481746 elif res ["dataRowsForGlobalKeysResult" ]["jobStatus" ] == "FAILED" :
1749- raise lbox .exceptions .LabelboxError (
1750- "Job dataRowsForGlobalKeys failed."
1751- )
1747+ raise LabelboxError ("Job dataRowsForGlobalKeys failed." )
17521748 current_time = time .time ()
17531749 if current_time - start_time > timeout_seconds :
1754- raise lbox . exceptions . TimeoutError (
1750+ raise TimeoutError (
17551751 "Timed out waiting for get_data_rows_for_global_keys job to complete."
17561752 )
17571753 time .sleep (sleep_time )
@@ -1850,12 +1846,10 @@ def _format_failed_rows(
18501846
18511847 return {"status" : status , "results" : results , "errors" : errors }
18521848 elif res ["clearGlobalKeysResult" ]["jobStatus" ] == "FAILED" :
1853- raise lbox .exceptions .LabelboxError (
1854- "Job clearGlobalKeys failed."
1855- )
1849+ raise LabelboxError ("Job clearGlobalKeys failed." )
18561850 current_time = time .time ()
18571851 if current_time - start_time > timeout_seconds :
1858- raise lbox . exceptions . TimeoutError (
1852+ raise TimeoutError (
18591853 "Timed out waiting for clear_global_keys job to complete."
18601854 )
18611855 time .sleep (sleep_time )
@@ -1920,14 +1914,14 @@ def is_feature_schema_archived(
19201914 if filtered_feature_schema_nodes :
19211915 return bool (filtered_feature_schema_nodes [0 ]["archived" ])
19221916 else :
1923- raise lbox . exceptions . LabelboxError (
1917+ raise LabelboxError (
19241918 "The specified feature schema was not in the ontology."
19251919 )
19261920
19271921 elif response .status_code == 404 :
1928- raise lbox . exceptions . ResourceNotFoundError (Ontology , ontology_id )
1922+ raise ResourceNotFoundError (Ontology , ontology_id )
19291923 else :
1930- raise lbox . exceptions . LabelboxError (
1924+ raise LabelboxError (
19311925 "Failed to get the feature schema archived status."
19321926 )
19331927
@@ -1954,7 +1948,7 @@ def get_model_slice(self, slice_id) -> ModelSlice:
19541948 """
19551949 res = self .execute (query_str , {"id" : slice_id })
19561950 if res is None or res ["getSavedQuery" ] is None :
1957- raise lbox . exceptions . ResourceNotFoundError (ModelSlice , slice_id )
1951+ raise ResourceNotFoundError (ModelSlice , slice_id )
19581952
19591953 return Entity .ModelSlice (self , res ["getSavedQuery" ])
19601954
@@ -2001,7 +1995,7 @@ def delete_feature_schema_from_ontology(
20011995 result .deleted = bool (response_json ["deleted" ])
20021996 return result
20031997 else :
2004- raise lbox . exceptions . LabelboxError (
1998+ raise LabelboxError (
20051999 "Failed to remove feature schema from ontology, message: "
20062000 + str (response .json ()["message" ])
20072001 )
@@ -2029,11 +2023,9 @@ def unarchive_feature_schema_node(
20292023 response = self .connection .patch (ontology_endpoint )
20302024 if response .status_code == requests .codes .ok :
20312025 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." )
20352027 else :
2036- raise lbox . exceptions . LabelboxError (
2028+ raise LabelboxError (
20372029 "Failed unarchive the feature schema node, message: " ,
20382030 response .text ,
20392031 )
@@ -2262,7 +2254,7 @@ def get_embedding_by_name(self, name: str) -> Embedding:
22622254 for e in embeddings :
22632255 if e .name == name :
22642256 return e
2265- raise lbox . exceptions . ResourceNotFoundError (Embedding , dict (name = name ))
2257+ raise ResourceNotFoundError (Embedding , dict (name = name ))
22662258
22672259 def upsert_label_feedback (
22682260 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]:
23852377 result = self .execute (query , {"userId" : user .uid , "taskId" : task_id })
23862378 data = result .get ("user" , {}).get ("createdTasks" , [])
23872379 if not data :
2388- raise lbox . exceptions . ResourceNotFoundError (
2380+ raise ResourceNotFoundError (
23892381 message = f"The task { task_id } does not exist."
23902382 )
23912383 task_data = data [0 ]
0 commit comments