diff --git a/.circleci/config.yml b/.circleci/config.yml index da31c5c..11c6c1b 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,7 +4,7 @@ version: 2.1 jobs: build_test: docker: - - image: cimg/python:3.6 + - image: cimg/python:3.8 resource_class: small steps: - checkout # checkout source code to working directory @@ -17,11 +17,11 @@ jobs: - run: name: Black Formatting Check # Only validation, without re-formatting command: | - black --check -t py36 . + black --check --exclude 'scaleapi/api_client/*' -t py38 . - run: name: isort Import Ordering Check # Only validation, without re-formatting command: | - isort --check-only --profile black . + isort --sg 'scaleapi/api_client/*' --check-only --profile black . - run: name: Flake8 Lint Check # Uses setup.cfg for configuration command: | @@ -46,7 +46,7 @@ jobs: twine check --strict dist/* pypi_publish: docker: - - image: cimg/python:3.6 + - image: cimg/python:3.8 steps: - checkout # checkout source code to working directory - run: diff --git a/.openapi-generator-ignore b/.openapi-generator-ignore new file mode 100644 index 0000000..94e1e31 --- /dev/null +++ b/.openapi-generator-ignore @@ -0,0 +1,2 @@ +scaleapi/__init__.py +scaleapi/api_client/v2/models/annotation.py diff --git a/.openapi-generator/FILES b/.openapi-generator/FILES new file mode 100644 index 0000000..3952232 --- /dev/null +++ b/.openapi-generator/FILES @@ -0,0 +1,55 @@ +scaleapi/api_client/__init__.py +scaleapi/api_client/v2/__init__.py +scaleapi/api_client/v2/api/__init__.py +scaleapi/api_client/v2/api/v2_api.py +scaleapi/api_client/v2/api_client.py +scaleapi/api_client/v2/api_response.py +scaleapi/api_client/v2/configuration.py +scaleapi/api_client/v2/exceptions.py +scaleapi/api_client/v2/models/__init__.py +scaleapi/api_client/v2/models/annotation_category.py +scaleapi/api_client/v2/models/annotation_category_multiple.py +scaleapi/api_client/v2/models/annotation_category_multiple_properties.py +scaleapi/api_client/v2/models/annotation_category_properties.py +scaleapi/api_client/v2/models/annotation_integer.py +scaleapi/api_client/v2/models/annotation_integer_properties.py +scaleapi/api_client/v2/models/annotation_metadata.py +scaleapi/api_client/v2/models/annotation_text.py +scaleapi/api_client/v2/models/annotation_text_properties.py +scaleapi/api_client/v2/models/annotation_type.py +scaleapi/api_client/v2/models/audio_file.py +scaleapi/api_client/v2/models/base_annotation.py +scaleapi/api_client/v2/models/batch.py +scaleapi/api_client/v2/models/delivery.py +scaleapi/api_client/v2/models/detailed_file.py +scaleapi/api_client/v2/models/error_detail.py +scaleapi/api_client/v2/models/error_type.py +scaleapi/api_client/v2/models/expandable.py +scaleapi/api_client/v2/models/expandable_annotation.py +scaleapi/api_client/v2/models/expandable_batch.py +scaleapi/api_client/v2/models/expandable_delivery.py +scaleapi/api_client/v2/models/expandable_enum_deliveries.py +scaleapi/api_client/v2/models/expandable_enum_delivery.py +scaleapi/api_client/v2/models/expandable_enum_task.py +scaleapi/api_client/v2/models/expandable_project.py +scaleapi/api_client/v2/models/file.py +scaleapi/api_client/v2/models/get_delivered_tasks_response.py +scaleapi/api_client/v2/models/get_deliveries_response.py +scaleapi/api_client/v2/models/get_task500_response.py +scaleapi/api_client/v2/models/get_tasks_response.py +scaleapi/api_client/v2/models/image_file.py +scaleapi/api_client/v2/models/message.py +scaleapi/api_client/v2/models/message_content.py +scaleapi/api_client/v2/models/message_role.py +scaleapi/api_client/v2/models/model_parameters.py +scaleapi/api_client/v2/models/option.py +scaleapi/api_client/v2/models/project.py +scaleapi/api_client/v2/models/reference_text.py +scaleapi/api_client/v2/models/submission.py +scaleapi/api_client/v2/models/task.py +scaleapi/api_client/v2/models/task_status.py +scaleapi/api_client/v2/models/thread.py +scaleapi/api_client/v2/models/turn.py +scaleapi/api_client/v2/models/v1_task_task_id_get200_response.py +scaleapi/api_client/v2/models/v1_task_task_id_get200_response_response.py +scaleapi/api_client/v2/rest.py diff --git a/.openapi-generator/VERSION b/.openapi-generator/VERSION new file mode 100644 index 0000000..b23eb27 --- /dev/null +++ b/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.11.0 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 384798f..05b4e14 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,41 +1,48 @@ default_language_version: - python: python3.6 + python: python3.8 default_stages: [commit] repos: -- repo: https://github.com/pre-commit/pre-commit-hooks + - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-added-large-files - - id: check-yaml - - id: check-case-conflict -- repo: https://github.com/pycqa/isort + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-added-large-files + - id: check-yaml + - id: check-case-conflict + - repo: https://github.com/pycqa/isort rev: 5.8.0 hooks: - - id: isort + - id: isort name: isort args: ["--profile", "black"] -- repo: https://github.com/psf/black + exclude: ^scaleapi/api_client/ + - repo: https://github.com/psf/black rev: 20.8b1 hooks: - - id: black -- repo: https://github.com/PyCQA/flake8 + - id: black + exclude: ^scaleapi/api_client/ + - repo: https://github.com/PyCQA/flake8 rev: 3.8.4 hooks: - - id: flake8 -- repo: local + - id: flake8 + exclude: ^scaleapi/api_client/ + - repo: local hooks: - - id: pylint + - id: pylint name: pylint entry: pylint language: python types: [python] files: scaleapi/ + exclude: ^scaleapi/api_client/ additional_dependencies: - - 'pylint>=2.7.4' - - 'requests>=2.25.0' - - 'urllib3>=1.26.0' - - 'pytest>=6.2.2' - language_version: python3.6 + - "pylint>=2.7.4" + - "requests>=2.25.0" + - "urllib3>=1.26.0" + - "pytest>=6.2.2" + - "python_dateutil>=2.8.2" + - "pydantic>=2" + - "typing-extensions>=4.7.1" + language_version: python3.8 diff --git a/.pylintrc b/.pylintrc index c262559..1c29c22 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,4 +1,6 @@ [MASTER] +ignore-paths= + ^scaleapi/api_client/* disable= missing-module-docstring, too-few-public-methods, diff --git a/README.rst b/README.rst index 5758702..f2fb8cc 100644 --- a/README.rst +++ b/README.rst @@ -914,6 +914,58 @@ For example: print(err.message) # Parameter is invalid, reason: "attachments" is required +V2 API +______ + +If your project is using V2 API, you can use the ``.v2`` API client and also ``v2_get_tasks()`` to retrieve tasks in the V2 API format. See our `V2 API documentation`__. + +__ https://docs.genai.scale.com/get-started/quickstart + +.. list-table:: + :widths: 25 25 50 + :header-rows: 1 + + * - Method + - HTTP request + - Description + * - **get_task** + - **GET** /v2/task + - Get a Task + * - **get_tasks** + - **GET** /v2/tasks + - Get Multiple Tasks + * - **get_deliveries** + - **GET** /v2/deliveries + - List All Deliveries + * - **get_delivery** + - **GET** /v2/delivery + - Get Tasks in a Delivery + * - **get_annotation** + - **GET** /v2/annotation + - Get an Annotation + +For example: + +.. code-block:: python + + # Get a task with the V2 format + task = client.v2.get_task('30553edd0b6a93f8f05f0fee') + + # Get tasks in the V2 format (paged) + tasks = client.v2.get_tasks( + project_name = "My Project" + ) + + # Get tasks in the V2 format (generator) + tasks = client.v2_get_tasks( + project_name = "My Project" + ) + + # Iterating through the generator + for task in tasks: + # Download task or do something! + print(task.task_id) + Troubleshooting _______________ diff --git a/docs/dev_requirements.txt b/docs/dev_requirements.txt index f0c4120..7b424e3 100644 --- a/docs/dev_requirements.txt +++ b/docs/dev_requirements.txt @@ -4,4 +4,9 @@ pre-commit==2.11.1 isort>=5.7.0 pytest>=6.2.2 pylint>=2.7.2 -twine>=3.4.1 +twine==6.0.1 +pkginfo>=1.12.0 +urllib3>=1.26.0 +python_dateutil>=2.8.2 +pydantic>=2 +typing-extensions>=4.7.1 diff --git a/docs/developer_guide.md b/docs/developer_guide.md index 4589a2b..1e1dab8 100644 --- a/docs/developer_guide.md +++ b/docs/developer_guide.md @@ -12,23 +12,27 @@ $ git clone git@github.com:scaleapi/scaleapi-python-client.git If you use a virtual environment (via venv or conda), please activate it before installing the following packages. -_Python SDK v2+ supports only Python 3.6+_ +_Python SDK v2+ supports only Python 3.8+_ ```bash $ pip install -r docs/dev_requirements.txt ``` + ### 3. Setup pre-commit Assure pre-commit[1] is installed: + ```bash $ pre-commit --version # pre-commit 2.11.1 ``` Configure pre-commit for the repo: + ```bash pre-commit install ``` + Now `pre-commit` will run automatically on `git commit`! ### 4. (Optional) VS Code Settings @@ -41,15 +45,14 @@ If you want to make those settings only apply to current workspace (not VS Code - Auto-formats python files on save according to `black` Append following lines to the json file: + ```json -"python.linting.enabled": true, -"python.linting.pylintEnabled": true, -"python.linting.flake8Enabled": true, -"python.formatting.provider": "black", -"[python]": { + "pylint.enabled": true, + "flake8.enabled": true, + "[python]": { "editor.formatOnSave": true, - "editor.defaultFormatter": "ms-python.python" - }, + "editor.defaultFormatter": "ms-python.black-formatter" + }, ``` In Python SDK we follow [Google's Python Docstring Guide](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for comments and docstring of modules, functions and classes. [Python Docstring Generator](https://marketplace.visualstudio.com/items?itemName=njpwerner.autodocstring) is a useful VS Code extension that helps to generate docstrings. @@ -95,10 +98,23 @@ tests/test_client.py::test_transcription_ok PASSED [ ......... ``` -#### 7. Deployment and Publishing of a new version +#### 7. Updating auto-generated v2 client + +The V2 API client is auto-generated from openapi.yaml using the v2_generator.json config. Run this to update the client: + +```bash +$ export SCALE_API_KEY="your_key" && SCALE_API_AUTH_HEADER=$(python -c "import urllib.parse; print(urllib.parse.quote('Bearer $SCALE_API_KEY'))") +$ openapi-generator-cli generate --auth "Authorization:$SCALE_API_AUTH_HEADER" --config v2_generator.json +``` + +Additionally, update the [Annotation model](../scaleapi/api_client/v2/models/annotation.py) `from_json` type discrimination if there are changes + +#### 8. Deployment and Publishing of a new version Please refer to [Deployment and Publishing Guide](pypi_update_guide.md) for details. -_____ + +--- + [1] pre-commit configuration is available in `.pre-commit-config.yaml` [2] Pylint configuration is available in `.pylintrc` diff --git a/openapitools.json b/openapitools.json new file mode 100644 index 0000000..973a005 --- /dev/null +++ b/openapitools.json @@ -0,0 +1,7 @@ +{ + "$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json", + "spaces": 2, + "generator-cli": { + "version": "7.11.0" + } +} diff --git a/scaleapi/__init__.py b/scaleapi/__init__.py index 240ac1a..5ae16e2 100644 --- a/scaleapi/__init__.py +++ b/scaleapi/__init__.py @@ -1,5 +1,12 @@ +from datetime import datetime from typing import IO, Dict, Generator, Generic, List, Optional, TypeVar, Union +from pydantic import Field, StrictStr +from typing_extensions import Annotated + +from scaleapi.api_client.v2 import ApiClient, Configuration, ExpandableEnumTask, Option +from scaleapi.api_client.v2 import Task as V2Task +from scaleapi.api_client.v2 import V2Api from scaleapi.batches import Batch, BatchStatus from scaleapi.evaluation_tasks import EvaluationTask from scaleapi.exceptions import ScaleInvalidRequest @@ -66,6 +73,11 @@ def __init__( cert=cert, ) + configuration = Configuration(access_token=api_key) + api_client = ApiClient(configuration) + api_client.user_agent = Api._generate_useragent(source) + self.v2 = V2Api(api_client) + def get_task(self, task_id: str) -> Task: """Fetches a task. Returns the associated task. @@ -111,7 +123,7 @@ def audit_task(self, task_id: str, accepted: bool, comments: str = None): for the audit status """ - payload = dict(accepted=accepted, comments=comments) + payload = {"accepted": accepted, "comments": comments} endpoint = f"task/{task_id}/audit" self.api.post_request(endpoint, body=payload) @@ -129,7 +141,7 @@ def update_task_unique_id(self, task_id: str, unique_id: str) -> Task: Returns: Task """ - payload = dict(unique_id=unique_id) + payload = {"unique_id": unique_id} endpoint = f"task/{task_id}/unique_id" return Task(self.api.post_request(endpoint, body=payload), self) @@ -318,6 +330,83 @@ def tasks(self, **kwargs) -> Tasklist: response.get("next_token"), ) + def v2_get_tasks( + self, + project_id: Optional[StrictStr] = None, + project_name: Optional[StrictStr] = None, + batch_id: Optional[StrictStr] = None, + batch_name: Optional[StrictStr] = None, + status: Optional[TaskStatus] = None, + completed_after: Optional[datetime] = None, + completed_before: Optional[datetime] = None, + limit: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]] = None, + expand: Optional[List[ExpandableEnumTask]] = None, + opts: Optional[List[Option]] = None, + ) -> Generator[V2Task, None, None]: + """Retrieve all tasks as a `generator` method, with the + given parameters. This methods handles pagination of + v2.get_tasks() method. + + In order to retrieve results as a list, please use: + `task_list = list(v2_get_tasks(...))` + + :param project_id: Scale's unique identifier for the + project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param batch_id: Scale's unique identifier for the + batch. + :type batch_id: str + :param batch_name: The name of the batch. + :type batch_name: str + :param status: The current status of the task, indicating + whether it is pending, completed, error, or canceled. + :type status: TaskStatus + :param completed_after: Tasks with a `completed_at` after + the given date will be returned. A timestamp formatted + as an ISO 8601 date-time string. + :type completed_after: datetime + :param completed_before: Tasks with a `completed_at` before + the given date will be returned. A timestamp formatted + as an ISO 8601 date-time string. + :type completed_before: datetime + :param limit: Limit the number of entities returned. + :type limit: int + :param expand: List of fields to + [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumTask] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + + Yields: + Generator[V2Task]: + Yields Task objects, can be iterated. + """ + + tasks_args = { + "project_id": project_id, + "project_name": project_name, + "batch_id": batch_id, + "batch_name": batch_name, + "status": status, + "completed_after": completed_after, + "completed_before": completed_before, + "limit": limit, + "expand": expand, + "opts": opts, + } + + next_token = None + has_more = True + + while has_more: + tasks_args["next_token"] = next_token + tasks = self.v2.get_tasks(**tasks_args) + yield from tasks.tasks + next_token = tasks.next_token + has_more = tasks.next_token is not None + def get_tasks( self, project_name: str = None, @@ -445,8 +534,7 @@ def get_tasks( tasks_args["next_token"] = next_token tasks = self.tasks(**tasks_args) - for task in tasks.docs: - yield task + yield from tasks.docs next_token = tasks.next_token has_more = tasks.has_more @@ -669,14 +757,14 @@ def create_batch( Batch: Created batch object """ endpoint = "batches" - payload = dict( - project=project, - name=batch_name, - calibration_batch=calibration_batch, - self_label_batch=self_label_batch, - callback=callback, - metadata=metadata or {}, - ) + payload = { + "project": project, + "name": batch_name, + "calibration_batch": calibration_batch, + "self_label_batch": self_label_batch, + "callback": callback, + "metadata": metadata or {}, + } batchdata = self.api.post_request(endpoint, body=payload) return Batch(batchdata, self) @@ -849,8 +937,7 @@ def get_batches( batches_args["status"] = batch_status.value batches = self.batches(**batches_args) - for batch in batches.docs: - yield batch + yield from batches.docs offset += batches.limit has_more = batches.has_more @@ -905,14 +992,14 @@ def create_project( Project: [description] """ endpoint = "projects" - payload = dict( - type=task_type.value, - name=project_name, - params=params, - rapid=rapid, - studio=studio, - datasetId=dataset_id, - ) + payload = { + "type": task_type.value, + "name": project_name, + "params": params, + "rapid": rapid, + "studio": studio, + "datasetId": dataset_id, + } projectdata = self.api.post_request(endpoint, body=payload) return Project(projectdata, self) @@ -1025,7 +1112,7 @@ def import_file(self, file_url: str, **kwargs) -> File: """ endpoint = "files/import" - payload = dict(file_url=file_url, **kwargs) + payload = {"file_url": file_url, **kwargs} filedata = self.api.post_request(endpoint, body=payload) return File(filedata, self) diff --git a/scaleapi/_version.py b/scaleapi/_version.py index 8829d8b..8852777 100644 --- a/scaleapi/_version.py +++ b/scaleapi/_version.py @@ -1,2 +1,2 @@ -__version__ = "2.15.14" +__version__ = "2.16.0" __package_name__ = "scaleapi" diff --git a/scaleapi/api_client/__init__.py b/scaleapi/api_client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scaleapi/api_client/v2/__init__.py b/scaleapi/api_client/v2/__init__.py new file mode 100644 index 0000000..a602032 --- /dev/null +++ b/scaleapi/api_client/v2/__init__.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +# flake8: noqa + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from scaleapi.api_client.v2.api.v2_api import V2Api + +# import ApiClient +from scaleapi.api_client.v2.api_response import ApiResponse +from scaleapi.api_client.v2.api_client import ApiClient +from scaleapi.api_client.v2.configuration import Configuration +from scaleapi.api_client.v2.exceptions import OpenApiException +from scaleapi.api_client.v2.exceptions import ApiTypeError +from scaleapi.api_client.v2.exceptions import ApiValueError +from scaleapi.api_client.v2.exceptions import ApiKeyError +from scaleapi.api_client.v2.exceptions import ApiAttributeError +from scaleapi.api_client.v2.exceptions import ApiException + +# import models into sdk package +from scaleapi.api_client.v2.models.annotation import Annotation +from scaleapi.api_client.v2.models.annotation_category import AnnotationCategory +from scaleapi.api_client.v2.models.annotation_category_multiple import AnnotationCategoryMultiple +from scaleapi.api_client.v2.models.annotation_category_multiple_properties import AnnotationCategoryMultipleProperties +from scaleapi.api_client.v2.models.annotation_category_properties import AnnotationCategoryProperties +from scaleapi.api_client.v2.models.annotation_integer import AnnotationInteger +from scaleapi.api_client.v2.models.annotation_integer_properties import AnnotationIntegerProperties +from scaleapi.api_client.v2.models.annotation_metadata import AnnotationMetadata +from scaleapi.api_client.v2.models.annotation_text import AnnotationText +from scaleapi.api_client.v2.models.annotation_text_properties import AnnotationTextProperties +from scaleapi.api_client.v2.models.annotation_type import AnnotationType +from scaleapi.api_client.v2.models.audio_file import AudioFile +from scaleapi.api_client.v2.models.base_annotation import BaseAnnotation +from scaleapi.api_client.v2.models.batch import Batch +from scaleapi.api_client.v2.models.delivery import Delivery +from scaleapi.api_client.v2.models.detailed_file import DetailedFile +from scaleapi.api_client.v2.models.error_detail import ErrorDetail +from scaleapi.api_client.v2.models.error_type import ErrorType +from scaleapi.api_client.v2.models.expandable import Expandable +from scaleapi.api_client.v2.models.expandable_annotation import ExpandableAnnotation +from scaleapi.api_client.v2.models.expandable_batch import ExpandableBatch +from scaleapi.api_client.v2.models.expandable_delivery import ExpandableDelivery +from scaleapi.api_client.v2.models.expandable_enum_deliveries import ExpandableEnumDeliveries +from scaleapi.api_client.v2.models.expandable_enum_delivery import ExpandableEnumDelivery +from scaleapi.api_client.v2.models.expandable_enum_task import ExpandableEnumTask +from scaleapi.api_client.v2.models.expandable_project import ExpandableProject +from scaleapi.api_client.v2.models.file import File +from scaleapi.api_client.v2.models.get_delivered_tasks_response import GetDeliveredTasksResponse +from scaleapi.api_client.v2.models.get_deliveries_response import GetDeliveriesResponse +from scaleapi.api_client.v2.models.get_task500_response import GetTask500Response +from scaleapi.api_client.v2.models.get_tasks_response import GetTasksResponse +from scaleapi.api_client.v2.models.image_file import ImageFile +from scaleapi.api_client.v2.models.message import Message +from scaleapi.api_client.v2.models.message_content import MessageContent +from scaleapi.api_client.v2.models.message_role import MessageRole +from scaleapi.api_client.v2.models.model_parameters import ModelParameters +from scaleapi.api_client.v2.models.option import Option +from scaleapi.api_client.v2.models.project import Project +from scaleapi.api_client.v2.models.reference_text import ReferenceText +from scaleapi.api_client.v2.models.submission import Submission +from scaleapi.api_client.v2.models.task import Task +from scaleapi.api_client.v2.models.task_status import TaskStatus +from scaleapi.api_client.v2.models.thread import Thread +from scaleapi.api_client.v2.models.turn import Turn +from scaleapi.api_client.v2.models.v1_task_task_id_get200_response import V1TaskTaskIdGet200Response +from scaleapi.api_client.v2.models.v1_task_task_id_get200_response_response import V1TaskTaskIdGet200ResponseResponse diff --git a/scaleapi/api_client/v2/api/__init__.py b/scaleapi/api_client/v2/api/__init__.py new file mode 100644 index 0000000..d1366c8 --- /dev/null +++ b/scaleapi/api_client/v2/api/__init__.py @@ -0,0 +1,4 @@ +# flake8: noqa + +# import apis into api package +from scaleapi.api_client.v2.api.v2_api import V2Api diff --git a/scaleapi/api_client/v2/api/v2_api.py b/scaleapi/api_client/v2/api/v2_api.py new file mode 100644 index 0000000..208a153 --- /dev/null +++ b/scaleapi/api_client/v2/api/v2_api.py @@ -0,0 +1,1816 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import datetime +from pydantic import Field, StrictStr +from typing import List, Optional +from typing_extensions import Annotated +from scaleapi.api_client.v2.models.annotation import Annotation +from scaleapi.api_client.v2.models.expandable_enum_deliveries import ExpandableEnumDeliveries +from scaleapi.api_client.v2.models.expandable_enum_delivery import ExpandableEnumDelivery +from scaleapi.api_client.v2.models.expandable_enum_task import ExpandableEnumTask +from scaleapi.api_client.v2.models.get_delivered_tasks_response import GetDeliveredTasksResponse +from scaleapi.api_client.v2.models.get_deliveries_response import GetDeliveriesResponse +from scaleapi.api_client.v2.models.get_tasks_response import GetTasksResponse +from scaleapi.api_client.v2.models.option import Option +from scaleapi.api_client.v2.models.task import Task +from scaleapi.api_client.v2.models.task_status import TaskStatus + +from scaleapi.api_client.v2.api_client import ApiClient, RequestSerialized +from scaleapi.api_client.v2.api_response import ApiResponse +from scaleapi.api_client.v2.rest import RESTResponseType + + +class V2Api: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def get_annotation( + self, + annotation_id: Annotated[StrictStr, Field(description="The unique identifier of the annotation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Annotation: + """Get an Annotation + + Retrieve an [Annotation](/core-resources/annotation) from its `id`. + + :param annotation_id: The unique identifier of the annotation. (required) + :type annotation_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_annotation_serialize( + annotation_id=annotation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Annotation", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_annotation_with_http_info( + self, + annotation_id: Annotated[StrictStr, Field(description="The unique identifier of the annotation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Annotation]: + """Get an Annotation + + Retrieve an [Annotation](/core-resources/annotation) from its `id`. + + :param annotation_id: The unique identifier of the annotation. (required) + :type annotation_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_annotation_serialize( + annotation_id=annotation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Annotation", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_annotation_without_preload_content( + self, + annotation_id: Annotated[StrictStr, Field(description="The unique identifier of the annotation.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get an Annotation + + Retrieve an [Annotation](/core-resources/annotation) from its `id`. + + :param annotation_id: The unique identifier of the annotation. (required) + :type annotation_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_annotation_serialize( + annotation_id=annotation_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Annotation", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_annotation_serialize( + self, + annotation_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if annotation_id is not None: + + _query_params.append(('annotation_id', annotation_id)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'basicAuth', + 'bearerAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/annotation', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_deliveries( + self, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + delivered_after: Annotated[Optional[datetime], Field(description="Deliveries with a `delivered_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + delivered_before: Annotated[Optional[datetime], Field(description="Deliveries with a `delivered_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + expand: Annotated[Optional[List[ExpandableEnumDeliveries]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> GetDeliveriesResponse: + """List All Deliveries + + Lists of [Deliveries](/core-resources/delivery) from a [Project](/core-resources/project). + + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param delivered_after: Deliveries with a `delivered_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type delivered_after: datetime + :param delivered_before: Deliveries with a `delivered_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type delivered_before: datetime + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumDeliveries] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_deliveries_serialize( + project_id=project_id, + project_name=project_name, + delivered_after=delivered_after, + delivered_before=delivered_before, + expand=expand, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetDeliveriesResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_deliveries_with_http_info( + self, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + delivered_after: Annotated[Optional[datetime], Field(description="Deliveries with a `delivered_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + delivered_before: Annotated[Optional[datetime], Field(description="Deliveries with a `delivered_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + expand: Annotated[Optional[List[ExpandableEnumDeliveries]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[GetDeliveriesResponse]: + """List All Deliveries + + Lists of [Deliveries](/core-resources/delivery) from a [Project](/core-resources/project). + + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param delivered_after: Deliveries with a `delivered_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type delivered_after: datetime + :param delivered_before: Deliveries with a `delivered_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type delivered_before: datetime + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumDeliveries] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_deliveries_serialize( + project_id=project_id, + project_name=project_name, + delivered_after=delivered_after, + delivered_before=delivered_before, + expand=expand, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetDeliveriesResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_deliveries_without_preload_content( + self, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + delivered_after: Annotated[Optional[datetime], Field(description="Deliveries with a `delivered_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + delivered_before: Annotated[Optional[datetime], Field(description="Deliveries with a `delivered_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + expand: Annotated[Optional[List[ExpandableEnumDeliveries]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List All Deliveries + + Lists of [Deliveries](/core-resources/delivery) from a [Project](/core-resources/project). + + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param delivered_after: Deliveries with a `delivered_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type delivered_after: datetime + :param delivered_before: Deliveries with a `delivered_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type delivered_before: datetime + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumDeliveries] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_deliveries_serialize( + project_id=project_id, + project_name=project_name, + delivered_after=delivered_after, + delivered_before=delivered_before, + expand=expand, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetDeliveriesResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_deliveries_serialize( + self, + project_id, + project_name, + delivered_after, + delivered_before, + expand, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'expand': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if project_id is not None: + + _query_params.append(('project_id', project_id)) + + if project_name is not None: + + _query_params.append(('project_name', project_name)) + + if delivered_after is not None: + if isinstance(delivered_after, datetime): + _query_params.append( + ( + 'delivered_after', + delivered_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('delivered_after', delivered_after)) + + if delivered_before is not None: + if isinstance(delivered_before, datetime): + _query_params.append( + ( + 'delivered_before', + delivered_before.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('delivered_before', delivered_before)) + + if expand is not None: + + _query_params.append(('expand', expand)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'basicAuth', + 'bearerAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/deliveries', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_delivery( + self, + delivery_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the delivery.")] = None, + delivery_name: Annotated[Optional[StrictStr], Field(description="The name of the delivery.")] = None, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + limit: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=1)]], Field(description="Limit the number of entities returned.")] = None, + next_token: Annotated[Optional[StrictStr], Field(description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request.")] = None, + expand: Annotated[Optional[List[ExpandableEnumDelivery]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> GetDeliveredTasksResponse: + """Get Tasks in a Delivery + + Retrieve multiple [Tasks](/core-resources/task) from a [Delivery](/core-resources/delivery). + + :param delivery_id: Scale's unique identifier for the delivery. + :type delivery_id: str + :param delivery_name: The name of the delivery. + :type delivery_name: str + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param limit: Limit the number of entities returned. + :type limit: int + :param next_token: A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request. + :type next_token: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumDelivery] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_delivery_serialize( + delivery_id=delivery_id, + delivery_name=delivery_name, + project_id=project_id, + project_name=project_name, + limit=limit, + next_token=next_token, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetDeliveredTasksResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_delivery_with_http_info( + self, + delivery_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the delivery.")] = None, + delivery_name: Annotated[Optional[StrictStr], Field(description="The name of the delivery.")] = None, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + limit: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=1)]], Field(description="Limit the number of entities returned.")] = None, + next_token: Annotated[Optional[StrictStr], Field(description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request.")] = None, + expand: Annotated[Optional[List[ExpandableEnumDelivery]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[GetDeliveredTasksResponse]: + """Get Tasks in a Delivery + + Retrieve multiple [Tasks](/core-resources/task) from a [Delivery](/core-resources/delivery). + + :param delivery_id: Scale's unique identifier for the delivery. + :type delivery_id: str + :param delivery_name: The name of the delivery. + :type delivery_name: str + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param limit: Limit the number of entities returned. + :type limit: int + :param next_token: A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request. + :type next_token: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumDelivery] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_delivery_serialize( + delivery_id=delivery_id, + delivery_name=delivery_name, + project_id=project_id, + project_name=project_name, + limit=limit, + next_token=next_token, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetDeliveredTasksResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_delivery_without_preload_content( + self, + delivery_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the delivery.")] = None, + delivery_name: Annotated[Optional[StrictStr], Field(description="The name of the delivery.")] = None, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + limit: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=1)]], Field(description="Limit the number of entities returned.")] = None, + next_token: Annotated[Optional[StrictStr], Field(description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request.")] = None, + expand: Annotated[Optional[List[ExpandableEnumDelivery]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get Tasks in a Delivery + + Retrieve multiple [Tasks](/core-resources/task) from a [Delivery](/core-resources/delivery). + + :param delivery_id: Scale's unique identifier for the delivery. + :type delivery_id: str + :param delivery_name: The name of the delivery. + :type delivery_name: str + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param limit: Limit the number of entities returned. + :type limit: int + :param next_token: A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request. + :type next_token: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumDelivery] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_delivery_serialize( + delivery_id=delivery_id, + delivery_name=delivery_name, + project_id=project_id, + project_name=project_name, + limit=limit, + next_token=next_token, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetDeliveredTasksResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_delivery_serialize( + self, + delivery_id, + delivery_name, + project_id, + project_name, + limit, + next_token, + expand, + opts, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'expand': 'multi', + 'opts': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if delivery_id is not None: + + _query_params.append(('delivery_id', delivery_id)) + + if delivery_name is not None: + + _query_params.append(('delivery_name', delivery_name)) + + if project_id is not None: + + _query_params.append(('project_id', project_id)) + + if project_name is not None: + + _query_params.append(('project_name', project_name)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if next_token is not None: + + _query_params.append(('next_token', next_token)) + + if expand is not None: + + _query_params.append(('expand', expand)) + + if opts is not None: + + _query_params.append(('opts', opts)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'basicAuth', + 'bearerAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/delivery', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_task( + self, + task_id: Annotated[StrictStr, Field(description="Scale's unique identifier for the task.")], + expand: Annotated[Optional[List[ExpandableEnumTask]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Task: + """Get a Task + + Retrieve a [Task](/core-resources/task) from its `task_id`. + + :param task_id: Scale's unique identifier for the task. (required) + :type task_id: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumTask] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_serialize( + task_id=task_id, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_task_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="Scale's unique identifier for the task.")], + expand: Annotated[Optional[List[ExpandableEnumTask]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Task]: + """Get a Task + + Retrieve a [Task](/core-resources/task) from its `task_id`. + + :param task_id: Scale's unique identifier for the task. (required) + :type task_id: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumTask] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_serialize( + task_id=task_id, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_task_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="Scale's unique identifier for the task.")], + expand: Annotated[Optional[List[ExpandableEnumTask]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Task + + Retrieve a [Task](/core-resources/task) from its `task_id`. + + :param task_id: Scale's unique identifier for the task. (required) + :type task_id: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumTask] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_serialize( + task_id=task_id, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_task_serialize( + self, + task_id, + expand, + opts, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'expand': 'multi', + 'opts': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if task_id is not None: + + _query_params.append(('task_id', task_id)) + + if expand is not None: + + _query_params.append(('expand', expand)) + + if opts is not None: + + _query_params.append(('opts', opts)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'basicAuth', + 'bearerAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/task', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_tasks( + self, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + batch_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the batch.")] = None, + batch_name: Annotated[Optional[StrictStr], Field(description="The name of the batch.")] = None, + status: Annotated[Optional[TaskStatus], Field(description="The current status of the task, indicating whether it is pending, completed, error, or canceled.")] = None, + completed_after: Annotated[Optional[datetime], Field(description="Tasks with a `completed_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + completed_before: Annotated[Optional[datetime], Field(description="Tasks with a `completed_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + limit: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=1)]], Field(description="Limit the number of entities returned.")] = None, + next_token: Annotated[Optional[StrictStr], Field(description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request.")] = None, + expand: Annotated[Optional[List[ExpandableEnumTask]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> GetTasksResponse: + """Get Multiple Tasks + + Retrieve multiple [Tasks](/core-resources/task) from a [Project](/core-resources/project) or [Batch](/core-resources/batch). + + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param batch_id: Scale's unique identifier for the batch. + :type batch_id: str + :param batch_name: The name of the batch. + :type batch_name: str + :param status: The current status of the task, indicating whether it is pending, completed, error, or canceled. + :type status: TaskStatus + :param completed_after: Tasks with a `completed_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type completed_after: datetime + :param completed_before: Tasks with a `completed_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type completed_before: datetime + :param limit: Limit the number of entities returned. + :type limit: int + :param next_token: A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request. + :type next_token: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumTask] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_tasks_serialize( + project_id=project_id, + project_name=project_name, + batch_id=batch_id, + batch_name=batch_name, + status=status, + completed_after=completed_after, + completed_before=completed_before, + limit=limit, + next_token=next_token, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetTasksResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_tasks_with_http_info( + self, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + batch_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the batch.")] = None, + batch_name: Annotated[Optional[StrictStr], Field(description="The name of the batch.")] = None, + status: Annotated[Optional[TaskStatus], Field(description="The current status of the task, indicating whether it is pending, completed, error, or canceled.")] = None, + completed_after: Annotated[Optional[datetime], Field(description="Tasks with a `completed_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + completed_before: Annotated[Optional[datetime], Field(description="Tasks with a `completed_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + limit: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=1)]], Field(description="Limit the number of entities returned.")] = None, + next_token: Annotated[Optional[StrictStr], Field(description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request.")] = None, + expand: Annotated[Optional[List[ExpandableEnumTask]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[GetTasksResponse]: + """Get Multiple Tasks + + Retrieve multiple [Tasks](/core-resources/task) from a [Project](/core-resources/project) or [Batch](/core-resources/batch). + + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param batch_id: Scale's unique identifier for the batch. + :type batch_id: str + :param batch_name: The name of the batch. + :type batch_name: str + :param status: The current status of the task, indicating whether it is pending, completed, error, or canceled. + :type status: TaskStatus + :param completed_after: Tasks with a `completed_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type completed_after: datetime + :param completed_before: Tasks with a `completed_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type completed_before: datetime + :param limit: Limit the number of entities returned. + :type limit: int + :param next_token: A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request. + :type next_token: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumTask] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_tasks_serialize( + project_id=project_id, + project_name=project_name, + batch_id=batch_id, + batch_name=batch_name, + status=status, + completed_after=completed_after, + completed_before=completed_before, + limit=limit, + next_token=next_token, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetTasksResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_tasks_without_preload_content( + self, + project_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the project.")] = None, + project_name: Annotated[Optional[StrictStr], Field(description="The name of the project.")] = None, + batch_id: Annotated[Optional[StrictStr], Field(description="Scale's unique identifier for the batch.")] = None, + batch_name: Annotated[Optional[StrictStr], Field(description="The name of the batch.")] = None, + status: Annotated[Optional[TaskStatus], Field(description="The current status of the task, indicating whether it is pending, completed, error, or canceled.")] = None, + completed_after: Annotated[Optional[datetime], Field(description="Tasks with a `completed_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + completed_before: Annotated[Optional[datetime], Field(description="Tasks with a `completed_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string.")] = None, + limit: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=1)]], Field(description="Limit the number of entities returned.")] = None, + next_token: Annotated[Optional[StrictStr], Field(description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request.")] = None, + expand: Annotated[Optional[List[ExpandableEnumTask]], Field(description="List of fields to [expand](/api-reference/expanding-entities) in the response.")] = None, + opts: Annotated[Optional[List[Option]], Field(description="List of properties to include in the task response.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get Multiple Tasks + + Retrieve multiple [Tasks](/core-resources/task) from a [Project](/core-resources/project) or [Batch](/core-resources/batch). + + :param project_id: Scale's unique identifier for the project. + :type project_id: str + :param project_name: The name of the project. + :type project_name: str + :param batch_id: Scale's unique identifier for the batch. + :type batch_id: str + :param batch_name: The name of the batch. + :type batch_name: str + :param status: The current status of the task, indicating whether it is pending, completed, error, or canceled. + :type status: TaskStatus + :param completed_after: Tasks with a `completed_at` after the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type completed_after: datetime + :param completed_before: Tasks with a `completed_at` before the given date will be returned. A timestamp formatted as an ISO 8601 date-time string. + :type completed_before: datetime + :param limit: Limit the number of entities returned. + :type limit: int + :param next_token: A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request. + :type next_token: str + :param expand: List of fields to [expand](/api-reference/expanding-entities) in the response. + :type expand: List[ExpandableEnumTask] + :param opts: List of properties to include in the task response. + :type opts: List[Option] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_tasks_serialize( + project_id=project_id, + project_name=project_name, + batch_id=batch_id, + batch_name=batch_name, + status=status, + completed_after=completed_after, + completed_before=completed_before, + limit=limit, + next_token=next_token, + expand=expand, + opts=opts, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "GetTasksResponse", + '500': "GetTask500Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_tasks_serialize( + self, + project_id, + project_name, + batch_id, + batch_name, + status, + completed_after, + completed_before, + limit, + next_token, + expand, + opts, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'expand': 'multi', + 'opts': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if project_id is not None: + + _query_params.append(('project_id', project_id)) + + if project_name is not None: + + _query_params.append(('project_name', project_name)) + + if batch_id is not None: + + _query_params.append(('batch_id', batch_id)) + + if batch_name is not None: + + _query_params.append(('batch_name', batch_name)) + + if status is not None: + + _query_params.append(('status', status.value)) + + if completed_after is not None: + if isinstance(completed_after, datetime): + _query_params.append( + ( + 'completed_after', + completed_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('completed_after', completed_after)) + + if completed_before is not None: + if isinstance(completed_before, datetime): + _query_params.append( + ( + 'completed_before', + completed_before.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('completed_before', completed_before)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if next_token is not None: + + _query_params.append(('next_token', next_token)) + + if expand is not None: + + _query_params.append(('expand', expand)) + + if opts is not None: + + _query_params.append(('opts', opts)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'basicAuth', + 'bearerAuth' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/v2/tasks', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) diff --git a/scaleapi/api_client/v2/api_client.py b/scaleapi/api_client/v2/api_client.py new file mode 100644 index 0000000..b6e36c2 --- /dev/null +++ b/scaleapi/api_client/v2/api_client.py @@ -0,0 +1,797 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import datetime +from dateutil.parser import parse +from enum import Enum +import decimal +import json +import mimetypes +import os +import re +import tempfile + +from urllib.parse import quote +from typing import Tuple, Optional, List, Dict, Union +from pydantic import SecretStr + +from scaleapi.api_client.v2.configuration import Configuration +from scaleapi.api_client.v2.api_response import ApiResponse, T as ApiResponseT +import scaleapi.api_client.v2.models +from scaleapi.api_client.v2 import rest +from scaleapi.api_client.v2.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'decimal': decimal.Decimal, + 'object': object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + if files: + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None or self.configuration.ignore_operation_servers: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query + + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + + except ApiException as e: + raise e + + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type, content_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is SecretStr, return obj.get_secret_value() + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is decimal.Decimal return string representation. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, Enum): + return obj.value + elif isinstance(obj, SecretStr): + return obj.get_secret_value() + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] + elif isinstance(obj, tuple): + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + elif isinstance(obj, decimal.Decimal): + return str(obj) + + elif isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')): + obj_dict = obj.to_dict() + else: + obj_dict = obj.__dict__ + + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } + + def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + :param content_type: content type of response. + + :return: deserialized object. + """ + + # fetch data from response object + if content_type is None: + try: + data = json.loads(response_text) + except ValueError: + data = response_text + elif re.match(r'^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE): + if response_text == "": + data = "" + else: + data = json.loads(response_text) + elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE): + data = response_text + else: + raise ApiException( + status=0, + reason="Unsupported content type: {0}".format(content_type) + ) + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith('List['): + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(scaleapi.api_client.v2.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + elif klass == decimal.Decimal: + return decimal.Decimal(data) + elif issubclass(klass, Enum): + return self.__deserialize_enum(data, klass) + else: + return self.__deserialize_model(data, klass) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, quote(str(value))) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(map(str, item)) for item in new_params]) + + def files_parameters( + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + ): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + for k, v in files.items(): + if isinstance(v, str): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + elif isinstance(v, bytes): + filename = k + filedata = v + elif isinstance(v, tuple): + filename, filedata = v + elif isinstance(v, list): + for file_param in v: + params.extend(self.files_parameters({k: file_param})) + continue + else: + raise ValueError("Unsupported file value") + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) + return params + + def select_header_accept(self, accepts: List[str]) -> Optional[str]: + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return None + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + handle file downloading + save response body into a tmp file and return the instance + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_enum(self, data, klass): + """Deserializes primitive type to enum. + + :param data: primitive type. + :param klass: class literal. + :return: enum value. + """ + try: + return klass(data) + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as `{1}`" + .format(data, klass) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/scaleapi/api_client/v2/api_response.py b/scaleapi/api_client/v2/api_response.py new file mode 100644 index 0000000..9bc7c11 --- /dev/null +++ b/scaleapi/api_client/v2/api_response.py @@ -0,0 +1,21 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") + + model_config = { + "arbitrary_types_allowed": True + } diff --git a/scaleapi/api_client/v2/configuration.py b/scaleapi/api_client/v2/configuration.py new file mode 100644 index 0000000..34139ee --- /dev/null +++ b/scaleapi/api_client/v2/configuration.py @@ -0,0 +1,598 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import copy +import http.client as httplib +import logging +from logging import FileHandler +import multiprocessing +import sys +from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict +from typing_extensions import NotRequired, Self + +import urllib3 + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +ServerVariablesT = Dict[str, str] + +GenericAuthSetting = TypedDict( + "GenericAuthSetting", + { + "type": str, + "in": str, + "key": str, + "value": str, + }, +) + + +OAuth2AuthSetting = TypedDict( + "OAuth2AuthSetting", + { + "type": Literal["oauth2"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +APIKeyAuthSetting = TypedDict( + "APIKeyAuthSetting", + { + "type": Literal["api_key"], + "in": str, + "key": str, + "value": Optional[str], + }, +) + + +BasicAuthSetting = TypedDict( + "BasicAuthSetting", + { + "type": Literal["basic"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": Optional[str], + }, +) + + +BearerFormatAuthSetting = TypedDict( + "BearerFormatAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "format": Literal["JWT"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +BearerAuthSetting = TypedDict( + "BearerAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +HTTPSignatureAuthSetting = TypedDict( + "HTTPSignatureAuthSetting", + { + "type": Literal["http-signature"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": None, + }, +) + + +AuthSettings = TypedDict( + "AuthSettings", + { + "basicAuth": BasicAuthSetting, + "bearerAuth": BearerAuthSetting, + }, + total=False, +) + + +class HostSettingVariable(TypedDict): + description: str + default_value: str + enum_values: List[str] + + +class HostSetting(TypedDict): + url: str + description: str + variables: NotRequired[Dict[str, HostSettingVariable]] + + +class Configuration: + """This class contains various settings of the API client. + + :param host: Base url. + :param ignore_operation_servers + Boolean to ignore operation servers for the API client. + Config will use `host` as the base url regardless of the operation servers. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum + values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + :param retries: Number of retries for API requests. + + :Example: + + HTTP Basic Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + http_basic_auth: + type: http + scheme: basic + + Configure API client with HTTP basic authentication: + +conf = scaleapi.api_client.v2.Configuration( + username='the-user', + password='the-password', +) + + """ + + _default: ClassVar[Optional[Self]] = None + + def __init__( + self, + host: Optional[str]=None, + api_key: Optional[Dict[str, str]]=None, + api_key_prefix: Optional[Dict[str, str]]=None, + username: Optional[str]=None, + password: Optional[str]=None, + access_token: Optional[str]=None, + server_index: Optional[int]=None, + server_variables: Optional[ServerVariablesT]=None, + server_operation_index: Optional[Dict[int, int]]=None, + server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, + ignore_operation_servers: bool=False, + ssl_ca_cert: Optional[str]=None, + retries: Optional[int] = None, + *, + debug: Optional[bool] = None, + ) -> None: + """Constructor + """ + self._base_path = "https://api.scale.com" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.ignore_operation_servers = ignore_operation_servers + """Ignore operation servers + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("scaleapi.api_client.v2") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler: Optional[FileHandler] = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + if debug is not None: + self.debug = debug + else: + self.__debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy: Optional[str] = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = retries + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + def __deepcopy__(self, memo: Dict[int, Any]) -> Self: + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name: str, value: Any) -> None: + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default: Optional[Self]) -> None: + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls) -> Self: + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls) -> Self: + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = cls() + return cls._default + + @property + def logger_file(self) -> Optional[str]: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value: Optional[str]) -> None: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self) -> bool: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value: bool) -> None: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self) -> str: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value: str) -> None: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + return None + + def get_basic_auth_token(self) -> Optional[str]: + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self)-> AuthSettings: + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth: AuthSettings = {} + if self.username is not None and self.password is not None: + auth['basicAuth'] = { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + } + if self.access_token is not None: + auth['bearerAuth'] = { + 'type': 'bearer', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + return auth + + def to_debug_report(self) -> str: + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 0.0.1\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self) -> List[HostSetting]: + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "https://api.scale.com", + 'description': "No description provided", + } + ] + + def get_host_from_settings( + self, + index: Optional[int], + variables: Optional[ServerVariablesT]=None, + servers: Optional[List[HostSetting]]=None, + ) -> str: + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self) -> str: + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value: str) -> None: + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/scaleapi/api_client/v2/exceptions.py b/scaleapi/api_client/v2/exceptions.py new file mode 100644 index 0000000..40dc419 --- /dev/null +++ b/scaleapi/api_client/v2/exceptions.py @@ -0,0 +1,216 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from typing import Any, Optional +from typing_extensions import Self + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + + if http_resp: + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass + self.headers = http_resp.getheaders() + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + # Added new conditions for 409 and 422 + if http_resp.status == 409: + raise ConflictException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 422: + raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) + + return error_message + + +class BadRequestException(ApiException): + pass + + +class NotFoundException(ApiException): + pass + + +class UnauthorizedException(ApiException): + pass + + +class ForbiddenException(ApiException): + pass + + +class ServiceException(ApiException): + pass + + +class ConflictException(ApiException): + """Exception for HTTP 409 Conflict.""" + pass + + +class UnprocessableEntityException(ApiException): + """Exception for HTTP 422 Unprocessable Entity.""" + pass + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/scaleapi/api_client/v2/models/__init__.py b/scaleapi/api_client/v2/models/__init__.py new file mode 100644 index 0000000..945d0dc --- /dev/null +++ b/scaleapi/api_client/v2/models/__init__.py @@ -0,0 +1,62 @@ +# coding: utf-8 + +# flake8: noqa +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +# import models into model package +from scaleapi.api_client.v2.models.annotation import Annotation +from scaleapi.api_client.v2.models.annotation_category import AnnotationCategory +from scaleapi.api_client.v2.models.annotation_category_multiple import AnnotationCategoryMultiple +from scaleapi.api_client.v2.models.annotation_category_multiple_properties import AnnotationCategoryMultipleProperties +from scaleapi.api_client.v2.models.annotation_category_properties import AnnotationCategoryProperties +from scaleapi.api_client.v2.models.annotation_integer import AnnotationInteger +from scaleapi.api_client.v2.models.annotation_integer_properties import AnnotationIntegerProperties +from scaleapi.api_client.v2.models.annotation_metadata import AnnotationMetadata +from scaleapi.api_client.v2.models.annotation_text import AnnotationText +from scaleapi.api_client.v2.models.annotation_text_properties import AnnotationTextProperties +from scaleapi.api_client.v2.models.annotation_type import AnnotationType +from scaleapi.api_client.v2.models.audio_file import AudioFile +from scaleapi.api_client.v2.models.base_annotation import BaseAnnotation +from scaleapi.api_client.v2.models.batch import Batch +from scaleapi.api_client.v2.models.delivery import Delivery +from scaleapi.api_client.v2.models.detailed_file import DetailedFile +from scaleapi.api_client.v2.models.error_detail import ErrorDetail +from scaleapi.api_client.v2.models.error_type import ErrorType +from scaleapi.api_client.v2.models.expandable import Expandable +from scaleapi.api_client.v2.models.expandable_annotation import ExpandableAnnotation +from scaleapi.api_client.v2.models.expandable_batch import ExpandableBatch +from scaleapi.api_client.v2.models.expandable_delivery import ExpandableDelivery +from scaleapi.api_client.v2.models.expandable_enum_deliveries import ExpandableEnumDeliveries +from scaleapi.api_client.v2.models.expandable_enum_delivery import ExpandableEnumDelivery +from scaleapi.api_client.v2.models.expandable_enum_task import ExpandableEnumTask +from scaleapi.api_client.v2.models.expandable_project import ExpandableProject +from scaleapi.api_client.v2.models.file import File +from scaleapi.api_client.v2.models.get_delivered_tasks_response import GetDeliveredTasksResponse +from scaleapi.api_client.v2.models.get_deliveries_response import GetDeliveriesResponse +from scaleapi.api_client.v2.models.get_task500_response import GetTask500Response +from scaleapi.api_client.v2.models.get_tasks_response import GetTasksResponse +from scaleapi.api_client.v2.models.image_file import ImageFile +from scaleapi.api_client.v2.models.message import Message +from scaleapi.api_client.v2.models.message_content import MessageContent +from scaleapi.api_client.v2.models.message_role import MessageRole +from scaleapi.api_client.v2.models.model_parameters import ModelParameters +from scaleapi.api_client.v2.models.option import Option +from scaleapi.api_client.v2.models.project import Project +from scaleapi.api_client.v2.models.reference_text import ReferenceText +from scaleapi.api_client.v2.models.submission import Submission +from scaleapi.api_client.v2.models.task import Task +from scaleapi.api_client.v2.models.task_status import TaskStatus +from scaleapi.api_client.v2.models.thread import Thread +from scaleapi.api_client.v2.models.turn import Turn +from scaleapi.api_client.v2.models.v1_task_task_id_get200_response import V1TaskTaskIdGet200Response +from scaleapi.api_client.v2.models.v1_task_task_id_get200_response_response import V1TaskTaskIdGet200ResponseResponse diff --git a/scaleapi/api_client/v2/models/annotation.py b/scaleapi/api_client/v2/models/annotation.py new file mode 100644 index 0000000..fbd475e --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation.py @@ -0,0 +1,262 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations + +import json +import pprint +from typing import Any, Dict, List, Optional, Set, Union + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + StrictStr, + ValidationError, + field_validator, +) +from typing_extensions import Literal, Self + +ANNOTATION_ONE_OF_SCHEMAS = [ + "AnnotationCategory", + "AnnotationCategoryMultiple", + "AnnotationInteger", + "AnnotationText", +] + + +class Annotation(BaseModel): + """ + Represents a generic annotation. + """ + + # data type: AnnotationInteger + oneof_schema_1_validator: Optional[AnnotationInteger] = None + # data type: AnnotationText + oneof_schema_2_validator: Optional[AnnotationText] = None + # data type: AnnotationCategory + oneof_schema_3_validator: Optional[AnnotationCategory] = None + # data type: AnnotationCategoryMultiple + oneof_schema_4_validator: Optional[AnnotationCategoryMultiple] = None + actual_instance: Optional[ + Union[ + AnnotationCategory, + AnnotationCategoryMultiple, + AnnotationInteger, + AnnotationText, + ] + ] = None + one_of_schemas: Set[str] = { + "AnnotationCategory", + "AnnotationCategoryMultiple", + "AnnotationInteger", + "AnnotationText", + } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + discriminator_value_class_map: Dict[str, Any] = {} + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError( + "If a position argument is used, only 1 is allowed to set `actual_instance`" + ) + if kwargs: + raise ValueError( + "If a position argument is used, keyword arguments cannot be used." + ) + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator("actual_instance") + def actual_instance_must_validate_oneof(cls, v): + instance = Annotation.model_construct() + error_messages = [] + match = 0 + # validate data type: AnnotationInteger + if not isinstance(v, AnnotationInteger): + error_messages.append( + f"Error! Input type `{type(v)}` is not `AnnotationInteger`" + ) + else: + match += 1 + # validate data type: AnnotationText + if not isinstance(v, AnnotationText): + error_messages.append( + f"Error! Input type `{type(v)}` is not `AnnotationText`" + ) + else: + match += 1 + # validate data type: AnnotationCategory + if not isinstance(v, AnnotationCategory): + error_messages.append( + f"Error! Input type `{type(v)}` is not `AnnotationCategory`" + ) + else: + match += 1 + # validate data type: AnnotationCategoryMultiple + if not isinstance(v, AnnotationCategoryMultiple): + error_messages.append( + f"Error! Input type `{type(v)}` is not `AnnotationCategoryMultiple`" + ) + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError( + "Multiple matches found when setting `actual_instance` in Annotation with oneOf schemas: AnnotationCategory, AnnotationCategoryMultiple, AnnotationInteger, AnnotationText. Details: " + + ", ".join(error_messages) + ) + elif match == 0: + # no match + raise ValueError( + "No match found when setting `actual_instance` in Annotation with oneOf schemas: AnnotationCategory, AnnotationCategoryMultiple, AnnotationInteger, AnnotationText. Details: " + + ", ".join(error_messages) + ) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + + data = json.loads(json_str) if isinstance(json_str, str) else json_str + annotation_type = data.get("type") if isinstance(data, dict) else None + + # https://github.com/swagger-api/swagger-codegen/issues/10962 + try: + if annotation_type == "integer": + instance.actual_instance = AnnotationInteger.from_json(json_str) + return instance + elif annotation_type == "text": + instance.actual_instance = AnnotationText.from_json(json_str) + return instance + elif annotation_type == "category": + instance.actual_instance = AnnotationCategory.from_json(json_str) + return instance + elif annotation_type == "category_multiple": + instance.actual_instance = AnnotationCategoryMultiple.from_json( + json_str + ) + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + raise ValueError( + "Can't discriminate annotation_type. Details: " + + ", ".join(error_messages) + ) + + match = 0 + + # deserialize data into AnnotationInteger + try: + instance.actual_instance = AnnotationInteger.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into AnnotationText + try: + instance.actual_instance = AnnotationText.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into AnnotationCategory + try: + instance.actual_instance = AnnotationCategory.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into AnnotationCategoryMultiple + try: + instance.actual_instance = AnnotationCategoryMultiple.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError( + "Multiple matches found when deserializing the JSON string into Annotation with oneOf schemas: AnnotationCategory, AnnotationCategoryMultiple, AnnotationInteger, AnnotationText. Details: " + + ", ".join(error_messages) + ) + elif match == 0: + # no match + raise ValueError( + "No match found when deserializing the JSON string into Annotation with oneOf schemas: AnnotationCategory, AnnotationCategoryMultiple, AnnotationInteger, AnnotationText. Details: " + + ", ".join(error_messages) + ) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable( + self.actual_instance.to_json + ): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict( + self, + ) -> Optional[ + Union[ + Dict[str, Any], + AnnotationCategory, + AnnotationCategoryMultiple, + AnnotationInteger, + AnnotationText, + ] + ]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable( + self.actual_instance.to_dict + ): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + +from scaleapi.api_client.v2.models.annotation_category import AnnotationCategory +from scaleapi.api_client.v2.models.annotation_category_multiple import ( + AnnotationCategoryMultiple, +) +from scaleapi.api_client.v2.models.annotation_integer import AnnotationInteger +from scaleapi.api_client.v2.models.annotation_text import AnnotationText + +# TODO: Rewrite to not use raise_errors +Annotation.model_rebuild(raise_errors=False) diff --git a/scaleapi/api_client/v2/models/annotation_category.py b/scaleapi/api_client/v2/models/annotation_category.py new file mode 100644 index 0000000..97b111b --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_category.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationCategory(BaseModel): + """ + AnnotationCategory + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier for an annotation.") + key: StrictStr = Field(description="Key for the annotation.") + type: StrictStr = Field(description="The type of the value and the possible_values, if they exist.") + title: Optional[StrictStr] = Field(default=None, description="Title of the annotation.") + description: Optional[StrictStr] = Field(default=None, description="Further details about the question.") + labels: Optional[List[StrictStr]] = Field(default=None, description="String representation of the possible options.") + not_applicable: Optional[StrictBool] = Field(default=None, description="This is set when the annotation is not applicable in the context.") + cannot_assess: Optional[StrictBool] = Field(default=None, description="This is set when the annotation cannot be assessed in the context.") + metadata: Optional[AnnotationMetadata] = None + value: Optional[StrictStr] = Field(default=None, description="Single-select category annotation.") + possible_values: Optional[List[StrictStr]] = Field(default=None, description="The possible values for this annotation.") + __properties: ClassVar[List[str]] = ["id", "key", "type", "title", "description", "labels", "not_applicable", "cannot_assess", "metadata", "value", "possible_values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationCategory from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationCategory from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "key": obj.get("key"), + "type": obj.get("type"), + "title": obj.get("title"), + "description": obj.get("description"), + "labels": obj.get("labels"), + "not_applicable": obj.get("not_applicable"), + "cannot_assess": obj.get("cannot_assess"), + "metadata": AnnotationMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "value": obj.get("value"), + "possible_values": obj.get("possible_values") + }) + return _obj + +from scaleapi.api_client.v2.models.annotation_metadata import AnnotationMetadata +# TODO: Rewrite to not use raise_errors +AnnotationCategory.model_rebuild(raise_errors=False) diff --git a/scaleapi/api_client/v2/models/annotation_category_multiple.py b/scaleapi/api_client/v2/models/annotation_category_multiple.py new file mode 100644 index 0000000..ac4bedc --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_category_multiple.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationCategoryMultiple(BaseModel): + """ + AnnotationCategoryMultiple + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier for an annotation.") + key: StrictStr = Field(description="Key for the annotation.") + type: StrictStr = Field(description="The type of the value and the possible_values, if they exist.") + title: Optional[StrictStr] = Field(default=None, description="Title of the annotation.") + description: Optional[StrictStr] = Field(default=None, description="Further details about the question.") + labels: Optional[List[StrictStr]] = Field(default=None, description="String representation of the possible options.") + not_applicable: Optional[StrictBool] = Field(default=None, description="This is set when the annotation is not applicable in the context.") + cannot_assess: Optional[StrictBool] = Field(default=None, description="This is set when the annotation cannot be assessed in the context.") + metadata: Optional[AnnotationMetadata] = None + value: Optional[List[StrictStr]] = Field(default=None, description="Multi-select category annotation.") + possible_values: Optional[List[StrictStr]] = Field(default=None, description="Multi-select category annotation.") + __properties: ClassVar[List[str]] = ["id", "key", "type", "title", "description", "labels", "not_applicable", "cannot_assess", "metadata", "value", "possible_values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationCategoryMultiple from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationCategoryMultiple from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "key": obj.get("key"), + "type": obj.get("type"), + "title": obj.get("title"), + "description": obj.get("description"), + "labels": obj.get("labels"), + "not_applicable": obj.get("not_applicable"), + "cannot_assess": obj.get("cannot_assess"), + "metadata": AnnotationMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "value": obj.get("value"), + "possible_values": obj.get("possible_values") + }) + return _obj + +from scaleapi.api_client.v2.models.annotation_metadata import AnnotationMetadata +# TODO: Rewrite to not use raise_errors +AnnotationCategoryMultiple.model_rebuild(raise_errors=False) diff --git a/scaleapi/api_client/v2/models/annotation_category_multiple_properties.py b/scaleapi/api_client/v2/models/annotation_category_multiple_properties.py new file mode 100644 index 0000000..2de8510 --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_category_multiple_properties.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationCategoryMultipleProperties(BaseModel): + """ + AnnotationCategoryMultipleProperties + """ # noqa: E501 + value: Optional[List[StrictStr]] = Field(default=None, description="Multi-select category annotation.") + possible_values: Optional[List[StrictStr]] = Field(default=None, description="Multi-select category annotation.") + __properties: ClassVar[List[str]] = ["value", "possible_values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationCategoryMultipleProperties from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationCategoryMultipleProperties from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "value": obj.get("value"), + "possible_values": obj.get("possible_values") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/annotation_category_properties.py b/scaleapi/api_client/v2/models/annotation_category_properties.py new file mode 100644 index 0000000..723767a --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_category_properties.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationCategoryProperties(BaseModel): + """ + AnnotationCategoryProperties + """ # noqa: E501 + value: Optional[StrictStr] = Field(default=None, description="Single-select category annotation.") + possible_values: Optional[List[StrictStr]] = Field(default=None, description="The possible values for this annotation.") + __properties: ClassVar[List[str]] = ["value", "possible_values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationCategoryProperties from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationCategoryProperties from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "value": obj.get("value"), + "possible_values": obj.get("possible_values") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/annotation_integer.py b/scaleapi/api_client/v2/models/annotation_integer.py new file mode 100644 index 0000000..84a46a0 --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_integer.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationInteger(BaseModel): + """ + AnnotationInteger + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier for an annotation.") + key: StrictStr = Field(description="Key for the annotation.") + type: StrictStr = Field(description="The type of the value and the possible_values, if they exist.") + title: Optional[StrictStr] = Field(default=None, description="Title of the annotation.") + description: Optional[StrictStr] = Field(default=None, description="Further details about the question.") + labels: Optional[List[StrictStr]] = Field(default=None, description="String representation of the possible options.") + not_applicable: Optional[StrictBool] = Field(default=None, description="This is set when the annotation is not applicable in the context.") + cannot_assess: Optional[StrictBool] = Field(default=None, description="This is set when the annotation cannot be assessed in the context.") + metadata: Optional[AnnotationMetadata] = None + value: Optional[StrictInt] = Field(default=None, description="Integer type annotation value.") + possible_values: Optional[List[StrictInt]] = Field(default=None, description="The possible values for this annotation.") + __properties: ClassVar[List[str]] = ["id", "key", "type", "title", "description", "labels", "not_applicable", "cannot_assess", "metadata", "value", "possible_values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationInteger from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationInteger from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "key": obj.get("key"), + "type": obj.get("type"), + "title": obj.get("title"), + "description": obj.get("description"), + "labels": obj.get("labels"), + "not_applicable": obj.get("not_applicable"), + "cannot_assess": obj.get("cannot_assess"), + "metadata": AnnotationMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "value": obj.get("value"), + "possible_values": obj.get("possible_values") + }) + return _obj + +from scaleapi.api_client.v2.models.annotation_metadata import AnnotationMetadata +# TODO: Rewrite to not use raise_errors +AnnotationInteger.model_rebuild(raise_errors=False) diff --git a/scaleapi/api_client/v2/models/annotation_integer_properties.py b/scaleapi/api_client/v2/models/annotation_integer_properties.py new file mode 100644 index 0000000..e5e37f7 --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_integer_properties.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationIntegerProperties(BaseModel): + """ + AnnotationIntegerProperties + """ # noqa: E501 + value: Optional[StrictInt] = Field(default=None, description="Integer type annotation value.") + possible_values: Optional[List[StrictInt]] = Field(default=None, description="The possible values for this annotation.") + __properties: ClassVar[List[str]] = ["value", "possible_values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationIntegerProperties from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationIntegerProperties from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "value": obj.get("value"), + "possible_values": obj.get("possible_values") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/annotation_metadata.py b/scaleapi/api_client/v2/models/annotation_metadata.py new file mode 100644 index 0000000..e9ad023 --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_metadata.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationMetadata(BaseModel): + """ + AnnotationMetadata + """ # noqa: E501 + criteria: Optional[ExpandableAnnotation] = None + __properties: ClassVar[List[str]] = ["criteria"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationMetadata from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of criteria + if self.criteria: + _dict['criteria'] = self.criteria.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationMetadata from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "criteria": ExpandableAnnotation.from_dict(obj["criteria"]) if obj.get("criteria") is not None else None + }) + return _obj + +from scaleapi.api_client.v2.models.expandable_annotation import ExpandableAnnotation +# TODO: Rewrite to not use raise_errors +AnnotationMetadata.model_rebuild(raise_errors=False) diff --git a/scaleapi/api_client/v2/models/annotation_text.py b/scaleapi/api_client/v2/models/annotation_text.py new file mode 100644 index 0000000..f54ab03 --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_text.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationText(BaseModel): + """ + AnnotationText + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier for an annotation.") + key: StrictStr = Field(description="Key for the annotation.") + type: StrictStr = Field(description="The type of the value and the possible_values, if they exist.") + title: Optional[StrictStr] = Field(default=None, description="Title of the annotation.") + description: Optional[StrictStr] = Field(default=None, description="Further details about the question.") + labels: Optional[List[StrictStr]] = Field(default=None, description="String representation of the possible options.") + not_applicable: Optional[StrictBool] = Field(default=None, description="This is set when the annotation is not applicable in the context.") + cannot_assess: Optional[StrictBool] = Field(default=None, description="This is set when the annotation cannot be assessed in the context.") + metadata: Optional[AnnotationMetadata] = None + value: Optional[StrictStr] = Field(default=None, description="String type annotation value.") + __properties: ClassVar[List[str]] = ["id", "key", "type", "title", "description", "labels", "not_applicable", "cannot_assess", "metadata", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationText from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationText from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "key": obj.get("key"), + "type": obj.get("type"), + "title": obj.get("title"), + "description": obj.get("description"), + "labels": obj.get("labels"), + "not_applicable": obj.get("not_applicable"), + "cannot_assess": obj.get("cannot_assess"), + "metadata": AnnotationMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "value": obj.get("value") + }) + return _obj + +from scaleapi.api_client.v2.models.annotation_metadata import AnnotationMetadata +# TODO: Rewrite to not use raise_errors +AnnotationText.model_rebuild(raise_errors=False) diff --git a/scaleapi/api_client/v2/models/annotation_text_properties.py b/scaleapi/api_client/v2/models/annotation_text_properties.py new file mode 100644 index 0000000..15d3f3a --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_text_properties.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class AnnotationTextProperties(BaseModel): + """ + AnnotationTextProperties + """ # noqa: E501 + value: Optional[StrictStr] = Field(default=None, description="String type annotation value.") + __properties: ClassVar[List[str]] = ["value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AnnotationTextProperties from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AnnotationTextProperties from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "value": obj.get("value") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/annotation_type.py b/scaleapi/api_client/v2/models/annotation_type.py new file mode 100644 index 0000000..ae9b685 --- /dev/null +++ b/scaleapi/api_client/v2/models/annotation_type.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class AnnotationType(str, Enum): + """ + AnnotationType + """ + + """ + allowed enum values + """ + INTEGER = 'integer' + TEXT = 'text' + CATEGORY = 'category' + CATEGORY_MULTIPLE = 'category_multiple' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AnnotationType from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/audio_file.py b/scaleapi/api_client/v2/models/audio_file.py new file mode 100644 index 0000000..b62f52d --- /dev/null +++ b/scaleapi/api_client/v2/models/audio_file.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self + +class AudioFile(BaseModel): + """ + AudioFile + """ # noqa: E501 + mime_type: Optional[StrictStr] = Field(default=None, description="The MIME type of the content, such as application/json or image/png.") + scale_url: Optional[StrictStr] = Field(default=None, description="A URL string pointing to a resource.") + duration: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="The duration of the audio file in seconds.") + transcript: Optional[StrictStr] = Field(default=None, description="The transcript of the audio file.") + transcript_url: Optional[StrictStr] = Field(default=None, description="A URL string pointing to a resource.") + transcript_start: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="The start time of the transcript in seconds.") + transcript_end: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="The end time of the transcript in seconds.") + __properties: ClassVar[List[str]] = ["mime_type", "scale_url", "duration", "transcript", "transcript_url", "transcript_start", "transcript_end"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AudioFile from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AudioFile from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mime_type": obj.get("mime_type"), + "scale_url": obj.get("scale_url"), + "duration": obj.get("duration"), + "transcript": obj.get("transcript"), + "transcript_url": obj.get("transcript_url"), + "transcript_start": obj.get("transcript_start"), + "transcript_end": obj.get("transcript_end") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/base_annotation.py b/scaleapi/api_client/v2/models/base_annotation.py new file mode 100644 index 0000000..12c86dd --- /dev/null +++ b/scaleapi/api_client/v2/models/base_annotation.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.annotation_metadata import AnnotationMetadata +from typing import Optional, Set +from typing_extensions import Self + +class BaseAnnotation(BaseModel): + """ + BaseAnnotation + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier for an annotation.") + key: StrictStr = Field(description="Key for the annotation.") + type: StrictStr = Field(description="The type of the value and the possible_values, if they exist.") + title: Optional[StrictStr] = Field(default=None, description="Title of the annotation.") + description: Optional[StrictStr] = Field(default=None, description="Further details about the question.") + labels: Optional[List[StrictStr]] = Field(default=None, description="String representation of the possible options.") + not_applicable: Optional[StrictBool] = Field(default=None, description="This is set when the annotation is not applicable in the context.") + cannot_assess: Optional[StrictBool] = Field(default=None, description="This is set when the annotation cannot be assessed in the context.") + metadata: Optional[AnnotationMetadata] = None + __properties: ClassVar[List[str]] = ["id", "key", "type", "title", "description", "labels", "not_applicable", "cannot_assess", "metadata"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BaseAnnotation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BaseAnnotation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "key": obj.get("key"), + "type": obj.get("type"), + "title": obj.get("title"), + "description": obj.get("description"), + "labels": obj.get("labels"), + "not_applicable": obj.get("not_applicable"), + "cannot_assess": obj.get("cannot_assess"), + "metadata": AnnotationMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/batch.py b/scaleapi/api_client/v2/models/batch.py new file mode 100644 index 0000000..6dceb4e --- /dev/null +++ b/scaleapi/api_client/v2/models/batch.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Batch(BaseModel): + """ + Represents a batch. + """ # noqa: E501 + id: StrictStr = Field(description="A unique identifier for the batch.") + name: StrictStr = Field(description="The name of the batch.") + __properties: ClassVar[List[str]] = ["id", "name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Batch from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Batch from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/delivery.py b/scaleapi/api_client/v2/models/delivery.py new file mode 100644 index 0000000..477fcb0 --- /dev/null +++ b/scaleapi/api_client/v2/models/delivery.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from scaleapi.api_client.v2.models.expandable_project import ExpandableProject +from typing import Optional, Set +from typing_extensions import Self + +class Delivery(BaseModel): + """ + Delivery + """ # noqa: E501 + id: StrictStr = Field(description="A unique identifier for the delivery.") + name: StrictStr = Field(description="The name of the delivery.") + task_count: StrictInt = Field(description="The number of tasks in the delivery.") + delivered_at: datetime = Field(description="A timestamp formatted as an ISO 8601 date-time string.") + project: ExpandableProject = Field(description="Project ID or [Project](/core-resources/project) associated with the delivery.") + __properties: ClassVar[List[str]] = ["id", "name", "task_count", "delivered_at", "project"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Delivery from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of project + if self.project: + _dict['project'] = self.project.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Delivery from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "task_count": obj.get("task_count"), + "delivered_at": obj.get("delivered_at"), + "project": ExpandableProject.from_dict(obj["project"]) if obj.get("project") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/detailed_file.py b/scaleapi/api_client/v2/models/detailed_file.py new file mode 100644 index 0000000..4eece34 --- /dev/null +++ b/scaleapi/api_client/v2/models/detailed_file.py @@ -0,0 +1,149 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from scaleapi.api_client.v2.models.audio_file import AudioFile +from scaleapi.api_client.v2.models.file import File +from scaleapi.api_client.v2.models.image_file import ImageFile +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +DETAILEDFILE_ONE_OF_SCHEMAS = ["AudioFile", "File", "ImageFile"] + +class DetailedFile(BaseModel): + """ + DetailedFile + """ + # data type: File + oneof_schema_1_validator: Optional[File] = None + # data type: ImageFile + oneof_schema_2_validator: Optional[ImageFile] = None + # data type: AudioFile + oneof_schema_3_validator: Optional[AudioFile] = None + actual_instance: Optional[Union[AudioFile, File, ImageFile]] = None + one_of_schemas: Set[str] = { "AudioFile", "File", "ImageFile" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = DetailedFile.model_construct() + error_messages = [] + match = 0 + # validate data type: File + if not isinstance(v, File): + error_messages.append(f"Error! Input type `{type(v)}` is not `File`") + else: + match += 1 + # validate data type: ImageFile + if not isinstance(v, ImageFile): + error_messages.append(f"Error! Input type `{type(v)}` is not `ImageFile`") + else: + match += 1 + # validate data type: AudioFile + if not isinstance(v, AudioFile): + error_messages.append(f"Error! Input type `{type(v)}` is not `AudioFile`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in DetailedFile with oneOf schemas: AudioFile, File, ImageFile. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in DetailedFile with oneOf schemas: AudioFile, File, ImageFile. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into File + try: + instance.actual_instance = File.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into ImageFile + try: + instance.actual_instance = ImageFile.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into AudioFile + try: + instance.actual_instance = AudioFile.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into DetailedFile with oneOf schemas: AudioFile, File, ImageFile. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into DetailedFile with oneOf schemas: AudioFile, File, ImageFile. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], AudioFile, File, ImageFile]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) diff --git a/scaleapi/api_client/v2/models/error_detail.py b/scaleapi/api_client/v2/models/error_detail.py new file mode 100644 index 0000000..78f2eee --- /dev/null +++ b/scaleapi/api_client/v2/models/error_detail.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.error_type import ErrorType +from typing import Optional, Set +from typing_extensions import Self + +class ErrorDetail(BaseModel): + """ + Details of the error on the task. Available when the task status is `error` + """ # noqa: E501 + type: Optional[ErrorType] = Field(default=None, description="Type of the error") + message: Optional[StrictStr] = Field(default=None, description="Details of the error message") + __properties: ClassVar[List[str]] = ["type", "message"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorDetail from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorDetail from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "message": obj.get("message") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/error_type.py b/scaleapi/api_client/v2/models/error_type.py new file mode 100644 index 0000000..443ebb7 --- /dev/null +++ b/scaleapi/api_client/v2/models/error_type.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class ErrorType(str, Enum): + """ + Type of the error + """ + + """ + allowed enum values + """ + UNSUPPORTED_LANGUAGE = 'UNSUPPORTED_LANGUAGE' + LANGUAGE_MISMATCH = 'LANGUAGE_MISMATCH' + PROMPT_LENGTH_EXCEEDED = 'PROMPT_LENGTH_EXCEEDED' + INVALID_CATEGORY = 'INVALID_CATEGORY' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ErrorType from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/expandable.py b/scaleapi/api_client/v2/models/expandable.py new file mode 100644 index 0000000..7ba53d4 --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable.py @@ -0,0 +1,36 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class Expandable(str, Enum): + """ + Entities that can be expanded from an ID to an object. + """ + + """ + allowed enum values + """ + PROJECT = 'project' + BATCH = 'batch' + DELIVERY = 'delivery' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Expandable from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/expandable_annotation.py b/scaleapi/api_client/v2/models/expandable_annotation.py new file mode 100644 index 0000000..c5d7f16 --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable_annotation.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +EXPANDABLEANNOTATION_ONE_OF_SCHEMAS = ["Annotation", "str"] + +class ExpandableAnnotation(BaseModel): + """ + ExpandableAnnotation + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = Field(default=None, description="Unique identifier for an annotation.") + # data type: Annotation + oneof_schema_2_validator: Optional[Annotation] = None + actual_instance: Optional[Union[Annotation, str]] = None + one_of_schemas: Set[str] = { "Annotation", "str" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = ExpandableAnnotation.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Annotation + if not isinstance(v, Annotation): + error_messages.append(f"Error! Input type `{type(v)}` is not `Annotation`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in ExpandableAnnotation with oneOf schemas: Annotation, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in ExpandableAnnotation with oneOf schemas: Annotation, str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Annotation + try: + instance.actual_instance = Annotation.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into ExpandableAnnotation with oneOf schemas: Annotation, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into ExpandableAnnotation with oneOf schemas: Annotation, str. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Annotation, str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + +from scaleapi.api_client.v2.models.annotation import Annotation +# TODO: Rewrite to not use raise_errors +ExpandableAnnotation.model_rebuild(raise_errors=False) diff --git a/scaleapi/api_client/v2/models/expandable_batch.py b/scaleapi/api_client/v2/models/expandable_batch.py new file mode 100644 index 0000000..646919e --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable_batch.py @@ -0,0 +1,138 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from scaleapi.api_client.v2.models.batch import Batch +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +EXPANDABLEBATCH_ONE_OF_SCHEMAS = ["Batch", "str"] + +class ExpandableBatch(BaseModel): + """ + Batch ID or [Batch](/core-resources/batch) associated with the task. + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = Field(default=None, description="A unique identifier for the batch.") + # data type: Batch + oneof_schema_2_validator: Optional[Batch] = None + actual_instance: Optional[Union[Batch, str]] = None + one_of_schemas: Set[str] = { "Batch", "str" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = ExpandableBatch.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Batch + if not isinstance(v, Batch): + error_messages.append(f"Error! Input type `{type(v)}` is not `Batch`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in ExpandableBatch with oneOf schemas: Batch, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in ExpandableBatch with oneOf schemas: Batch, str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Batch + try: + instance.actual_instance = Batch.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into ExpandableBatch with oneOf schemas: Batch, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into ExpandableBatch with oneOf schemas: Batch, str. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Batch, str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) diff --git a/scaleapi/api_client/v2/models/expandable_delivery.py b/scaleapi/api_client/v2/models/expandable_delivery.py new file mode 100644 index 0000000..16251a5 --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable_delivery.py @@ -0,0 +1,138 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from scaleapi.api_client.v2.models.delivery import Delivery +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +EXPANDABLEDELIVERY_ONE_OF_SCHEMAS = ["Delivery", "str"] + +class ExpandableDelivery(BaseModel): + """ + Delivery ID or [Delivery](/core-resources/delivery) associated with the task. + """ + # data type: Delivery + oneof_schema_1_validator: Optional[Delivery] = None + # data type: str + oneof_schema_2_validator: Optional[StrictStr] = Field(default=None, description="A unique identifier for the delivery.") + actual_instance: Optional[Union[Delivery, str]] = None + one_of_schemas: Set[str] = { "Delivery", "str" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = ExpandableDelivery.model_construct() + error_messages = [] + match = 0 + # validate data type: Delivery + if not isinstance(v, Delivery): + error_messages.append(f"Error! Input type `{type(v)}` is not `Delivery`") + else: + match += 1 + # validate data type: str + try: + instance.oneof_schema_2_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in ExpandableDelivery with oneOf schemas: Delivery, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in ExpandableDelivery with oneOf schemas: Delivery, str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into Delivery + try: + instance.actual_instance = Delivery.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into str + try: + # validation + instance.oneof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_2_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into ExpandableDelivery with oneOf schemas: Delivery, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into ExpandableDelivery with oneOf schemas: Delivery, str. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Delivery, str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) diff --git a/scaleapi/api_client/v2/models/expandable_enum_deliveries.py b/scaleapi/api_client/v2/models/expandable_enum_deliveries.py new file mode 100644 index 0000000..99c5678 --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable_enum_deliveries.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class ExpandableEnumDeliveries(str, Enum): + """ + Entities that can be expanded from an ID to an object. + """ + + """ + allowed enum values + """ + PROJECT = 'project' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ExpandableEnumDeliveries from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/expandable_enum_delivery.py b/scaleapi/api_client/v2/models/expandable_enum_delivery.py new file mode 100644 index 0000000..3b3bf9d --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable_enum_delivery.py @@ -0,0 +1,36 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class ExpandableEnumDelivery(str, Enum): + """ + Entities that can be expanded from an ID to an object. + """ + + """ + allowed enum values + """ + PROJECT = 'project' + BATCH = 'batch' + DELIVERY = 'delivery' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ExpandableEnumDelivery from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/expandable_enum_task.py b/scaleapi/api_client/v2/models/expandable_enum_task.py new file mode 100644 index 0000000..62781b7 --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable_enum_task.py @@ -0,0 +1,35 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class ExpandableEnumTask(str, Enum): + """ + Entities that can be expanded from an ID to an object. + """ + + """ + allowed enum values + """ + PROJECT = 'project' + BATCH = 'batch' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ExpandableEnumTask from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/expandable_project.py b/scaleapi/api_client/v2/models/expandable_project.py new file mode 100644 index 0000000..c57a368 --- /dev/null +++ b/scaleapi/api_client/v2/models/expandable_project.py @@ -0,0 +1,138 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from scaleapi.api_client.v2.models.project import Project +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +EXPANDABLEPROJECT_ONE_OF_SCHEMAS = ["Project", "str"] + +class ExpandableProject(BaseModel): + """ + Project ID or [Project](/core-resources/project) associated with the task. + """ + # data type: str + oneof_schema_1_validator: Optional[StrictStr] = Field(default=None, description="A unique identifier for the project.") + # data type: Project + oneof_schema_2_validator: Optional[Project] = None + actual_instance: Optional[Union[Project, str]] = None + one_of_schemas: Set[str] = { "Project", "str" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = ExpandableProject.model_construct() + error_messages = [] + match = 0 + # validate data type: str + try: + instance.oneof_schema_1_validator = v + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: Project + if not isinstance(v, Project): + error_messages.append(f"Error! Input type `{type(v)}` is not `Project`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in ExpandableProject with oneOf schemas: Project, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in ExpandableProject with oneOf schemas: Project, str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into str + try: + # validation + instance.oneof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.oneof_schema_1_validator + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into Project + try: + instance.actual_instance = Project.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into ExpandableProject with oneOf schemas: Project, str. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into ExpandableProject with oneOf schemas: Project, str. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], Project, str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) diff --git a/scaleapi/api_client/v2/models/file.py b/scaleapi/api_client/v2/models/file.py new file mode 100644 index 0000000..bfb8a99 --- /dev/null +++ b/scaleapi/api_client/v2/models/file.py @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBytes, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self + +class File(BaseModel): + """ + File + """ # noqa: E501 + content: Optional[Union[StrictBytes, StrictStr]] = Field(default=None, description="Base-64 encoded data") + mime_type: Optional[StrictStr] = Field(default=None, description="The MIME type of the content, such as application/json or image/png.") + scale_url: Optional[StrictStr] = Field(default=None, description="A URL string pointing to a resource.") + url: Optional[StrictStr] = Field(default=None, description="A URL string pointing to a resource.") + __properties: ClassVar[List[str]] = ["content", "mime_type", "scale_url", "url"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of File from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of File from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "content": obj.get("content"), + "mime_type": obj.get("mime_type"), + "scale_url": obj.get("scale_url"), + "url": obj.get("url") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/get_delivered_tasks_response.py b/scaleapi/api_client/v2/models/get_delivered_tasks_response.py new file mode 100644 index 0000000..092903d --- /dev/null +++ b/scaleapi/api_client/v2/models/get_delivered_tasks_response.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.expandable_delivery import ExpandableDelivery +from scaleapi.api_client.v2.models.task import Task +from typing import Optional, Set +from typing_extensions import Self + +class GetDeliveredTasksResponse(BaseModel): + """ + GetDeliveredTasksResponse + """ # noqa: E501 + delivery: Optional[ExpandableDelivery] = None + tasks: List[Task] = Field(description="Array of task objects") + next_token: Optional[StrictStr] = Field(default=None, description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request") + __properties: ClassVar[List[str]] = ["delivery", "tasks", "next_token"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetDeliveredTasksResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of delivery + if self.delivery: + _dict['delivery'] = self.delivery.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in tasks (list) + _items = [] + if self.tasks: + for _item_tasks in self.tasks: + if _item_tasks: + _items.append(_item_tasks.to_dict()) + _dict['tasks'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetDeliveredTasksResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "delivery": ExpandableDelivery.from_dict(obj["delivery"]) if obj.get("delivery") is not None else None, + "tasks": [Task.from_dict(_item) for _item in obj["tasks"]] if obj.get("tasks") is not None else None, + "next_token": obj.get("next_token") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/get_deliveries_response.py b/scaleapi/api_client/v2/models/get_deliveries_response.py new file mode 100644 index 0000000..96d3d5f --- /dev/null +++ b/scaleapi/api_client/v2/models/get_deliveries_response.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from scaleapi.api_client.v2.models.delivery import Delivery +from typing import Optional, Set +from typing_extensions import Self + +class GetDeliveriesResponse(BaseModel): + """ + GetDeliveriesResponse + """ # noqa: E501 + deliveries: List[Delivery] = Field(description="Array of delivery objects") + __properties: ClassVar[List[str]] = ["deliveries"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetDeliveriesResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in deliveries (list) + _items = [] + if self.deliveries: + for _item_deliveries in self.deliveries: + if _item_deliveries: + _items.append(_item_deliveries.to_dict()) + _dict['deliveries'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetDeliveriesResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "deliveries": [Delivery.from_dict(_item) for _item in obj["deliveries"]] if obj.get("deliveries") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/get_task500_response.py b/scaleapi/api_client/v2/models/get_task500_response.py new file mode 100644 index 0000000..2088c1c --- /dev/null +++ b/scaleapi/api_client/v2/models/get_task500_response.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self + +class GetTask500Response(BaseModel): + """ + GetTask500Response + """ # noqa: E501 + status_code: Optional[Union[StrictFloat, StrictInt]] = None + error: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["status_code", "error"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetTask500Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetTask500Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "status_code": obj.get("status_code"), + "error": obj.get("error") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/get_tasks_response.py b/scaleapi/api_client/v2/models/get_tasks_response.py new file mode 100644 index 0000000..2be5110 --- /dev/null +++ b/scaleapi/api_client/v2/models/get_tasks_response.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.task import Task +from typing import Optional, Set +from typing_extensions import Self + +class GetTasksResponse(BaseModel): + """ + GetTasksResponse + """ # noqa: E501 + tasks: List[Task] = Field(description="Array of task objects") + next_token: Optional[StrictStr] = Field(default=None, description="A token used to retrieve the next page of results if there are more. You can find the `next_token` in your last request") + __properties: ClassVar[List[str]] = ["tasks", "next_token"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of GetTasksResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in tasks (list) + _items = [] + if self.tasks: + for _item_tasks in self.tasks: + if _item_tasks: + _items.append(_item_tasks.to_dict()) + _dict['tasks'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of GetTasksResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "tasks": [Task.from_dict(_item) for _item in obj["tasks"]] if obj.get("tasks") is not None else None, + "next_token": obj.get("next_token") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/image_file.py b/scaleapi/api_client/v2/models/image_file.py new file mode 100644 index 0000000..e4e2607 --- /dev/null +++ b/scaleapi/api_client/v2/models/image_file.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ImageFile(BaseModel): + """ + ImageFile + """ # noqa: E501 + mime_type: Optional[StrictStr] = Field(default=None, description="The MIME type of the content, such as application/json or image/png.") + scale_url: Optional[StrictStr] = Field(default=None, description="A URL string pointing to a resource.") + url: Optional[StrictStr] = Field(default=None, description="A URL string pointing to a resource.") + name: Optional[StrictStr] = Field(default=None, description="The name of the image file.") + file_size_in_bytes: Optional[StrictInt] = Field(default=None, description="The size of the file in bytes.") + __properties: ClassVar[List[str]] = ["mime_type", "scale_url", "url", "name", "file_size_in_bytes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ImageFile from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ImageFile from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mime_type": obj.get("mime_type"), + "scale_url": obj.get("scale_url"), + "url": obj.get("url"), + "name": obj.get("name"), + "file_size_in_bytes": obj.get("file_size_in_bytes") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/message.py b/scaleapi/api_client/v2/models/message.py new file mode 100644 index 0000000..2a362a8 --- /dev/null +++ b/scaleapi/api_client/v2/models/message.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.annotation import Annotation +from scaleapi.api_client.v2.models.message_content import MessageContent +from scaleapi.api_client.v2.models.message_role import MessageRole +from scaleapi.api_client.v2.models.model_parameters import ModelParameters +from typing import Optional, Set +from typing_extensions import Self + +class Message(BaseModel): + """ + Message + """ # noqa: E501 + role: MessageRole = Field(description="The role of the sender in the conversation (e.g., user, assistant).") + content: MessageContent = Field(description="The content of the message, including text and any attachments.") + source_id: StrictStr = Field(description="A unique identifier for the source.") + model_parameters: Optional[ModelParameters] = None + annotations: List[Annotation] = Field(description="Array of annotations.") + __properties: ClassVar[List[str]] = ["role", "content", "source_id", "model_parameters", "annotations"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Message from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of content + if self.content: + _dict['content'] = self.content.to_dict() + # override the default output from pydantic by calling `to_dict()` of model_parameters + if self.model_parameters: + _dict['model_parameters'] = self.model_parameters.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in annotations (list) + _items = [] + if self.annotations: + for _item_annotations in self.annotations: + if _item_annotations: + _items.append(_item_annotations.to_dict()) + _dict['annotations'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Message from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "role": obj.get("role"), + "content": MessageContent.from_dict(obj["content"]) if obj.get("content") is not None else None, + "source_id": obj.get("source_id"), + "model_parameters": ModelParameters.from_dict(obj["model_parameters"]) if obj.get("model_parameters") is not None else None, + "annotations": [Annotation.from_dict(_item) for _item in obj["annotations"]] if obj.get("annotations") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/message_content.py b/scaleapi/api_client/v2/models/message_content.py new file mode 100644 index 0000000..9a2e029 --- /dev/null +++ b/scaleapi/api_client/v2/models/message_content.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.detailed_file import DetailedFile +from scaleapi.api_client.v2.models.reference_text import ReferenceText +from typing import Optional, Set +from typing_extensions import Self + +class MessageContent(BaseModel): + """ + MessageContent + """ # noqa: E501 + text: Optional[StrictStr] = Field(default=None, description="A plain text field.") + reference_texts: Optional[List[ReferenceText]] = Field(default=None, description="A list of files or attachments associated with the message.") + attachments: Optional[List[DetailedFile]] = Field(default=None, description="A list of files or attachments associated with the message.") + __properties: ClassVar[List[str]] = ["text", "reference_texts", "attachments"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of MessageContent from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in reference_texts (list) + _items = [] + if self.reference_texts: + for _item_reference_texts in self.reference_texts: + if _item_reference_texts: + _items.append(_item_reference_texts.to_dict()) + _dict['reference_texts'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in attachments (list) + _items = [] + if self.attachments: + for _item_attachments in self.attachments: + if _item_attachments: + _items.append(_item_attachments.to_dict()) + _dict['attachments'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of MessageContent from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "text": obj.get("text"), + "reference_texts": [ReferenceText.from_dict(_item) for _item in obj["reference_texts"]] if obj.get("reference_texts") is not None else None, + "attachments": [DetailedFile.from_dict(_item) for _item in obj["attachments"]] if obj.get("attachments") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/message_role.py b/scaleapi/api_client/v2/models/message_role.py new file mode 100644 index 0000000..386cbde --- /dev/null +++ b/scaleapi/api_client/v2/models/message_role.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class MessageRole(str, Enum): + """ + The role of the sender in the conversation. Possible values include system, user, assistant, and function. + """ + + """ + allowed enum values + """ + SYSTEM = 'system' + USER = 'user' + ASSISTANT = 'assistant' + FUNCTION = 'function' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of MessageRole from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/model_parameters.py b/scaleapi/api_client/v2/models/model_parameters.py new file mode 100644 index 0000000..e31b351 --- /dev/null +++ b/scaleapi/api_client/v2/models/model_parameters.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self + +class ModelParameters(BaseModel): + """ + ModelParameters + """ # noqa: E501 + model: Optional[StrictStr] = Field(default=None, description="The name of the model that generated the message.") + temperature: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="The temperature of the model that generated the message.") + max_completion_tokens: Optional[StrictInt] = Field(default=None, description="The maximum number of tokens the model can generate.") + __properties: ClassVar[List[str]] = ["model", "temperature", "max_completion_tokens"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ModelParameters from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ModelParameters from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "model": obj.get("model"), + "temperature": obj.get("temperature"), + "max_completion_tokens": obj.get("max_completion_tokens") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/option.py b/scaleapi/api_client/v2/models/option.py new file mode 100644 index 0000000..a8aa954 --- /dev/null +++ b/scaleapi/api_client/v2/models/option.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class Option(str, Enum): + """ + Property that can be included in the annotations + """ + + """ + allowed enum values + """ + ANNOTATION_DETAILS = 'annotation_details' + ATTACHMENT_DETAILS = 'attachment_details' + MODEL_PARAMETERS = 'model_parameters' + SUBMISSIONS = 'submissions' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Option from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/project.py b/scaleapi/api_client/v2/models/project.py new file mode 100644 index 0000000..339841f --- /dev/null +++ b/scaleapi/api_client/v2/models/project.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class Project(BaseModel): + """ + Represents a project. + """ # noqa: E501 + id: StrictStr = Field(description="A unique identifier for the project.") + name: StrictStr = Field(description="The name of the project.") + __properties: ClassVar[List[str]] = ["id", "name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Project from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Project from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/reference_text.py b/scaleapi/api_client/v2/models/reference_text.py new file mode 100644 index 0000000..a456c3e --- /dev/null +++ b/scaleapi/api_client/v2/models/reference_text.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class ReferenceText(BaseModel): + """ + ReferenceText + """ # noqa: E501 + content: Optional[StrictStr] = Field(default=None, description="Content of the reference text.") + category: Optional[StrictStr] = Field(default=None, description="Category of the reference text.") + url: Optional[StrictStr] = Field(default=None, description="A URL string pointing to a resource.") + __properties: ClassVar[List[str]] = ["content", "category", "url"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReferenceText from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReferenceText from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "content": obj.get("content"), + "category": obj.get("category"), + "url": obj.get("url") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/submission.py b/scaleapi/api_client/v2/models/submission.py new file mode 100644 index 0000000..b81c2cd --- /dev/null +++ b/scaleapi/api_client/v2/models/submission.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class Submission(BaseModel): + """ + Details on the contributor submission made to the thread. + """ # noqa: E501 + submitted_at: Optional[datetime] = Field(default=None, description="A timestamp formatted as an ISO 8601 date-time string.") + contributor_id: Optional[StrictStr] = Field(default=None, description="A unique identifier for the contributor.") + __properties: ClassVar[List[str]] = ["submitted_at", "contributor_id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Submission from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Submission from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "submitted_at": obj.get("submitted_at"), + "contributor_id": obj.get("contributor_id") + }) + return _obj diff --git a/scaleapi/api_client/v2/models/task.py b/scaleapi/api_client/v2/models/task.py new file mode 100644 index 0000000..47fba3a --- /dev/null +++ b/scaleapi/api_client/v2/models/task.py @@ -0,0 +1,128 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.error_detail import ErrorDetail +from scaleapi.api_client.v2.models.expandable_batch import ExpandableBatch +from scaleapi.api_client.v2.models.expandable_project import ExpandableProject +from scaleapi.api_client.v2.models.task_status import TaskStatus +from scaleapi.api_client.v2.models.thread import Thread +from typing import Optional, Set +from typing_extensions import Self + +class Task(BaseModel): + """ + Represents a single task + """ # noqa: E501 + task_id: StrictStr = Field(description="Unique identifier for a task") + project: ExpandableProject = Field(description="Project ID or [Project](/core-resources/project) associated with the task.") + batch: Optional[ExpandableBatch] = Field(default=None, description="Batch ID or [Batch](/core-resources/batch) associated with the task.") + status: TaskStatus = Field(description="Current status of the task.") + created_at: datetime = Field(description="A timestamp formatted as an ISO 8601 date-time string.") + completed_at: Optional[datetime] = Field(default=None, description="A timestamp formatted as an ISO 8601 date-time string.") + metadata: Optional[Dict[str, Any]] = Field(default=None, description="Task metadata defined during task creation.") + threads: Optional[List[Thread]] = Field(default=None, description="Threads associated with the task. Tasks that do not have a `status` of `completed` will have an empty `threads` array.") + errors: Optional[List[ErrorDetail]] = Field(default=None, description="Errors associated with the task. Available when the task status is `error`") + __properties: ClassVar[List[str]] = ["task_id", "project", "batch", "status", "created_at", "completed_at", "metadata", "threads", "errors"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Task from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of project + if self.project: + _dict['project'] = self.project.to_dict() + # override the default output from pydantic by calling `to_dict()` of batch + if self.batch: + _dict['batch'] = self.batch.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in threads (list) + _items = [] + if self.threads: + for _item_threads in self.threads: + if _item_threads: + _items.append(_item_threads.to_dict()) + _dict['threads'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in errors (list) + _items = [] + if self.errors: + for _item_errors in self.errors: + if _item_errors: + _items.append(_item_errors.to_dict()) + _dict['errors'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Task from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_id": obj.get("task_id"), + "project": ExpandableProject.from_dict(obj["project"]) if obj.get("project") is not None else None, + "batch": ExpandableBatch.from_dict(obj["batch"]) if obj.get("batch") is not None else None, + "status": obj.get("status"), + "created_at": obj.get("created_at"), + "completed_at": obj.get("completed_at"), + "metadata": obj.get("metadata"), + "threads": [Thread.from_dict(_item) for _item in obj["threads"]] if obj.get("threads") is not None else None, + "errors": [ErrorDetail.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/task_status.py b/scaleapi/api_client/v2/models/task_status.py new file mode 100644 index 0000000..e4350f7 --- /dev/null +++ b/scaleapi/api_client/v2/models/task_status.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TaskStatus(str, Enum): + """ + The current status of the task, indicating whether it is pending, completed, error, or canceled. + """ + + """ + allowed enum values + """ + PENDING = 'pending' + COMPLETED = 'completed' + CANCELED = 'canceled' + ERROR = 'error' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TaskStatus from a JSON string""" + return cls(json.loads(json_str)) diff --git a/scaleapi/api_client/v2/models/thread.py b/scaleapi/api_client/v2/models/thread.py new file mode 100644 index 0000000..d194bf4 --- /dev/null +++ b/scaleapi/api_client/v2/models/thread.py @@ -0,0 +1,116 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.annotation import Annotation +from scaleapi.api_client.v2.models.submission import Submission +from scaleapi.api_client.v2.models.turn import Turn +from typing import Optional, Set +from typing_extensions import Self + +class Thread(BaseModel): + """ + Represents a thread of messages in a task. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier for a thread") + turns: List[Turn] = Field(description="[Turns](/core-resources/turn) within the thread. ") + submissions: Optional[List[Submission]] = Field(default=None, description="List of contributor submission details made to the thread.") + annotations: List[Annotation] = Field(description="Array of annotations.") + __properties: ClassVar[List[str]] = ["id", "turns", "submissions", "annotations"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Thread from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in turns (list) + _items = [] + if self.turns: + for _item_turns in self.turns: + if _item_turns: + _items.append(_item_turns.to_dict()) + _dict['turns'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in submissions (list) + _items = [] + if self.submissions: + for _item_submissions in self.submissions: + if _item_submissions: + _items.append(_item_submissions.to_dict()) + _dict['submissions'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in annotations (list) + _items = [] + if self.annotations: + for _item_annotations in self.annotations: + if _item_annotations: + _items.append(_item_annotations.to_dict()) + _dict['annotations'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Thread from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "turns": [Turn.from_dict(_item) for _item in obj["turns"]] if obj.get("turns") is not None else None, + "submissions": [Submission.from_dict(_item) for _item in obj["submissions"]] if obj.get("submissions") is not None else None, + "annotations": [Annotation.from_dict(_item) for _item in obj["annotations"]] if obj.get("annotations") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/turn.py b/scaleapi/api_client/v2/models/turn.py new file mode 100644 index 0000000..26b8f92 --- /dev/null +++ b/scaleapi/api_client/v2/models/turn.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from scaleapi.api_client.v2.models.annotation import Annotation +from scaleapi.api_client.v2.models.message import Message +from typing import Optional, Set +from typing_extensions import Self + +class Turn(BaseModel): + """ + Turn + """ # noqa: E501 + id: StrictStr = Field(description="A unique identifier for the turn.") + messages: List[Message] = Field(description="A list of [messages](/core-resources/message) associated with this turn.") + annotations: List[Annotation] = Field(description="Array of annotations.") + __properties: ClassVar[List[str]] = ["id", "messages", "annotations"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Turn from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in messages (list) + _items = [] + if self.messages: + for _item_messages in self.messages: + if _item_messages: + _items.append(_item_messages.to_dict()) + _dict['messages'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in annotations (list) + _items = [] + if self.annotations: + for _item_annotations in self.annotations: + if _item_annotations: + _items.append(_item_annotations.to_dict()) + _dict['annotations'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Turn from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "messages": [Message.from_dict(_item) for _item in obj["messages"]] if obj.get("messages") is not None else None, + "annotations": [Annotation.from_dict(_item) for _item in obj["annotations"]] if obj.get("annotations") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/v1_task_task_id_get200_response.py b/scaleapi/api_client/v2/models/v1_task_task_id_get200_response.py new file mode 100644 index 0000000..b088e1e --- /dev/null +++ b/scaleapi/api_client/v2/models/v1_task_task_id_get200_response.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from scaleapi.api_client.v2.models.v1_task_task_id_get200_response_response import V1TaskTaskIdGet200ResponseResponse +from typing import Optional, Set +from typing_extensions import Self + +class V1TaskTaskIdGet200Response(BaseModel): + """ + V1TaskTaskIdGet200Response + """ # noqa: E501 + task_id: Optional[StrictStr] = Field(default=None, description="Unique identifier for the task.") + created_at: Optional[StrictStr] = Field(default=None, description="Timestamp when the task was created.") + type: Optional[StrictStr] = Field(default=None, description="Type of the task") + params: Optional[Dict[str, Any]] = Field(default=None, description="Additional parameters for the task.") + response: Optional[V1TaskTaskIdGet200ResponseResponse] = None + __properties: ClassVar[List[str]] = ["task_id", "created_at", "type", "params", "response"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of V1TaskTaskIdGet200Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of response + if self.response: + _dict['response'] = self.response.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of V1TaskTaskIdGet200Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "task_id": obj.get("task_id"), + "created_at": obj.get("created_at"), + "type": obj.get("type"), + "params": obj.get("params"), + "response": V1TaskTaskIdGet200ResponseResponse.from_dict(obj["response"]) if obj.get("response") is not None else None + }) + return _obj diff --git a/scaleapi/api_client/v2/models/v1_task_task_id_get200_response_response.py b/scaleapi/api_client/v2/models/v1_task_task_id_get200_response_response.py new file mode 100644 index 0000000..70c4901 --- /dev/null +++ b/scaleapi/api_client/v2/models/v1_task_task_id_get200_response_response.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class V1TaskTaskIdGet200ResponseResponse(BaseModel): + """ + Response object containing task output. + """ # noqa: E501 + responses: Optional[List[Dict[str, Any]]] = Field(default=None, description="List of response objects.") + __properties: ClassVar[List[str]] = ["responses"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of V1TaskTaskIdGet200ResponseResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of V1TaskTaskIdGet200ResponseResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "responses": obj.get("responses") + }) + return _obj diff --git a/scaleapi/api_client/v2/rest.py b/scaleapi/api_client/v2/rest.py new file mode 100644 index 0000000..7e62b7b --- /dev/null +++ b/scaleapi/api_client/v2/rest.py @@ -0,0 +1,257 @@ +# coding: utf-8 + +""" + GenAI API Spec + + Data Engine: Generative AI API Specification + + The version of the OpenAPI document: 0.0.1 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import re +import ssl + +import urllib3 + +from scaleapi.api_client.v2.exceptions import ApiException, ApiValueError + +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } + if configuration.assert_hostname is not None: + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + pool_args['socket_options'] = configuration.socket_options + + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize + + # https pool manager + self.pool_manager: urllib3.PoolManager + + if configuration.proxy: + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) + else: + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a `string` parameter directly in the body to support + # other content types than JSON when `body` argument is + # provided in serialized form. + elif isinstance(body, str) or isinstance(body, bytes): + r = self.pool_manager.request( + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=False, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) diff --git a/setup.cfg b/setup.cfg index 69b2789..c61e56e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -3,6 +3,7 @@ long_description = file: README.rst long_description_content_type = text/x-rst [flake8] +exclude = scaleapi/api_client # Recommend matching the black line length (default 88) max-line-length = 88 max-doc-length = 72 diff --git a/setup.py b/setup.py index 9c5799e..b8c231b 100644 --- a/setup.py +++ b/setup.py @@ -1,11 +1,14 @@ import os.path -try: - from setuptools import setup -except ImportError: - from distutils.core import setup +from setuptools import find_packages, setup -install_requires = ["requests>=2.25.0", "urllib3>=1.26.0"] +install_requires = [ + "requests>=2.25.0", + "urllib3>=1.26.0", + "python_dateutil>=2.8.2", + "pydantic>=2", + "typing-extensions>=4.7.1", +] def read(rel_path): @@ -26,7 +29,7 @@ def get_version(rel_path): setup( name="scaleapi", - packages=["scaleapi"], + packages=find_packages(), version=get_version("scaleapi/_version.py"), description="The official Python client library for Scale AI, " "the Data Platform for AI", @@ -42,16 +45,16 @@ def get_version(rel_path): "annotation", ], install_requires=install_requires, - python_requires=">=3.6", + python_requires=">=3.8", classifiers=[ "Development Status :: 5 - Production/Stable", "Natural Language :: English", "Programming Language :: Python", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries", diff --git a/tests/test_v2_client.py b/tests/test_v2_client.py new file mode 100644 index 0000000..2f2654b --- /dev/null +++ b/tests/test_v2_client.py @@ -0,0 +1,66 @@ +# # pylint: disable=missing-function-docstring +# import os + +# import scaleapi +# from scaleapi.exceptions import ( +# ScaleResourceNotFound, +# ) +# from scaleapi.tasks import TaskType + +# # The test project needs to be setup before running these tests +# # Alternatively, you can use an existing project +# TEST_PROJECT_NAME = "scaleapi-python-sdk-v2-test" + +# try: +# print(f"SDK Version: {scaleapi.__version__}") +# test_api_key = os.environ["SCALE_TEST_API_KEY"] + +# if test_api_key.startswith("test_") or \ +# test_api_key.endswith("|test"): +# client = scaleapi.ScaleClient(test_api_key, "pytest") +# else: +# raise Exception("Please provide a valid" +# + "TEST environment key.") +# except KeyError as err: +# raise Exception( +# "Please set the environment variable" +# + "SCALE_TEST_API_KEY to run tests." +# ) from err + +# try: +# project = client.get_project(TEST_PROJECT_NAME) +# except ScaleResourceNotFound: +# res = client.create_project(project_name=TEST_PROJECT_NAME, \ +# task_type=TaskType.Chat) + + +# def make_a_chat_task(): +# args = { +# "project": TEST_PROJECT_NAME, +# "instruction": "Task instructions.", +# "params": { +# "before": [], +# "turn": [], +# "after": [], +# }, +# "template_variables": { +# "some_key": "some_value", +# "languageCode": "en_US", +# }, +# } +# return client.create_task(TaskType.Chat, **args) + + +# def test_v2_get_tasks(): +# new_task = make_a_chat_task() +# tasks = client.v2_get_tasks( +# project_name=TEST_PROJECT_NAME, +# ) +# task_ids = {task.task_id for task in tasks} +# assert new_task.id in task_ids + + +# def test_v2_get_task(): +# new_task = make_a_chat_task() +# task = client.v2.get_task(task_id=new_task.id) +# assert task.task_id == new_task.id diff --git a/v2_generator.json b/v2_generator.json new file mode 100644 index 0000000..d1958a2 --- /dev/null +++ b/v2_generator.json @@ -0,0 +1,16 @@ +{ + "generatorName": "python", + "packageName": "scaleapi.api_client.v2", + "inputSpec": "https://api.scale.com/v2/openapi", + "outputDir": "./", + "templateDir": "./v2_templates", + "globalProperties": { + "models": "", + "apis": "v2", + "apiTests": false, + "modelTests": false, + "apiDocs": false, + "modelDocs": false, + "supportingFiles": "api_client.py,configuration.py,exceptions.py,models.py,rest.py,serializer.py,serializers.py,api_response.py,__init__.py" + } +} diff --git a/v2_templates/model_generic.mustache b/v2_templates/model_generic.mustache new file mode 100644 index 0000000..7bb6727 --- /dev/null +++ b/v2_templates/model_generic.mustache @@ -0,0 +1,403 @@ +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +{{#vendorExtensions.x-py-other-imports}} +{{{.}}} +{{/vendorExtensions.x-py-other-imports}} +{{#vendorExtensions.x-py-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-model-imports}} +from typing import Optional, Set +from typing_extensions import Self + +{{#hasChildren}} +{{#discriminator}} +{{! If this model is a super class, importlib is used. So import the necessary modules for the type here. }} +from typing import TYPE_CHECKING +if TYPE_CHECKING: +{{#mappedModels}} + from {{packageName}}.models.{{model.classVarName}} import {{modelName}} +{{/mappedModels}} + +{{/discriminator}} +{{/hasChildren}} +class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): + """ + {{#description}}{{{description}}}{{/description}}{{^description}}{{{classname}}}{{/description}} + """ # noqa: E501 +{{#vars}} + {{name}}: {{{vendorExtensions.x-py-typing}}} +{{/vars}} +{{#isAdditionalPropertiesTrue}} + additional_properties: Dict[str, Any] = {} +{{/isAdditionalPropertiesTrue}} + __properties: ClassVar[List[str]] = [{{#allVars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/allVars}}] +{{#vars}} + {{#vendorExtensions.x-regex}} + + @field_validator('{{{name}}}') + def {{{name}}}_validate_regular_expression(cls, value): + """Validates the regular expression""" + {{^required}} + if value is None: + return value + + {{/required}} + {{#required}} + {{#isNullable}} + if value is None: + return value + + {{/isNullable}} + {{/required}} + if not re.match(r"{{{.}}}", value{{#vendorExtensions.x-modifiers}} ,re.{{{.}}}{{/vendorExtensions.x-modifiers}}): + raise ValueError(r"must validate the regular expression {{{vendorExtensions.x-pattern}}}") + return value + {{/vendorExtensions.x-regex}} + {{#isEnum}} + + @field_validator('{{{name}}}') + def {{{name}}}_validate_enum(cls, value): + """Validates the enum""" + {{^required}} + if value is None: + return value + + {{/required}} + {{#required}} + {{#isNullable}} + if value is None: + return value + + {{/isNullable}} + {{/required}} + {{#isArray}} + for i in value: + if i not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): + raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") + {{/isArray}} + {{^isArray}} + if value not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): + raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") + {{/isArray}} + return value + {{/isEnum}} +{{/vars}} + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + +{{#hasChildren}} +{{#discriminator}} + # JSON field name that stores the object type + __discriminator_property_name: ClassVar[str] = '{{discriminator.propertyBaseName}}' + + # discriminator mappings + __discriminator_value_class_map: ClassVar[Dict[str, str]] = { + {{#mappedModels}}'{{{mappingName}}}': '{{{modelName}}}'{{^-last}},{{/-last}}{{/mappedModels}} + } + + @classmethod + def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: + """Returns the discriminator value (object type) of the data""" + discriminator_value = obj[cls.__discriminator_property_name] + if discriminator_value: + return cls.__discriminator_value_class_map.get(discriminator_value) + else: + return None + +{{/discriminator}} +{{/hasChildren}} + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + excluded_fields: Set[str] = set([ + {{#vendorExtensions.x-py-readonly}} + "{{{.}}}", + {{/vendorExtensions.x-py-readonly}} + {{#isAdditionalPropertiesTrue}} + "additional_properties", + {{/isAdditionalPropertiesTrue}} + ]) + return self.model_dump_json(by_alias=True, exclude_unset=True, exclude=excluded_fields) + + @classmethod + def from_json(cls, json_str: str) -> Optional[{{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#mappedModels}}{{{modelName}}}{{^-last}}, {{/-last}}{{/mappedModels}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}]: + """Create an instance of {{{classname}}} from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + {{#vendorExtensions.x-py-readonly}} + * OpenAPI `readOnly` fields are excluded. + {{/vendorExtensions.x-py-readonly}} + {{#isAdditionalPropertiesTrue}} + * Fields in `self.additional_properties` are added to the output dict. + {{/isAdditionalPropertiesTrue}} + """ + excluded_fields: Set[str] = set([ + {{#vendorExtensions.x-py-readonly}} + "{{{.}}}", + {{/vendorExtensions.x-py-readonly}} + {{#isAdditionalPropertiesTrue}} + "additional_properties", + {{/isAdditionalPropertiesTrue}} + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + {{#allVars}} + {{#isContainer}} + {{#isArray}} + {{#items.isArray}} + {{^items.items.isPrimitiveType}} + # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list of list) + _items = [] + if self.{{{name}}}: + for _item_{{{name}}} in self.{{{name}}}: + if _item_{{{name}}}: + _items.append( + [_inner_item.to_dict() for _inner_item in _item_{{{name}}} if _inner_item is not None] + ) + _dict['{{{baseName}}}'] = _items + {{/items.items.isPrimitiveType}} + {{/items.isArray}} + {{^items.isArray}} + {{^items.isPrimitiveType}} + {{^items.isEnumOrRef}} + # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list) + _items = [] + if self.{{{name}}}: + for _item_{{{name}}} in self.{{{name}}}: + if _item_{{{name}}}: + _items.append(_item_{{{name}}}.to_dict()) + _dict['{{{baseName}}}'] = _items + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{/items.isArray}} + {{/isArray}} + {{#isMap}} + {{#items.isArray}} + {{^items.items.isPrimitiveType}} + # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict of array) + _field_dict_of_array = {} + if self.{{{name}}}: + for _key_{{{name}}} in self.{{{name}}}: + if self.{{{name}}}[_key_{{{name}}}] is not None: + _field_dict_of_array[_key_{{{name}}}] = [ + _item.to_dict() for _item in self.{{{name}}}[_key_{{{name}}}] + ] + _dict['{{{baseName}}}'] = _field_dict_of_array + {{/items.items.isPrimitiveType}} + {{/items.isArray}} + {{^items.isArray}} + {{^items.isPrimitiveType}} + {{^items.isEnumOrRef}} + # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict) + _field_dict = {} + if self.{{{name}}}: + for _key_{{{name}}} in self.{{{name}}}: + if self.{{{name}}}[_key_{{{name}}}]: + _field_dict[_key_{{{name}}}] = self.{{{name}}}[_key_{{{name}}}].to_dict() + _dict['{{{baseName}}}'] = _field_dict + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{/items.isArray}} + {{/isMap}} + {{/isContainer}} + {{^isContainer}} + {{^isPrimitiveType}} + {{^isEnumOrRef}} + # override the default output from pydantic by calling `to_dict()` of {{{name}}} + if self.{{{name}}}: + _dict['{{{baseName}}}'] = self.{{{name}}}.to_dict() + {{/isEnumOrRef}} + {{/isPrimitiveType}} + {{/isContainer}} + {{/allVars}} + {{#isAdditionalPropertiesTrue}} + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + {{/isAdditionalPropertiesTrue}} + {{#allVars}} + {{#isNullable}} + # set to None if {{{name}}} (nullable) is None + # and model_fields_set contains the field + if self.{{name}} is None and "{{{name}}}" in self.model_fields_set: + _dict['{{{baseName}}}'] = None + + {{/isNullable}} + {{/allVars}} + return _dict + + {{#hasChildren}} + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Optional[{{#discriminator}}Union[{{#mappedModels}}{{{modelName}}}{{^-last}}, {{/-last}}{{/mappedModels}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}]: + """Create an instance of {{{classname}}} from a dict""" + {{#discriminator}} + # look up the object type based on discriminator mapping + object_type = cls.get_discriminator_value(obj) + {{#mappedModels}} + if object_type == '{{{modelName}}}': + return import_module("{{packageName}}.models.{{model.classVarName}}").{{modelName}}.from_dict(obj) + {{/mappedModels}} + + raise ValueError("{{{classname}}} failed to lookup discriminator value from " + + json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + + ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) + {{/discriminator}} + {{/hasChildren}} + {{^hasChildren}} + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of {{{classname}}} from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + {{#disallowAdditionalPropertiesIfNotPresent}} + {{^isAdditionalPropertiesTrue}} + # raise errors for additional fields in the input + for _key in obj.keys(): + if _key not in cls.__properties: + raise ValueError("Error due to additional fields (not defined in {{classname}}) in the input: " + _key) + + {{/isAdditionalPropertiesTrue}} + {{/disallowAdditionalPropertiesIfNotPresent}} + _obj = cls.model_validate({ + {{#allVars}} + {{#isContainer}} + {{#isArray}} + {{#items.isArray}} + {{#items.items.isPrimitiveType}} + "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.items.isPrimitiveType}} + {{^items.items.isPrimitiveType}} + "{{{baseName}}}": [ + [{{{items.items.dataType}}}.from_dict(_inner_item) for _inner_item in _item] + for _item in obj["{{{baseName}}}"] + ] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + {{/items.items.isPrimitiveType}} + {{/items.isArray}} + {{^items.isArray}} + {{^items.isPrimitiveType}} + {{#items.isEnumOrRef}} + "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.isEnumOrRef}} + {{^items.isEnumOrRef}} + "{{{baseName}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj["{{{baseName}}}"]] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{#items.isPrimitiveType}} + "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.isPrimitiveType}} + {{/items.isArray}} + {{/isArray}} + {{#isMap}} + {{^items.isPrimitiveType}} + {{^items.isEnumOrRef}} + {{#items.isContainer}} + {{#items.isMap}} + "{{{baseName}}}": dict( + (_k, dict( + (_ik, {{{items.items.dataType}}}.from_dict(_iv)) + for _ik, _iv in _v.items() + ) + if _v is not None + else None + ) + for _k, _v in obj.get("{{{baseName}}}").items() + ) + if obj.get("{{{baseName}}}") is not None + else None{{^-last}},{{/-last}} + {{/items.isMap}} + {{#items.isArray}} + "{{{baseName}}}": dict( + (_k, + [{{{items.items.dataType}}}.from_dict(_item) for _item in _v] + if _v is not None + else None + ) + for _k, _v in obj.get("{{{baseName}}}", {}).items() + ){{^-last}},{{/-last}} + {{/items.isArray}} + {{/items.isContainer}} + {{^items.isContainer}} + "{{{baseName}}}": dict( + (_k, {{{items.dataType}}}.from_dict(_v)) + for _k, _v in obj["{{{baseName}}}"].items() + ) + if obj.get("{{{baseName}}}") is not None + else None{{^-last}},{{/-last}} + {{/items.isContainer}} + {{/items.isEnumOrRef}} + {{#items.isEnumOrRef}} + "{{{baseName}}}": dict((_k, _v) for _k, _v in obj.get("{{{baseName}}}").items()){{^-last}},{{/-last}} + {{/items.isEnumOrRef}} + {{/items.isPrimitiveType}} + {{#items.isPrimitiveType}} + "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/items.isPrimitiveType}} + {{/isMap}} + {{/isContainer}} + {{^isContainer}} + {{^isPrimitiveType}} + {{^isEnumOrRef}} + "{{{baseName}}}": {{{dataType}}}.from_dict(obj["{{{baseName}}}"]) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + {{/isEnumOrRef}} + {{#isEnumOrRef}} + "{{{baseName}}}": obj.get("{{{baseName}}}"){{#defaultValue}} if obj.get("{{baseName}}") is not None else {{defaultValue}}{{/defaultValue}}{{^-last}},{{/-last}} + {{/isEnumOrRef}} + {{/isPrimitiveType}} + {{#isPrimitiveType}} + {{#defaultValue}} + "{{{baseName}}}": obj.get("{{{baseName}}}") if obj.get("{{{baseName}}}") is not None else {{{defaultValue}}}{{^-last}},{{/-last}} + {{/defaultValue}} + {{^defaultValue}} + "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} + {{/defaultValue}} + {{/isPrimitiveType}} + {{/isContainer}} + {{/allVars}} + }) + {{#isAdditionalPropertiesTrue}} + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + {{/isAdditionalPropertiesTrue}} + return _obj + {{/hasChildren}} + +{{#vendorExtensions.x-py-postponed-model-imports.size}} +{{#vendorExtensions.x-py-postponed-model-imports}} +{{{.}}} +{{/vendorExtensions.x-py-postponed-model-imports}} +# TODO: Rewrite to not use raise_errors +{{classname}}.model_rebuild(raise_errors=False) +{{/vendorExtensions.x-py-postponed-model-imports.size}}