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

import typing
from ..core.client_wrapper import SyncClientWrapper
from ..types.text_to_speech_language import TextToSpeechLanguage
from ..types.text_to_speech_speaker import TextToSpeechSpeaker
from ..types.speech_sample_rate import SpeechSampleRate
from ..types.text_to_speech_model import TextToSpeechModel
from ..core.request_options import RequestOptions
from ..core.http_response import HttpResponse
from ..types.text_to_speech_response import TextToSpeechResponse
from ..core.pydantic_utilities import parse_obj_as
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..types.error_message import ErrorMessage
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..errors.too_many_requests_error import TooManyRequestsError
from ..errors.internal_server_error import InternalServerError
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper
from ..core.http_response import AsyncHttpResponse

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


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

    def convert(
        self,
        *,
        text: str,
        target_language_code: TextToSpeechLanguage,
        speaker: typing.Optional[TextToSpeechSpeaker] = OMIT,
        pitch: typing.Optional[float] = OMIT,
        pace: typing.Optional[float] = OMIT,
        loudness: typing.Optional[float] = OMIT,
        speech_sample_rate: typing.Optional[SpeechSampleRate] = OMIT,
        enable_preprocessing: typing.Optional[bool] = OMIT,
        model: typing.Optional[TextToSpeechModel] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TextToSpeechResponse]:
        """
        This is the model to convert text into spoken audio.
        The output is a wave file encoded as a base64 string.

        Parameters
        ----------
        text : str

        target_language_code : TextToSpeechLanguage
            The language of the text is BCP-47 format

        speaker : typing.Optional[TextToSpeechSpeaker]
            The speaker voice to be used for the output audio.

            **Default:** Meera

            **Model Compatibility (Speakers compatible with respective models):**
            - **bulbul:v1:**
              - Female: Diya, Maya, Meera, Pavithra, Maitreyi, Misha
              - Male: Amol, Arjun, Amartya, Arvind, Neel, Vian

            - **bulbul:v2:**
              - Female: Anushka, Manisha, Vidya, Arya
              - Male: Abhilash, Karun, Hitesh

            **Note:** Speaker selection must match the chosen model version.

        pitch : typing.Optional[float]
            Controls the pitch of the audio. Lower values result in a deeper voice, while higher values make it sharper. The suitable range is between -0.75 and 0.75. Default is 0.0.

        pace : typing.Optional[float]
            Controls the speed of the audio. Lower values result in slower speech, while higher values make it faster. The suitable range is between 0.5 and 2.0. Default is 1.0.

        loudness : typing.Optional[float]
            Controls the loudness of the audio. Lower values result in quieter audio, while higher values make it louder. The suitable range is between 0.3 and 3.0. Default is 1.0.

        speech_sample_rate : typing.Optional[SpeechSampleRate]
            Specifies the sample rate of the output audio. Supported values are 8000, 16000, 22050, 24000 Hz. If not provided, the default is 22050 Hz.

        enable_preprocessing : typing.Optional[bool]
             Controls whether normalization of English words and numeric entities (e.g., numbers, dates) is performed. Set to true for better handling of mixed-language text. Default is false.

        model : typing.Optional[TextToSpeechModel]
            Specifies the model to use for text-to-speech conversion. Default is bulbul:v1.

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

        Returns
        -------
        HttpResponse[TextToSpeechResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "text-to-speech",
            method="POST",
            json={
                "text": text,
                "target_language_code": target_language_code,
                "speaker": speaker,
                "pitch": pitch,
                "pace": pace,
                "loudness": loudness,
                "speech_sample_rate": speech_sample_rate,
                "enable_preprocessing": enable_preprocessing,
                "model": model,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TextToSpeechResponse,
                    parse_obj_as(
                        type_=TextToSpeechResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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 AsyncRawTextToSpeechClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def convert(
        self,
        *,
        text: str,
        target_language_code: TextToSpeechLanguage,
        speaker: typing.Optional[TextToSpeechSpeaker] = OMIT,
        pitch: typing.Optional[float] = OMIT,
        pace: typing.Optional[float] = OMIT,
        loudness: typing.Optional[float] = OMIT,
        speech_sample_rate: typing.Optional[SpeechSampleRate] = OMIT,
        enable_preprocessing: typing.Optional[bool] = OMIT,
        model: typing.Optional[TextToSpeechModel] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TextToSpeechResponse]:
        """
        This is the model to convert text into spoken audio.
        The output is a wave file encoded as a base64 string.

        Parameters
        ----------
        text : str

        target_language_code : TextToSpeechLanguage
            The language of the text is BCP-47 format

        speaker : typing.Optional[TextToSpeechSpeaker]
            The speaker voice to be used for the output audio.

            **Default:** Meera

            **Model Compatibility (Speakers compatible with respective models):**
            - **bulbul:v1:**
              - Female: Diya, Maya, Meera, Pavithra, Maitreyi, Misha
              - Male: Amol, Arjun, Amartya, Arvind, Neel, Vian

            - **bulbul:v2:**
              - Female: Anushka, Manisha, Vidya, Arya
              - Male: Abhilash, Karun, Hitesh

            **Note:** Speaker selection must match the chosen model version.

        pitch : typing.Optional[float]
            Controls the pitch of the audio. Lower values result in a deeper voice, while higher values make it sharper. The suitable range is between -0.75 and 0.75. Default is 0.0.

        pace : typing.Optional[float]
            Controls the speed of the audio. Lower values result in slower speech, while higher values make it faster. The suitable range is between 0.5 and 2.0. Default is 1.0.

        loudness : typing.Optional[float]
            Controls the loudness of the audio. Lower values result in quieter audio, while higher values make it louder. The suitable range is between 0.3 and 3.0. Default is 1.0.

        speech_sample_rate : typing.Optional[SpeechSampleRate]
            Specifies the sample rate of the output audio. Supported values are 8000, 16000, 22050, 24000 Hz. If not provided, the default is 22050 Hz.

        enable_preprocessing : typing.Optional[bool]
             Controls whether normalization of English words and numeric entities (e.g., numbers, dates) is performed. Set to true for better handling of mixed-language text. Default is false.

        model : typing.Optional[TextToSpeechModel]
            Specifies the model to use for text-to-speech conversion. Default is bulbul:v1.

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

        Returns
        -------
        AsyncHttpResponse[TextToSpeechResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "text-to-speech",
            method="POST",
            json={
                "text": text,
                "target_language_code": target_language_code,
                "speaker": speaker,
                "pitch": pitch,
                "pace": pace,
                "loudness": loudness,
                "speech_sample_rate": speech_sample_rate,
                "enable_preprocessing": enable_preprocessing,
                "model": model,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TextToSpeechResponse,
                    parse_obj_as(
                        type_=TextToSpeechResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    typing.cast(
                        ErrorMessage,
                        parse_obj_as(
                            type_=ErrorMessage,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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)
