label-studio-sdk 0.0.32__py3-none-any.whl → 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. label_studio_sdk/__init__.py +206 -6
  2. label_studio_sdk/_extensions/label_studio_tools/__init__.py +0 -0
  3. label_studio_sdk/_extensions/label_studio_tools/core/__init__.py +0 -0
  4. label_studio_sdk/_extensions/label_studio_tools/core/label_config.py +163 -0
  5. label_studio_sdk/_extensions/label_studio_tools/core/utils/__init__.py +0 -0
  6. label_studio_sdk/_extensions/label_studio_tools/core/utils/exceptions.py +2 -0
  7. label_studio_sdk/_extensions/label_studio_tools/core/utils/io.py +228 -0
  8. label_studio_sdk/_extensions/label_studio_tools/core/utils/params.py +45 -0
  9. label_studio_sdk/_extensions/label_studio_tools/etl/__init__.py +1 -0
  10. label_studio_sdk/_extensions/label_studio_tools/etl/beam.py +34 -0
  11. label_studio_sdk/_extensions/label_studio_tools/etl/example.py +17 -0
  12. label_studio_sdk/_extensions/label_studio_tools/etl/registry.py +67 -0
  13. label_studio_sdk/_extensions/label_studio_tools/postprocessing/__init__.py +0 -0
  14. label_studio_sdk/_extensions/label_studio_tools/postprocessing/video.py +97 -0
  15. label_studio_sdk/_legacy/__init__.py +11 -0
  16. label_studio_sdk/_legacy/client.py +471 -0
  17. label_studio_sdk/_legacy/exceptions.py +10 -0
  18. label_studio_sdk/_legacy/label_interface/__init__.py +1 -0
  19. label_studio_sdk/_legacy/label_interface/base.py +77 -0
  20. label_studio_sdk/_legacy/label_interface/control_tags.py +756 -0
  21. label_studio_sdk/_legacy/label_interface/data_examples.json +96 -0
  22. label_studio_sdk/_legacy/label_interface/interface.py +925 -0
  23. label_studio_sdk/_legacy/label_interface/label_tags.py +72 -0
  24. label_studio_sdk/_legacy/label_interface/object_tags.py +292 -0
  25. label_studio_sdk/_legacy/label_interface/region.py +43 -0
  26. label_studio_sdk/_legacy/objects.py +35 -0
  27. label_studio_sdk/{project.py → _legacy/project.py} +711 -258
  28. label_studio_sdk/_legacy/schema/label_config_schema.json +226 -0
  29. label_studio_sdk/{users.py → _legacy/users.py} +15 -13
  30. label_studio_sdk/{utils.py → _legacy/utils.py} +31 -30
  31. label_studio_sdk/{workspaces.py → _legacy/workspaces.py} +13 -11
  32. label_studio_sdk/actions/__init__.py +2 -0
  33. label_studio_sdk/actions/client.py +150 -0
  34. label_studio_sdk/annotations/__init__.py +2 -0
  35. label_studio_sdk/annotations/client.py +750 -0
  36. label_studio_sdk/client.py +164 -436
  37. label_studio_sdk/converter/__init__.py +7 -0
  38. label_studio_sdk/converter/audio.py +56 -0
  39. label_studio_sdk/converter/brush.py +452 -0
  40. label_studio_sdk/converter/converter.py +1175 -0
  41. label_studio_sdk/converter/exports/__init__.py +0 -0
  42. label_studio_sdk/converter/exports/csv.py +82 -0
  43. label_studio_sdk/converter/exports/csv2.py +103 -0
  44. label_studio_sdk/converter/funsd.py +85 -0
  45. label_studio_sdk/converter/imports/__init__.py +0 -0
  46. label_studio_sdk/converter/imports/coco.py +314 -0
  47. label_studio_sdk/converter/imports/colors.py +198 -0
  48. label_studio_sdk/converter/imports/label_config.py +45 -0
  49. label_studio_sdk/converter/imports/pathtrack.py +269 -0
  50. label_studio_sdk/converter/imports/yolo.py +236 -0
  51. label_studio_sdk/converter/main.py +202 -0
  52. label_studio_sdk/converter/utils.py +473 -0
  53. label_studio_sdk/core/__init__.py +33 -0
  54. label_studio_sdk/core/api_error.py +15 -0
  55. label_studio_sdk/core/client_wrapper.py +55 -0
  56. label_studio_sdk/core/datetime_utils.py +28 -0
  57. label_studio_sdk/core/file.py +38 -0
  58. label_studio_sdk/core/http_client.py +443 -0
  59. label_studio_sdk/core/jsonable_encoder.py +99 -0
  60. label_studio_sdk/core/pagination.py +87 -0
  61. label_studio_sdk/core/pydantic_utilities.py +28 -0
  62. label_studio_sdk/core/query_encoder.py +33 -0
  63. label_studio_sdk/core/remove_none_from_dict.py +11 -0
  64. label_studio_sdk/core/request_options.py +32 -0
  65. label_studio_sdk/data_manager.py +32 -23
  66. label_studio_sdk/environment.py +7 -0
  67. label_studio_sdk/errors/__init__.py +6 -0
  68. label_studio_sdk/errors/bad_request_error.py +8 -0
  69. label_studio_sdk/errors/internal_server_error.py +8 -0
  70. label_studio_sdk/export_storage/__init__.py +28 -0
  71. label_studio_sdk/export_storage/azure/__init__.py +5 -0
  72. label_studio_sdk/export_storage/azure/client.py +722 -0
  73. label_studio_sdk/export_storage/azure/types/__init__.py +6 -0
  74. label_studio_sdk/export_storage/azure/types/azure_create_response.py +52 -0
  75. label_studio_sdk/export_storage/azure/types/azure_update_response.py +52 -0
  76. label_studio_sdk/export_storage/client.py +107 -0
  77. label_studio_sdk/export_storage/gcs/__init__.py +5 -0
  78. label_studio_sdk/export_storage/gcs/client.py +722 -0
  79. label_studio_sdk/export_storage/gcs/types/__init__.py +6 -0
  80. label_studio_sdk/export_storage/gcs/types/gcs_create_response.py +52 -0
  81. label_studio_sdk/export_storage/gcs/types/gcs_update_response.py +52 -0
  82. label_studio_sdk/export_storage/local/__init__.py +5 -0
  83. label_studio_sdk/export_storage/local/client.py +688 -0
  84. label_studio_sdk/export_storage/local/types/__init__.py +6 -0
  85. label_studio_sdk/export_storage/local/types/local_create_response.py +47 -0
  86. label_studio_sdk/export_storage/local/types/local_update_response.py +47 -0
  87. label_studio_sdk/export_storage/redis/__init__.py +5 -0
  88. label_studio_sdk/export_storage/redis/client.py +714 -0
  89. label_studio_sdk/export_storage/redis/types/__init__.py +6 -0
  90. label_studio_sdk/export_storage/redis/types/redis_create_response.py +57 -0
  91. label_studio_sdk/export_storage/redis/types/redis_update_response.py +57 -0
  92. label_studio_sdk/export_storage/s3/__init__.py +5 -0
  93. label_studio_sdk/export_storage/s3/client.py +820 -0
  94. label_studio_sdk/export_storage/s3/types/__init__.py +6 -0
  95. label_studio_sdk/export_storage/s3/types/s3create_response.py +74 -0
  96. label_studio_sdk/export_storage/s3/types/s3update_response.py +74 -0
  97. label_studio_sdk/export_storage/types/__init__.py +5 -0
  98. label_studio_sdk/export_storage/types/export_storage_list_types_response_item.py +30 -0
  99. label_studio_sdk/files/__init__.py +2 -0
  100. label_studio_sdk/files/client.py +556 -0
  101. label_studio_sdk/import_storage/__init__.py +28 -0
  102. label_studio_sdk/import_storage/azure/__init__.py +5 -0
  103. label_studio_sdk/import_storage/azure/client.py +812 -0
  104. label_studio_sdk/import_storage/azure/types/__init__.py +6 -0
  105. label_studio_sdk/import_storage/azure/types/azure_create_response.py +72 -0
  106. label_studio_sdk/import_storage/azure/types/azure_update_response.py +72 -0
  107. label_studio_sdk/import_storage/client.py +107 -0
  108. label_studio_sdk/import_storage/gcs/__init__.py +5 -0
  109. label_studio_sdk/import_storage/gcs/client.py +812 -0
  110. label_studio_sdk/import_storage/gcs/types/__init__.py +6 -0
  111. label_studio_sdk/import_storage/gcs/types/gcs_create_response.py +72 -0
  112. label_studio_sdk/import_storage/gcs/types/gcs_update_response.py +72 -0
  113. label_studio_sdk/import_storage/local/__init__.py +5 -0
  114. label_studio_sdk/import_storage/local/client.py +690 -0
  115. label_studio_sdk/import_storage/local/types/__init__.py +6 -0
  116. label_studio_sdk/import_storage/local/types/local_create_response.py +47 -0
  117. label_studio_sdk/import_storage/local/types/local_update_response.py +47 -0
  118. label_studio_sdk/import_storage/redis/__init__.py +5 -0
  119. label_studio_sdk/import_storage/redis/client.py +768 -0
  120. label_studio_sdk/import_storage/redis/types/__init__.py +6 -0
  121. label_studio_sdk/import_storage/redis/types/redis_create_response.py +62 -0
  122. label_studio_sdk/import_storage/redis/types/redis_update_response.py +62 -0
  123. label_studio_sdk/import_storage/s3/__init__.py +5 -0
  124. label_studio_sdk/import_storage/s3/client.py +912 -0
  125. label_studio_sdk/import_storage/s3/types/__init__.py +6 -0
  126. label_studio_sdk/import_storage/s3/types/s3create_response.py +99 -0
  127. label_studio_sdk/import_storage/s3/types/s3update_response.py +99 -0
  128. label_studio_sdk/import_storage/types/__init__.py +5 -0
  129. label_studio_sdk/import_storage/types/import_storage_list_types_response_item.py +30 -0
  130. label_studio_sdk/ml/__init__.py +19 -0
  131. label_studio_sdk/ml/client.py +981 -0
  132. label_studio_sdk/ml/types/__init__.py +17 -0
  133. label_studio_sdk/ml/types/ml_create_request_auth_method.py +5 -0
  134. label_studio_sdk/ml/types/ml_create_response.py +78 -0
  135. label_studio_sdk/ml/types/ml_create_response_auth_method.py +5 -0
  136. label_studio_sdk/ml/types/ml_update_request_auth_method.py +5 -0
  137. label_studio_sdk/ml/types/ml_update_response.py +78 -0
  138. label_studio_sdk/ml/types/ml_update_response_auth_method.py +5 -0
  139. label_studio_sdk/predictions/__init__.py +2 -0
  140. label_studio_sdk/predictions/client.py +638 -0
  141. label_studio_sdk/projects/__init__.py +6 -0
  142. label_studio_sdk/projects/client.py +1053 -0
  143. label_studio_sdk/projects/exports/__init__.py +2 -0
  144. label_studio_sdk/projects/exports/client.py +930 -0
  145. label_studio_sdk/projects/types/__init__.py +7 -0
  146. label_studio_sdk/projects/types/projects_create_response.py +96 -0
  147. label_studio_sdk/projects/types/projects_import_tasks_response.py +71 -0
  148. label_studio_sdk/projects/types/projects_list_response.py +33 -0
  149. label_studio_sdk/py.typed +0 -0
  150. label_studio_sdk/tasks/__init__.py +5 -0
  151. label_studio_sdk/tasks/client.py +811 -0
  152. label_studio_sdk/tasks/types/__init__.py +6 -0
  153. label_studio_sdk/tasks/types/tasks_list_request_fields.py +5 -0
  154. label_studio_sdk/tasks/types/tasks_list_response.py +48 -0
  155. label_studio_sdk/types/__init__.py +115 -0
  156. label_studio_sdk/types/annotation.py +116 -0
  157. label_studio_sdk/types/annotation_filter_options.py +42 -0
  158. label_studio_sdk/types/annotation_last_action.py +19 -0
  159. label_studio_sdk/types/azure_blob_export_storage.py +112 -0
  160. label_studio_sdk/types/azure_blob_export_storage_status.py +7 -0
  161. label_studio_sdk/types/azure_blob_import_storage.py +113 -0
  162. label_studio_sdk/types/azure_blob_import_storage_status.py +7 -0
  163. label_studio_sdk/types/base_task.py +113 -0
  164. label_studio_sdk/types/base_user.py +42 -0
  165. label_studio_sdk/types/converted_format.py +36 -0
  166. label_studio_sdk/types/converted_format_status.py +5 -0
  167. label_studio_sdk/types/export.py +48 -0
  168. label_studio_sdk/types/export_convert.py +32 -0
  169. label_studio_sdk/types/export_create.py +54 -0
  170. label_studio_sdk/types/export_create_status.py +5 -0
  171. label_studio_sdk/types/export_status.py +5 -0
  172. label_studio_sdk/types/file_upload.py +30 -0
  173. label_studio_sdk/types/filter.py +53 -0
  174. label_studio_sdk/types/filter_group.py +35 -0
  175. label_studio_sdk/types/gcs_export_storage.py +112 -0
  176. label_studio_sdk/types/gcs_export_storage_status.py +7 -0
  177. label_studio_sdk/types/gcs_import_storage.py +113 -0
  178. label_studio_sdk/types/gcs_import_storage_status.py +7 -0
  179. label_studio_sdk/types/local_files_export_storage.py +97 -0
  180. label_studio_sdk/types/local_files_export_storage_status.py +7 -0
  181. label_studio_sdk/types/local_files_import_storage.py +92 -0
  182. label_studio_sdk/types/local_files_import_storage_status.py +7 -0
  183. label_studio_sdk/types/ml_backend.py +89 -0
  184. label_studio_sdk/types/ml_backend_auth_method.py +5 -0
  185. label_studio_sdk/types/ml_backend_state.py +5 -0
  186. label_studio_sdk/types/prediction.py +78 -0
  187. label_studio_sdk/types/project.py +198 -0
  188. label_studio_sdk/types/project_import.py +63 -0
  189. label_studio_sdk/types/project_import_status.py +5 -0
  190. label_studio_sdk/types/project_label_config.py +32 -0
  191. label_studio_sdk/types/project_sampling.py +7 -0
  192. label_studio_sdk/types/project_skip_queue.py +5 -0
  193. label_studio_sdk/types/redis_export_storage.py +117 -0
  194. label_studio_sdk/types/redis_export_storage_status.py +7 -0
  195. label_studio_sdk/types/redis_import_storage.py +112 -0
  196. label_studio_sdk/types/redis_import_storage_status.py +7 -0
  197. label_studio_sdk/types/s3export_storage.py +134 -0
  198. label_studio_sdk/types/s3export_storage_status.py +7 -0
  199. label_studio_sdk/types/s3import_storage.py +140 -0
  200. label_studio_sdk/types/s3import_storage_status.py +7 -0
  201. label_studio_sdk/types/serialization_option.py +36 -0
  202. label_studio_sdk/types/serialization_options.py +45 -0
  203. label_studio_sdk/types/task.py +157 -0
  204. label_studio_sdk/types/task_filter_options.py +49 -0
  205. label_studio_sdk/types/user_simple.py +37 -0
  206. label_studio_sdk/types/view.py +55 -0
  207. label_studio_sdk/types/webhook.py +67 -0
  208. label_studio_sdk/types/webhook_actions_item.py +21 -0
  209. label_studio_sdk/types/webhook_serializer_for_update.py +67 -0
  210. label_studio_sdk/types/webhook_serializer_for_update_actions_item.py +21 -0
  211. label_studio_sdk/users/__init__.py +5 -0
  212. label_studio_sdk/users/client.py +830 -0
  213. label_studio_sdk/users/types/__init__.py +6 -0
  214. label_studio_sdk/users/types/users_get_token_response.py +36 -0
  215. label_studio_sdk/users/types/users_reset_token_response.py +36 -0
  216. label_studio_sdk/version.py +4 -0
  217. label_studio_sdk/views/__init__.py +31 -0
  218. label_studio_sdk/views/client.py +564 -0
  219. label_studio_sdk/views/types/__init__.py +29 -0
  220. label_studio_sdk/views/types/views_create_request_data.py +43 -0
  221. label_studio_sdk/views/types/views_create_request_data_filters.py +43 -0
  222. label_studio_sdk/views/types/views_create_request_data_filters_conjunction.py +5 -0
  223. label_studio_sdk/views/types/views_create_request_data_filters_items_item.py +47 -0
  224. label_studio_sdk/views/types/views_create_request_data_ordering_item.py +38 -0
  225. label_studio_sdk/views/types/views_create_request_data_ordering_item_direction.py +5 -0
  226. label_studio_sdk/views/types/views_update_request_data.py +43 -0
  227. label_studio_sdk/views/types/views_update_request_data_filters.py +43 -0
  228. label_studio_sdk/views/types/views_update_request_data_filters_conjunction.py +5 -0
  229. label_studio_sdk/views/types/views_update_request_data_filters_items_item.py +47 -0
  230. label_studio_sdk/views/types/views_update_request_data_ordering_item.py +38 -0
  231. label_studio_sdk/views/types/views_update_request_data_ordering_item_direction.py +5 -0
  232. label_studio_sdk/webhooks/__init__.py +5 -0
  233. label_studio_sdk/webhooks/client.py +636 -0
  234. label_studio_sdk/webhooks/types/__init__.py +5 -0
  235. label_studio_sdk/webhooks/types/webhooks_update_request_actions_item.py +21 -0
  236. label_studio_sdk-1.0.0.dist-info/METADATA +307 -0
  237. label_studio_sdk-1.0.0.dist-info/RECORD +239 -0
  238. {label_studio_sdk-0.0.32.dist-info → label_studio_sdk-1.0.0.dist-info}/WHEEL +1 -2
  239. docs/__init__.py +0 -3
  240. label_studio_sdk-0.0.32.dist-info/LICENSE +0 -201
  241. label_studio_sdk-0.0.32.dist-info/METADATA +0 -22
  242. label_studio_sdk-0.0.32.dist-info/RECORD +0 -15
  243. label_studio_sdk-0.0.32.dist-info/top_level.txt +0 -3
  244. tests/test_client.py +0 -26
  245. {tests → label_studio_sdk/_extensions}/__init__.py +0 -0
