# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import pydantic_v1
from ..core.request_options import RequestOptions
from ..types.prediction import Prediction

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class PredictionsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def list(
        self,
        *,
        task: typing.Optional[int] = None,
        project: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Prediction]:
        """
        Get a list of all predictions. You can optionally filter these by task or by project. If you want to filter, you will need the project ID and/or task ID. Both of these can be found in the Label Studio URL when viewing a task, or you can use [List all projects](../projects/list) and [Get tasks list](../tasks/list).

        <Note>The terms "predictions" and pre-annotations" are used interchangeably.</Note>

        Predictions can be [imported directly into Label Studio](https://labelstud.io/guide/predictions) or [generated by a connected ML backend](https://labelstud.io/guide/ml.html#Pre-annotations-predictions).

        To import predictions via the API, see [Create prediction](create).

        Parameters
        ----------
        task : typing.Optional[int]
            Filter predictions by task ID

        project : typing.Optional[int]
            Filter predictions by project ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        typing.List[Prediction]
            Predictions list

        Examples
        --------
        from label_studio_sdk.client import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.list()
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/predictions/", method="GET", params={"task": task, "project": project}, request_options=request_options
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Prediction], _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self,
        *,
        task: typing.Optional[int] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        model_version: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        If you have predictions generated for your dataset from a model, either as pre-annotated tasks or pre-labeled tasks, you can import the predictions with your dataset into Label Studio for review and correction.

        To import predicted labels into Label Studio, you must use the [Basic Label Studio JSON format](https://labelstud.io/guide/tasks#Basic-Label-Studio-JSON-format) and set up your tasks with the predictions JSON key. The Label Studio ML backend also outputs tasks in this format.

        #### JSON format for predictions

        Label Studio JSON format for pre-annotations must contain two sections:

        - A data object which references the source of the data that the pre-annotations apply to. This can be a URL to an audio file, a pre-signed cloud storage link to an image, plain text, a reference to a CSV file stored in Label Studio, or something else.
        - A predictions array that contains the pre-annotation results for the different types of labeling. See how to add results to the predictions array.

        For more information, see [the JSON format reference in the Label Studio documentation](https://labelstud.io/guide/predictions#JSON-format-for-pre-annotations)

        Parameters
        ----------
        task : typing.Optional[int]
            Task ID for which the prediction is created

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Prediction
            Created prediction

        Examples
        --------
        from label_studio_sdk.client import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.create(
            result=[
                {
                    "original_width": 1920,
                    "original_height": 1080,
                    "image_rotation": 0,
                    "from_name": "bboxes",
                    "to_name": "image",
                    "type": "rectanglelabels",
                    "value": {
                        "x": 20,
                        "y": 30,
                        "width": 50,
                        "height": 60,
                        "rotation": 0,
                        "values": {"rectanglelabels": {"0": "Person"}},
                    },
                }
            ],
            score=0.95,
            model_version="yolo-v8",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/predictions/",
            method="POST",
            json={"task": task, "result": result, "score": score, "model_version": model_version},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Prediction, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> Prediction:
        """
        Get details about a specific prediction by its ID. To find the prediction ID, use [List predictions](list).

        For information about the prediction format, see [the JSON format reference in the Label Studio documentation](https://labelstud.io/guide/predictions#JSON-format-for-pre-annotations).

        Parameters
        ----------
        id : int
            Prediction ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Prediction
            Prediction details

        Examples
        --------
        from label_studio_sdk.client import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.get(
            id=1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/", method="GET", request_options=request_options
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Prediction, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def delete(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Delete a prediction. To find the prediction ID, use [List predictions](list).

        Parameters
        ----------
        id : int
            Prediction ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        from label_studio_sdk.client import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.delete(
            id=1,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/", method="DELETE", request_options=request_options
        )
        if 200 <= _response.status_code < 300:
            return
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update(
        self,
        id: int,
        *,
        task: typing.Optional[int] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        model_version: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        Update a prediction. To find the prediction ID, use [List predictions](list).

        For information about the prediction format, see [the JSON format reference in the Label Studio documentation](https://labelstud.io/guide/predictions#JSON-format-for-pre-annotations).

        Parameters
        ----------
        id : int
            Prediction ID

        task : typing.Optional[int]
            Task ID for which the prediction is created

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Prediction
            Updated prediction

        Examples
        --------
        from label_studio_sdk.client import LabelStudio

        client = LabelStudio(
            api_key="YOUR_API_KEY",
        )
        client.predictions.update(
            id=1,
            result=[
                {
                    "original_width": 1920,
                    "original_height": 1080,
                    "image_rotation": 0,
                    "from_name": "bboxes",
                    "to_name": "image",
                    "type": "rectanglelabels",
                    "value": {
                        "x": 20,
                        "y": 30,
                        "width": 50,
                        "height": 60,
                        "rotation": 0,
                        "values": {"rectanglelabels": {"0": "Person"}},
                    },
                }
            ],
            score=0.95,
            model_version="yolo-v8",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="PATCH",
            json={"task": task, "result": result, "score": score, "model_version": model_version},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Prediction, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncPredictionsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        task: typing.Optional[int] = None,
        project: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Prediction]:
        """
        Get a list of all predictions. You can optionally filter these by task or by project. If you want to filter, you will need the project ID and/or task ID. Both of these can be found in the Label Studio URL when viewing a task, or you can use [List all projects](../projects/list) and [Get tasks list](../tasks/list).

        <Note>The terms "predictions" and pre-annotations" are used interchangeably.</Note>

        Predictions can be [imported directly into Label Studio](https://labelstud.io/guide/predictions) or [generated by a connected ML backend](https://labelstud.io/guide/ml.html#Pre-annotations-predictions).

        To import predictions via the API, see [Create prediction](create).

        Parameters
        ----------
        task : typing.Optional[int]
            Filter predictions by task ID

        project : typing.Optional[int]
            Filter predictions by project ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        typing.List[Prediction]
            Predictions list

        Examples
        --------
        from label_studio_sdk.client import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )
        await client.predictions.list()
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/predictions/", method="GET", params={"task": task, "project": project}, request_options=request_options
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(typing.List[Prediction], _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self,
        *,
        task: typing.Optional[int] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        model_version: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        If you have predictions generated for your dataset from a model, either as pre-annotated tasks or pre-labeled tasks, you can import the predictions with your dataset into Label Studio for review and correction.

        To import predicted labels into Label Studio, you must use the [Basic Label Studio JSON format](https://labelstud.io/guide/tasks#Basic-Label-Studio-JSON-format) and set up your tasks with the predictions JSON key. The Label Studio ML backend also outputs tasks in this format.

        #### JSON format for predictions

        Label Studio JSON format for pre-annotations must contain two sections:

        - A data object which references the source of the data that the pre-annotations apply to. This can be a URL to an audio file, a pre-signed cloud storage link to an image, plain text, a reference to a CSV file stored in Label Studio, or something else.
        - A predictions array that contains the pre-annotation results for the different types of labeling. See how to add results to the predictions array.

        For more information, see [the JSON format reference in the Label Studio documentation](https://labelstud.io/guide/predictions#JSON-format-for-pre-annotations)

        Parameters
        ----------
        task : typing.Optional[int]
            Task ID for which the prediction is created

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Prediction
            Created prediction

        Examples
        --------
        from label_studio_sdk.client import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )
        await client.predictions.create(
            result=[
                {
                    "original_width": 1920,
                    "original_height": 1080,
                    "image_rotation": 0,
                    "from_name": "bboxes",
                    "to_name": "image",
                    "type": "rectanglelabels",
                    "value": {
                        "x": 20,
                        "y": 30,
                        "width": 50,
                        "height": 60,
                        "rotation": 0,
                        "values": {"rectanglelabels": {"0": "Person"}},
                    },
                }
            ],
            score=0.95,
            model_version="yolo-v8",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/predictions/",
            method="POST",
            json={"task": task, "result": result, "score": score, "model_version": model_version},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Prediction, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> Prediction:
        """
        Get details about a specific prediction by its ID. To find the prediction ID, use [List predictions](list).

        For information about the prediction format, see [the JSON format reference in the Label Studio documentation](https://labelstud.io/guide/predictions#JSON-format-for-pre-annotations).

        Parameters
        ----------
        id : int
            Prediction ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Prediction
            Prediction details

        Examples
        --------
        from label_studio_sdk.client import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )
        await client.predictions.get(
            id=1,
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/", method="GET", request_options=request_options
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Prediction, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def delete(self, id: int, *, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Delete a prediction. To find the prediction ID, use [List predictions](list).

        Parameters
        ----------
        id : int
            Prediction ID

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        from label_studio_sdk.client import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )
        await client.predictions.delete(
            id=1,
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/", method="DELETE", request_options=request_options
        )
        if 200 <= _response.status_code < 300:
            return
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update(
        self,
        id: int,
        *,
        task: typing.Optional[int] = OMIT,
        result: typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]] = OMIT,
        score: typing.Optional[float] = OMIT,
        model_version: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Prediction:
        """
        Update a prediction. To find the prediction ID, use [List predictions](list).

        For information about the prediction format, see [the JSON format reference in the Label Studio documentation](https://labelstud.io/guide/predictions#JSON-format-for-pre-annotations).

        Parameters
        ----------
        id : int
            Prediction ID

        task : typing.Optional[int]
            Task ID for which the prediction is created

        result : typing.Optional[typing.Sequence[typing.Dict[str, typing.Any]]]
            Prediction result in JSON format. Read more about the format in [the Label Studio documentation.](https://labelstud.io/guide/predictions)

        score : typing.Optional[float]
            Prediction score. Can be used in Data Manager to sort task by model confidence. Task with the lowest score will be shown first.

        model_version : typing.Optional[str]
            Model version - tag for predictions that can be used to filter tasks in Data Manager, as well as select specific model version for showing preannotations in the labeling interface

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Prediction
            Updated prediction

        Examples
        --------
        from label_studio_sdk.client import AsyncLabelStudio

        client = AsyncLabelStudio(
            api_key="YOUR_API_KEY",
        )
        await client.predictions.update(
            id=1,
            result=[
                {
                    "original_width": 1920,
                    "original_height": 1080,
                    "image_rotation": 0,
                    "from_name": "bboxes",
                    "to_name": "image",
                    "type": "rectanglelabels",
                    "value": {
                        "x": 20,
                        "y": 30,
                        "width": 50,
                        "height": 60,
                        "rotation": 0,
                        "values": {"rectanglelabels": {"0": "Person"}},
                    },
                }
            ],
            score=0.95,
            model_version="yolo-v8",
        )
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/predictions/{jsonable_encoder(id)}/",
            method="PATCH",
            json={"task": task, "result": result, "score": score, "model_version": model_version},
            request_options=request_options,
            omit=OMIT,
        )
        if 200 <= _response.status_code < 300:
            return pydantic_v1.parse_obj_as(Prediction, _response.json())  # type: ignore
        try:
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
