unitlab 2.3.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.
unitlab/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ import logging
2
+
3
+ from .client import UnitlabClient
4
+
5
+ logging.basicConfig(
6
+ level=logging.INFO,
7
+ format="%(asctime)s [%(levelname)s] %(message)s",
8
+ datefmt="%Y-%m-%d %H:%M:%S",
9
+ )
10
+
11
+ __all__ = ["UnitlabClient"]
unitlab/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .main import app
2
+
3
+ app()
unitlab/client.py ADDED
@@ -0,0 +1,236 @@
1
+ import asyncio
2
+ import glob
3
+ import logging
4
+ import os
5
+ import urllib.parse
6
+
7
+ import aiofiles
8
+ import aiohttp
9
+ import requests
10
+ import tqdm
11
+
12
+ from .utils import get_api_url, handle_exceptions
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class UnitlabClient:
18
+ """A client with a connection to the Unitlab.ai platform.
19
+
20
+ Note:
21
+ Please refer to the `Python SDK quickstart <https://docs.unitlab.ai/cli-python-sdk/unitlab-python-sdk>`__ for a full example of working with the Python SDK.
22
+
23
+ First install the SDK.
24
+
25
+ .. code-block:: bash
26
+
27
+ pip install --upgrade unitlab
28
+
29
+ Import the ``unitlab`` package in your python file and set up a client with an API key. An API key can be created on <https://unitlab.ai/>`__.
30
+
31
+ .. code-block:: python
32
+
33
+ from unitlab import UnitlabClient
34
+ api_key = 'YOUR_API_KEY'
35
+ client = UnitlabClient(api_key)
36
+
37
+ Or store your Unitlab API key in your environment (``UNITLAB_API_KEY = 'YOUR_API_KEY'``):
38
+
39
+ .. code-block:: python
40
+
41
+ from unitlab import UnitlabClient
42
+ client = UnitlabClient()
43
+
44
+ Args:
45
+ api_key: Your Unitlab.ai API key. If no API key given, reads ``UNITLAB_API_KEY`` from the environment. Defaults to :obj:`None`.
46
+ Raises:
47
+ :exc:`~unitlab.exceptions.AuthenticationError`: If an invalid API key is used or (when not passing the API key directly) if ``UNITLAB_API_KEY`` is not found in your environment.
48
+ """
49
+
50
+ def __init__(self, api_key, api_url=None):
51
+ self.api_key = api_key
52
+ self.api_url = api_url or get_api_url()
53
+ self.api_session = requests.Session()
54
+ adapter = requests.adapters.HTTPAdapter(max_retries=3)
55
+ self.api_session.mount("http://", adapter)
56
+ self.api_session.mount("https://", adapter)
57
+
58
+ def close(self) -> None:
59
+ """Close :class:`UnitlabClient` connections.
60
+
61
+ You can manually close the Unitlab client's connections:
62
+
63
+ .. code-block:: python
64
+
65
+ client = UnitlabClient()
66
+ client.projects()
67
+ client.close()
68
+
69
+ Or use the client as a context manager:
70
+
71
+ .. code-block:: python
72
+
73
+ with UnitlabClient() as client:
74
+ client.projects()
75
+ """
76
+ self.api_session.close()
77
+
78
+ def __enter__(self):
79
+ return self
80
+
81
+ def __exit__(
82
+ self,
83
+ exc_type,
84
+ exc_value,
85
+ traceback,
86
+ ) -> None:
87
+ self.close()
88
+
89
+ def _get_headers(self):
90
+ return {"Authorization": f"Api-Key {self.api_key}"}
91
+
92
+ @handle_exceptions
93
+ def _get(self, endpoint):
94
+ return self.api_session.get(
95
+ urllib.parse.urljoin(self.api_url, endpoint), headers=self._get_headers()
96
+ )
97
+
98
+ @handle_exceptions
99
+ def _post(self, endpoint, data=None):
100
+ return self.api_session.post(
101
+ urllib.parse.urljoin(self.api_url, endpoint),
102
+ json=data or {},
103
+ headers=self._get_headers(),
104
+ )
105
+
106
+ def projects(self, pretty=0):
107
+ return self._get(f"/api/sdk/projects/?pretty={pretty}")
108
+
109
+ def project(self, project_id, pretty=0):
110
+ return self._get(f"/api/sdk/projects/{project_id}/?pretty={pretty}")
111
+
112
+ def project_members(self, project_id, pretty=0):
113
+ return self._get(f"/api/sdk/projects/{project_id}/members/?pretty={pretty}")
114
+
115
+ def project_upload_data(self, project_id, directory, batch_size=100):
116
+ if not os.path.isdir(directory):
117
+ raise ValueError(f"Directory {directory} does not exist")
118
+
119
+ files = [
120
+ file
121
+ for files_list in (
122
+ glob.glob(os.path.join(directory, "") + extension)
123
+ for extension in ["*jpg", "*png", "*jpeg", "*webp"]
124
+ )
125
+ for file in files_list
126
+ ]
127
+ filtered_files = []
128
+ for file in files:
129
+ file_size = os.path.getsize(file) / 1024 / 1024
130
+ if file_size > 6:
131
+ logger.warning(
132
+ f"File {file} is too large ({file_size:.4f} megabytes) skipping, max size is 6 MB"
133
+ )
134
+ continue
135
+ filtered_files.append(file)
136
+
137
+ num_files = len(filtered_files)
138
+ num_batches = (num_files + batch_size - 1) // batch_size
139
+
140
+ async def post_file(session: aiohttp.ClientSession, file: str, project_id: str):
141
+ async with aiofiles.open(file, "rb") as f:
142
+ form_data = aiohttp.FormData()
143
+ form_data.add_field("project", project_id)
144
+ form_data.add_field(
145
+ "file", await f.read(), filename=os.path.basename(file)
146
+ )
147
+ try:
148
+ await asyncio.sleep(0.1)
149
+ async with session.post(
150
+ urllib.parse.urljoin(self.api_url, "/api/sdk/upload-data/"),
151
+ data=form_data,
152
+ ) as response:
153
+ response.raise_for_status()
154
+ return 1
155
+ except Exception as e:
156
+ logger.error(f"Error uploading file {file} - {e}")
157
+ return 0
158
+
159
+ async def main():
160
+ logger.info(f"Uploading {num_files} files to project {project_id}")
161
+ with tqdm.tqdm(total=num_files, ncols=80) as pbar:
162
+ async with aiohttp.ClientSession(
163
+ headers=self._get_headers()
164
+ ) as session:
165
+ for i in range(num_batches):
166
+ tasks = []
167
+ for file in filtered_files[
168
+ i * batch_size : min((i + 1) * batch_size, num_files)
169
+ ]:
170
+ tasks.append(
171
+ post_file(
172
+ session=session, file=file, project_id=project_id
173
+ )
174
+ )
175
+ for f in asyncio.as_completed(tasks):
176
+ pbar.update(await f)
177
+
178
+ asyncio.run(main())
179
+
180
+ def datasets(self, pretty=0):
181
+ return self._get(f"/api/sdk/datasets/?pretty={pretty}")
182
+
183
+ def dataset_download(self, dataset_id, export_type):
184
+ response = self._post(
185
+ f"/api/sdk/datasets/{dataset_id}/",
186
+ data={"download_type": "annotation", "export_type": export_type},
187
+ )
188
+
189
+ with self.api_session.get(url=response["file"], stream=True) as r:
190
+ r.raise_for_status()
191
+ filename = f"dataset-{dataset_id}.json"
192
+ with open(filename, "wb") as f:
193
+ for chunk in r.iter_content(chunk_size=1024 * 1024):
194
+ f.write(chunk)
195
+ logger.info(f"File: {os.path.abspath(filename)}")
196
+ return os.path.abspath(filename)
197
+
198
+ def dataset_download_files(self, dataset_id):
199
+ response = self._post(
200
+ f"/api/sdk/datasets/{dataset_id}/", data={"download_type": "files"}
201
+ )
202
+ folder = f"dataset-files-{dataset_id}"
203
+ os.makedirs(folder, exist_ok=True)
204
+ dataset_files = [
205
+ dataset_file
206
+ for dataset_file in response
207
+ if not os.path.isfile(os.path.join(folder, dataset_file["file_name"]))
208
+ ]
209
+
210
+ async def download_file(session: aiohttp.ClientSession, dataset_file: dict):
211
+ async with session.get(url=dataset_file["source"]) as r:
212
+ try:
213
+ r.raise_for_status()
214
+ except Exception as e:
215
+ logger.error(
216
+ f"Error downloading file {dataset_file['file_name']} - {e}"
217
+ )
218
+ return 0
219
+ async with aiofiles.open(
220
+ os.path.join(folder, dataset_file["file_name"]), "wb"
221
+ ) as f:
222
+ async for chunk in r.content.iter_any():
223
+ await f.write(chunk)
224
+ return 1
225
+
226
+ async def main():
227
+ with tqdm.tqdm(total=len(dataset_files), ncols=80) as pbar:
228
+ async with aiohttp.ClientSession() as session:
229
+ tasks = [
230
+ download_file(session=session, dataset_file=dataset_file)
231
+ for dataset_file in dataset_files
232
+ ]
233
+ for f in asyncio.as_completed(tasks):
234
+ pbar.update(await f)
235
+
236
+ asyncio.run(main())
unitlab/exceptions.py ADDED
@@ -0,0 +1,42 @@
1
+ from typing import Optional
2
+
3
+
4
+ class UnitlabError(Exception):
5
+ """Base class for exceptions."""
6
+
7
+ def __init__(self, message: str, detail: Optional[Exception] = None):
8
+ """
9
+ Args:
10
+ message: An informative message about the exception.
11
+ detail: The detail of the exception raised by Python or another library. Defaults to :obj:`None`.
12
+ """
13
+ super().__init__(message, detail)
14
+ self.message = message
15
+ self.detail = detail
16
+
17
+ def __str__(self) -> str:
18
+ return self.message
19
+
20
+
21
+ class ConfigurationError(UnitlabError):
22
+ """Raised when a configuration error occurs."""
23
+
24
+ pass
25
+
26
+
27
+ class AuthenticationError(UnitlabError):
28
+ """Raised when an API key fails authentication."""
29
+
30
+ pass
31
+
32
+
33
+ class NetworkError(UnitlabError):
34
+ """Raised when an HTTP error occurs."""
35
+
36
+ pass
37
+
38
+
39
+ class SubscriptionError(NetworkError):
40
+ """Raised when a subscription error occurs"""
41
+
42
+ pass
unitlab/main.py ADDED
@@ -0,0 +1,109 @@
1
+ from enum import Enum
2
+ from pathlib import Path
3
+ from uuid import UUID
4
+
5
+ import typer
6
+ import validators
7
+ from typing_extensions import Annotated
8
+
9
+ from . import utils
10
+ from .client import UnitlabClient
11
+
12
+ app = typer.Typer()
13
+ project_app = typer.Typer()
14
+ dataset_app = typer.Typer()
15
+
16
+ app.add_typer(project_app, name="project", help="Project commands")
17
+ app.add_typer(dataset_app, name="dataset", help="Dataset commands")
18
+
19
+
20
+ API_KEY = Annotated[
21
+ str,
22
+ typer.Option(
23
+ default_factory=utils.get_api_key, help="The api-key obtained from unitlab.ai"
24
+ ),
25
+ ]
26
+
27
+
28
+ class DownloadType(str, Enum):
29
+ annotation = "annotation"
30
+ files = "files"
31
+
32
+
33
+ class AnnotationType(str, Enum):
34
+ IMG_BBOX = "img_bbox"
35
+ IMG_SEMANTIC_SEGMENTATION = "img_semantic_segmentation"
36
+ IMG_INSTANCE_SEGMENTATION = "img_instance_segmentation"
37
+ IMG_POLYGON = "img_polygon"
38
+ IMG_LINE = "img_line"
39
+ IMG_POINT = "img_point"
40
+
41
+
42
+ @app.command(help="Configure the credentials")
43
+ def configure(
44
+ api_key: Annotated[str, typer.Option(help="The api-key obtained from unitlab.ai")],
45
+ api_url: Annotated[str, typer.Option()] = "https://api.unitlab.ai",
46
+ ):
47
+ if not validators.url(api_url, simple_host=True):
48
+ raise typer.BadParameter("Invalid api url")
49
+ utils.write_config(api_key=api_key, api_url=api_url)
50
+
51
+
52
+ def get_client(api_key: str) -> UnitlabClient:
53
+ return UnitlabClient(api_key=api_key)
54
+
55
+
56
+ @project_app.command(name="list", help="Project list")
57
+ def project_list(api_key: API_KEY):
58
+ print(get_client(api_key).projects(pretty=1))
59
+
60
+
61
+ @project_app.command(name="detail", help="Project detail")
62
+ def project_detail(pk: UUID, api_key: API_KEY):
63
+ print(get_client(api_key).project(project_id=pk, pretty=1))
64
+
65
+
66
+ @project_app.command(help="Project members")
67
+ def members(pk: UUID, api_key: API_KEY):
68
+ print(get_client(api_key).project_members(project_id=pk, pretty=1))
69
+
70
+
71
+ @project_app.command(help="Upload data")
72
+ def upload(
73
+ pk: UUID,
74
+ api_key: API_KEY,
75
+ directory: Annotated[
76
+ Path, typer.Option(help="Directory containing the data to be uploaded")
77
+ ],
78
+ ):
79
+ get_client(api_key).project_upload_data(str(pk), directory=directory)
80
+
81
+
82
+ @dataset_app.command(name="list", help="List datasets")
83
+ def dataset_list(api_key: API_KEY):
84
+ print(get_client(api_key).datasets(pretty=1))
85
+
86
+
87
+ @dataset_app.command(name="download", help="Download dataset")
88
+ def dataset_download(
89
+ pk: UUID,
90
+ api_key: API_KEY,
91
+ download_type: Annotated[
92
+ DownloadType,
93
+ typer.Option(help="Download type (annotation, files)"),
94
+ ] = DownloadType.annotation,
95
+ export_type: Annotated[
96
+ str, typer.Option(help="Export type (COCO, YOLOv8, YOLOv5)")
97
+ ] = "COCO",
98
+ ):
99
+ if download_type == DownloadType.annotation:
100
+ if not export_type:
101
+ raise typer.BadParameter(
102
+ "Export type is required when download type is annotation"
103
+ )
104
+ return get_client(api_key).dataset_download(pk, export_type)
105
+ get_client(api_key).dataset_download_files(pk)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ app()
unitlab/utils.py ADDED
@@ -0,0 +1,65 @@
1
+ import logging
2
+ from configparser import ConfigParser
3
+ from pathlib import Path
4
+
5
+ import requests
6
+
7
+ from . import exceptions
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ CONFIG_FILE_PATH = Path.home() / ".unitlab" / "credentials"
12
+
13
+
14
+ def handle_exceptions(f):
15
+ def throw_exception(*args, **kwargs):
16
+ try:
17
+ r = f(*args, **kwargs)
18
+ if r.status_code == 401:
19
+ raise exceptions.AuthenticationError("Authentication failed")
20
+ r.raise_for_status()
21
+ return r.json()
22
+ except requests.exceptions.RequestException as e:
23
+ raise exceptions.NetworkError(str(e))
24
+
25
+ return throw_exception
26
+
27
+
28
+ def write_config(api_key: str, api_url: str):
29
+ config = ConfigParser()
30
+ config.add_section("default")
31
+ config.set("default", "api_key", api_key)
32
+ config.set("default", "api_url", api_url)
33
+
34
+ CONFIG_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
35
+ with open(CONFIG_FILE_PATH, "w") as configfile:
36
+ config.write(configfile)
37
+ logger.info(f"Credentials saved to {CONFIG_FILE_PATH}")
38
+
39
+
40
+ def read_config():
41
+ if not CONFIG_FILE_PATH.exists():
42
+ raise exceptions.ConfigurationError(
43
+ f"No configuration file found at {CONFIG_FILE_PATH}. Please run `unitlab configure --help` for more information."
44
+ )
45
+ config = ConfigParser()
46
+ config.read(CONFIG_FILE_PATH)
47
+ return config
48
+
49
+
50
+ def get_api_key() -> str:
51
+ config = read_config()
52
+ try:
53
+ return config.get("default", "api_key")
54
+ except Exception:
55
+ raise exceptions.ConfigurationError(
56
+ f"Key `api_key` not found in {CONFIG_FILE_PATH}. Please run `unitlab configure` or provide the api-key using the --api-key option."
57
+ )
58
+
59
+
60
+ def get_api_url() -> str:
61
+ config = read_config()
62
+ try:
63
+ return config.get("default", "api_url")
64
+ except Exception:
65
+ return "https://api.unitlab.ai"
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: unitlab
3
+ Version: 2.3.0
4
+ Home-page: https://github.com/teamunitlab/unitlab-sdk
5
+ Author: Unitlab Inc.
6
+ Author-email: team@unitlab.ai
7
+ License: MIT
8
+ Keywords: unitlab-sdk
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ License-File: LICENSE.md
18
+ Requires-Dist: aiohttp
19
+ Requires-Dist: aiofiles
20
+ Requires-Dist: requests
21
+ Requires-Dist: tqdm
22
+ Requires-Dist: typer
23
+ Requires-Dist: validators
24
+ Dynamic: author
25
+ Dynamic: author-email
26
+ Dynamic: classifier
27
+ Dynamic: home-page
28
+ Dynamic: keywords
29
+ Dynamic: license
30
+ Dynamic: license-file
31
+ Dynamic: requires-dist
@@ -0,0 +1,12 @@
1
+ unitlab/__init__.py,sha256=Wtk5kQ_MTlxtd3mxJIn2qHVK5URrVcasMMPjD3BtrVM,214
2
+ unitlab/__main__.py,sha256=6Hs2PV7EYc5Tid4g4OtcLXhqVHiNYTGzSBdoOnW2HXA,29
3
+ unitlab/client.py,sha256=j8m0An4Bt3ARA1ps7P2o-NLcfWFPoaXG_PxIdBDAEpQ,8374
4
+ unitlab/exceptions.py,sha256=68Tr6LreEzjQ3Vns8HAaWdtewtkNUJOvPazbf6NSnXU,950
5
+ unitlab/main.py,sha256=3_awGLQ39dOA4WpOLkngzTK1X9ttOs9avh4PvJFlH34,3039
6
+ unitlab/utils.py,sha256=U95JqeUvKP0p5Ka0KIar0e8Uqe_4TZmZ7N68UdEGfpk,1888
7
+ unitlab-2.3.0.dist-info/licenses/LICENSE.md,sha256=Gn7RRvByorAcAaM-WbyUpsgi5ED1-bKFFshbWfYYz2Y,1069
8
+ unitlab-2.3.0.dist-info/METADATA,sha256=9gk8MoNLgV1jPR9TdT_NSvM8wqAqxU10isgBNjQzgNY,903
9
+ unitlab-2.3.0.dist-info/WHEEL,sha256=1tXe9gY0PYatrMPMDd6jXqjfpz_B-Wqm32CPfRC58XU,91
10
+ unitlab-2.3.0.dist-info/entry_points.txt,sha256=ig-PjKEqSCj3UTdyANgEi4tsAU84DyXdaOJ02NHX4bY,45
11
+ unitlab-2.3.0.dist-info/top_level.txt,sha256=Al4ZlTYE3fTJK2o6YLCDMH5_DjuQkffRBMxgmWbKaqQ,8
12
+ unitlab-2.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (77.0.3)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ unitlab = unitlab.main:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Team Unitlab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ unitlab