@@ -1,455 +1,183 @@
1
- """ .. include::../docs/client.md
2
- """
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
3
  import os
4
+ import typing
5
+
6
+ import httpx
7
+
8
+ from .actions.client import ActionsClient, AsyncActionsClient
9
+ from .annotations.client import AnnotationsClient, AsyncAnnotationsClient
10
+ from .core.api_error import ApiError
11
+ from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
12
+ from .environment import LabelStudioEnvironment
13
+ from .export_storage.client import AsyncExportStorageClient, ExportStorageClient
14
+ from .files.client import AsyncFilesClient, FilesClient
15
+ from .import_storage.client import AsyncImportStorageClient, ImportStorageClient
16
+ from .ml.client import AsyncMlClient, MlClient
17
+ from .predictions.client import AsyncPredictionsClient, PredictionsClient
18
+ from .projects.client import AsyncProjectsClient, ProjectsClient
19
+ from .tasks.client import AsyncTasksClient, TasksClient
20
+ from .users.client import AsyncUsersClient, UsersClient
21
+ from .views.client import AsyncViewsClient, ViewsClient
22
+ from .webhooks.client import AsyncWebhooksClient, WebhooksClient
23
+
24
+
25
+ class LabelStudio:
26
+ """
27
+ Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.
28
+
29
+ Parameters
30
+ ----------
31
+ base_url : typing.Optional[str]
32
+ The base url to use for requests from the client.
33
+
34
+ environment : LabelStudioEnvironment
35
+ The environment to use for requests from the client. from .environment import LabelStudioEnvironment
36
+
4
37
 
5
- import json
6
- import warnings
7
- import logging
8
- import requests
9
38
 
10
- from typing import Optional
11
- from pydantic import BaseModel, constr, root_validator
12
- from requests.adapters import HTTPAdapter
13
- from types import SimpleNamespace
39
+ Defaults to LabelStudioEnvironment.DEFAULT
14
40
 
15
- logger = logging.getLogger(__name__)
16
41
 
17
- MAX_RETRIES = 3
18
- TIMEOUT = (10.0, 180.0)
19
- HEADERS = {}
20
- LABEL_STUDIO_DEFAULT_URL = 'http://localhost:8080'
21
42
 
43
+ api_key : typing.Optional[str]
44
+ timeout : typing.Optional[float]
45
+ The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.
22
46
 
23
- class ClientCredentials(BaseModel):
24
- email: Optional[str] = None
25
- password: Optional[str] = None
26
- api_key: Optional[constr()] = None
47
+ follow_redirects : typing.Optional[bool]
48
+ Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.
27
49
 
28
- @root_validator(pre=True, allow_reuse=True)
29
- def either_key_or_email_password(cls, values):
30
- assert (
31
- 'email' in values or 'api_key' in values
32
- ), 'At least one of email or api_key should be included'
33
- assert (
34
- 'email' not in values or 'password' in values
35
- ), 'Provide both email and password for login auth'
36
- return values
50
+ httpx_client : typing.Optional[httpx.Client]
51
+ The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
37
52
 
53
+ Examples
54
+ --------
55
+ from label_studio_sdk.client import LabelStudio
56
+
57
+ client = LabelStudio(
58
+ api_key="YOUR_API_KEY",
59
+ )
60
+ """
38
61
 
