11import json
2+ from pathlib import Path
23from typing import Iterable
34
5+ import ndjson
6+
47from labelbox import Client
8+ from labelbox .exceptions import LabelboxError
59from labelbox .orm import query
610from labelbox .orm .db_object import DbObject
711from labelbox .orm .model import Field
812from labelbox .orm .model import Relationship
913from labelbox .schema .enums import BulkImportRequestState
14+ from labelbox .schema .enums import UploadedFileType
1015
1116
1217class BulkImportRequest (DbObject ):
@@ -25,7 +30,8 @@ def create(
2530 predictions : Iterable [dict ]) -> 'BulkImportRequest' :
2631 data_str = '\n ' .join (json .dumps (prediction ) for prediction in predictions )
2732 data = data_str .encode ('utf-8' )
28- input_file_url = client .upload_data (data )
33+ input_file_url = client .upload_data (
34+ data , uploaded_file_type = UploadedFileType .PREDICTIONS )
2935 query_str = """
3036 mutation CreateBulkImportRequestPyApi {
3137 createBulkImportRequest(data: {
@@ -44,3 +50,27 @@ def create(
4450 )
4551 bulk_import_request_kwargs = client .execute (query_str )["createBulkImportRequest" ]
4652 return BulkImportRequest (client , bulk_import_request_kwargs )
53+
54+ @staticmethod
55+ def upload_local_predictions_file (
56+ client : Client , local_predictions_file_path : Path ) -> str :
57+ """
58+ Uploads local NDJSON file containing predictions to Labelbox' object store
59+ and returns a URL of created file.
60+
61+ Args:
62+ client (Client): The Labelbox client
63+ local_predictions_file_path (str): local NDJSON file containing predictions
64+ Returns:
65+ A URL of uploaded NDJSON file
66+ Raises:
67+ LabelboxError: if local file is not a valid NDJSON file
68+ """
69+ with local_predictions_file_path .open ("rb" ) as f :
70+ try :
71+ data = ndjson .load (f )
72+ return client .upload_data (
73+ data , uploaded_file_type = UploadedFileType .PREDICTIONS )
74+ except ValueError :
75+ raise LabelboxError (
76+ f"File { local_predictions_file_path } is not a valid ndjson file" )
0 commit comments