39
- class Client(object):
40
62
  def __init__(
41
63
  self,
42
- url: str = None,
43
- api_key: str = None,
44
- credentials=None,
45
- session=None,
46
- extra_headers: dict = None,
47
- cookies: dict = None,
48
- oidc_token=None,
49
- versions=None,
50
- make_request_raise=True,
64
+ *,
65
+ base_url: typing.Optional[str] = None,
66
+ environment: LabelStudioEnvironment = LabelStudioEnvironment.DEFAULT,
67
+ api_key: typing.Optional[str] = os.getenv("LABEL_STUDIO_API_KEY"),
68
+ timeout: typing.Optional[float] = None,
69
+ follow_redirects: typing.Optional[bool] = True,
70
+ httpx_client: typing.Optional[httpx.Client] = None
51
71
  ):
52
- """Initialize the client. Do this before using other Label Studio SDK classes and methods in your script.
53
-
54
- Parameters
55
- ----------
56
- url: str
57
- Label Studio host address.
58
- Example: http://localhost:8080
59
- api_key: str
60
- User token for the API. You can find this on your user account page in Label Studio.
61
- credentials: ClientCredentials
62
- User email and password or api_key.
63
- session: requests.Session()
64
- If None, a new one is created.
65
- extra_headers: dict
66
- Additional headers that will be passed to each http request
67
- cookies: dict
68
- Cookies that will be passed to each http request.
69
- oidc_token: str
70
- Bearer token for proxy authentication - in case the server is behind an authenticating proxy.
71
- versions: dict
72
- Versions of Label Studio components for the connected instance
73
- make_request_raise: bool
74
- If true, make_request will raise exceptions on request errors
75
- """
76
- if not url:
77
- url = os.getenv('LABEL_STUDIO_URL', LABEL_STUDIO_DEFAULT_URL)
78
- self.url = url.rstrip('/')
79
- self.make_request_raise = make_request_raise
80
- self.session = session or self.get_session()
81
-
82
- # set api key or get it using credentials (username and password)
83
- if api_key is None and credentials is None:
84
- api_key = os.getenv('LABEL_STUDIO_API_KEY')
85
-
86
- if api_key is not None:
87
- credentials = ClientCredentials(api_key=api_key)
88
- self.api_key = (
89
- credentials.api_key
90
- if credentials.api_key
91
- else self.get_api_key(credentials)
72
+ _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
73
+ if api_key is None:
74
+ raise ApiError(
75
+ body="The client must be instantiated be either passing in api_key or setting LABEL_STUDIO_API_KEY"
76
+ )
77
+ self._client_wrapper = SyncClientWrapper(
78
+ base_url=_get_base_url(base_url=base_url, environment=environment),
79
+ api_key=api_key,
80
+ httpx_client=httpx_client
81
+ if httpx_client is not None
82
+ else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
83
+ if follow_redirects is not None
84
+ else httpx.Client(timeout=_defaulted_timeout),
85
+ timeout=_defaulted_timeout,
92
86
  )
87
+ self.annotations = AnnotationsClient(client_wrapper=self._client_wrapper)
88
+ self.users = UsersClient(client_wrapper=self._client_wrapper)
89
+ self.actions = ActionsClient(client_wrapper=self._client_wrapper)
90
+ self.views = ViewsClient(client_wrapper=self._client_wrapper)
91
+ self.files = FilesClient(client_wrapper=self._client_wrapper)
92
+ self.projects = ProjectsClient(client_wrapper=self._client_wrapper)
93
+ self.ml = MlClient(client_wrapper=self._client_wrapper)
94
+ self.predictions = PredictionsClient(client_wrapper=self._client_wrapper)
95
+ self.tasks = TasksClient(client_wrapper=self._client_wrapper)
96
+ self.import_storage = ImportStorageClient(client_wrapper=self._client_wrapper)
97
+ self.export_storage = ExportStorageClient(client_wrapper=self._client_wrapper)
98
+ self.webhooks = WebhooksClient(client_wrapper=self._client_wrapper)
93
99
 
94
- # set headers
95
- self.headers = {'Authorization': f'Token {self.api_key}'}
96
- if oidc_token:
97
- self.headers.update({'Proxy-Authorization': f'Bearer {oidc_token}'})
98
- if extra_headers:
99
- self.headers.update(extra_headers)
100
-
101
- # set cookies
102
- self.cookies = cookies
103
-
104
- # set versions from /version endpoint
105
- self.versions = versions if versions else self.get_versions()
106
- self.is_enterprise = 'label-studio-enterprise-backend' in self.versions
107
-
108
- def get_versions(self):
109
- """Call /version api and get all Label Studio component versions
110
-
111
- Returns
112
- -------
113
- dict with Label Studio component names and their versions
114
-
115
- """
116
- self.versions = self.make_request('GET', '/api/version').json()
117
- return self.versions
118
-
119
- def get_api_key(self, credentials: ClientCredentials):
120
- login_url = self.get_url("/user/login")
121
- # Retrieve and set the CSRF token first
122
- self.session.get(login_url)
123
- csrf_token = self.session.cookies.get('csrftoken', None)
124
- login_data = dict(**credentials.dict(), csrfmiddlewaretoken=csrf_token)
125
- self.session.post(
126
- login_url,
127
- data=login_data,
128
- headers=dict(Referer=self.url),
129
- cookies=self.cookies,
130
- ).raise_for_status()
131
- api_key = (
132
- self.session.get(self.get_url("/api/current-user/token"))
133
- .json()
134
- .get("token")
135
- )
136
- return api_key
137
-
138
- def check_connection(self):
139
- """Call Label Studio /health endpoint to check the connection to the server.
140
-
141
- Returns
142
- -------
143
- dict
144
- Status string like "UP"
145
- """
146
- response = self.make_request('GET', '/health')
147
- return response.json()
148
-
149
- def get_projects(self, **query_params):
150
- """List all projects in Label Studio.
151
-
152
- Returns
153
- -------
154
- list or `label_studio_sdk.project.Project` instances
155
-
156
- """
157
- return self.list_projects(**query_params)
158
-
159
- def delete_project(self, project_id: int):
160
- """Delete a project in Label Studio.
161
-
162
- Returns
163
- -------
164
- dict
165
- Status string
166
- """
167
- response = self.make_request('DELETE', f'/api/projects/{project_id}/')
168
- return response
169
-
170
- def delete_all_projects(self):
171
- """Deletes all projects in Label Studio.
172
-
173
- Returns
174
- -------
175
- List
176
- List of (dict) status strings
177
- """
178
- responses = []
179
- project_ids = [project.get_params()['id'] for project in self.list_projects()]
180
- for project_id in project_ids:
181
- response = self.delete_project(project_id)
182
- responses.append(response)
183
- return responses
184
-
185
- def list_projects(self, **query_params):
186
- """List all projects in Label Studio.
187
-
188
- Returns
189
- -------
190
- list or `label_studio_sdk.project.Project` instances
191
-
192
- """
193
- from .project import Project
194
-
195
- params = {'page_size': 10000000}
196
- params.update(query_params)
197
- response = self.make_request('GET', '/api/projects', params=params)
198
- if response.status_code == 200:
199
- projects = []
200
- for data in response.json()['results']:
201
- project = Project._create_from_id(
202
- client=self, project_id=data['id'], params=data
203
- )
204
- projects.append(project)
205
- logger.debug(
206
- f'Project {project.id} "{project.get_params().get("title")}" is retrieved'
207
- )
208
- return projects
209
-
210
- def create_project(self, **kwargs):
211
- return self.start_project(**kwargs)
212
-
213
- def start_project(self, **kwargs):
214
- """Create a new project instance.
215
-
216
- Parameters
217
- ----------
218
- kwargs:
219
- Parameters for `project.start_project(**kwargs)`
220
-
221
- Returns
222
- -------
223
- `label_studio_sdk.project.Project`
224
-
225
- """
226
- from .project import Project
227
-
228
- project = Project(
229
- url=self.url,
230
- api_key=self.api_key,
231
- session=self.session,
232
- versions=self.versions,
233
- )
234
- project.start_project(**kwargs)
235
- return project
236
-
237
- def get_project(self, id):
238
- """Return project SDK object by ID existed in Label Studio
239
-
240
- Parameters
241
- ----------
242
- id: int
243
- Project ID for the project you want to retrieve.
244
-
245
- Returns
246
- -------
247
- `label_studio_sdk.project.Project`
248
-
249
- """
250
- from .project import Project
251
-
252
- return Project.get_from_id(self, id)
253
-
254
- def get_users(self):
255
- """Return all users from the current organization account
256
-
257
- Parameters
258
- ----------
259
-
260
- Returns
261
- -------
262
- list of `label_studio_sdk.users.User`
263
-
264
- """
265
- from .users import User
266
-
267
- response = self.make_request('GET', '/api/users')
268
- users = []
269
- for user_data in response.json():
270
- user_data['client'] = self
271
- users.append(User(**user_data))
272
- return users
273
-
274
- def create_user(self, user, exist_ok=True):
275
- """Create a new user
276
-
277
- Parameters
278
- ----------
279
- user: User or dict
280
- User instance, you can initialize it this way:
281
- User(username='x', email='x@x.xx', first_name='X', last_name='Z')
282
- exist_ok: bool
283
- True by default, it won't print error if user exists and exist_ok=True
284
-
285
- Returns
286
- -------
287
- `label_studio_sdk.users.User`
288
- Created user
289
-
290
- """
291
- from .users import User
292
-
293
- payload = (
294
- {
295
- 'username': user.username if user.username else user.email,
296
- 'email': user.email,
297
- 'first_name': user.first_name,
298
- 'last_name': user.last_name,
299
- 'phone': user.phone,
300
- }
301
- if isinstance(user, User)
302
- else user
303
- )
304
100
 
305
- response = self.make_request(
306
- 'POST', '/api/users', json=payload, raise_exceptions=False
307
- )
308
- user_data = response.json()
309
- user_data['client'] = self
310
-
311
- if response.status_code < 400:
312
- return User(**user_data)
313
- else:
314
- if 'already exists' in response.text and exist_ok is True:
315
- return None
316
- logger.error('Create user error: ' + str(response.json()))
317
- return None
318
-
319
- def get_workspaces(self):
320
- """Return all workspaces from the current organization account
321
-
322
- Parameters
323
- ----------
324
-
325
- Returns
326
- -------
327
- list of `label_studio_sdk.workspaces.Workspace`
328
-
329
- """
330
- from .workspaces import Workspace
331
-
332
- assert (
333
- self.is_enterprise
334
- ), "Workspaces are available only for Enterprise instance of Label Studio"
335
-
336
- response = self.make_request('GET', '/api/workspaces')
337
- workspaces = []
338
- for workspace_data in response.json():
339
- workspace_data['client'] = self
340
- workspaces.append(Workspace(**workspace_data))
341
- return workspaces
342
-
343
- def get_session(self):
344
- """Create a session with requests.Session()
345
-
346
- Returns
347
- -------
348
- request.Session
349
-
350
- """
351
- session = requests.Session()
352
- session.headers.update(HEADERS)
353
- session.mount('http://', HTTPAdapter(max_retries=MAX_RETRIES))
354
- session.mount('https://', HTTPAdapter(max_retries=MAX_RETRIES))
355
- return session
356
-
357
- def get_url(self, suffix):
358
- """Get the URL of the Label Studio server
359
-
360
- Returns
361
- -------
362
- String with the URL
363
-
364
- """
365
- return f'{self.url}/{suffix.lstrip("/")}'
366
-
367
- def make_request(self, method, url, *args, **kwargs):
368
- """Make a request with an API key to Label Studio instance
369
-
370
- Parameters
371
- ----------
372
- method: str
373
- HTTP method like POST, PATCH, GET, DELETE.
374
- url: str
375
- URL of the API endpoint that you want to make a request to.
376
-
377
- args
378
- session.request(*args)
379
- kwargs
380
- session.request(*kwargs)
381
-
382
- Returns
383
- -------
384
- Response object for the relevant endpoint.
385
-
386
- """
387
- if 'timeout' not in kwargs:
388
- kwargs['timeout'] = TIMEOUT
389
-
390
- raise_exceptions = self.make_request_raise
391
- if 'raise_exceptions' in kwargs: # kwargs have higher priority
392
- raise_exceptions = kwargs.pop('raise_exceptions')
393
-
394
- logger.debug(f'{method}: {url} with args={args}, kwargs={kwargs}')
395
- response = self.session.request(
396
- method,
397
- self.get_url(url),
398
- headers=self.headers,
399
- cookies=self.cookies,
400
- *args,
401
- **kwargs,
402
- )
101
+ class AsyncLabelStudio:
102
+ """
103
+ Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.
403
104
 
404
- if raise_exceptions:
405
- if response.status_code >= 400:
406
- self.log_response_error(response)
407
- response.raise_for_status()
408
-
409
- return response
410
-
411
- def log_response_error(self, response):
412
- try:
413
- content = json.dumps(json.loads(response.content), indent=2)
414
- except:
415
- content = response.text
416
-
417
- logger.error(
418
- f'\n--------------------------------------------\n'
419
- f'Request URL: {response.url}\n'
420
- f'Response status code: {response.status_code}\n'
421
- f'Response content:\n{content}\n\n'
422
- f'SDK error traceback:'
423
- )
105
+ Parameters
106
+ ----------
107
+ base_url : typing.Optional[str]
108
+ The base url to use for requests from the client.
424
109
 
425
- def sync_storage(self, storage_type, storage_id):
426
- """Synchronize Cloud Storage.
427
-
428
- Parameters
429
- ----------
430
- storage_type: string
431
- Specify the type of the storage container.
432
- storage_id: int
433
- Specify the storage ID of the storage container.
434
-
435
- Returns
436
- -------
437
- dict:
438
- containing the same fields as in the original storage request and:
439
-
440
- id: int
441
- Storage ID
442
- type: str
443
- Type of storage
444
- created_at: str
445
- Creation time
446
- last_sync: str
447
- Time last sync finished, can be empty.
448
- last_sync_count: int
449
- Number of tasks synced in the last sync
450
- """
451
-
452
- response = self.make_request(
453
- "POST", f"/api/storages/{storage_type}/{str(storage_id)}/sync"
110
+ environment : LabelStudioEnvironment
111
+ The environment to use for requests from the client. from .environment import LabelStudioEnvironment
112
+
113
+
114
+
115
+ Defaults to LabelStudioEnvironment.DEFAULT
116
+
117
+
118
+
119
+ api_key : typing.Optional[str]
120
+ timeout : typing.Optional[float]
121
+ The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.
122
+
123
+ follow_redirects : typing.Optional[bool]
124
+ Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.
125
+
126
+ httpx_client : typing.Optional[httpx.AsyncClient]
127
+ The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
128
+
129
+ Examples
130
+ --------
131
+ from label_studio_sdk.client import AsyncLabelStudio
132
+
133
+ client = AsyncLabelStudio(
134
+ api_key="YOUR_API_KEY",
135
+ )
136
+ """
137
+
138
+ def __init__(
139
+ self,
140
+ *,
141
+ base_url: typing.Optional[str] = None,
142
+ environment: LabelStudioEnvironment = LabelStudioEnvironment.DEFAULT,
143
+ api_key: typing.Optional[str] = os.getenv("LABEL_STUDIO_API_KEY"),
144
+ timeout: typing.Optional[float] = None,
145
+ follow_redirects: typing.Optional[bool] = True,
146
+ httpx_client: typing.Optional[httpx.AsyncClient] = None
147
+ ):
148
+ _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
149
+ if api_key is None:
150
+ raise ApiError(
151
+ body="The client must be instantiated be either passing in api_key or setting LABEL_STUDIO_API_KEY"
152
+ )
153
+ self._client_wrapper = AsyncClientWrapper(
154
+ base_url=_get_base_url(base_url=base_url, environment=environment),
155
+ api_key=api_key,
156
+ httpx_client=httpx_client
157
+ if httpx_client is not None
158
+ else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
159
+ if follow_redirects is not None
160
+ else httpx.AsyncClient(timeout=_defaulted_timeout),
161
+ timeout=_defaulted_timeout,
454
162
  )
455
- return response.json()
163
+ self.annotations = AsyncAnnotationsClient(client_wrapper=self._client_wrapper)
164
+ self.users = AsyncUsersClient(client_wrapper=self._client_wrapper)
165
+ self.actions = AsyncActionsClient(client_wrapper=self._client_wrapper)
166
+ self.views = AsyncViewsClient(client_wrapper=self._client_wrapper)
167
+ self.files = AsyncFilesClient(client_wrapper=self._client_wrapper)
168
+ self.projects = AsyncProjectsClient(client_wrapper=self._client_wrapper)
169
+ self.ml = AsyncMlClient(client_wrapper=self._client_wrapper)
170
+ self.predictions = AsyncPredictionsClient(client_wrapper=self._client_wrapper)
171
+ self.tasks = AsyncTasksClient(client_wrapper=self._client_wrapper)
172
+ self.import_storage = AsyncImportStorageClient(client_wrapper=self._client_wrapper)
173
+ self.export_storage = AsyncExportStorageClient(client_wrapper=self._client_wrapper)
174
+ self.webhooks = AsyncWebhooksClient(client_wrapper=self._client_wrapper)
175
+
176
+
177
+ def _get_base_url(*, base_url: typing.Optional[str] = None, environment: LabelStudioEnvironment) -> str:
178
+ if base_url is not None:
179
+ return base_url
180
+ elif environment is not None:
181
+ return environment.value
182
+ else:
183
+ raise Exception("Please pass in either base_url or environment to construct the client")
@@ -0,0 +1,7 @@
1
+ # try is used here to import this file in setup.py and don't break the setup process
2
+ try:
3
+ from .converter import Converter
4
+ except ModuleNotFoundError as e:
5
+ print(e)
6
+
7
+ __version__ = "0.0.59.dev"
@@ -0,0 +1,56 @@
1
+ import os
2
+ import io
3
+ import logging
4
+ import json
5
+
6
+
7
+ from .utils import get_audio_duration, ensure_dir, download, get_annotator
8
+
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ def convert_to_asr_json_manifest(
14
+ input_data, output_dir, data_key, project_dir, upload_dir, download_resources
15
+ ):
16
+ audio_dir_rel = "audio"
17
+ output_audio_dir = os.path.join(output_dir, audio_dir_rel)
18
+ ensure_dir(output_dir), ensure_dir(output_audio_dir)
19
+ output_file = os.path.join(output_dir, "manifest.json")
20
+ with io.open(output_file, mode="w") as fout:
21
+ for item in input_data:
22
+ audio_path = item["input"][data_key]
23
+ try:
24
+ audio_path = download(
25
+ audio_path,
26
+ output_audio_dir,
27
+ project_dir=project_dir,
28
+ upload_dir=upload_dir,
29
+ return_relative_path=True,
30
+ download_resources=download_resources,
31
+ )
32
+ duration = get_audio_duration(
33
+ os.path.join(output_audio_dir, os.path.basename(audio_path))
34
+ )
35
+ except:
36
+ logger.info(
37
+ "Unable to download {image_path} or get audio duration. The item {item} will be skipped".format(
38
+ image_path=audio_path, item=item
39
+ ),
40
+ exc_info=True,
41
+ )
42
+ continue
43
+
44
+ for texts in iter(item["output"].values()):
45
+ if len(texts) > 0 and "text" in texts[0]:
46
+ break
47
+
48
+ transcript = texts[0]["text"][0]
49
+ metadata = {
50
+ "audio_filepath": audio_path,
51
+ "duration": duration,
52
+ "text": transcript,
53
+ "annotator": get_annotator(item, default=""),
54
+ }
55
+ json.dump(metadata, fout)
56
+ fout.write("\n")