diff --git a/venv/lib/python3.12/site-packages/anyio-4.13.0.dist-info/licenses/LICENSE b/venv/lib/python3.12/site-packages/anyio-4.13.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..104eebf5a3002fccdaceef3a4cb936173c1c2035 --- /dev/null +++ b/venv/lib/python3.12/site-packages/anyio-4.13.0.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2018 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71a36ee07d4ef722047497183a42bfe765f00948 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c78a8d9feda985b6927e6171cf45f72061f57b10 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d7c94d230e9d5b74f5e7773d69bfb4462864afb Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26d8504b738e0064c3fbee006b9244a9c9bab3f9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/datetime.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/datetime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffb1f9a3f9ace60c8fd06e513ac6b4258dbea9bc Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/datetime.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ba2bcff92e6b1db8540869977e01877bec66307 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a19139f8f9481919a4b17650ce09a079548e746 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cdb5a3a461034848370ec6b8a1d358234a6509e Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/encoding.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/encoding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83c844998531f2f4dd45ae83b5526ab7ce7ba861 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/encoding.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51eaaa72b418473749e0bba7da94645fb2f5b917 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00ae45a7b04931ccfd0fe0cc57e77d4646d5da9c Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db47e4a88772f2f3a386446d08d064e02ec77934 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/logging.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af3bbd0bc6062eaa63e3601ed7d811dc66355510 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/logging.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/models.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92e61497827545ad3b43f27746d9bac52a6739cd Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/models.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..103058008d64ce2fbea29f11fdb1b8dd2672bfb5 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d32d4a8daa4b213b9bfad65df94c2b7c7de65db1 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..055bb63ec904ebcb26695e6ecb612cf2c984ab31 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/urls.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/urls.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b92516af9a5cd1f8e7dd0f06c54af59e6d797f43 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/urls.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-312.pyc b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d7496cee62a36e82b5f786dc0b7aa6f66acc584 Binary files /dev/null and b/venv/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b6c94b0387bbb29f067fc2b37615f14401ae7d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f6d5ca5be8b088414a8e71dd406a4ac30e195f0 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/__pycache__/environment.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/environment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43d6bc828ef143b8dbadbdf8124d3071950ddcc8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/environment.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/__pycache__/play.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/play.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03f6e29f9f9841d62ee59129d83509e6ba28dc69 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/play.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/__pycache__/version.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09dd3685a58346c4515ecdf182fdf4e938ebb149 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/__pycache__/version.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/chat/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/chat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/chat/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae26983d9e9ffed88a4c3c1431a327d6e8697513 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f2d991bc4d1edb7fb395836f212c7593fcc38c6 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc3121bbaf9c6df3a5be6b8f8a9c5c916de96fbb Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/chat/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/chat/client.py b/venv/lib/python3.12/site-packages/sarvamai/chat/client.py new file mode 100644 index 0000000000000000000000000000000000000000..f93b995ca390f1938a60a25ee696521e68fe2632 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/chat/client.py @@ -0,0 +1,446 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..requests.chat_completion_request_message import ChatCompletionRequestMessageParams +from ..requests.chat_completion_tool import ChatCompletionToolParams +from ..requests.stop_configuration import StopConfigurationParams +from ..requests.tool_choice_option import ToolChoiceOptionParams +from ..types.chat_completion_chunk import ChatCompletionChunk +from ..types.create_chat_completion_response import CreateChatCompletionResponse +from ..types.reasoning_effort import ReasoningEffort +from ..types.sarvam_model_ids import SarvamModelIds +from .raw_client import AsyncRawChatClient, RawChatClient + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class ChatClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawChatClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawChatClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawChatClient + """ + return self._raw_client + + @typing.overload + def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Literal[True], + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> typing.Iterator[ChatCompletionChunk]: ... + + @typing.overload + def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Optional[typing.Literal[False]] = ..., + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> CreateChatCompletionResponse: ... + + def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = OMIT, + top_p: typing.Optional[float] = OMIT, + reasoning_effort: typing.Optional[ReasoningEffort] = OMIT, + max_tokens: typing.Optional[int] = OMIT, + stream: typing.Optional[bool] = OMIT, + stop: typing.Optional[StopConfigurationParams] = OMIT, + n: typing.Optional[int] = OMIT, + seed: typing.Optional[int] = OMIT, + frequency_penalty: typing.Optional[float] = OMIT, + presence_penalty: typing.Optional[float] = OMIT, + wiki_grounding: typing.Optional[bool] = OMIT, + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = OMIT, + tool_choice: typing.Optional[ToolChoiceOptionParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Union[CreateChatCompletionResponse, typing.Iterator[ChatCompletionChunk]]: + """ + Parameters + ---------- + messages : typing.Sequence[ChatCompletionRequestMessageParams] + A list of messages comprising the conversation so far. + + model : SarvamModelIds + Model ID used to generate the response, like `sarvam-m`. + + temperature : typing.Optional[float] + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + We generally recommend altering this or `top_p` but not both. + + top_p : typing.Optional[float] + An alternative to sampling with temperature, called nucleus sampling, + where the model considers the results of the tokens with top_p probability + mass. So 0.1 means only the tokens comprising the top 10% probability mass + are considered. + + We generally recommend altering this or `temperature` but not both. + + reasoning_effort : typing.Optional[ReasoningEffort] + The effort to use for reasoning + + max_tokens : typing.Optional[int] + The maximum number of tokens that can be generated in the chat completion. + + stream : typing.Optional[bool] + If set to true, the model response data will be streamed to the client + as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + When true, returns an Iterator[ChatCompletionChunk] instead of CreateChatCompletionResponse. + + stop : typing.Optional[StopConfigurationParams] + + n : typing.Optional[int] + How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + + seed : typing.Optional[int] + This feature is in Beta. + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + + frequency_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + their existing frequency in the text so far, decreasing the model's + likelihood to repeat the same line verbatim. + + presence_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood + to talk about new topics. + + wiki_grounding : typing.Optional[bool] + If set to true, the model response will be wiki grounded. + + tools : typing.Optional[typing.Sequence[ChatCompletionToolParams]] + A list of tools the model may call. Currently, only functions are supported as a tool. + + tool_choice : typing.Optional[ToolChoiceOptionParams] + Controls which (if any) tool is called by the model. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + CreateChatCompletionResponse or Iterator[ChatCompletionChunk] + When stream=False (default): CreateChatCompletionResponse. + When stream=True: Iterator yielding ChatCompletionChunk objects. + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + # Non-streaming + response = client.chat.completions( + messages=[{"role": "user", "content": "Hello"}], + model="sarvam-m", + ) + + # Streaming + for chunk in client.chat.completions( + messages=[{"role": "user", "content": "Hello"}], + model="sarvam-m", + stream=True, + ): + print(chunk) + """ + if stream is True: + return self._raw_client.completions( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=reasoning_effort, + max_tokens=max_tokens, + stream=True, + stop=stop, + n=n, + seed=seed, + frequency_penalty=frequency_penalty, + presence_penalty=presence_penalty, + wiki_grounding=wiki_grounding, + tools=tools, + tool_choice=tool_choice, + request_options=request_options, + ) + + _response = self._raw_client.completions( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=reasoning_effort, + max_tokens=max_tokens, + stream=stream, + stop=stop, + n=n, + seed=seed, + frequency_penalty=frequency_penalty, + presence_penalty=presence_penalty, + wiki_grounding=wiki_grounding, + tools=tools, + tool_choice=tool_choice, + request_options=request_options, + ) + return _response.data + + +class AsyncChatClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawChatClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawChatClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawChatClient + """ + return self._raw_client + + @typing.overload + async def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Literal[True], + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> typing.AsyncIterator[ChatCompletionChunk]: ... + + @typing.overload + async def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Optional[typing.Literal[False]] = ..., + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> CreateChatCompletionResponse: ... + + async def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = OMIT, + top_p: typing.Optional[float] = OMIT, + reasoning_effort: typing.Optional[ReasoningEffort] = OMIT, + max_tokens: typing.Optional[int] = OMIT, + stream: typing.Optional[bool] = OMIT, + stop: typing.Optional[StopConfigurationParams] = OMIT, + n: typing.Optional[int] = OMIT, + seed: typing.Optional[int] = OMIT, + frequency_penalty: typing.Optional[float] = OMIT, + presence_penalty: typing.Optional[float] = OMIT, + wiki_grounding: typing.Optional[bool] = OMIT, + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = OMIT, + tool_choice: typing.Optional[ToolChoiceOptionParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Union[CreateChatCompletionResponse, typing.AsyncIterator[ChatCompletionChunk]]: + """ + Parameters + ---------- + messages : typing.Sequence[ChatCompletionRequestMessageParams] + A list of messages comprising the conversation so far. + + model : SarvamModelIds + Model ID used to generate the response, like `sarvam-m`. + + temperature : typing.Optional[float] + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + We generally recommend altering this or `top_p` but not both. + + top_p : typing.Optional[float] + An alternative to sampling with temperature, called nucleus sampling, + where the model considers the results of the tokens with top_p probability + mass. So 0.1 means only the tokens comprising the top 10% probability mass + are considered. + + We generally recommend altering this or `temperature` but not both. + + reasoning_effort : typing.Optional[ReasoningEffort] + The effort to use for reasoning + + max_tokens : typing.Optional[int] + The maximum number of tokens that can be generated in the chat completion. + + stream : typing.Optional[bool] + If set to true, the model response data will be streamed to the client + as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + When true, returns an AsyncIterator[ChatCompletionChunk] instead of CreateChatCompletionResponse. + + stop : typing.Optional[StopConfigurationParams] + + n : typing.Optional[int] + How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + + seed : typing.Optional[int] + This feature is in Beta. + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + + frequency_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + their existing frequency in the text so far, decreasing the model's + likelihood to repeat the same line verbatim. + + presence_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood + to talk about new topics. + + wiki_grounding : typing.Optional[bool] + If set to true, the model response will be wiki grounded. + + tools : typing.Optional[typing.Sequence[ChatCompletionToolParams]] + A list of tools the model may call. Currently, only functions are supported as a tool. + + tool_choice : typing.Optional[ToolChoiceOptionParams] + Controls which (if any) tool is called by the model. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + CreateChatCompletionResponse or AsyncIterator[ChatCompletionChunk] + When stream=False (default): CreateChatCompletionResponse. + When stream=True: AsyncIterator yielding ChatCompletionChunk objects. + + Examples + -------- + import asyncio + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + async def main() -> None: + # Non-streaming + response = await client.chat.completions( + messages=[{"role": "user", "content": "Hello"}], + model="sarvam-m", + ) + + # Streaming + async for chunk in client.chat.completions( + messages=[{"role": "user", "content": "Hello"}], + model="sarvam-m", + stream=True, + ): + print(chunk) + + asyncio.run(main()) + """ + if stream is True: + return await self._raw_client.completions( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=reasoning_effort, + max_tokens=max_tokens, + stream=True, + stop=stop, + n=n, + seed=seed, + frequency_penalty=frequency_penalty, + presence_penalty=presence_penalty, + wiki_grounding=wiki_grounding, + tools=tools, + tool_choice=tool_choice, + request_options=request_options, + ) + + _response = await self._raw_client.completions( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=reasoning_effort, + max_tokens=max_tokens, + stream=stream, + stop=stop, + n=n, + seed=seed, + frequency_penalty=frequency_penalty, + presence_penalty=presence_penalty, + wiki_grounding=wiki_grounding, + tools=tools, + tool_choice=tool_choice, + request_options=request_options, + ) + return _response.data diff --git a/venv/lib/python3.12/site-packages/sarvamai/chat/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/chat/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a725302232ff385e8db1b8076afac526dd786ffd --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/chat/raw_client.py @@ -0,0 +1,718 @@ +# This file was auto-generated by Fern from our API Definition. + +import json +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..core.serialization import convert_and_respect_annotation_metadata +from ..errors.bad_request_error import BadRequestError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..errors.unprocessable_entity_error import UnprocessableEntityError +from ..requests.chat_completion_request_message import ChatCompletionRequestMessageParams +from ..requests.chat_completion_tool import ChatCompletionToolParams +from ..requests.stop_configuration import StopConfigurationParams +from ..requests.tool_choice_option import ToolChoiceOptionParams +from ..types.chat_completion_chunk import ChatCompletionChunk +from ..types.create_chat_completion_response import CreateChatCompletionResponse +from ..types.reasoning_effort import ReasoningEffort +from ..types.sarvam_model_ids import SarvamModelIds + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawChatClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + @typing.overload + def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Literal[True], + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> typing.Iterator[ChatCompletionChunk]: ... + + @typing.overload + def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Optional[typing.Literal[False]] = ..., + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> HttpResponse[CreateChatCompletionResponse]: ... + + def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = OMIT, + top_p: typing.Optional[float] = OMIT, + reasoning_effort: typing.Optional[ReasoningEffort] = OMIT, + max_tokens: typing.Optional[int] = OMIT, + stream: typing.Optional[bool] = OMIT, + stop: typing.Optional[StopConfigurationParams] = OMIT, + n: typing.Optional[int] = OMIT, + seed: typing.Optional[int] = OMIT, + frequency_penalty: typing.Optional[float] = OMIT, + presence_penalty: typing.Optional[float] = OMIT, + wiki_grounding: typing.Optional[bool] = OMIT, + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = OMIT, + tool_choice: typing.Optional[ToolChoiceOptionParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Union[HttpResponse[CreateChatCompletionResponse], typing.Iterator[ChatCompletionChunk]]: + """ + Parameters + ---------- + messages : typing.Sequence[ChatCompletionRequestMessageParams] + A list of messages comprising the conversation so far. + + model : SarvamModelIds + Model ID used to generate the response, like `sarvam-m`. + + temperature : typing.Optional[float] + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + We generally recommend altering this or `top_p` but not both. + + top_p : typing.Optional[float] + An alternative to sampling with temperature, called nucleus sampling, + where the model considers the results of the tokens with top_p probability + mass. So 0.1 means only the tokens comprising the top 10% probability mass + are considered. + + We generally recommend altering this or `temperature` but not both. + + reasoning_effort : typing.Optional[ReasoningEffort] + The effort to use for reasoning + + max_tokens : typing.Optional[int] + The maximum number of tokens that can be generated in the chat completion. + + stream : typing.Optional[bool] + If set to true, the model response data will be streamed to the client + as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + When true, returns an Iterator[ChatCompletionChunk] instead of HttpResponse. + + stop : typing.Optional[StopConfigurationParams] + + n : typing.Optional[int] + How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + + seed : typing.Optional[int] + This feature is in Beta. + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + + frequency_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + their existing frequency in the text so far, decreasing the model's + likelihood to repeat the same line verbatim. + + presence_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood + to talk about new topics. + + wiki_grounding : typing.Optional[bool] + If set to true, the model response will be wiki grounded. + + tools : typing.Optional[typing.Sequence[ChatCompletionToolParams]] + A list of tools the model may call. Currently, only functions are supported as a tool. + + tool_choice : typing.Optional[ToolChoiceOptionParams] + Controls which (if any) tool is called by the model. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[CreateChatCompletionResponse] or Iterator[ChatCompletionChunk] + When stream=False (default): HttpResponse wrapping CreateChatCompletionResponse. + When stream=True: Iterator yielding ChatCompletionChunk objects. + """ + if stream is True: + return self._completions_stream( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=reasoning_effort, + max_tokens=max_tokens, + stop=stop, + n=n, + seed=seed, + frequency_penalty=frequency_penalty, + presence_penalty=presence_penalty, + wiki_grounding=wiki_grounding, + tools=tools, + tool_choice=tool_choice, + request_options=request_options, + ) + + _response = self._client_wrapper.httpx_client.request( + "v1/chat/completions", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "messages": convert_and_respect_annotation_metadata( + object_=messages, annotation=typing.Sequence[ChatCompletionRequestMessageParams], direction="write" + ), + "model": model, + "temperature": temperature, + "top_p": top_p, + "reasoning_effort": reasoning_effort, + "max_tokens": max_tokens, + "stream": stream, + "stop": convert_and_respect_annotation_metadata( + object_=stop, annotation=StopConfigurationParams, direction="write" + ), + "n": n, + "seed": seed, + "frequency_penalty": frequency_penalty, + "presence_penalty": presence_penalty, + "wiki_grounding": wiki_grounding, + "tools": convert_and_respect_annotation_metadata( + object_=tools, annotation=typing.Sequence[ChatCompletionToolParams], direction="write" + ), + "tool_choice": convert_and_respect_annotation_metadata( + object_=tool_choice, annotation=ToolChoiceOptionParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + CreateChatCompletionResponse, + parse_obj_as( + type_=CreateChatCompletionResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=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( + headers=dict(_response.headers), + body=typing.cast( + typing.Optional[typing.Any], + parse_obj_as( + type_=typing.Optional[typing.Any], # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=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( + headers=dict(_response.headers), + body=typing.cast( + typing.Optional[typing.Any], + parse_obj_as( + type_=typing.Optional[typing.Any], # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=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, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def _completions_stream( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = OMIT, + top_p: typing.Optional[float] = OMIT, + reasoning_effort: typing.Optional[ReasoningEffort] = OMIT, + max_tokens: typing.Optional[int] = OMIT, + stop: typing.Optional[StopConfigurationParams] = OMIT, + n: typing.Optional[int] = OMIT, + seed: typing.Optional[int] = OMIT, + frequency_penalty: typing.Optional[float] = OMIT, + presence_penalty: typing.Optional[float] = OMIT, + wiki_grounding: typing.Optional[bool] = OMIT, + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = OMIT, + tool_choice: typing.Optional[ToolChoiceOptionParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[ChatCompletionChunk]: + with self._client_wrapper.httpx_client.stream( + "v1/chat/completions", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "messages": convert_and_respect_annotation_metadata( + object_=messages, annotation=typing.Sequence[ChatCompletionRequestMessageParams], direction="write" + ), + "model": model, + "temperature": temperature, + "top_p": top_p, + "reasoning_effort": reasoning_effort, + "max_tokens": max_tokens, + "stream": True, + "stop": convert_and_respect_annotation_metadata( + object_=stop, annotation=StopConfigurationParams, direction="write" + ), + "n": n, + "seed": seed, + "frequency_penalty": frequency_penalty, + "presence_penalty": presence_penalty, + "wiki_grounding": wiki_grounding, + "tools": convert_and_respect_annotation_metadata( + object_=tools, annotation=typing.Sequence[ChatCompletionToolParams], direction="write" + ), + "tool_choice": convert_and_respect_annotation_metadata( + object_=tool_choice, annotation=ToolChoiceOptionParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) as _response: + if not (200 <= _response.status_code < 300): + _response.read() + try: + _body = _response.json() + except Exception: + _body = _response.text + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_body) + + for _line in _response.iter_lines(): + if not _line: + continue + if _line.startswith("data: "): + _data_str = _line[len("data: "):] + if _data_str.strip() == "[DONE]": + return + try: + _chunk_json = json.loads(_data_str) + _chunk = typing.cast( + ChatCompletionChunk, + parse_obj_as( + type_=ChatCompletionChunk, # type: ignore + object_=_chunk_json, + ), + ) + yield _chunk + except json.JSONDecodeError: + continue + + +class AsyncRawChatClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + @typing.overload + async def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Literal[True], + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> typing.AsyncIterator[ChatCompletionChunk]: ... + + @typing.overload + async def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = ..., + top_p: typing.Optional[float] = ..., + reasoning_effort: typing.Optional[ReasoningEffort] = ..., + max_tokens: typing.Optional[int] = ..., + stream: typing.Optional[typing.Literal[False]] = ..., + stop: typing.Optional[StopConfigurationParams] = ..., + n: typing.Optional[int] = ..., + seed: typing.Optional[int] = ..., + frequency_penalty: typing.Optional[float] = ..., + presence_penalty: typing.Optional[float] = ..., + wiki_grounding: typing.Optional[bool] = ..., + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = ..., + tool_choice: typing.Optional[ToolChoiceOptionParams] = ..., + request_options: typing.Optional[RequestOptions] = ..., + ) -> AsyncHttpResponse[CreateChatCompletionResponse]: ... + + async def completions( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = OMIT, + top_p: typing.Optional[float] = OMIT, + reasoning_effort: typing.Optional[ReasoningEffort] = OMIT, + max_tokens: typing.Optional[int] = OMIT, + stream: typing.Optional[bool] = OMIT, + stop: typing.Optional[StopConfigurationParams] = OMIT, + n: typing.Optional[int] = OMIT, + seed: typing.Optional[int] = OMIT, + frequency_penalty: typing.Optional[float] = OMIT, + presence_penalty: typing.Optional[float] = OMIT, + wiki_grounding: typing.Optional[bool] = OMIT, + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = OMIT, + tool_choice: typing.Optional[ToolChoiceOptionParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Union[AsyncHttpResponse[CreateChatCompletionResponse], typing.AsyncIterator[ChatCompletionChunk]]: + """ + Parameters + ---------- + messages : typing.Sequence[ChatCompletionRequestMessageParams] + A list of messages comprising the conversation so far. + + model : SarvamModelIds + Model ID used to generate the response, like `sarvam-m`. + + temperature : typing.Optional[float] + What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + We generally recommend altering this or `top_p` but not both. + + top_p : typing.Optional[float] + An alternative to sampling with temperature, called nucleus sampling, + where the model considers the results of the tokens with top_p probability + mass. So 0.1 means only the tokens comprising the top 10% probability mass + are considered. + + We generally recommend altering this or `temperature` but not both. + + reasoning_effort : typing.Optional[ReasoningEffort] + The effort to use for reasoning + + max_tokens : typing.Optional[int] + The maximum number of tokens that can be generated in the chat completion. + + stream : typing.Optional[bool] + If set to true, the model response data will be streamed to the client + as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + When true, returns an AsyncIterator[ChatCompletionChunk] instead of AsyncHttpResponse. + + stop : typing.Optional[StopConfigurationParams] + + n : typing.Optional[int] + How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + + seed : typing.Optional[int] + This feature is in Beta. + If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + + frequency_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + their existing frequency in the text so far, decreasing the model's + likelihood to repeat the same line verbatim. + + presence_penalty : typing.Optional[float] + Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood + to talk about new topics. + + wiki_grounding : typing.Optional[bool] + If set to true, the model response will be wiki grounded. + + tools : typing.Optional[typing.Sequence[ChatCompletionToolParams]] + A list of tools the model may call. Currently, only functions are supported as a tool. + + tool_choice : typing.Optional[ToolChoiceOptionParams] + Controls which (if any) tool is called by the model. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[CreateChatCompletionResponse] or AsyncIterator[ChatCompletionChunk] + When stream=False (default): AsyncHttpResponse wrapping CreateChatCompletionResponse. + When stream=True: AsyncIterator yielding ChatCompletionChunk objects. + """ + if stream is True: + return self._completions_stream( + messages=messages, + model=model, + temperature=temperature, + top_p=top_p, + reasoning_effort=reasoning_effort, + max_tokens=max_tokens, + stop=stop, + n=n, + seed=seed, + frequency_penalty=frequency_penalty, + presence_penalty=presence_penalty, + wiki_grounding=wiki_grounding, + tools=tools, + tool_choice=tool_choice, + request_options=request_options, + ) + + _response = await self._client_wrapper.httpx_client.request( + "v1/chat/completions", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "messages": convert_and_respect_annotation_metadata( + object_=messages, annotation=typing.Sequence[ChatCompletionRequestMessageParams], direction="write" + ), + "model": model, + "temperature": temperature, + "top_p": top_p, + "reasoning_effort": reasoning_effort, + "max_tokens": max_tokens, + "stream": stream, + "stop": convert_and_respect_annotation_metadata( + object_=stop, annotation=StopConfigurationParams, direction="write" + ), + "n": n, + "seed": seed, + "frequency_penalty": frequency_penalty, + "presence_penalty": presence_penalty, + "wiki_grounding": wiki_grounding, + "tools": convert_and_respect_annotation_metadata( + object_=tools, annotation=typing.Sequence[ChatCompletionToolParams], direction="write" + ), + "tool_choice": convert_and_respect_annotation_metadata( + object_=tool_choice, annotation=ToolChoiceOptionParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + CreateChatCompletionResponse, + parse_obj_as( + type_=CreateChatCompletionResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=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( + headers=dict(_response.headers), + body=typing.cast( + typing.Optional[typing.Any], + parse_obj_as( + type_=typing.Optional[typing.Any], # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=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( + headers=dict(_response.headers), + body=typing.cast( + typing.Optional[typing.Any], + parse_obj_as( + type_=typing.Optional[typing.Any], # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=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, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def _completions_stream( + self, + *, + messages: typing.Sequence[ChatCompletionRequestMessageParams], + model: SarvamModelIds, + temperature: typing.Optional[float] = OMIT, + top_p: typing.Optional[float] = OMIT, + reasoning_effort: typing.Optional[ReasoningEffort] = OMIT, + max_tokens: typing.Optional[int] = OMIT, + stop: typing.Optional[StopConfigurationParams] = OMIT, + n: typing.Optional[int] = OMIT, + seed: typing.Optional[int] = OMIT, + frequency_penalty: typing.Optional[float] = OMIT, + presence_penalty: typing.Optional[float] = OMIT, + wiki_grounding: typing.Optional[bool] = OMIT, + tools: typing.Optional[typing.Sequence[ChatCompletionToolParams]] = OMIT, + tool_choice: typing.Optional[ToolChoiceOptionParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[ChatCompletionChunk]: + async with self._client_wrapper.httpx_client.stream( + "v1/chat/completions", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "messages": convert_and_respect_annotation_metadata( + object_=messages, annotation=typing.Sequence[ChatCompletionRequestMessageParams], direction="write" + ), + "model": model, + "temperature": temperature, + "top_p": top_p, + "reasoning_effort": reasoning_effort, + "max_tokens": max_tokens, + "stream": True, + "stop": convert_and_respect_annotation_metadata( + object_=stop, annotation=StopConfigurationParams, direction="write" + ), + "n": n, + "seed": seed, + "frequency_penalty": frequency_penalty, + "presence_penalty": presence_penalty, + "wiki_grounding": wiki_grounding, + "tools": convert_and_respect_annotation_metadata( + object_=tools, annotation=typing.Sequence[ChatCompletionToolParams], direction="write" + ), + "tool_choice": convert_and_respect_annotation_metadata( + object_=tool_choice, annotation=ToolChoiceOptionParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) as _response: + if not (200 <= _response.status_code < 300): + await _response.aread() + try: + _body = _response.json() + except Exception: + _body = _response.text + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_body) + + async for _line in _response.aiter_lines(): + if not _line: + continue + if _line.startswith("data: "): + _data_str = _line[len("data: "):] + if _data_str.strip() == "[DONE]": + return + try: + _chunk_json = json.loads(_data_str) + _chunk = typing.cast( + ChatCompletionChunk, + parse_obj_as( + type_=ChatCompletionChunk, # type: ignore + object_=_chunk_json, + ), + ) + yield _chunk + except json.JSONDecodeError: + continue diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb31b40f24d6962f678726de077334b487641f55 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/__init__.py @@ -0,0 +1,132 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .api_error import ApiError + from .client_wrapper import AsyncClientWrapper, BaseClientWrapper, SyncClientWrapper + from .datetime_utils import Rfc2822DateTime, parse_rfc2822_datetime, serialize_datetime + from .events import EventEmitterMixin, EventType + from .file import File, convert_file_dict_to_httpx_tuples, with_content_type + from .http_client import AsyncHttpClient, HttpClient + from .http_response import AsyncHttpResponse, HttpResponse + from .jsonable_encoder import jsonable_encoder + from .logging import ConsoleLogger, ILogger, LogConfig, LogLevel, Logger, create_logger + from .pydantic_utilities import ( + IS_PYDANTIC_V2, + UniversalBaseModel, + UniversalRootModel, + parse_obj_as, + universal_field_validator, + universal_root_validator, + update_forward_refs, + ) + from .query_encoder import encode_query + from .remove_none_from_dict import remove_none_from_dict + from .request_options import RequestOptions + from .serialization import FieldMetadata, convert_and_respect_annotation_metadata + from .websocket_compat import InvalidWebSocketStatus, get_status_code +_dynamic_imports: typing.Dict[str, str] = { + "ApiError": ".api_error", + "AsyncClientWrapper": ".client_wrapper", + "AsyncHttpClient": ".http_client", + "AsyncHttpResponse": ".http_response", + "BaseClientWrapper": ".client_wrapper", + "ConsoleLogger": ".logging", + "EventEmitterMixin": ".events", + "EventType": ".events", + "FieldMetadata": ".serialization", + "File": ".file", + "HttpClient": ".http_client", + "HttpResponse": ".http_response", + "ILogger": ".logging", + "IS_PYDANTIC_V2": ".pydantic_utilities", + "InvalidWebSocketStatus": ".websocket_compat", + "LogConfig": ".logging", + "LogLevel": ".logging", + "Logger": ".logging", + "RequestOptions": ".request_options", + "Rfc2822DateTime": ".datetime_utils", + "SyncClientWrapper": ".client_wrapper", + "UniversalBaseModel": ".pydantic_utilities", + "UniversalRootModel": ".pydantic_utilities", + "convert_and_respect_annotation_metadata": ".serialization", + "convert_file_dict_to_httpx_tuples": ".file", + "create_logger": ".logging", + "encode_query": ".query_encoder", + "get_status_code": ".websocket_compat", + "jsonable_encoder": ".jsonable_encoder", + "parse_obj_as": ".pydantic_utilities", + "parse_rfc2822_datetime": ".datetime_utils", + "remove_none_from_dict": ".remove_none_from_dict", + "serialize_datetime": ".datetime_utils", + "universal_field_validator": ".pydantic_utilities", + "universal_root_validator": ".pydantic_utilities", + "update_forward_refs": ".pydantic_utilities", + "with_content_type": ".file", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "ApiError", + "AsyncClientWrapper", + "AsyncHttpClient", + "AsyncHttpResponse", + "BaseClientWrapper", + "ConsoleLogger", + "EventEmitterMixin", + "EventType", + "FieldMetadata", + "File", + "HttpClient", + "HttpResponse", + "ILogger", + "IS_PYDANTIC_V2", + "InvalidWebSocketStatus", + "LogConfig", + "LogLevel", + "Logger", + "RequestOptions", + "Rfc2822DateTime", + "SyncClientWrapper", + "UniversalBaseModel", + "UniversalRootModel", + "convert_and_respect_annotation_metadata", + "convert_file_dict_to_httpx_tuples", + "create_logger", + "encode_query", + "get_status_code", + "jsonable_encoder", + "parse_obj_as", + "parse_rfc2822_datetime", + "remove_none_from_dict", + "serialize_datetime", + "universal_field_validator", + "universal_root_validator", + "update_forward_refs", + "with_content_type", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/api_error.py b/venv/lib/python3.12/site-packages/sarvamai/core/api_error.py new file mode 100644 index 0000000000000000000000000000000000000000..6f850a60cba321de59f940ea48995e15c7978048 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/api_error.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Any, Dict, Optional + + +class ApiError(Exception): + headers: Optional[Dict[str, str]] + status_code: Optional[int] + body: Any + + def __init__( + self, + *, + headers: Optional[Dict[str, str]] = None, + status_code: Optional[int] = None, + body: Any = None, + ) -> None: + self.headers = headers + self.status_code = status_code + self.body = body + + def __str__(self) -> str: + return f"headers: {self.headers}, status_code: {self.status_code}, body: {self.body}" diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/client_wrapper.py b/venv/lib/python3.12/site-packages/sarvamai/core/client_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..7148cf2c2375d083a294b46916fe371fd1febe8a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/client_wrapper.py @@ -0,0 +1,111 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import httpx +from ..environment import SarvamAIEnvironment +from .http_client import AsyncHttpClient, HttpClient +from .logging import LogConfig, Logger + + +class BaseClientWrapper: + def __init__( + self, + *, + api_subscription_key: str, + headers: typing.Optional[typing.Dict[str, str]] = None, + environment: SarvamAIEnvironment, + timeout: typing.Optional[float] = None, + logging: typing.Optional[typing.Union[LogConfig, Logger]] = None, + ): + self.api_subscription_key = api_subscription_key + self._headers = headers + self._environment = environment + self._timeout = timeout + self._logging = logging + + def get_headers(self) -> typing.Dict[str, str]: + import platform + + headers: typing.Dict[str, str] = { + "User-Agent": "sarvamai/0.1.28", + "X-Fern-Language": "Python", + "X-Fern-Runtime": f"python/{platform.python_version()}", + "X-Fern-Platform": f"{platform.system().lower()}/{platform.release()}", + "X-Fern-SDK-Name": "sarvamai", + "X-Fern-SDK-Version": "0.1.28", + **(self.get_custom_headers() or {}), + } + headers["api-subscription-key"] = self.api_subscription_key + return headers + + def get_custom_headers(self) -> typing.Optional[typing.Dict[str, str]]: + return self._headers + + def get_environment(self) -> SarvamAIEnvironment: + return self._environment + + def get_timeout(self) -> typing.Optional[float]: + return self._timeout + + +class SyncClientWrapper(BaseClientWrapper): + def __init__( + self, + *, + api_subscription_key: str, + headers: typing.Optional[typing.Dict[str, str]] = None, + environment: SarvamAIEnvironment, + timeout: typing.Optional[float] = None, + logging: typing.Optional[typing.Union[LogConfig, Logger]] = None, + httpx_client: httpx.Client, + ): + super().__init__( + api_subscription_key=api_subscription_key, + headers=headers, + environment=environment, + timeout=timeout, + logging=logging, + ) + self.httpx_client = HttpClient( + httpx_client=httpx_client, + base_headers=self.get_headers, + base_timeout=self.get_timeout, + logging_config=self._logging, + ) + + +class AsyncClientWrapper(BaseClientWrapper): + def __init__( + self, + *, + api_subscription_key: str, + headers: typing.Optional[typing.Dict[str, str]] = None, + environment: SarvamAIEnvironment, + timeout: typing.Optional[float] = None, + logging: typing.Optional[typing.Union[LogConfig, Logger]] = None, + async_token: typing.Optional[typing.Callable[[], typing.Awaitable[str]]] = None, + httpx_client: httpx.AsyncClient, + ): + super().__init__( + api_subscription_key=api_subscription_key, + headers=headers, + environment=environment, + timeout=timeout, + logging=logging, + ) + self._async_token = async_token + self.httpx_client = AsyncHttpClient( + httpx_client=httpx_client, + base_headers=self.get_headers, + base_timeout=self.get_timeout, + async_base_headers=self.async_get_headers, + logging_config=self._logging, + ) + + async def async_get_headers(self) -> typing.Dict[str, str]: + headers = self.get_headers() + if self._async_token is not None: + token = await self._async_token() + headers["Authorization"] = f"Bearer {token}" + return headers diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/datetime_utils.py b/venv/lib/python3.12/site-packages/sarvamai/core/datetime_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a12b2ad03c5338e654ef64f96b9b0f25007a9d92 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/datetime_utils.py @@ -0,0 +1,70 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt +from email.utils import parsedate_to_datetime +from typing import Any + +import pydantic + +IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.") + + +def parse_rfc2822_datetime(v: Any) -> dt.datetime: + """ + Parse an RFC 2822 datetime string (e.g., "Wed, 02 Oct 2002 13:00:00 GMT") + into a datetime object. If the value is already a datetime, return it as-is. + Falls back to ISO 8601 parsing if RFC 2822 parsing fails. + """ + if isinstance(v, dt.datetime): + return v + if isinstance(v, str): + try: + return parsedate_to_datetime(v) + except Exception: + pass + # Fallback to ISO 8601 parsing + return dt.datetime.fromisoformat(v.replace("Z", "+00:00")) + raise ValueError(f"Expected str or datetime, got {type(v)}") + + +class Rfc2822DateTime(dt.datetime): + """A datetime subclass that parses RFC 2822 date strings. + + On Pydantic V1, uses __get_validators__ for pre-validation. + On Pydantic V2, uses __get_pydantic_core_schema__ for BeforeValidator-style parsing. + """ + + @classmethod + def __get_validators__(cls): # type: ignore[no-untyped-def] + yield parse_rfc2822_datetime + + @classmethod + def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: Any) -> Any: # type: ignore[override] + from pydantic_core import core_schema + + return core_schema.no_info_before_validator_function(parse_rfc2822_datetime, core_schema.datetime_schema()) + + +def serialize_datetime(v: dt.datetime) -> str: + """ + Serialize a datetime including timezone info. + + Uses the timezone info provided if present, otherwise uses the current runtime's timezone info. + + UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00. + """ + + def _serialize_zoned_datetime(v: dt.datetime) -> str: + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + # UTC is a special case where we use "Z" at the end instead of "+00:00" + return v.isoformat().replace("+00:00", "Z") + else: + # Delegate to the typical +/- offset format + return v.isoformat() + + if v.tzinfo is not None: + return _serialize_zoned_datetime(v) + else: + local_tz = dt.datetime.now().astimezone().tzinfo + localized_dt = v.replace(tzinfo=local_tz) + return _serialize_zoned_datetime(localized_dt) diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/events.py b/venv/lib/python3.12/site-packages/sarvamai/core/events.py new file mode 100644 index 0000000000000000000000000000000000000000..afbeec507fe0a9ea13f8ee17a2c266889fb5b9cd --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/events.py @@ -0,0 +1,38 @@ +# This file was auto-generated by Fern from our API Definition. + +import inspect +import typing +from enum import Enum + + +class EventType(str, Enum): + OPEN = "open" + MESSAGE = "message" + ERROR = "error" + CLOSE = "close" + + +class EventEmitterMixin: + """ + Simple mixin for registering and emitting events. + """ + + def __init__(self) -> None: + self._callbacks: typing.Dict[EventType, typing.List[typing.Callable]] = {} + + def on(self, event_name: EventType, callback: typing.Callable[[typing.Any], typing.Any]) -> None: + if event_name not in self._callbacks: + self._callbacks[event_name] = [] + self._callbacks[event_name].append(callback) + + def _emit(self, event_name: EventType, data: typing.Any) -> None: + if event_name in self._callbacks: + for cb in self._callbacks[event_name]: + cb(data) + + async def _emit_async(self, event_name: EventType, data: typing.Any) -> None: + if event_name in self._callbacks: + for cb in self._callbacks[event_name]: + res = cb(data) + if inspect.isawaitable(res): + await res diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/file.py b/venv/lib/python3.12/site-packages/sarvamai/core/file.py new file mode 100644 index 0000000000000000000000000000000000000000..44b0d27c08952bcf507d01558ee469408c8d9abe --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/file.py @@ -0,0 +1,67 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import IO, Dict, List, Mapping, Optional, Tuple, Union, cast + +# File typing inspired by the flexibility of types within the httpx library +# https://github.com/encode/httpx/blob/master/httpx/_types.py +FileContent = Union[IO[bytes], bytes, str] +File = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[ + Optional[str], + FileContent, + Optional[str], + Mapping[str, str], + ], +] + + +def convert_file_dict_to_httpx_tuples( + d: Dict[str, Union[File, List[File]]], +) -> List[Tuple[str, File]]: + """ + The format we use is a list of tuples, where the first element is the + name of the file and the second is the file object. Typically HTTPX wants + a dict, but to be able to send lists of files, you have to use the list + approach (which also works for non-lists) + https://github.com/encode/httpx/pull/1032 + """ + + httpx_tuples = [] + for key, file_like in d.items(): + if isinstance(file_like, list): + for file_like_item in file_like: + httpx_tuples.append((key, file_like_item)) + else: + httpx_tuples.append((key, file_like)) + return httpx_tuples + + +def with_content_type(*, file: File, default_content_type: str) -> File: + """ + This function resolves to the file's content type, if provided, and defaults + to the default_content_type value if not. + """ + if isinstance(file, tuple): + if len(file) == 2: + filename, content = cast(Tuple[Optional[str], FileContent], file) # type: ignore + return (filename, content, default_content_type) + elif len(file) == 3: + filename, content, file_content_type = cast(Tuple[Optional[str], FileContent, Optional[str]], file) # type: ignore + out_content_type = file_content_type or default_content_type + return (filename, content, out_content_type) + elif len(file) == 4: + filename, content, file_content_type, headers = cast( # type: ignore + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], file + ) + out_content_type = file_content_type or default_content_type + return (filename, content, out_content_type, headers) + else: + raise ValueError(f"Unexpected tuple length: {len(file)}") + return (None, file, default_content_type) diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/force_multipart.py b/venv/lib/python3.12/site-packages/sarvamai/core/force_multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..5440913fd4bc8760e3cdb3a61855d87f5f41b859 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/force_multipart.py @@ -0,0 +1,18 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Any, Dict + + +class ForceMultipartDict(Dict[str, Any]): + """ + A dictionary subclass that always evaluates to True in boolean contexts. + + This is used to force multipart/form-data encoding in HTTP requests even when + the dictionary is empty, which would normally evaluate to False. + """ + + def __bool__(self) -> bool: + return True + + +FORCE_MULTIPART = ForceMultipartDict() diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/http_client.py b/venv/lib/python3.12/site-packages/sarvamai/core/http_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ee937589c9c7436ce73cf0960ae45e691c3e2aed --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/http_client.py @@ -0,0 +1,776 @@ +# This file was auto-generated by Fern from our API Definition. + +import asyncio +import email.utils +import re +import time +import typing +from contextlib import asynccontextmanager, contextmanager +from random import random + +import httpx +from .file import File, convert_file_dict_to_httpx_tuples +from .force_multipart import FORCE_MULTIPART +from .jsonable_encoder import jsonable_encoder +from .logging import LogConfig, Logger, create_logger +from .query_encoder import encode_query +from .remove_none_from_dict import remove_none_from_dict as remove_none_from_dict +from .request_options import RequestOptions +from httpx._types import RequestFiles + +INITIAL_RETRY_DELAY_SECONDS = 1.0 +MAX_RETRY_DELAY_SECONDS = 60.0 +JITTER_FACTOR = 0.2 # 20% random jitter + + +def _parse_retry_after(response_headers: httpx.Headers) -> typing.Optional[float]: + """ + This function parses the `Retry-After` header in a HTTP response and returns the number of seconds to wait. + + Inspired by the urllib3 retry implementation. + """ + retry_after_ms = response_headers.get("retry-after-ms") + if retry_after_ms is not None: + try: + return int(retry_after_ms) / 1000 if retry_after_ms > 0 else 0 + except Exception: + pass + + retry_after = response_headers.get("retry-after") + if retry_after is None: + return None + + # Attempt to parse the header as an int. + if re.match(r"^\s*[0-9]+\s*$", retry_after): + seconds = float(retry_after) + # Fallback to parsing it as a date. + else: + retry_date_tuple = email.utils.parsedate_tz(retry_after) + if retry_date_tuple is None: + return None + if retry_date_tuple[9] is None: # Python 2 + # Assume UTC if no timezone was specified + # On Python2.7, parsedate_tz returns None for a timezone offset + # instead of 0 if no timezone is given, where mktime_tz treats + # a None timezone offset as local time. + retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:] + + retry_date = email.utils.mktime_tz(retry_date_tuple) + seconds = retry_date - time.time() + + if seconds < 0: + seconds = 0 + + return seconds + + +def _add_positive_jitter(delay: float) -> float: + """Add positive jitter (0-20%) to prevent thundering herd.""" + jitter_multiplier = 1 + random() * JITTER_FACTOR + return delay * jitter_multiplier + + +def _add_symmetric_jitter(delay: float) -> float: + """Add symmetric jitter (±10%) for exponential backoff.""" + jitter_multiplier = 1 + (random() - 0.5) * JITTER_FACTOR + return delay * jitter_multiplier + + +def _parse_x_ratelimit_reset(response_headers: httpx.Headers) -> typing.Optional[float]: + """ + Parse the X-RateLimit-Reset header (Unix timestamp in seconds). + Returns seconds to wait, or None if header is missing/invalid. + """ + reset_time_str = response_headers.get("x-ratelimit-reset") + if reset_time_str is None: + return None + + try: + reset_time = int(reset_time_str) + delay = reset_time - time.time() + if delay > 0: + return delay + except (ValueError, TypeError): + pass + + return None + + +def _retry_timeout(response: httpx.Response, retries: int) -> float: + """ + Determine the amount of time to wait before retrying a request. + This function begins by trying to parse a retry-after header from the response, and then proceeds to use exponential backoff + with a jitter to determine the number of seconds to wait. + """ + + # 1. Check Retry-After header first + retry_after = _parse_retry_after(response.headers) + if retry_after is not None and retry_after > 0: + return min(retry_after, MAX_RETRY_DELAY_SECONDS) + + # 2. Check X-RateLimit-Reset header (with positive jitter) + ratelimit_reset = _parse_x_ratelimit_reset(response.headers) + if ratelimit_reset is not None: + return _add_positive_jitter(min(ratelimit_reset, MAX_RETRY_DELAY_SECONDS)) + + # 3. Fall back to exponential backoff (with symmetric jitter) + backoff = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + return _add_symmetric_jitter(backoff) + + +def _should_retry(response: httpx.Response) -> bool: + retryable_400s = [429, 408, 409] + return response.status_code >= 500 or response.status_code in retryable_400s + + +_SENSITIVE_HEADERS = frozenset( + { + "authorization", + "www-authenticate", + "x-api-key", + "api-key", + "apikey", + "x-api-token", + "x-auth-token", + "auth-token", + "cookie", + "set-cookie", + "proxy-authorization", + "proxy-authenticate", + "x-csrf-token", + "x-xsrf-token", + "x-session-token", + "x-access-token", + } +) + + +def _redact_headers(headers: typing.Dict[str, str]) -> typing.Dict[str, str]: + return {k: ("[REDACTED]" if k.lower() in _SENSITIVE_HEADERS else v) for k, v in headers.items()} + + +def _build_url(base_url: str, path: typing.Optional[str]) -> str: + """ + Build a full URL by joining a base URL with a path. + + This function correctly handles base URLs that contain path prefixes (e.g., tenant-based URLs) + by using string concatenation instead of urllib.parse.urljoin(), which would incorrectly + strip path components when the path starts with '/'. + + Example: + >>> _build_url("https://cloud.example.com/org/tenant/api", "/users") + 'https://cloud.example.com/org/tenant/api/users' + + Args: + base_url: The base URL, which may contain path prefixes. + path: The path to append. Can be None or empty string. + + Returns: + The full URL with base_url and path properly joined. + """ + if not path: + return base_url + return f"{base_url.rstrip('/')}/{path.lstrip('/')}" + + +def _maybe_filter_none_from_multipart_data( + data: typing.Optional[typing.Any], + request_files: typing.Optional[RequestFiles], + force_multipart: typing.Optional[bool], +) -> typing.Optional[typing.Any]: + """ + Filter None values from data body for multipart/form requests. + This prevents httpx from converting None to empty strings in multipart encoding. + Only applies when files are present or force_multipart is True. + """ + if data is not None and isinstance(data, typing.Mapping) and (request_files or force_multipart): + return remove_none_from_dict(data) + return data + + +def remove_omit_from_dict( + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], +) -> typing.Dict[str, typing.Any]: + if omit is None: + return original + new: typing.Dict[str, typing.Any] = {} + for key, value in original.items(): + if value is not omit: + new[key] = value + return new + + +def maybe_filter_request_body( + data: typing.Optional[typing.Any], + request_options: typing.Optional[RequestOptions], + omit: typing.Optional[typing.Any], +) -> typing.Optional[typing.Any]: + if data is None: + return ( + jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + if request_options is not None + else None + ) + elif not isinstance(data, typing.Mapping): + data_content = jsonable_encoder(data) + else: + data_content = { + **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore + **( + jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + if request_options is not None + else {} + ), + } + return data_content + + +# Abstracted out for testing purposes +def get_request_body( + *, + json: typing.Optional[typing.Any], + data: typing.Optional[typing.Any], + request_options: typing.Optional[RequestOptions], + omit: typing.Optional[typing.Any], +) -> typing.Tuple[typing.Optional[typing.Any], typing.Optional[typing.Any]]: + json_body = None + data_body = None + if data is not None: + data_body = maybe_filter_request_body(data, request_options, omit) + else: + # If both data and json are None, we send json data in the event extra properties are specified + json_body = maybe_filter_request_body(json, request_options, omit) + + has_additional_body_parameters = bool( + request_options is not None and request_options.get("additional_body_parameters") + ) + + # Only collapse empty dict to None when the body was not explicitly provided + # and there are no additional body parameters. This preserves explicit empty + # bodies (e.g., when an endpoint has a request body type but all fields are optional). + if json_body == {} and json is None and not has_additional_body_parameters: + json_body = None + if data_body == {} and data is None and not has_additional_body_parameters: + data_body = None + + return json_body, data_body + + +class HttpClient: + def __init__( + self, + *, + httpx_client: httpx.Client, + base_timeout: typing.Callable[[], typing.Optional[float]], + base_headers: typing.Callable[[], typing.Dict[str, str]], + base_url: typing.Optional[typing.Callable[[], str]] = None, + logging_config: typing.Optional[typing.Union[LogConfig, Logger]] = None, + ): + self.base_url = base_url + self.base_timeout = base_timeout + self.base_headers = base_headers + self.httpx_client = httpx_client + self.logger = create_logger(logging_config) + + def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: + base_url = maybe_base_url + if self.base_url is not None and base_url is None: + base_url = self.base_url() + + if base_url is None: + raise ValueError("A base_url is required to make this request, please provide one and try again.") + return base_url + + def request( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[ + typing.Union[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]], + typing.List[typing.Tuple[str, File]], + ] + ] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 0, + omit: typing.Optional[typing.Any] = None, + force_multipart: typing.Optional[bool] = None, + ) -> httpx.Response: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + request_files: typing.Optional[RequestFiles] = ( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if (files is not None and files is not omit and isinstance(files, dict)) + else None + ) + + if (request_files is None or len(request_files) == 0) and force_multipart: + request_files = FORCE_MULTIPART + + data_body = _maybe_filter_none_from_multipart_data(data_body, request_files, force_multipart) + + # Compute encoded params separately to avoid passing empty list to httpx + # (httpx strips existing query params from URL when params=[] is passed) + _encoded_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + }, + omit, + ) + ) + ) + ) + + _request_url = _build_url(base_url, path) + _request_headers = jsonable_encoder( + remove_none_from_dict( + { + **self.base_headers(), + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + } + ) + ) + + if self.logger.is_debug(): + self.logger.debug( + "Making HTTP request", + method=method, + url=_request_url, + headers=_redact_headers(_request_headers), + has_body=json_body is not None or data_body is not None, + ) + + response = self.httpx_client.request( + method=method, + url=_request_url, + headers=_request_headers, + params=_encoded_params if _encoded_params else None, + json=json_body, + data=data_body, + content=content, + files=request_files, + timeout=timeout, + ) + + max_retries: int = request_options.get("max_retries", 2) if request_options is not None else 2 + if _should_retry(response=response): + if retries < max_retries: + time.sleep(_retry_timeout(response=response, retries=retries)) + return self.request( + path=path, + method=method, + base_url=base_url, + params=params, + json=json, + content=content, + files=files, + headers=headers, + request_options=request_options, + retries=retries + 1, + omit=omit, + ) + + if self.logger.is_debug(): + if 200 <= response.status_code < 400: + self.logger.debug( + "HTTP request succeeded", + method=method, + url=_request_url, + status_code=response.status_code, + ) + + if self.logger.is_error(): + if response.status_code >= 400: + self.logger.error( + "HTTP request failed with error status", + method=method, + url=_request_url, + status_code=response.status_code, + ) + + return response + + @contextmanager + def stream( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[ + typing.Union[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]], + typing.List[typing.Tuple[str, File]], + ] + ] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 0, + omit: typing.Optional[typing.Any] = None, + force_multipart: typing.Optional[bool] = None, + ) -> typing.Iterator[httpx.Response]: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + request_files: typing.Optional[RequestFiles] = ( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if (files is not None and files is not omit and isinstance(files, dict)) + else None + ) + + if (request_files is None or len(request_files) == 0) and force_multipart: + request_files = FORCE_MULTIPART + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + data_body = _maybe_filter_none_from_multipart_data(data_body, request_files, force_multipart) + + # Compute encoded params separately to avoid passing empty list to httpx + # (httpx strips existing query params from URL when params=[] is passed) + _encoded_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) + if request_options is not None + else {} + ), + }, + omit, + ) + ) + ) + ) + + _request_url = _build_url(base_url, path) + _request_headers = jsonable_encoder( + remove_none_from_dict( + { + **self.base_headers(), + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) if request_options is not None else {}), + } + ) + ) + + if self.logger.is_debug(): + self.logger.debug( + "Making streaming HTTP request", + method=method, + url=_request_url, + headers=_redact_headers(_request_headers), + ) + + with self.httpx_client.stream( + method=method, + url=_request_url, + headers=_request_headers, + params=_encoded_params if _encoded_params else None, + json=json_body, + data=data_body, + content=content, + files=request_files, + timeout=timeout, + ) as stream: + yield stream + + +class AsyncHttpClient: + def __init__( + self, + *, + httpx_client: httpx.AsyncClient, + base_timeout: typing.Callable[[], typing.Optional[float]], + base_headers: typing.Callable[[], typing.Dict[str, str]], + base_url: typing.Optional[typing.Callable[[], str]] = None, + async_base_headers: typing.Optional[typing.Callable[[], typing.Awaitable[typing.Dict[str, str]]]] = None, + logging_config: typing.Optional[typing.Union[LogConfig, Logger]] = None, + ): + self.base_url = base_url + self.base_timeout = base_timeout + self.base_headers = base_headers + self.async_base_headers = async_base_headers + self.httpx_client = httpx_client + self.logger = create_logger(logging_config) + + async def _get_headers(self) -> typing.Dict[str, str]: + if self.async_base_headers is not None: + return await self.async_base_headers() + return self.base_headers() + + def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: + base_url = maybe_base_url + if self.base_url is not None and base_url is None: + base_url = self.base_url() + + if base_url is None: + raise ValueError("A base_url is required to make this request, please provide one and try again.") + return base_url + + async def request( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[ + typing.Union[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]], + typing.List[typing.Tuple[str, File]], + ] + ] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 0, + omit: typing.Optional[typing.Any] = None, + force_multipart: typing.Optional[bool] = None, + ) -> httpx.Response: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + request_files: typing.Optional[RequestFiles] = ( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if (files is not None and files is not omit and isinstance(files, dict)) + else None + ) + + if (request_files is None or len(request_files) == 0) and force_multipart: + request_files = FORCE_MULTIPART + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + data_body = _maybe_filter_none_from_multipart_data(data_body, request_files, force_multipart) + + # Get headers (supports async token providers) + _headers = await self._get_headers() + + # Compute encoded params separately to avoid passing empty list to httpx + # (httpx strips existing query params from URL when params=[] is passed) + _encoded_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + }, + omit, + ) + ) + ) + ) + + _request_url = _build_url(base_url, path) + _request_headers = jsonable_encoder( + remove_none_from_dict( + { + **_headers, + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + } + ) + ) + + if self.logger.is_debug(): + self.logger.debug( + "Making HTTP request", + method=method, + url=_request_url, + headers=_redact_headers(_request_headers), + has_body=json_body is not None or data_body is not None, + ) + + response = await self.httpx_client.request( + method=method, + url=_request_url, + headers=_request_headers, + params=_encoded_params if _encoded_params else None, + json=json_body, + data=data_body, + content=content, + files=request_files, + timeout=timeout, + ) + + max_retries: int = request_options.get("max_retries", 2) if request_options is not None else 2 + if _should_retry(response=response): + if retries < max_retries: + await asyncio.sleep(_retry_timeout(response=response, retries=retries)) + return await self.request( + path=path, + method=method, + base_url=base_url, + params=params, + json=json, + content=content, + files=files, + headers=headers, + request_options=request_options, + retries=retries + 1, + omit=omit, + ) + + if self.logger.is_debug(): + if 200 <= response.status_code < 400: + self.logger.debug( + "HTTP request succeeded", + method=method, + url=_request_url, + status_code=response.status_code, + ) + + if self.logger.is_error(): + if response.status_code >= 400: + self.logger.error( + "HTTP request failed with error status", + method=method, + url=_request_url, + status_code=response.status_code, + ) + + return response + + @asynccontextmanager + async def stream( + self, + path: typing.Optional[str] = None, + *, + method: str, + base_url: typing.Optional[str] = None, + params: typing.Optional[typing.Dict[str, typing.Any]] = None, + json: typing.Optional[typing.Any] = None, + data: typing.Optional[typing.Any] = None, + content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, + files: typing.Optional[ + typing.Union[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]], + typing.List[typing.Tuple[str, File]], + ] + ] = None, + headers: typing.Optional[typing.Dict[str, typing.Any]] = None, + request_options: typing.Optional[RequestOptions] = None, + retries: int = 0, + omit: typing.Optional[typing.Any] = None, + force_multipart: typing.Optional[bool] = None, + ) -> typing.AsyncIterator[httpx.Response]: + base_url = self.get_base_url(base_url) + timeout = ( + request_options.get("timeout_in_seconds") + if request_options is not None and request_options.get("timeout_in_seconds") is not None + else self.base_timeout() + ) + + request_files: typing.Optional[RequestFiles] = ( + convert_file_dict_to_httpx_tuples(remove_omit_from_dict(remove_none_from_dict(files), omit)) + if (files is not None and files is not omit and isinstance(files, dict)) + else None + ) + + if (request_files is None or len(request_files) == 0) and force_multipart: + request_files = FORCE_MULTIPART + + json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + + data_body = _maybe_filter_none_from_multipart_data(data_body, request_files, force_multipart) + + # Get headers (supports async token providers) + _headers = await self._get_headers() + + # Compute encoded params separately to avoid passing empty list to httpx + # (httpx strips existing query params from URL when params=[] is passed) + _encoded_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + remove_omit_from_dict( + { + **(params if params is not None else {}), + **( + request_options.get("additional_query_parameters", {}) + if request_options is not None + else {} + ), + }, + omit=omit, + ) + ) + ) + ) + + _request_url = _build_url(base_url, path) + _request_headers = jsonable_encoder( + remove_none_from_dict( + { + **_headers, + **(headers if headers is not None else {}), + **(request_options.get("additional_headers", {}) if request_options is not None else {}), + } + ) + ) + + if self.logger.is_debug(): + self.logger.debug( + "Making streaming HTTP request", + method=method, + url=_request_url, + headers=_redact_headers(_request_headers), + ) + + async with self.httpx_client.stream( + method=method, + url=_request_url, + headers=_request_headers, + params=_encoded_params if _encoded_params else None, + json=json_body, + data=data_body, + content=content, + files=request_files, + timeout=timeout, + ) as stream: + yield stream diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/http_response.py b/venv/lib/python3.12/site-packages/sarvamai/core/http_response.py new file mode 100644 index 0000000000000000000000000000000000000000..00bb1096d2d0799ba4125298574fcb7dc96dff4f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/http_response.py @@ -0,0 +1,59 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Dict, Generic, TypeVar + +import httpx + +# Generic to represent the underlying type of the data wrapped by the HTTP response. +T = TypeVar("T") + + +class BaseHttpResponse: + """Minimalist HTTP response wrapper that exposes response headers and status code.""" + + _response: httpx.Response + + def __init__(self, response: httpx.Response): + self._response = response + + @property + def headers(self) -> Dict[str, str]: + return dict(self._response.headers) + + @property + def status_code(self) -> int: + return self._response.status_code + + +class HttpResponse(Generic[T], BaseHttpResponse): + """HTTP response wrapper that exposes response headers and data.""" + + _data: T + + def __init__(self, response: httpx.Response, data: T): + super().__init__(response) + self._data = data + + @property + def data(self) -> T: + return self._data + + def close(self) -> None: + self._response.close() + + +class AsyncHttpResponse(Generic[T], BaseHttpResponse): + """HTTP response wrapper that exposes response headers and data.""" + + _data: T + + def __init__(self, response: httpx.Response, data: T): + super().__init__(response) + self._data = data + + @property + def data(self) -> T: + return self._data + + async def close(self) -> None: + await self._response.aclose() diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/jsonable_encoder.py b/venv/lib/python3.12/site-packages/sarvamai/core/jsonable_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..f8beaeafb17f697dff432cd199bf721d1cb77847 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/jsonable_encoder.py @@ -0,0 +1,108 @@ +# This file was auto-generated by Fern from our API Definition. + +""" +jsonable_encoder converts a Python object to a JSON-friendly dict +(e.g. datetimes to strings, Pydantic models to dicts). + +Taken from FastAPI, and made a bit simpler +https://github.com/tiangolo/fastapi/blob/master/fastapi/encoders.py +""" + +import base64 +import dataclasses +import datetime as dt +from enum import Enum +from pathlib import PurePath +from types import GeneratorType +from typing import Any, Callable, Dict, List, Optional, Set, Union + +import pydantic +from .datetime_utils import serialize_datetime +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) + +SetIntStr = Set[Union[int, str]] +DictIntStrAny = Dict[Union[int, str], Any] + + +def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: + custom_encoder = custom_encoder or {} + # Generated SDKs use Ellipsis (`...`) as the sentinel value for "OMIT". + # OMIT values should be excluded from serialized payloads. + if obj is Ellipsis: + return None + if custom_encoder: + if type(obj) in custom_encoder: + return custom_encoder[type(obj)](obj) + else: + for encoder_type, encoder_instance in custom_encoder.items(): + if isinstance(obj, encoder_type): + return encoder_instance(obj) + if isinstance(obj, pydantic.BaseModel): + if IS_PYDANTIC_V2: + encoder = getattr(obj.model_config, "json_encoders", {}) # type: ignore # Pydantic v2 + else: + encoder = getattr(obj.__config__, "json_encoders", {}) # type: ignore # Pydantic v1 + if custom_encoder: + encoder.update(custom_encoder) + obj_dict = obj.dict(by_alias=True) + if "__root__" in obj_dict: + obj_dict = obj_dict["__root__"] + if "root" in obj_dict: + obj_dict = obj_dict["root"] + return jsonable_encoder(obj_dict, custom_encoder=encoder) + if dataclasses.is_dataclass(obj): + obj_dict = dataclasses.asdict(obj) # type: ignore + return jsonable_encoder(obj_dict, custom_encoder=custom_encoder) + if isinstance(obj, bytes): + return base64.b64encode(obj).decode("utf-8") + if isinstance(obj, Enum): + return obj.value + if isinstance(obj, PurePath): + return str(obj) + if isinstance(obj, (str, int, float, type(None))): + return obj + if isinstance(obj, dt.datetime): + return serialize_datetime(obj) + if isinstance(obj, dt.date): + return str(obj) + if isinstance(obj, dict): + encoded_dict = {} + allowed_keys = set(obj.keys()) + for key, value in obj.items(): + if key in allowed_keys: + if value is Ellipsis: + continue + encoded_key = jsonable_encoder(key, custom_encoder=custom_encoder) + encoded_value = jsonable_encoder(value, custom_encoder=custom_encoder) + encoded_dict[encoded_key] = encoded_value + return encoded_dict + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)): + encoded_list = [] + for item in obj: + if item is Ellipsis: + continue + encoded_list.append(jsonable_encoder(item, custom_encoder=custom_encoder)) + return encoded_list + + def fallback_serializer(o: Any) -> Any: + attempt_encode = encode_by_type(o) + if attempt_encode is not None: + return attempt_encode + + try: + data = dict(o) + except Exception as e: + errors: List[Exception] = [] + errors.append(e) + try: + data = vars(o) + except Exception as e: + errors.append(e) + raise ValueError(errors) from e + return jsonable_encoder(data, custom_encoder=custom_encoder) + + return to_jsonable_with_fallback(obj, fallback_serializer) diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/logging.py b/venv/lib/python3.12/site-packages/sarvamai/core/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e572458bc85f883d04ed74e6ab5d4871921d4a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/logging.py @@ -0,0 +1,107 @@ +# This file was auto-generated by Fern from our API Definition. + +import logging +import typing + +LogLevel = typing.Literal["debug", "info", "warn", "error"] + +_LOG_LEVEL_MAP: typing.Dict[LogLevel, int] = { + "debug": 1, + "info": 2, + "warn": 3, + "error": 4, +} + + +class ILogger(typing.Protocol): + def debug(self, message: str, **kwargs: typing.Any) -> None: ... + def info(self, message: str, **kwargs: typing.Any) -> None: ... + def warn(self, message: str, **kwargs: typing.Any) -> None: ... + def error(self, message: str, **kwargs: typing.Any) -> None: ... + + +class ConsoleLogger: + _logger: logging.Logger + + def __init__(self) -> None: + self._logger = logging.getLogger("fern") + if not self._logger.handlers: + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter("%(levelname)s - %(message)s")) + self._logger.addHandler(handler) + self._logger.setLevel(logging.DEBUG) + + def debug(self, message: str, **kwargs: typing.Any) -> None: + self._logger.debug(message, extra=kwargs) + + def info(self, message: str, **kwargs: typing.Any) -> None: + self._logger.info(message, extra=kwargs) + + def warn(self, message: str, **kwargs: typing.Any) -> None: + self._logger.warning(message, extra=kwargs) + + def error(self, message: str, **kwargs: typing.Any) -> None: + self._logger.error(message, extra=kwargs) + + +class LogConfig(typing.TypedDict, total=False): + level: LogLevel + logger: ILogger + silent: bool + + +class Logger: + _level: int + _logger: ILogger + _silent: bool + + def __init__(self, *, level: LogLevel, logger: ILogger, silent: bool) -> None: + self._level = _LOG_LEVEL_MAP[level] + self._logger = logger + self._silent = silent + + def _should_log(self, level: LogLevel) -> bool: + return not self._silent and self._level <= _LOG_LEVEL_MAP[level] + + def is_debug(self) -> bool: + return self._should_log("debug") + + def is_info(self) -> bool: + return self._should_log("info") + + def is_warn(self) -> bool: + return self._should_log("warn") + + def is_error(self) -> bool: + return self._should_log("error") + + def debug(self, message: str, **kwargs: typing.Any) -> None: + if self.is_debug(): + self._logger.debug(message, **kwargs) + + def info(self, message: str, **kwargs: typing.Any) -> None: + if self.is_info(): + self._logger.info(message, **kwargs) + + def warn(self, message: str, **kwargs: typing.Any) -> None: + if self.is_warn(): + self._logger.warn(message, **kwargs) + + def error(self, message: str, **kwargs: typing.Any) -> None: + if self.is_error(): + self._logger.error(message, **kwargs) + + +_default_logger: Logger = Logger(level="info", logger=ConsoleLogger(), silent=True) + + +def create_logger(config: typing.Optional[typing.Union[LogConfig, Logger]] = None) -> Logger: + if config is None: + return _default_logger + if isinstance(config, Logger): + return config + return Logger( + level=config.get("level", "info"), + logger=config.get("logger", ConsoleLogger()), + silent=config.get("silent", True), + ) diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/pydantic_utilities.py b/venv/lib/python3.12/site-packages/sarvamai/core/pydantic_utilities.py new file mode 100644 index 0000000000000000000000000000000000000000..831aadc3edfe74833e6a732162d12cd30045d6b2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/pydantic_utilities.py @@ -0,0 +1,577 @@ +# This file was auto-generated by Fern from our API Definition. + +# nopycln: file +import datetime as dt +import inspect +import json +import logging +from collections import defaultdict +from dataclasses import asdict +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Dict, + List, + Mapping, + Optional, + Set, + Tuple, + Type, + TypeVar, + Union, + cast, +) + +import pydantic +import typing_extensions + +_logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from .http_sse._models import ServerSentEvent + +IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.") + +if IS_PYDANTIC_V2: + import warnings + + _datetime_adapter = pydantic.TypeAdapter(dt.datetime) # type: ignore[attr-defined] + _date_adapter = pydantic.TypeAdapter(dt.date) # type: ignore[attr-defined] + + def parse_datetime(value: Any) -> dt.datetime: # type: ignore[misc] + if isinstance(value, dt.datetime): + return value + return _datetime_adapter.validate_python(value) + + def parse_date(value: Any) -> dt.date: # type: ignore[misc] + if isinstance(value, dt.datetime): + return value.date() + if isinstance(value, dt.date): + return value + return _date_adapter.validate_python(value) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + from pydantic.v1.fields import ModelField as ModelField + from pydantic.v1.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[attr-defined] + from pydantic.v1.typing import get_args as get_args + from pydantic.v1.typing import get_origin as get_origin + from pydantic.v1.typing import is_literal_type as is_literal_type + from pydantic.v1.typing import is_union as is_union +else: + from pydantic.datetime_parse import parse_date as parse_date # type: ignore[no-redef] + from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore[no-redef] + from pydantic.fields import ModelField as ModelField # type: ignore[attr-defined, no-redef] + from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore[no-redef] + from pydantic.typing import get_args as get_args # type: ignore[no-redef] + from pydantic.typing import get_origin as get_origin # type: ignore[no-redef] + from pydantic.typing import is_literal_type as is_literal_type # type: ignore[no-redef] + from pydantic.typing import is_union as is_union # type: ignore[no-redef] + +from .datetime_utils import serialize_datetime +from .serialization import convert_and_respect_annotation_metadata +from typing_extensions import TypeAlias + +T = TypeVar("T") +Model = TypeVar("Model", bound=pydantic.BaseModel) + + +def _get_discriminator_and_variants(type_: Type[Any]) -> Tuple[Optional[str], Optional[List[Type[Any]]]]: + """ + Extract the discriminator field name and union variants from a discriminated union type. + Supports Annotated[Union[...], Field(discriminator=...)] patterns. + Returns (discriminator, variants) or (None, None) if not a discriminated union. + """ + origin = typing_extensions.get_origin(type_) + + if origin is typing_extensions.Annotated: + args = typing_extensions.get_args(type_) + if len(args) >= 2: + inner_type = args[0] + # Check annotations for discriminator + discriminator = None + for annotation in args[1:]: + if hasattr(annotation, "discriminator"): + discriminator = getattr(annotation, "discriminator", None) + break + + if discriminator: + inner_origin = typing_extensions.get_origin(inner_type) + if inner_origin is Union: + variants = list(typing_extensions.get_args(inner_type)) + return discriminator, variants + return None, None + + +def _get_field_annotation(model: Type[Any], field_name: str) -> Optional[Type[Any]]: + """Get the type annotation of a field from a Pydantic model.""" + if IS_PYDANTIC_V2: + fields = getattr(model, "model_fields", {}) + field_info = fields.get(field_name) + if field_info: + return cast(Optional[Type[Any]], field_info.annotation) + else: + fields = getattr(model, "__fields__", {}) + field_info = fields.get(field_name) + if field_info: + return cast(Optional[Type[Any]], field_info.outer_type_) + return None + + +def _find_variant_by_discriminator( + variants: List[Type[Any]], + discriminator: str, + discriminator_value: Any, +) -> Optional[Type[Any]]: + """Find the union variant that matches the discriminator value.""" + for variant in variants: + if not (inspect.isclass(variant) and issubclass(variant, pydantic.BaseModel)): + continue + + disc_annotation = _get_field_annotation(variant, discriminator) + if disc_annotation and is_literal_type(disc_annotation): + literal_args = get_args(disc_annotation) + if literal_args and literal_args[0] == discriminator_value: + return variant + return None + + +def _is_string_type(type_: Type[Any]) -> bool: + """Check if a type is str or Optional[str].""" + if type_ is str: + return True + + origin = typing_extensions.get_origin(type_) + if origin is Union: + args = typing_extensions.get_args(type_) + # Optional[str] = Union[str, None] + non_none_args = [a for a in args if a is not type(None)] + if len(non_none_args) == 1 and non_none_args[0] is str: + return True + + return False + + +def parse_sse_obj(sse: "ServerSentEvent", type_: Type[T]) -> T: + """ + Parse a ServerSentEvent into the appropriate type. + + Handles two scenarios based on where the discriminator field is located: + + 1. Data-level discrimination: The discriminator (e.g., 'type') is inside the 'data' payload. + The union describes the data content, not the SSE envelope. + -> Returns: json.loads(data) parsed into the type + + Example: ChatStreamResponse with discriminator='type' + Input: ServerSentEvent(event="message", data='{"type": "content-delta", ...}', id="") + Output: ContentDeltaEvent (parsed from data, SSE envelope stripped) + + 2. Event-level discrimination: The discriminator (e.g., 'event') is at the SSE event level. + The union describes the full SSE event structure. + -> Returns: SSE envelope with 'data' field JSON-parsed only if the variant expects non-string + + Example: JobStreamResponse with discriminator='event' + Input: ServerSentEvent(event="ERROR", data='{"code": "FAILED", ...}', id="123") + Output: JobStreamResponse_Error with data as ErrorData object + + But for variants where data is str (like STATUS_UPDATE): + Input: ServerSentEvent(event="STATUS_UPDATE", data='{"status": "processing"}', id="1") + Output: JobStreamResponse_StatusUpdate with data as string (not parsed) + + Args: + sse: The ServerSentEvent object to parse + type_: The target discriminated union type + + Returns: + The parsed object of type T + + Note: + This function is only available in SDK contexts where http_sse module exists. + """ + sse_event = asdict(sse) + discriminator, variants = _get_discriminator_and_variants(type_) + + if discriminator is None or variants is None: + # Not a discriminated union - parse the data field as JSON + data_value = sse_event.get("data") + if isinstance(data_value, str) and data_value: + try: + parsed_data = json.loads(data_value) + return parse_obj_as(type_, parsed_data) + except json.JSONDecodeError as e: + _logger.warning( + "Failed to parse SSE data field as JSON: %s, data: %s", + e, + data_value[:100] if len(data_value) > 100 else data_value, + ) + return parse_obj_as(type_, sse_event) + + data_value = sse_event.get("data") + + # Check if discriminator is at the top level (event-level discrimination) + if discriminator in sse_event: + # Case 2: Event-level discrimination + # Find the matching variant to check if 'data' field needs JSON parsing + disc_value = sse_event.get(discriminator) + matching_variant = _find_variant_by_discriminator(variants, discriminator, disc_value) + + if matching_variant is not None: + # Check what type the variant expects for 'data' + data_type = _get_field_annotation(matching_variant, "data") + if data_type is not None and not _is_string_type(data_type): + # Variant expects non-string data - parse JSON + if isinstance(data_value, str) and data_value: + try: + parsed_data = json.loads(data_value) + new_object = dict(sse_event) + new_object["data"] = parsed_data + return parse_obj_as(type_, new_object) + except json.JSONDecodeError as e: + _logger.warning( + "Failed to parse SSE data field as JSON for event-level discrimination: %s, data: %s", + e, + data_value[:100] if len(data_value) > 100 else data_value, + ) + # Either no matching variant, data is string type, or JSON parse failed + return parse_obj_as(type_, sse_event) + + else: + # Case 1: Data-level discrimination + # The discriminator is inside the data payload - extract and parse data only + if isinstance(data_value, str) and data_value: + try: + parsed_data = json.loads(data_value) + return parse_obj_as(type_, parsed_data) + except json.JSONDecodeError as e: + _logger.warning( + "Failed to parse SSE data field as JSON for data-level discrimination: %s, data: %s", + e, + data_value[:100] if len(data_value) > 100 else data_value, + ) + return parse_obj_as(type_, sse_event) + + +def parse_obj_as(type_: Type[T], object_: Any) -> T: + # convert_and_respect_annotation_metadata is required for TypedDict aliasing. + # + # For Pydantic models, whether we should pre-dealias depends on how the model encodes aliasing: + # - If the model uses real Pydantic aliases (pydantic.Field(alias=...)), then we must pass wire keys through + # unchanged so Pydantic can validate them. + # - If the model encodes aliasing only via FieldMetadata annotations, then we MUST pre-dealias because Pydantic + # will not recognize those aliases during validation. + if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel): + has_pydantic_aliases = False + if IS_PYDANTIC_V2: + for field_name, field_info in getattr(type_, "model_fields", {}).items(): # type: ignore[attr-defined] + alias = getattr(field_info, "alias", None) + if alias is not None and alias != field_name: + has_pydantic_aliases = True + break + else: + for field in getattr(type_, "__fields__", {}).values(): + alias = getattr(field, "alias", None) + name = getattr(field, "name", None) + if alias is not None and name is not None and alias != name: + has_pydantic_aliases = True + break + + dealiased_object = ( + object_ + if has_pydantic_aliases + else convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read") + ) + else: + dealiased_object = convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read") + if IS_PYDANTIC_V2: + adapter = pydantic.TypeAdapter(type_) # type: ignore[attr-defined] + return adapter.validate_python(dealiased_object) + return pydantic.parse_obj_as(type_, dealiased_object) + + +def to_jsonable_with_fallback(obj: Any, fallback_serializer: Callable[[Any], Any]) -> Any: + if IS_PYDANTIC_V2: + from pydantic_core import to_jsonable_python + + return to_jsonable_python(obj, fallback=fallback_serializer) + return fallback_serializer(obj) + + +class UniversalBaseModel(pydantic.BaseModel): + if IS_PYDANTIC_V2: + model_config: ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( # type: ignore[typeddict-unknown-key] + # Allow fields beginning with `model_` to be used in the model + protected_namespaces=(), + ) + + @pydantic.model_validator(mode="before") # type: ignore[attr-defined] + @classmethod + def _coerce_field_names_to_aliases(cls, data: Any) -> Any: + """ + Accept Python field names in input by rewriting them to their Pydantic aliases, + while avoiding silent collisions when a key could refer to multiple fields. + """ + if not isinstance(data, Mapping): + return data + + fields = getattr(cls, "model_fields", {}) # type: ignore[attr-defined] + name_to_alias: Dict[str, str] = {} + alias_to_name: Dict[str, str] = {} + + for name, field_info in fields.items(): + alias = getattr(field_info, "alias", None) or name + name_to_alias[name] = alias + if alias != name: + alias_to_name[alias] = name + + # Detect ambiguous keys: a key that is an alias for one field and a name for another. + ambiguous_keys = set(alias_to_name.keys()).intersection(set(name_to_alias.keys())) + for key in ambiguous_keys: + if key in data and name_to_alias[key] not in data: + raise ValueError( + f"Ambiguous input key '{key}': it is both a field name and an alias. " + "Provide the explicit alias key to disambiguate." + ) + + original_keys = set(data.keys()) + rewritten: Dict[str, Any] = dict(data) + for name, alias in name_to_alias.items(): + if alias != name and name in original_keys and alias not in rewritten: + rewritten[alias] = rewritten.pop(name) + + return rewritten + + @pydantic.model_serializer(mode="plain", when_used="json") # type: ignore[attr-defined] + def serialize_model(self) -> Any: # type: ignore[name-defined] + serialized = self.dict() # type: ignore[attr-defined] + data = {k: serialize_datetime(v) if isinstance(v, dt.datetime) else v for k, v in serialized.items()} + return data + + else: + + class Config: + smart_union = True + json_encoders = {dt.datetime: serialize_datetime} + + @pydantic.root_validator(pre=True) + def _coerce_field_names_to_aliases(cls, values: Any) -> Any: + """ + Pydantic v1 equivalent of _coerce_field_names_to_aliases. + """ + if not isinstance(values, Mapping): + return values + + fields = getattr(cls, "__fields__", {}) + name_to_alias: Dict[str, str] = {} + alias_to_name: Dict[str, str] = {} + + for name, field in fields.items(): + alias = getattr(field, "alias", None) or name + name_to_alias[name] = alias + if alias != name: + alias_to_name[alias] = name + + ambiguous_keys = set(alias_to_name.keys()).intersection(set(name_to_alias.keys())) + for key in ambiguous_keys: + if key in values and name_to_alias[key] not in values: + raise ValueError( + f"Ambiguous input key '{key}': it is both a field name and an alias. " + "Provide the explicit alias key to disambiguate." + ) + + original_keys = set(values.keys()) + rewritten: Dict[str, Any] = dict(values) + for name, alias in name_to_alias.items(): + if alias != name and name in original_keys and alias not in rewritten: + rewritten[alias] = rewritten.pop(name) + + return rewritten + + @classmethod + def model_construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model": + dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read") + return cls.construct(_fields_set, **dealiased_object) + + @classmethod + def construct(cls: Type["Model"], _fields_set: Optional[Set[str]] = None, **values: Any) -> "Model": + dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read") + if IS_PYDANTIC_V2: + return super().model_construct(_fields_set, **dealiased_object) # type: ignore[misc] + return super().construct(_fields_set, **dealiased_object) + + def json(self, **kwargs: Any) -> str: + kwargs_with_defaults = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + if IS_PYDANTIC_V2: + return super().model_dump_json(**kwargs_with_defaults) # type: ignore[misc] + return super().json(**kwargs_with_defaults) + + def dict(self, **kwargs: Any) -> Dict[str, Any]: + """ + Override the default dict method to `exclude_unset` by default. This function patches + `exclude_unset` to work include fields within non-None default values. + """ + # Note: the logic here is multiplexed given the levers exposed in Pydantic V1 vs V2 + # Pydantic V1's .dict can be extremely slow, so we do not want to call it twice. + # + # We'd ideally do the same for Pydantic V2, but it shells out to a library to serialize models + # that we have less control over, and this is less intrusive than custom serializers for now. + if IS_PYDANTIC_V2: + kwargs_with_defaults_exclude_unset = { + **kwargs, + "by_alias": True, + "exclude_unset": True, + "exclude_none": False, + } + kwargs_with_defaults_exclude_none = { + **kwargs, + "by_alias": True, + "exclude_none": True, + "exclude_unset": False, + } + dict_dump = deep_union_pydantic_dicts( + super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore[misc] + super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore[misc] + ) + + else: + _fields_set = self.__fields_set__.copy() + + fields = _get_model_fields(self.__class__) + for name, field in fields.items(): + if name not in _fields_set: + default = _get_field_default(field) + + # If the default values are non-null act like they've been set + # This effectively allows exclude_unset to work like exclude_none where + # the latter passes through intentionally set none values. + if default is not None or ("exclude_unset" in kwargs and not kwargs["exclude_unset"]): + _fields_set.add(name) + + if default is not None: + self.__fields_set__.add(name) + + kwargs_with_defaults_exclude_unset_include_fields = { + "by_alias": True, + "exclude_unset": True, + "include": _fields_set, + **kwargs, + } + + dict_dump = super().dict(**kwargs_with_defaults_exclude_unset_include_fields) + + return cast( + Dict[str, Any], + convert_and_respect_annotation_metadata(object_=dict_dump, annotation=self.__class__, direction="write"), + ) + + +def _union_list_of_pydantic_dicts(source: List[Any], destination: List[Any]) -> List[Any]: + converted_list: List[Any] = [] + for i, item in enumerate(source): + destination_value = destination[i] + if isinstance(item, dict): + converted_list.append(deep_union_pydantic_dicts(item, destination_value)) + elif isinstance(item, list): + converted_list.append(_union_list_of_pydantic_dicts(item, destination_value)) + else: + converted_list.append(item) + return converted_list + + +def deep_union_pydantic_dicts(source: Dict[str, Any], destination: Dict[str, Any]) -> Dict[str, Any]: + for key, value in source.items(): + node = destination.setdefault(key, {}) + if isinstance(value, dict): + deep_union_pydantic_dicts(value, node) + # Note: we do not do this same processing for sets given we do not have sets of models + # and given the sets are unordered, the processing of the set and matching objects would + # be non-trivial. + elif isinstance(value, list): + destination[key] = _union_list_of_pydantic_dicts(value, node) + else: + destination[key] = value + + return destination + + +if IS_PYDANTIC_V2: + + class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore[misc, name-defined, type-arg] + pass + + UniversalRootModel: TypeAlias = V2RootModel # type: ignore[misc] +else: + UniversalRootModel: TypeAlias = UniversalBaseModel # type: ignore[misc, no-redef] + + +def encode_by_type(o: Any) -> Any: + encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple) + for type_, encoder in encoders_by_type.items(): + encoders_by_class_tuples[encoder] += (type_,) + + if type(o) in encoders_by_type: + return encoders_by_type[type(o)](o) + for encoder, classes_tuple in encoders_by_class_tuples.items(): + if isinstance(o, classes_tuple): + return encoder(o) + + +def update_forward_refs(model: Type["Model"], **localns: Any) -> None: + if IS_PYDANTIC_V2: + model.model_rebuild(raise_errors=False) # type: ignore[attr-defined] + else: + model.update_forward_refs(**localns) + + +# Mirrors Pydantic's internal typing +AnyCallable = Callable[..., Any] + + +def universal_root_validator( + pre: bool = False, +) -> Callable[[AnyCallable], AnyCallable]: + def decorator(func: AnyCallable) -> AnyCallable: + if IS_PYDANTIC_V2: + # In Pydantic v2, for RootModel we always use "before" mode + # The custom validators transform the input value before the model is created + return cast(AnyCallable, pydantic.model_validator(mode="before")(func)) # type: ignore[attr-defined] + return cast(AnyCallable, pydantic.root_validator(pre=pre)(func)) # type: ignore[call-overload] + + return decorator + + +def universal_field_validator(field_name: str, pre: bool = False) -> Callable[[AnyCallable], AnyCallable]: + def decorator(func: AnyCallable) -> AnyCallable: + if IS_PYDANTIC_V2: + return cast(AnyCallable, pydantic.field_validator(field_name, mode="before" if pre else "after")(func)) # type: ignore[attr-defined] + return cast(AnyCallable, pydantic.validator(field_name, pre=pre)(func)) + + return decorator + + +PydanticField = Union[ModelField, pydantic.fields.FieldInfo] + + +def _get_model_fields(model: Type["Model"]) -> Mapping[str, PydanticField]: + if IS_PYDANTIC_V2: + return cast(Mapping[str, PydanticField], model.model_fields) # type: ignore[attr-defined] + return cast(Mapping[str, PydanticField], model.__fields__) + + +def _get_field_default(field: PydanticField) -> Any: + try: + value = field.get_default() # type: ignore[union-attr] + except: + value = field.default + if IS_PYDANTIC_V2: + from pydantic_core import PydanticUndefined + + if value == PydanticUndefined: + return None + return value + return value diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/query_encoder.py b/venv/lib/python3.12/site-packages/sarvamai/core/query_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..3183001d40462d0f35f8c2aea4e309bc565ea79a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/query_encoder.py @@ -0,0 +1,58 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Any, Dict, List, Optional, Tuple + +import pydantic + + +# Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict +def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> List[Tuple[str, Any]]: + result = [] + for k, v in dict_flat.items(): + key = f"{key_prefix}[{k}]" if key_prefix is not None else k + if isinstance(v, dict): + result.extend(traverse_query_dict(v, key)) + elif isinstance(v, list): + for arr_v in v: + if isinstance(arr_v, dict): + result.extend(traverse_query_dict(arr_v, key)) + else: + result.append((key, arr_v)) + else: + result.append((key, v)) + return result + + +def single_query_encoder(query_key: str, query_value: Any) -> List[Tuple[str, Any]]: + if isinstance(query_value, pydantic.BaseModel) or isinstance(query_value, dict): + if isinstance(query_value, pydantic.BaseModel): + obj_dict = query_value.dict(by_alias=True) + else: + obj_dict = query_value + return traverse_query_dict(obj_dict, query_key) + elif isinstance(query_value, list): + encoded_values: List[Tuple[str, Any]] = [] + for value in query_value: + if isinstance(value, pydantic.BaseModel) or isinstance(value, dict): + if isinstance(value, pydantic.BaseModel): + obj_dict = value.dict(by_alias=True) + elif isinstance(value, dict): + obj_dict = value + + encoded_values.extend(single_query_encoder(query_key, obj_dict)) + else: + encoded_values.append((query_key, value)) + + return encoded_values + + return [(query_key, query_value)] + + +def encode_query(query: Optional[Dict[str, Any]]) -> Optional[List[Tuple[str, Any]]]: + if query is None: + return None + + encoded_query = [] + for k, v in query.items(): + encoded_query.extend(single_query_encoder(k, v)) + return encoded_query diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/remove_none_from_dict.py b/venv/lib/python3.12/site-packages/sarvamai/core/remove_none_from_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..c2298143f14a09aee4e01e9ad51d8fedd6bce545 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/remove_none_from_dict.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +from typing import Any, Dict, Mapping, Optional + + +def remove_none_from_dict(original: Mapping[str, Optional[Any]]) -> Dict[str, Any]: + new: Dict[str, Any] = {} + for key, value in original.items(): + if value is not None: + new[key] = value + return new diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/request_options.py b/venv/lib/python3.12/site-packages/sarvamai/core/request_options.py new file mode 100644 index 0000000000000000000000000000000000000000..1b38804432ba93a2c474ed1d18eac356e9d197e3 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/request_options.py @@ -0,0 +1,35 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +try: + from typing import NotRequired # type: ignore +except ImportError: + from typing_extensions import NotRequired + + +class RequestOptions(typing.TypedDict, total=False): + """ + Additional options for request-specific configuration when calling APIs via the SDK. + This is used primarily as an optional final parameter for service functions. + + Attributes: + - timeout_in_seconds: int. The number of seconds to await an API call before timing out. + + - max_retries: int. The max number of retries to attempt if the API call fails. + + - additional_headers: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's header dict + + - additional_query_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's query parameters dict + + - additional_body_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's body parameters dict + + - chunk_size: int. The size, in bytes, to process each chunk of data being streamed back within the response. This equates to leveraging `chunk_size` within `requests` or `httpx`, and is only leveraged for file downloads. + """ + + timeout_in_seconds: NotRequired[int] + max_retries: NotRequired[int] + additional_headers: NotRequired[typing.Dict[str, typing.Any]] + additional_query_parameters: NotRequired[typing.Dict[str, typing.Any]] + additional_body_parameters: NotRequired[typing.Dict[str, typing.Any]] + chunk_size: NotRequired[int] diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/serialization.py b/venv/lib/python3.12/site-packages/sarvamai/core/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..c36e865cc729e0d8aa42fc223aadd5410ca42c15 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/serialization.py @@ -0,0 +1,276 @@ +# This file was auto-generated by Fern from our API Definition. + +import collections +import inspect +import typing + +import pydantic +import typing_extensions + + +class FieldMetadata: + """ + Metadata class used to annotate fields to provide additional information. + + Example: + class MyDict(TypedDict): + field: typing.Annotated[str, FieldMetadata(alias="field_name")] + + Will serialize: `{"field": "value"}` + To: `{"field_name": "value"}` + """ + + alias: str + + def __init__(self, *, alias: str) -> None: + self.alias = alias + + +def convert_and_respect_annotation_metadata( + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, + direction: typing.Literal["read", "write"], +) -> typing.Any: + """ + Respect the metadata annotations on a field, such as aliasing. This function effectively + manipulates the dict-form of an object to respect the metadata annotations. This is primarily used for + TypedDicts, which cannot support aliasing out of the box, and can be extended for additional + utilities, such as defaults. + + Parameters + ---------- + object_ : typing.Any + + annotation : type + The type we're looking to apply typing annotations from + + inner_type : typing.Optional[type] + + Returns + ------- + typing.Any + """ + + if object_ is None: + return None + if inner_type is None: + inner_type = annotation + + clean_type = _remove_annotations(inner_type) + # Pydantic models + if ( + inspect.isclass(clean_type) + and issubclass(clean_type, pydantic.BaseModel) + and isinstance(object_, typing.Mapping) + ): + return _convert_mapping(object_, clean_type, direction) + # TypedDicts + if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + return _convert_mapping(object_, clean_type, direction) + + if ( + typing_extensions.get_origin(clean_type) == typing.Dict + or typing_extensions.get_origin(clean_type) == dict + or clean_type == typing.Dict + ) and isinstance(object_, typing.Dict): + key_type = typing_extensions.get_args(clean_type)[0] + value_type = typing_extensions.get_args(clean_type)[1] + + return { + key: convert_and_respect_annotation_metadata( + object_=value, + annotation=annotation, + inner_type=value_type, + direction=direction, + ) + for key, value in object_.items() + } + + # If you're iterating on a string, do not bother to coerce it to a sequence. + if not isinstance(object_, str): + if ( + typing_extensions.get_origin(clean_type) == typing.Set + or typing_extensions.get_origin(clean_type) == set + or clean_type == typing.Set + ) and isinstance(object_, typing.Set): + inner_type = typing_extensions.get_args(clean_type)[0] + return { + convert_and_respect_annotation_metadata( + object_=item, + annotation=annotation, + inner_type=inner_type, + direction=direction, + ) + for item in object_ + } + elif ( + ( + typing_extensions.get_origin(clean_type) == typing.List + or typing_extensions.get_origin(clean_type) == list + or clean_type == typing.List + ) + and isinstance(object_, typing.List) + ) or ( + ( + typing_extensions.get_origin(clean_type) == typing.Sequence + or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or clean_type == typing.Sequence + ) + and isinstance(object_, typing.Sequence) + ): + inner_type = typing_extensions.get_args(clean_type)[0] + return [ + convert_and_respect_annotation_metadata( + object_=item, + annotation=annotation, + inner_type=inner_type, + direction=direction, + ) + for item in object_ + ] + + if typing_extensions.get_origin(clean_type) == typing.Union: + # We should be able to ~relatively~ safely try to convert keys against all + # member types in the union, the edge case here is if one member aliases a field + # of the same name to a different name from another member + # Or if another member aliases a field of the same name that another member does not. + for member in typing_extensions.get_args(clean_type): + object_ = convert_and_respect_annotation_metadata( + object_=object_, + annotation=annotation, + inner_type=member, + direction=direction, + ) + return object_ + + annotated_type = _get_annotation(annotation) + if annotated_type is None: + return object_ + + # If the object is not a TypedDict, a Union, or other container (list, set, sequence, etc.) + # Then we can safely call it on the recursive conversion. + return object_ + + +def _convert_mapping( + object_: typing.Mapping[str, object], + expected_type: typing.Any, + direction: typing.Literal["read", "write"], +) -> typing.Mapping[str, object]: + converted_object: typing.Dict[str, object] = {} + try: + annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) + except NameError: + # The TypedDict contains a circular reference, so + # we use the __annotations__ attribute directly. + annotations = getattr(expected_type, "__annotations__", {}) + aliases_to_field_names = _get_alias_to_field_name(annotations) + for key, value in object_.items(): + if direction == "read" and key in aliases_to_field_names: + dealiased_key = aliases_to_field_names.get(key) + if dealiased_key is not None: + type_ = annotations.get(dealiased_key) + else: + type_ = annotations.get(key) + # Note you can't get the annotation by the field name if you're in read mode, so you must check the aliases map + # + # So this is effectively saying if we're in write mode, and we don't have a type, or if we're in read mode and we don't have an alias + # then we can just pass the value through as is + if type_ is None: + converted_object[key] = value + elif direction == "read" and key not in aliases_to_field_names: + converted_object[key] = convert_and_respect_annotation_metadata( + object_=value, annotation=type_, direction=direction + ) + else: + converted_object[_alias_key(key, type_, direction, aliases_to_field_names)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_, direction=direction) + ) + return converted_object + + +def _get_annotation(type_: typing.Any) -> typing.Optional[typing.Any]: + maybe_annotated_type = typing_extensions.get_origin(type_) + if maybe_annotated_type is None: + return None + + if maybe_annotated_type == typing_extensions.NotRequired: + type_ = typing_extensions.get_args(type_)[0] + maybe_annotated_type = typing_extensions.get_origin(type_) + + if maybe_annotated_type == typing_extensions.Annotated: + return type_ + + return None + + +def _remove_annotations(type_: typing.Any) -> typing.Any: + maybe_annotated_type = typing_extensions.get_origin(type_) + if maybe_annotated_type is None: + return type_ + + if maybe_annotated_type == typing_extensions.NotRequired: + return _remove_annotations(typing_extensions.get_args(type_)[0]) + + if maybe_annotated_type == typing_extensions.Annotated: + return _remove_annotations(typing_extensions.get_args(type_)[0]) + + return type_ + + +def get_alias_to_field_mapping(type_: typing.Any) -> typing.Dict[str, str]: + annotations = typing_extensions.get_type_hints(type_, include_extras=True) + return _get_alias_to_field_name(annotations) + + +def get_field_to_alias_mapping(type_: typing.Any) -> typing.Dict[str, str]: + annotations = typing_extensions.get_type_hints(type_, include_extras=True) + return _get_field_to_alias_name(annotations) + + +def _get_alias_to_field_name( + field_to_hint: typing.Dict[str, typing.Any], +) -> typing.Dict[str, str]: + aliases = {} + for field, hint in field_to_hint.items(): + maybe_alias = _get_alias_from_type(hint) + if maybe_alias is not None: + aliases[maybe_alias] = field + return aliases + + +def _get_field_to_alias_name( + field_to_hint: typing.Dict[str, typing.Any], +) -> typing.Dict[str, str]: + aliases = {} + for field, hint in field_to_hint.items(): + maybe_alias = _get_alias_from_type(hint) + if maybe_alias is not None: + aliases[field] = maybe_alias + return aliases + + +def _get_alias_from_type(type_: typing.Any) -> typing.Optional[str]: + maybe_annotated_type = _get_annotation(type_) + + if maybe_annotated_type is not None: + # The actual annotations are 1 onward, the first is the annotated type + annotations = typing_extensions.get_args(maybe_annotated_type)[1:] + + for annotation in annotations: + if isinstance(annotation, FieldMetadata) and annotation.alias is not None: + return annotation.alias + return None + + +def _alias_key( + key: str, + type_: typing.Any, + direction: typing.Literal["read", "write"], + aliases_to_field_names: typing.Dict[str, str], +) -> str: + if direction == "read": + return aliases_to_field_names.get(key, key) + return _get_alias_from_type(type_=type_) or key diff --git a/venv/lib/python3.12/site-packages/sarvamai/core/websocket_compat.py b/venv/lib/python3.12/site-packages/sarvamai/core/websocket_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..caa6cd0efb7591117711ddf2355b2c98495b77d2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/core/websocket_compat.py @@ -0,0 +1,13 @@ +# This file was auto-generated by Fern from our API Definition. + +try: + from websockets.exceptions import InvalidStatusCode as InvalidWebSocketStatus # type: ignore[attr-defined] + + def get_status_code(exc: InvalidWebSocketStatus) -> int: + return exc.status_code # type: ignore[attr-defined, union-attr] + +except ImportError: + from websockets.exceptions import InvalidStatus as InvalidWebSocketStatus # type: ignore[assignment, no-redef] + + def get_status_code(exc: InvalidWebSocketStatus) -> int: # type: ignore[no-redef] + return exc.response.status_code # type: ignore[attr-defined, union-attr] diff --git a/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cb38d6094d83052110791d1acac2a9c7cbc4e5d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e8cb2d1d81ace0e90a3a4cf67743d21767763ef Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..483fec6dbee02b960e1da5285d360a31023339c8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/client.py b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/client.py new file mode 100644 index 0000000000000000000000000000000000000000..f012888d6fa924c4cf21d8ff8bcb90d4bd4b8eef --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/client.py @@ -0,0 +1,1240 @@ +# This file was auto-generated by Fern from our API Definition. + +import os +import time +import typing +import httpx + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..requests.doc_digitization_job_parameters import ( + DocDigitizationJobParametersParams, +) +from ..requests.doc_digitization_webhook_callback import ( + DocDigitizationWebhookCallbackParams, +) +from ..types.doc_digitization_create_job_response import ( + DocDigitizationCreateJobResponse, +) +from ..types.doc_digitization_download_files_response import ( + DocDigitizationDownloadFilesResponse, +) +from ..types.doc_digitization_job_status_response import ( + DocDigitizationJobStatusResponse, +) +from ..types.doc_digitization_upload_files_response import ( + DocDigitizationUploadFilesResponse, +) +from .raw_client import ( + AsyncRawDocumentIntelligenceClient, + RawDocumentIntelligenceClient, +) + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class DocumentIntelligenceJob: + """ + A convenience wrapper for managing document intelligence jobs. + + This class provides high-level methods for the complete document processing workflow: + create job → upload file → start → wait → download output. + """ + + def __init__( + self, + *, + client: "DocumentIntelligenceClient", + job_id: str, + language: typing.Optional[str] = None, + output_format: typing.Optional[str] = None, + ): + self._client = client + self._job_id = job_id + self._language = language + self._output_format = output_format + self._status: typing.Optional[DocDigitizationJobStatusResponse] = None + + @property + def job_id(self) -> str: + """The unique identifier for this job.""" + return self._job_id + + @property + def language(self) -> typing.Optional[str]: + """The language configured for this job.""" + return self._language + + @property + def output_format(self) -> typing.Optional[str]: + """The output format configured for this job.""" + return self._output_format + + def upload_file(self, file_path: str) -> None: + """ + Upload a file for processing. + + Parameters + ---------- + file_path : str + Path to the file to upload (PDF, PNG, JPG, or ZIP) + """ + filename = os.path.basename(file_path) + + # Get presigned upload URL + upload_response = self._client.get_upload_links( + job_id=self._job_id, files=[filename] + ) + + if not upload_response.upload_urls: + raise ValueError("No upload URL returned") + + # Get the upload URL for the filename + file_details = upload_response.upload_urls.get(filename) + if not file_details: + raise ValueError(f"No upload URL for file: {filename}") + + upload_url = file_details.file_url + + # Determine content type + ext = os.path.splitext(filename)[1].lower() + content_types = { + ".pdf": "application/pdf", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".zip": "application/zip", + } + content_type = content_types.get(ext, "application/octet-stream") + + # Upload file + with open(file_path, "rb") as f: + file_data = f.read() + + response = httpx.put( + upload_url, + content=file_data, + headers={ + "Content-Type": content_type, + "x-ms-blob-type": "BlockBlob", # Required for Azure Blob Storage + }, + timeout=300.0, + ) + response.raise_for_status() + + def start(self) -> DocDigitizationJobStatusResponse: + """ + Start processing the uploaded file. + + Returns + ------- + DocDigitizationJobStatusResponse + The job status after starting + """ + self._status = self._client.start(self._job_id) + return self._status + + def get_status(self) -> DocDigitizationJobStatusResponse: + """ + Get the current status of the job. + + Returns + ------- + DocDigitizationJobStatusResponse + The current job status + """ + self._status = self._client.get_status(self._job_id) + return self._status + + def wait_until_complete( + self, + poll_interval: float = 2.0, + timeout: typing.Optional[float] = None, + ) -> DocDigitizationJobStatusResponse: + """ + Poll the job status until it completes or fails. + + Parameters + ---------- + poll_interval : float + Seconds between status checks (default: 2.0) + timeout : float, optional + Maximum seconds to wait (default: None = wait forever) + + Returns + ------- + DocDigitizationJobStatusResponse + The final job status + + Raises + ------ + TimeoutError + If timeout is reached before job completes + """ + start_time = time.time() + terminal_states = {"Completed", "PartiallyCompleted", "Failed"} + + while True: + status = self.get_status() + + if status.job_state in terminal_states: + return status + + if timeout is not None and (time.time() - start_time) >= timeout: + raise TimeoutError( + f"Job {self._job_id} did not complete within {timeout} seconds" + ) + + time.sleep(poll_interval) + + def get_page_metrics(self) -> typing.Optional[typing.Dict[str, typing.Any]]: + """ + Get page-level metrics from the last status check. + + Returns + ------- + dict or None + Dictionary with total_pages, pages_processed, pages_succeeded, pages_failed + """ + if self._status is None: + self.get_status() + + if ( + self._status + and self._status.job_details + and len(self._status.job_details) > 0 + ): + detail = self._status.job_details[0] + return { + "total_pages": detail.total_pages, + "pages_processed": detail.pages_processed, + "pages_succeeded": detail.pages_succeeded, + "pages_failed": detail.pages_failed, + } + return None + + def download_output(self, output_path: str) -> str: + """ + Download the processed output to a file. + + Parameters + ---------- + output_path : str + Path where the output file will be saved + + Returns + ------- + str + The path to the downloaded file + """ + download_response = self._client.get_download_links(self._job_id) + + if not download_response.download_urls: + raise ValueError("No download URL available") + + # Get the first available download URL + first_filename = next(iter(download_response.download_urls.keys())) + file_details = download_response.download_urls[first_filename] + download_url = file_details.file_url + + # Download file + response = httpx.get(download_url, timeout=300.0) + response.raise_for_status() + + # Ensure output directory exists + output_dir = os.path.dirname(output_path) + if output_dir: + os.makedirs(output_dir, exist_ok=True) + + with open(output_path, "wb") as f: + f.write(response.content) + + return output_path + + +class DocumentIntelligenceClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawDocumentIntelligenceClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawDocumentIntelligenceClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawDocumentIntelligenceClient + """ + return self._raw_client + + def create_job( + self, + *, + language: str = "hi-IN", + output_format: str = "html", + callback_url: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> DocumentIntelligenceJob: + """ + Create a new document intelligence job with convenience methods. + + This is a high-level method that returns a DocumentIntelligenceJob object + with methods for uploading, starting, waiting, and downloading. + + Parameters + ---------- + language : str + Language code in BCP-47 format (default: "hi-IN") + Supported: hi-IN, en-IN, bn-IN, gu-IN, kn-IN, ml-IN, mr-IN, or-IN, + pa-IN, ta-IN, te-IN, ur-IN, as-IN, bodo-IN, doi-IN, ks-IN, + kok-IN, mai-IN, mni-IN, ne-IN, sa-IN, sat-IN, sd-IN + + output_format : str + Output format: "html" or "md" (default: "html") + + callback_url : str, optional + Webhook URL for completion notification + + request_options : RequestOptions, optional + Request-specific configuration + + Returns + ------- + DocumentIntelligenceJob + A job object with convenience methods for the workflow + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI(api_subscription_key="YOUR_API_KEY") + + # Create job + job = client.document_intelligence.create_job( + language="hi-IN", + output_format="html" + ) + + # Upload, start, wait, download + job.upload_file("document.pdf") + job.start() + job.wait_until_complete() + job.download_output("./output.html") + """ + # Build job parameters + job_params: DocDigitizationJobParametersParams = { + "language": language, + "output_format": output_format, + } + + # Build callback if provided + callback: typing.Optional[DocDigitizationWebhookCallbackParams] = None + if callback_url is not None: + callback = {"url": callback_url} + + # Create the job via the API + response = self.initialise( + job_parameters=job_params, + callback=callback, + request_options=request_options, + ) + + # Return a job object with convenience methods + return DocumentIntelligenceJob( + client=self, + job_id=response.job_id, + language=language, + output_format=output_format, + ) + + def initialise( + self, + *, + job_parameters: typing.Optional[DocDigitizationJobParametersParams] = OMIT, + callback: typing.Optional[DocDigitizationWebhookCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> DocDigitizationCreateJobResponse: + """ + Creates a new document intelligence job. + + **Supported Languages (BCP-47 format):** + - `hi-IN`: Hindi (default) + - `en-IN`: English + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `or-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `ur-IN`: Urdu + - `as-IN`: Assamese + - `bodo-IN`: Bodo + - `doi-IN`: Dogri + - `ks-IN`: Kashmiri + - `kok-IN`: Konkani + - `mai-IN`: Maithili + - `mni-IN`: Manipuri + - `ne-IN`: Nepali + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `sd-IN`: Sindhi + + **Output Formats:** + - `html`: Structured HTML with layout preservation (default) + - `md`: Markdown format + + **Prompt Types:** + Customize how specific content types are processed: + - `default_ocr`: Standard text extraction (default for all text blocks) + - `table_to_html`: Convert tables to HTML format + - `table_to_markdown`: Convert tables to Markdown format + - `chart_to_markdown`: Extract chart data as Markdown table + - `chart_to_json`: Extract chart data as JSON + - `describe_image`: Generate image caption + - `caption_en`: Same as describe_image (English) + - `caption_in`: Caption in document language + + **Webhook Callback:** + Optionally provide a callback URL to receive notification when processing completes. + + Parameters + ---------- + job_parameters : typing.Optional[DocDigitizationJobParametersParams] + Job configuration parameters. Omit the request body to use defaults. + + callback : typing.Optional[DocDigitizationWebhookCallbackParams] + Optional webhook for completion notification + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationCreateJobResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.document_intelligence.initialise() + """ + _response = self._raw_client.initialise( + job_parameters=job_parameters, + callback=callback, + request_options=request_options, + ) + return _response.data + + def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, + ) -> DocDigitizationUploadFilesResponse: + """ + Returns presigned URLs for uploading input files. + + **File Constraints:** + - Exactly one file required (PDF or ZIP) + - PDF files: `.pdf` extension + - ZIP files: `.zip` extension + + Parameters + ---------- + job_id : str + Job identifier returned from Create Job + + files : typing.Sequence[str] + List of filenames to upload (exactly 1 file: PDF or ZIP) + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationUploadFilesResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.document_intelligence.get_upload_links( + job_id="job_id", + files=["files"], + ) + """ + _response = self._raw_client.get_upload_links( + job_id=job_id, files=files, request_options=request_options + ) + return _response.data + + def start( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> DocDigitizationJobStatusResponse: + """ + Validates the uploaded file and starts processing. + + **Validation Checks:** + - File must be uploaded before starting + - File size must not exceed 200 MB + - PDF must be parseable by the PDF parser + - ZIP must contain only JPEG/PNG images + - ZIP must be flat (no nested folders beyond one level) + - ZIP must contain at least one valid image + - Page/image count must not exceed 500 + - User must have sufficient credits + + **Processing:** + Job runs asynchronously. Poll the status endpoint or use webhook callback for completion notification. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationJobStatusResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.document_intelligence.start( + job_id="job_id", + ) + """ + _response = self._raw_client.start(job_id, request_options=request_options) + return _response.data + + def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> DocDigitizationJobStatusResponse: + """ + Returns the current status of a job with page-level metrics. + + **Job States:** + - `Accepted`: Job created, awaiting file upload + - `Pending`: File uploaded, waiting to start + - `Running`: Processing in progress + - `Completed`: All pages processed successfully + - `PartiallyCompleted`: Some pages succeeded, some failed + - `Failed`: All pages failed or job-level error + + **Page Metrics:** + Response includes detailed progress: total pages, pages processed, succeeded, failed, and per-page errors. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationJobStatusResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.document_intelligence.get_status( + job_id="job_id", + ) + """ + _response = self._raw_client.get_status(job_id, request_options=request_options) + return _response.data + + def get_download_links( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> DocDigitizationDownloadFilesResponse: + """ + Returns presigned URLs for downloading output files. + + **Prerequisites:** + - Job must be in `Completed` or `PartiallyCompleted` state + - Failed jobs have no output available + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationDownloadFilesResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.document_intelligence.get_download_links( + job_id="job_id", + ) + """ + _response = self._raw_client.get_download_links( + job_id, request_options=request_options + ) + return _response.data + + +class AsyncDocumentIntelligenceJob: + """ + An async convenience wrapper for managing document intelligence jobs. + + This class provides high-level async methods for the complete document processing workflow: + create job → upload file → start → wait → download output. + """ + + def __init__( + self, + *, + client: "AsyncDocumentIntelligenceClient", + job_id: str, + language: typing.Optional[str] = None, + output_format: typing.Optional[str] = None, + ): + self._client = client + self._job_id = job_id + self._language = language + self._output_format = output_format + self._status: typing.Optional[DocDigitizationJobStatusResponse] = None + + @property + def job_id(self) -> str: + """The unique identifier for this job.""" + return self._job_id + + @property + def language(self) -> typing.Optional[str]: + """The language configured for this job.""" + return self._language + + @property + def output_format(self) -> typing.Optional[str]: + """The output format configured for this job.""" + return self._output_format + + async def upload_file(self, file_path: str) -> None: + """ + Upload a file for processing. + + Parameters + ---------- + file_path : str + Path to the file to upload (PDF, PNG, JPG, or ZIP) + """ + filename = os.path.basename(file_path) + + # Get presigned upload URL + upload_response = await self._client.get_upload_links( + job_id=self._job_id, files=[filename] + ) + + if not upload_response.upload_urls: + raise ValueError("No upload URL returned") + + # Get the upload URL for the filename + file_details = upload_response.upload_urls.get(filename) + if not file_details: + raise ValueError(f"No upload URL for file: {filename}") + + upload_url = file_details.file_url + + # Determine content type + ext = os.path.splitext(filename)[1].lower() + content_types = { + ".pdf": "application/pdf", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".zip": "application/zip", + } + content_type = content_types.get(ext, "application/octet-stream") + + # Upload file (sync read is fine before async HTTP call) + with open(file_path, "rb") as f: + file_data = f.read() + + async with httpx.AsyncClient() as http_client: + response = await http_client.put( + upload_url, + content=file_data, + headers={ + "Content-Type": content_type, + "x-ms-blob-type": "BlockBlob", # Required for Azure Blob Storage + }, + timeout=300.0, + ) + response.raise_for_status() + + async def start(self) -> DocDigitizationJobStatusResponse: + """ + Start processing the uploaded file. + + Returns + ------- + DocDigitizationJobStatusResponse + The job status after starting + """ + self._status = await self._client.start(self._job_id) + return self._status + + async def get_status(self) -> DocDigitizationJobStatusResponse: + """ + Get the current status of the job. + + Returns + ------- + DocDigitizationJobStatusResponse + The current job status + """ + self._status = await self._client.get_status(self._job_id) + return self._status + + async def wait_until_complete( + self, + poll_interval: float = 2.0, + timeout: typing.Optional[float] = None, + ) -> DocDigitizationJobStatusResponse: + """ + Poll the job status until it completes or fails. + + Parameters + ---------- + poll_interval : float + Seconds between status checks (default: 2.0) + timeout : float, optional + Maximum seconds to wait (default: None = wait forever) + + Returns + ------- + DocDigitizationJobStatusResponse + The final job status + + Raises + ------ + TimeoutError + If timeout is reached before job completes + """ + import asyncio + + start_time = time.time() + terminal_states = {"Completed", "PartiallyCompleted", "Failed"} + + while True: + status = await self.get_status() + + if status.job_state in terminal_states: + return status + + if timeout is not None and (time.time() - start_time) >= timeout: + raise TimeoutError( + f"Job {self._job_id} did not complete within {timeout} seconds" + ) + + await asyncio.sleep(poll_interval) + + def get_page_metrics(self) -> typing.Optional[typing.Dict[str, typing.Any]]: + """ + Get page-level metrics from the last status check. + + Returns + ------- + dict or None + Dictionary with total_pages, pages_processed, pages_succeeded, pages_failed + """ + if ( + self._status + and self._status.job_details + and len(self._status.job_details) > 0 + ): + detail = self._status.job_details[0] + return { + "total_pages": detail.total_pages, + "pages_processed": detail.pages_processed, + "pages_succeeded": detail.pages_succeeded, + "pages_failed": detail.pages_failed, + } + return None + + async def download_output(self, output_path: str) -> str: + """ + Download the processed output to a file. + + Parameters + ---------- + output_path : str + Path where the output file will be saved + + Returns + ------- + str + The path to the downloaded file + """ + download_response = await self._client.get_download_links(self._job_id) + + if not download_response.download_urls: + raise ValueError("No download URL available") + + # Get the first available download URL + first_filename = next(iter(download_response.download_urls.keys())) + file_details = download_response.download_urls[first_filename] + download_url = file_details.file_url + + # Download file + async with httpx.AsyncClient() as http_client: + response = await http_client.get(download_url, timeout=300.0) + response.raise_for_status() + + # Ensure output directory exists + output_dir = os.path.dirname(output_path) + if output_dir: + os.makedirs(output_dir, exist_ok=True) + + # Sync write is fine after async HTTP call + with open(output_path, "wb") as f: + f.write(response.content) + + return output_path + + +class AsyncDocumentIntelligenceClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawDocumentIntelligenceClient( + client_wrapper=client_wrapper + ) + + @property + def with_raw_response(self) -> AsyncRawDocumentIntelligenceClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawDocumentIntelligenceClient + """ + return self._raw_client + + async def create_job( + self, + *, + language: str = "hi-IN", + output_format: str = "html", + callback_url: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncDocumentIntelligenceJob: + """ + Create a new document intelligence job with convenience methods. + + This is a high-level method that returns an AsyncDocumentIntelligenceJob object + with async methods for uploading, starting, waiting, and downloading. + + Parameters + ---------- + language : str + Language code in BCP-47 format (default: "hi-IN") + Supported: hi-IN, en-IN, bn-IN, gu-IN, kn-IN, ml-IN, mr-IN, or-IN, + pa-IN, ta-IN, te-IN, ur-IN, as-IN, bodo-IN, doi-IN, ks-IN, + kok-IN, mai-IN, mni-IN, ne-IN, sa-IN, sat-IN, sd-IN + + output_format : str + Output format: "html" or "md" (default: "html") + + callback_url : str, optional + Webhook URL for completion notification + + request_options : RequestOptions, optional + Request-specific configuration + + Returns + ------- + AsyncDocumentIntelligenceJob + A job object with async convenience methods for the workflow + + Examples + -------- + import asyncio + from sarvamai import AsyncSarvamAI + + async def main(): + client = AsyncSarvamAI(api_subscription_key="YOUR_API_KEY") + + # Create job + job = await client.document_intelligence.create_job( + language="hi-IN", + output_format="html" + ) + + # Upload, start, wait, download + await job.upload_file("document.pdf") + await job.start() + await job.wait_until_complete() + await job.download_output("./output.html") + + asyncio.run(main()) + """ + # Build job parameters + job_params: DocDigitizationJobParametersParams = { + "language": language, + "output_format": output_format, + } + + # Build callback if provided + callback: typing.Optional[DocDigitizationWebhookCallbackParams] = None + if callback_url is not None: + callback = {"url": callback_url} + + # Create the job via the API + response = await self.initialise( + job_parameters=job_params, + callback=callback, + request_options=request_options, + ) + + # Return a job object with convenience methods + return AsyncDocumentIntelligenceJob( + client=self, + job_id=response.job_id, + language=language, + output_format=output_format, + ) + + async def initialise( + self, + *, + job_parameters: typing.Optional[DocDigitizationJobParametersParams] = OMIT, + callback: typing.Optional[DocDigitizationWebhookCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> DocDigitizationCreateJobResponse: + """ + Creates a new document intelligence job. + + **Supported Languages (BCP-47 format):** + - `hi-IN`: Hindi (default) + - `en-IN`: English + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `or-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `ur-IN`: Urdu + - `as-IN`: Assamese + - `bodo-IN`: Bodo + - `doi-IN`: Dogri + - `ks-IN`: Kashmiri + - `kok-IN`: Konkani + - `mai-IN`: Maithili + - `mni-IN`: Manipuri + - `ne-IN`: Nepali + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `sd-IN`: Sindhi + + **Output Formats:** + - `html`: Structured HTML with layout preservation (default) + - `md`: Markdown format + + **Prompt Types:** + Customize how specific content types are processed: + - `default_ocr`: Standard text extraction (default for all text blocks) + - `table_to_html`: Convert tables to HTML format + - `table_to_markdown`: Convert tables to Markdown format + - `chart_to_markdown`: Extract chart data as Markdown table + - `chart_to_json`: Extract chart data as JSON + - `describe_image`: Generate image caption + - `caption_en`: Same as describe_image (English) + - `caption_in`: Caption in document language + + **Webhook Callback:** + Optionally provide a callback URL to receive notification when processing completes. + + Parameters + ---------- + job_parameters : typing.Optional[DocDigitizationJobParametersParams] + Job configuration parameters. Omit the request body to use defaults. + + callback : typing.Optional[DocDigitizationWebhookCallbackParams] + Optional webhook for completion notification + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationCreateJobResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.document_intelligence.initialise() + + + asyncio.run(main()) + """ + _response = await self._raw_client.initialise( + job_parameters=job_parameters, + callback=callback, + request_options=request_options, + ) + return _response.data + + async def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, + ) -> DocDigitizationUploadFilesResponse: + """ + Returns presigned URLs for uploading input files. + + **File Constraints:** + - Exactly one file required (PDF or ZIP) + - PDF files: `.pdf` extension + - ZIP files: `.zip` extension + + Parameters + ---------- + job_id : str + Job identifier returned from Create Job + + files : typing.Sequence[str] + List of filenames to upload (exactly 1 file: PDF or ZIP) + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationUploadFilesResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.document_intelligence.get_upload_links( + job_id="job_id", + files=["files"], + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_upload_links( + job_id=job_id, files=files, request_options=request_options + ) + return _response.data + + async def start( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> DocDigitizationJobStatusResponse: + """ + Validates the uploaded file and starts processing. + + **Validation Checks:** + - File must be uploaded before starting + - File size must not exceed 200 MB + - PDF must be parseable by the PDF parser + - ZIP must contain only JPEG/PNG images + - ZIP must be flat (no nested folders beyond one level) + - ZIP must contain at least one valid image + - Page/image count must not exceed 500 + - User must have sufficient credits + + **Processing:** + Job runs asynchronously. Poll the status endpoint or use webhook callback for completion notification. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationJobStatusResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.document_intelligence.start( + job_id="job_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.start( + job_id, request_options=request_options + ) + return _response.data + + async def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> DocDigitizationJobStatusResponse: + """ + Returns the current status of a job with page-level metrics. + + **Job States:** + - `Accepted`: Job created, awaiting file upload + - `Pending`: File uploaded, waiting to start + - `Running`: Processing in progress + - `Completed`: All pages processed successfully + - `PartiallyCompleted`: Some pages succeeded, some failed + - `Failed`: All pages failed or job-level error + + **Page Metrics:** + Response includes detailed progress: total pages, pages processed, succeeded, failed, and per-page errors. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationJobStatusResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.document_intelligence.get_status( + job_id="job_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_status( + job_id, request_options=request_options + ) + return _response.data + + async def get_download_links( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> DocDigitizationDownloadFilesResponse: + """ + Returns presigned URLs for downloading output files. + + **Prerequisites:** + - Job must be in `Completed` or `PartiallyCompleted` state + - Failed jobs have no output available + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + DocDigitizationDownloadFilesResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.document_intelligence.get_download_links( + job_id="job_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_download_links( + job_id, request_options=request_options + ) + return _response.data diff --git a/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..3c5ec43d1da018fb4ae7ad089018c53a4929cda1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/document_intelligence/raw_client.py @@ -0,0 +1,1172 @@ +# 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.http_response import AsyncHttpResponse, HttpResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..core.serialization import convert_and_respect_annotation_metadata +from ..errors.bad_request_error import BadRequestError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.service_unavailable_error import ServiceUnavailableError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..requests.doc_digitization_job_parameters import DocDigitizationJobParametersParams +from ..requests.doc_digitization_webhook_callback import DocDigitizationWebhookCallbackParams +from ..types.doc_digitization_create_job_response import DocDigitizationCreateJobResponse +from ..types.doc_digitization_download_files_response import DocDigitizationDownloadFilesResponse +from ..types.doc_digitization_job_status_response import DocDigitizationJobStatusResponse +from ..types.doc_digitization_upload_files_response import DocDigitizationUploadFilesResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawDocumentIntelligenceClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def initialise( + self, + *, + job_parameters: typing.Optional[DocDigitizationJobParametersParams] = OMIT, + callback: typing.Optional[DocDigitizationWebhookCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[DocDigitizationCreateJobResponse]: + """ + Creates a new Document Intelligence job. + + **Supported Languages (BCP-47 format):** + - `hi-IN`: Hindi (default) + - `en-IN`: English + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `or-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `ur-IN`: Urdu + - `as-IN`: Assamese + - `bodo-IN`: Bodo + - `doi-IN`: Dogri + - `ks-IN`: Kashmiri + - `kok-IN`: Konkani + - `mai-IN`: Maithili + - `mni-IN`: Manipuri + - `ne-IN`: Nepali + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `sd-IN`: Sindhi + + **Output Formats (delivered as ZIP file):** + - `html`: Structured HTML files with layout preservation + - `md`: Markdown files (default) + - `json`: Structured JSON files for programmatic processing + + Parameters + ---------- + job_parameters : typing.Optional[DocDigitizationJobParametersParams] + Configuration parameters for the Document Intelligence job including language and output format. Defaults to Hindi (hi-IN) and Markdown output if omitted. + + callback : typing.Optional[DocDigitizationWebhookCallbackParams] + Optional webhook for completion notification + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[DocDigitizationCreateJobResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "doc-digitization/job/v1", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_parameters": convert_and_respect_annotation_metadata( + object_=job_parameters, annotation=DocDigitizationJobParametersParams, direction="write" + ), + "callback": convert_and_respect_annotation_metadata( + object_=callback, annotation=DocDigitizationWebhookCallbackParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationCreateJobResponse, + parse_obj_as( + type_=DocDigitizationCreateJobResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_upload_links( + self, *, job_id: str, files: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[DocDigitizationUploadFilesResponse]: + """ + Returns presigned URLs for uploading input files. + + **File Constraints:** + - Exactly one file required (PDF or ZIP) + - PDF files: `.pdf` extension + - ZIP files: `.zip` extension + + Parameters + ---------- + job_id : str + Job identifier returned from Create Job + + files : typing.Sequence[str] + List of filenames to upload (exactly 1 file: PDF or ZIP) + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[DocDigitizationUploadFilesResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "doc-digitization/job/v1/upload-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationUploadFilesResponse, + parse_obj_as( + type_=DocDigitizationUploadFilesResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def start( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[DocDigitizationJobStatusResponse]: + """ + Validates the uploaded file and starts processing. + + **Validation Checks:** + - File must be uploaded before starting + - File size must not exceed 200 MB + - PDF must be parseable by the PDF parser + - ZIP must contain only JPEG/PNG images + - ZIP must be flat (no nested folders beyond one level) + - ZIP must contain at least one valid image + - Page/image count must not exceed 10 (returns `422` with `max_page_limit_exceeded` if exceeded) + - User must have sufficient credits + + **Processing:** + Job runs asynchronously. Poll the status endpoint or use webhook callback for completion notification. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[DocDigitizationJobStatusResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"doc-digitization/job/v1/{jsonable_encoder(job_id)}/start", + base_url=self._client_wrapper.get_environment().base, + method="POST", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationJobStatusResponse, + parse_obj_as( + type_=DocDigitizationJobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[DocDigitizationJobStatusResponse]: + """ + Returns the current status of a job with page-level metrics. + + **Job States:** + - `Accepted`: Job created, awaiting file upload + - `Pending`: File uploaded, waiting to start + - `Running`: Processing in progress + - `Completed`: All pages processed successfully + - `PartiallyCompleted`: Some pages succeeded, some failed + - `Failed`: All pages failed or job-level error + + **Page Metrics:** + Response includes detailed progress: total pages, pages processed, succeeded, failed, and per-page errors. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[DocDigitizationJobStatusResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"doc-digitization/job/v1/{jsonable_encoder(job_id)}/status", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationJobStatusResponse, + parse_obj_as( + type_=DocDigitizationJobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_download_links( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[DocDigitizationDownloadFilesResponse]: + """ + Returns presigned URLs for downloading output files. + + **Prerequisites:** + - Job must be in `Completed` or `PartiallyCompleted` state + - Failed jobs have no output available + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[DocDigitizationDownloadFilesResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"doc-digitization/job/v1/{jsonable_encoder(job_id)}/download-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationDownloadFilesResponse, + parse_obj_as( + type_=DocDigitizationDownloadFilesResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + +class AsyncRawDocumentIntelligenceClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def initialise( + self, + *, + job_parameters: typing.Optional[DocDigitizationJobParametersParams] = OMIT, + callback: typing.Optional[DocDigitizationWebhookCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[DocDigitizationCreateJobResponse]: + """ + Creates a new Document Intelligence job. + + **Supported Languages (BCP-47 format):** + - `hi-IN`: Hindi (default) + - `en-IN`: English + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `or-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `ur-IN`: Urdu + - `as-IN`: Assamese + - `bodo-IN`: Bodo + - `doi-IN`: Dogri + - `ks-IN`: Kashmiri + - `kok-IN`: Konkani + - `mai-IN`: Maithili + - `mni-IN`: Manipuri + - `ne-IN`: Nepali + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `sd-IN`: Sindhi + + **Output Formats (delivered as ZIP file):** + - `html`: Structured HTML files with layout preservation + - `md`: Markdown files (default) + - `json`: Structured JSON files for programmatic processing + + Parameters + ---------- + job_parameters : typing.Optional[DocDigitizationJobParametersParams] + Configuration parameters for the Document Intelligence job including language and output format. Defaults to Hindi (hi-IN) and Markdown output if omitted. + + callback : typing.Optional[DocDigitizationWebhookCallbackParams] + Optional webhook for completion notification + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[DocDigitizationCreateJobResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "doc-digitization/job/v1", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_parameters": convert_and_respect_annotation_metadata( + object_=job_parameters, annotation=DocDigitizationJobParametersParams, direction="write" + ), + "callback": convert_and_respect_annotation_metadata( + object_=callback, annotation=DocDigitizationWebhookCallbackParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationCreateJobResponse, + parse_obj_as( + type_=DocDigitizationCreateJobResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_upload_links( + self, *, job_id: str, files: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[DocDigitizationUploadFilesResponse]: + """ + Returns presigned URLs for uploading input files. + + **File Constraints:** + - Exactly one file required (PDF or ZIP) + - PDF files: `.pdf` extension + - ZIP files: `.zip` extension + + Parameters + ---------- + job_id : str + Job identifier returned from Create Job + + files : typing.Sequence[str] + List of filenames to upload (exactly 1 file: PDF or ZIP) + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[DocDigitizationUploadFilesResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "doc-digitization/job/v1/upload-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationUploadFilesResponse, + parse_obj_as( + type_=DocDigitizationUploadFilesResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def start( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[DocDigitizationJobStatusResponse]: + """ + Validates the uploaded file and starts processing. + + **Validation Checks:** + - File must be uploaded before starting + - File size must not exceed 200 MB + - PDF must be parseable by the PDF parser + - ZIP must contain only JPEG/PNG images + - ZIP must be flat (no nested folders beyond one level) + - ZIP must contain at least one valid image + - Page/image count must not exceed 10 (returns `422` with `max_page_limit_exceeded` if exceeded) + - User must have sufficient credits + + **Processing:** + Job runs asynchronously. Poll the status endpoint or use webhook callback for completion notification. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[DocDigitizationJobStatusResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"doc-digitization/job/v1/{jsonable_encoder(job_id)}/start", + base_url=self._client_wrapper.get_environment().base, + method="POST", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationJobStatusResponse, + parse_obj_as( + type_=DocDigitizationJobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[DocDigitizationJobStatusResponse]: + """ + Returns the current status of a job with page-level metrics. + + **Job States:** + - `Accepted`: Job created, awaiting file upload + - `Pending`: File uploaded, waiting to start + - `Running`: Processing in progress + - `Completed`: All pages processed successfully + - `PartiallyCompleted`: Some pages succeeded, some failed + - `Failed`: All pages failed or job-level error + + **Page Metrics:** + Response includes detailed progress: total pages, pages processed, succeeded, failed, and per-page errors. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[DocDigitizationJobStatusResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"doc-digitization/job/v1/{jsonable_encoder(job_id)}/status", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationJobStatusResponse, + parse_obj_as( + type_=DocDigitizationJobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_download_links( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[DocDigitizationDownloadFilesResponse]: + """ + Returns presigned URLs for downloading output files. + + **Prerequisites:** + - Job must be in `Completed` or `PartiallyCompleted` state + - Failed jobs have no output available + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[DocDigitizationDownloadFilesResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"doc-digitization/job/v1/{jsonable_encoder(job_id)}/download-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + DocDigitizationDownloadFilesResponse, + parse_obj_as( + type_=DocDigitizationDownloadFilesResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/errors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c16f0e1917f7be40e0e89fcc0e5c2647b0e02da1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/__init__.py @@ -0,0 +1,59 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .bad_request_error import BadRequestError + from .content_too_large_error import ContentTooLargeError + from .forbidden_error import ForbiddenError + from .internal_server_error import InternalServerError + from .not_found_error import NotFoundError + from .service_unavailable_error import ServiceUnavailableError + from .too_many_requests_error import TooManyRequestsError + from .unprocessable_entity_error import UnprocessableEntityError +_dynamic_imports: typing.Dict[str, str] = { + "BadRequestError": ".bad_request_error", + "ContentTooLargeError": ".content_too_large_error", + "ForbiddenError": ".forbidden_error", + "InternalServerError": ".internal_server_error", + "NotFoundError": ".not_found_error", + "ServiceUnavailableError": ".service_unavailable_error", + "TooManyRequestsError": ".too_many_requests_error", + "UnprocessableEntityError": ".unprocessable_entity_error", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "BadRequestError", + "ContentTooLargeError", + "ForbiddenError", + "InternalServerError", + "NotFoundError", + "ServiceUnavailableError", + "TooManyRequestsError", + "UnprocessableEntityError", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f8ebf8792093aa4364673cfd2c536ebd768aebf Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/bad_request_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/bad_request_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a60698293bb75d7c145046f41255cd97fb821d64 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/bad_request_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/content_too_large_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/content_too_large_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..486aadba5a09f092683950eb4d4d958bddee1ed7 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/content_too_large_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/forbidden_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/forbidden_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..facb1bbf447758b713cc3bec0f4d88c102fa573a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/forbidden_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/internal_server_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/internal_server_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa4350836dec64558e3300769f14c34a5deda812 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/internal_server_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/not_found_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/not_found_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3be577cb24f2a9b8480315519d3affa1dcc858ac Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/not_found_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/service_unavailable_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/service_unavailable_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ef84a5e4c3cc1352c04810421f550550f2b009b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/service_unavailable_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/too_many_requests_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/too_many_requests_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef6c7a0efeb4cd6cced68254001acf3ba21c08d2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/too_many_requests_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/unprocessable_entity_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/unprocessable_entity_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86c31ab43d2ddf6a0d4746be9c6b616bcd256da6 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/errors/__pycache__/unprocessable_entity_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/bad_request_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/bad_request_error.py new file mode 100644 index 0000000000000000000000000000000000000000..ec78e2697a834d83fdb55fad71f2994d943d55d0 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/bad_request_error.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError + + +class BadRequestError(ApiError): + def __init__(self, body: typing.Any, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=400, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/content_too_large_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/content_too_large_error.py new file mode 100644 index 0000000000000000000000000000000000000000..070419722aee447801b81e3af4e698b7d3e8ebd4 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/content_too_large_error.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError +from ..types.error_message import ErrorMessage + + +class ContentTooLargeError(ApiError): + def __init__(self, body: ErrorMessage, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=413, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/forbidden_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/forbidden_error.py new file mode 100644 index 0000000000000000000000000000000000000000..07d7e45b85a17844bc95f36afaf0e614ae225950 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/forbidden_error.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError + + +class ForbiddenError(ApiError): + def __init__(self, body: typing.Any, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=403, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/internal_server_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/internal_server_error.py new file mode 100644 index 0000000000000000000000000000000000000000..fabcc45cf7eb736e0bc44b2ed5c08422e5ffde4b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/internal_server_error.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError + + +class InternalServerError(ApiError): + def __init__(self, body: typing.Any, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=500, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/not_found_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/not_found_error.py new file mode 100644 index 0000000000000000000000000000000000000000..c41db5d8e670ea133ff9271b0b3f2c277f3506fb --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/not_found_error.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError +from ..types.error_message import ErrorMessage + + +class NotFoundError(ApiError): + def __init__(self, body: ErrorMessage, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=404, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/service_unavailable_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/service_unavailable_error.py new file mode 100644 index 0000000000000000000000000000000000000000..950c47402846219973901b0a38295f5b6996c467 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/service_unavailable_error.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError + + +class ServiceUnavailableError(ApiError): + def __init__(self, body: typing.Any, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=503, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/too_many_requests_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/too_many_requests_error.py new file mode 100644 index 0000000000000000000000000000000000000000..705d6f1ba4d2747b048f13a221669f1a619d3198 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/too_many_requests_error.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError + + +class TooManyRequestsError(ApiError): + def __init__(self, body: typing.Any, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=429, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/errors/unprocessable_entity_error.py b/venv/lib/python3.12/site-packages/sarvamai/errors/unprocessable_entity_error.py new file mode 100644 index 0000000000000000000000000000000000000000..1c801a4bc08bb1e0c42e59f978ad275f4656a150 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/errors/unprocessable_entity_error.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.api_error import ApiError + + +class UnprocessableEntityError(ApiError): + def __init__(self, body: typing.Any, headers: typing.Optional[typing.Dict[str, str]] = None): + super().__init__(status_code=422, headers=headers, body=body) diff --git a/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1904dc2a48d52d08b834af21adf9584facf46e4 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ca96d8f49b5da0bfb280a1c8504149337a8f254 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..192852faf72c0fca0edd781c6eb6a7faff2023f3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/client.py b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/client.py new file mode 100644 index 0000000000000000000000000000000000000000..9380d91b709dcc93f82c95130e646471be1aa7d2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/client.py @@ -0,0 +1,430 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .. import core +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..types.pronunciation_dictionary_data import PronunciationDictionaryData +from ..types.pronunciation_dictionary_delete_response import PronunciationDictionaryDeleteResponse +from ..types.pronunciation_dictionary_get_response import PronunciationDictionaryGetResponse +from ..types.pronunciation_dictionary_response import PronunciationDictionaryResponse +from ..types.pronunciation_dictionary_update_response import PronunciationDictionaryUpdateResponse +from .raw_client import AsyncRawPronunciationDictionaryClient, RawPronunciationDictionaryClient + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class PronunciationDictionaryClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawPronunciationDictionaryClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawPronunciationDictionaryClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawPronunciationDictionaryClient + """ + return self._raw_client + + def list(self, *, request_options: typing.Optional[RequestOptions] = None) -> PronunciationDictionaryGetResponse: + """ + Retrieve a list of all pronunciation dictionary IDs associated with the authenticated user. + + Parameters + ---------- + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryGetResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.pronunciation_dictionary.list() + """ + _response = self._raw_client.list(request_options=request_options) + return _response.data + + def create( + self, *, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryResponse: + """ + Upload a `.json` file to create a new pronunciation dictionary. Only supported by **bulbul:v3**. + + The file should contain a JSON object with a `pronunciations` key mapping language codes to word-pronunciation pairs. See the [Pronunciation Dictionary guide](/api-reference-docs/api-guides-tutorials/text-to-speech/pronunciation-dictionary) for format details and examples. + + The returned `dictionary_id` can be passed as `dict_id` in text-to-speech requests (REST, HTTP Stream, and WebSocket). + + **Limits:** Max 10 dictionaries per user, 100 words per dictionary, 1 MB file size. + + Parameters + ---------- + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.pronunciation_dictionary.create() + """ + _response = self._raw_client.create(file=file, request_options=request_options) + return _response.data + + def update( + self, *, dict_id: str, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryUpdateResponse: + """ + Update an existing pronunciation dictionary by uploading a JSON file. You can add new words, change existing pronunciations, or both — entries not included in the uploaded file remain unchanged. + + **Limits:** Max 100 words per dictionary, 1 MB file size. + + The response includes the `dictionary_id` and the updated pronunciation mappings for verification. + + Parameters + ---------- + dict_id : str + ID of the dictionary to update + + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryUpdateResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.pronunciation_dictionary.update( + dict_id="dict_id", + ) + """ + _response = self._raw_client.update(dict_id=dict_id, file=file, request_options=request_options) + return _response.data + + def delete( + self, *, dict_id: str, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryDeleteResponse: + """ + Delete a pronunciation dictionary by its ID. Once deleted, the dictionary can no longer be referenced in text-to-speech requests. + + Parameters + ---------- + dict_id : str + ID of the dictionary to delete + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryDeleteResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.pronunciation_dictionary.delete( + dict_id="dict_id", + ) + """ + _response = self._raw_client.delete(dict_id=dict_id, request_options=request_options) + return _response.data + + def get( + self, dict_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryData: + """ + Retrieve the full pronunciation mappings for a specific dictionary by its ID. + + Returns the pronunciation data organized by language code, where each language contains word-to-pronunciation pairs. + + Parameters + ---------- + dict_id : str + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryData + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.pronunciation_dictionary.get( + dict_id="dict_id", + ) + """ + _response = self._raw_client.get(dict_id, request_options=request_options) + return _response.data + + +class AsyncPronunciationDictionaryClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawPronunciationDictionaryClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawPronunciationDictionaryClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawPronunciationDictionaryClient + """ + return self._raw_client + + async def list( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryGetResponse: + """ + Retrieve a list of all pronunciation dictionary IDs associated with the authenticated user. + + Parameters + ---------- + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryGetResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.pronunciation_dictionary.list() + + + asyncio.run(main()) + """ + _response = await self._raw_client.list(request_options=request_options) + return _response.data + + async def create( + self, *, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryResponse: + """ + Upload a `.json` file to create a new pronunciation dictionary. Only supported by **bulbul:v3**. + + The file should contain a JSON object with a `pronunciations` key mapping language codes to word-pronunciation pairs. See the [Pronunciation Dictionary guide](/api-reference-docs/api-guides-tutorials/text-to-speech/pronunciation-dictionary) for format details and examples. + + The returned `dictionary_id` can be passed as `dict_id` in text-to-speech requests (REST, HTTP Stream, and WebSocket). + + **Limits:** Max 10 dictionaries per user, 100 words per dictionary, 1 MB file size. + + Parameters + ---------- + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.pronunciation_dictionary.create() + + + asyncio.run(main()) + """ + _response = await self._raw_client.create(file=file, request_options=request_options) + return _response.data + + async def update( + self, *, dict_id: str, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryUpdateResponse: + """ + Update an existing pronunciation dictionary by uploading a JSON file. You can add new words, change existing pronunciations, or both — entries not included in the uploaded file remain unchanged. + + **Limits:** Max 100 words per dictionary, 1 MB file size. + + The response includes the `dictionary_id` and the updated pronunciation mappings for verification. + + Parameters + ---------- + dict_id : str + ID of the dictionary to update + + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryUpdateResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.pronunciation_dictionary.update( + dict_id="dict_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.update(dict_id=dict_id, file=file, request_options=request_options) + return _response.data + + async def delete( + self, *, dict_id: str, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryDeleteResponse: + """ + Delete a pronunciation dictionary by its ID. Once deleted, the dictionary can no longer be referenced in text-to-speech requests. + + Parameters + ---------- + dict_id : str + ID of the dictionary to delete + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryDeleteResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.pronunciation_dictionary.delete( + dict_id="dict_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.delete(dict_id=dict_id, request_options=request_options) + return _response.data + + async def get( + self, dict_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> PronunciationDictionaryData: + """ + Retrieve the full pronunciation mappings for a specific dictionary by its ID. + + Returns the pronunciation data organized by language code, where each language contains word-to-pronunciation pairs. + + Parameters + ---------- + dict_id : str + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + PronunciationDictionaryData + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.pronunciation_dictionary.get( + dict_id="dict_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get(dict_id, request_options=request_options) + return _response.data diff --git a/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a416fce03da1c8a7d1e2abe1eeabc149a82ebd64 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/pronunciation_dictionary/raw_client.py @@ -0,0 +1,1156 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from .. import core +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..errors.bad_request_error import BadRequestError +from ..errors.content_too_large_error import ContentTooLargeError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.not_found_error import NotFoundError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..errors.unprocessable_entity_error import UnprocessableEntityError +from ..types.error_message import ErrorMessage +from ..types.pronunciation_dictionary_data import PronunciationDictionaryData +from ..types.pronunciation_dictionary_delete_response import PronunciationDictionaryDeleteResponse +from ..types.pronunciation_dictionary_get_response import PronunciationDictionaryGetResponse +from ..types.pronunciation_dictionary_response import PronunciationDictionaryResponse +from ..types.pronunciation_dictionary_update_response import PronunciationDictionaryUpdateResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawPronunciationDictionaryClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def list( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[PronunciationDictionaryGetResponse]: + """ + Retrieve a list of all pronunciation dictionary IDs associated with the authenticated user. + + Parameters + ---------- + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[PronunciationDictionaryGetResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryGetResponse, + parse_obj_as( + type_=PronunciationDictionaryGetResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def create( + self, *, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[PronunciationDictionaryResponse]: + """ + Upload a `.json` file to create a new pronunciation dictionary. Only supported by **bulbul:v3**. + + The file should contain a JSON object with a `pronunciations` key mapping language codes to word-pronunciation pairs. See the [Pronunciation Dictionary guide](/api-reference-docs/api-guides-tutorials/text-to-speech/pronunciation-dictionary) for format details and examples. + + The returned `dictionary_id` can be passed as `dict_id` in text-to-speech requests (REST, HTTP Stream, and WebSocket). + + **Limits:** Max 10 dictionaries per user, 100 words per dictionary, 1 MB file size. + + Parameters + ---------- + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[PronunciationDictionaryResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="POST", + data={}, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryResponse, + parse_obj_as( + type_=PronunciationDictionaryResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 413: + raise ContentTooLargeError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def update( + self, *, dict_id: str, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[PronunciationDictionaryUpdateResponse]: + """ + Update an existing pronunciation dictionary by uploading a JSON file. You can add new words, change existing pronunciations, or both — entries not included in the uploaded file remain unchanged. + + **Limits:** Max 100 words per dictionary, 1 MB file size. + + The response includes the `dictionary_id` and the updated pronunciation mappings for verification. + + Parameters + ---------- + dict_id : str + ID of the dictionary to update + + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[PronunciationDictionaryUpdateResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="PUT", + params={ + "dict_id": dict_id, + }, + data={}, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryUpdateResponse, + parse_obj_as( + type_=PronunciationDictionaryUpdateResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 413: + raise ContentTooLargeError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def delete( + self, *, dict_id: str, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[PronunciationDictionaryDeleteResponse]: + """ + Delete a pronunciation dictionary by its ID. Once deleted, the dictionary can no longer be referenced in text-to-speech requests. + + Parameters + ---------- + dict_id : str + ID of the dictionary to delete + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[PronunciationDictionaryDeleteResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="DELETE", + params={ + "dict_id": dict_id, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryDeleteResponse, + parse_obj_as( + type_=PronunciationDictionaryDeleteResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get( + self, dict_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[PronunciationDictionaryData]: + """ + Retrieve the full pronunciation mappings for a specific dictionary by its ID. + + Returns the pronunciation data organized by language code, where each language contains word-to-pronunciation pairs. + + Parameters + ---------- + dict_id : str + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[PronunciationDictionaryData] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"text-to-speech/pronunciation-dictionary/{jsonable_encoder(dict_id)}", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryData, + parse_obj_as( + type_=PronunciationDictionaryData, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + +class AsyncRawPronunciationDictionaryClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def list( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[PronunciationDictionaryGetResponse]: + """ + Retrieve a list of all pronunciation dictionary IDs associated with the authenticated user. + + Parameters + ---------- + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[PronunciationDictionaryGetResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryGetResponse, + parse_obj_as( + type_=PronunciationDictionaryGetResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def create( + self, *, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[PronunciationDictionaryResponse]: + """ + Upload a `.json` file to create a new pronunciation dictionary. Only supported by **bulbul:v3**. + + The file should contain a JSON object with a `pronunciations` key mapping language codes to word-pronunciation pairs. See the [Pronunciation Dictionary guide](/api-reference-docs/api-guides-tutorials/text-to-speech/pronunciation-dictionary) for format details and examples. + + The returned `dictionary_id` can be passed as `dict_id` in text-to-speech requests (REST, HTTP Stream, and WebSocket). + + **Limits:** Max 10 dictionaries per user, 100 words per dictionary, 1 MB file size. + + Parameters + ---------- + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[PronunciationDictionaryResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="POST", + data={}, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryResponse, + parse_obj_as( + type_=PronunciationDictionaryResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 413: + raise ContentTooLargeError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def update( + self, *, dict_id: str, file: core.File, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[PronunciationDictionaryUpdateResponse]: + """ + Update an existing pronunciation dictionary by uploading a JSON file. You can add new words, change existing pronunciations, or both — entries not included in the uploaded file remain unchanged. + + **Limits:** Max 100 words per dictionary, 1 MB file size. + + The response includes the `dictionary_id` and the updated pronunciation mappings for verification. + + Parameters + ---------- + dict_id : str + ID of the dictionary to update + + file : core.File + See core.File for more documentation + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[PronunciationDictionaryUpdateResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="PUT", + params={ + "dict_id": dict_id, + }, + data={}, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryUpdateResponse, + parse_obj_as( + type_=PronunciationDictionaryUpdateResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 413: + raise ContentTooLargeError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def delete( + self, *, dict_id: str, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[PronunciationDictionaryDeleteResponse]: + """ + Delete a pronunciation dictionary by its ID. Once deleted, the dictionary can no longer be referenced in text-to-speech requests. + + Parameters + ---------- + dict_id : str + ID of the dictionary to delete + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[PronunciationDictionaryDeleteResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "text-to-speech/pronunciation-dictionary", + base_url=self._client_wrapper.get_environment().base, + method="DELETE", + params={ + "dict_id": dict_id, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryDeleteResponse, + parse_obj_as( + type_=PronunciationDictionaryDeleteResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get( + self, dict_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[PronunciationDictionaryData]: + """ + Retrieve the full pronunciation mappings for a specific dictionary by its ID. + + Returns the pronunciation data organized by language code, where each language contains word-to-pronunciation pairs. + + Parameters + ---------- + dict_id : str + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[PronunciationDictionaryData] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"text-to-speech/pronunciation-dictionary/{jsonable_encoder(dict_id)}", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + PronunciationDictionaryData, + parse_obj_as( + type_=PronunciationDictionaryData, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 404: + raise NotFoundError( + headers=dict(_response.headers), + body=typing.cast( + ErrorMessage, + parse_obj_as( + type_=ErrorMessage, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/requests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..779f934b009f13b6f027286d6d9fbb23eb988ea4 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/__init__.py @@ -0,0 +1,295 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .audio_data import AudioDataParams + from .audio_message import AudioMessageParams + from .audio_output import AudioOutputParams + from .audio_output_data import AudioOutputDataParams + from .base_job_parameters import BaseJobParametersParams + from .bulk_job_callback import BulkJobCallbackParams + from .bulk_job_init_response import BulkJobInitResponseParams + from .chat_completion_message_tool_call import ChatCompletionMessageToolCallParams + from .chat_completion_named_tool_choice import ChatCompletionNamedToolChoiceParams + from .chat_completion_named_tool_choice_function import ChatCompletionNamedToolChoiceFunctionParams + from .chat_completion_request_assistant_message import ChatCompletionRequestAssistantMessageParams + from .chat_completion_request_message import ( + ChatCompletionRequestMessageParams, + ChatCompletionRequestMessage_AssistantParams, + ChatCompletionRequestMessage_SystemParams, + ChatCompletionRequestMessage_ToolParams, + ChatCompletionRequestMessage_UserParams, + ) + from .chat_completion_request_system_message import ChatCompletionRequestSystemMessageParams + from .chat_completion_request_tool_message import ChatCompletionRequestToolMessageParams + from .chat_completion_request_user_message import ChatCompletionRequestUserMessageParams + from .chat_completion_response_message import ChatCompletionResponseMessageParams + from .chat_completion_tool import ChatCompletionToolParams + from .choice import ChoiceParams + from .completion_usage import CompletionUsageParams + from .config_message import ConfigMessageParams + from .configure_connection import ConfigureConnectionParams + from .configure_connection_data import ConfigureConnectionDataParams + from .create_chat_completion_response import CreateChatCompletionResponseParams + from .diarized_entry import DiarizedEntryParams + from .diarized_transcript import DiarizedTranscriptParams + from .doc_digitization_create_job_response import DocDigitizationCreateJobResponseParams + from .doc_digitization_download_files_response import DocDigitizationDownloadFilesResponseParams + from .doc_digitization_error_details import DocDigitizationErrorDetailsParams + from .doc_digitization_error_message import DocDigitizationErrorMessageParams + from .doc_digitization_job_detail import DocDigitizationJobDetailParams + from .doc_digitization_job_parameters import DocDigitizationJobParametersParams + from .doc_digitization_job_status_response import DocDigitizationJobStatusResponseParams + from .doc_digitization_page_error import DocDigitizationPageErrorParams + from .doc_digitization_upload_files_response import DocDigitizationUploadFilesResponseParams + from .doc_digitization_webhook_callback import DocDigitizationWebhookCallbackParams + from .error_data import ErrorDataParams + from .error_details import ErrorDetailsParams + from .error_details2 import ErrorDetails2Params + from .error_message import ErrorMessageParams + from .error_message2 import ErrorMessage2Params + from .error_response import ErrorResponseParams + from .error_response_data import ErrorResponseDataParams + from .event_response import EventResponseParams + from .event_response_data import EventResponseDataParams + from .events_data import EventsDataParams + from .file_signed_url_details import FileSignedUrlDetailsParams + from .files_download_response import FilesDownloadResponseParams + from .files_request import FilesRequestParams + from .files_upload_response import FilesUploadResponseParams + from .flush_signal import FlushSignalParams + from .function_call import FunctionCallParams + from .function_definition import FunctionDefinitionParams + from .job_status_response import JobStatusResponseParams + from .language_identification_response import LanguageIdentificationResponseParams + from .ping_signal import PingSignalParams + from .pronunciation_dictionary_data import PronunciationDictionaryDataParams + from .pronunciation_dictionary_delete_response import PronunciationDictionaryDeleteResponseParams + from .pronunciation_dictionary_get_response import PronunciationDictionaryGetResponseParams + from .pronunciation_dictionary_response import PronunciationDictionaryResponseParams + from .pronunciation_dictionary_update_response import PronunciationDictionaryUpdateResponseParams + from .send_text import SendTextParams + from .send_text_data import SendTextDataParams + from .speech_to_text_job_parameters import SpeechToTextJobParametersParams + from .speech_to_text_response import SpeechToTextResponseParams + from .speech_to_text_response_data import SpeechToTextResponseDataParams + from .speech_to_text_streaming_response import SpeechToTextStreamingResponseParams + from .speech_to_text_transcription_data import SpeechToTextTranscriptionDataParams + from .speech_to_text_translate_job_parameters import SpeechToTextTranslateJobParametersParams + from .speech_to_text_translate_response import SpeechToTextTranslateResponseParams + from .speech_to_text_translate_response_data import SpeechToTextTranslateResponseDataParams + from .speech_to_text_translate_streaming_response import SpeechToTextTranslateStreamingResponseParams + from .speech_to_text_translate_transcription_data import SpeechToTextTranslateTranscriptionDataParams + from .stop_configuration import StopConfigurationParams + from .stt_flush_signal import SttFlushSignalParams + from .task_detail import TaskDetailParams + from .task_file_details import TaskFileDetailsParams + from .text_to_speech_response import TextToSpeechResponseParams + from .timestamps_model import TimestampsModelParams + from .tool_choice_option import ToolChoiceOptionParams + from .transcription_metrics import TranscriptionMetricsParams + from .translation_response import TranslationResponseParams + from .transliteration_response import TransliterationResponseParams +_dynamic_imports: typing.Dict[str, str] = { + "AudioDataParams": ".audio_data", + "AudioMessageParams": ".audio_message", + "AudioOutputDataParams": ".audio_output_data", + "AudioOutputParams": ".audio_output", + "BaseJobParametersParams": ".base_job_parameters", + "BulkJobCallbackParams": ".bulk_job_callback", + "BulkJobInitResponseParams": ".bulk_job_init_response", + "ChatCompletionMessageToolCallParams": ".chat_completion_message_tool_call", + "ChatCompletionNamedToolChoiceFunctionParams": ".chat_completion_named_tool_choice_function", + "ChatCompletionNamedToolChoiceParams": ".chat_completion_named_tool_choice", + "ChatCompletionRequestAssistantMessageParams": ".chat_completion_request_assistant_message", + "ChatCompletionRequestMessageParams": ".chat_completion_request_message", + "ChatCompletionRequestMessage_AssistantParams": ".chat_completion_request_message", + "ChatCompletionRequestMessage_SystemParams": ".chat_completion_request_message", + "ChatCompletionRequestMessage_ToolParams": ".chat_completion_request_message", + "ChatCompletionRequestMessage_UserParams": ".chat_completion_request_message", + "ChatCompletionRequestSystemMessageParams": ".chat_completion_request_system_message", + "ChatCompletionRequestToolMessageParams": ".chat_completion_request_tool_message", + "ChatCompletionRequestUserMessageParams": ".chat_completion_request_user_message", + "ChatCompletionResponseMessageParams": ".chat_completion_response_message", + "ChatCompletionToolParams": ".chat_completion_tool", + "ChoiceParams": ".choice", + "CompletionUsageParams": ".completion_usage", + "ConfigMessageParams": ".config_message", + "ConfigureConnectionDataParams": ".configure_connection_data", + "ConfigureConnectionParams": ".configure_connection", + "CreateChatCompletionResponseParams": ".create_chat_completion_response", + "DiarizedEntryParams": ".diarized_entry", + "DiarizedTranscriptParams": ".diarized_transcript", + "DocDigitizationCreateJobResponseParams": ".doc_digitization_create_job_response", + "DocDigitizationDownloadFilesResponseParams": ".doc_digitization_download_files_response", + "DocDigitizationErrorDetailsParams": ".doc_digitization_error_details", + "DocDigitizationErrorMessageParams": ".doc_digitization_error_message", + "DocDigitizationJobDetailParams": ".doc_digitization_job_detail", + "DocDigitizationJobParametersParams": ".doc_digitization_job_parameters", + "DocDigitizationJobStatusResponseParams": ".doc_digitization_job_status_response", + "DocDigitizationPageErrorParams": ".doc_digitization_page_error", + "DocDigitizationUploadFilesResponseParams": ".doc_digitization_upload_files_response", + "DocDigitizationWebhookCallbackParams": ".doc_digitization_webhook_callback", + "ErrorDataParams": ".error_data", + "ErrorDetails2Params": ".error_details2", + "ErrorDetailsParams": ".error_details", + "ErrorMessage2Params": ".error_message2", + "ErrorMessageParams": ".error_message", + "ErrorResponseDataParams": ".error_response_data", + "ErrorResponseParams": ".error_response", + "EventResponseDataParams": ".event_response_data", + "EventResponseParams": ".event_response", + "EventsDataParams": ".events_data", + "FileSignedUrlDetailsParams": ".file_signed_url_details", + "FilesDownloadResponseParams": ".files_download_response", + "FilesRequestParams": ".files_request", + "FilesUploadResponseParams": ".files_upload_response", + "FlushSignalParams": ".flush_signal", + "FunctionCallParams": ".function_call", + "FunctionDefinitionParams": ".function_definition", + "JobStatusResponseParams": ".job_status_response", + "LanguageIdentificationResponseParams": ".language_identification_response", + "PingSignalParams": ".ping_signal", + "PronunciationDictionaryDataParams": ".pronunciation_dictionary_data", + "PronunciationDictionaryDeleteResponseParams": ".pronunciation_dictionary_delete_response", + "PronunciationDictionaryGetResponseParams": ".pronunciation_dictionary_get_response", + "PronunciationDictionaryResponseParams": ".pronunciation_dictionary_response", + "PronunciationDictionaryUpdateResponseParams": ".pronunciation_dictionary_update_response", + "SendTextDataParams": ".send_text_data", + "SendTextParams": ".send_text", + "SpeechToTextJobParametersParams": ".speech_to_text_job_parameters", + "SpeechToTextResponseDataParams": ".speech_to_text_response_data", + "SpeechToTextResponseParams": ".speech_to_text_response", + "SpeechToTextStreamingResponseParams": ".speech_to_text_streaming_response", + "SpeechToTextTranscriptionDataParams": ".speech_to_text_transcription_data", + "SpeechToTextTranslateJobParametersParams": ".speech_to_text_translate_job_parameters", + "SpeechToTextTranslateResponseDataParams": ".speech_to_text_translate_response_data", + "SpeechToTextTranslateResponseParams": ".speech_to_text_translate_response", + "SpeechToTextTranslateStreamingResponseParams": ".speech_to_text_translate_streaming_response", + "SpeechToTextTranslateTranscriptionDataParams": ".speech_to_text_translate_transcription_data", + "StopConfigurationParams": ".stop_configuration", + "SttFlushSignalParams": ".stt_flush_signal", + "TaskDetailParams": ".task_detail", + "TaskFileDetailsParams": ".task_file_details", + "TextToSpeechResponseParams": ".text_to_speech_response", + "TimestampsModelParams": ".timestamps_model", + "ToolChoiceOptionParams": ".tool_choice_option", + "TranscriptionMetricsParams": ".transcription_metrics", + "TranslationResponseParams": ".translation_response", + "TransliterationResponseParams": ".transliteration_response", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "AudioDataParams", + "AudioMessageParams", + "AudioOutputDataParams", + "AudioOutputParams", + "BaseJobParametersParams", + "BulkJobCallbackParams", + "BulkJobInitResponseParams", + "ChatCompletionMessageToolCallParams", + "ChatCompletionNamedToolChoiceFunctionParams", + "ChatCompletionNamedToolChoiceParams", + "ChatCompletionRequestAssistantMessageParams", + "ChatCompletionRequestMessageParams", + "ChatCompletionRequestMessage_AssistantParams", + "ChatCompletionRequestMessage_SystemParams", + "ChatCompletionRequestMessage_ToolParams", + "ChatCompletionRequestMessage_UserParams", + "ChatCompletionRequestSystemMessageParams", + "ChatCompletionRequestToolMessageParams", + "ChatCompletionRequestUserMessageParams", + "ChatCompletionResponseMessageParams", + "ChatCompletionToolParams", + "ChoiceParams", + "CompletionUsageParams", + "ConfigMessageParams", + "ConfigureConnectionDataParams", + "ConfigureConnectionParams", + "CreateChatCompletionResponseParams", + "DiarizedEntryParams", + "DiarizedTranscriptParams", + "DocDigitizationCreateJobResponseParams", + "DocDigitizationDownloadFilesResponseParams", + "DocDigitizationErrorDetailsParams", + "DocDigitizationErrorMessageParams", + "DocDigitizationJobDetailParams", + "DocDigitizationJobParametersParams", + "DocDigitizationJobStatusResponseParams", + "DocDigitizationPageErrorParams", + "DocDigitizationUploadFilesResponseParams", + "DocDigitizationWebhookCallbackParams", + "ErrorDataParams", + "ErrorDetails2Params", + "ErrorDetailsParams", + "ErrorMessage2Params", + "ErrorMessageParams", + "ErrorResponseDataParams", + "ErrorResponseParams", + "EventResponseDataParams", + "EventResponseParams", + "EventsDataParams", + "FileSignedUrlDetailsParams", + "FilesDownloadResponseParams", + "FilesRequestParams", + "FilesUploadResponseParams", + "FlushSignalParams", + "FunctionCallParams", + "FunctionDefinitionParams", + "JobStatusResponseParams", + "LanguageIdentificationResponseParams", + "PingSignalParams", + "PronunciationDictionaryDataParams", + "PronunciationDictionaryDeleteResponseParams", + "PronunciationDictionaryGetResponseParams", + "PronunciationDictionaryResponseParams", + "PronunciationDictionaryUpdateResponseParams", + "SendTextDataParams", + "SendTextParams", + "SpeechToTextJobParametersParams", + "SpeechToTextResponseDataParams", + "SpeechToTextResponseParams", + "SpeechToTextStreamingResponseParams", + "SpeechToTextTranscriptionDataParams", + "SpeechToTextTranslateJobParametersParams", + "SpeechToTextTranslateResponseDataParams", + "SpeechToTextTranslateResponseParams", + "SpeechToTextTranslateStreamingResponseParams", + "SpeechToTextTranslateTranscriptionDataParams", + "StopConfigurationParams", + "SttFlushSignalParams", + "TaskDetailParams", + "TaskFileDetailsParams", + "TextToSpeechResponseParams", + "TimestampsModelParams", + "ToolChoiceOptionParams", + "TranscriptionMetricsParams", + "TranslationResponseParams", + "TransliterationResponseParams", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0906b4f6cad80d23e58fbfb606d1e29305da9e01 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52f9691bdd7beacbf2342349ee5a5f35b38b4cfb Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d707d2355bfbbf4e0e9c1a9fc9e6a6b2052b252 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_output.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_output.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41d2b5fffba51b5b786cdf1959812a5aff9796d3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_output.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_output_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_output_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9028f7f149780e693fff2373c6ad707a86af6dae Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/audio_output_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/base_job_parameters.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/base_job_parameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d433df6e88599e9e9065547173c5e75d9040843a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/base_job_parameters.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/bulk_job_callback.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/bulk_job_callback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c5a201bfd10a137ca19bf1d5fd32929c8a39c32 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/bulk_job_callback.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/bulk_job_init_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/bulk_job_init_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcb1113960e1bc007a35aaaa21db4b62058516ea Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/bulk_job_init_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_message_tool_call.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_message_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c371b5b53bc9371b9ebdad52053f1a4bbb208348 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_message_tool_call.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_named_tool_choice.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_named_tool_choice.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a756bfa30f7c3f66a6ae80ce1a4a48bdc734a999 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_named_tool_choice.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_named_tool_choice_function.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_named_tool_choice_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..415c8983bc093ccc19c91461d2a96829989925da Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_named_tool_choice_function.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_assistant_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_assistant_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..439a6cf7f963e444ec1ea44ec77f1be314651f98 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_assistant_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92f1694438710a3906e7ccdf90c7fd1d5c5ea8a8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_system_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_system_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b44714b291a920014083edb98d2f97e7413d73ba Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_system_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_tool_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_tool_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c844607cdb61b453c3e28a82a09b2c9245ff40bf Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_tool_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_user_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_user_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dc0f1c3c358077a5837e9e9914c88fc41f9565e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_request_user_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_response_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_response_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c4da2fef599a43dba30c41e9d9999ed219f465b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_response_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_tool.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7b04da23586ad4b8a4294e7a6397404a4f2c736 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/chat_completion_tool.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/choice.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/choice.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61fa4a63bf6614c47a215c2b77ffd39831186c90 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/choice.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/completion_usage.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/completion_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8841918833449a98f1f9366f64c1f6bee4477bf2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/completion_usage.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/config_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/config_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d1f9fe5544c24af663ca79807833d322d44f4a3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/config_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/configure_connection.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/configure_connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..917b2561caa1f76023b0f2aa213de1a91c7750d1 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/configure_connection.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/configure_connection_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/configure_connection_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1ec94d5a043956b6a6d3a31dc233ee7b368d2a9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/configure_connection_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/create_chat_completion_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/create_chat_completion_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9470a06de93d3bb1d39aa86a6fd14bbebe672f3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/create_chat_completion_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/diarized_entry.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/diarized_entry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acd929093a81fab90f0419309e594d21cbda7dc5 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/diarized_entry.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/diarized_transcript.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/diarized_transcript.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5081f9cc23ddea2ed3ddffb27b8ffbfc3858edaa Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/diarized_transcript.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_create_job_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_create_job_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1391b15098dd87077a94e7f6485f578a4acdda1 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_create_job_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_download_files_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_download_files_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3332aaa27d07cbc8b2de570c8fa2af18740e35fb Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_download_files_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_error_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_error_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ad49b60f1a2ef3b509e43c2f8afd12ef6b1222 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_error_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_error_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_error_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3124f7e3d3065a16a01533de8c48716fd3acd52e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_error_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_detail.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_detail.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ccd47ca4d58a53f2a12227cbe433165b4aeab5c Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_detail.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_parameters.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_parameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bbb727cb945600a006a6caf629df4321ee4a7f8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_parameters.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_status_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_status_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..450e7361922afea3b925fe79a74af3c506a144b2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_job_status_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_page_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_page_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26a4eb0bea6c5cdc05d9e7f6643005a0f1526fac Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_page_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_upload_files_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_upload_files_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b34651d968b7fd624a08c83064af9872eab8d79 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_upload_files_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_webhook_callback.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_webhook_callback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9eb46cc8c2527ddd7a7d1b0268730bef2bad8f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/doc_digitization_webhook_callback.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e61cc607054499155878f93793427e61f7ccb3f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0521e2460ea2b20714857e4665e2eee6fbd42c5 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_details2.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_details2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f07d564f6a657eb35b7a4ed85c3e45649003507 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_details2.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3606e8840655f491353691f3b577498b5587b684 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_message2.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_message2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ad78ab3feb4c2fe0cbd912c260f3e0e83acb94 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_message2.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4009dd56ca9abb615bc1816ed50325b8d78749ef Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_response_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_response_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2014546a79a2ffa6c3244d2f84e6dc2d26a093d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/error_response_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/event_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/event_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f6afbb767b8e6f85e8987c387c0247f763b2ab3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/event_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/event_response_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/event_response_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c48975d230d0251bbc274a755b66d8c7aa4c622 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/event_response_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/events_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/events_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad41ce0723f993e7ffc620059031c570d8ad5a0f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/events_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/file_signed_url_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/file_signed_url_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3511a249338bed07125480e74ced86f00f61680a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/file_signed_url_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_download_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_download_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..079806b3238c5c52712b1cb7026114b5f72c65d9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_download_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_request.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..255f3f645758a4d03978d0ab5a4d89e8a6d13227 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_request.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_upload_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_upload_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bce25b9129ed8eaa3117dda79573a9f328b3d988 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/files_upload_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/flush_signal.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/flush_signal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a293710eee0b7a78555bb8a31257d3aff54c8f7e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/flush_signal.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/function_call.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/function_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a61f6a532415ee153a2b3c401f2d00fbdf698b39 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/function_call.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/function_definition.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/function_definition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6f1e4e40758e60d7e11fd75815cd637497dd88d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/function_definition.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/job_status_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/job_status_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21e673add0a3408da5048b2df592ed8611a8b5a7 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/job_status_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/language_identification_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/language_identification_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c08fcbf01d9f5eec3bece47c17ee4b144b892f9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/language_identification_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/ping_signal.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/ping_signal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dc3be95077f8139740cd605e536b63cb215887f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/ping_signal.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..453194f3ece3e94c93add413bebda6e059a6a8d2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_delete_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_delete_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee49a992c9e497b1d29f0232437cf5cf0cecdf2e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_delete_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_get_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_get_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..379b14245c354df1c3bc4087359645df88c573ac Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_get_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12976b6deb6910c9fa332886ac67a0b27a541bfe Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_update_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_update_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90c6b849c6fb683b366ba5f0db734372c3edcc8a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/pronunciation_dictionary_update_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/send_text.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/send_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b04e4cba1292a57f3ef65448f911124de97d07d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/send_text.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/send_text_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/send_text_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84590ea4dcd616cc9150ad2d4d2869a9cf1b0acc Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/send_text_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_job_parameters.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_job_parameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7133988e21fe3c62af73e3d3a5051bd1f90a92e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_job_parameters.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54ea21b078e3677b974124d973dfbebbbf300d57 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_response_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_response_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f68d1ca0793f61bd60dae46105327c5b7f152b8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_response_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_streaming_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_streaming_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1b4ad10e4b3962e5a28e3b7f7711eea8141e872 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_streaming_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_transcription_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_transcription_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3507f28c7e683c34c380c6941695266a11318d94 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_transcription_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_job_parameters.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_job_parameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a33ba7e68101e1426b86c9c132e12cf07669ffb2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_job_parameters.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..981b428db34fb649a4b82d14f7b189b7140d54ba Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_response_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_response_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb5c6a534e29fe0597af63b497fa1d8f83657da4 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_response_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_streaming_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_streaming_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c33f0695d31cbe98d4df0799ff68e230796af33e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_streaming_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_transcription_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_transcription_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96b2af96cdda690e0837569bd85e5000ab029b80 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/speech_to_text_translate_transcription_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/stop_configuration.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/stop_configuration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..021629a2af984495f0d920b94ba07add695936e0 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/stop_configuration.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/stt_flush_signal.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/stt_flush_signal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30012aea4bfbb20f524c7e701c55b198cebd41dd Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/stt_flush_signal.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/task_detail.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/task_detail.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf909fd01d6027d31f62d205b62aae28efde27d5 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/task_detail.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/task_file_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/task_file_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1f97747bd3b388ff75cd9fbc6fbd5f4d9e8c74f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/task_file_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/text_to_speech_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/text_to_speech_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab8e9d10ea0607f0d3b96e6021c8c2e0f929eaf6 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/text_to_speech_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/timestamps_model.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/timestamps_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4579f2c50016c5c288e0515c07dbea45d3eee5a5 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/timestamps_model.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/tool_choice_option.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/tool_choice_option.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2039b6a8277803ca3c6e6c3eaba802474a50a5a6 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/tool_choice_option.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/transcription_metrics.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/transcription_metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64af6be3ffad17b7e3ea145c685fe426e5632708 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/transcription_metrics.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/translation_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/translation_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94a182b923bacb5a00e38e72e6d3cbc5efaea801 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/translation_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/transliteration_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/transliteration_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e78db7d430eb777b4aeaed85b1c4c56991e8cdfd Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/requests/__pycache__/transliteration_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/audio_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_data.py new file mode 100644 index 0000000000000000000000000000000000000000..70f096c31c9bd64e77f5da9f4e7265c146cb5d46 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_data.py @@ -0,0 +1,28 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class AudioDataParams(typing_extensions.TypedDict): + data: str + """ + Base64 encoded audio data + """ + + sample_rate: int + """ + Audio sample rate in Hz for individual audio messages. + + **Backward Compatibility**: This property is maintained for legacy support. + **Recommended**: Use the connection-level sample_rate parameter instead. + **Note**: 8kHz is only supported via connection parameter, not in AudioData messages. + + Supported values: 16kHz (preferred), 22.05kHz, 24kHz + """ + + encoding: typing.Literal["audio/wav"] + """ + Audio encoding format + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/audio_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_message.py new file mode 100644 index 0000000000000000000000000000000000000000..80f6247017bc31c6b8f08066e7229fcc937824a8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_message.py @@ -0,0 +1,8 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from .audio_data import AudioDataParams + + +class AudioMessageParams(typing_extensions.TypedDict): + audio: AudioDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/audio_output.py b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_output.py new file mode 100644 index 0000000000000000000000000000000000000000..75c18e69e790b05caca31141414850dd924b5203 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_output.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .audio_output_data import AudioOutputDataParams + + +class AudioOutputParams(typing_extensions.TypedDict): + type: typing.Literal["audio"] + data: AudioOutputDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/audio_output_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_output_data.py new file mode 100644 index 0000000000000000000000000000000000000000..48bbbaeead43577e05bc565fd7c2c8a16cd07b00 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/audio_output_data.py @@ -0,0 +1,20 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class AudioOutputDataParams(typing_extensions.TypedDict): + content_type: str + """ + MIME type of the audio content (e.g., 'audio/mp3', 'audio/wav') + """ + + audio: str + """ + Base64-encoded audio data ready for playback or download + """ + + request_id: typing_extensions.NotRequired[str] + """ + Unique identifier for the request + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/base_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/requests/base_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8cf915d04c31574695c8608d1359c31fe17586 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/base_job_parameters.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class BaseJobParametersParams(typing_extensions.TypedDict): + pass diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/bulk_job_callback.py b/venv/lib/python3.12/site-packages/sarvamai/requests/bulk_job_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..ae9b6df2b8f27f1ed5893b4b06524ee9e579e9be --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/bulk_job_callback.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class BulkJobCallbackParams(typing_extensions.TypedDict): + url: str + """ + Webhook url to call upon job completion + """ + + auth_token: typing_extensions.NotRequired[str] + """ + Authorization token required for the callback Url + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/bulk_job_init_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/bulk_job_init_response.py new file mode 100644 index 0000000000000000000000000000000000000000..31949aecfd9af34b492bef2c4ca944fabcfab0d6 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/bulk_job_init_response.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.job_state import JobState +from ..types.storage_container_type import StorageContainerType +from .base_job_parameters import BaseJobParametersParams + + +class BulkJobInitResponseParams(typing_extensions.TypedDict): + job_id: str + """ + Job UUID. + """ + + storage_container_type: StorageContainerType + """ + Storage Container Type + """ + + job_parameters: BaseJobParametersParams + job_state: JobState diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_message_tool_call.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_message_tool_call.py new file mode 100644 index 0000000000000000000000000000000000000000..528cc0b57d0e7ca44781c911106d91eb6d1ac19a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_message_tool_call.py @@ -0,0 +1,20 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .function_call import FunctionCallParams + + +class ChatCompletionMessageToolCallParams(typing_extensions.TypedDict): + id: str + """ + The ID of the tool call. + """ + + type: typing.Literal["function"] + """ + The type of the tool call, currently only `function`. + """ + + function: FunctionCallParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_named_tool_choice.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_named_tool_choice.py new file mode 100644 index 0000000000000000000000000000000000000000..225f3d0da7f0d14c1eb3d37dd58a4cd23d2350ca --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_named_tool_choice.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .chat_completion_named_tool_choice_function import ChatCompletionNamedToolChoiceFunctionParams + + +class ChatCompletionNamedToolChoiceParams(typing_extensions.TypedDict): + type: typing.Literal["function"] + """ + The type of the tool. Currently, only `function` is supported. + """ + + function: ChatCompletionNamedToolChoiceFunctionParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_named_tool_choice_function.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_named_tool_choice_function.py new file mode 100644 index 0000000000000000000000000000000000000000..79a809193fddc1201c0058c3521fee1f3bb7a871 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_named_tool_choice_function.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class ChatCompletionNamedToolChoiceFunctionParams(typing_extensions.TypedDict): + name: str + """ + The name of the function to call. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_assistant_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_assistant_message.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a3f1bae05ed02beae7e959c9aed179b5e45873 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_assistant_message.py @@ -0,0 +1,18 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .chat_completion_message_tool_call import ChatCompletionMessageToolCallParams + + +class ChatCompletionRequestAssistantMessageParams(typing_extensions.TypedDict): + content: typing_extensions.NotRequired[str] + """ + The contents of the assistant message + """ + + tool_calls: typing_extensions.NotRequired[typing.Sequence[ChatCompletionMessageToolCallParams]] + """ + The tool calls generated by the model. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_message.py new file mode 100644 index 0000000000000000000000000000000000000000..09e572c65f6377950ba3a50ebbc1e07f2582fcc4 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_message.py @@ -0,0 +1,38 @@ +# This file was auto-generated by Fern from our API Definition. + +from __future__ import annotations + +import typing + +import typing_extensions +from .chat_completion_message_tool_call import ChatCompletionMessageToolCallParams + + +class ChatCompletionRequestMessage_AssistantParams(typing_extensions.TypedDict): + role: typing.Literal["assistant"] + content: typing_extensions.NotRequired[str] + tool_calls: typing_extensions.NotRequired[typing.Sequence[ChatCompletionMessageToolCallParams]] + + +class ChatCompletionRequestMessage_SystemParams(typing_extensions.TypedDict): + role: typing.Literal["system"] + content: str + + +class ChatCompletionRequestMessage_ToolParams(typing_extensions.TypedDict): + role: typing.Literal["tool"] + content: str + tool_call_id: str + + +class ChatCompletionRequestMessage_UserParams(typing_extensions.TypedDict): + role: typing.Literal["user"] + content: str + + +ChatCompletionRequestMessageParams = typing.Union[ + ChatCompletionRequestMessage_AssistantParams, + ChatCompletionRequestMessage_SystemParams, + ChatCompletionRequestMessage_ToolParams, + ChatCompletionRequestMessage_UserParams, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_system_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_system_message.py new file mode 100644 index 0000000000000000000000000000000000000000..b0f21c20a85c921ba2ddcf7dfa890ed0842fd562 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_system_message.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class ChatCompletionRequestSystemMessageParams(typing_extensions.TypedDict): + content: str + """ + The contents of the system message. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_tool_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_tool_message.py new file mode 100644 index 0000000000000000000000000000000000000000..f2213f57465a896bfb5133cc6ecd9da0b7b456ba --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_tool_message.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class ChatCompletionRequestToolMessageParams(typing_extensions.TypedDict): + content: str + """ + The contents of the tool message. + """ + + tool_call_id: str + """ + Tool call that this message is responding to. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_user_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_user_message.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b0c55a9bd9f638c7724bfce517df4daebacdba --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_request_user_message.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class ChatCompletionRequestUserMessageParams(typing_extensions.TypedDict): + content: str + """ + The contents of the user message. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_response_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_response_message.py new file mode 100644 index 0000000000000000000000000000000000000000..20e53256c489c820f1a358197f955b14234f1bdd --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_response_message.py @@ -0,0 +1,30 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.role import Role +from .chat_completion_message_tool_call import ChatCompletionMessageToolCallParams + + +class ChatCompletionResponseMessageParams(typing_extensions.TypedDict): + content: typing_extensions.NotRequired[str] + """ + The contents of the message. + """ + + refusal: typing_extensions.NotRequired[str] + reasoning_content: typing_extensions.NotRequired[str] + """ + The contents of the reasoning message. + """ + + role: Role + """ + The role of the author of this message. + """ + + tool_calls: typing_extensions.NotRequired[typing.Sequence[ChatCompletionMessageToolCallParams]] + """ + The tool calls generated by the model. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_tool.py b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..71bbe63f5fa171d0b2e54b6d139f6440ba087ace --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/chat_completion_tool.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .function_definition import FunctionDefinitionParams + + +class ChatCompletionToolParams(typing_extensions.TypedDict): + type: typing.Literal["function"] + """ + The type of the tool. Currently, only `function` is supported. + """ + + function: FunctionDefinitionParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/choice.py b/venv/lib/python3.12/site-packages/sarvamai/requests/choice.py new file mode 100644 index 0000000000000000000000000000000000000000..1cde4633890dd17444cde431961644b4a0923b74 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/choice.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.finish_reason import FinishReason +from .chat_completion_response_message import ChatCompletionResponseMessageParams + + +class ChoiceParams(typing_extensions.TypedDict): + finish_reason: FinishReason + """ + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + `length` if the maximum number of tokens specified in the request was reached, + `content_filter` if content was omitted due to a flag from our content filters, + `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. + """ + + index: int + """ + The index of the choice in the list of choices. + """ + + logprobs: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] + message: ChatCompletionResponseMessageParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/completion_usage.py b/venv/lib/python3.12/site-packages/sarvamai/requests/completion_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6f7939c7ba39b674d11aaa0c7ab32285684d52 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/completion_usage.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class CompletionUsageParams(typing_extensions.TypedDict): + completion_tokens: int + """ + Number of tokens in the generated completion. + """ + + prompt_tokens: int + """ + Number of tokens in the prompt. + """ + + total_tokens: int + """ + Total number of tokens used in the request (prompt + completion). + """ + + completion_tokens_details: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] + prompt_tokens_details: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/config_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/config_message.py new file mode 100644 index 0000000000000000000000000000000000000000..52a4cdc6ab8df451cf7b40699521bb2b6cb4a113 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/config_message.py @@ -0,0 +1,17 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class ConfigMessageParams(typing_extensions.TypedDict): + type: typing.Literal["config"] + """ + Message type identifier for configuration + """ + + prompt: typing_extensions.NotRequired[str] + """ + Prompt for ASR model to improve transcription accuracy. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/configure_connection.py b/venv/lib/python3.12/site-packages/sarvamai/requests/configure_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..062ab0f663b76e5077c0ec8de70ffb2e07e80b1a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/configure_connection.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .configure_connection_data import ConfigureConnectionDataParams + + +class ConfigureConnectionParams(typing_extensions.TypedDict): + """ + Configuration message required as the first message after establishing the WebSocket connection. + This initializes TTS parameters and can be updated at any time during the WebSocket lifecycle + by sending a new config message. When a config update is sent, any text currently in the buffer + will be automatically flushed and processed before applying the new configuration. + + **Model-Specific Notes:** + - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz. + - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature. Default sample rate: 24000 Hz. + """ + + type: typing.Literal["config"] + data: ConfigureConnectionDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/configure_connection_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/configure_connection_data.py new file mode 100644 index 0000000000000000000000000000000000000000..242f63bbf8fa8569f717a11a6274ee073071c3c0 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/configure_connection_data.py @@ -0,0 +1,122 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.configure_connection_data_model import ConfigureConnectionDataModel +from ..types.configure_connection_data_output_audio_bitrate import ConfigureConnectionDataOutputAudioBitrate +from ..types.configure_connection_data_output_audio_codec import ConfigureConnectionDataOutputAudioCodec +from ..types.configure_connection_data_speaker import ConfigureConnectionDataSpeaker +from ..types.configure_connection_data_target_language_code import ConfigureConnectionDataTargetLanguageCode + + +class ConfigureConnectionDataParams(typing_extensions.TypedDict): + model: typing_extensions.NotRequired[ConfigureConnectionDataModel] + """ + Specifies the model to use for text-to-speech conversion. + - **bulbul:v2** (default): Standard TTS model with pitch/loudness support + - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness) + """ + + target_language_code: ConfigureConnectionDataTargetLanguageCode + """ + The language of the text in BCP-47 format + """ + + speaker: ConfigureConnectionDataSpeaker + """ + The speaker voice to be used for the output audio. + + **Model Compatibility:** + - **bulbul:v2:** anushka (default), abhilash, manisha, vidya, arya, karun, hitesh + - **bulbul:v3:** aditya (default), ritu, priya, neha, rahul, pooja, rohan, simran, kavya, amit, dev, ishita, shreya, ratan, varun, manan, sumit, roopa, kabir, aayan, shubh, ashutosh, advait, amelia, sophia + + **Note:** Speaker selection must match the chosen model version. + """ + + pitch: typing_extensions.NotRequired[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. + + **Note:** NOT supported for bulbul:v3. Will be ignored if provided. + """ + + pace: typing_extensions.NotRequired[float] + """ + Controls the speed of the audio. Lower values result in slower speech, + while higher values make it faster. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v2:** 0.3 to 3.0 + - **bulbul:v3:** 0.5 to 2.0 + """ + + loudness: typing_extensions.NotRequired[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. + + **Note:** NOT supported for bulbul:v3. Will be ignored if provided. + """ + + temperature: typing_extensions.NotRequired[float] + """ + Controls the randomness of the output. Lower values make the output more + focused and deterministic, while higher values make it more random. + The suitable range is between 0.01 and 1.0. Default is 0.6. + + **Note:** Only supported for bulbul:v3. Will be ignored for bulbul:v2. + """ + + speech_sample_rate: typing_extensions.NotRequired[int] + """ + Specifies the sample rate of the output audio. Supported values are + 8000, 16000, 22050, 24000 Hz. + + **Model-specific defaults:** + - **bulbul:v2:** 22050 Hz + - **bulbul:v3:** 24000 Hz + """ + + enable_preprocessing: typing_extensions.NotRequired[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. + + **Model-specific defaults:** + - **bulbul:v2:** false (optional) + - **bulbul:v3:** Always enabled (cannot be disabled) + """ + + output_audio_codec: typing_extensions.NotRequired[ConfigureConnectionDataOutputAudioCodec] + """ + Audio codec (currently supports MP3 only, optimized for real-time playback) + """ + + output_audio_bitrate: typing_extensions.NotRequired[ConfigureConnectionDataOutputAudioBitrate] + """ + Audio bitrate (choose from 5 supported bitrate options) + """ + + dict_id: typing_extensions.NotRequired[str] + """ + The ID of a pronunciation dictionary to apply during synthesis. + When provided, matching words in the input text will be replaced + with their custom pronunciations before generating speech. + + Create and manage dictionaries via the `/text-to-speech/pronunciation-dictionary` endpoints. + + **Note:** Only supported by **bulbul:v3**. + """ + + min_buffer_size: typing_extensions.NotRequired[int] + """ + Minimum character length that triggers buffer flushing for TTS model processing + """ + + max_chunk_length: typing_extensions.NotRequired[int] + """ + Maximum length for sentence splitting (adjust based on content length) + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/create_chat_completion_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/create_chat_completion_response.py new file mode 100644 index 0000000000000000000000000000000000000000..50d23ad5e4a811ec3dd866298c29384576c1b6b9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/create_chat_completion_response.py @@ -0,0 +1,38 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .choice import ChoiceParams +from .completion_usage import CompletionUsageParams + + +class CreateChatCompletionResponseParams(typing_extensions.TypedDict): + id: str + """ + A unique identifier for the chat completion. + """ + + choices: typing.Sequence[ChoiceParams] + """ + A list of chat completion choices. Can be more than one if `n` is greater than 1. + """ + + created: int + """ + The Unix timestamp (in seconds) of when the chat completion was created. + """ + + model: str + """ + The model used for the chat completion. + """ + + object: typing.Literal["chat.completion"] + """ + The object type, which is always `chat.completion`. + """ + + service_tier: typing_extensions.NotRequired[str] + system_fingerprint: typing_extensions.NotRequired[str] + usage: typing_extensions.NotRequired[CompletionUsageParams] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/diarized_entry.py b/venv/lib/python3.12/site-packages/sarvamai/requests/diarized_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8695121c4d68d5a26bb34f23c4178b2d837b86 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/diarized_entry.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class DiarizedEntryParams(typing_extensions.TypedDict): + transcript: str + """ + transcript of the segment of that audio + """ + + start_time_seconds: float + """ + Start time of the word in seconds. + """ + + end_time_seconds: float + """ + End time of the word in seconds. + """ + + speaker_id: str + """ + Speaker ID for the word. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/diarized_transcript.py b/venv/lib/python3.12/site-packages/sarvamai/requests/diarized_transcript.py new file mode 100644 index 0000000000000000000000000000000000000000..23a134bccaffc848f6431a19604d41c5f9cb2902 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/diarized_transcript.py @@ -0,0 +1,13 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .diarized_entry import DiarizedEntryParams + + +class DiarizedTranscriptParams(typing_extensions.TypedDict): + entries: typing.Sequence[DiarizedEntryParams] + """ + List of diarized transcript entries. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_create_job_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_create_job_response.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe1416f8a37706793caeefe07e7f310607bd082 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_create_job_response.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.doc_digitization_job_state import DocDigitizationJobState +from ..types.storage_container_type import StorageContainerType +from .doc_digitization_job_parameters import DocDigitizationJobParametersParams + + +class DocDigitizationCreateJobResponseParams(typing_extensions.TypedDict): + job_id: str + """ + Unique job identifier (UUID) + """ + + storage_container_type: StorageContainerType + """ + Storage Container Type + """ + + job_parameters: DocDigitizationJobParametersParams + """ + Job configuration parameters + """ + + job_state: DocDigitizationJobState diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_download_files_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_download_files_response.py new file mode 100644 index 0000000000000000000000000000000000000000..db9b9b2b93fca9e62ebf225e97d009ecbb706522 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_download_files_response.py @@ -0,0 +1,37 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.doc_digitization_job_state import DocDigitizationJobState +from ..types.storage_container_type import StorageContainerType +from .file_signed_url_details import FileSignedUrlDetailsParams + + +class DocDigitizationDownloadFilesResponseParams(typing_extensions.TypedDict): + """ + Response for download-files endpoint. + """ + + job_id: str + """ + Job identifier (UUID) + """ + + job_state: DocDigitizationJobState + """ + Current job state + """ + + storage_container_type: StorageContainerType + """ + Storage backend type + """ + + download_urls: typing.Dict[str, FileSignedUrlDetailsParams] + """ + Map of filename to presigned download URL details + """ + + error_code: typing_extensions.NotRequired[str] + error_message: typing_extensions.NotRequired[str] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_error_details.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_error_details.py new file mode 100644 index 0000000000000000000000000000000000000000..a7938d2111f73d77109f13233e820b11a5bae665 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_error_details.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.doc_digitization_error_code import DocDigitizationErrorCode + + +class DocDigitizationErrorDetailsParams(typing_extensions.TypedDict): + message: str + """ + Message describing the error + """ + + code: DocDigitizationErrorCode + """ + Error code for the specific error that has occurred. + """ + + request_id: typing_extensions.NotRequired[str] + """ + Unique identifier for the request. Format: date_UUID4 + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_error_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_error_message.py new file mode 100644 index 0000000000000000000000000000000000000000..82606028336273c4fa4be5607520641bfe1720a5 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_error_message.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from .doc_digitization_error_details import DocDigitizationErrorDetailsParams + + +class DocDigitizationErrorMessageParams(typing_extensions.TypedDict): + error: DocDigitizationErrorDetailsParams + """ + Error details + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_detail.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_detail.py new file mode 100644 index 0000000000000000000000000000000000000000..33c0ca089fd806ce76d08651f9b2cf08b7e8f255 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_detail.py @@ -0,0 +1,64 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.doc_digitization_job_detail_state import DocDigitizationJobDetailState +from .doc_digitization_page_error import DocDigitizationPageErrorParams +from .task_file_details import TaskFileDetailsParams + + +class DocDigitizationJobDetailParams(typing_extensions.TypedDict): + """ + Processing details for a single input file with page-level metrics. + """ + + inputs: typing.Sequence[TaskFileDetailsParams] + """ + Input file(s) for this task + """ + + outputs: typing.Sequence[TaskFileDetailsParams] + """ + Output file(s) produced + """ + + state: DocDigitizationJobDetailState + """ + Processing state for this file + """ + + total_pages: typing_extensions.NotRequired[int] + """ + Total pages/images in the input file + """ + + pages_processed: typing_extensions.NotRequired[int] + """ + Number of pages processed so far + """ + + pages_succeeded: typing_extensions.NotRequired[int] + """ + Number of pages successfully processed + """ + + pages_failed: typing_extensions.NotRequired[int] + """ + Number of pages that failed processing + """ + + error_message: typing_extensions.NotRequired[str] + """ + Error message if processing failed + """ + + error_code: typing_extensions.NotRequired[str] + """ + Standardized error code if failed + """ + + page_errors: typing_extensions.NotRequired[typing.Sequence[DocDigitizationPageErrorParams]] + """ + Detailed errors for each failed page + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..ab15da747942e52666dacdd9f9a894b70440897c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_parameters.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.doc_digitization_output_format import DocDigitizationOutputFormat +from ..types.doc_digitization_supported_language import DocDigitizationSupportedLanguage + + +class DocDigitizationJobParametersParams(typing_extensions.TypedDict): + """ + Configuration parameters for Document Intelligence job. Specify the document language and desired output format. + """ + + language: typing_extensions.NotRequired[DocDigitizationSupportedLanguage] + """ + Primary language of the document in BCP-47 format. This helps optimize text extraction accuracy for the specified language. + """ + + output_format: typing_extensions.NotRequired[DocDigitizationOutputFormat] + """ + Output format for the extracted content (delivered as a ZIP file). Use 'html' for structured HTML, 'md' for Markdown, or 'json' for structured JSON data. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_status_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_status_response.py new file mode 100644 index 0000000000000000000000000000000000000000..fa9f9c54e010df5f7f03c316746cab956403042f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_job_status_response.py @@ -0,0 +1,65 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt +import typing + +import typing_extensions +from ..types.doc_digitization_job_state import DocDigitizationJobState +from ..types.storage_container_type import StorageContainerType +from .doc_digitization_job_detail import DocDigitizationJobDetailParams + + +class DocDigitizationJobStatusResponseParams(typing_extensions.TypedDict): + """ + Response model for job status endpoint. + """ + + job_id: str + """ + Job identifier (UUID) + """ + + job_state: DocDigitizationJobState + """ + Current job state + """ + + created_at: dt.datetime + """ + Job creation timestamp (ISO 8601) + """ + + updated_at: dt.datetime + """ + Last update timestamp (ISO 8601) + """ + + storage_container_type: StorageContainerType + """ + Storage backend type + """ + + total_files: typing_extensions.NotRequired[int] + """ + Total input files (always 1) + """ + + successful_files_count: typing_extensions.NotRequired[int] + """ + Files that completed successfully + """ + + failed_files_count: typing_extensions.NotRequired[int] + """ + Files that failed + """ + + error_message: typing_extensions.NotRequired[str] + """ + Job-level error message + """ + + job_details: typing_extensions.NotRequired[typing.Sequence[DocDigitizationJobDetailParams]] + """ + Per-file processing details with page metrics + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_page_error.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_page_error.py new file mode 100644 index 0000000000000000000000000000000000000000..a63e1857b2dd0d7b953de9612c2ed631e1e83eef --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_page_error.py @@ -0,0 +1,24 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class DocDigitizationPageErrorParams(typing_extensions.TypedDict): + """ + Error details for a specific page. + """ + + page_number: int + """ + Page number that failed + """ + + error_code: str + """ + Standardized error code + """ + + error_message: str + """ + Human-readable error description + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_upload_files_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_upload_files_response.py new file mode 100644 index 0000000000000000000000000000000000000000..89b3f487d8599a90475c304eb532f43402d22fe8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_upload_files_response.py @@ -0,0 +1,34 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.doc_digitization_job_state import DocDigitizationJobState +from ..types.storage_container_type import StorageContainerType +from .file_signed_url_details import FileSignedUrlDetailsParams + + +class DocDigitizationUploadFilesResponseParams(typing_extensions.TypedDict): + """ + Response with presigned upload URLs + """ + + job_id: str + """ + Job identifier + """ + + job_state: DocDigitizationJobState + """ + Current job state + """ + + upload_urls: typing.Dict[str, FileSignedUrlDetailsParams] + """ + Map of filename to presigned upload URL details + """ + + storage_container_type: StorageContainerType + """ + Storage backend type + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_webhook_callback.py b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_webhook_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..9bcaaead0ab30e8d466723bc1b8af502d8bf4af6 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/doc_digitization_webhook_callback.py @@ -0,0 +1,19 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class DocDigitizationWebhookCallbackParams(typing_extensions.TypedDict): + """ + Webhook configuration for job completion notification + """ + + url: str + """ + HTTPS webhook URL to call upon job completion (HTTP not allowed) + """ + + auth_token: typing_extensions.NotRequired[str] + """ + Authorization token sent as X-SARVAM-JOB-CALLBACK-TOKEN header + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/error_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/error_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e01f878ecc9c48c667d28d890caee68da8c51019 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/error_data.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class ErrorDataParams(typing_extensions.TypedDict): + error: str + """ + Error message + """ + + code: str + """ + Error code + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/error_details.py b/venv/lib/python3.12/site-packages/sarvamai/requests/error_details.py new file mode 100644 index 0000000000000000000000000000000000000000..880f9b384c59d518d4f03e92add29755fb17e40d --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/error_details.py @@ -0,0 +1,17 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.error_code import ErrorCode + + +class ErrorDetailsParams(typing_extensions.TypedDict): + request_id: typing_extensions.NotRequired[str] + message: str + """ + Message describing the error + """ + + code: ErrorCode + """ + Error code for the specific error that has occured. Refer to the error code documentation for more details. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/error_details2.py b/venv/lib/python3.12/site-packages/sarvamai/requests/error_details2.py new file mode 100644 index 0000000000000000000000000000000000000000..ff396cc082a5fd42316556f0485cffd2cca5e61e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/error_details2.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.error_code2 import ErrorCode2 + + +class ErrorDetails2Params(typing_extensions.TypedDict): + message: str + """ + Message describing the error + """ + + code: ErrorCode2 + """ + Error code for the specific error that has occured. Refer to the error code documentation for more details. + """ + + request_id: typing_extensions.NotRequired[str] + """ + Unique identifier for the request. Format: date_UUID4 + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/error_message.py b/venv/lib/python3.12/site-packages/sarvamai/requests/error_message.py new file mode 100644 index 0000000000000000000000000000000000000000..60613e70f9b4cf794c9beaf24f690ec50349bc67 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/error_message.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from .error_details import ErrorDetailsParams + + +class ErrorMessageParams(typing_extensions.TypedDict): + error: ErrorDetailsParams + """ + Error details + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/error_message2.py b/venv/lib/python3.12/site-packages/sarvamai/requests/error_message2.py new file mode 100644 index 0000000000000000000000000000000000000000..0b75f2db4708b8618e0faae6d70268397c3cee14 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/error_message2.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from .error_details2 import ErrorDetails2Params + + +class ErrorMessage2Params(typing_extensions.TypedDict): + error: ErrorDetails2Params + """ + Error details + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/error_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/error_response.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa07422dc22ea44b6a361c092d4ee61f9e7d626 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/error_response.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .error_response_data import ErrorResponseDataParams + + +class ErrorResponseParams(typing_extensions.TypedDict): + type: typing.Literal["error"] + data: ErrorResponseDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/error_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/error_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..079f9e54edb8a51ca3fa2dec5638a8bd0e7ab0a9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/error_response_data.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class ErrorResponseDataParams(typing_extensions.TypedDict): + message: str + code: typing_extensions.NotRequired[int] + """ + Optional error code for programmatic error handling + """ + + details: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] + """ + Additional error details and context information + """ + + request_id: typing_extensions.NotRequired[str] + """ + Unique identifier for the request + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/event_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/event_response.py new file mode 100644 index 0000000000000000000000000000000000000000..43f8c0cf01d6da3447a7e1337c2f06ae1edd9db9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/event_response.py @@ -0,0 +1,19 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .event_response_data import EventResponseDataParams + + +class EventResponseParams(typing_extensions.TypedDict): + """ + Event notification message sent when specific events occur during TTS processing + """ + + type: typing.Literal["event"] + """ + Message type identifier for events + """ + + data: EventResponseDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/event_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/event_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ed05cab2f6a1f0211520f7e26d0ce4d0cdba9e64 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/event_response_data.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt +import typing + +import typing_extensions + + +class EventResponseDataParams(typing_extensions.TypedDict): + event_type: typing.Literal["final"] + """ + Type of event that occurred + """ + + message: typing_extensions.NotRequired[str] + """ + Human-readable description of the event + """ + + timestamp: typing_extensions.NotRequired[dt.datetime] + """ + ISO 8601 timestamp when the event occurred + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/events_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/events_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b16b6fcd522cf1156d4ef0665dbc888d3cac14 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/events_data.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt + +import typing_extensions +from ..types.events_data_signal_type import EventsDataSignalType + + +class EventsDataParams(typing_extensions.TypedDict): + """ + VAD events are sent when vad_signals=true. Fields may vary by event type. + """ + + event_type: typing_extensions.NotRequired[str] + """ + Type of event + """ + + timestamp: typing_extensions.NotRequired[dt.datetime] + """ + Event timestamp + """ + + signal_type: typing_extensions.NotRequired[EventsDataSignalType] + """ + VAD signal type + """ + + occured_at: typing_extensions.NotRequired[float] + """ + Epoch timestamp when the event occurred + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/file_signed_url_details.py b/venv/lib/python3.12/site-packages/sarvamai/requests/file_signed_url_details.py new file mode 100644 index 0000000000000000000000000000000000000000..16d177583ee642ac35a3fa33600c19884f9b9ea5 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/file_signed_url_details.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class FileSignedUrlDetailsParams(typing_extensions.TypedDict): + file_url: str + file_metadata: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/files_download_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/files_download_response.py new file mode 100644 index 0000000000000000000000000000000000000000..81e1908fad35d599252411dabc79ae2a96e1f334 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/files_download_response.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.job_state import JobState +from ..types.storage_container_type import StorageContainerType +from .file_signed_url_details import FileSignedUrlDetailsParams + + +class FilesDownloadResponseParams(typing_extensions.TypedDict): + job_id: str + job_state: JobState + download_urls: typing.Dict[str, FileSignedUrlDetailsParams] + storage_container_type: StorageContainerType diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/files_request.py b/venv/lib/python3.12/site-packages/sarvamai/requests/files_request.py new file mode 100644 index 0000000000000000000000000000000000000000..46739dc299ae272bed9cd718343346fc16a0ccc1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/files_request.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class FilesRequestParams(typing_extensions.TypedDict): + job_id: str + files: typing.Sequence[str] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/files_upload_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/files_upload_response.py new file mode 100644 index 0000000000000000000000000000000000000000..eefbf29771070c08bed1d777cba1903f6d3ffb3e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/files_upload_response.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.job_state import JobState +from ..types.storage_container_type import StorageContainerType +from .file_signed_url_details import FileSignedUrlDetailsParams + + +class FilesUploadResponseParams(typing_extensions.TypedDict): + job_id: str + job_state: JobState + upload_urls: typing.Dict[str, FileSignedUrlDetailsParams] + storage_container_type: StorageContainerType diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/flush_signal.py b/venv/lib/python3.12/site-packages/sarvamai/requests/flush_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..f1982df77b01596714187ae078028cbcc9ab0df2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/flush_signal.py @@ -0,0 +1,14 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class FlushSignalParams(typing_extensions.TypedDict): + """ + Forces the text buffer to process immediately, regardless of the min_buffer_size threshold. + Use this when you need to process remaining text that hasn't reached the minimum buffer size. + """ + + type: typing.Literal["flush"] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/function_call.py b/venv/lib/python3.12/site-packages/sarvamai/requests/function_call.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0eaf82e76fdf126880e1814924e6c99ff09121 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/function_call.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class FunctionCallParams(typing_extensions.TypedDict): + name: str + """ + The name of the function to call. + """ + + arguments: str + """ + The arguments to call the function with, as a JSON string. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/function_definition.py b/venv/lib/python3.12/site-packages/sarvamai/requests/function_definition.py new file mode 100644 index 0000000000000000000000000000000000000000..b42f57524467bc2d889c555fc0e0013792f7ec7c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/function_definition.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class FunctionDefinitionParams(typing_extensions.TypedDict): + name: str + """ + The name of the function to be called. + """ + + description: typing_extensions.NotRequired[str] + """ + A description of what the function does. + """ + + parameters: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] + """ + The parameters the function accepts, described as a JSON Schema object. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/job_status_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/job_status_response.py new file mode 100644 index 0000000000000000000000000000000000000000..55aef42a32727aa133d2b128f101e02b47d4b258 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/job_status_response.py @@ -0,0 +1,60 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.job_state import JobState +from ..types.storage_container_type import StorageContainerType +from .task_detail import TaskDetailParams + + +class JobStatusResponseParams(typing_extensions.TypedDict): + job_state: JobState + """ + Job State + """ + + created_at: str + """ + Created At + """ + + updated_at: str + """ + Updated At + """ + + job_id: str + """ + Job Id + """ + + total_files: typing_extensions.NotRequired[int] + """ + Total Files + """ + + successful_files_count: typing_extensions.NotRequired[int] + """ + Success Count + """ + + failed_files_count: typing_extensions.NotRequired[int] + """ + Failed Count + """ + + storage_container_type: StorageContainerType + """ + Storage Container Type + """ + + error_message: typing_extensions.NotRequired[str] + """ + Error Message + """ + + job_details: typing_extensions.NotRequired[typing.Sequence[TaskDetailParams]] + """ + Job details at file level. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/language_identification_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/language_identification_response.py new file mode 100644 index 0000000000000000000000000000000000000000..82578a949b50e8dc7049c1588d4e2711093cae01 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/language_identification_response.py @@ -0,0 +1,41 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class LanguageIdentificationResponseParams(typing_extensions.TypedDict): + request_id: typing_extensions.NotRequired[str] + language_code: typing_extensions.NotRequired[str] + """ + The detected language code of the input text. + + Available languages: + - **`en-IN`**: English + - **`hi-IN`**: Hindi + - **`bn-IN`**: Bengali + - **`gu-IN`**: Gujarati + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + """ + + script_code: typing_extensions.NotRequired[str] + """ + The detected script code of the input text. + + Available scripts: + - **`Latn`**: Latin (Romanized script) + - **`Deva`**: Devanagari (Hindi, Marathi) + - **`Beng`**: Bengali + - **`Gujr`**: Gujarati + - **`Knda`**: Kannada + - **`Mlym`**: Malayalam + - **`Orya`**: Odia + - **`Guru`**: Gurmukhi + - **`Taml`**: Tamil + - **`Telu`**: Telugu + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/ping_signal.py b/venv/lib/python3.12/site-packages/sarvamai/requests/ping_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..54e25d71629b2bc229d04dcc65b8564fdeeb6896 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/ping_signal.py @@ -0,0 +1,14 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class PingSignalParams(typing_extensions.TypedDict): + """ + Send ping signal to keep the WebSocket connection alive. The connection automatically + closes after one minute of inactivity. + """ + + type: typing.Literal["ping"] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_data.py new file mode 100644 index 0000000000000000000000000000000000000000..99b3396ceec8b5dc1c90364a642f6686d0d06e5b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_data.py @@ -0,0 +1,16 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class PronunciationDictionaryDataParams(typing_extensions.TypedDict): + """ + The full pronunciation data for a dictionary. + """ + + pronunciations: typing.Dict[str, typing.Dict[str, str]] + """ + Pronunciation mappings organized by language code (e.g. `hi-IN`, `en-IN`). Each language maps words to their custom pronunciations. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_delete_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_delete_response.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5b653564f8b4985a2328bafe57a73afcf1b5fe --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_delete_response.py @@ -0,0 +1,19 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class PronunciationDictionaryDeleteResponseParams(typing_extensions.TypedDict): + """ + Response returned after deleting a pronunciation dictionary. + """ + + success: bool + """ + Whether the deletion was successful. + """ + + message: str + """ + Human-readable status message (e.g. "Dictionary 'p_5cb7faa6' deleted successfully"). + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_get_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_get_response.py new file mode 100644 index 0000000000000000000000000000000000000000..cd6350530f82969719d6d3f881027c7fd6d87648 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_get_response.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class PronunciationDictionaryGetResponseParams(typing_extensions.TypedDict): + """ + Response containing all pronunciation dictionary IDs for the authenticated user. + """ + + dictionary_count: int + """ + Total number of pronunciation dictionaries owned by the user. + """ + + dictionaries: typing.Sequence[str] + """ + List of dictionary IDs. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_response.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e70818de89ffac9dd162a35ed78907b1679138 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_response.py @@ -0,0 +1,14 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class PronunciationDictionaryResponseParams(typing_extensions.TypedDict): + """ + Response returned after successfully creating a pronunciation dictionary. + """ + + dictionary_id: str + """ + Unique identifier for the created dictionary (e.g. `p_5cb7faa6`). Use this as the `dict_id` parameter in text-to-speech requests. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_update_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_update_response.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb6ea2cf5a76a7eca76103f928e692051a953cb --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/pronunciation_dictionary_update_response.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class PronunciationDictionaryUpdateResponseParams(typing_extensions.TypedDict): + """ + Response returned after successfully updating a pronunciation dictionary. Includes the full updated pronunciation data for verification. + """ + + dictionary_id: str + """ + Unique identifier of the updated dictionary. + """ + + updated_pronunciations: typing.Dict[str, typing.Dict[str, str]] + """ + The new pronunciation data after the update, organized as `{language_code: {word: pronunciation}}`. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/send_text.py b/venv/lib/python3.12/site-packages/sarvamai/requests/send_text.py new file mode 100644 index 0000000000000000000000000000000000000000..575404b0385f323a67633d5f6df027056ccf4136 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/send_text.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .send_text_data import SendTextDataParams + + +class SendTextParams(typing_extensions.TypedDict): + type: typing.Literal["text"] + data: SendTextDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/send_text_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/send_text_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5c34b57e7f76813ec3ae5a72967bef607145cc3d --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/send_text_data.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class SendTextDataParams(typing_extensions.TypedDict): + text: str diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf42fbd5acb8ef5e78f8c538f045c6918056639 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_job_parameters.py @@ -0,0 +1,93 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.input_audio_codec import InputAudioCodec +from ..types.mode import Mode +from ..types.speech_to_text_language import SpeechToTextLanguage +from ..types.speech_to_text_model import SpeechToTextModel + + +class SpeechToTextJobParametersParams(typing_extensions.TypedDict): + language_code: typing_extensions.NotRequired[SpeechToTextLanguage] + """ + Specifies the language of the input audio in BCP-47 format. + + **Available Options:** + - `unknown` (default): Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + - `gu-IN`: Gujarati + + **Additional Options (saaras:v3 only):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + """ + + model: typing_extensions.NotRequired[SpeechToTextModel] + """ + Model to be used for speech to text. + + - **saarika:v2.5** (default): Transcribes audio in the spoken language. + + - **saaras:v3**: State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + """ + + mode: typing_extensions.NotRequired[Mode] + """ + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + """ + + with_timestamps: typing_extensions.NotRequired[bool] + """ + Whether to include timestamps in the response + """ + + with_diarization: typing_extensions.NotRequired[bool] + """ + Enables speaker diarization, which identifies and separates different speakers in the audio. In beta mode + """ + + num_speakers: typing_extensions.NotRequired[int] + """ + Number of speakers to be detected in the audio. This is used when with_diarization is true. + """ + + input_audio_codec: typing_extensions.NotRequired[InputAudioCodec] + """ + Audio codec/format of uploaded files. The API automatically detects most formats; for PCM files (pcm_s16le, pcm_l16, pcm_raw), you must specify this parameter. PCM files are supported only at 16kHz sample rate. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_response.py new file mode 100644 index 0000000000000000000000000000000000000000..8c951bc67dd7f3262218ecf163654326a402cc89 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_response.py @@ -0,0 +1,42 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from .diarized_transcript import DiarizedTranscriptParams +from .timestamps_model import TimestampsModelParams + + +class SpeechToTextResponseParams(typing_extensions.TypedDict): + request_id: typing_extensions.NotRequired[str] + transcript: str + """ + The transcribed text from the provided audio file. + """ + + timestamps: typing_extensions.NotRequired[TimestampsModelParams] + """ + Contains timestamps for the transcribed text. This field is included only if with_timestamps is set to true + """ + + diarized_transcript: typing_extensions.NotRequired[DiarizedTranscriptParams] + """ + Diarized transcript of the provided speech + """ + + language_code: typing_extensions.NotRequired[str] + """ + This will return the BCP-47 code of language spoken in the input. If multiple languages are detected, this will return language code of most predominant spoken language. If no language is detected, this will be null + """ + + language_probability: typing_extensions.NotRequired[float] + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..10af83808803163d2eea110d97d0ea39f05b69fe --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_response_data.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .error_data import ErrorDataParams +from .events_data import EventsDataParams +from .speech_to_text_transcription_data import SpeechToTextTranscriptionDataParams + +SpeechToTextResponseDataParams = typing.Union[SpeechToTextTranscriptionDataParams, ErrorDataParams, EventsDataParams] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_streaming_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_streaming_response.py new file mode 100644 index 0000000000000000000000000000000000000000..e81a2daccd652bab0c38dc1724d0f9d46ec02fba --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_streaming_response.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.response_type import ResponseType +from .speech_to_text_response_data import SpeechToTextResponseDataParams + + +class SpeechToTextStreamingResponseParams(typing_extensions.TypedDict): + type: ResponseType + data: SpeechToTextResponseDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_transcription_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_transcription_data.py new file mode 100644 index 0000000000000000000000000000000000000000..7fcdcde8bb13f2838c834f3788262c2453aa01e7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_transcription_data.py @@ -0,0 +1,49 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from .transcription_metrics import TranscriptionMetricsParams + + +class SpeechToTextTranscriptionDataParams(typing_extensions.TypedDict): + request_id: str + """ + Unique identifier for the request + """ + + transcript: str + """ + Transcript of the provided speech in original language + """ + + timestamps: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] + """ + Timestamp information (if available) + """ + + diarized_transcript: typing_extensions.NotRequired[typing.Dict[str, typing.Any]] + """ + Diarized transcript of the provided speech + """ + + language_code: typing_extensions.NotRequired[str] + """ + BCP-47 code of detected language + """ + + language_probability: typing_extensions.NotRequired[float] + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ + + metrics: TranscriptionMetricsParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c1a538ee2ceec74d3275043cc752ffca2752a2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_job_parameters.py @@ -0,0 +1,37 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.input_audio_codec import InputAudioCodec +from ..types.speech_to_text_translate_model import SpeechToTextTranslateModel + + +class SpeechToTextTranslateJobParametersParams(typing_extensions.TypedDict): + prompt: typing_extensions.NotRequired[str] + """ + Prompt to assist the transcription + """ + + model: typing_extensions.NotRequired[SpeechToTextTranslateModel] + """ + Model to be used for speech to text translation. + + - **saaras:v2.5** (default): Translation model that translates audio from any spoken Indic language to English. + - Example: Hindi audio → English text output + """ + + with_diarization: typing_extensions.NotRequired[bool] + """ + Enables speaker diarization, which identifies and separates different speakers in the audio. + When set to true, the API will provide speaker-specific segments in the response. + Note: This parameter is currently in Beta mode. + """ + + num_speakers: typing_extensions.NotRequired[int] + """ + Number of speakers to be detected in the audio. This is used when with_diarization is set to true. + """ + + input_audio_codec: typing_extensions.NotRequired[InputAudioCodec] + """ + Audio codec/format of uploaded files. The API automatically detects most formats; for PCM files (pcm_s16le, pcm_l16, pcm_raw), you must specify this parameter. PCM files are supported only at 16kHz sample rate. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_response.py new file mode 100644 index 0000000000000000000000000000000000000000..222e5356a6b27d5277cacd88cbb9e40bb5590dd8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_response.py @@ -0,0 +1,37 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.speech_to_text_translate_language import SpeechToTextTranslateLanguage +from .diarized_transcript import DiarizedTranscriptParams + + +class SpeechToTextTranslateResponseParams(typing_extensions.TypedDict): + request_id: typing_extensions.NotRequired[str] + transcript: str + """ + Transcript of the provided speech + """ + + language_code: typing_extensions.NotRequired[SpeechToTextTranslateLanguage] + """ + This will return the BCP-47 code of language spoken in the input. If multiple languages are detected, this will return language code of most predominant spoken language. If no language is detected, this will be null + """ + + diarized_transcript: typing_extensions.NotRequired[DiarizedTranscriptParams] + """ + Diarized transcript of the provided speech + """ + + language_probability: typing_extensions.NotRequired[float] + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..62b50367b61835a8ea89e3a3db00801bbf37ba6a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_response_data.py @@ -0,0 +1,11 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .error_data import ErrorDataParams +from .events_data import EventsDataParams +from .speech_to_text_translate_transcription_data import SpeechToTextTranslateTranscriptionDataParams + +SpeechToTextTranslateResponseDataParams = typing.Union[ + SpeechToTextTranslateTranscriptionDataParams, ErrorDataParams, EventsDataParams +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_streaming_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_streaming_response.py new file mode 100644 index 0000000000000000000000000000000000000000..9716743844c2b88bc8188bdbfdcfecc5438ea83d --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_streaming_response.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from ..types.response_type import ResponseType +from .speech_to_text_translate_response_data import SpeechToTextTranslateResponseDataParams + + +class SpeechToTextTranslateStreamingResponseParams(typing_extensions.TypedDict): + type: ResponseType + data: SpeechToTextTranslateResponseDataParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_transcription_data.py b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_transcription_data.py new file mode 100644 index 0000000000000000000000000000000000000000..73257c5b3094d850713bc01c811769142787c7d2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/speech_to_text_translate_transcription_data.py @@ -0,0 +1,37 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions +from .transcription_metrics import TranscriptionMetricsParams + + +class SpeechToTextTranslateTranscriptionDataParams(typing_extensions.TypedDict): + request_id: str + """ + Unique identifier for the request + """ + + transcript: str + """ + English translation of the provided speech + """ + + language_code: typing_extensions.NotRequired[str] + """ + BCP-47 code of detected source language (null when language detection is in progress) + """ + + language_probability: typing_extensions.NotRequired[float] + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ + + metrics: TranscriptionMetricsParams diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/stop_configuration.py b/venv/lib/python3.12/site-packages/sarvamai/requests/stop_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..5e58e8a16b7933871da21843bfcf895f95885502 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/stop_configuration.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +StopConfigurationParams = typing.Union[str, typing.Sequence[str]] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/stt_flush_signal.py b/venv/lib/python3.12/site-packages/sarvamai/requests/stt_flush_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3398a8a60c2aa86c9670239ea95309cdd225d7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/stt_flush_signal.py @@ -0,0 +1,16 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class SttFlushSignalParams(typing_extensions.TypedDict): + """ + Signal to flush the audio buffer and force finalize partial transcriptions/translations + """ + + type: typing.Literal["flush"] + """ + Type identifier for flush signal + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/task_detail.py b/venv/lib/python3.12/site-packages/sarvamai/requests/task_detail.py new file mode 100644 index 0000000000000000000000000000000000000000..eb932c1fa43e293fbcd798f27a2b69c3efec2cca --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/task_detail.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions +from ..types.task_state import TaskState +from .task_file_details import TaskFileDetailsParams + + +class TaskDetailParams(typing_extensions.TypedDict): + inputs: typing_extensions.NotRequired[typing.Sequence[TaskFileDetailsParams]] + outputs: typing_extensions.NotRequired[typing.Sequence[TaskFileDetailsParams]] + state: typing_extensions.NotRequired[TaskState] + error_message: typing_extensions.NotRequired[str] + exception_name: typing_extensions.NotRequired[str] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/task_file_details.py b/venv/lib/python3.12/site-packages/sarvamai/requests/task_file_details.py new file mode 100644 index 0000000000000000000000000000000000000000..a39571289587a4d277387de82cd11dc70dd47f90 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/task_file_details.py @@ -0,0 +1,8 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class TaskFileDetailsParams(typing_extensions.TypedDict): + file_name: str + file_id: str diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/text_to_speech_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/text_to_speech_response.py new file mode 100644 index 0000000000000000000000000000000000000000..b018508d73d6e4990c300d751de4c65d2a096e52 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/text_to_speech_response.py @@ -0,0 +1,13 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class TextToSpeechResponseParams(typing_extensions.TypedDict): + request_id: typing_extensions.NotRequired[str] + audios: typing.Sequence[str] + """ + The output audio files in WAV format, encoded as base64 strings. Each string corresponds to one of the input texts. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/timestamps_model.py b/venv/lib/python3.12/site-packages/sarvamai/requests/timestamps_model.py new file mode 100644 index 0000000000000000000000000000000000000000..41d6eac89334b23fead3e88639943e19ab99003c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/timestamps_model.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import typing_extensions + + +class TimestampsModelParams(typing_extensions.TypedDict): + words: typing.Sequence[str] + """ + List of words in the transcript. + """ + + start_time_seconds: typing.Sequence[float] + """ + List of start times of words in seconds. + """ + + end_time_seconds: typing.Sequence[float] + """ + List of end times of words in seconds. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/tool_choice_option.py b/venv/lib/python3.12/site-packages/sarvamai/requests/tool_choice_option.py new file mode 100644 index 0000000000000000000000000000000000000000..de77c51185ff409ff01dba4424b73390750fa238 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/tool_choice_option.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .chat_completion_named_tool_choice import ChatCompletionNamedToolChoiceParams + +ToolChoiceOptionParams = typing.Union[ + typing.Literal["none"], typing.Literal["auto"], typing.Literal["required"], ChatCompletionNamedToolChoiceParams +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/transcription_metrics.py b/venv/lib/python3.12/site-packages/sarvamai/requests/transcription_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..2250d1c06ef73884c917e67eb7bb5008eedf5250 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/transcription_metrics.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class TranscriptionMetricsParams(typing_extensions.TypedDict): + audio_duration: float + """ + Duration of processed audio in seconds + """ + + processing_latency: float + """ + Processing latency in seconds + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/translation_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/translation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..532839e96ce67f0df88ba58b19acff10464e78e8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/translation_response.py @@ -0,0 +1,16 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class TranslationResponseParams(typing_extensions.TypedDict): + request_id: typing_extensions.NotRequired[str] + translated_text: str + """ + Translated text result in the requested target language. + """ + + source_language_code: str + """ + Detected or provided source language of the input text. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/requests/transliteration_response.py b/venv/lib/python3.12/site-packages/sarvamai/requests/transliteration_response.py new file mode 100644 index 0000000000000000000000000000000000000000..6c06c62c732acf19a9362debebe48a280533e270 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/requests/transliteration_response.py @@ -0,0 +1,16 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing_extensions + + +class TransliterationResponseParams(typing_extensions.TypedDict): + request_id: typing_extensions.NotRequired[str] + transliterated_text: str + """ + Transliterated text result in the requested target language. + """ + + source_language_code: str + """ + Detected or provided source language of the input text. + """ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aafbb8521de7c15095cef47d56a3b537ab6d5833 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6d5dce5de7f7cfd79f4ae6fcecef1e7c5c4cf05 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5e23910199a78164c7a6e260bcb804e26abc977 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/client.py new file mode 100644 index 0000000000000000000000000000000000000000..1cdc2be5157633b7cc78f2ff847c3e47245656fb --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/client.py @@ -0,0 +1,432 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .. import core +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..types.input_audio_codec import InputAudioCodec +from ..types.mode import Mode +from ..types.speech_to_text_language import SpeechToTextLanguage +from ..types.speech_to_text_model import SpeechToTextModel +from ..types.speech_to_text_response import SpeechToTextResponse +from ..types.speech_to_text_translate_model import SpeechToTextTranslateModel +from ..types.speech_to_text_translate_response import SpeechToTextTranslateResponse +from .raw_client import AsyncRawSpeechToTextClient, RawSpeechToTextClient + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class SpeechToTextClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawSpeechToTextClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawSpeechToTextClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawSpeechToTextClient + """ + return self._raw_client + + def transcribe( + self, + *, + file: core.File, + model: typing.Optional[SpeechToTextModel] = OMIT, + mode: typing.Optional[Mode] = OMIT, + language_code: typing.Optional[SpeechToTextLanguage] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> SpeechToTextResponse: + """ + ## Speech to Text API + + This API transcribes speech to text in multiple Indian languages and English. Supports transcription for interactive applications. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files, [Follow This Documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + model : typing.Optional[SpeechToTextModel] + Specifies the model to use for speech-to-text conversion. + + - **saarika:v2.5** (default): Transcribes audio in the spoken language. + + - **saaras:v3**: State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + mode : typing.Optional[Mode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + language_code : typing.Optional[SpeechToTextLanguage] + Specifies the language of the input audio in BCP-47 format. + + **Note:** This parameter is optional for `saarika:v2.5` model. + + **Available Options:** + - `unknown`: Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + - `gu-IN`: Gujarati + + **Additional Options (saaras:v3 only):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + input_audio_codec : typing.Optional[InputAudioCodec] + Input Audio codec/format of the input file. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text.transcribe() + """ + _response = self._raw_client.transcribe( + file=file, + model=model, + mode=mode, + language_code=language_code, + input_audio_codec=input_audio_codec, + request_options=request_options, + ) + return _response.data + + def translate( + self, + *, + file: core.File, + prompt: typing.Optional[str] = OMIT, + model: typing.Optional[SpeechToTextTranslateModel] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> SpeechToTextTranslateResponse: + """ + ## Speech to Text Translation API + + This API automatically detects the input language, transcribes the speech, and translates the text to English. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files [Follow this documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + prompt : typing.Optional[str] + Conversation context can be passed as a prompt to boost model accuracy. However, the current system is at an experimentation stage and doesn't match the prompt performance of large language models. + + model : typing.Optional[SpeechToTextTranslateModel] + Model to be used for speech to text translation. + + - **saaras:v2.5** (default): Translation model that translates audio from any spoken Indic language to English. + - Example: Hindi audio → English text output + + input_audio_codec : typing.Optional[InputAudioCodec] + Audio codec/format of the input file. Our API automatically detects all codec formats, but for PCM files specifically (pcm_s16le, pcm_l16, pcm_raw), you must pass this parameter. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextTranslateResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text.translate() + """ + _response = self._raw_client.translate( + file=file, prompt=prompt, model=model, input_audio_codec=input_audio_codec, request_options=request_options + ) + return _response.data + + +class AsyncSpeechToTextClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawSpeechToTextClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawSpeechToTextClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawSpeechToTextClient + """ + return self._raw_client + + async def transcribe( + self, + *, + file: core.File, + model: typing.Optional[SpeechToTextModel] = OMIT, + mode: typing.Optional[Mode] = OMIT, + language_code: typing.Optional[SpeechToTextLanguage] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> SpeechToTextResponse: + """ + ## Speech to Text API + + This API transcribes speech to text in multiple Indian languages and English. Supports transcription for interactive applications. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files, [Follow This Documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + model : typing.Optional[SpeechToTextModel] + Specifies the model to use for speech-to-text conversion. + + - **saarika:v2.5** (default): Transcribes audio in the spoken language. + + - **saaras:v3**: State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + mode : typing.Optional[Mode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + language_code : typing.Optional[SpeechToTextLanguage] + Specifies the language of the input audio in BCP-47 format. + + **Note:** This parameter is optional for `saarika:v2.5` model. + + **Available Options:** + - `unknown`: Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + - `gu-IN`: Gujarati + + **Additional Options (saaras:v3 only):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + input_audio_codec : typing.Optional[InputAudioCodec] + Input Audio codec/format of the input file. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text.transcribe() + + + asyncio.run(main()) + """ + _response = await self._raw_client.transcribe( + file=file, + model=model, + mode=mode, + language_code=language_code, + input_audio_codec=input_audio_codec, + request_options=request_options, + ) + return _response.data + + async def translate( + self, + *, + file: core.File, + prompt: typing.Optional[str] = OMIT, + model: typing.Optional[SpeechToTextTranslateModel] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> SpeechToTextTranslateResponse: + """ + ## Speech to Text Translation API + + This API automatically detects the input language, transcribes the speech, and translates the text to English. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files [Follow this documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + prompt : typing.Optional[str] + Conversation context can be passed as a prompt to boost model accuracy. However, the current system is at an experimentation stage and doesn't match the prompt performance of large language models. + + model : typing.Optional[SpeechToTextTranslateModel] + Model to be used for speech to text translation. + + - **saaras:v2.5** (default): Translation model that translates audio from any spoken Indic language to English. + - Example: Hindi audio → English text output + + input_audio_codec : typing.Optional[InputAudioCodec] + Audio codec/format of the input file. Our API automatically detects all codec formats, but for PCM files specifically (pcm_s16le, pcm_l16, pcm_raw), you must pass this parameter. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextTranslateResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text.translate() + + + asyncio.run(main()) + """ + _response = await self._raw_client.translate( + file=file, prompt=prompt, model=model, input_audio_codec=input_audio_codec, request_options=request_options + ) + return _response.data diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d66e3dddbf2399ae6b4c656e2d1b9967a9eeaef9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text/raw_client.py @@ -0,0 +1,727 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from .. import core +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..errors.bad_request_error import BadRequestError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.service_unavailable_error import ServiceUnavailableError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..errors.unprocessable_entity_error import UnprocessableEntityError +from ..types.input_audio_codec import InputAudioCodec +from ..types.mode import Mode +from ..types.speech_to_text_language import SpeechToTextLanguage +from ..types.speech_to_text_model import SpeechToTextModel +from ..types.speech_to_text_response import SpeechToTextResponse +from ..types.speech_to_text_translate_model import SpeechToTextTranslateModel +from ..types.speech_to_text_translate_response import SpeechToTextTranslateResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawSpeechToTextClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def transcribe( + self, + *, + file: core.File, + model: typing.Optional[SpeechToTextModel] = OMIT, + mode: typing.Optional[Mode] = OMIT, + language_code: typing.Optional[SpeechToTextLanguage] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[SpeechToTextResponse]: + """ + ## Speech to Text API + + This API transcribes speech to text in multiple Indian languages and English. Supports transcription for interactive applications. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files, [Follow This Documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + model : typing.Optional[SpeechToTextModel] + Specifies the model to use for speech-to-text conversion. + + - **saarika:v2.5** (default): Transcribes audio in the spoken language. + + - **saaras:v3**: State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + mode : typing.Optional[Mode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + language_code : typing.Optional[SpeechToTextLanguage] + Specifies the language of the input audio in BCP-47 format. + + **Note:** This parameter is optional for `saarika:v2.5` model. + + **Available Options:** + - `unknown`: Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + - `gu-IN`: Gujarati + + **Additional Options (saaras:v3 only):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + input_audio_codec : typing.Optional[InputAudioCodec] + Input Audio codec/format of the input file. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[SpeechToTextResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text", + base_url=self._client_wrapper.get_environment().base, + method="POST", + data={ + "model": model, + "mode": mode, + "language_code": language_code, + "input_audio_codec": input_audio_codec, + }, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + SpeechToTextResponse, + parse_obj_as( + type_=SpeechToTextResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def translate( + self, + *, + file: core.File, + prompt: typing.Optional[str] = OMIT, + model: typing.Optional[SpeechToTextTranslateModel] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[SpeechToTextTranslateResponse]: + """ + ## Speech to Text Translation API + + This API automatically detects the input language, transcribes the speech, and translates the text to English. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files [Follow this documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + prompt : typing.Optional[str] + Conversation context can be passed as a prompt to boost model accuracy. However, the current system is at an experimentation stage and doesn't match the prompt performance of large language models. + + model : typing.Optional[SpeechToTextTranslateModel] + Model to be used for speech to text translation. + + - **saaras:v2.5** (default): Translation model that translates audio from any spoken Indic language to English. + - Example: Hindi audio → English text output + + input_audio_codec : typing.Optional[InputAudioCodec] + Audio codec/format of the input file. Our API automatically detects all codec formats, but for PCM files specifically (pcm_s16le, pcm_l16, pcm_raw), you must pass this parameter. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[SpeechToTextTranslateResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text-translate", + base_url=self._client_wrapper.get_environment().base, + method="POST", + data={ + "prompt": prompt, + "model": model, + "input_audio_codec": input_audio_codec, + }, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + SpeechToTextTranslateResponse, + parse_obj_as( + type_=SpeechToTextTranslateResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + +class AsyncRawSpeechToTextClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def transcribe( + self, + *, + file: core.File, + model: typing.Optional[SpeechToTextModel] = OMIT, + mode: typing.Optional[Mode] = OMIT, + language_code: typing.Optional[SpeechToTextLanguage] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[SpeechToTextResponse]: + """ + ## Speech to Text API + + This API transcribes speech to text in multiple Indian languages and English. Supports transcription for interactive applications. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files, [Follow This Documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + model : typing.Optional[SpeechToTextModel] + Specifies the model to use for speech-to-text conversion. + + - **saarika:v2.5** (default): Transcribes audio in the spoken language. + + - **saaras:v3**: State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + mode : typing.Optional[Mode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + language_code : typing.Optional[SpeechToTextLanguage] + Specifies the language of the input audio in BCP-47 format. + + **Note:** This parameter is optional for `saarika:v2.5` model. + + **Available Options:** + - `unknown`: Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + - `gu-IN`: Gujarati + + **Additional Options (saaras:v3 only):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + input_audio_codec : typing.Optional[InputAudioCodec] + Input Audio codec/format of the input file. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[SpeechToTextResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text", + base_url=self._client_wrapper.get_environment().base, + method="POST", + data={ + "model": model, + "mode": mode, + "language_code": language_code, + "input_audio_codec": input_audio_codec, + }, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + SpeechToTextResponse, + parse_obj_as( + type_=SpeechToTextResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def translate( + self, + *, + file: core.File, + prompt: typing.Optional[str] = OMIT, + model: typing.Optional[SpeechToTextTranslateModel] = OMIT, + input_audio_codec: typing.Optional[InputAudioCodec] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[SpeechToTextTranslateResponse]: + """ + ## Speech to Text Translation API + + This API automatically detects the input language, transcribes the speech, and translates the text to English. + + ### Available Options: + - **REST API** (Current Endpoint): For quick responses under 30 seconds with immediate results + - **Batch API**: For longer audio files [Follow this documentation](https://docs.sarvam.ai/api-reference-docs/api-guides-tutorials/speech-to-text/batch-api) + - Supports diarization (speaker identification) + + ### Note: + - Pricing differs for REST and Batch APIs + - Diarization is only available in Batch API with separate pricing + - Please refer to [here](https://docs.sarvam.ai/api-reference-docs/getting-started/pricing) for detailed pricing information + + Parameters + ---------- + file : core.File + See core.File for more documentation + + prompt : typing.Optional[str] + Conversation context can be passed as a prompt to boost model accuracy. However, the current system is at an experimentation stage and doesn't match the prompt performance of large language models. + + model : typing.Optional[SpeechToTextTranslateModel] + Model to be used for speech to text translation. + + - **saaras:v2.5** (default): Translation model that translates audio from any spoken Indic language to English. + - Example: Hindi audio → English text output + + input_audio_codec : typing.Optional[InputAudioCodec] + Audio codec/format of the input file. Our API automatically detects all codec formats, but for PCM files specifically (pcm_s16le, pcm_l16, pcm_raw), you must pass this parameter. PCM files are supported only at 16kHz sample rate. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[SpeechToTextTranslateResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text-translate", + base_url=self._client_wrapper.get_environment().base, + method="POST", + data={ + "prompt": prompt, + "model": model, + "input_audio_codec": input_audio_codec, + }, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, + force_multipart=True, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + SpeechToTextTranslateResponse, + parse_obj_as( + type_=SpeechToTextTranslateResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..608da535c25938668b34d3f7e79b8895ec2a0309 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27b13c31e79a84fa775009b724d333885c0d781b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/job.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/job.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b17190e275e89b2186778684d8f42348469772b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/job.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0bde276d836c76cd4f0f395974f420b86f2c849 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/client.py new file mode 100644 index 0000000000000000000000000000000000000000..1f0d3ac58bfe9a7eee217be265cc0c9c6edbc3be --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/client.py @@ -0,0 +1,646 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..requests.bulk_job_callback import BulkJobCallbackParams +from ..requests.speech_to_text_job_parameters import SpeechToTextJobParametersParams +from ..types.bulk_job_init_response import BulkJobInitResponse +from ..types.files_download_response import FilesDownloadResponse +from ..types.files_upload_response import FilesUploadResponse +from ..types.job_status_response import JobStatusResponse +from ..types.speech_to_text_model import SpeechToTextModel +from ..types.speech_to_text_language import SpeechToTextLanguage +from ..types.mode import Mode +from .raw_client import AsyncRawSpeechToTextJobClient, RawSpeechToTextJobClient +from .job import AsyncSpeechToTextJob, SpeechToTextJob + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class SpeechToTextJobClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawSpeechToTextJobClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawSpeechToTextJobClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawSpeechToTextJobClient + """ + return self._raw_client + + def initialise( + self, + *, + job_parameters: SpeechToTextJobParametersParams, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> BulkJobInitResponse: + """ + Get a job uuid, and storage folder details for speech to text bulk job v1 + + Parameters + ---------- + job_parameters : SpeechToTextJobParametersParams + Job Parameters for the bulk job + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + BulkJobInitResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_job.initialise( + job_parameters={}, + ) + """ + _response = self._raw_client.initialise( + job_parameters=job_parameters, + callback=callback, + request_options=request_options, + ) + return _response.data + + def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> JobStatusResponse: + """ + Get the status of a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_job.get_status( + job_id="job_id", + ) + """ + _response = self._raw_client.get_status(job_id, request_options=request_options) + return _response.data + + def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> JobStatusResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_job.start( + job_id="job_id", + ) + """ + _response = self._raw_client.start( + job_id, ptu_id=ptu_id, request_options=request_options + ) + return _response.data + + def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesUploadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesUploadResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_job.get_upload_links( + job_id="job_id", + files=["files"], + ) + """ + _response = self._raw_client.get_upload_links( + job_id=job_id, files=files, request_options=request_options + ) + return _response.data + + def get_download_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesDownloadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesDownloadResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_job.get_download_links( + job_id="job_id", + files=["files"], + ) + """ + _response = self._raw_client.get_download_links( + job_id=job_id, files=files, request_options=request_options + ) + return _response.data + + def create_job( + self, + model: SpeechToTextModel = "saarika:v2.5", + mode: typing.Optional[Mode] = None, + with_diarization: bool = False, + with_timestamps: bool = False, + language_code: typing.Optional[SpeechToTextLanguage] = None, + num_speakers: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> SpeechToTextJob: + """ + Create a new Speech-to-Text bulk job. + + Parameters + ---------- + model : SpeechToTextModel, default="saarika:v2.5" + The model to use for transcription. + + mode : typing.Optional[Mode], default=None + Mode of operation. Only applicable for saaras:v3 model. + Options: transcribe, translate, indic-en, verbatim, translit, codemix + + with_diarization : typing.Optional[bool], default=False + Whether to enable speaker diarization (distinguishing who said what). + + with_timestamps : typing.Optional[bool], default=False + Whether to include word-level timestamps in the transcription output. + + language_code : typing.Optional[SpeechToTextLanguage], default=None + The language code of the input audio (e.g., "hi-IN", "bn-IN"). + + num_speakers : typing.Optional[int], default=None + The number of distinct speakers in the audio, if known. + + callback : typing.Optional[BulkJobCallbackParams], default=OMIT + Optional callback configuration to receive job completion events. + + request_options : typing.Optional[RequestOptions], default=None + Request-specific configuration. + + Returns + ------- + SpeechToTextJob + A handle to the newly created Speech-to-Text job. + """ + response = self.initialise( + job_parameters=SpeechToTextJobParametersParams( + language_code=language_code, + model=model, + mode=mode, # type: ignore[typeddict-item] + num_speakers=num_speakers, # type: ignore[typeddict-item] + with_diarization=with_diarization, + with_timestamps=with_timestamps, + ), + callback=callback, + request_options=request_options, + ) + return SpeechToTextJob(job_id=response.job_id, client=self) + + def get_job(self, job_id: str) -> SpeechToTextJob: + """ + Get an existing Speech-to-Text job handle by job ID. + + Parameters + ---------- + job_id : str + The job ID of the previously created Speech-to-Text job. + + Returns + ------- + SpeechToTextJob + A job handle which can be used to check status or retrieve results. + """ + return SpeechToTextJob(job_id=job_id, client=self) + + +class AsyncSpeechToTextJobClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawSpeechToTextJobClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawSpeechToTextJobClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawSpeechToTextJobClient + """ + return self._raw_client + + async def initialise( + self, + *, + job_parameters: SpeechToTextJobParametersParams, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> BulkJobInitResponse: + """ + Get a job uuid, and storage folder details for speech to text bulk job v1 + + Parameters + ---------- + job_parameters : SpeechToTextJobParametersParams + Job Parameters for the bulk job + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + BulkJobInitResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_job.initialise( + job_parameters={}, + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.initialise( + job_parameters=job_parameters, + callback=callback, + request_options=request_options, + ) + return _response.data + + async def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> JobStatusResponse: + """ + Get the status of a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_job.get_status( + job_id="job_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_status( + job_id, request_options=request_options + ) + return _response.data + + async def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> JobStatusResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_job.start( + job_id="job_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.start( + job_id, ptu_id=ptu_id, request_options=request_options + ) + return _response.data + + async def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesUploadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesUploadResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_job.get_upload_links( + job_id="job_id", + files=["files"], + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_upload_links( + job_id=job_id, files=files, request_options=request_options + ) + return _response.data + + async def get_download_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesDownloadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesDownloadResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_job.get_download_links( + job_id="job_id", + files=["files"], + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_download_links( + job_id=job_id, files=files, request_options=request_options + ) + return _response.data + + async def create_job( + self, + model: SpeechToTextModel = "saarika:v2.5", + mode: typing.Optional[Mode] = None, + with_diarization: bool = False, + with_timestamps: bool = False, + language_code: typing.Optional[SpeechToTextLanguage] = None, + num_speakers: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> "AsyncSpeechToTextJob": + """ + Create a new Speech-to-Text bulk job. + + Parameters + ---------- + model : SpeechToTextModel, default="saarika:v2.5" + The model to use for transcription. + + mode : typing.Optional[Mode], default=None + Mode of operation. Only applicable for saaras:v3 model. + Options: transcribe, translate, indic-en, verbatim, translit, codemix + + with_diarization : typing.Optional[bool], default=False + Whether to enable speaker diarization (distinguishing who said what). + + with_timestamps : typing.Optional[bool], default=False + Whether to include word-level timestamps in the transcription output. + + language_code : typing.Optional[SpeechToTextLanguage], default=None + The language code of the input audio (e.g., "hi-IN", "bn-IN"). + + num_speakers : typing.Optional[int] = None + The number of distinct speakers in the audio, if known. + + callback : typing.Optional[BulkJobCallbackParams], default=OMIT + Optional callback configuration to receive job completion events. + + request_options : typing.Optional[RequestOptions], default=None + Request-specific configuration. + + Returns + ------- + AsyncSpeechToTextJob + A handle to the newly created job. + """ + response = await self.initialise( + job_parameters=SpeechToTextJobParametersParams( + language_code=language_code, + model=model, + mode=mode, # type: ignore[typeddict-item] + with_diarization=with_diarization, + with_timestamps=with_timestamps, + num_speakers=num_speakers, # type: ignore[typeddict-item] + ), + callback=callback, + request_options=request_options, + ) + return AsyncSpeechToTextJob(job_id=response.job_id, client=self) + + async def get_job(self, job_id: str) -> "AsyncSpeechToTextJob": + """ + Get an existing Speech-to-Text job handle by job ID. + + Parameters + ---------- + job_id : str + The job ID of the previously created speech-to-text job. + + Returns + ------- + AsyncSpeechToTextJob + A job handle which can be used to check status or retrieve results. + """ + return AsyncSpeechToTextJob(job_id=job_id, client=self) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/job.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/job.py new file mode 100644 index 0000000000000000000000000000000000000000..6786c443bf718220973d540e6d07963aa62cb3b4 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/job.py @@ -0,0 +1,595 @@ +import asyncio +import mimetypes +import os +import time +import typing +import httpx +from http import HTTPStatus + +from ..types import JobStatusResponse + +if typing.TYPE_CHECKING: + from .client import AsyncSpeechToTextJobClient, SpeechToTextJobClient + + +class AsyncSpeechToTextJob: + def __init__(self, job_id: str, client: "AsyncSpeechToTextJobClient"): + """ + Initialize the asynchronous speech-to-text job. + + Parameters + ---------- + job_id : str + The unique job identifier returned from a previous job initialization. + + client : AsyncSpeechToTextJobClient + The async client instance used to create the job. + + !!! important + This must be the **same client instance** that was used to initialize + the job originally, as it contains the subscription key and configuration + required to authenticate and manage the job. + + """ + self._job_id = job_id + self._client = client + + @property + def job_id(self) -> str: + """ + Returns the job ID associated with this job instance. + + Returns + ------- + str + """ + return self._job_id + + async def upload_files( + self, file_paths: typing.Sequence[str], timeout: float = 60.0 + ) -> bool: + """ + Upload input audio files for the speech-to-text job. + + Parameters + ---------- + file_paths : Sequence[str] + List of full paths to local audio files. + + timeout : float, optional + The maximum time to wait for the upload to complete (in seconds), + by default 60.0 + Returns + ------- + bool + True if all files are uploaded successfully. + """ + upload_links = await self._client.get_upload_links( + job_id=self._job_id, + files=[os.path.basename(p) for p in file_paths], + ) + client_timeout = httpx.Timeout(timeout=timeout) + async with httpx.AsyncClient(timeout=client_timeout) as session: + for path in file_paths: + file_name = os.path.basename(path) + url = upload_links.upload_urls[file_name].file_url + with open(path, "rb") as f: + content_type, _ = mimetypes.guess_type(path) + if content_type is None: + content_type = "audio/wav" + response = await session.put( + url, + content=f.read(), + headers={ + "x-ms-blob-type": "BlockBlob", + "Content-Type": content_type, + }, + ) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Upload failed for {file_name}: {response.status_code}" + ) + return True + + async def wait_until_complete( + self, poll_interval: int = 5, timeout: int = 600 + ) -> JobStatusResponse: + """ + Polls job status until it completes or fails. + + Parameters + ---------- + poll_interval : int, optional + Time in seconds between polling attempts (default is 5). + + timeout : int, optional + Maximum time to wait for completion in seconds (default is 600). + + Returns + ------- + JobStatusResponse + Final job status. + + Raises + ------ + TimeoutError + If the job does not complete within the given timeout. + """ + start = asyncio.get_event_loop().time() + while True: + status = await self.get_status() + state = status.job_state.lower() + if state in {"completed", "failed"}: + return status + if asyncio.get_event_loop().time() - start > timeout: + raise TimeoutError( + f"Job {self._job_id} did not complete within {timeout} seconds." + ) + await asyncio.sleep(poll_interval) + + async def get_output_mappings(self) -> typing.List[typing.Dict[str, str]]: + """ + Get the mapping of input files to their corresponding output files. + + Returns + ------- + List[Dict[str, str]] + List of mappings with keys 'input_file' and 'output_file'. + """ + job_status = await self.get_status() + return [ + { + "input_file": detail.inputs[0].file_name, + "output_file": detail.outputs[0].file_name, + } + for detail in (job_status.job_details or []) + if detail.inputs and detail.outputs and detail.state == "Success" + ] + + async def get_file_results( + self, + ) -> typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]]: + """ + Get detailed results for each file in the batch job. + + Returns + ------- + Dict[str, List[Dict[str, Any]]] + Dictionary with 'successful' and 'failed' keys, each containing a list of file details. + Each file detail includes: + - 'file_name': Name of the input file + - 'status': Status of processing ('Success' or 'Failed') + - 'error_message': Error message if failed (None if successful) + - 'output_file': Name of output file if successful (None if failed) + """ + job_status = await self.get_status() + results: typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]] = { + "successful": [], + "failed": [], + } + + for detail in job_status.job_details or []: + # Check for empty lists explicitly + if not detail.inputs or len(detail.inputs) == 0: + continue + + try: + file_info = { + "file_name": detail.inputs[0].file_name, + "status": detail.state, + "error_message": detail.error_message, + "output_file": ( + detail.outputs[0].file_name + if detail.outputs and len(detail.outputs) > 0 + else None + ), + } + + if detail.state == "Success": + results["successful"].append(file_info) + else: + results["failed"].append(file_info) + except (IndexError, AttributeError): + # Skip malformed job details + continue + + return results + + async def download_outputs(self, output_dir: str) -> bool: + """ + Download output files to the specified directory. + + Parameters + ---------- + output_dir : str + Local directory where outputs will be saved. + + Returns + ------- + bool + True if all files downloaded successfully. + + Raises + ------ + RuntimeError + If a file fails to download. + """ + mappings = await self.get_output_mappings() + file_names = [m["output_file"] for m in mappings] + download_links = await self._client.get_download_links( + job_id=self._job_id, files=file_names + ) + + os.makedirs(output_dir, exist_ok=True) + async with httpx.AsyncClient() as session: + for m in mappings: + url = download_links.download_urls[m["output_file"]].file_url + response = await session.get(url) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Download failed for {m['output_file']}: {response.status_code}" + ) + output_path = os.path.join(output_dir, f"{m['input_file']}.json") + with open(output_path, "wb") as f: + f.write(response.content) + return True + + async def get_status(self) -> JobStatusResponse: + """ + Retrieve the current status of the job. + + Returns + ------- + JobStatusResponse + """ + return await self._client.get_status(self._job_id) + + async def start(self) -> JobStatusResponse: + """ + Start the speech-to-text job processing. + + Returns + ------- + JobStatusResponse + """ + return await self._client.start(job_id=self._job_id) + + async def exists(self) -> bool: + """ + Check if the job exists in the system. + + Returns + ------- + bool + """ + try: + await self.get_status() + return True + except httpx.HTTPStatusError: + return False + + async def is_complete(self) -> bool: + """ + Check if the job is either completed or failed. + + Returns + ------- + bool + """ + state = (await self.get_status()).job_state.lower() + return state in {"completed", "failed"} + + async def is_successful(self) -> bool: + """ + Check if the job completed successfully. + + Returns + ------- + bool + """ + return (await self.get_status()).job_state.lower() == "completed" + + async def is_failed(self) -> bool: + """ + Check if the job has failed. + + Returns + ------- + bool + """ + return (await self.get_status()).job_state.lower() == "failed" + + +class SpeechToTextJob: + def __init__(self, job_id: str, client: "SpeechToTextJobClient"): + """ + Initialize the synchronous speech-to-text job. + + Parameters + ---------- + job_id : str + The unique job identifier returned from a previous job initialization. + + client : SpeechToTextJobClient + The client instance used to create the job. + + !!! important + This must be the **same client instance** that was used to initialize + the job originally, as it contains the subscription key and configuration + required to authenticate and manage the job. + + """ + self._job_id = job_id + self._client = client + + @property + def job_id(self) -> str: + """ + Returns the job ID associated with this job instance. + + Returns + ------- + str + """ + return self._job_id + + def upload_files( + self, file_paths: typing.Sequence[str], timeout: float = 60.0 + ) -> bool: + """ + Upload input audio files for the speech-to-text job. + + Parameters + ---------- + file_paths : Sequence[str] + List of full paths to local audio files. + + timeout : float, optional + The maximum time to wait for the upload to complete (in seconds), + by default 60.0 + Returns + ------- + bool + True if all files are uploaded successfully. + """ + upload_links = self._client.get_upload_links( + job_id=self._job_id, files=[os.path.basename(p) for p in file_paths] + ) + client_timeout = httpx.Timeout(timeout=timeout) + with httpx.Client(timeout=client_timeout) as client: + for path in file_paths: + file_name = os.path.basename(path) + url = upload_links.upload_urls[file_name].file_url + with open(path, "rb") as f: + response = client.put( + url, + content=f, + headers={ + "x-ms-blob-type": "BlockBlob", + "Content-Type": "audio/wav", + }, + ) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Upload failed for {file_name}: {response.status_code}" + ) + return True + + def wait_until_complete( + self, poll_interval: int = 5, timeout: int = 600 + ) -> JobStatusResponse: + """ + Polls job status until it completes or fails. + + Parameters + ---------- + poll_interval : int, optional + Time in seconds between polling attempts (default is 5). + + timeout : int, optional + Maximum time to wait for completion in seconds (default is 600). + + Returns + ------- + JobStatusResponse + Final job status. + + Raises + ------ + TimeoutError + If the job does not complete within the given timeout. + """ + start = time.monotonic() + while True: + status = self.get_status() + state = status.job_state.lower() + if state in {"completed", "failed"}: + return status + if time.monotonic() - start > timeout: + raise TimeoutError( + f"Job {self._job_id} did not complete within {timeout} seconds." + ) + time.sleep(poll_interval) + + def get_output_mappings(self) -> typing.List[typing.Dict[str, str]]: + """ + Get the mapping of input files to their corresponding output files. + + Returns + ------- + List[Dict[str, str]] + List of mappings with keys 'input_file' and 'output_file'. + """ + job_status = self.get_status() + return [ + { + "input_file": detail.inputs[0].file_name, + "output_file": detail.outputs[0].file_name, + } + for detail in (job_status.job_details or []) + if detail.inputs and detail.outputs and detail.state == "Success" + ] + + def get_file_results( + self, + ) -> typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]]: + """ + Get detailed results for each file in the batch job. + + Returns + ------- + Dict[str, List[Dict[str, Any]]] + Dictionary with 'successful' and 'failed' keys, each containing a list of file details. + Each file detail includes: + - 'file_name': Name of the input file + - 'status': Status of processing ('Success' or 'Failed') + - 'error_message': Error message if failed (None if successful) + - 'output_file': Name of output file if successful (None if failed) + """ + job_status = self.get_status() + results: typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]] = { + "successful": [], + "failed": [], + } + + for detail in job_status.job_details or []: + # Check for empty lists explicitly + if not detail.inputs or len(detail.inputs) == 0: + continue + + try: + file_info = { + "file_name": detail.inputs[0].file_name, + "status": detail.state, + "error_message": detail.error_message, + "output_file": ( + detail.outputs[0].file_name + if detail.outputs and len(detail.outputs) > 0 + else None + ), + } + + if detail.state == "Success": + results["successful"].append(file_info) + else: + results["failed"].append(file_info) + except (IndexError, AttributeError): + # Skip malformed job details + continue + + return results + + def download_outputs(self, output_dir: str) -> bool: + """ + Download output files to the specified directory. + + Parameters + ---------- + output_dir : str + Local directory where outputs will be saved. + + Returns + ------- + bool + True if all files downloaded successfully. + + Raises + ------ + RuntimeError + If a file fails to download. + """ + mappings = self.get_output_mappings() + file_names = [m["output_file"] for m in mappings] + download_links = self._client.get_download_links( + job_id=self._job_id, files=file_names + ) + + os.makedirs(output_dir, exist_ok=True) + with httpx.Client() as client: + for m in mappings: + url = download_links.download_urls[m["output_file"]].file_url + response = client.get(url) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Download failed for {m['output_file']}: {response.status_code}" + ) + output_path = os.path.join(output_dir, f"{m['input_file']}.json") + with open(output_path, "wb") as f: + f.write(response.content) + return True + + def get_status(self) -> JobStatusResponse: + """ + Retrieve the current status of the job. + + Returns + ------- + JobStatusResponse + """ + return self._client.get_status(self._job_id) + + def start(self) -> JobStatusResponse: + """ + Start the speech-to-text job processing. + + Returns + ------- + JobStatusResponse + """ + return self._client.start(job_id=self._job_id) + + def exists(self) -> bool: + """ + Check if the job exists in the system. + + Returns + ------- + bool + """ + try: + self.get_status() + return True + except httpx.HTTPStatusError: + return False + + def is_complete(self) -> bool: + """ + Check if the job is either completed or failed. + + Returns + ------- + bool + """ + return self.get_status().job_state.lower() in {"completed", "failed"} + + def is_successful(self) -> bool: + """ + Check if the job completed successfully. + + Returns + ------- + bool + """ + return self.get_status().job_state.lower() == "completed" + + def is_failed(self) -> bool: + """ + Check if the job has failed. + + Returns + ------- + bool + """ + return self.get_status().job_state.lower() == "failed" diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..406f59df1cb19af94693c466ba603d6c5a5ae5c5 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_job/raw_client.py @@ -0,0 +1,1193 @@ +# 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.http_response import AsyncHttpResponse, HttpResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..core.serialization import convert_and_respect_annotation_metadata +from ..errors.bad_request_error import BadRequestError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.service_unavailable_error import ServiceUnavailableError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..errors.unprocessable_entity_error import UnprocessableEntityError +from ..requests.bulk_job_callback import BulkJobCallbackParams +from ..requests.speech_to_text_job_parameters import SpeechToTextJobParametersParams +from ..types.bulk_job_init_response import BulkJobInitResponse +from ..types.files_download_response import FilesDownloadResponse +from ..types.files_upload_response import FilesUploadResponse +from ..types.job_status_response import JobStatusResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawSpeechToTextJobClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def initialise( + self, + *, + job_parameters: SpeechToTextJobParametersParams, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[BulkJobInitResponse]: + """ + Create a new speech to text bulk job and receive a job UUID and storage folder details for processing multiple audio files. Set `job_parameters.input_audio_codec` when uploads are raw PCM (`pcm_s16le`, `pcm_l16`, or `pcm_raw`); the API auto-detects other formats. PCM must be 16 kHz. + + Parameters + ---------- + job_parameters : SpeechToTextJobParametersParams + Job Parameters for the bulk job + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[BulkJobInitResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text/job/v1", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_parameters": convert_and_respect_annotation_metadata( + object_=job_parameters, annotation=SpeechToTextJobParametersParams, direction="write" + ), + "callback": convert_and_respect_annotation_metadata( + object_=callback, annotation=BulkJobCallbackParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + BulkJobInitResponse, + parse_obj_as( + type_=BulkJobInitResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[JobStatusResponse]: + """ + Retrieve the current status and details of a speech to text bulk job, including progress and file-level information. + + **Rate Limiting Best Practice:** To prevent rate limit errors and ensure optimal server performance, we recommend implementing a minimum 5-millisecond delay between consecutive status polling requests. This helps maintain system stability while still providing timely status updates. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[JobStatusResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"speech-to-text/job/v1/{jsonable_encoder(job_id)}/status", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[JobStatusResponse]: + """ + Start processing a speech to text bulk job after all audio files have been uploaded + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[JobStatusResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"speech-to-text/job/v1/{jsonable_encoder(job_id)}/start", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_upload_links( + self, *, job_id: str, files: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[FilesUploadResponse]: + """ + Generate presigned upload URLs for audio files that will be processed in a speech to text bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[FilesUploadResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text/job/v1/upload-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesUploadResponse, + parse_obj_as( + type_=FilesUploadResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_download_links( + self, *, job_id: str, files: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[FilesDownloadResponse]: + """ + Generate presigned download URLs for the transcription output files of a completed speech to text bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[FilesDownloadResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text/job/v1/download-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesDownloadResponse, + parse_obj_as( + type_=FilesDownloadResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + +class AsyncRawSpeechToTextJobClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def initialise( + self, + *, + job_parameters: SpeechToTextJobParametersParams, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[BulkJobInitResponse]: + """ + Create a new speech to text bulk job and receive a job UUID and storage folder details for processing multiple audio files. Set `job_parameters.input_audio_codec` when uploads are raw PCM (`pcm_s16le`, `pcm_l16`, or `pcm_raw`); the API auto-detects other formats. PCM must be 16 kHz. + + Parameters + ---------- + job_parameters : SpeechToTextJobParametersParams + Job Parameters for the bulk job + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[BulkJobInitResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text/job/v1", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_parameters": convert_and_respect_annotation_metadata( + object_=job_parameters, annotation=SpeechToTextJobParametersParams, direction="write" + ), + "callback": convert_and_respect_annotation_metadata( + object_=callback, annotation=BulkJobCallbackParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + BulkJobInitResponse, + parse_obj_as( + type_=BulkJobInitResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[JobStatusResponse]: + """ + Retrieve the current status and details of a speech to text bulk job, including progress and file-level information. + + **Rate Limiting Best Practice:** To prevent rate limit errors and ensure optimal server performance, we recommend implementing a minimum 5-millisecond delay between consecutive status polling requests. This helps maintain system stability while still providing timely status updates. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[JobStatusResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"speech-to-text/job/v1/{jsonable_encoder(job_id)}/status", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[JobStatusResponse]: + """ + Start processing a speech to text bulk job after all audio files have been uploaded + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[JobStatusResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"speech-to-text/job/v1/{jsonable_encoder(job_id)}/start", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_upload_links( + self, *, job_id: str, files: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[FilesUploadResponse]: + """ + Generate presigned upload URLs for audio files that will be processed in a speech to text bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[FilesUploadResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text/job/v1/upload-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesUploadResponse, + parse_obj_as( + type_=FilesUploadResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_download_links( + self, *, job_id: str, files: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[FilesDownloadResponse]: + """ + Generate presigned download URLs for the transcription output files of a completed speech to text bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[FilesDownloadResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text/job/v1/download-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesDownloadResponse, + parse_obj_as( + type_=FilesDownloadResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..54d86220d4fcf8d2bb84053b3d7a78947a3d169b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__init__.py @@ -0,0 +1,58 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .types import ( + SpeechToTextStreamingFlushSignal, + SpeechToTextStreamingHighVadSensitivity, + SpeechToTextStreamingInputAudioCodec, + SpeechToTextStreamingLanguageCode, + SpeechToTextStreamingMode, + SpeechToTextStreamingModel, + SpeechToTextStreamingVadSignals, + ) +_dynamic_imports: typing.Dict[str, str] = { + "SpeechToTextStreamingFlushSignal": ".types", + "SpeechToTextStreamingHighVadSensitivity": ".types", + "SpeechToTextStreamingInputAudioCodec": ".types", + "SpeechToTextStreamingLanguageCode": ".types", + "SpeechToTextStreamingMode": ".types", + "SpeechToTextStreamingModel": ".types", + "SpeechToTextStreamingVadSignals": ".types", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "SpeechToTextStreamingFlushSignal", + "SpeechToTextStreamingHighVadSensitivity", + "SpeechToTextStreamingInputAudioCodec", + "SpeechToTextStreamingLanguageCode", + "SpeechToTextStreamingMode", + "SpeechToTextStreamingModel", + "SpeechToTextStreamingVadSignals", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeeb7e8dce0785b4daf1bf1d1fe4533fa0ef9e48 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f2b1bfff0baf930dca6dc0544e97b08f761b4e9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8421e70f665ef6c3ac86c1805fa8e8f5a9359dd3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/socket_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/socket_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e84549e18f41e56aba28eb7ddf80c4066cfcdd9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/__pycache__/socket_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/client.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a0345aa032776c67a79994d6c64e6c729e561e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/client.py @@ -0,0 +1,492 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +import urllib.parse +from contextlib import asynccontextmanager, contextmanager + +import websockets.sync.client as websockets_sync_client +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.jsonable_encoder import jsonable_encoder +from ..core.query_encoder import encode_query +from ..core.remove_none_from_dict import remove_none_from_dict +from ..core.request_options import RequestOptions +from ..core.websocket_compat import InvalidWebSocketStatus, get_status_code +from .raw_client import AsyncRawSpeechToTextStreamingClient, RawSpeechToTextStreamingClient +from .socket_client import AsyncSpeechToTextStreamingSocketClient, SpeechToTextStreamingSocketClient +from .types.speech_to_text_streaming_flush_signal import SpeechToTextStreamingFlushSignal +from .types.speech_to_text_streaming_high_vad_sensitivity import SpeechToTextStreamingHighVadSensitivity +from .types.speech_to_text_streaming_input_audio_codec import SpeechToTextStreamingInputAudioCodec +from .types.speech_to_text_streaming_language_code import SpeechToTextStreamingLanguageCode +from .types.speech_to_text_streaming_mode import SpeechToTextStreamingMode +from .types.speech_to_text_streaming_model import SpeechToTextStreamingModel +from .types.speech_to_text_streaming_vad_signals import SpeechToTextStreamingVadSignals + +try: + from websockets.legacy.client import connect as websockets_client_connect # type: ignore +except ImportError: + from websockets import connect as websockets_client_connect # type: ignore + + +class SpeechToTextStreamingClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawSpeechToTextStreamingClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawSpeechToTextStreamingClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawSpeechToTextStreamingClient + """ + return self._raw_client + + @contextmanager + def connect( + self, + *, + language_code: SpeechToTextStreamingLanguageCode, + model: typing.Optional[SpeechToTextStreamingModel] = None, + mode: typing.Optional[SpeechToTextStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[SpeechToTextStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + language_code : SpeechToTextStreamingLanguageCode + Specifies the language of the input audio in BCP-47 format. + + **Available Options (saarika:v2.5, legacy):** + - `unknown` (default): Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + + **Additional Options (saaras:v3, recommended):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + model : typing.Optional[SpeechToTextStreamingModel] + Specifies the model to use for speech-to-text conversion. + + - **saaras:v3** (default, recommended): State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + - **saarika:v2.5** (legacy): Transcribes audio in the spoken language. Kept for backward compatibility. + + mode : typing.Optional[SpeechToTextStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription + + input_audio_codec : typing.Optional[SpeechToTextStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextStreamingSocketClient + """ + ws_url = self._raw_client._client_wrapper.get_environment().production + "/speech-to-text/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "language-code": language_code, + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._raw_client._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol: + yield SpeechToTextStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) + + +class AsyncSpeechToTextStreamingClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawSpeechToTextStreamingClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawSpeechToTextStreamingClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawSpeechToTextStreamingClient + """ + return self._raw_client + + @asynccontextmanager + async def connect( + self, + *, + language_code: SpeechToTextStreamingLanguageCode, + model: typing.Optional[SpeechToTextStreamingModel] = None, + mode: typing.Optional[SpeechToTextStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[AsyncSpeechToTextStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + language_code : SpeechToTextStreamingLanguageCode + Specifies the language of the input audio in BCP-47 format. + + **Available Options (saarika:v2.5, legacy):** + - `unknown` (default): Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + + **Additional Options (saaras:v3, recommended):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + model : typing.Optional[SpeechToTextStreamingModel] + Specifies the model to use for speech-to-text conversion. + + - **saaras:v3** (default, recommended): State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + - **saarika:v2.5** (legacy): Transcribes audio in the spoken language. Kept for backward compatibility. + + mode : typing.Optional[SpeechToTextStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription + + input_audio_codec : typing.Optional[SpeechToTextStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncSpeechToTextStreamingSocketClient + """ + ws_url = self._raw_client._client_wrapper.get_environment().production + "/speech-to-text/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "language-code": language_code, + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._raw_client._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + async with websockets_client_connect(ws_url, extra_headers=headers) as protocol: + yield AsyncSpeechToTextStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..19d2fce4617f1ecf46add76b4ff0fa824a1b1a4e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/raw_client.py @@ -0,0 +1,469 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +import urllib.parse +from contextlib import asynccontextmanager, contextmanager + +import websockets.sync.client as websockets_sync_client +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.jsonable_encoder import jsonable_encoder +from ..core.query_encoder import encode_query +from ..core.remove_none_from_dict import remove_none_from_dict +from ..core.request_options import RequestOptions +from ..core.websocket_compat import InvalidWebSocketStatus, get_status_code +from .socket_client import AsyncSpeechToTextStreamingSocketClient, SpeechToTextStreamingSocketClient +from .types.speech_to_text_streaming_flush_signal import SpeechToTextStreamingFlushSignal +from .types.speech_to_text_streaming_high_vad_sensitivity import SpeechToTextStreamingHighVadSensitivity +from .types.speech_to_text_streaming_input_audio_codec import SpeechToTextStreamingInputAudioCodec +from .types.speech_to_text_streaming_language_code import SpeechToTextStreamingLanguageCode +from .types.speech_to_text_streaming_mode import SpeechToTextStreamingMode +from .types.speech_to_text_streaming_model import SpeechToTextStreamingModel +from .types.speech_to_text_streaming_vad_signals import SpeechToTextStreamingVadSignals + +try: + from websockets.legacy.client import connect as websockets_client_connect # type: ignore +except ImportError: + from websockets import connect as websockets_client_connect # type: ignore + + +class RawSpeechToTextStreamingClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + @contextmanager + def connect( + self, + *, + language_code: SpeechToTextStreamingLanguageCode, + model: typing.Optional[SpeechToTextStreamingModel] = None, + mode: typing.Optional[SpeechToTextStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[SpeechToTextStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + language_code : SpeechToTextStreamingLanguageCode + Specifies the language of the input audio in BCP-47 format. + + **Available Options (saarika:v2.5, legacy):** + - `unknown` (default): Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + + **Additional Options (saaras:v3, recommended):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + model : typing.Optional[SpeechToTextStreamingModel] + Specifies the model to use for speech-to-text conversion. + + - **saaras:v3** (default, recommended): State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + - **saarika:v2.5** (legacy): Transcribes audio in the spoken language. Kept for backward compatibility. + + mode : typing.Optional[SpeechToTextStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription + + input_audio_codec : typing.Optional[SpeechToTextStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextStreamingSocketClient + """ + ws_url = self._client_wrapper.get_environment().production + "/speech-to-text/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "language-code": language_code, + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol: + yield SpeechToTextStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) + + +class AsyncRawSpeechToTextStreamingClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + @asynccontextmanager + async def connect( + self, + *, + language_code: SpeechToTextStreamingLanguageCode, + model: typing.Optional[SpeechToTextStreamingModel] = None, + mode: typing.Optional[SpeechToTextStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[AsyncSpeechToTextStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + language_code : SpeechToTextStreamingLanguageCode + Specifies the language of the input audio in BCP-47 format. + + **Available Options (saarika:v2.5, legacy):** + - `unknown` (default): Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `gu-IN`: Gujarati + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + + **Additional Options (saaras:v3, recommended):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + + model : typing.Optional[SpeechToTextStreamingModel] + Specifies the model to use for speech-to-text conversion. + + - **saaras:v3** (default, recommended): State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + + - **saarika:v2.5** (legacy): Transcribes audio in the spoken language. Kept for backward compatibility. + + mode : typing.Optional[SpeechToTextStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription + + input_audio_codec : typing.Optional[SpeechToTextStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncSpeechToTextStreamingSocketClient + """ + ws_url = self._client_wrapper.get_environment().production + "/speech-to-text/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "language-code": language_code, + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + async with websockets_client_connect(ws_url, extra_headers=headers) as protocol: + yield AsyncSpeechToTextStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/socket_client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/socket_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1f1fefa8e4f940d7a7752aa4b80218f6c85ee7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/socket_client.py @@ -0,0 +1,208 @@ +# This file was auto-generated by Fern from our API Definition. + +import json +import typing + +import websockets +import websockets.sync.connection as websockets_sync_connection +from ..core.events import EventEmitterMixin, EventType +from ..core.pydantic_utilities import parse_obj_as +from ..types.audio_data import AudioData +from ..types.audio_message import AudioMessage +from ..types.speech_to_text_streaming_response import ( + SpeechToTextStreamingResponse, +) +from ..types.stt_flush_signal import SttFlushSignal + +SpeechToTextStreamingSocketClientResponse = typing.Union[SpeechToTextStreamingResponse] + + +class AsyncSpeechToTextStreamingSocketClient(EventEmitterMixin): + def __init__(self, *, websocket: websockets.WebSocketClientProtocol): + super().__init__() + self._websocket = websocket + + async def __aiter__(self): + async for message in self._websocket: + message = json.loads(message) if isinstance(message, str) else message + yield parse_obj_as( + SpeechToTextStreamingSocketClientResponse, message + ) # type: ignore + + async def start_listening(self): + """ + Start listening for messages on the websocket connection. + + Emits events in the following order: + - EventType.OPEN when connection is established + - EventType.MESSAGE for each message received + - EventType.ERROR if an error occurs + - EventType.CLOSE when connection is closed + """ + self._emit(EventType.OPEN, None) + try: + async for raw_message in self._websocket: + raw_message = ( + json.loads(raw_message) + if isinstance(raw_message, str) + else raw_message + ) + parsed = parse_obj_as( + SpeechToTextStreamingSocketClientResponse, raw_message + ) # type: ignore + self._emit(EventType.MESSAGE, parsed) + except websockets.WebSocketException as exc: + self._emit(EventType.ERROR, exc) + finally: + self._emit(EventType.CLOSE, None) + + async def transcribe(self, audio: str, encoding="audio/wav", sample_rate=16000): + """ + Sends transcription request to the server. + :param audio: Base64 encoded audio data + :param encoding: Audio encoding format (default is "audio/wav") + :param sample_rate: Audio sample rate in Hz (default is 16000) + """ + + return await self._send_speech_to_text_streaming_audio_message( + message=AudioMessage( + audio=AudioData(data=audio, sample_rate=sample_rate, encoding=encoding) + ) + ) + + async def flush(self) -> None: + """ + Signal to flush the audio buffer and force finalize partial transcriptions. + Use this to force processing of any remaining audio that hasn't been + transcribed yet. + """ + message = SttFlushSignal() + await self._send_model(message) + + async def _send_speech_to_text_streaming_audio_message( + self, message: AudioMessage + ) -> None: + """ + Send a message to the websocket connection. + The message will be sent as a AudioMessage. + """ + await self._send_model(message) + + async def recv(self) -> SpeechToTextStreamingSocketClientResponse: + """ + Receive a message from the websocket connection. + """ + data = await self._websocket.recv() + data = json.loads(data) if isinstance(data, str) else data + return parse_obj_as( + SpeechToTextStreamingSocketClientResponse, data + ) # type: ignore + + async def _send(self, data: typing.Any) -> None: + """ + Send a message to the websocket connection. + """ + if isinstance(data, dict): + data = json.dumps(data) + await self._websocket.send(data) + + async def _send_model(self, data: typing.Any) -> None: + """ + Send a Pydantic model to the websocket connection. + """ + await self._send(data.dict()) + + +class SpeechToTextStreamingSocketClient(EventEmitterMixin): + def __init__(self, *, websocket: websockets_sync_connection.Connection): + super().__init__() + self._websocket = websocket + + def __iter__(self): + for message in self._websocket: + message = json.loads(message) if isinstance(message, str) else message + yield parse_obj_as( + SpeechToTextStreamingSocketClientResponse, message + ) # type: ignore + + def start_listening(self): + """ + Start listening for messages on the websocket connection. + + Emits events in the following order: + - EventType.OPEN when connection is established + - EventType.MESSAGE for each message received + - EventType.ERROR if an error occurs + - EventType.CLOSE when connection is closed + """ + self._emit(EventType.OPEN, None) + try: + for raw_message in self._websocket: + raw_message = ( + json.loads(raw_message) + if isinstance(raw_message, str) + else raw_message + ) + parsed = parse_obj_as( + SpeechToTextStreamingSocketClientResponse, raw_message + ) # type: ignore + self._emit(EventType.MESSAGE, parsed) + except websockets.WebSocketException as exc: + self._emit(EventType.ERROR, exc) + finally: + self._emit(EventType.CLOSE, None) + + def transcribe(self, audio: str, encoding="audio/wav", sample_rate=16000) -> None: + """ + Sends transcription request to the server. + :param audio: Base64 encoded audio data + :param encoding (Optional): Audio encoding format (default is "audio/wav") + :param sample_rate (Optional): Audio sample rate in Hz (default is 16000) + """ + return self._send_speech_to_text_streaming_audio_message( + message=AudioMessage( + audio=AudioData(data=audio, sample_rate=sample_rate, encoding=encoding) + ) + ) + + def flush(self) -> None: + """ + Signal to flush the audio buffer and force finalize partial transcriptions. + Use this to force processing of any remaining audio that hasn't been + transcribed yet. + """ + message = SttFlushSignal() + self._send_model(message) + + def recv(self) -> SpeechToTextStreamingSocketClientResponse: + """ + Receive a message from the websocket connection. + """ + data = self._websocket.recv() + data = json.loads(data) if isinstance(data, str) else data + return parse_obj_as( + SpeechToTextStreamingSocketClientResponse, data + ) # type: ignore + + def _send_speech_to_text_streaming_audio_message( + self, message: AudioMessage + ) -> None: + """ + Send a message to the websocket connection. + The message will be sent as a AudioMessage. + """ + self._send_model(message) + + def _send(self, data: typing.Any) -> None: + """ + Send a message to the websocket connection. + """ + if isinstance(data, dict): + data = json.dumps(data) + self._websocket.send(data) + + def _send_model(self, data: typing.Any) -> None: + """ + Send a Pydantic model to the websocket connection. + """ + self._send(data.dict()) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9df92db5d8ff2dfc0b2ea9de0fc793b86b956208 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__init__.py @@ -0,0 +1,56 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .speech_to_text_streaming_flush_signal import SpeechToTextStreamingFlushSignal + from .speech_to_text_streaming_high_vad_sensitivity import SpeechToTextStreamingHighVadSensitivity + from .speech_to_text_streaming_input_audio_codec import SpeechToTextStreamingInputAudioCodec + from .speech_to_text_streaming_language_code import SpeechToTextStreamingLanguageCode + from .speech_to_text_streaming_mode import SpeechToTextStreamingMode + from .speech_to_text_streaming_model import SpeechToTextStreamingModel + from .speech_to_text_streaming_vad_signals import SpeechToTextStreamingVadSignals +_dynamic_imports: typing.Dict[str, str] = { + "SpeechToTextStreamingFlushSignal": ".speech_to_text_streaming_flush_signal", + "SpeechToTextStreamingHighVadSensitivity": ".speech_to_text_streaming_high_vad_sensitivity", + "SpeechToTextStreamingInputAudioCodec": ".speech_to_text_streaming_input_audio_codec", + "SpeechToTextStreamingLanguageCode": ".speech_to_text_streaming_language_code", + "SpeechToTextStreamingMode": ".speech_to_text_streaming_mode", + "SpeechToTextStreamingModel": ".speech_to_text_streaming_model", + "SpeechToTextStreamingVadSignals": ".speech_to_text_streaming_vad_signals", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "SpeechToTextStreamingFlushSignal", + "SpeechToTextStreamingHighVadSensitivity", + "SpeechToTextStreamingInputAudioCodec", + "SpeechToTextStreamingLanguageCode", + "SpeechToTextStreamingMode", + "SpeechToTextStreamingModel", + "SpeechToTextStreamingVadSignals", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40416e6013534409402449f59aba92a1fd9755e2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_flush_signal.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_flush_signal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa386c77cd4d960dbc67598f3b4e966c30ad6f9f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_flush_signal.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_high_vad_sensitivity.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_high_vad_sensitivity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44c16a72b23ed660721b822782f2397726e01d00 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_high_vad_sensitivity.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_input_audio_codec.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_input_audio_codec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..887a365fbc7cbcc88a6a23d9b503ec124a3e905a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_input_audio_codec.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_language_code.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_language_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bffc965e5a47f22a3b8bb96856949f029b090a7 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_language_code.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_mode.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61f552fb47bb33a29b53af2eed84fc1f40c40ffe Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_mode.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_model.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fda4df2b629126d11f9184bdc04b53ae325def23 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_model.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_vad_signals.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_vad_signals.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8aab606d318d1270ff2468f5d940a28c8bf3067d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/__pycache__/speech_to_text_streaming_vad_signals.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_flush_signal.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_flush_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..964a9ba344df1692ff3639dcfb9181e25e2641d8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_flush_signal.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextStreamingFlushSignal = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_high_vad_sensitivity.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_high_vad_sensitivity.py new file mode 100644 index 0000000000000000000000000000000000000000..4ca6ca265dd4cfaccdbf3ce7f37e975eeed6ba3b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_high_vad_sensitivity.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextStreamingHighVadSensitivity = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_input_audio_codec.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_input_audio_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..f16a27ed151d4c719653297189334163ae407c31 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_input_audio_codec.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextStreamingInputAudioCodec = typing.Union[ + typing.Literal["wav", "pcm_s16le", "pcm_l16", "pcm_raw"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_language_code.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_language_code.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3b3d1af985b91662a52af3ec51a8d925df7725 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_language_code.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextStreamingLanguageCode = typing.Union[ + typing.Literal[ + "unknown", + "en-IN", + "hi-IN", + "bn-IN", + "gu-IN", + "kn-IN", + "ml-IN", + "mr-IN", + "od-IN", + "pa-IN", + "ta-IN", + "te-IN", + "as-IN", + "ur-IN", + "ne-IN", + "kok-IN", + "ks-IN", + "sd-IN", + "sa-IN", + "sat-IN", + "mni-IN", + "brx-IN", + "mai-IN", + "doi-IN", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_mode.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..37ffa923f08379d1e3d2175b20b66cdbed66de98 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_mode.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextStreamingMode = typing.Union[ + typing.Literal["transcribe", "translate", "verbatim", "translit", "codemix"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_model.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_model.py new file mode 100644 index 0000000000000000000000000000000000000000..23fbb3a4a76729709b4637ab8490e1095757477f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextStreamingModel = typing.Union[typing.Literal["saaras:v3", "saarika:v2.5"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_vad_signals.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_vad_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..e4bc0e0b5c6e9dc8e5f5a45e861064f6f4b8c76a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_streaming/types/speech_to_text_streaming_vad_signals.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextStreamingVadSignals = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1049774215941a26a166821d2aedbb3e5cb7b7b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb1d40b9388ae81b1255675b934dc4d66b2bb60c Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/job.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/job.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97b4d1fdf8a73420a4d13ef6717c2e17e3f54f46 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/job.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2adafd637dc71e22062f09b9e991ca1969050eb8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/client.py new file mode 100644 index 0000000000000000000000000000000000000000..281b1b7ae7e67c66937fc60da275efc5c2e3845d --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/client.py @@ -0,0 +1,631 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..requests.bulk_job_callback import BulkJobCallbackParams +from ..requests.speech_to_text_translate_job_parameters import SpeechToTextTranslateJobParametersParams +from ..types.bulk_job_init_response import BulkJobInitResponse +from ..types.files_download_response import FilesDownloadResponse +from ..types.files_upload_response import FilesUploadResponse +from ..types.job_status_response import JobStatusResponse +from ..types.speech_to_text_translate_model import SpeechToTextTranslateModel +from .raw_client import AsyncRawSpeechToTextTranslateJobClient, RawSpeechToTextTranslateJobClient +from .job import AsyncSpeechToTextTranslateJob, SpeechToTextTranslateJob + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class SpeechToTextTranslateJobClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawSpeechToTextTranslateJobClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawSpeechToTextTranslateJobClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawSpeechToTextTranslateJobClient + """ + return self._raw_client + + def initialise( + self, + *, + job_parameters: SpeechToTextTranslateJobParametersParams, + ptu_id: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> BulkJobInitResponse: + """ + Get a job uuid, and storage folder details for speech to text tranlsate bulk job v1 + + Parameters + ---------- + job_parameters : SpeechToTextTranslateJobParametersParams + Job Parameters for the bulk job + + ptu_id : typing.Optional[int] + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + BulkJobInitResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_translate_job.initialise( + job_parameters={}, + ) + """ + _response = self._raw_client.initialise( + job_parameters=job_parameters, ptu_id=ptu_id, callback=callback, request_options=request_options + ) + return _response.data + + def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> JobStatusResponse: + """ + Get the status of a speech to text translate bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_translate_job.get_status( + job_id="job_id", + ) + """ + _response = self._raw_client.get_status(job_id, request_options=request_options) + return _response.data + + def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> JobStatusResponse: + """ + Start a speech to text translate bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_translate_job.start( + job_id="job_id", + ) + """ + _response = self._raw_client.start(job_id, ptu_id=ptu_id, request_options=request_options) + return _response.data + + def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesUploadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesUploadResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_translate_job.get_upload_links( + job_id="job_id", + files=["files"], + ) + """ + _response = self._raw_client.get_upload_links( + job_id=job_id, files=files, ptu_id=ptu_id, request_options=request_options + ) + return _response.data + + def get_download_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesDownloadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesDownloadResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.speech_to_text_translate_job.get_download_links( + job_id="job_id", + files=["files"], + ) + """ + _response = self._raw_client.get_download_links( + job_id=job_id, files=files, ptu_id=ptu_id, request_options=request_options + ) + return _response.data + + def create_job( + self, + model: SpeechToTextTranslateModel = "saaras:v2.5", + with_diarization: bool = False, + prompt: typing.Optional[str] = None, + num_speakers: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> SpeechToTextTranslateJob: + """ + Create a new Speech-to-Text-Translate bulk job. + + Parameters + ---------- + model : typing.Optional[SpeechToTextTranslateModel], default="saaras:v2.5" + The model to use for speech-to-text translation. + + with_diarization : typing.Optional[bool], default=False + Whether to enable speaker diarization (i.e., distinguishing who is speaking). + + prompt : typing.Optional[str], default=None + An optional prompt to guide the transcription and translation model. + + num_speakers : typing.Optional[int], default=None + The number of distinct speakers in the input audio, if known. + + callback : typing.Optional[BulkJobCallbackParams], default=OMIT + Optional callback configuration to receive job completion events via webhook. + + request_options : typing.Optional[RequestOptions], default=None + Optional configuration for request timeout, retries, etc. + + Returns + ------- + SpeechToTextTranslateJob + A handle to the newly created Speech-to-Text-Translate job. + """ + response = self.initialise( + job_parameters=SpeechToTextTranslateJobParametersParams( + prompt=prompt, # type: ignore[typeddict-item] + model=model, + with_diarization=with_diarization, + num_speakers=num_speakers, # type: ignore[typeddict-item] + ), + callback=callback, + request_options=request_options, + ) + return SpeechToTextTranslateJob(job_id=response.job_id, client=self) + + def get_job(self, job_id: str) -> SpeechToTextTranslateJob: + """ + Get an existing Speech-to-Text-Translate job handle by job ID. + + Parameters + ---------- + job_id : str + The job ID of the previously created Speech-to-Text-Translate job. + + Returns + ------- + SpeechToTextTranslateJob + A job handle which can be used to check status or retrieve results. + """ + return SpeechToTextTranslateJob(job_id=job_id, client=self) + + + +class AsyncSpeechToTextTranslateJobClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawSpeechToTextTranslateJobClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawSpeechToTextTranslateJobClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawSpeechToTextTranslateJobClient + """ + return self._raw_client + + async def initialise( + self, + *, + job_parameters: SpeechToTextTranslateJobParametersParams, + ptu_id: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> BulkJobInitResponse: + """ + Get a job uuid, and storage folder details for speech to text tranlsate bulk job v1 + + Parameters + ---------- + job_parameters : SpeechToTextTranslateJobParametersParams + Job Parameters for the bulk job + + ptu_id : typing.Optional[int] + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + BulkJobInitResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_translate_job.initialise( + job_parameters={}, + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.initialise( + job_parameters=job_parameters, ptu_id=ptu_id, callback=callback, request_options=request_options + ) + return _response.data + + async def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> JobStatusResponse: + """ + Get the status of a speech to text translate bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_translate_job.get_status( + job_id="job_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_status(job_id, request_options=request_options) + return _response.data + + async def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> JobStatusResponse: + """ + Start a speech to text translate bulk job V1 + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + JobStatusResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_translate_job.start( + job_id="job_id", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.start(job_id, ptu_id=ptu_id, request_options=request_options) + return _response.data + + async def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesUploadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesUploadResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_translate_job.get_upload_links( + job_id="job_id", + files=["files"], + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_upload_links( + job_id=job_id, files=files, ptu_id=ptu_id, request_options=request_options + ) + return _response.data + + async def get_download_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> FilesDownloadResponse: + """ + Start a speech to text bulk job V1 + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + FilesDownloadResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.speech_to_text_translate_job.get_download_links( + job_id="job_id", + files=["files"], + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.get_download_links( + job_id=job_id, files=files, ptu_id=ptu_id, request_options=request_options + ) + return _response.data + + async def create_job( + self, + model: SpeechToTextTranslateModel = "saaras:v2.5", + with_diarization: bool = False, + prompt: typing.Optional[str] = None, + num_speakers: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> "AsyncSpeechToTextTranslateJob": + """ + Create a new Speech-to-Text-Translate bulk job. + + Parameters + ---------- + model : typing.Optional[SpeechToTextTranslateModel], default="saaras:v2.5" + The model to use for speech-to-text translation. + + with_diarization : typing.Optional[bool], default=False + Whether to enable speaker diarization (i.e., distinguishing who is speaking). + + prompt : typing.Optional[str], default=None + An optional prompt to guide the transcription and translation model. + + num_speakers : typing.Optional[int], default=None + The number of distinct speakers in the input audio, if known. + + callback : typing.Optional[BulkJobCallbackParams], default=OMIT + Optional callback configuration to receive job completion events via webhook. + + request_options : typing.Optional[RequestOptions], default=None + Optional configuration for request timeout, retries, etc. + + Returns + ------- + AsyncSpeechToTextTranslateJob + A handle to the newly created job. + """ + response = await self.initialise( + job_parameters=SpeechToTextTranslateJobParametersParams( + prompt=prompt, # type: ignore[typeddict-item] + model=model, + with_diarization=with_diarization, # type: ignore[typeddict-item] + num_speakers=num_speakers, # type: ignore[typeddict-item] + ), + callback=callback, + request_options=request_options, + ) + return AsyncSpeechToTextTranslateJob(job_id=response.job_id, client=self) + + async def get_job(self, job_id: str) -> "AsyncSpeechToTextTranslateJob": + """ + Get an existing Speech-to-Text-Translate job handle by job ID. + + Parameters + ---------- + job_id : str + The job ID of the previously created speech-to-text-translate job. + + Returns + ------- + AsyncSpeechToTextTranslateJob + A job handle which can be used to check status or retrieve results. + """ + return AsyncSpeechToTextTranslateJob(job_id=job_id, client=self) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/job.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/job.py new file mode 100644 index 0000000000000000000000000000000000000000..f47d2dd6cad8d26f8873fba45535f9d06b2b6c1e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/job.py @@ -0,0 +1,603 @@ +import asyncio +import mimetypes +import os +import time +import typing +import httpx +from http import HTTPStatus + +from ..types import JobStatusResponse + +if typing.TYPE_CHECKING: + from .client import ( + AsyncSpeechToTextTranslateJobClient, + SpeechToTextTranslateJobClient, + ) + + +class AsyncSpeechToTextTranslateJob: + def __init__( + self, + job_id: str, + client: "AsyncSpeechToTextTranslateJobClient", + ): + """ + Initialise the asynchronous speech-to-text-translate-translate job. + + Parameters + ---------- + job_id : str + The unique job identifier returned from a previous job initialisation. + + client : AsyncSpeechToTextTranslateJobClient + The async client instance used to create the job. + + !!! important + This must be the **same client instance** that was used to initialise + the job originally, as it contains the subscription key and configuration + required to authenticate and manage the job. + + """ + self._job_id = job_id + self._client = client + + @property + def job_id(self) -> str: + """ + Returns the job ID associated with this job instance. + + Returns + ------- + str + """ + return self._job_id + + async def upload_files( + self, file_paths: typing.Sequence[str], timeout: float = 60.0 + ) -> bool: + """ + Upload input audio files for the speech-to-text-translate job. + + Parameters + ---------- + file_paths : Sequence[str] + List of full paths to local audio files. + + timeout : float, optional + The maximum time to wait for the upload to complete (in seconds), + by default 60.0 + Returns + ------- + bool + True if all files are uploaded successfully. + """ + upload_links = await self._client.get_upload_links( + job_id=self._job_id, + files=[os.path.basename(p) for p in file_paths], + ) + client_timeout = httpx.Timeout(timeout=timeout) + async with httpx.AsyncClient(timeout=client_timeout) as session: + for path in file_paths: + file_name = os.path.basename(path) + url = upload_links.upload_urls[file_name].file_url + with open(path, "rb") as f: + response = await session.put( + url, + content=f.read(), + headers={ + "x-ms-blob-type": "BlockBlob", + "Content-Type": "audio/wav", + }, + ) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Upload failed for {file_name}: {response.status_code}" + ) + return True + + async def wait_until_complete( + self, poll_interval: int = 5, timeout: int = 600 + ) -> JobStatusResponse: + """ + Polls job status until it completes or fails. + + Parameters + ---------- + poll_interval : int, optional + Time in seconds between polling attempts (default is 5). + + timeout : int, optional + Maximum time to wait for completion in seconds (default is 600). + + Returns + ------- + JobStatusResponse + Final job status. + + Raises + ------ + TimeoutError + If the job does not complete within the given timeout. + """ + start = asyncio.get_event_loop().time() + while True: + status = await self.get_status() + state = status.job_state.lower() + if state in {"completed", "failed"}: + return status + if asyncio.get_event_loop().time() - start > timeout: + raise TimeoutError( + f"Job {self._job_id} did not complete within {timeout} seconds." + ) + await asyncio.sleep(poll_interval) + + async def get_output_mappings(self) -> typing.List[typing.Dict[str, str]]: + """ + Get the mapping of input files to their corresponding output files. + + Returns + ------- + List[Dict[str, str]] + List of mappings with keys 'input_file' and 'output_file'. + """ + job_status = await self.get_status() + return [ + { + "input_file": detail.inputs[0].file_name, + "output_file": detail.outputs[0].file_name, + } + for detail in (job_status.job_details or []) + if detail.inputs and detail.outputs and detail.state == "Success" + ] + + async def get_file_results( + self, + ) -> typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]]: + """ + Get detailed results for each file in the batch job. + + Returns + ------- + Dict[str, List[Dict[str, Any]]] + Dictionary with 'successful' and 'failed' keys, each containing a list of file details. + Each file detail includes: + - 'file_name': Name of the input file + - 'status': Status of processing ('Success' or 'Failed') + - 'error_message': Error message if failed (None if successful) + - 'output_file': Name of output file if successful (None if failed) + """ + job_status = await self.get_status() + results: typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]] = { + "successful": [], + "failed": [], + } + + for detail in job_status.job_details or []: + # Check for empty lists explicitly + if not detail.inputs or len(detail.inputs) == 0: + continue + + try: + file_info = { + "file_name": detail.inputs[0].file_name, + "status": detail.state, + "error_message": detail.error_message, + "output_file": ( + detail.outputs[0].file_name + if detail.outputs and len(detail.outputs) > 0 + else None + ), + } + + if detail.state == "Success": + results["successful"].append(file_info) + else: + results["failed"].append(file_info) + except (IndexError, AttributeError): + # Skip malformed job details + continue + + return results + + async def download_outputs(self, output_dir: str) -> bool: + """ + Download output files to the specified directory. + + Parameters + ---------- + output_dir : str + Local directory where outputs will be saved. + + Returns + ------- + bool + True if all files downloaded successfully. + + Raises + ------ + RuntimeError + If a file fails to download. + """ + mappings = await self.get_output_mappings() + file_names = [m["output_file"] for m in mappings] + download_links = await self._client.get_download_links( + job_id=self._job_id, files=file_names + ) + + os.makedirs(output_dir, exist_ok=True) + async with httpx.AsyncClient() as session: + for m in mappings: + url = download_links.download_urls[m["output_file"]].file_url + response = await session.get(url) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Download failed for {m['output_file']}: {response.status_code}" + ) + output_path = os.path.join(output_dir, f"{m['input_file']}.json") + with open(output_path, "wb") as f: + f.write(response.content) + return True + + async def get_status(self) -> JobStatusResponse: + """ + Retrieve the current status of the job. + + Returns + ------- + JobStatusResponse + """ + return await self._client.get_status(self._job_id) + + async def start(self) -> JobStatusResponse: + """ + Start the speech-to-text-translate job processing. + + Returns + ------- + JobStatusResponse + """ + return await self._client.start(job_id=self._job_id) + + async def exists(self) -> bool: + """ + Check if the job exists in the system. + + Returns + ------- + bool + """ + try: + await self.get_status() + return True + except httpx.HTTPStatusError: + return False + + async def is_complete(self) -> bool: + """ + Check if the job is either completed or failed. + + Returns + ------- + bool + """ + state = (await self.get_status()).job_state.lower() + return state in {"completed", "failed"} + + async def is_successful(self) -> bool: + """ + Check if the job completed successfully. + + Returns + ------- + bool + """ + return (await self.get_status()).job_state.lower() == "completed" + + async def is_failed(self) -> bool: + """ + Check if the job has failed. + + Returns + ------- + bool + """ + return (await self.get_status()).job_state.lower() == "failed" + + +class SpeechToTextTranslateJob: + def __init__(self, job_id: str, client: "SpeechToTextTranslateJobClient"): + """ + Initialise the synchronous speech-to-text-translate job. + + Parameters + ---------- + job_id : str + The unique job identifier returned from a previous job initialisation. + + client : SpeechToTextTranslateJobClient + The client instance used to create the job. + + !!! important + This must be the **same client instance** that was used to initialise + the job originally, as it contains the subscription key and configuration + required to authenticate and manage the job. + + """ + self._job_id = job_id + self._client = client + + @property + def job_id(self) -> str: + """ + Returns the job ID associated with this job instance. + + Returns + ------- + str + """ + return self._job_id + + def upload_files( + self, file_paths: typing.Sequence[str], timeout: float = 60.0 + ) -> bool: + """ + Upload input audio files for the speech-to-text-translate job. + + Parameters + ---------- + file_paths : Sequence[str] + List of full paths to local audio files. + + timeout : float, optional + The maximum time to wait for the upload to complete (in seconds), + by default 60.0 + + Returns + ------- + bool + True if all files are uploaded successfully. + """ + upload_links = self._client.get_upload_links( + job_id=self._job_id, files=[os.path.basename(p) for p in file_paths] + ) + client_timeout = httpx.Timeout(timeout=timeout) + with httpx.Client(timeout=client_timeout) as client: + for path in file_paths: + file_name = os.path.basename(path) + url = upload_links.upload_urls[file_name].file_url + content_type, _ = mimetypes.guess_type(path) + if content_type is None: + content_type = "audio/wav" + with open(path, "rb") as f: + response = client.put( + url, + content=f, + headers={ + "x-ms-blob-type": "BlockBlob", + "Content-Type": content_type, + }, + ) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Upload failed for {file_name}: {response.status_code}" + ) + return True + + def wait_until_complete( + self, poll_interval: int = 5, timeout: int = 600 + ) -> JobStatusResponse: + """ + Polls job status until it completes or fails. + + Parameters + ---------- + poll_interval : int, optional + Time in seconds between polling attempts (default is 5). + + timeout : int, optional + Maximum time to wait for completion in seconds (default is 600). + + Returns + ------- + JobStatusResponse + Final job status. + + Raises + ------ + TimeoutError + If the job does not complete within the given timeout. + """ + start = time.monotonic() + while True: + status = self.get_status() + state = status.job_state.lower() + if state in {"completed", "failed"}: + return status + if time.monotonic() - start > timeout: + raise TimeoutError( + f"Job {self._job_id} did not complete within {timeout} seconds." + ) + time.sleep(poll_interval) + + def get_output_mappings(self) -> typing.List[typing.Dict[str, str]]: + """ + Get the mapping of input files to their corresponding output files. + + Returns + ------- + List[Dict[str, str]] + List of mappings with keys 'input_file' and 'output_file'. + """ + job_status = self.get_status() + return [ + { + "input_file": detail.inputs[0].file_name, + "output_file": detail.outputs[0].file_name, + } + for detail in (job_status.job_details or []) + if detail.inputs and detail.outputs and detail.state == "Success" + ] + + def get_file_results( + self, + ) -> typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]]: + """ + Get detailed results for each file in the batch job. + + Returns + ------- + Dict[str, List[Dict[str, Any]]] + Dictionary with 'successful' and 'failed' keys, each containing a list of file details. + Each file detail includes: + - 'file_name': Name of the input file + - 'status': Status of processing ('Success' or 'Failed') + - 'error_message': Error message if failed (None if successful) + - 'output_file': Name of output file if successful (None if failed) + """ + job_status = self.get_status() + results: typing.Dict[str, typing.List[typing.Dict[str, typing.Any]]] = { + "successful": [], + "failed": [], + } + + for detail in job_status.job_details or []: + # Check for empty lists explicitly + if not detail.inputs or len(detail.inputs) == 0: + continue + + try: + file_info = { + "file_name": detail.inputs[0].file_name, + "status": detail.state, + "error_message": detail.error_message, + "output_file": ( + detail.outputs[0].file_name + if detail.outputs and len(detail.outputs) > 0 + else None + ), + } + + if detail.state == "Success": + results["successful"].append(file_info) + else: + results["failed"].append(file_info) + except (IndexError, AttributeError): + # Skip malformed job details + continue + + return results + + def download_outputs(self, output_dir: str) -> bool: + """ + Download output files to the specified directory. + + Parameters + ---------- + output_dir : str + Local directory where outputs will be saved. + + Returns + ------- + bool + True if all files downloaded successfully. + + Raises + ------ + RuntimeError + If a file fails to download. + """ + mappings = self.get_output_mappings() + file_names = [m["output_file"] for m in mappings] + download_links = self._client.get_download_links( + job_id=self._job_id, files=file_names + ) + + os.makedirs(output_dir, exist_ok=True) + with httpx.Client() as client: + for m in mappings: + url = download_links.download_urls[m["output_file"]].file_url + response = client.get(url) + if ( + response.status_code > HTTPStatus.IM_USED + or response.status_code < HTTPStatus.OK + ): + raise RuntimeError( + f"Download failed for {m['output_file']}: {response.status_code}" + ) + output_path = os.path.join(output_dir, f"{m['input_file']}.json") + with open(output_path, "wb") as f: + f.write(response.content) + return True + + def get_status(self) -> JobStatusResponse: + """ + Retrieve the current status of the job. + + Returns + ------- + JobStatusResponse + """ + return self._client.get_status(self._job_id) + + def start(self) -> JobStatusResponse: + """ + Start the speech-to-text-translate job processing. + + Returns + ------- + JobStatusResponse + """ + return self._client.start(job_id=self._job_id) + + def exists(self) -> bool: + """ + Check if the job exists in the system. + + Returns + ------- + bool + """ + try: + self.get_status() + return True + except httpx.HTTPStatusError: + return False + + def is_complete(self) -> bool: + """ + Check if the job is either completed or failed. + + Returns + ------- + bool + """ + return self.get_status().job_state.lower() in {"completed", "failed"} + + def is_successful(self) -> bool: + """ + Check if the job completed successfully. + + Returns + ------- + bool + """ + return self.get_status().job_state.lower() == "completed" + + def is_failed(self) -> bool: + """ + Check if the job has failed. + + Returns + ------- + bool + """ + return self.get_status().job_state.lower() == "failed" diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..0d65d81e74607e8d3470423dca80c048b1ee1cba --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_job/raw_client.py @@ -0,0 +1,1245 @@ +# 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.http_response import AsyncHttpResponse, HttpResponse +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..core.serialization import convert_and_respect_annotation_metadata +from ..errors.bad_request_error import BadRequestError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.service_unavailable_error import ServiceUnavailableError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..errors.unprocessable_entity_error import UnprocessableEntityError +from ..requests.bulk_job_callback import BulkJobCallbackParams +from ..requests.speech_to_text_translate_job_parameters import SpeechToTextTranslateJobParametersParams +from ..types.bulk_job_init_response import BulkJobInitResponse +from ..types.files_download_response import FilesDownloadResponse +from ..types.files_upload_response import FilesUploadResponse +from ..types.job_status_response import JobStatusResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawSpeechToTextTranslateJobClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def initialise( + self, + *, + job_parameters: SpeechToTextTranslateJobParametersParams, + ptu_id: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[BulkJobInitResponse]: + """ + Create a new speech to text translate bulk job and receive a job UUID and storage folder details for processing multiple audio files with translation. Set `job_parameters.input_audio_codec` when uploads are raw PCM (`pcm_s16le`, `pcm_l16`, or `pcm_raw`); the API auto-detects other formats. PCM must be 16 kHz. + + Parameters + ---------- + job_parameters : SpeechToTextTranslateJobParametersParams + Job Parameters for the bulk job + + ptu_id : typing.Optional[int] + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[BulkJobInitResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text-translate/job/v1", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + json={ + "job_parameters": convert_and_respect_annotation_metadata( + object_=job_parameters, annotation=SpeechToTextTranslateJobParametersParams, direction="write" + ), + "callback": convert_and_respect_annotation_metadata( + object_=callback, annotation=BulkJobCallbackParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + BulkJobInitResponse, + parse_obj_as( + type_=BulkJobInitResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[JobStatusResponse]: + """ + Retrieve the current status and details of a speech to text translate bulk job, including progress and file-level information. + + **Rate Limiting Best Practice:** To prevent rate limit errors and ensure optimal server performance, we recommend implementing a minimum 5-millisecond delay between consecutive status polling requests. This helps maintain system stability while still providing timely status updates. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[JobStatusResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"speech-to-text-translate/job/v1/{jsonable_encoder(job_id)}/status", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[JobStatusResponse]: + """ + Start processing a speech to text translate bulk job after all audio files have been uploaded + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[JobStatusResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + f"speech-to-text-translate/job/v1/{jsonable_encoder(job_id)}/start", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[FilesUploadResponse]: + """ + Generate presigned upload URLs for audio files that will be processed in a speech to text translate bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[FilesUploadResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text-translate/job/v1/upload-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesUploadResponse, + parse_obj_as( + type_=FilesUploadResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def get_download_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[FilesDownloadResponse]: + """ + Generate presigned download URLs for the translated transcription output files of a completed speech to text translate bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[FilesDownloadResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "speech-to-text-translate/job/v1/download-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesDownloadResponse, + parse_obj_as( + type_=FilesDownloadResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + +class AsyncRawSpeechToTextTranslateJobClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def initialise( + self, + *, + job_parameters: SpeechToTextTranslateJobParametersParams, + ptu_id: typing.Optional[int] = None, + callback: typing.Optional[BulkJobCallbackParams] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[BulkJobInitResponse]: + """ + Create a new speech to text translate bulk job and receive a job UUID and storage folder details for processing multiple audio files with translation. Set `job_parameters.input_audio_codec` when uploads are raw PCM (`pcm_s16le`, `pcm_l16`, or `pcm_raw`); the API auto-detects other formats. PCM must be 16 kHz. + + Parameters + ---------- + job_parameters : SpeechToTextTranslateJobParametersParams + Job Parameters for the bulk job + + ptu_id : typing.Optional[int] + + callback : typing.Optional[BulkJobCallbackParams] + Parameters for callback URL + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[BulkJobInitResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text-translate/job/v1", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + json={ + "job_parameters": convert_and_respect_annotation_metadata( + object_=job_parameters, annotation=SpeechToTextTranslateJobParametersParams, direction="write" + ), + "callback": convert_and_respect_annotation_metadata( + object_=callback, annotation=BulkJobCallbackParams, direction="write" + ), + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + BulkJobInitResponse, + parse_obj_as( + type_=BulkJobInitResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_status( + self, job_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[JobStatusResponse]: + """ + Retrieve the current status and details of a speech to text translate bulk job, including progress and file-level information. + + **Rate Limiting Best Practice:** To prevent rate limit errors and ensure optimal server performance, we recommend implementing a minimum 5-millisecond delay between consecutive status polling requests. This helps maintain system stability while still providing timely status updates. + + Parameters + ---------- + job_id : str + The unique identifier of the job + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[JobStatusResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"speech-to-text-translate/job/v1/{jsonable_encoder(job_id)}/status", + base_url=self._client_wrapper.get_environment().base, + method="GET", + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def start( + self, + job_id: str, + *, + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[JobStatusResponse]: + """ + Start processing a speech to text translate bulk job after all audio files have been uploaded + + Parameters + ---------- + job_id : str + The unique identifier of the job + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[JobStatusResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + f"speech-to-text-translate/job/v1/{jsonable_encoder(job_id)}/start", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + JobStatusResponse, + parse_obj_as( + type_=JobStatusResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_upload_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[FilesUploadResponse]: + """ + Generate presigned upload URLs for audio files that will be processed in a speech to text translate bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[FilesUploadResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text-translate/job/v1/upload-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesUploadResponse, + parse_obj_as( + type_=FilesUploadResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def get_download_links( + self, + *, + job_id: str, + files: typing.Sequence[str], + ptu_id: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[FilesDownloadResponse]: + """ + Generate presigned download URLs for the translated transcription output files of a completed speech to text translate bulk job + + Parameters + ---------- + job_id : str + + files : typing.Sequence[str] + + ptu_id : typing.Optional[int] + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[FilesDownloadResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "speech-to-text-translate/job/v1/download-files", + base_url=self._client_wrapper.get_environment().base, + method="POST", + params={ + "ptu_id": ptu_id, + }, + json={ + "job_id": job_id, + "files": files, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + FilesDownloadResponse, + parse_obj_as( + type_=FilesDownloadResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 503: + raise ServiceUnavailableError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d883abaecd59bb126f534dcc85ebd0cb5e21253 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__init__.py @@ -0,0 +1,55 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .types import ( + SpeechToTextTranslateStreamingFlushSignal, + SpeechToTextTranslateStreamingHighVadSensitivity, + SpeechToTextTranslateStreamingInputAudioCodec, + SpeechToTextTranslateStreamingMode, + SpeechToTextTranslateStreamingModel, + SpeechToTextTranslateStreamingVadSignals, + ) +_dynamic_imports: typing.Dict[str, str] = { + "SpeechToTextTranslateStreamingFlushSignal": ".types", + "SpeechToTextTranslateStreamingHighVadSensitivity": ".types", + "SpeechToTextTranslateStreamingInputAudioCodec": ".types", + "SpeechToTextTranslateStreamingMode": ".types", + "SpeechToTextTranslateStreamingModel": ".types", + "SpeechToTextTranslateStreamingVadSignals": ".types", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "SpeechToTextTranslateStreamingFlushSignal", + "SpeechToTextTranslateStreamingHighVadSensitivity", + "SpeechToTextTranslateStreamingInputAudioCodec", + "SpeechToTextTranslateStreamingMode", + "SpeechToTextTranslateStreamingModel", + "SpeechToTextTranslateStreamingVadSignals", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c01858fbd99f30f2f93d3d0f4c7d3b7473736e06 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e2f26ef6b2c12d040c660edb03389ce0114c22b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bdca7cd9685345a1f2d371d936d6b4dc9135724 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/socket_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/socket_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2b1849f40edb41e27b7eb517c70edbc71c67a53 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/__pycache__/socket_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/client.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8fbee1412f9427f1d65aaef5a1c9bf337601ba --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/client.py @@ -0,0 +1,417 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +import urllib.parse +from contextlib import asynccontextmanager, contextmanager + +import websockets.sync.client as websockets_sync_client +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.jsonable_encoder import jsonable_encoder +from ..core.query_encoder import encode_query +from ..core.remove_none_from_dict import remove_none_from_dict +from ..core.request_options import RequestOptions +from ..core.websocket_compat import InvalidWebSocketStatus, get_status_code +from .raw_client import AsyncRawSpeechToTextTranslateStreamingClient, RawSpeechToTextTranslateStreamingClient +from .socket_client import AsyncSpeechToTextTranslateStreamingSocketClient, SpeechToTextTranslateStreamingSocketClient +from .types.speech_to_text_translate_streaming_flush_signal import SpeechToTextTranslateStreamingFlushSignal +from .types.speech_to_text_translate_streaming_high_vad_sensitivity import ( + SpeechToTextTranslateStreamingHighVadSensitivity, +) +from .types.speech_to_text_translate_streaming_input_audio_codec import SpeechToTextTranslateStreamingInputAudioCodec +from .types.speech_to_text_translate_streaming_mode import SpeechToTextTranslateStreamingMode +from .types.speech_to_text_translate_streaming_model import SpeechToTextTranslateStreamingModel +from .types.speech_to_text_translate_streaming_vad_signals import SpeechToTextTranslateStreamingVadSignals + +try: + from websockets.legacy.client import connect as websockets_client_connect # type: ignore +except ImportError: + from websockets import connect as websockets_client_connect # type: ignore + + +class SpeechToTextTranslateStreamingClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawSpeechToTextTranslateStreamingClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawSpeechToTextTranslateStreamingClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawSpeechToTextTranslateStreamingClient + """ + return self._raw_client + + @contextmanager + def connect( + self, + *, + model: typing.Optional[SpeechToTextTranslateStreamingModel] = None, + mode: typing.Optional[SpeechToTextTranslateStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextTranslateStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextTranslateStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[SpeechToTextTranslateStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming with English translation. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + model : typing.Optional[SpeechToTextTranslateStreamingModel] + Model to be used for speech to text translation. + + - **saaras:v3** (default, recommended): State-of-the-art translation model that translates audio from any spoken Indic language to English with flexible output formats via the `mode` parameter. + + - **saaras:v2.5** (legacy): Translation model that translates audio from any spoken Indic language to English. Kept for backward compatibility. + - Example: Hindi audio → English text output + + mode : typing.Optional[SpeechToTextTranslateStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + - **translate** (default): Translates speech from any supported Indic language to English. + - Example: Hindi audio → English text output + + - **transcribe**: Standard transcription in the original language. + + - **verbatim**: Exact word-for-word transcription without normalization. + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextTranslateStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextTranslateStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription and translation + + input_audio_codec : typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextTranslateStreamingSocketClient + """ + ws_url = self._raw_client._client_wrapper.get_environment().production + "/speech-to-text-translate/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._raw_client._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol: + yield SpeechToTextTranslateStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) + + +class AsyncSpeechToTextTranslateStreamingClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawSpeechToTextTranslateStreamingClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawSpeechToTextTranslateStreamingClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawSpeechToTextTranslateStreamingClient + """ + return self._raw_client + + @asynccontextmanager + async def connect( + self, + *, + model: typing.Optional[SpeechToTextTranslateStreamingModel] = None, + mode: typing.Optional[SpeechToTextTranslateStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextTranslateStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextTranslateStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[AsyncSpeechToTextTranslateStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming with English translation. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + model : typing.Optional[SpeechToTextTranslateStreamingModel] + Model to be used for speech to text translation. + + - **saaras:v3** (default, recommended): State-of-the-art translation model that translates audio from any spoken Indic language to English with flexible output formats via the `mode` parameter. + + - **saaras:v2.5** (legacy): Translation model that translates audio from any spoken Indic language to English. Kept for backward compatibility. + - Example: Hindi audio → English text output + + mode : typing.Optional[SpeechToTextTranslateStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + - **translate** (default): Translates speech from any supported Indic language to English. + - Example: Hindi audio → English text output + + - **transcribe**: Standard transcription in the original language. + + - **verbatim**: Exact word-for-word transcription without normalization. + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextTranslateStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextTranslateStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription and translation + + input_audio_codec : typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncSpeechToTextTranslateStreamingSocketClient + """ + ws_url = self._raw_client._client_wrapper.get_environment().production + "/speech-to-text-translate/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._raw_client._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + async with websockets_client_connect(ws_url, extra_headers=headers) as protocol: + yield AsyncSpeechToTextTranslateStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2590c03ae51c41d28cecadd96d06e87bc3d770aa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/raw_client.py @@ -0,0 +1,394 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +import urllib.parse +from contextlib import asynccontextmanager, contextmanager + +import websockets.sync.client as websockets_sync_client +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.jsonable_encoder import jsonable_encoder +from ..core.query_encoder import encode_query +from ..core.remove_none_from_dict import remove_none_from_dict +from ..core.request_options import RequestOptions +from ..core.websocket_compat import InvalidWebSocketStatus, get_status_code +from .socket_client import AsyncSpeechToTextTranslateStreamingSocketClient, SpeechToTextTranslateStreamingSocketClient +from .types.speech_to_text_translate_streaming_flush_signal import SpeechToTextTranslateStreamingFlushSignal +from .types.speech_to_text_translate_streaming_high_vad_sensitivity import ( + SpeechToTextTranslateStreamingHighVadSensitivity, +) +from .types.speech_to_text_translate_streaming_input_audio_codec import SpeechToTextTranslateStreamingInputAudioCodec +from .types.speech_to_text_translate_streaming_mode import SpeechToTextTranslateStreamingMode +from .types.speech_to_text_translate_streaming_model import SpeechToTextTranslateStreamingModel +from .types.speech_to_text_translate_streaming_vad_signals import SpeechToTextTranslateStreamingVadSignals + +try: + from websockets.legacy.client import connect as websockets_client_connect # type: ignore +except ImportError: + from websockets import connect as websockets_client_connect # type: ignore + + +class RawSpeechToTextTranslateStreamingClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + @contextmanager + def connect( + self, + *, + model: typing.Optional[SpeechToTextTranslateStreamingModel] = None, + mode: typing.Optional[SpeechToTextTranslateStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextTranslateStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextTranslateStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[SpeechToTextTranslateStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming with English translation. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + model : typing.Optional[SpeechToTextTranslateStreamingModel] + Model to be used for speech to text translation. + + - **saaras:v3** (default, recommended): State-of-the-art translation model that translates audio from any spoken Indic language to English with flexible output formats via the `mode` parameter. + + - **saaras:v2.5** (legacy): Translation model that translates audio from any spoken Indic language to English. Kept for backward compatibility. + - Example: Hindi audio → English text output + + mode : typing.Optional[SpeechToTextTranslateStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + - **translate** (default): Translates speech from any supported Indic language to English. + - Example: Hindi audio → English text output + + - **transcribe**: Standard transcription in the original language. + + - **verbatim**: Exact word-for-word transcription without normalization. + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextTranslateStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextTranslateStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription and translation + + input_audio_codec : typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SpeechToTextTranslateStreamingSocketClient + """ + ws_url = self._client_wrapper.get_environment().production + "/speech-to-text-translate/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol: + yield SpeechToTextTranslateStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) + + +class AsyncRawSpeechToTextTranslateStreamingClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + @asynccontextmanager + async def connect( + self, + *, + model: typing.Optional[SpeechToTextTranslateStreamingModel] = None, + mode: typing.Optional[SpeechToTextTranslateStreamingMode] = None, + sample_rate: typing.Optional[str] = None, + high_vad_sensitivity: typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] = None, + positive_speech_threshold: typing.Optional[str] = None, + negative_speech_threshold: typing.Optional[str] = None, + min_speech_frames: typing.Optional[str] = None, + first_turn_min_speech_frames: typing.Optional[str] = None, + negative_frames_count: typing.Optional[str] = None, + negative_frames_window: typing.Optional[str] = None, + start_speech_volume_threshold: typing.Optional[str] = None, + interrupt_min_speech_frames: typing.Optional[str] = None, + pre_speech_pad_frames: typing.Optional[str] = None, + num_initial_ignored_frames: typing.Optional[str] = None, + vad_signals: typing.Optional[SpeechToTextTranslateStreamingVadSignals] = None, + flush_signal: typing.Optional[SpeechToTextTranslateStreamingFlushSignal] = None, + input_audio_codec: typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[AsyncSpeechToTextTranslateStreamingSocketClient]: + """ + WebSocket channel for real-time speech to text streaming with English translation. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + Parameters + ---------- + model : typing.Optional[SpeechToTextTranslateStreamingModel] + Model to be used for speech to text translation. + + - **saaras:v3** (default, recommended): State-of-the-art translation model that translates audio from any spoken Indic language to English with flexible output formats via the `mode` parameter. + + - **saaras:v2.5** (legacy): Translation model that translates audio from any spoken Indic language to English. Kept for backward compatibility. + - Example: Hindi audio → English text output + + mode : typing.Optional[SpeechToTextTranslateStreamingMode] + Mode of operation. **Only applicable when using saaras:v3 model.** + + - **translate** (default): Translates speech from any supported Indic language to English. + - Example: Hindi audio → English text output + + - **transcribe**: Standard transcription in the original language. + + - **verbatim**: Exact word-for-word transcription without normalization. + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + + sample_rate : typing.Optional[str] + Audio sample rate for the WebSocket connection. When specified as a connection parameter, only 16kHz and 8kHz are supported. 8kHz is only available via this connection parameter. If not specified, defaults to 16kHz. + + high_vad_sensitivity : typing.Optional[SpeechToTextTranslateStreamingHighVadSensitivity] + Enable high VAD (Voice Activity Detection) sensitivity + + positive_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) above which a frame is considered speech. + Overrides the server default when provided. + + negative_speech_threshold : typing.Optional[str] + VAD probability threshold (0.0–1.0) below which a frame is considered silence. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + min_speech_frames : typing.Optional[str] + Minimum number of consecutive speech frames required to start a speech segment. + Overrides the server default when provided. + + first_turn_min_speech_frames : typing.Optional[str] + Minimum speech frames required specifically for the first user turn. + Overrides the server default when provided. + + negative_frames_count : typing.Optional[str] + Number of negative (silence) frames needed within the window to end a speech segment. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + negative_frames_window : typing.Optional[str] + Sliding window size (in frames) over which negative frames are counted. + Overrides the server default (or the high_vad_sensitivity preset) when provided. + + start_speech_volume_threshold : typing.Optional[str] + Volume level (dB) below which audio is considered too quiet to be speech. + When not provided, no volume-based filtering is applied. + + interrupt_min_speech_frames : typing.Optional[str] + Minimum speech frames required to register a barge-in / interruption. + Overrides the server default when provided. + + pre_speech_pad_frames : typing.Optional[str] + Number of audio frames to prepend before the detected speech onset, + ensuring the beginning of speech is not clipped. + Overrides the server default when provided. + + num_initial_ignored_frames : typing.Optional[str] + Number of leading audio frames to skip entirely at connection start. + Useful for discarding connection setup noise. + Overrides the server default when provided. + + vad_signals : typing.Optional[SpeechToTextTranslateStreamingVadSignals] + Enable VAD signals in response + + flush_signal : typing.Optional[SpeechToTextTranslateStreamingFlushSignal] + Signal to flush the audio buffer and finalize transcription and translation + + input_audio_codec : typing.Optional[SpeechToTextTranslateStreamingInputAudioCodec] + Audio codec/format of the input stream. Use this when sending raw PCM audio. + Supported values: wav, pcm_s16le, pcm_l16, pcm_raw. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncSpeechToTextTranslateStreamingSocketClient + """ + ws_url = self._client_wrapper.get_environment().production + "/speech-to-text-translate/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "mode": mode, + "sample_rate": sample_rate, + "high_vad_sensitivity": high_vad_sensitivity, + "positive_speech_threshold": positive_speech_threshold, + "negative_speech_threshold": negative_speech_threshold, + "min_speech_frames": min_speech_frames, + "first_turn_min_speech_frames": first_turn_min_speech_frames, + "negative_frames_count": negative_frames_count, + "negative_frames_window": negative_frames_window, + "start_speech_volume_threshold": start_speech_volume_threshold, + "interrupt_min_speech_frames": interrupt_min_speech_frames, + "pre_speech_pad_frames": pre_speech_pad_frames, + "num_initial_ignored_frames": num_initial_ignored_frames, + "vad_signals": vad_signals, + "flush_signal": flush_signal, + "input_audio_codec": input_audio_codec, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + async with websockets_client_connect(ws_url, extra_headers=headers) as protocol: + yield AsyncSpeechToTextTranslateStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/socket_client.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/socket_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b04b1540568d3af3c7ebdd6251efdbbabf91849c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/socket_client.py @@ -0,0 +1,236 @@ +# This file was auto-generated by Fern from our API Definition. + +import json +import typing + +import websockets +import websockets.sync.connection as websockets_sync_connection +from ..core.events import EventEmitterMixin, EventType +from ..core.pydantic_utilities import parse_obj_as +from ..types.audio_data import AudioData +from ..types.audio_message import AudioMessage +from ..types.config_message import ConfigMessage +from ..types.speech_to_text_translate_streaming_response import ( + SpeechToTextTranslateStreamingResponse, +) +from ..types.stt_flush_signal import SttFlushSignal + +SpeechToTextTranslateStreamingSocketClientResponse = typing.Union[ + SpeechToTextTranslateStreamingResponse +] + + +class AsyncSpeechToTextTranslateStreamingSocketClient(EventEmitterMixin): + def __init__(self, *, websocket: websockets.WebSocketClientProtocol): + super().__init__() + self._websocket = websocket + + async def __aiter__(self): + async for message in self._websocket: + message = json.loads(message) if isinstance(message, str) else message + yield parse_obj_as(SpeechToTextTranslateStreamingSocketClientResponse, message) # type: ignore + + async def start_listening(self): + """ + Start listening for messages on the websocket connection. + + Emits events in the following order: + - EventType.OPEN when connection is established + - EventType.MESSAGE for each message received + - EventType.ERROR if an error occurs + - EventType.CLOSE when connection is closed + """ + self._emit(EventType.OPEN, None) + try: + async for raw_message in self._websocket: + raw_message = ( + json.loads(raw_message) + if isinstance(raw_message, str) + else raw_message + ) + parsed = parse_obj_as(SpeechToTextTranslateStreamingSocketClientResponse, raw_message) # type: ignore + self._emit(EventType.MESSAGE, parsed) + except websockets.WebSocketException as exc: + self._emit(EventType.ERROR, exc) + finally: + self._emit(EventType.CLOSE, None) + + async def translate( + self, audio: str, encoding: str = "audio/wav", sample_rate: int = 16000 + ): + """ + Sends audio translation request to the server. + :param audio: Base64 encoded audio data + :param encoding (Optional): Audio encoding format (default is "audio/wav") + :param sample_rate (Optional): Audio sample rate in Hz (default is 16000) + """ + return await self._send_speech_to_text_translate_streaming_audio_message( + message=AudioMessage( + audio=AudioData(data=audio, encoding=encoding, sample_rate=sample_rate) + ) + ) + + async def set_prompt(self, prompt: str) -> None: + """ + Set the prompt for the translation. + The prompt is useful for detecting hotwords in the audio stream. + This will send a ConfigMessage to the websocket connection. + """ + message = ConfigMessage(prompt=prompt) + await self._send_config_message(message) + + async def flush(self) -> None: + """ + Signal to flush the audio buffer and force finalize partial + transcriptions and translations. Use this to force processing of any + remaining audio that hasn't been transcribed and translated yet. + """ + message = SttFlushSignal() + await self._send_model(message) + + async def recv(self) -> SpeechToTextTranslateStreamingSocketClientResponse: + """ + Receive a message from the websocket connection. + """ + data = await self._websocket.recv() + data = json.loads(data) if isinstance(data, str) else data + return parse_obj_as( + SpeechToTextTranslateStreamingSocketClientResponse, data + ) # type: ignore + + async def _send_speech_to_text_translate_streaming_audio_message( + self, message: AudioMessage + ) -> None: + """ + Send a message to the websocket connection. + The message will be sent as a AudioMessage. + """ + await self._send_model(message) + + async def _send_config_message(self, message: ConfigMessage) -> None: + """ + Send a message to the websocket connection. + The message will be sent as a ConfigMessage. + """ + await self._send_model(message) + + async def _send(self, data: typing.Any) -> None: + """ + Send a message to the websocket connection. + """ + if isinstance(data, dict): + data = json.dumps(data) + await self._websocket.send(data) + + async def _send_model(self, data: typing.Any) -> None: + """ + Send a Pydantic model to the websocket connection. + """ + await self._send(data.dict()) + + +class SpeechToTextTranslateStreamingSocketClient(EventEmitterMixin): + def __init__(self, *, websocket: websockets_sync_connection.Connection): + super().__init__() + self._websocket = websocket + + def __iter__(self): + for message in self._websocket: + message = json.loads(message) if isinstance(message, str) else message + yield parse_obj_as(SpeechToTextTranslateStreamingSocketClientResponse, message) # type: ignore + + def start_listening(self): + """ + Start listening for messages on the websocket connection. + + Emits events in the following order: + - EventType.OPEN when connection is established + - EventType.MESSAGE for each message received + - EventType.ERROR if an error occurs + - EventType.CLOSE when connection is closed + """ + self._emit(EventType.OPEN, None) + try: + for raw_message in self._websocket: + raw_message = ( + json.loads(raw_message) + if isinstance(raw_message, str) + else raw_message + ) + parsed = parse_obj_as(SpeechToTextTranslateStreamingSocketClientResponse, raw_message) # type: ignore + self._emit(EventType.MESSAGE, parsed) + except websockets.WebSocketException as exc: + self._emit(EventType.ERROR, exc) + finally: + self._emit(EventType.CLOSE, None) + + def translate( + self, audio: str, encoding: str = "audio/wav", sample_rate: int = 16000 + ): + """ + Sends audio translation request to the server. + :param audio: Base64 encoded audio data + :param encoding: Audio encoding format (default is "audio/wav") + :param sample_rate: Audio sample rate in Hz (default is 16000) + """ + return self._send_speech_to_text_translate_streaming_audio_message( + message=AudioMessage( + audio=AudioData(data=audio, encoding=encoding, sample_rate=sample_rate) + ) + ) + + def set_prompt(self, prompt: str) -> None: + """ + Set the prompt for the translation. + The prompt is useful for detecting hotwords in the audio stream. + This will send a ConfigMessage to the websocket connection. + """ + message = ConfigMessage(prompt=prompt) + self._send_config_message(message) + + def flush(self) -> None: + """ + Signal to flush the audio buffer and force finalize partial transcriptions and translations. + Use this to force processing of any remaining audio that hasn't been + transcribed and translated yet. + """ + message = SttFlushSignal() + self._send_model(message) + + def recv(self) -> SpeechToTextTranslateStreamingSocketClientResponse: + """ + Receive a message from the websocket connection. + """ + data = self._websocket.recv() + data = json.loads(data) if isinstance(data, str) else data + return parse_obj_as(SpeechToTextTranslateStreamingSocketClientResponse, data) # type: ignore + + def _send_config_message(self, message: ConfigMessage) -> None: + """ + Send a message to the websocket connection. + The message will be sent as a ConfigMessage. + """ + self._send_model(message) + + def _send_speech_to_text_translate_streaming_audio_message( + self, message: AudioMessage + ) -> None: + """ + Send a message to the websocket connection. + The message will be sent as a AudioMessage. + """ + self._send_model(message) + + def _send(self, data: typing.Any) -> None: + """ + Send a message to the websocket connection. + """ + if isinstance(data, dict): + data = json.dumps(data) + self._websocket.send(data) + + def _send_model(self, data: typing.Any) -> None: + """ + Send a Pydantic model to the websocket connection. + """ + self._send(data.dict()) diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04bac84a9931c8b50c06f7322afcbfdc3e164572 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__init__.py @@ -0,0 +1,55 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .speech_to_text_translate_streaming_flush_signal import SpeechToTextTranslateStreamingFlushSignal + from .speech_to_text_translate_streaming_high_vad_sensitivity import ( + SpeechToTextTranslateStreamingHighVadSensitivity, + ) + from .speech_to_text_translate_streaming_input_audio_codec import SpeechToTextTranslateStreamingInputAudioCodec + from .speech_to_text_translate_streaming_mode import SpeechToTextTranslateStreamingMode + from .speech_to_text_translate_streaming_model import SpeechToTextTranslateStreamingModel + from .speech_to_text_translate_streaming_vad_signals import SpeechToTextTranslateStreamingVadSignals +_dynamic_imports: typing.Dict[str, str] = { + "SpeechToTextTranslateStreamingFlushSignal": ".speech_to_text_translate_streaming_flush_signal", + "SpeechToTextTranslateStreamingHighVadSensitivity": ".speech_to_text_translate_streaming_high_vad_sensitivity", + "SpeechToTextTranslateStreamingInputAudioCodec": ".speech_to_text_translate_streaming_input_audio_codec", + "SpeechToTextTranslateStreamingMode": ".speech_to_text_translate_streaming_mode", + "SpeechToTextTranslateStreamingModel": ".speech_to_text_translate_streaming_model", + "SpeechToTextTranslateStreamingVadSignals": ".speech_to_text_translate_streaming_vad_signals", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "SpeechToTextTranslateStreamingFlushSignal", + "SpeechToTextTranslateStreamingHighVadSensitivity", + "SpeechToTextTranslateStreamingInputAudioCodec", + "SpeechToTextTranslateStreamingMode", + "SpeechToTextTranslateStreamingModel", + "SpeechToTextTranslateStreamingVadSignals", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9514cee908ac41c3dc88db67790a43a589ca89b2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_flush_signal.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_flush_signal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..465d857670faab85649ebf380db16ca2f18c2131 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_flush_signal.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_high_vad_sensitivity.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_high_vad_sensitivity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e1b7a3dbff4074ab0af22793b4ef48140a484c0 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_high_vad_sensitivity.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_input_audio_codec.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_input_audio_codec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51ff6c4e76e09761e71712da1705a8c189a00543 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_input_audio_codec.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_mode.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dba4c17a44dca315b12b1a7f22d1a7ad3d850eb Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_mode.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_model.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a2b2b01c3222a7a1bb9eaf43a76f0f0647c6f62 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_model.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_vad_signals.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_vad_signals.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..701205dd2aaf305138de1e3b9e8c41edafe71b7f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/__pycache__/speech_to_text_translate_streaming_vad_signals.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_flush_signal.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_flush_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..9cfc875cc1028e3a59dff0bef35b20b62bbb4f79 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_flush_signal.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateStreamingFlushSignal = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_high_vad_sensitivity.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_high_vad_sensitivity.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b66969da12d0d1a780ab426b645098904159b3 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_high_vad_sensitivity.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateStreamingHighVadSensitivity = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_input_audio_codec.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_input_audio_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d52476963e9bd4511ea6ff2fb5dbacfffd503c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_input_audio_codec.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateStreamingInputAudioCodec = typing.Union[ + typing.Literal["wav", "pcm_s16le", "pcm_l16", "pcm_raw"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_mode.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..8495b020e0c431eb04e1189c884e18502f15f391 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_mode.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateStreamingMode = typing.Union[ + typing.Literal["translate", "transcribe", "verbatim", "translit", "codemix"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_model.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_model.py new file mode 100644 index 0000000000000000000000000000000000000000..ac19f71a2789a32da27110bf63d046b90fb573c7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateStreamingModel = typing.Union[typing.Literal["saaras:v3", "saaras:v2.5"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_vad_signals.py b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_vad_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..69002041e3972b9e0c046cbcdf77623d2f1d9216 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/speech_to_text_translate_streaming/types/speech_to_text_translate_streaming_vad_signals.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateStreamingVadSignals = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/text/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81df79082d484011c05dd3a6670d32d673285e3a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5830a08ac3f2b27fd9e8e361249df6f2bc272f44 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6661556a3b84575065bc5c0bb2404d161b31c7a5 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text/client.py b/venv/lib/python3.12/site-packages/sarvamai/text/client.py new file mode 100644 index 0000000000000000000000000000000000000000..01fb152a6717d24cad35bf24285e0d9c431cc7c1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text/client.py @@ -0,0 +1,683 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..types.language_identification_response import LanguageIdentificationResponse +from ..types.numerals_format import NumeralsFormat +from ..types.spoken_form_numerals_format import SpokenFormNumeralsFormat +from ..types.translate_mode import TranslateMode +from ..types.translate_model import TranslateModel +from ..types.translate_source_language import TranslateSourceLanguage +from ..types.translate_speaker_gender import TranslateSpeakerGender +from ..types.translate_target_language import TranslateTargetLanguage +from ..types.translation_response import TranslationResponse +from ..types.translatiterate_target_language import TranslatiterateTargetLanguage +from ..types.transliterate_mode import TransliterateMode +from ..types.transliterate_source_language import TransliterateSourceLanguage +from ..types.transliteration_response import TransliterationResponse +from .raw_client import AsyncRawTextClient, RawTextClient + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class TextClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawTextClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawTextClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawTextClient + """ + return self._raw_client + + def translate( + self, + *, + input: str, + source_language_code: TranslateSourceLanguage, + target_language_code: TranslateTargetLanguage, + speaker_gender: typing.Optional[TranslateSpeakerGender] = OMIT, + mode: typing.Optional[TranslateMode] = OMIT, + model: typing.Optional[TranslateModel] = OMIT, + output_script: typing.Optional[TransliterateMode] = OMIT, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> TranslationResponse: + """ + **Translation** converts text from one language to another while preserving its meaning. + For Example: **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, where the script and language change, but the original meaning remains the same. + + Available languages: + - **`bn-IN`**: Bengali + - **`en-IN`**: English + - **`gu-IN`**: Gujarati + - **`hi-IN`**: Hindi + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + ### Newly added languages: + - **`as-IN`**: Assamese + - **`brx-IN`**: Bodo + - **`doi-IN`**: Dogri + - **`kok-IN`**: Konkani + - **`ks-IN`**: Kashmiri + - **`mai-IN`**: Maithili + - **`mni-IN`**: Manipuri (Meiteilon) + - **`ne-IN`**: Nepali + - **`sa-IN`**: Sanskrit + - **`sat-IN`**: Santali + - **`sd-IN`**: Sindhi + - **`ur-IN`**: Urdu + + For hands-on practice, you can explore the notebook tutorial on [Translate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/translate/Translate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to translate is the input text that will be processed by the translation model. The maximum is 1000 characters for Mayura:v1 and 2000 characters for Sarvam-Translate:v1. + + source_language_code : TranslateSourceLanguage + Source language code for translation input. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 languages and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + **Note:** mayura:v1 supports automatic language detection using 'auto' as the source language code. + + + target_language_code : TranslateTargetLanguage + The language code of the translated text. This specifies the target language for translation. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + + speaker_gender : typing.Optional[TranslateSpeakerGender] + Please specify the gender of the speaker for better translations. + + mode : typing.Optional[TranslateMode] + Specifies the tone or style of the translation. + + **Model Support:** + - **mayura:v1**: Supports formal, classic-colloquial, and modern-colloquial modes + - **sarvam-translate:v1**: Only formal mode is supported + + **Default:** formal + + model : typing.Optional[TranslateModel] + Specifies the translation model to use. + - mayura:v1: Supports 12 languages with all modes, output scripts, and automatic language detection. + - sarvam-translate:v1: Supports all 22 scheduled languages of India, formal mode only. + + output_script : typing.Optional[TransliterateMode] + **output_script**: This is an optional parameter which controls the transliteration style applied to the output text. + + **Transliteration**: Converting text from one script to another while preserving pronunciation. + + For mayura:v1 - We support transliteration with four options: + - **`null`**(default): No transliteration applied. + - **`roman`**: Transliteration in Romanized script. + - **`fully-native`**: Transliteration in the native script with formal style. + - **`spoken-form-in-native`**: Transliteration in the native script with spoken style. + + For sarvam-translate:v1 - Transliteration is not supported. + ### Example: + English: Your EMI of Rs. 3000 is pending. + Default modern translation: आपका Rs. 3000 का EMI pending है (when `null` is passed). + + With postprocessing enabled: + - **roman output**: aapka Rs. 3000 ka EMI pending hai. + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options (supported for both mayura:v1 and sarvam-translate:v1): + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TranslationResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.text.translate( + input="input", + source_language_code="auto", + target_language_code="bn-IN", + ) + """ + _response = self._raw_client.translate( + input=input, + source_language_code=source_language_code, + target_language_code=target_language_code, + speaker_gender=speaker_gender, + mode=mode, + model=model, + output_script=output_script, + numerals_format=numerals_format, + request_options=request_options, + ) + return _response.data + + def identify_language( + self, *, input: str, request_options: typing.Optional[RequestOptions] = None + ) -> LanguageIdentificationResponse: + """ + Identifies the language (e.g., en-IN, hi-IN) and script (e.g., Latin, Devanagari) of the input text, supporting multiple languages. + + Parameters + ---------- + input : str + The text input for language and script identification. Max Input Limit is 1000 characters + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + LanguageIdentificationResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.text.identify_language( + input="input", + ) + """ + _response = self._raw_client.identify_language(input=input, request_options=request_options) + return _response.data + + def transliterate( + self, + *, + input: str, + source_language_code: TransliterateSourceLanguage, + target_language_code: TranslatiterateTargetLanguage, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + spoken_form_numerals_language: typing.Optional[SpokenFormNumeralsFormat] = OMIT, + spoken_form: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> TransliterationResponse: + """ + **Transliteration** converts text from one script to another while preserving the original pronunciation. For example, **'नमस्ते'** becomes **'namaste'** in English, and **'how are you'** can be written as **'हाउ आर यू'** in Devanagari. This process ensures that the sound of the original text remains intact, even when written in a different script. + + Transliteration is useful when you want to represent words phonetically across different writing systems, such as converting **'मैं ऑफिस जा रहा हूँ'** to **'main office ja raha hun'** in English letters. + + **Translation**, on the other hand, converts text from one language to another while preserving the meaning rather than pronunciation. For example, **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, changing both the script and the language while conveying the intended message. + ### Examples of **Transliteration**: + - **'Good morning'** becomes **'गुड मॉर्निंग'** in Hindi, where the pronunciation is preserved but the meaning is not translated. + - **'सुप्रभात'** becomes **'suprabhat'** in English. + + Available languages: + - **`en-IN`**: English + - **`hi-IN`**: Hindi + - **`bn-IN`**: Bengali + - **`gu-IN`**: Gujarati + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + For hands-on practice, you can explore the notebook tutorial on [Transliterate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/transliterate/Transliterate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to transliterate. + + source_language_code : TransliterateSourceLanguage + The language code of the input text. This specifies the source language for transliteration. + + + + Note: The source language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + target_language_code : TranslatiterateTargetLanguage + The language code of the transliteration text. This specifies the target language for transliteration. + + + + Note:The target language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options: + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + spoken_form_numerals_language : typing.Optional[SpokenFormNumeralsFormat] + `spoken_form_numerals_language` is an optional parameter with two options and only works when spoken_form is true: + + - **`english`** : Numbers in the text will be spoken in English. + - **`native(default)`**: Numbers in the text will be spoken in the native language. + + ### Examples: + - **Input:** "मेरे पास ₹200 है" + - If `english` format is selected: "मेरे पास टू हन्डर्ड रूपीस है" + - If `native` format is selected: "मेरे पास दो सौ रुपये है" + + + spoken_form : typing.Optional[bool] + - Default: `False` + - Converts text into a natural spoken form when `True`. + - **Note:** No effect if output language is `en-IN`. + + ### Example: + - **Input:** `मुझे कल 9:30am को appointment है` + - **Output:** `मुझे कल सुबह साढ़े नौ बजे को अपॉइंटमेंट है` + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TransliterationResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.text.transliterate( + input="input", + source_language_code="auto", + target_language_code="bn-IN", + ) + """ + _response = self._raw_client.transliterate( + input=input, + source_language_code=source_language_code, + target_language_code=target_language_code, + numerals_format=numerals_format, + spoken_form_numerals_language=spoken_form_numerals_language, + spoken_form=spoken_form, + request_options=request_options, + ) + return _response.data + + +class AsyncTextClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawTextClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawTextClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawTextClient + """ + return self._raw_client + + async def translate( + self, + *, + input: str, + source_language_code: TranslateSourceLanguage, + target_language_code: TranslateTargetLanguage, + speaker_gender: typing.Optional[TranslateSpeakerGender] = OMIT, + mode: typing.Optional[TranslateMode] = OMIT, + model: typing.Optional[TranslateModel] = OMIT, + output_script: typing.Optional[TransliterateMode] = OMIT, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> TranslationResponse: + """ + **Translation** converts text from one language to another while preserving its meaning. + For Example: **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, where the script and language change, but the original meaning remains the same. + + Available languages: + - **`bn-IN`**: Bengali + - **`en-IN`**: English + - **`gu-IN`**: Gujarati + - **`hi-IN`**: Hindi + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + ### Newly added languages: + - **`as-IN`**: Assamese + - **`brx-IN`**: Bodo + - **`doi-IN`**: Dogri + - **`kok-IN`**: Konkani + - **`ks-IN`**: Kashmiri + - **`mai-IN`**: Maithili + - **`mni-IN`**: Manipuri (Meiteilon) + - **`ne-IN`**: Nepali + - **`sa-IN`**: Sanskrit + - **`sat-IN`**: Santali + - **`sd-IN`**: Sindhi + - **`ur-IN`**: Urdu + + For hands-on practice, you can explore the notebook tutorial on [Translate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/translate/Translate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to translate is the input text that will be processed by the translation model. The maximum is 1000 characters for Mayura:v1 and 2000 characters for Sarvam-Translate:v1. + + source_language_code : TranslateSourceLanguage + Source language code for translation input. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 languages and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + **Note:** mayura:v1 supports automatic language detection using 'auto' as the source language code. + + + target_language_code : TranslateTargetLanguage + The language code of the translated text. This specifies the target language for translation. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + + speaker_gender : typing.Optional[TranslateSpeakerGender] + Please specify the gender of the speaker for better translations. + + mode : typing.Optional[TranslateMode] + Specifies the tone or style of the translation. + + **Model Support:** + - **mayura:v1**: Supports formal, classic-colloquial, and modern-colloquial modes + - **sarvam-translate:v1**: Only formal mode is supported + + **Default:** formal + + model : typing.Optional[TranslateModel] + Specifies the translation model to use. + - mayura:v1: Supports 12 languages with all modes, output scripts, and automatic language detection. + - sarvam-translate:v1: Supports all 22 scheduled languages of India, formal mode only. + + output_script : typing.Optional[TransliterateMode] + **output_script**: This is an optional parameter which controls the transliteration style applied to the output text. + + **Transliteration**: Converting text from one script to another while preserving pronunciation. + + For mayura:v1 - We support transliteration with four options: + - **`null`**(default): No transliteration applied. + - **`roman`**: Transliteration in Romanized script. + - **`fully-native`**: Transliteration in the native script with formal style. + - **`spoken-form-in-native`**: Transliteration in the native script with spoken style. + + For sarvam-translate:v1 - Transliteration is not supported. + ### Example: + English: Your EMI of Rs. 3000 is pending. + Default modern translation: आपका Rs. 3000 का EMI pending है (when `null` is passed). + + With postprocessing enabled: + - **roman output**: aapka Rs. 3000 ka EMI pending hai. + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options (supported for both mayura:v1 and sarvam-translate:v1): + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TranslationResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.text.translate( + input="input", + source_language_code="auto", + target_language_code="bn-IN", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.translate( + input=input, + source_language_code=source_language_code, + target_language_code=target_language_code, + speaker_gender=speaker_gender, + mode=mode, + model=model, + output_script=output_script, + numerals_format=numerals_format, + request_options=request_options, + ) + return _response.data + + async def identify_language( + self, *, input: str, request_options: typing.Optional[RequestOptions] = None + ) -> LanguageIdentificationResponse: + """ + Identifies the language (e.g., en-IN, hi-IN) and script (e.g., Latin, Devanagari) of the input text, supporting multiple languages. + + Parameters + ---------- + input : str + The text input for language and script identification. Max Input Limit is 1000 characters + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + LanguageIdentificationResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.text.identify_language( + input="input", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.identify_language(input=input, request_options=request_options) + return _response.data + + async def transliterate( + self, + *, + input: str, + source_language_code: TransliterateSourceLanguage, + target_language_code: TranslatiterateTargetLanguage, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + spoken_form_numerals_language: typing.Optional[SpokenFormNumeralsFormat] = OMIT, + spoken_form: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> TransliterationResponse: + """ + **Transliteration** converts text from one script to another while preserving the original pronunciation. For example, **'नमस्ते'** becomes **'namaste'** in English, and **'how are you'** can be written as **'हाउ आर यू'** in Devanagari. This process ensures that the sound of the original text remains intact, even when written in a different script. + + Transliteration is useful when you want to represent words phonetically across different writing systems, such as converting **'मैं ऑफिस जा रहा हूँ'** to **'main office ja raha hun'** in English letters. + + **Translation**, on the other hand, converts text from one language to another while preserving the meaning rather than pronunciation. For example, **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, changing both the script and the language while conveying the intended message. + ### Examples of **Transliteration**: + - **'Good morning'** becomes **'गुड मॉर्निंग'** in Hindi, where the pronunciation is preserved but the meaning is not translated. + - **'सुप्रभात'** becomes **'suprabhat'** in English. + + Available languages: + - **`en-IN`**: English + - **`hi-IN`**: Hindi + - **`bn-IN`**: Bengali + - **`gu-IN`**: Gujarati + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + For hands-on practice, you can explore the notebook tutorial on [Transliterate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/transliterate/Transliterate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to transliterate. + + source_language_code : TransliterateSourceLanguage + The language code of the input text. This specifies the source language for transliteration. + + + + Note: The source language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + target_language_code : TranslatiterateTargetLanguage + The language code of the transliteration text. This specifies the target language for transliteration. + + + + Note:The target language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options: + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + spoken_form_numerals_language : typing.Optional[SpokenFormNumeralsFormat] + `spoken_form_numerals_language` is an optional parameter with two options and only works when spoken_form is true: + + - **`english`** : Numbers in the text will be spoken in English. + - **`native(default)`**: Numbers in the text will be spoken in the native language. + + ### Examples: + - **Input:** "मेरे पास ₹200 है" + - If `english` format is selected: "मेरे पास टू हन्डर्ड रूपीस है" + - If `native` format is selected: "मेरे पास दो सौ रुपये है" + + + spoken_form : typing.Optional[bool] + - Default: `False` + - Converts text into a natural spoken form when `True`. + - **Note:** No effect if output language is `en-IN`. + + ### Example: + - **Input:** `मुझे कल 9:30am को appointment है` + - **Output:** `मुझे कल सुबह साढ़े नौ बजे को अपॉइंटमेंट है` + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TransliterationResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.text.transliterate( + input="input", + source_language_code="auto", + target_language_code="bn-IN", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.transliterate( + input=input, + source_language_code=source_language_code, + target_language_code=target_language_code, + numerals_format=numerals_format, + spoken_form_numerals_language=spoken_form_numerals_language, + spoken_form=spoken_form, + request_options=request_options, + ) + return _response.data diff --git a/venv/lib/python3.12/site-packages/sarvamai/text/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/text/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..798df964ac612ec1e5551fa317c4fe86ca6e1203 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text/raw_client.py @@ -0,0 +1,1039 @@ +# 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.http_response import AsyncHttpResponse, HttpResponse +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..errors.bad_request_error import BadRequestError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..errors.unprocessable_entity_error import UnprocessableEntityError +from ..types.language_identification_response import LanguageIdentificationResponse +from ..types.numerals_format import NumeralsFormat +from ..types.spoken_form_numerals_format import SpokenFormNumeralsFormat +from ..types.translate_mode import TranslateMode +from ..types.translate_model import TranslateModel +from ..types.translate_source_language import TranslateSourceLanguage +from ..types.translate_speaker_gender import TranslateSpeakerGender +from ..types.translate_target_language import TranslateTargetLanguage +from ..types.translation_response import TranslationResponse +from ..types.translatiterate_target_language import TranslatiterateTargetLanguage +from ..types.transliterate_mode import TransliterateMode +from ..types.transliterate_source_language import TransliterateSourceLanguage +from ..types.transliteration_response import TransliterationResponse + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class RawTextClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def translate( + self, + *, + input: str, + source_language_code: TranslateSourceLanguage, + target_language_code: TranslateTargetLanguage, + speaker_gender: typing.Optional[TranslateSpeakerGender] = OMIT, + mode: typing.Optional[TranslateMode] = OMIT, + model: typing.Optional[TranslateModel] = OMIT, + output_script: typing.Optional[TransliterateMode] = OMIT, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[TranslationResponse]: + """ + **Translation** converts text from one language to another while preserving its meaning. + For Example: **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, where the script and language change, but the original meaning remains the same. + + Available languages: + - **`bn-IN`**: Bengali + - **`en-IN`**: English + - **`gu-IN`**: Gujarati + - **`hi-IN`**: Hindi + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + ### Newly added languages: + - **`as-IN`**: Assamese + - **`brx-IN`**: Bodo + - **`doi-IN`**: Dogri + - **`kok-IN`**: Konkani + - **`ks-IN`**: Kashmiri + - **`mai-IN`**: Maithili + - **`mni-IN`**: Manipuri (Meiteilon) + - **`ne-IN`**: Nepali + - **`sa-IN`**: Sanskrit + - **`sat-IN`**: Santali + - **`sd-IN`**: Sindhi + - **`ur-IN`**: Urdu + + For hands-on practice, you can explore the notebook tutorial on [Translate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/translate/Translate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to translate is the input text that will be processed by the translation model. The maximum is 1000 characters for Mayura:v1 and 2000 characters for Sarvam-Translate:v1. + + source_language_code : TranslateSourceLanguage + Source language code for translation input. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 languages and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + **Note:** mayura:v1 supports automatic language detection using 'auto' as the source language code. + + + target_language_code : TranslateTargetLanguage + The language code of the translated text. This specifies the target language for translation. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + + speaker_gender : typing.Optional[TranslateSpeakerGender] + Please specify the gender of the speaker for better translations. + + mode : typing.Optional[TranslateMode] + Specifies the tone or style of the translation. + + **Model Support:** + - **mayura:v1**: Supports formal, classic-colloquial, and modern-colloquial modes + - **sarvam-translate:v1**: Only formal mode is supported + + **Default:** formal + + model : typing.Optional[TranslateModel] + Specifies the translation model to use. + - mayura:v1: Supports 12 languages with all modes, output scripts, and automatic language detection. + - sarvam-translate:v1: Supports all 22 scheduled languages of India, formal mode only. + + output_script : typing.Optional[TransliterateMode] + **output_script**: This is an optional parameter which controls the transliteration style applied to the output text. + + **Transliteration**: Converting text from one script to another while preserving pronunciation. + + For mayura:v1 - We support transliteration with four options: + - **`null`**(default): No transliteration applied. + - **`roman`**: Transliteration in Romanized script. + - **`fully-native`**: Transliteration in the native script with formal style. + - **`spoken-form-in-native`**: Transliteration in the native script with spoken style. + + For sarvam-translate:v1 - Transliteration is not supported. + ### Example: + English: Your EMI of Rs. 3000 is pending. + Default modern translation: आपका Rs. 3000 का EMI pending है (when `null` is passed). + + With postprocessing enabled: + - **roman output**: aapka Rs. 3000 ka EMI pending hai. + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options (supported for both mayura:v1 and sarvam-translate:v1): + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[TranslationResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "translate", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "input": input, + "source_language_code": source_language_code, + "target_language_code": target_language_code, + "speaker_gender": speaker_gender, + "mode": mode, + "model": model, + "output_script": output_script, + "numerals_format": numerals_format, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + TranslationResponse, + parse_obj_as( + type_=TranslationResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def identify_language( + self, *, input: str, request_options: typing.Optional[RequestOptions] = None + ) -> HttpResponse[LanguageIdentificationResponse]: + """ + Identifies the language (e.g., en-IN, hi-IN) and script (e.g., Latin, Devanagari) of the input text, supporting multiple languages. + + Parameters + ---------- + input : str + The text input for language and script identification. Max Input Limit is 1000 characters + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[LanguageIdentificationResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "text-lid", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "input": input, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + LanguageIdentificationResponse, + parse_obj_as( + type_=LanguageIdentificationResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + def transliterate( + self, + *, + input: str, + source_language_code: TransliterateSourceLanguage, + target_language_code: TranslatiterateTargetLanguage, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + spoken_form_numerals_language: typing.Optional[SpokenFormNumeralsFormat] = OMIT, + spoken_form: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[TransliterationResponse]: + """ + **Transliteration** converts text from one script to another while preserving the original pronunciation. For example, **'नमस्ते'** becomes **'namaste'** in English, and **'how are you'** can be written as **'हाउ आर यू'** in Devanagari. This process ensures that the sound of the original text remains intact, even when written in a different script. + + Transliteration is useful when you want to represent words phonetically across different writing systems, such as converting **'मैं ऑफिस जा रहा हूँ'** to **'main office ja raha hun'** in English letters. + + **Translation**, on the other hand, converts text from one language to another while preserving the meaning rather than pronunciation. For example, **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, changing both the script and the language while conveying the intended message. + ### Examples of **Transliteration**: + - **'Good morning'** becomes **'गुड मॉर्निंग'** in Hindi, where the pronunciation is preserved but the meaning is not translated. + - **'सुप्रभात'** becomes **'suprabhat'** in English. + + Available languages: + - **`en-IN`**: English + - **`hi-IN`**: Hindi + - **`bn-IN`**: Bengali + - **`gu-IN`**: Gujarati + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + For hands-on practice, you can explore the notebook tutorial on [Transliterate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/transliterate/Transliterate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to transliterate. + + source_language_code : TransliterateSourceLanguage + The language code of the input text. This specifies the source language for transliteration. + + + + Note: The source language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + target_language_code : TranslatiterateTargetLanguage + The language code of the transliteration text. This specifies the target language for transliteration. + + + + Note:The target language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options: + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + spoken_form_numerals_language : typing.Optional[SpokenFormNumeralsFormat] + `spoken_form_numerals_language` is an optional parameter with two options and only works when spoken_form is true: + + - **`english`** : Numbers in the text will be spoken in English. + - **`native(default)`**: Numbers in the text will be spoken in the native language. + + ### Examples: + - **Input:** "मेरे पास ₹200 है" + - If `english` format is selected: "मेरे पास टू हन्डर्ड रूपीस है" + - If `native` format is selected: "मेरे पास दो सौ रुपये है" + + + spoken_form : typing.Optional[bool] + - Default: `False` + - Converts text into a natural spoken form when `True`. + - **Note:** No effect if output language is `en-IN`. + + ### Example: + - **Input:** `मुझे कल 9:30am को appointment है` + - **Output:** `मुझे कल सुबह साढ़े नौ बजे को अपॉइंटमेंट है` + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[TransliterationResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "transliterate", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "input": input, + "source_language_code": source_language_code, + "target_language_code": target_language_code, + "numerals_format": numerals_format, + "spoken_form_numerals_language": spoken_form_numerals_language, + "spoken_form": spoken_form, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + TransliterationResponse, + parse_obj_as( + type_=TransliterationResponse, # type: ignore + object_=_response.json(), + ), + ) + return HttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + +class AsyncRawTextClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def translate( + self, + *, + input: str, + source_language_code: TranslateSourceLanguage, + target_language_code: TranslateTargetLanguage, + speaker_gender: typing.Optional[TranslateSpeakerGender] = OMIT, + mode: typing.Optional[TranslateMode] = OMIT, + model: typing.Optional[TranslateModel] = OMIT, + output_script: typing.Optional[TransliterateMode] = OMIT, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[TranslationResponse]: + """ + **Translation** converts text from one language to another while preserving its meaning. + For Example: **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, where the script and language change, but the original meaning remains the same. + + Available languages: + - **`bn-IN`**: Bengali + - **`en-IN`**: English + - **`gu-IN`**: Gujarati + - **`hi-IN`**: Hindi + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + ### Newly added languages: + - **`as-IN`**: Assamese + - **`brx-IN`**: Bodo + - **`doi-IN`**: Dogri + - **`kok-IN`**: Konkani + - **`ks-IN`**: Kashmiri + - **`mai-IN`**: Maithili + - **`mni-IN`**: Manipuri (Meiteilon) + - **`ne-IN`**: Nepali + - **`sa-IN`**: Sanskrit + - **`sat-IN`**: Santali + - **`sd-IN`**: Sindhi + - **`ur-IN`**: Urdu + + For hands-on practice, you can explore the notebook tutorial on [Translate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/translate/Translate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to translate is the input text that will be processed by the translation model. The maximum is 1000 characters for Mayura:v1 and 2000 characters for Sarvam-Translate:v1. + + source_language_code : TranslateSourceLanguage + Source language code for translation input. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 languages and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + **Note:** mayura:v1 supports automatic language detection using 'auto' as the source language code. + + + target_language_code : TranslateTargetLanguage + The language code of the translated text. This specifies the target language for translation. + + **mayura:v1 Languages:** Bengali, English, Gujarati, Hindi, Kannada, Malayalam, Marathi, Odia, Punjabi, Tamil, Telugu + + **sarvam-translate:v1 Languages:** All mayura:v1 and Assamese, Bodo, Dogri, Konkani, Kashmiri, Maithili, Manipuri, Nepali, Sanskrit, Santali, Sindhi, Urdu + + + speaker_gender : typing.Optional[TranslateSpeakerGender] + Please specify the gender of the speaker for better translations. + + mode : typing.Optional[TranslateMode] + Specifies the tone or style of the translation. + + **Model Support:** + - **mayura:v1**: Supports formal, classic-colloquial, and modern-colloquial modes + - **sarvam-translate:v1**: Only formal mode is supported + + **Default:** formal + + model : typing.Optional[TranslateModel] + Specifies the translation model to use. + - mayura:v1: Supports 12 languages with all modes, output scripts, and automatic language detection. + - sarvam-translate:v1: Supports all 22 scheduled languages of India, formal mode only. + + output_script : typing.Optional[TransliterateMode] + **output_script**: This is an optional parameter which controls the transliteration style applied to the output text. + + **Transliteration**: Converting text from one script to another while preserving pronunciation. + + For mayura:v1 - We support transliteration with four options: + - **`null`**(default): No transliteration applied. + - **`roman`**: Transliteration in Romanized script. + - **`fully-native`**: Transliteration in the native script with formal style. + - **`spoken-form-in-native`**: Transliteration in the native script with spoken style. + + For sarvam-translate:v1 - Transliteration is not supported. + ### Example: + English: Your EMI of Rs. 3000 is pending. + Default modern translation: आपका Rs. 3000 का EMI pending है (when `null` is passed). + + With postprocessing enabled: + - **roman output**: aapka Rs. 3000 ka EMI pending hai. + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options (supported for both mayura:v1 and sarvam-translate:v1): + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[TranslationResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "translate", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "input": input, + "source_language_code": source_language_code, + "target_language_code": target_language_code, + "speaker_gender": speaker_gender, + "mode": mode, + "model": model, + "output_script": output_script, + "numerals_format": numerals_format, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + TranslationResponse, + parse_obj_as( + type_=TranslationResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def identify_language( + self, *, input: str, request_options: typing.Optional[RequestOptions] = None + ) -> AsyncHttpResponse[LanguageIdentificationResponse]: + """ + Identifies the language (e.g., en-IN, hi-IN) and script (e.g., Latin, Devanagari) of the input text, supporting multiple languages. + + Parameters + ---------- + input : str + The text input for language and script identification. Max Input Limit is 1000 characters + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[LanguageIdentificationResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "text-lid", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "input": input, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + LanguageIdentificationResponse, + parse_obj_as( + type_=LanguageIdentificationResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + async def transliterate( + self, + *, + input: str, + source_language_code: TransliterateSourceLanguage, + target_language_code: TranslatiterateTargetLanguage, + numerals_format: typing.Optional[NumeralsFormat] = OMIT, + spoken_form_numerals_language: typing.Optional[SpokenFormNumeralsFormat] = OMIT, + spoken_form: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[TransliterationResponse]: + """ + **Transliteration** converts text from one script to another while preserving the original pronunciation. For example, **'नमस्ते'** becomes **'namaste'** in English, and **'how are you'** can be written as **'हाउ आर यू'** in Devanagari. This process ensures that the sound of the original text remains intact, even when written in a different script. + + Transliteration is useful when you want to represent words phonetically across different writing systems, such as converting **'मैं ऑफिस जा रहा हूँ'** to **'main office ja raha hun'** in English letters. + + **Translation**, on the other hand, converts text from one language to another while preserving the meaning rather than pronunciation. For example, **'मैं ऑफिस जा रहा हूँ'** translates to **'I am going to the office'** in English, changing both the script and the language while conveying the intended message. + ### Examples of **Transliteration**: + - **'Good morning'** becomes **'गुड मॉर्निंग'** in Hindi, where the pronunciation is preserved but the meaning is not translated. + - **'सुप्रभात'** becomes **'suprabhat'** in English. + + Available languages: + - **`en-IN`**: English + - **`hi-IN`**: Hindi + - **`bn-IN`**: Bengali + - **`gu-IN`**: Gujarati + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + + For hands-on practice, you can explore the notebook tutorial on [Transliterate API Tutorial](https://github.com/sarvamai/sarvam-ai-cookbook/blob/main/notebooks/transliterate/Transliterate_API_Tutorial.ipynb). + + Parameters + ---------- + input : str + The text you want to transliterate. + + source_language_code : TransliterateSourceLanguage + The language code of the input text. This specifies the source language for transliteration. + + + + Note: The source language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + target_language_code : TranslatiterateTargetLanguage + The language code of the transliteration text. This specifies the target language for transliteration. + + + + Note:The target language should either be an Indic language or English. As we supports both Indic-to-English and English-to-Indic transliteration. + + + numerals_format : typing.Optional[NumeralsFormat] + `numerals_format` is an optional parameter with two options: + + - **`international`** (default): Uses regular numerals (0-9). + - **`native`**: Uses language-specific native numerals. + + ### Example: + - If `international` format is selected, we use regular numerals (0-9). For example: `मेरा phone number है: 9840950950`. + - If `native` format is selected, we use language-specific native numerals, like: `मेरा phone number है: ९८४०९५०९५०`. + + spoken_form_numerals_language : typing.Optional[SpokenFormNumeralsFormat] + `spoken_form_numerals_language` is an optional parameter with two options and only works when spoken_form is true: + + - **`english`** : Numbers in the text will be spoken in English. + - **`native(default)`**: Numbers in the text will be spoken in the native language. + + ### Examples: + - **Input:** "मेरे पास ₹200 है" + - If `english` format is selected: "मेरे पास टू हन्डर्ड रूपीस है" + - If `native` format is selected: "मेरे पास दो सौ रुपये है" + + + spoken_form : typing.Optional[bool] + - Default: `False` + - Converts text into a natural spoken form when `True`. + - **Note:** No effect if output language is `en-IN`. + + ### Example: + - **Input:** `मुझे कल 9:30am को appointment है` + - **Output:** `मुझे कल सुबह साढ़े नौ बजे को अपॉइंटमेंट है` + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[TransliterationResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "transliterate", + base_url=self._client_wrapper.get_environment().base, + method="POST", + json={ + "input": input, + "source_language_code": source_language_code, + "target_language_code": target_language_code, + "numerals_format": numerals_format, + "spoken_form_numerals_language": spoken_form_numerals_language, + "spoken_form": spoken_form, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) + try: + if 200 <= _response.status_code < 300: + _data = typing.cast( + TransliterationResponse, + parse_obj_as( + type_=TransliterationResponse, # type: ignore + object_=_response.json(), + ), + ) + return AsyncHttpResponse(response=_response, data=_data) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5cde0202dcf357bdc706ddaddb2b07a9fe49fffa --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/client.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/client.py new file mode 100644 index 0000000000000000000000000000000000000000..60e04447e199d59feea4450e5caa11ae03c0e67b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/client.py @@ -0,0 +1,665 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.request_options import RequestOptions +from ..types.speech_sample_rate import SpeechSampleRate +from ..types.speech_stream_bitrate import SpeechStreamBitrate +from ..types.speech_stream_codec import SpeechStreamCodec +from ..types.text_to_speech_language import TextToSpeechLanguage +from ..types.text_to_speech_model import TextToSpeechModel +from ..types.text_to_speech_output_audio_codec import TextToSpeechOutputAudioCodec +from ..types.text_to_speech_response import TextToSpeechResponse +from ..types.text_to_speech_speaker import TextToSpeechSpeaker +from .raw_client import AsyncRawTextToSpeechClient, RawTextToSpeechClient + +# this is used as the default value for optional parameters +OMIT = typing.cast(typing.Any, ...) + + +class TextToSpeechClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawTextToSpeechClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawTextToSpeechClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawTextToSpeechClient + """ + return self._raw_client + + 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, + output_audio_codec: typing.Optional[TextToSpeechOutputAudioCodec] = OMIT, + temperature: typing.Optional[float] = OMIT, + dict_id: typing.Optional[str] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> TextToSpeechResponse: + """ + Convert text into spoken audio. The output is a base64-encoded audio string that must be decoded before use. + + **Available Models:** + - **bulbul:v3**: Latest model with improved quality, 30+ voices, and temperature control + - **bulbul:v2**: Legacy model with pitch and loudness controls + + **Important Notes for bulbul:v3:** + - Pitch and loudness parameters are NOT supported + - Pace range: 0.5 to 2.0 + - Preprocessing is automatically enabled + - Default sample rate is 24000 Hz + - Supports sample rates: 8000, 16000, 22050, 24000 Hz (REST API also supports 32000, 44100, 48000 Hz) + + Parameters + ---------- + text : str + The text(s) to be converted into speech. + + **Features:** + - Supports code-mixed text (English and Indic languages) + + **Model-specific limits:** + - **bulbul:v3:** Max 2500 characters + - **bulbul:v2:** Max 1500 characters + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : TextToSpeechLanguage + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Model Compatibility (Speakers compatible with respective model):** + - **bulbul:v3:** + - shubh (default), aditya, ritu, priya, neha, rahul, pooja, rohan, simran, kavya, amit, dev, ishita, shreya, ratan, varun, manan, sumit, roopa, kabir, aayan, ashutosh, advait, anand, tanya, tarun, sunny, mani, gokul, vijay, shruti, suhani, mohit, kavitha, rehan, soham, rupali + - **bulbul:v2:** + - Female: anushka, manisha, vidya, arya + - Male: abhilash, karun, hitesh + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + 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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + pace : typing.Optional[float] + Controls the speed of the audio. Lower values result in slower speech, while higher values make it faster. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Supported values are 8000, 16000, 22050, 24000, 32000, 44100, 48000 Hz. + + **Note:** Higher sample rates (32000, 44100, 48000 Hz) are only available with bulbul:v3 via the REST API, not in streaming mode. + + **Default:** 24000 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. + + **Model-specific behavior:** + - **bulbul:v3:** Not Supported + - **bulbul:v2:** Default is false + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. + + **Available models:** + - **bulbul:v3:** Latest model with improved quality, 30+ voices, pace, and temperature control + - **bulbul:v2:** Legacy model with pitch, loudness, and pace controls + + output_audio_codec : typing.Optional[TextToSpeechOutputAudioCodec] + Specifies the audio codec for the output audio file. Different codecs offer various compression and quality characteristics. + + temperature : typing.Optional[float] + Temperature controls how much randomness and expressiveness the TTS model uses while generating speech. + + Lower values produce more stable and consistent output, while higher values sound more expressive but may introduce artifacts or errors. The suitable range is between 0.01 and 2.0. Default is 0.6. + + **Note:** This parameter is only supported for bulbul:v3. It has no effect on bulbul:v2. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. When enabled, identical requests will return cached audio instead of regenerating. Default is false. + + **Note:** Currently in beta and only available for bulbul:v1 and bulbul:v2 models. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TextToSpeechResponse + Successful Response + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.text_to_speech.convert( + text="text", + target_language_code="bn-IN", + ) + """ + _response = self._raw_client.convert( + 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, + output_audio_codec=output_audio_codec, + temperature=temperature, + dict_id=dict_id, + enable_cached_responses=enable_cached_responses, + request_options=request_options, + ) + return _response.data + + def convert_stream( + self, + *, + text: str, + target_language_code: typing.Optional[TextToSpeechLanguage] = OMIT, + 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, + temperature: typing.Optional[float] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + dict_id: typing.Optional[str] = OMIT, + output_audio_codec: typing.Optional[SpeechStreamCodec] = OMIT, + output_audio_bitrate: typing.Optional[SpeechStreamBitrate] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[bytes]: + """ + Converts the input text into a streamed spoken audio response. + + This endpoint supports streaming audio using the specified output codec (e.g., `audio/mpeg` for MP3). The response is returned as a binary audio stream, which can be played or saved directly by the client. + + Supports the `dict_id` parameter to apply a [pronunciation dictionary](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create) during synthesis. + + Parameters + ---------- + text : str + The text to be converted into streamed speech. + + **Features:** + - Max 3500 characters + - Supports code-mixed text (English and Indic languages) + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : typing.Optional[TextToSpeechLanguage] + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + pitch : typing.Optional[float] + Controls the pitch of the audio. Range: -0.75 to 0.75. Default is 0.0. + + **Note:** Only supported for bulbul:v2. + + pace : typing.Optional[float] + Controls the speed of the audio. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.0 + + loudness : typing.Optional[float] + Controls the loudness of the audio. Range: 0.3 to 3.0. Default is 1.0. + + **Note:** Only supported for bulbul:v2. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Default is 22050 Hz. + + **Note:** OPUS codec only supports 8000, 12000, 16000, 24000, 48000 Hz. + + enable_preprocessing : typing.Optional[bool] + Controls whether normalization of English words and numeric entities is performed. Default is false. + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. Default is bulbul:v2. + + temperature : typing.Optional[float] + Controls the randomness of the output. Range: 0.01 to 1.0. Default is 0.6. + + **Note:** Only supported for bulbul:v3. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. Default is false. Currently in beta. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + output_audio_codec : typing.Optional[SpeechStreamCodec] + Specifies the codec for the streamed output audio (e.g., 'mp3'). + + output_audio_bitrate : typing.Optional[SpeechStreamBitrate] + Bitrate for the streamed output audio. Default is '128k'. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response. + + Returns + ------- + typing.Iterator[bytes] + Success. Returns a streamed audio response in the requested format (e.g., `audio/mpeg` for MP3, `audio/wav` for WAV). + + Examples + -------- + from sarvamai import SarvamAI + + client = SarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + client.text_to_speech.convert_stream( + text="x", + ) + """ + with self._raw_client.convert_stream( + 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, + temperature=temperature, + enable_cached_responses=enable_cached_responses, + dict_id=dict_id, + output_audio_codec=output_audio_codec, + output_audio_bitrate=output_audio_bitrate, + request_options=request_options, + ) as r: + yield from r.data + + +class AsyncTextToSpeechClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawTextToSpeechClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawTextToSpeechClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawTextToSpeechClient + """ + return self._raw_client + + 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, + output_audio_codec: typing.Optional[TextToSpeechOutputAudioCodec] = OMIT, + temperature: typing.Optional[float] = OMIT, + dict_id: typing.Optional[str] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> TextToSpeechResponse: + """ + Convert text into spoken audio. The output is a base64-encoded audio string that must be decoded before use. + + **Available Models:** + - **bulbul:v3**: Latest model with improved quality, 30+ voices, and temperature control + - **bulbul:v2**: Legacy model with pitch and loudness controls + + **Important Notes for bulbul:v3:** + - Pitch and loudness parameters are NOT supported + - Pace range: 0.5 to 2.0 + - Preprocessing is automatically enabled + - Default sample rate is 24000 Hz + - Supports sample rates: 8000, 16000, 22050, 24000 Hz (REST API also supports 32000, 44100, 48000 Hz) + + Parameters + ---------- + text : str + The text(s) to be converted into speech. + + **Features:** + - Supports code-mixed text (English and Indic languages) + + **Model-specific limits:** + - **bulbul:v3:** Max 2500 characters + - **bulbul:v2:** Max 1500 characters + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : TextToSpeechLanguage + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Model Compatibility (Speakers compatible with respective model):** + - **bulbul:v3:** + - shubh (default), aditya, ritu, priya, neha, rahul, pooja, rohan, simran, kavya, amit, dev, ishita, shreya, ratan, varun, manan, sumit, roopa, kabir, aayan, ashutosh, advait, anand, tanya, tarun, sunny, mani, gokul, vijay, shruti, suhani, mohit, kavitha, rehan, soham, rupali + - **bulbul:v2:** + - Female: anushka, manisha, vidya, arya + - Male: abhilash, karun, hitesh + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + 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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + pace : typing.Optional[float] + Controls the speed of the audio. Lower values result in slower speech, while higher values make it faster. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Supported values are 8000, 16000, 22050, 24000, 32000, 44100, 48000 Hz. + + **Note:** Higher sample rates (32000, 44100, 48000 Hz) are only available with bulbul:v3 via the REST API, not in streaming mode. + + **Default:** 24000 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. + + **Model-specific behavior:** + - **bulbul:v3:** Not Supported + - **bulbul:v2:** Default is false + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. + + **Available models:** + - **bulbul:v3:** Latest model with improved quality, 30+ voices, pace, and temperature control + - **bulbul:v2:** Legacy model with pitch, loudness, and pace controls + + output_audio_codec : typing.Optional[TextToSpeechOutputAudioCodec] + Specifies the audio codec for the output audio file. Different codecs offer various compression and quality characteristics. + + temperature : typing.Optional[float] + Temperature controls how much randomness and expressiveness the TTS model uses while generating speech. + + Lower values produce more stable and consistent output, while higher values sound more expressive but may introduce artifacts or errors. The suitable range is between 0.01 and 2.0. Default is 0.6. + + **Note:** This parameter is only supported for bulbul:v3. It has no effect on bulbul:v2. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. When enabled, identical requests will return cached audio instead of regenerating. Default is false. + + **Note:** Currently in beta and only available for bulbul:v1 and bulbul:v2 models. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TextToSpeechResponse + Successful Response + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.text_to_speech.convert( + text="text", + target_language_code="bn-IN", + ) + + + asyncio.run(main()) + """ + _response = await self._raw_client.convert( + 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, + output_audio_codec=output_audio_codec, + temperature=temperature, + dict_id=dict_id, + enable_cached_responses=enable_cached_responses, + request_options=request_options, + ) + return _response.data + + async def convert_stream( + self, + *, + text: str, + target_language_code: typing.Optional[TextToSpeechLanguage] = OMIT, + 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, + temperature: typing.Optional[float] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + dict_id: typing.Optional[str] = OMIT, + output_audio_codec: typing.Optional[SpeechStreamCodec] = OMIT, + output_audio_bitrate: typing.Optional[SpeechStreamBitrate] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[bytes]: + """ + Converts the input text into a streamed spoken audio response. + + This endpoint supports streaming audio using the specified output codec (e.g., `audio/mpeg` for MP3). The response is returned as a binary audio stream, which can be played or saved directly by the client. + + Supports the `dict_id` parameter to apply a [pronunciation dictionary](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create) during synthesis. + + Parameters + ---------- + text : str + The text to be converted into streamed speech. + + **Features:** + - Max 3500 characters + - Supports code-mixed text (English and Indic languages) + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : typing.Optional[TextToSpeechLanguage] + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + pitch : typing.Optional[float] + Controls the pitch of the audio. Range: -0.75 to 0.75. Default is 0.0. + + **Note:** Only supported for bulbul:v2. + + pace : typing.Optional[float] + Controls the speed of the audio. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.0 + + loudness : typing.Optional[float] + Controls the loudness of the audio. Range: 0.3 to 3.0. Default is 1.0. + + **Note:** Only supported for bulbul:v2. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Default is 22050 Hz. + + **Note:** OPUS codec only supports 8000, 12000, 16000, 24000, 48000 Hz. + + enable_preprocessing : typing.Optional[bool] + Controls whether normalization of English words and numeric entities is performed. Default is false. + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. Default is bulbul:v2. + + temperature : typing.Optional[float] + Controls the randomness of the output. Range: 0.01 to 1.0. Default is 0.6. + + **Note:** Only supported for bulbul:v3. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. Default is false. Currently in beta. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + output_audio_codec : typing.Optional[SpeechStreamCodec] + Specifies the codec for the streamed output audio (e.g., 'mp3'). + + output_audio_bitrate : typing.Optional[SpeechStreamBitrate] + Bitrate for the streamed output audio. Default is '128k'. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response. + + Returns + ------- + typing.AsyncIterator[bytes] + Success. Returns a streamed audio response in the requested format (e.g., `audio/mpeg` for MP3, `audio/wav` for WAV). + + Examples + -------- + import asyncio + + from sarvamai import AsyncSarvamAI + + client = AsyncSarvamAI( + api_subscription_key="YOUR_API_SUBSCRIPTION_KEY", + ) + + + async def main() -> None: + await client.text_to_speech.convert_stream( + text="x", + ) + + + asyncio.run(main()) + """ + async with self._raw_client.convert_stream( + 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, + temperature=temperature, + enable_cached_responses=enable_cached_responses, + dict_id=dict_id, + output_audio_codec=output_audio_codec, + output_audio_bitrate=output_audio_bitrate, + request_options=request_options, + ) as r: + async for _chunk in r.data: + yield _chunk diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..93ed6c9ab38cc6abc37fbcbfc4308c615f739d0f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech/raw_client.py @@ -0,0 +1,906 @@ +# This file was auto-generated by Fern from our API Definition. + +import contextlib +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.http_response import AsyncHttpResponse, HttpResponse +from ..core.pydantic_utilities import parse_obj_as +from ..core.request_options import RequestOptions +from ..errors.bad_request_error import BadRequestError +from ..errors.forbidden_error import ForbiddenError +from ..errors.internal_server_error import InternalServerError +from ..errors.too_many_requests_error import TooManyRequestsError +from ..errors.unprocessable_entity_error import UnprocessableEntityError +from ..types.speech_sample_rate import SpeechSampleRate +from ..types.speech_stream_bitrate import SpeechStreamBitrate +from ..types.speech_stream_codec import SpeechStreamCodec +from ..types.text_to_speech_language import TextToSpeechLanguage +from ..types.text_to_speech_model import TextToSpeechModel +from ..types.text_to_speech_output_audio_codec import TextToSpeechOutputAudioCodec +from ..types.text_to_speech_response import TextToSpeechResponse +from ..types.text_to_speech_speaker import TextToSpeechSpeaker + +# 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, + output_audio_codec: typing.Optional[TextToSpeechOutputAudioCodec] = OMIT, + temperature: typing.Optional[float] = OMIT, + dict_id: typing.Optional[str] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> HttpResponse[TextToSpeechResponse]: + """ + Convert text into spoken audio. The output is a base64-encoded audio string that must be decoded before use. + + **Available Models:** + - **bulbul:v3**: Latest model with improved quality, 30+ voices, and temperature control + - **bulbul:v2**: Legacy model with pitch and loudness controls + + **Important Notes for bulbul:v3:** + - Pitch and loudness parameters are NOT supported + - Pace range: 0.5 to 2.0 + - Preprocessing is automatically enabled + - Default sample rate is 24000 Hz + - Supports sample rates: 8000, 16000, 22050, 24000 Hz (REST API also supports 32000, 44100, 48000 Hz) + + Parameters + ---------- + text : str + The text(s) to be converted into speech. + + **Features:** + - Supports code-mixed text (English and Indic languages) + + **Model-specific limits:** + - **bulbul:v3:** Max 2500 characters + - **bulbul:v2:** Max 1500 characters + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : TextToSpeechLanguage + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Model Compatibility (Speakers compatible with respective model):** + - **bulbul:v3:** + - shubh (default), aditya, ritu, priya, neha, rahul, pooja, rohan, simran, kavya, amit, dev, ishita, shreya, ratan, varun, manan, sumit, roopa, kabir, aayan, ashutosh, advait, anand, tanya, tarun, sunny, mani, gokul, vijay, shruti, suhani, mohit, kavitha, rehan, soham, rupali + - **bulbul:v2:** + - Female: anushka, manisha, vidya, arya + - Male: abhilash, karun, hitesh + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + 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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + pace : typing.Optional[float] + Controls the speed of the audio. Lower values result in slower speech, while higher values make it faster. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Supported values are 8000, 16000, 22050, 24000, 32000, 44100, 48000 Hz. + + **Note:** Higher sample rates (32000, 44100, 48000 Hz) are only available with bulbul:v3 via the REST API, not in streaming mode. + + **Default:** 24000 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. + + **Model-specific behavior:** + - **bulbul:v3:** Not Supported + - **bulbul:v2:** Default is false + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. + + **Available models:** + - **bulbul:v3:** Latest model with improved quality, 30+ voices, pace, and temperature control + - **bulbul:v2:** Legacy model with pitch, loudness, and pace controls + + output_audio_codec : typing.Optional[TextToSpeechOutputAudioCodec] + Specifies the audio codec for the output audio file. Different codecs offer various compression and quality characteristics. + + temperature : typing.Optional[float] + Temperature controls how much randomness and expressiveness the TTS model uses while generating speech. + + Lower values produce more stable and consistent output, while higher values sound more expressive but may introduce artifacts or errors. The suitable range is between 0.01 and 2.0. Default is 0.6. + + **Note:** This parameter is only supported for bulbul:v3. It has no effect on bulbul:v2. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. When enabled, identical requests will return cached audio instead of regenerating. Default is false. + + **Note:** Currently in beta and only available for bulbul:v1 and bulbul:v2 models. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + HttpResponse[TextToSpeechResponse] + Successful Response + """ + _response = self._client_wrapper.httpx_client.request( + "text-to-speech", + base_url=self._client_wrapper.get_environment().base, + 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, + "output_audio_codec": output_audio_codec, + "temperature": temperature, + "dict_id": dict_id, + "enable_cached_responses": enable_cached_responses, + }, + 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( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + @contextlib.contextmanager + def convert_stream( + self, + *, + text: str, + target_language_code: typing.Optional[TextToSpeechLanguage] = OMIT, + 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, + temperature: typing.Optional[float] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + dict_id: typing.Optional[str] = OMIT, + output_audio_codec: typing.Optional[SpeechStreamCodec] = OMIT, + output_audio_bitrate: typing.Optional[SpeechStreamBitrate] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[HttpResponse[typing.Iterator[bytes]]]: + """ + Converts the input text into a streamed spoken audio response. + + This endpoint supports streaming audio using the specified output codec (e.g., `audio/mpeg` for MP3). The response is returned as a binary audio stream, which can be played or saved directly by the client. + + Supports the `dict_id` parameter to apply a [pronunciation dictionary](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create) during synthesis. + + Parameters + ---------- + text : str + The text to be converted into streamed speech. + + **Features:** + - Max 3500 characters + - Supports code-mixed text (English and Indic languages) + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : typing.Optional[TextToSpeechLanguage] + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + pitch : typing.Optional[float] + Controls the pitch of the audio. Range: -0.75 to 0.75. Default is 0.0. + + **Note:** Only supported for bulbul:v2. + + pace : typing.Optional[float] + Controls the speed of the audio. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.0 + + loudness : typing.Optional[float] + Controls the loudness of the audio. Range: 0.3 to 3.0. Default is 1.0. + + **Note:** Only supported for bulbul:v2. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Default is 22050 Hz. + + **Note:** OPUS codec only supports 8000, 12000, 16000, 24000, 48000 Hz. + + enable_preprocessing : typing.Optional[bool] + Controls whether normalization of English words and numeric entities is performed. Default is false. + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. Default is bulbul:v2. + + temperature : typing.Optional[float] + Controls the randomness of the output. Range: 0.01 to 1.0. Default is 0.6. + + **Note:** Only supported for bulbul:v3. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. Default is false. Currently in beta. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + output_audio_codec : typing.Optional[SpeechStreamCodec] + Specifies the codec for the streamed output audio (e.g., 'mp3'). + + output_audio_bitrate : typing.Optional[SpeechStreamBitrate] + Bitrate for the streamed output audio. Default is '128k'. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response. + + Returns + ------- + typing.Iterator[HttpResponse[typing.Iterator[bytes]]] + Success. Returns a streamed audio response in the requested format (e.g., `audio/mpeg` for MP3, `audio/wav` for WAV). + """ + with self._client_wrapper.httpx_client.stream( + "text-to-speech/stream", + base_url=self._client_wrapper.get_environment().base, + 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, + "temperature": temperature, + "enable_cached_responses": enable_cached_responses, + "dict_id": dict_id, + "output_audio_codec": output_audio_codec, + "output_audio_bitrate": output_audio_bitrate, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) as _response: + + def _stream() -> HttpResponse[typing.Iterator[bytes]]: + try: + if 200 <= _response.status_code < 300: + _chunk_size = request_options.get("chunk_size", None) if request_options is not None else None + return HttpResponse( + response=_response, data=(_chunk for _chunk in _response.iter_bytes(chunk_size=_chunk_size)) + ) + _response.read() + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError( + status_code=_response.status_code, headers=dict(_response.headers), body=_response.text + ) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + yield _stream() + + +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, + output_audio_codec: typing.Optional[TextToSpeechOutputAudioCodec] = OMIT, + temperature: typing.Optional[float] = OMIT, + dict_id: typing.Optional[str] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncHttpResponse[TextToSpeechResponse]: + """ + Convert text into spoken audio. The output is a base64-encoded audio string that must be decoded before use. + + **Available Models:** + - **bulbul:v3**: Latest model with improved quality, 30+ voices, and temperature control + - **bulbul:v2**: Legacy model with pitch and loudness controls + + **Important Notes for bulbul:v3:** + - Pitch and loudness parameters are NOT supported + - Pace range: 0.5 to 2.0 + - Preprocessing is automatically enabled + - Default sample rate is 24000 Hz + - Supports sample rates: 8000, 16000, 22050, 24000 Hz (REST API also supports 32000, 44100, 48000 Hz) + + Parameters + ---------- + text : str + The text(s) to be converted into speech. + + **Features:** + - Supports code-mixed text (English and Indic languages) + + **Model-specific limits:** + - **bulbul:v3:** Max 2500 characters + - **bulbul:v2:** Max 1500 characters + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : TextToSpeechLanguage + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Model Compatibility (Speakers compatible with respective model):** + - **bulbul:v3:** + - shubh (default), aditya, ritu, priya, neha, rahul, pooja, rohan, simran, kavya, amit, dev, ishita, shreya, ratan, varun, manan, sumit, roopa, kabir, aayan, ashutosh, advait, anand, tanya, tarun, sunny, mani, gokul, vijay, shruti, suhani, mohit, kavitha, rehan, soham, rupali + - **bulbul:v2:** + - Female: anushka, manisha, vidya, arya + - Male: abhilash, karun, hitesh + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + 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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + pace : typing.Optional[float] + Controls the speed of the audio. Lower values result in slower speech, while higher values make it faster. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.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. + + **Note:** This parameter is only supported for bulbul:v2. It is NOT supported for bulbul:v3. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Supported values are 8000, 16000, 22050, 24000, 32000, 44100, 48000 Hz. + + **Note:** Higher sample rates (32000, 44100, 48000 Hz) are only available with bulbul:v3 via the REST API, not in streaming mode. + + **Default:** 24000 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. + + **Model-specific behavior:** + - **bulbul:v3:** Not Supported + - **bulbul:v2:** Default is false + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. + + **Available models:** + - **bulbul:v3:** Latest model with improved quality, 30+ voices, pace, and temperature control + - **bulbul:v2:** Legacy model with pitch, loudness, and pace controls + + output_audio_codec : typing.Optional[TextToSpeechOutputAudioCodec] + Specifies the audio codec for the output audio file. Different codecs offer various compression and quality characteristics. + + temperature : typing.Optional[float] + Temperature controls how much randomness and expressiveness the TTS model uses while generating speech. + + Lower values produce more stable and consistent output, while higher values sound more expressive but may introduce artifacts or errors. The suitable range is between 0.01 and 2.0. Default is 0.6. + + **Note:** This parameter is only supported for bulbul:v3. It has no effect on bulbul:v2. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. When enabled, identical requests will return cached audio instead of regenerating. Default is false. + + **Note:** Currently in beta and only available for bulbul:v1 and bulbul:v2 models. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncHttpResponse[TextToSpeechResponse] + Successful Response + """ + _response = await self._client_wrapper.httpx_client.request( + "text-to-speech", + base_url=self._client_wrapper.get_environment().base, + 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, + "output_audio_codec": output_audio_codec, + "temperature": temperature, + "dict_id": dict_id, + "enable_cached_responses": enable_cached_responses, + }, + 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( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + @contextlib.asynccontextmanager + async def convert_stream( + self, + *, + text: str, + target_language_code: typing.Optional[TextToSpeechLanguage] = OMIT, + 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, + temperature: typing.Optional[float] = OMIT, + enable_cached_responses: typing.Optional[bool] = OMIT, + dict_id: typing.Optional[str] = OMIT, + output_audio_codec: typing.Optional[SpeechStreamCodec] = OMIT, + output_audio_bitrate: typing.Optional[SpeechStreamBitrate] = OMIT, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]: + """ + Converts the input text into a streamed spoken audio response. + + This endpoint supports streaming audio using the specified output codec (e.g., `audio/mpeg` for MP3). The response is returned as a binary audio stream, which can be played or saved directly by the client. + + Supports the `dict_id` parameter to apply a [pronunciation dictionary](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create) during synthesis. + + Parameters + ---------- + text : str + The text to be converted into streamed speech. + + **Features:** + - Max 3500 characters + - Supports code-mixed text (English and Indic languages) + + **Important Note:** + - For numbers larger than 4 digits, use commas (e.g., '10,000' instead of '10000') + - This ensures proper pronunciation as a whole number + + target_language_code : typing.Optional[TextToSpeechLanguage] + The language code in BCP-47 format. + + speaker : typing.Optional[TextToSpeechSpeaker] + The speaker voice to be used for the output audio. + + **Default:** shubh (for bulbul:v3), anushka (for bulbul:v2) + + **Note:** Speaker selection must match the chosen model version. + + **Important:** Speaker names are case-sensitive and must be lowercase (e.g., `ritu` not `Ritu`). + + pitch : typing.Optional[float] + Controls the pitch of the audio. Range: -0.75 to 0.75. Default is 0.0. + + **Note:** Only supported for bulbul:v2. + + pace : typing.Optional[float] + Controls the speed of the audio. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v3:** 0.5 to 2.0 + - **bulbul:v2:** 0.3 to 3.0 + + loudness : typing.Optional[float] + Controls the loudness of the audio. Range: 0.3 to 3.0. Default is 1.0. + + **Note:** Only supported for bulbul:v2. + + speech_sample_rate : typing.Optional[SpeechSampleRate] + Specifies the sample rate of the output audio. Default is 22050 Hz. + + **Note:** OPUS codec only supports 8000, 12000, 16000, 24000, 48000 Hz. + + enable_preprocessing : typing.Optional[bool] + Controls whether normalization of English words and numeric entities is performed. Default is false. + + model : typing.Optional[TextToSpeechModel] + Specifies the model to use for text-to-speech conversion. Default is bulbul:v2. + + temperature : typing.Optional[float] + Controls the randomness of the output. Range: 0.01 to 1.0. Default is 0.6. + + **Note:** Only supported for bulbul:v3. + + enable_cached_responses : typing.Optional[bool] + Enable caching for the request. Default is false. Currently in beta. + + dict_id : typing.Optional[str] + The ID of a pronunciation dictionary to apply during synthesis. When provided, matching words in the input text will be replaced with their custom pronunciations before generating speech. + + Create and manage dictionaries via the [Pronunciation Dictionary API](https://docs.sarvam.ai/api-reference-docs/pronunciation-dictionary/create). Only supported by **bulbul:v3**. + + output_audio_codec : typing.Optional[SpeechStreamCodec] + Specifies the codec for the streamed output audio (e.g., 'mp3'). + + output_audio_bitrate : typing.Optional[SpeechStreamBitrate] + Bitrate for the streamed output audio. Default is '128k'. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. You can pass in configuration such as `chunk_size`, and more to customize the request and response. + + Returns + ------- + typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]] + Success. Returns a streamed audio response in the requested format (e.g., `audio/mpeg` for MP3, `audio/wav` for WAV). + """ + async with self._client_wrapper.httpx_client.stream( + "text-to-speech/stream", + base_url=self._client_wrapper.get_environment().base, + 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, + "temperature": temperature, + "enable_cached_responses": enable_cached_responses, + "dict_id": dict_id, + "output_audio_codec": output_audio_codec, + "output_audio_bitrate": output_audio_bitrate, + }, + headers={ + "content-type": "application/json", + }, + request_options=request_options, + omit=OMIT, + ) as _response: + + async def _stream() -> AsyncHttpResponse[typing.AsyncIterator[bytes]]: + try: + if 200 <= _response.status_code < 300: + _chunk_size = request_options.get("chunk_size", None) if request_options is not None else None + return AsyncHttpResponse( + response=_response, + data=(_chunk async for _chunk in _response.aiter_bytes(chunk_size=_chunk_size)), + ) + await _response.aread() + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 403: + raise ForbiddenError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 422: + raise UnprocessableEntityError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 429: + raise TooManyRequestsError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 500: + raise InternalServerError( + headers=dict(_response.headers), + body=typing.cast( + typing.Any, + parse_obj_as( + type_=typing.Any, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError( + status_code=_response.status_code, headers=dict(_response.headers), body=_response.text + ) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + yield await _stream() diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1aea70a18de69e1b07b45463b833ef69cdc8fabf --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__init__.py @@ -0,0 +1,37 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .types import TextToSpeechStreamingModel, TextToSpeechStreamingSendCompletionEvent +_dynamic_imports: typing.Dict[str, str] = { + "TextToSpeechStreamingModel": ".types", + "TextToSpeechStreamingSendCompletionEvent": ".types", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = ["TextToSpeechStreamingModel", "TextToSpeechStreamingSendCompletionEvent"] diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..931703b8c80c19333f67b13fae9d7f7abd4c7a25 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0a66b736572487b176b9a2fe42c5265379f977d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/raw_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/raw_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7b0c33f1aa1f0bcd5869f75d42a7df415b350bd Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/raw_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/socket_client.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/socket_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1af426464716c2925838cff73c5a2e7f1eb1f6f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/__pycache__/socket_client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/client.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/client.py new file mode 100644 index 0000000000000000000000000000000000000000..cdffcfc57cf9923b373f0872389f566d63aa6fdd --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/client.py @@ -0,0 +1,215 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +import urllib.parse +from contextlib import asynccontextmanager, contextmanager + +import websockets.sync.client as websockets_sync_client +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.jsonable_encoder import jsonable_encoder +from ..core.query_encoder import encode_query +from ..core.remove_none_from_dict import remove_none_from_dict +from ..core.request_options import RequestOptions +from ..core.websocket_compat import InvalidWebSocketStatus, get_status_code +from .raw_client import AsyncRawTextToSpeechStreamingClient, RawTextToSpeechStreamingClient +from .socket_client import AsyncTextToSpeechStreamingSocketClient, TextToSpeechStreamingSocketClient +from .types.text_to_speech_streaming_model import TextToSpeechStreamingModel +from .types.text_to_speech_streaming_send_completion_event import TextToSpeechStreamingSendCompletionEvent + +try: + from websockets.legacy.client import connect as websockets_client_connect # type: ignore +except ImportError: + from websockets import connect as websockets_client_connect # type: ignore + + +class TextToSpeechStreamingClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawTextToSpeechStreamingClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawTextToSpeechStreamingClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawTextToSpeechStreamingClient + """ + return self._raw_client + + @contextmanager + def connect( + self, + *, + model: typing.Optional[TextToSpeechStreamingModel] = None, + send_completion_event: typing.Optional[TextToSpeechStreamingSendCompletionEvent] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[TextToSpeechStreamingSocketClient]: + """ + WebSocket channel for real-time TTS synthesis. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + **Model-Specific Notes:** + - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz. + - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature parameter. Default sample rate: 24000 Hz. Preprocessing is always enabled. + + Parameters + ---------- + model : typing.Optional[TextToSpeechStreamingModel] + Text to speech model to use. + - **bulbul:v2** (default): Standard TTS model with pitch/loudness support + - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness) + + send_completion_event : typing.Optional[TextToSpeechStreamingSendCompletionEvent] + Enable completion event notifications when TTS generation finishes. When set to true, an event message will be sent when the final audio chunk has been generated. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TextToSpeechStreamingSocketClient + """ + ws_url = self._raw_client._client_wrapper.get_environment().production + "/text-to-speech/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "send_completion_event": send_completion_event, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._raw_client._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol: + yield TextToSpeechStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) + + +class AsyncTextToSpeechStreamingClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawTextToSpeechStreamingClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawTextToSpeechStreamingClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawTextToSpeechStreamingClient + """ + return self._raw_client + + @asynccontextmanager + async def connect( + self, + *, + model: typing.Optional[TextToSpeechStreamingModel] = None, + send_completion_event: typing.Optional[TextToSpeechStreamingSendCompletionEvent] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[AsyncTextToSpeechStreamingSocketClient]: + """ + WebSocket channel for real-time TTS synthesis. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + **Model-Specific Notes:** + - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz. + - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature parameter. Default sample rate: 24000 Hz. Preprocessing is always enabled. + + Parameters + ---------- + model : typing.Optional[TextToSpeechStreamingModel] + Text to speech model to use. + - **bulbul:v2** (default): Standard TTS model with pitch/loudness support + - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness) + + send_completion_event : typing.Optional[TextToSpeechStreamingSendCompletionEvent] + Enable completion event notifications when TTS generation finishes. When set to true, an event message will be sent when the final audio chunk has been generated. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncTextToSpeechStreamingSocketClient + """ + ws_url = self._raw_client._client_wrapper.get_environment().production + "/text-to-speech/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "send_completion_event": send_completion_event, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._raw_client._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + async with websockets_client_connect(ws_url, extra_headers=headers) as protocol: + yield AsyncTextToSpeechStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/raw_client.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/raw_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e90542ae04410cacabf343dd6ef0628dd5774fcd --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/raw_client.py @@ -0,0 +1,192 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +import urllib.parse +from contextlib import asynccontextmanager, contextmanager + +import websockets.sync.client as websockets_sync_client +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.jsonable_encoder import jsonable_encoder +from ..core.query_encoder import encode_query +from ..core.remove_none_from_dict import remove_none_from_dict +from ..core.request_options import RequestOptions +from ..core.websocket_compat import InvalidWebSocketStatus, get_status_code +from .socket_client import AsyncTextToSpeechStreamingSocketClient, TextToSpeechStreamingSocketClient +from .types.text_to_speech_streaming_model import TextToSpeechStreamingModel +from .types.text_to_speech_streaming_send_completion_event import TextToSpeechStreamingSendCompletionEvent + +try: + from websockets.legacy.client import connect as websockets_client_connect # type: ignore +except ImportError: + from websockets import connect as websockets_client_connect # type: ignore + + +class RawTextToSpeechStreamingClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + @contextmanager + def connect( + self, + *, + model: typing.Optional[TextToSpeechStreamingModel] = None, + send_completion_event: typing.Optional[TextToSpeechStreamingSendCompletionEvent] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.Iterator[TextToSpeechStreamingSocketClient]: + """ + WebSocket channel for real-time TTS synthesis. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + **Model-Specific Notes:** + - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz. + - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature parameter. Default sample rate: 24000 Hz. Preprocessing is always enabled. + + Parameters + ---------- + model : typing.Optional[TextToSpeechStreamingModel] + Text to speech model to use. + - **bulbul:v2** (default): Standard TTS model with pitch/loudness support + - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness) + + send_completion_event : typing.Optional[TextToSpeechStreamingSendCompletionEvent] + Enable completion event notifications when TTS generation finishes. When set to true, an event message will be sent when the final audio chunk has been generated. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + TextToSpeechStreamingSocketClient + """ + ws_url = self._client_wrapper.get_environment().production + "/text-to-speech/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "send_completion_event": send_completion_event, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + with websockets_sync_client.connect(ws_url, additional_headers=headers) as protocol: + yield TextToSpeechStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) + + +class AsyncRawTextToSpeechStreamingClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + @asynccontextmanager + async def connect( + self, + *, + model: typing.Optional[TextToSpeechStreamingModel] = None, + send_completion_event: typing.Optional[TextToSpeechStreamingSendCompletionEvent] = None, + api_subscription_key: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> typing.AsyncIterator[AsyncTextToSpeechStreamingSocketClient]: + """ + WebSocket channel for real-time TTS synthesis. + + **Note:** This API Reference page is provided for informational purposes only. + The Try It playground may not provide the best experience for streaming audio. + For optimal streaming performance, please use the SDK or implement your own WebSocket client. + + **Model-Specific Notes:** + - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz. + - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature parameter. Default sample rate: 24000 Hz. Preprocessing is always enabled. + + Parameters + ---------- + model : typing.Optional[TextToSpeechStreamingModel] + Text to speech model to use. + - **bulbul:v2** (default): Standard TTS model with pitch/loudness support + - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness) + + send_completion_event : typing.Optional[TextToSpeechStreamingSendCompletionEvent] + Enable completion event notifications when TTS generation finishes. When set to true, an event message will be sent when the final audio chunk has been generated. + + api_subscription_key : typing.Optional[str] + API subscription key for authentication + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncTextToSpeechStreamingSocketClient + """ + ws_url = self._client_wrapper.get_environment().production + "/text-to-speech/ws" + _encoded_query_params = encode_query( + jsonable_encoder( + remove_none_from_dict( + { + "model": model, + "send_completion_event": send_completion_event, + **( + request_options.get("additional_query_parameters", {}) or {} + if request_options is not None + else {} + ), + } + ) + ) + ) + if _encoded_query_params: + ws_url = ws_url + "?" + urllib.parse.urlencode(_encoded_query_params) + headers = self._client_wrapper.get_headers() + if api_subscription_key is not None: + headers["Api-Subscription-Key"] = str(api_subscription_key) + if request_options and "additional_headers" in request_options: + headers.update(request_options["additional_headers"]) + try: + async with websockets_client_connect(ws_url, extra_headers=headers) as protocol: + yield AsyncTextToSpeechStreamingSocketClient(websocket=protocol) + except InvalidWebSocketStatus as exc: + status_code: int = get_status_code(exc) + if status_code == 401: + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Websocket initialized with invalid credentials.", + ) + raise ApiError( + status_code=status_code, + headers=dict(headers), + body="Unexpected error when initializing websocket connection.", + ) diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/socket_client.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/socket_client.py new file mode 100644 index 0000000000000000000000000000000000000000..9cdde1490917978ff2892c8393557191421bfda1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/socket_client.py @@ -0,0 +1,318 @@ +# This file was auto-generated by Fern from our API Definition. + +import json +import typing + +import websockets +import websockets.sync.connection as websockets_sync_connection +from ..core.events import EventEmitterMixin, EventType +from ..core.pydantic_utilities import parse_obj_as +from ..types.audio_output import AudioOutput +from ..types.flush_signal import FlushSignal +from ..types.error_response import ErrorResponse +from ..types.event_response import EventResponse +from ..types.configure_connection import ConfigureConnection +from ..types.configure_connection_data import ConfigureConnectionData +from ..types.ping_signal import PingSignal +from ..types.send_text import SendText +from ..types.send_text_data import SendTextData + +TextToSpeechStreamingSocketClientResponse = typing.Union[AudioOutput, ErrorResponse, EventResponse] + + +class AsyncTextToSpeechStreamingSocketClient(EventEmitterMixin): + def __init__(self, *, websocket: websockets.WebSocketClientProtocol): + super().__init__() + self._websocket = websocket + + async def __aiter__(self): + async for message in self._websocket: + message = json.loads(message) if isinstance(message, str) else message + yield parse_obj_as(TextToSpeechStreamingSocketClientResponse, message) # type: ignore + + async def start_listening(self): + """ + Start listening for messages on the websocket connection. + + Emits events in the following order: + - EventType.OPEN when connection is established + - EventType.MESSAGE for each message received + - EventType.ERROR if an error occurs + - EventType.CLOSE when connection is closed + """ + self._emit(EventType.OPEN, None) + try: + async for raw_message in self._websocket: + raw_message = ( + json.loads(raw_message) + if isinstance(raw_message, str) + else raw_message + ) + parsed = parse_obj_as(TextToSpeechStreamingSocketClientResponse, raw_message) # type: ignore + self._emit(EventType.MESSAGE, parsed) + except websockets.WebSocketException as exc: + self._emit(EventType.ERROR, exc) + finally: + self._emit(EventType.CLOSE, None) + + async def configure( + self, + target_language_code: str, + speaker: str = "anushka", + pitch: float = 0.0, + pace: float = 1.0, + loudness: float = 1.0, + speech_sample_rate: int = 22050, + enable_preprocessing: bool = False, + output_audio_codec: str = "mp3", + output_audio_bitrate: str = "128k", + min_buffer_size: int = 50, + max_chunk_length: int = 150, + dict_id: typing.Optional[str] = None, + ) -> None: + """ + Configuration message required as the first message after establishing the WebSocket connection. + This initializes TTS parameters and can be updated at any time during the WebSocket lifecycle + by sending a new config message. When a config update is sent, any text currently in the buffer + will be automatically flushed and processed before applying the new configuration. + + :param target_language_code: The language of the text is BCP-47 format + :param speaker: The speaker voice to be used for the output audio. Default: Anushka. + Model Compatibility (bulbul:v2): Female: Anushka, Manisha, Vidya, Arya; + Male: Abhilash, Karun, Hitesh + :param pitch: 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. + :param pace: 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. + :param loudness: 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. + :param speech_sample_rate: Specifies the sample rate of the output audio. Supported values are + 8000, 16000, 22050, 24000 Hz. If not provided, the default is 22050 Hz. + :param enable_preprocessing: 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. + :param output_audio_codec: Audio codec (currently supports MP3 only, optimized for real-time playback) + :param output_audio_bitrate: Audio bitrate (choose from 5 supported bitrate options) + :param min_buffer_size: Minimum character length that triggers buffer flushing for TTS model processing + :param max_chunk_length: Maximum length for sentence splitting (adjust based on content length) + :param dict_id: The ID of a pronunciation dictionary to apply during synthesis. + Only supported by bulbul:v3. + """ + data = ConfigureConnectionData( + target_language_code=target_language_code, + speaker=speaker, + pitch=pitch, + pace=pace, + loudness=loudness, + speech_sample_rate=speech_sample_rate, + enable_preprocessing=enable_preprocessing, + output_audio_codec=output_audio_codec, + output_audio_bitrate=output_audio_bitrate, + min_buffer_size=min_buffer_size, + max_chunk_length=max_chunk_length, + dict_id=dict_id, + ) + message = ConfigureConnection(data=data) + await self._send_model(message) + + async def convert(self, text: str) -> None: + """ + Send text to be converted to speech. Text length should be 1-2500 characters. + Recommended: <500 characters for optimal streaming performance. + Real-time endpoints perform better with longer character counts. + + :param text: Text to be synthesized (1-2500 characters, recommended <500) + """ + data = SendTextData(text=text) + message = SendText(data=data) + await self._send_model(message) + + async def flush(self) -> None: + """ + Forces the text buffer to process immediately, regardless of the min_buffer_size threshold. + Use this when you need to process remaining text that hasn't reached the minimum buffer size. + """ + message = FlushSignal() + await self._send_model(message) + + async def ping(self) -> None: + """ + Send ping signal to keep the WebSocket connection alive. The connection automatically + closes after one minute of inactivity. + """ + message = PingSignal() + await self._send_model(message) + + async def recv(self) -> TextToSpeechStreamingSocketClientResponse: + """ + Receive a message from the websocket connection. + """ + data = await self._websocket.recv() + data = json.loads(data) if isinstance(data, str) else data + return parse_obj_as(TextToSpeechStreamingSocketClientResponse, data) # type: ignore + + async def _send(self, data: typing.Any) -> None: + """ + Send a message to the websocket connection. + """ + if isinstance(data, dict): + data = json.dumps(data) + await self._websocket.send(data) + + async def _send_model(self, data: typing.Any) -> None: + """ + Send a Pydantic model to the websocket connection. + """ + await self._send(data.dict()) + + +class TextToSpeechStreamingSocketClient(EventEmitterMixin): + def __init__(self, *, websocket: websockets_sync_connection.Connection): + super().__init__() + self._websocket = websocket + + def __iter__(self): + for message in self._websocket: + message = json.loads(message) if isinstance(message, str) else message + yield parse_obj_as(TextToSpeechStreamingSocketClientResponse, message) # type: ignore + + def start_listening(self): + """ + Start listening for messages on the websocket connection. + + Emits events in the following order: + - EventType.OPEN when connection is established + - EventType.MESSAGE for each message received + - EventType.ERROR if an error occurs + - EventType.CLOSE when connection is closed + """ + self._emit(EventType.OPEN, None) + try: + for raw_message in self._websocket: + raw_message = ( + json.loads(raw_message) + if isinstance(raw_message, str) + else raw_message + ) + parsed = parse_obj_as(TextToSpeechStreamingSocketClientResponse, raw_message) # type: ignore + self._emit(EventType.MESSAGE, parsed) + except websockets.WebSocketException as exc: + self._emit(EventType.ERROR, exc) + finally: + self._emit(EventType.CLOSE, None) + + def configure( + self, + target_language_code: str, + speaker: str = "anushka", + pitch: float = 0.0, + pace: float = 1.0, + loudness: float = 1.0, + speech_sample_rate: int = 22050, + enable_preprocessing: bool = False, + output_audio_codec: str = "mp3", + output_audio_bitrate: str = "128k", + min_buffer_size: int = 50, + max_chunk_length: int = 150, + dict_id: typing.Optional[str] = None, + ) -> None: + """ + Configuration message required as the first message after establishing the WebSocket connection. + This initializes TTS parameters and can be updated at any time during the WebSocket lifecycle + by sending a new config message. When a config update is sent, any text currently in the buffer + will be automatically flushed and processed before applying the new configuration. + + :param target_language_code: The language of the text is BCP-47 format + :param speaker: The speaker voice to be used for the output audio. Default: Anushka. + Model Compatibility (bulbul:v2): Female: Anushka, Manisha, Vidya, Arya; + Male: Abhilash, Karun, Hitesh + :param pitch: 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. + :param pace: 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. + :param loudness: 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. + :param speech_sample_rate: Specifies the sample rate of the output audio. Supported values are + 8000, 16000, 22050, 24000 Hz. If not provided, the default is 22050 Hz. + :param enable_preprocessing: 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. + :param output_audio_codec: Audio codec (currently supports MP3 only, optimized for real-time playback) + :param output_audio_bitrate: Audio bitrate (choose from 5 supported bitrate options) + :param min_buffer_size: Minimum character length that triggers buffer flushing for TTS model processing + :param max_chunk_length: Maximum length for sentence splitting (adjust based on content length) + :param dict_id: The ID of a pronunciation dictionary to apply during synthesis. + Only supported by bulbul:v3. + """ + data = ConfigureConnectionData( + target_language_code=target_language_code, + speaker=speaker, + pitch=pitch, + pace=pace, + loudness=loudness, + speech_sample_rate=speech_sample_rate, + enable_preprocessing=enable_preprocessing, + output_audio_codec=output_audio_codec, + output_audio_bitrate=output_audio_bitrate, + min_buffer_size=min_buffer_size, + max_chunk_length=max_chunk_length, + dict_id=dict_id, + ) + message = ConfigureConnection(data=data) + self._send_model(message) + + def convert(self, text: str) -> None: + """ + Send text to be converted to speech. Text length should be 1-2500 characters. + Recommended: <500 characters for optimal streaming performance. + Real-time endpoints perform better with longer character counts. + + :param text: Text to be synthesized (1-2500 characters, recommended <500) + """ + data = SendTextData(text=text) + message = SendText(data=data) + self._send_model(message) + + def flush(self) -> None: + """ + Forces the text buffer to process immediately, regardless of the min_buffer_size threshold. + Use this when you need to process remaining text that hasn't reached the minimum buffer size. + """ + message = FlushSignal() + self._send_model(message) + + def ping(self) -> None: + """ + Send ping signal to keep the WebSocket connection alive. The connection automatically + closes after one minute of inactivity. + """ + message = PingSignal() + self._send_model(message) + + def recv(self) -> TextToSpeechStreamingSocketClientResponse: + """ + Receive a message from the websocket connection. + """ + data = self._websocket.recv() + data = json.loads(data) if isinstance(data, str) else data + return parse_obj_as(TextToSpeechStreamingSocketClientResponse, data) # type: ignore + + def _send(self, data: typing.Any) -> None: + """ + Send a message to the websocket connection. + """ + if isinstance(data, dict): + data = json.dumps(data) + self._websocket.send(data) + + def _send_model(self, data: typing.Any) -> None: + """ + Send a Pydantic model to the websocket connection. + """ + self._send(data.dict()) diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..48a2ead0977b4ce23154b150c457f10cd187e622 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__init__.py @@ -0,0 +1,38 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .text_to_speech_streaming_model import TextToSpeechStreamingModel + from .text_to_speech_streaming_send_completion_event import TextToSpeechStreamingSendCompletionEvent +_dynamic_imports: typing.Dict[str, str] = { + "TextToSpeechStreamingModel": ".text_to_speech_streaming_model", + "TextToSpeechStreamingSendCompletionEvent": ".text_to_speech_streaming_send_completion_event", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = ["TextToSpeechStreamingModel", "TextToSpeechStreamingSendCompletionEvent"] diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7db60f3cf4f602a5f2a644192f5b8a2127834ae Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/text_to_speech_streaming_model.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/text_to_speech_streaming_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f3da48bf7f96e0156ad323e464db30129144532 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/text_to_speech_streaming_model.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/text_to_speech_streaming_send_completion_event.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/text_to_speech_streaming_send_completion_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82b571865b2cb841dc9dbe4cdebc62ada064497a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/__pycache__/text_to_speech_streaming_send_completion_event.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/text_to_speech_streaming_model.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/text_to_speech_streaming_model.py new file mode 100644 index 0000000000000000000000000000000000000000..d0743ad565f3420db12b8c6803f1beeb02ac9959 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/text_to_speech_streaming_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TextToSpeechStreamingModel = typing.Union[typing.Literal["bulbul:v2", "bulbul:v3"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/text_to_speech_streaming_send_completion_event.py b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/text_to_speech_streaming_send_completion_event.py new file mode 100644 index 0000000000000000000000000000000000000000..516983b667f4aa4d6023aee684b57b2b6144b658 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/text_to_speech_streaming/types/text_to_speech_streaming_send_completion_event.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TextToSpeechStreamingSendCompletionEvent = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__init__.py b/venv/lib/python3.12/site-packages/sarvamai/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad3fb2e86db839aec0bf59ab13fdb9474b25adb --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/__init__.py @@ -0,0 +1,433 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + +import typing +from importlib import import_module + +if typing.TYPE_CHECKING: + from .audio_data import AudioData + from .audio_message import AudioMessage + from .audio_output import AudioOutput + from .audio_output_data import AudioOutputData + from .base_job_parameters import BaseJobParameters + from .bulk_job_callback import BulkJobCallback + from .bulk_job_init_response import BulkJobInitResponse + from .chat_completion_message_tool_call import ChatCompletionMessageToolCall + from .chat_completion_named_tool_choice import ChatCompletionNamedToolChoice + from .chat_completion_named_tool_choice_function import ChatCompletionNamedToolChoiceFunction + from .chat_completion_request_assistant_message import ChatCompletionRequestAssistantMessage + from .chat_completion_request_message import ( + ChatCompletionRequestMessage, + ChatCompletionRequestMessage_Assistant, + ChatCompletionRequestMessage_System, + ChatCompletionRequestMessage_Tool, + ChatCompletionRequestMessage_User, + ) + from .chat_completion_request_system_message import ChatCompletionRequestSystemMessage + from .chat_completion_request_tool_message import ChatCompletionRequestToolMessage + from .chat_completion_request_user_message import ChatCompletionRequestUserMessage + from .chat_completion_response_message import ChatCompletionResponseMessage + from .chat_completion_tool import ChatCompletionTool + from .choice import Choice + from .completion_event_flag import CompletionEventFlag + from .completion_usage import CompletionUsage + from .config_message import ConfigMessage + from .configure_connection import ConfigureConnection + from .configure_connection_data import ConfigureConnectionData + from .configure_connection_data_model import ConfigureConnectionDataModel + from .configure_connection_data_output_audio_bitrate import ConfigureConnectionDataOutputAudioBitrate + from .configure_connection_data_output_audio_codec import ConfigureConnectionDataOutputAudioCodec + from .configure_connection_data_speaker import ConfigureConnectionDataSpeaker + from .configure_connection_data_target_language_code import ConfigureConnectionDataTargetLanguageCode + from .connection_sample_rate import ConnectionSampleRate + from .create_chat_completion_response import CreateChatCompletionResponse + from .diarized_entry import DiarizedEntry + from .diarized_transcript import DiarizedTranscript + from .doc_digitization_create_job_response import DocDigitizationCreateJobResponse + from .doc_digitization_download_files_response import DocDigitizationDownloadFilesResponse + from .doc_digitization_error_code import DocDigitizationErrorCode + from .doc_digitization_error_details import DocDigitizationErrorDetails + from .doc_digitization_error_message import DocDigitizationErrorMessage + from .doc_digitization_job_detail import DocDigitizationJobDetail + from .doc_digitization_job_detail_state import DocDigitizationJobDetailState + from .doc_digitization_job_parameters import DocDigitizationJobParameters + from .doc_digitization_job_state import DocDigitizationJobState + from .doc_digitization_job_status_response import DocDigitizationJobStatusResponse + from .doc_digitization_output_format import DocDigitizationOutputFormat + from .doc_digitization_page_error import DocDigitizationPageError + from .doc_digitization_supported_language import DocDigitizationSupportedLanguage + from .doc_digitization_upload_files_response import DocDigitizationUploadFilesResponse + from .doc_digitization_webhook_callback import DocDigitizationWebhookCallback + from .error_code import ErrorCode + from .error_code2 import ErrorCode2 + from .error_data import ErrorData + from .error_details import ErrorDetails + from .error_details2 import ErrorDetails2 + from .error_message import ErrorMessage + from .error_message2 import ErrorMessage2 + from .error_response import ErrorResponse + from .error_response_data import ErrorResponseData + from .event_response import EventResponse + from .event_response_data import EventResponseData + from .events_data import EventsData + from .events_data_signal_type import EventsDataSignalType + from .file_signed_url_details import FileSignedUrlDetails + from .files_download_response import FilesDownloadResponse + from .files_request import FilesRequest + from .files_upload_response import FilesUploadResponse + from .finish_reason import FinishReason + from .flush_signal import FlushSignal + from .function_call import FunctionCall + from .function_definition import FunctionDefinition + from .input_audio_codec import InputAudioCodec + from .job_state import JobState + from .job_status_response import JobStatusResponse + from .language_identification_response import LanguageIdentificationResponse + from .mode import Mode + from .numerals_format import NumeralsFormat + from .ping_signal import PingSignal + from .pronunciation_dictionary_data import PronunciationDictionaryData + from .pronunciation_dictionary_delete_response import PronunciationDictionaryDeleteResponse + from .pronunciation_dictionary_get_response import PronunciationDictionaryGetResponse + from .pronunciation_dictionary_response import PronunciationDictionaryResponse + from .pronunciation_dictionary_update_response import PronunciationDictionaryUpdateResponse + from .reasoning_effort import ReasoningEffort + from .response_type import ResponseType + from .role import Role + from .sarvam_model_ids import SarvamModelIds + from .send_text import SendText + from .send_text_data import SendTextData + from .speech_sample_rate import SpeechSampleRate + from .speech_stream_bitrate import SpeechStreamBitrate + from .speech_stream_codec import SpeechStreamCodec + from .speech_to_text_job_parameters import SpeechToTextJobParameters + from .speech_to_text_language import SpeechToTextLanguage + from .speech_to_text_model import SpeechToTextModel + from .speech_to_text_response import SpeechToTextResponse + from .speech_to_text_response_data import SpeechToTextResponseData + from .speech_to_text_streaming_response import SpeechToTextStreamingResponse + from .speech_to_text_transcription_data import SpeechToTextTranscriptionData + from .speech_to_text_translate_job_parameters import SpeechToTextTranslateJobParameters + from .speech_to_text_translate_language import SpeechToTextTranslateLanguage + from .speech_to_text_translate_model import SpeechToTextTranslateModel + from .speech_to_text_translate_response import SpeechToTextTranslateResponse + from .speech_to_text_translate_response_data import SpeechToTextTranslateResponseData + from .speech_to_text_translate_streaming_response import SpeechToTextTranslateStreamingResponse + from .speech_to_text_translate_transcription_data import SpeechToTextTranslateTranscriptionData + from .spoken_form_numerals_format import SpokenFormNumeralsFormat + from .stop_configuration import StopConfiguration + from .storage_container_type import StorageContainerType + from .stt_flush_signal import SttFlushSignal + from .task_detail import TaskDetail + from .task_file_details import TaskFileDetails + from .task_state import TaskState + from .text_to_speech_language import TextToSpeechLanguage + from .text_to_speech_model import TextToSpeechModel + from .text_to_speech_output_audio_codec import TextToSpeechOutputAudioCodec + from .text_to_speech_response import TextToSpeechResponse + from .text_to_speech_speaker import TextToSpeechSpeaker + from .timestamps_model import TimestampsModel + from .tool_choice_option import ToolChoiceOption + from .transcription_metrics import TranscriptionMetrics + from .translate_mode import TranslateMode + from .translate_model import TranslateModel + from .translate_source_language import TranslateSourceLanguage + from .translate_speaker_gender import TranslateSpeakerGender + from .translate_target_language import TranslateTargetLanguage + from .translation_response import TranslationResponse + from .translatiterate_target_language import TranslatiterateTargetLanguage + from .transliterate_mode import TransliterateMode + from .transliterate_source_language import TransliterateSourceLanguage + from .transliteration_response import TransliterationResponse +_dynamic_imports: typing.Dict[str, str] = { + "AudioData": ".audio_data", + "AudioMessage": ".audio_message", + "AudioOutput": ".audio_output", + "AudioOutputData": ".audio_output_data", + "BaseJobParameters": ".base_job_parameters", + "BulkJobCallback": ".bulk_job_callback", + "BulkJobInitResponse": ".bulk_job_init_response", + "ChatCompletionMessageToolCall": ".chat_completion_message_tool_call", + "ChatCompletionNamedToolChoice": ".chat_completion_named_tool_choice", + "ChatCompletionNamedToolChoiceFunction": ".chat_completion_named_tool_choice_function", + "ChatCompletionRequestAssistantMessage": ".chat_completion_request_assistant_message", + "ChatCompletionRequestMessage": ".chat_completion_request_message", + "ChatCompletionRequestMessage_Assistant": ".chat_completion_request_message", + "ChatCompletionRequestMessage_System": ".chat_completion_request_message", + "ChatCompletionRequestMessage_Tool": ".chat_completion_request_message", + "ChatCompletionRequestMessage_User": ".chat_completion_request_message", + "ChatCompletionRequestSystemMessage": ".chat_completion_request_system_message", + "ChatCompletionRequestToolMessage": ".chat_completion_request_tool_message", + "ChatCompletionRequestUserMessage": ".chat_completion_request_user_message", + "ChatCompletionResponseMessage": ".chat_completion_response_message", + "ChatCompletionTool": ".chat_completion_tool", + "Choice": ".choice", + "CompletionEventFlag": ".completion_event_flag", + "CompletionUsage": ".completion_usage", + "ConfigMessage": ".config_message", + "ConfigureConnection": ".configure_connection", + "ConfigureConnectionData": ".configure_connection_data", + "ConfigureConnectionDataModel": ".configure_connection_data_model", + "ConfigureConnectionDataOutputAudioBitrate": ".configure_connection_data_output_audio_bitrate", + "ConfigureConnectionDataOutputAudioCodec": ".configure_connection_data_output_audio_codec", + "ConfigureConnectionDataSpeaker": ".configure_connection_data_speaker", + "ConfigureConnectionDataTargetLanguageCode": ".configure_connection_data_target_language_code", + "ConnectionSampleRate": ".connection_sample_rate", + "CreateChatCompletionResponse": ".create_chat_completion_response", + "DiarizedEntry": ".diarized_entry", + "DiarizedTranscript": ".diarized_transcript", + "DocDigitizationCreateJobResponse": ".doc_digitization_create_job_response", + "DocDigitizationDownloadFilesResponse": ".doc_digitization_download_files_response", + "DocDigitizationErrorCode": ".doc_digitization_error_code", + "DocDigitizationErrorDetails": ".doc_digitization_error_details", + "DocDigitizationErrorMessage": ".doc_digitization_error_message", + "DocDigitizationJobDetail": ".doc_digitization_job_detail", + "DocDigitizationJobDetailState": ".doc_digitization_job_detail_state", + "DocDigitizationJobParameters": ".doc_digitization_job_parameters", + "DocDigitizationJobState": ".doc_digitization_job_state", + "DocDigitizationJobStatusResponse": ".doc_digitization_job_status_response", + "DocDigitizationOutputFormat": ".doc_digitization_output_format", + "DocDigitizationPageError": ".doc_digitization_page_error", + "DocDigitizationSupportedLanguage": ".doc_digitization_supported_language", + "DocDigitizationUploadFilesResponse": ".doc_digitization_upload_files_response", + "DocDigitizationWebhookCallback": ".doc_digitization_webhook_callback", + "ErrorCode": ".error_code", + "ErrorCode2": ".error_code2", + "ErrorData": ".error_data", + "ErrorDetails": ".error_details", + "ErrorDetails2": ".error_details2", + "ErrorMessage": ".error_message", + "ErrorMessage2": ".error_message2", + "ErrorResponse": ".error_response", + "ErrorResponseData": ".error_response_data", + "EventResponse": ".event_response", + "EventResponseData": ".event_response_data", + "EventsData": ".events_data", + "EventsDataSignalType": ".events_data_signal_type", + "FileSignedUrlDetails": ".file_signed_url_details", + "FilesDownloadResponse": ".files_download_response", + "FilesRequest": ".files_request", + "FilesUploadResponse": ".files_upload_response", + "FinishReason": ".finish_reason", + "FlushSignal": ".flush_signal", + "FunctionCall": ".function_call", + "FunctionDefinition": ".function_definition", + "InputAudioCodec": ".input_audio_codec", + "JobState": ".job_state", + "JobStatusResponse": ".job_status_response", + "LanguageIdentificationResponse": ".language_identification_response", + "Mode": ".mode", + "NumeralsFormat": ".numerals_format", + "PingSignal": ".ping_signal", + "PronunciationDictionaryData": ".pronunciation_dictionary_data", + "PronunciationDictionaryDeleteResponse": ".pronunciation_dictionary_delete_response", + "PronunciationDictionaryGetResponse": ".pronunciation_dictionary_get_response", + "PronunciationDictionaryResponse": ".pronunciation_dictionary_response", + "PronunciationDictionaryUpdateResponse": ".pronunciation_dictionary_update_response", + "ReasoningEffort": ".reasoning_effort", + "ResponseType": ".response_type", + "Role": ".role", + "SarvamModelIds": ".sarvam_model_ids", + "SendText": ".send_text", + "SendTextData": ".send_text_data", + "SpeechSampleRate": ".speech_sample_rate", + "SpeechStreamBitrate": ".speech_stream_bitrate", + "SpeechStreamCodec": ".speech_stream_codec", + "SpeechToTextJobParameters": ".speech_to_text_job_parameters", + "SpeechToTextLanguage": ".speech_to_text_language", + "SpeechToTextModel": ".speech_to_text_model", + "SpeechToTextResponse": ".speech_to_text_response", + "SpeechToTextResponseData": ".speech_to_text_response_data", + "SpeechToTextStreamingResponse": ".speech_to_text_streaming_response", + "SpeechToTextTranscriptionData": ".speech_to_text_transcription_data", + "SpeechToTextTranslateJobParameters": ".speech_to_text_translate_job_parameters", + "SpeechToTextTranslateLanguage": ".speech_to_text_translate_language", + "SpeechToTextTranslateModel": ".speech_to_text_translate_model", + "SpeechToTextTranslateResponse": ".speech_to_text_translate_response", + "SpeechToTextTranslateResponseData": ".speech_to_text_translate_response_data", + "SpeechToTextTranslateStreamingResponse": ".speech_to_text_translate_streaming_response", + "SpeechToTextTranslateTranscriptionData": ".speech_to_text_translate_transcription_data", + "SpokenFormNumeralsFormat": ".spoken_form_numerals_format", + "StopConfiguration": ".stop_configuration", + "StorageContainerType": ".storage_container_type", + "SttFlushSignal": ".stt_flush_signal", + "TaskDetail": ".task_detail", + "TaskFileDetails": ".task_file_details", + "TaskState": ".task_state", + "TextToSpeechLanguage": ".text_to_speech_language", + "TextToSpeechModel": ".text_to_speech_model", + "TextToSpeechOutputAudioCodec": ".text_to_speech_output_audio_codec", + "TextToSpeechResponse": ".text_to_speech_response", + "TextToSpeechSpeaker": ".text_to_speech_speaker", + "TimestampsModel": ".timestamps_model", + "ToolChoiceOption": ".tool_choice_option", + "TranscriptionMetrics": ".transcription_metrics", + "TranslateMode": ".translate_mode", + "TranslateModel": ".translate_model", + "TranslateSourceLanguage": ".translate_source_language", + "TranslateSpeakerGender": ".translate_speaker_gender", + "TranslateTargetLanguage": ".translate_target_language", + "TranslationResponse": ".translation_response", + "TranslatiterateTargetLanguage": ".translatiterate_target_language", + "TransliterateMode": ".transliterate_mode", + "TransliterateSourceLanguage": ".transliterate_source_language", + "TransliterationResponse": ".transliteration_response", +} + + +def __getattr__(attr_name: str) -> typing.Any: + module_name = _dynamic_imports.get(attr_name) + if module_name is None: + raise AttributeError(f"No {attr_name} found in _dynamic_imports for module name -> {__name__}") + try: + module = import_module(module_name, __package__) + if module_name == f".{attr_name}": + return module + else: + return getattr(module, attr_name) + except ImportError as e: + raise ImportError(f"Failed to import {attr_name} from {module_name}: {e}") from e + except AttributeError as e: + raise AttributeError(f"Failed to get {attr_name} from {module_name}: {e}") from e + + +def __dir__(): + lazy_attrs = list(_dynamic_imports.keys()) + return sorted(lazy_attrs) + + +__all__ = [ + "AudioData", + "AudioMessage", + "AudioOutput", + "AudioOutputData", + "BaseJobParameters", + "BulkJobCallback", + "BulkJobInitResponse", + "ChatCompletionMessageToolCall", + "ChatCompletionNamedToolChoice", + "ChatCompletionNamedToolChoiceFunction", + "ChatCompletionRequestAssistantMessage", + "ChatCompletionRequestMessage", + "ChatCompletionRequestMessage_Assistant", + "ChatCompletionRequestMessage_System", + "ChatCompletionRequestMessage_Tool", + "ChatCompletionRequestMessage_User", + "ChatCompletionRequestSystemMessage", + "ChatCompletionRequestToolMessage", + "ChatCompletionRequestUserMessage", + "ChatCompletionResponseMessage", + "ChatCompletionTool", + "Choice", + "CompletionEventFlag", + "CompletionUsage", + "ConfigMessage", + "ConfigureConnection", + "ConfigureConnectionData", + "ConfigureConnectionDataModel", + "ConfigureConnectionDataOutputAudioBitrate", + "ConfigureConnectionDataOutputAudioCodec", + "ConfigureConnectionDataSpeaker", + "ConfigureConnectionDataTargetLanguageCode", + "ConnectionSampleRate", + "CreateChatCompletionResponse", + "DiarizedEntry", + "DiarizedTranscript", + "DocDigitizationCreateJobResponse", + "DocDigitizationDownloadFilesResponse", + "DocDigitizationErrorCode", + "DocDigitizationErrorDetails", + "DocDigitizationErrorMessage", + "DocDigitizationJobDetail", + "DocDigitizationJobDetailState", + "DocDigitizationJobParameters", + "DocDigitizationJobState", + "DocDigitizationJobStatusResponse", + "DocDigitizationOutputFormat", + "DocDigitizationPageError", + "DocDigitizationSupportedLanguage", + "DocDigitizationUploadFilesResponse", + "DocDigitizationWebhookCallback", + "ErrorCode", + "ErrorCode2", + "ErrorData", + "ErrorDetails", + "ErrorDetails2", + "ErrorMessage", + "ErrorMessage2", + "ErrorResponse", + "ErrorResponseData", + "EventResponse", + "EventResponseData", + "EventsData", + "EventsDataSignalType", + "FileSignedUrlDetails", + "FilesDownloadResponse", + "FilesRequest", + "FilesUploadResponse", + "FinishReason", + "FlushSignal", + "FunctionCall", + "FunctionDefinition", + "InputAudioCodec", + "JobState", + "JobStatusResponse", + "LanguageIdentificationResponse", + "Mode", + "NumeralsFormat", + "PingSignal", + "PronunciationDictionaryData", + "PronunciationDictionaryDeleteResponse", + "PronunciationDictionaryGetResponse", + "PronunciationDictionaryResponse", + "PronunciationDictionaryUpdateResponse", + "ReasoningEffort", + "ResponseType", + "Role", + "SarvamModelIds", + "SendText", + "SendTextData", + "SpeechSampleRate", + "SpeechStreamBitrate", + "SpeechStreamCodec", + "SpeechToTextJobParameters", + "SpeechToTextLanguage", + "SpeechToTextModel", + "SpeechToTextResponse", + "SpeechToTextResponseData", + "SpeechToTextStreamingResponse", + "SpeechToTextTranscriptionData", + "SpeechToTextTranslateJobParameters", + "SpeechToTextTranslateLanguage", + "SpeechToTextTranslateModel", + "SpeechToTextTranslateResponse", + "SpeechToTextTranslateResponseData", + "SpeechToTextTranslateStreamingResponse", + "SpeechToTextTranslateTranscriptionData", + "SpokenFormNumeralsFormat", + "StopConfiguration", + "StorageContainerType", + "SttFlushSignal", + "TaskDetail", + "TaskFileDetails", + "TaskState", + "TextToSpeechLanguage", + "TextToSpeechModel", + "TextToSpeechOutputAudioCodec", + "TextToSpeechResponse", + "TextToSpeechSpeaker", + "TimestampsModel", + "ToolChoiceOption", + "TranscriptionMetrics", + "TranslateMode", + "TranslateModel", + "TranslateSourceLanguage", + "TranslateSpeakerGender", + "TranslateTargetLanguage", + "TranslationResponse", + "TranslatiterateTargetLanguage", + "TransliterateMode", + "TransliterateSourceLanguage", + "TransliterationResponse", +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2884eb6008cd59448f05d6fc1b069da89b0c8c96 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/audio_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/audio_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74c218a0a7ff54f9fd10d9ef890022c8ad7a892c Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/audio_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/audio_output_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/audio_output_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8dbcd03127f2604b5c1ac7e12b947ae73362c68 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/audio_output_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/bulk_job_init_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/bulk_job_init_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1cf4665df2e7e72b2c04a0f5eb68c08f47ed68d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/bulk_job_init_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_chunk.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_chunk.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a083cc2b88ff763f27642cb514324f6c1451e4b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_chunk.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_named_tool_choice.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_named_tool_choice.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5671a4e623b007ef4f06b3ba8d29376ca4d4a8b0 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_named_tool_choice.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_assistant_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_assistant_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7be4eb94efa0523f0ae3f84116848360a62f168a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_assistant_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_system_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_system_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c9cbaad1c1099eb612c0531e5eca500ee97b06b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_system_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_user_message.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_user_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0cd2083681e45b9c370723026904c0accabcb50 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_request_user_message.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_tool.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4474b0e42edfd0a6f1306cb598262ac64e40b7d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/chat_completion_tool.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/choice.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/choice.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b26133f5b2a374eef8b6086fa6c3b595b3f1659 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/choice.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/completion_event_flag.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/completion_event_flag.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b734fd177d31574e49970994e4c6f39812a1f09 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/completion_event_flag.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/completion_usage.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/completion_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b59e2ed5de793a2cdbf1fc656094620feeec2ef6 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/completion_usage.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/configure_connection_data_output_audio_codec.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/configure_connection_data_output_audio_codec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..460ad05ff98774b6f71a4d7e8895b3998183d0b0 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/configure_connection_data_output_audio_codec.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/connection_sample_rate.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/connection_sample_rate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e68b9f4b59460667f96e501fabb43f84dcd7a840 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/connection_sample_rate.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/diarized_transcript.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/diarized_transcript.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21e6a15e21eb40831472dfe77da25859335b7066 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/diarized_transcript.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_create_job_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_create_job_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a0a43ab60ba8ac25802cb48c6f42b39dea3707f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_create_job_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_download_files_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_download_files_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db7409a461898f5c6ae737a510f02ffc32605425 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_download_files_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_error_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_error_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4dc3b5d36768d64aaf17d78c7f99eda9bf1dfc3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_error_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_detail_state.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_detail_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8497017fff9c398cc24763f1967f6e3a3f7c6d33 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_detail_state.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_parameters.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_parameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd2ad512e8feeeafb9ae12b9d31e6e1d5a0d25e9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_parameters.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_state.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c54ee04f190936d83288a5aba44aae30e8b206d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_job_state.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_page_error.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_page_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79b96e2036ff336b21b9f7e929df857b286c7dd0 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_page_error.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_supported_language.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_supported_language.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8339f94ec828eb37b0f41ce280254f58c38cdb72 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/doc_digitization_supported_language.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/error_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/error_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57fcaf324ce22d2ff4a3451911d1e499698d53dc Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/error_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/error_response_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/error_response_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63f4490ed2410f60fe4b1eee537ea2babdaa1a04 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/error_response_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/event_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/event_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc2acb94a80d0aa4d1361c7bd328eb4c7bc7df5b Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/event_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/file_signed_url_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/file_signed_url_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b660d0444b75882b54ea557d34e5fcf7fb96a81d Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/file_signed_url_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/files_upload_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/files_upload_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ea47269af031533103d7adfbec27caf8b36f90 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/files_upload_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/flush_signal.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/flush_signal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1805b7bb31f55a393b64d6a17c6473f1e231189f Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/flush_signal.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/function_definition.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/function_definition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..577442533ab83f037a9e495bd1d3f12421864be4 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/function_definition.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/job_state.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/job_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20cc33e4ef7c07cc71a72873454aac237c4ce9ce Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/job_state.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/pronunciation_dictionary_get_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/pronunciation_dictionary_get_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfd42de29aa3059e4816b39b4f041e691d4d93e4 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/pronunciation_dictionary_get_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/pronunciation_dictionary_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/pronunciation_dictionary_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6618d1f134c1c4917529139174ca231bdd93fbb Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/pronunciation_dictionary_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/role.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/role.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..649ba24d6a9dd963760716d19e355e52e5a97de2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/role.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/send_text.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/send_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6aceb21d478c5484b331265dae1d470678232469 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/send_text.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/send_text_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/send_text_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c361b07e91ee1ca3ec1861f423835c39a1e6683 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/send_text_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_sample_rate.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_sample_rate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a9692578a69a5f9c50739b9dd0f4a4e677737f4 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_sample_rate.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_stream_codec.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_stream_codec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38528bcabfab05478c04c498fd067303af081c37 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_stream_codec.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_transcription_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_transcription_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..133fdf848deb4d103b2a7bad791d76f1a5935a2a Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_transcription_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_language.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_language.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..064f6ce59119affca27753cb740c21c976dcd951 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_language.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_model.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2a26210c18f5a7293cc5db78fba0661dfc1ab48 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_model.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_response_data.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_response_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d1b5b56e93a834fb3a5cb89ed375222afc9cbca Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/speech_to_text_translate_response_data.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/stop_configuration.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/stop_configuration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8768d24c3f8c8057ed826ce28ca8430816570f27 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/stop_configuration.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/storage_container_type.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/storage_container_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78cc33ea5eaf82a85609ff19da7c41161f170792 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/storage_container_type.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/stt_flush_signal.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/stt_flush_signal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53e93b0d2bd1b5a3feac6981cb9945481b379a6e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/stt_flush_signal.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/task_file_details.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/task_file_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3502c2fa63dc148f0f78916698d7bd40c3f0a355 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/task_file_details.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/task_state.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/task_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c507a15a7916d58c07a8dc9713138b3363beb2bf Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/task_state.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/text_to_speech_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/text_to_speech_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0d3fab9cc6034672992847a65258e767261950c Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/text_to_speech_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/timestamps_model.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/timestamps_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ae294865bbaded3be0bdd77dba4ec75704d6825 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/timestamps_model.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/tool_choice_option.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/tool_choice_option.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc8b01468a65208d2b96f97d4c751499ad6f1889 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/tool_choice_option.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_source_language.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_source_language.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4309b808670e7faf3f287e0b9e903f81ba44fedd Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_source_language.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_speaker_gender.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_speaker_gender.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..790d5115556d6079b8caa0675038a9ee36bd3a3e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_speaker_gender.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_target_language.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_target_language.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59eaf82f5484a663aa7dbbc2b8d748851117dc79 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/translate_target_language.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliterate_mode.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliterate_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4905e15e3134cf6beeb9118b3bd713bd3fe9deed Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliterate_mode.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliterate_source_language.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliterate_source_language.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb1e20a3ee6c0dbeb7e32e0a0b657ee34d8502e Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliterate_source_language.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliteration_response.cpython-312.pyc b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliteration_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..120b6a01ccdf1d33e4a28dcc1626a05c6e5d7ed8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/sarvamai/types/__pycache__/transliteration_response.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/audio_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/audio_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e8ebd03d7b0252896a2f6e458118a750d6eab1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/audio_data.py @@ -0,0 +1,38 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class AudioData(UniversalBaseModel): + data: str = pydantic.Field() + """ + Base64 encoded audio data + """ + + sample_rate: int = pydantic.Field() + """ + Audio sample rate in Hz for individual audio messages. + + **Backward Compatibility**: This property is maintained for legacy support. + **Recommended**: Use the connection-level sample_rate parameter instead. + **Note**: 8kHz is only supported via connection parameter, not in AudioData messages. + + Supported values: 16kHz (preferred), 22.05kHz, 24kHz + """ + + encoding: typing.Literal["audio/wav"] = pydantic.Field(default="audio/wav") + """ + Audio encoding format + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/audio_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/audio_message.py new file mode 100644 index 0000000000000000000000000000000000000000..29b0608d8c7fc62a951163c43d814769ad883953 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/audio_message.py @@ -0,0 +1,20 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .audio_data import AudioData + + +class AudioMessage(UniversalBaseModel): + audio: AudioData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/audio_output.py b/venv/lib/python3.12/site-packages/sarvamai/types/audio_output.py new file mode 100644 index 0000000000000000000000000000000000000000..57bf5cf6c9663bc2adf3d7676b45181eaf2282f9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/audio_output.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .audio_output_data import AudioOutputData + + +class AudioOutput(UniversalBaseModel): + type: typing.Literal["audio"] = "audio" + data: AudioOutputData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/audio_output_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/audio_output_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb5babc3d212f332b5c173f0d00319ad4e52f08 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/audio_output_data.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class AudioOutputData(UniversalBaseModel): + content_type: str = pydantic.Field() + """ + MIME type of the audio content (e.g., 'audio/mp3', 'audio/wav') + """ + + audio: str = pydantic.Field() + """ + Base64-encoded audio data ready for playback or download + """ + + request_id: typing.Optional[str] = pydantic.Field(default=None) + """ + Unique identifier for the request + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/base_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/types/base_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..b5289d1792de4c68a41b2ee317dc8556a629e39a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/base_job_parameters.py @@ -0,0 +1,17 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class BaseJobParameters(UniversalBaseModel): + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/bulk_job_callback.py b/venv/lib/python3.12/site-packages/sarvamai/types/bulk_job_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..c2d72497b236f6e09398cc73fa340cfe78fde972 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/bulk_job_callback.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class BulkJobCallback(UniversalBaseModel): + url: str = pydantic.Field() + """ + Webhook url to call upon job completion + """ + + auth_token: typing.Optional[str] = pydantic.Field(default=None) + """ + Authorization token required for the callback Url + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/bulk_job_init_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/bulk_job_init_response.py new file mode 100644 index 0000000000000000000000000000000000000000..bb115f4b2c3d17dcc2d5fcf761c1e830a225d2ad --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/bulk_job_init_response.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .base_job_parameters import BaseJobParameters +from .job_state import JobState +from .storage_container_type import StorageContainerType + + +class BulkJobInitResponse(UniversalBaseModel): + job_id: str = pydantic.Field() + """ + Job UUID. + """ + + storage_container_type: StorageContainerType = pydantic.Field() + """ + Storage Container Type + """ + + job_parameters: BaseJobParameters + job_state: JobState + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_chunk.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..9620891c9db4fa640d9908e705b23c38c1b6ae2e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_chunk.py @@ -0,0 +1,50 @@ +# This file was added to support streaming chat completions (SSE). + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .chunk_choice import ChunkChoice +from .completion_usage import CompletionUsage + + +class ChatCompletionChunk(UniversalBaseModel): + """A single chunk from a streaming chat completion response.""" + + id: str = pydantic.Field() + """ + A unique identifier for the chat completion (same across all chunks). + """ + + choices: typing.List[ChunkChoice] = pydantic.Field() + """ + A list of chat completion choices for this chunk. + """ + + created: int = pydantic.Field() + """ + The Unix timestamp (in seconds) of when the chat completion was created. + """ + + model: str = pydantic.Field() + """ + The model used for the chat completion. + """ + + object: typing.Literal["chat.completion.chunk"] = pydantic.Field(default="chat.completion.chunk") + """ + The object type, which is always `chat.completion.chunk` for streaming. + """ + + service_tier: typing.Optional[str] = None + system_fingerprint: typing.Optional[str] = None + usage: typing.Optional[CompletionUsage] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_message_tool_call.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_message_tool_call.py new file mode 100644 index 0000000000000000000000000000000000000000..881fe2b1af77dfdc61504cd7572a7315f62c0632 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_message_tool_call.py @@ -0,0 +1,30 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .function_call import FunctionCall + + +class ChatCompletionMessageToolCall(UniversalBaseModel): + id: str = pydantic.Field() + """ + The ID of the tool call. + """ + + type: typing.Literal["function"] = pydantic.Field(default="function") + """ + The type of the tool call, currently only `function`. + """ + + function: FunctionCall + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_named_tool_choice.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_named_tool_choice.py new file mode 100644 index 0000000000000000000000000000000000000000..4735e3237295defc9aa12d3d65edc4b9671b98e0 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_named_tool_choice.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .chat_completion_named_tool_choice_function import ChatCompletionNamedToolChoiceFunction + + +class ChatCompletionNamedToolChoice(UniversalBaseModel): + type: typing.Literal["function"] = pydantic.Field(default="function") + """ + The type of the tool. Currently, only `function` is supported. + """ + + function: ChatCompletionNamedToolChoiceFunction + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_named_tool_choice_function.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_named_tool_choice_function.py new file mode 100644 index 0000000000000000000000000000000000000000..d0bd47fb53af38feb7346280a0c07a35bfb18519 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_named_tool_choice_function.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ChatCompletionNamedToolChoiceFunction(UniversalBaseModel): + name: str = pydantic.Field() + """ + The name of the function to call. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_assistant_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_assistant_message.py new file mode 100644 index 0000000000000000000000000000000000000000..155ec7a76e2b94958b31cf375db78690b126c3df --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_assistant_message.py @@ -0,0 +1,28 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .chat_completion_message_tool_call import ChatCompletionMessageToolCall + + +class ChatCompletionRequestAssistantMessage(UniversalBaseModel): + content: typing.Optional[str] = pydantic.Field(default=None) + """ + The contents of the assistant message + """ + + tool_calls: typing.Optional[typing.List[ChatCompletionMessageToolCall]] = pydantic.Field(default=None) + """ + The tool calls generated by the model. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_message.py new file mode 100644 index 0000000000000000000000000000000000000000..afc7af95f72d8cc0f8ee9ba4c6de0fa2eedde3c0 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_message.py @@ -0,0 +1,79 @@ +# This file was auto-generated by Fern from our API Definition. + +from __future__ import annotations + +import typing + +import pydantic +import typing_extensions +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .chat_completion_message_tool_call import ChatCompletionMessageToolCall + + +class ChatCompletionRequestMessage_Assistant(UniversalBaseModel): + role: typing.Literal["assistant"] = "assistant" + content: typing.Optional[str] = None + tool_calls: typing.Optional[typing.List[ChatCompletionMessageToolCall]] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow + + +class ChatCompletionRequestMessage_System(UniversalBaseModel): + role: typing.Literal["system"] = "system" + content: str + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow + + +class ChatCompletionRequestMessage_Tool(UniversalBaseModel): + role: typing.Literal["tool"] = "tool" + content: str + tool_call_id: str + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow + + +class ChatCompletionRequestMessage_User(UniversalBaseModel): + role: typing.Literal["user"] = "user" + content: str + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow + + +ChatCompletionRequestMessage = typing_extensions.Annotated[ + typing.Union[ + ChatCompletionRequestMessage_Assistant, + ChatCompletionRequestMessage_System, + ChatCompletionRequestMessage_Tool, + ChatCompletionRequestMessage_User, + ], + pydantic.Field(discriminator="role"), +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_system_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_system_message.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c75504bac061fbc30b0af7490232103d0b1dbb --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_system_message.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ChatCompletionRequestSystemMessage(UniversalBaseModel): + content: str = pydantic.Field() + """ + The contents of the system message. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_tool_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_tool_message.py new file mode 100644 index 0000000000000000000000000000000000000000..b82b831aed0ce33bb156e7f81b8498f83d498494 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_tool_message.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ChatCompletionRequestToolMessage(UniversalBaseModel): + content: str = pydantic.Field() + """ + The contents of the tool message. + """ + + tool_call_id: str = pydantic.Field() + """ + Tool call that this message is responding to. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_user_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_user_message.py new file mode 100644 index 0000000000000000000000000000000000000000..ede009ccda3b629f49dd9298b356e127922d7527 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_request_user_message.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ChatCompletionRequestUserMessage(UniversalBaseModel): + content: str = pydantic.Field() + """ + The contents of the user message. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_response_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_response_message.py new file mode 100644 index 0000000000000000000000000000000000000000..6757d1d63f67afde8f9fdc81b876bbafb2ad92dc --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_response_message.py @@ -0,0 +1,40 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .chat_completion_message_tool_call import ChatCompletionMessageToolCall +from .role import Role + + +class ChatCompletionResponseMessage(UniversalBaseModel): + content: typing.Optional[str] = pydantic.Field(default=None) + """ + The contents of the message. + """ + + refusal: typing.Optional[str] = None + reasoning_content: typing.Optional[str] = pydantic.Field(default=None) + """ + The contents of the reasoning message. + """ + + role: Role = pydantic.Field(default="assistant") + """ + The role of the author of this message. + """ + + tool_calls: typing.Optional[typing.List[ChatCompletionMessageToolCall]] = pydantic.Field(default=None) + """ + The tool calls generated by the model. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_tool.py b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..1484d9f28f3a45880c72b82d49acfa66935b6792 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chat_completion_tool.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .function_definition import FunctionDefinition + + +class ChatCompletionTool(UniversalBaseModel): + type: typing.Literal["function"] = pydantic.Field(default="function") + """ + The type of the tool. Currently, only `function` is supported. + """ + + function: FunctionDefinition + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/choice.py b/venv/lib/python3.12/site-packages/sarvamai/types/choice.py new file mode 100644 index 0000000000000000000000000000000000000000..eae3886d3cf9907df6fb2d6ed2e1272111ee860a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/choice.py @@ -0,0 +1,35 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .chat_completion_response_message import ChatCompletionResponseMessage +from .finish_reason import FinishReason + + +class Choice(UniversalBaseModel): + finish_reason: FinishReason = pydantic.Field() + """ + The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, + `length` if the maximum number of tokens specified in the request was reached, + `content_filter` if content was omitted due to a flag from our content filters, + `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. + """ + + index: int = pydantic.Field() + """ + The index of the choice in the list of choices. + """ + + logprobs: typing.Optional[typing.Dict[str, typing.Any]] = None + message: ChatCompletionResponseMessage + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/choice_delta.py b/venv/lib/python3.12/site-packages/sarvamai/types/choice_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..a484d6e6ba4b9739834026738a79d9febb826db2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/choice_delta.py @@ -0,0 +1,45 @@ +# This file was added to support streaming chat completions (SSE). + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .choice_delta_tool_call import ChoiceDeltaToolCall +from .role import Role + + +class ChoiceDelta(UniversalBaseModel): + """Delta content in a streaming chat completion chunk.""" + + content: typing.Optional[str] = pydantic.Field(default=None) + """ + The contents of the chunk message. + """ + + refusal: typing.Optional[str] = None + + reasoning_content: typing.Optional[str] = pydantic.Field(default=None) + """ + The contents of the reasoning message chunk. + """ + + role: typing.Optional[Role] = pydantic.Field(default=None) + """ + The role of the author of this message (only present in first chunk). + """ + + function_call: typing.Optional[typing.Dict[str, typing.Any]] = None + + tool_calls: typing.Optional[typing.List[ChoiceDeltaToolCall]] = pydantic.Field(default=None) + """ + Tool calls generated by the model in this chunk. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/choice_delta_tool_call.py b/venv/lib/python3.12/site-packages/sarvamai/types/choice_delta_tool_call.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd461f1bb73296c1f4ef45a6104fe9be7c8c0e8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/choice_delta_tool_call.py @@ -0,0 +1,40 @@ +# This file was added to support streaming chat completions (SSE). + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ChoiceDeltaToolCallFunction(UniversalBaseModel): + """Partial function call data in a streaming tool call.""" + + name: typing.Optional[str] = None + arguments: typing.Optional[str] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow + + +class ChoiceDeltaToolCall(UniversalBaseModel): + """A tool call chunk in a streaming response (fields may be null in subsequent chunks).""" + + index: int + id: typing.Optional[str] = None + type: typing.Optional[typing.Literal["function"]] = None + function: typing.Optional[ChoiceDeltaToolCallFunction] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/chunk_choice.py b/venv/lib/python3.12/site-packages/sarvamai/types/chunk_choice.py new file mode 100644 index 0000000000000000000000000000000000000000..53bae4ce28aa7df896679146f424dc582b1e8d88 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/chunk_choice.py @@ -0,0 +1,34 @@ +# This file was added to support streaming chat completions (SSE). + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .choice_delta import ChoiceDelta +from .finish_reason import FinishReason + + +class ChunkChoice(UniversalBaseModel): + """A choice in a streaming chat completion chunk.""" + + delta: ChoiceDelta + finish_reason: typing.Optional[FinishReason] = pydantic.Field(default=None) + """ + The reason the model stopped generating (null while streaming, set on the final chunk). + """ + + index: int = pydantic.Field() + """ + The index of the choice in the list of choices. + """ + + logprobs: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/completion_event_flag.py b/venv/lib/python3.12/site-packages/sarvamai/types/completion_event_flag.py new file mode 100644 index 0000000000000000000000000000000000000000..207e9b612d34ca56c4827116096f12b701c04481 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/completion_event_flag.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +CompletionEventFlag = typing.Union[typing.Literal["true", "false"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/completion_usage.py b/venv/lib/python3.12/site-packages/sarvamai/types/completion_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..183e39bb23580a06db6d25c32888840d6d8b04f5 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/completion_usage.py @@ -0,0 +1,35 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class CompletionUsage(UniversalBaseModel): + completion_tokens: int = pydantic.Field() + """ + Number of tokens in the generated completion. + """ + + prompt_tokens: int = pydantic.Field() + """ + Number of tokens in the prompt. + """ + + total_tokens: int = pydantic.Field() + """ + Total number of tokens used in the request (prompt + completion). + """ + + completion_tokens_details: typing.Optional[typing.Dict[str, typing.Any]] = None + prompt_tokens_details: typing.Optional[typing.Dict[str, typing.Any]] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/config_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/config_message.py new file mode 100644 index 0000000000000000000000000000000000000000..62319ecf9e609b30ff32089dc26c5909c37fbd43 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/config_message.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ConfigMessage(UniversalBaseModel): + type: typing.Literal["config"] = pydantic.Field(default="config") + """ + Message type identifier for configuration + """ + + prompt: typing.Optional[str] = pydantic.Field(default=None) + """ + Prompt for ASR model to improve transcription accuracy. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection.py b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..f376d5c393ede0bd68e16b123aaee004093c3ec7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .configure_connection_data import ConfigureConnectionData + + +class ConfigureConnection(UniversalBaseModel): + """ + Configuration message required as the first message after establishing the WebSocket connection. + This initializes TTS parameters and can be updated at any time during the WebSocket lifecycle + by sending a new config message. When a config update is sent, any text currently in the buffer + will be automatically flushed and processed before applying the new configuration. + + **Model-Specific Notes:** + - **bulbul:v2:** Supports pitch, loudness, pace (0.3-3.0). Default sample rate: 22050 Hz. + - **bulbul:v3:** Does NOT support pitch/loudness. Pace range: 0.5-2.0. Supports temperature. Default sample rate: 24000 Hz. + """ + + type: typing.Literal["config"] = "config" + data: ConfigureConnectionData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data.py new file mode 100644 index 0000000000000000000000000000000000000000..90c6f4dc4864c0fab66194b004142fdbaef00044 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data.py @@ -0,0 +1,134 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .configure_connection_data_model import ConfigureConnectionDataModel +from .configure_connection_data_output_audio_bitrate import ConfigureConnectionDataOutputAudioBitrate +from .configure_connection_data_output_audio_codec import ConfigureConnectionDataOutputAudioCodec +from .configure_connection_data_speaker import ConfigureConnectionDataSpeaker +from .configure_connection_data_target_language_code import ConfigureConnectionDataTargetLanguageCode + + +class ConfigureConnectionData(UniversalBaseModel): + model: typing.Optional[ConfigureConnectionDataModel] = pydantic.Field(default=None) + """ + Specifies the model to use for text-to-speech conversion. + - **bulbul:v2** (default): Standard TTS model with pitch/loudness support + - **bulbul:v3**: Advanced model with temperature control (no pitch/loudness) + """ + + target_language_code: ConfigureConnectionDataTargetLanguageCode = pydantic.Field() + """ + The language of the text in BCP-47 format + """ + + speaker: ConfigureConnectionDataSpeaker = pydantic.Field() + """ + The speaker voice to be used for the output audio. + + **Model Compatibility:** + - **bulbul:v2:** anushka (default), abhilash, manisha, vidya, arya, karun, hitesh + - **bulbul:v3:** aditya (default), ritu, priya, neha, rahul, pooja, rohan, simran, kavya, amit, dev, ishita, shreya, ratan, varun, manan, sumit, roopa, kabir, aayan, shubh, ashutosh, advait, amelia, sophia + + **Note:** Speaker selection must match the chosen model version. + """ + + pitch: typing.Optional[float] = pydantic.Field(default=None) + """ + 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. + + **Note:** NOT supported for bulbul:v3. Will be ignored if provided. + """ + + pace: typing.Optional[float] = pydantic.Field(default=None) + """ + Controls the speed of the audio. Lower values result in slower speech, + while higher values make it faster. Default is 1.0. + + **Model-specific ranges:** + - **bulbul:v2:** 0.3 to 3.0 + - **bulbul:v3:** 0.5 to 2.0 + """ + + loudness: typing.Optional[float] = pydantic.Field(default=None) + """ + 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. + + **Note:** NOT supported for bulbul:v3. Will be ignored if provided. + """ + + temperature: typing.Optional[float] = pydantic.Field(default=None) + """ + Controls the randomness of the output. Lower values make the output more + focused and deterministic, while higher values make it more random. + The suitable range is between 0.01 and 1.0. Default is 0.6. + + **Note:** Only supported for bulbul:v3. Will be ignored for bulbul:v2. + """ + + speech_sample_rate: typing.Optional[int] = pydantic.Field(default=None) + """ + Specifies the sample rate of the output audio. Supported values are + 8000, 16000, 22050, 24000 Hz. + + **Model-specific defaults:** + - **bulbul:v2:** 22050 Hz + - **bulbul:v3:** 24000 Hz + """ + + enable_preprocessing: typing.Optional[bool] = pydantic.Field(default=None) + """ + 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. + + **Model-specific defaults:** + - **bulbul:v2:** false (optional) + - **bulbul:v3:** Always enabled (cannot be disabled) + """ + + output_audio_codec: typing.Optional[ConfigureConnectionDataOutputAudioCodec] = pydantic.Field(default=None) + """ + Audio codec (currently supports MP3 only, optimized for real-time playback) + """ + + output_audio_bitrate: typing.Optional[ConfigureConnectionDataOutputAudioBitrate] = pydantic.Field(default=None) + """ + Audio bitrate (choose from 5 supported bitrate options) + """ + + dict_id: typing.Optional[str] = pydantic.Field(default=None) + """ + The ID of a pronunciation dictionary to apply during synthesis. + When provided, matching words in the input text will be replaced + with their custom pronunciations before generating speech. + + Create and manage dictionaries via the `/text-to-speech/pronunciation-dictionary` endpoints. + + **Note:** Only supported by **bulbul:v3**. + """ + + min_buffer_size: typing.Optional[int] = pydantic.Field(default=None) + """ + Minimum character length that triggers buffer flushing for TTS model processing + """ + + max_chunk_length: typing.Optional[int] = pydantic.Field(default=None) + """ + Maximum length for sentence splitting (adjust based on content length) + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_model.py b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ff7976fe4bfc9409945e3dd02f2965106ca478 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ConfigureConnectionDataModel = typing.Union[typing.Literal["bulbul:v2", "bulbul:v3"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_output_audio_bitrate.py b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_output_audio_bitrate.py new file mode 100644 index 0000000000000000000000000000000000000000..8c71b520785a3794f2bbc9339b0bcc3e8b0bc5e7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_output_audio_bitrate.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ConfigureConnectionDataOutputAudioBitrate = typing.Union[ + typing.Literal["32k", "64k", "96k", "128k", "192k"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_output_audio_codec.py b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_output_audio_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..a011bc646e6fd06dd4769e55440774da29c0ceb9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_output_audio_codec.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ConfigureConnectionDataOutputAudioCodec = typing.Union[ + typing.Literal["linear16", "mulaw", "alaw", "opus", "flac", "aac", "wav", "mp3"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_speaker.py b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_speaker.py new file mode 100644 index 0000000000000000000000000000000000000000..00caacb9fe42f4bca80a84a30ab7b3aac49ae53e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_speaker.py @@ -0,0 +1,41 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ConfigureConnectionDataSpeaker = typing.Union[ + typing.Literal[ + "anushka", + "abhilash", + "manisha", + "vidya", + "arya", + "karun", + "hitesh", + "aditya", + "ritu", + "priya", + "neha", + "rahul", + "pooja", + "rohan", + "simran", + "kavya", + "amit", + "dev", + "ishita", + "shreya", + "ratan", + "varun", + "manan", + "sumit", + "roopa", + "kabir", + "aayan", + "shubh", + "ashutosh", + "advait", + "amelia", + "sophia", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_target_language_code.py b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_target_language_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d79940ff0036c09aa6ccc696fdaa613fbd352e47 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/configure_connection_data_target_language_code.py @@ -0,0 +1,8 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ConfigureConnectionDataTargetLanguageCode = typing.Union[ + typing.Literal["bn-IN", "en-IN", "gu-IN", "hi-IN", "kn-IN", "ml-IN", "mr-IN", "od-IN", "pa-IN", "ta-IN", "te-IN"], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/connection_sample_rate.py b/venv/lib/python3.12/site-packages/sarvamai/types/connection_sample_rate.py new file mode 100644 index 0000000000000000000000000000000000000000..bd39ed4d6e02ea77885e9067953d7a6c0dcf2f97 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/connection_sample_rate.py @@ -0,0 +1,3 @@ +# This file was auto-generated by Fern from our API Definition. + +ConnectionSampleRate = int diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/create_chat_completion_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/create_chat_completion_response.py new file mode 100644 index 0000000000000000000000000000000000000000..9d2d18b6ed9571c725686849f26f68215678d579 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/create_chat_completion_response.py @@ -0,0 +1,48 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .choice import Choice +from .completion_usage import CompletionUsage + + +class CreateChatCompletionResponse(UniversalBaseModel): + id: str = pydantic.Field() + """ + A unique identifier for the chat completion. + """ + + choices: typing.List[Choice] = pydantic.Field() + """ + A list of chat completion choices. Can be more than one if `n` is greater than 1. + """ + + created: int = pydantic.Field() + """ + The Unix timestamp (in seconds) of when the chat completion was created. + """ + + model: str = pydantic.Field() + """ + The model used for the chat completion. + """ + + object: typing.Literal["chat.completion"] = pydantic.Field(default="chat.completion") + """ + The object type, which is always `chat.completion`. + """ + + service_tier: typing.Optional[str] = None + system_fingerprint: typing.Optional[str] = None + usage: typing.Optional[CompletionUsage] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/diarized_entry.py b/venv/lib/python3.12/site-packages/sarvamai/types/diarized_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..1f9df1792870761a0221f23cc5ed16ca85ded1c0 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/diarized_entry.py @@ -0,0 +1,37 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class DiarizedEntry(UniversalBaseModel): + transcript: str = pydantic.Field() + """ + transcript of the segment of that audio + """ + + start_time_seconds: float = pydantic.Field() + """ + Start time of the word in seconds. + """ + + end_time_seconds: float = pydantic.Field() + """ + End time of the word in seconds. + """ + + speaker_id: str = pydantic.Field() + """ + Speaker ID for the word. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/diarized_transcript.py b/venv/lib/python3.12/site-packages/sarvamai/types/diarized_transcript.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bfa901cded64ba4dbfed6d4395d3b61d458606 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/diarized_transcript.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .diarized_entry import DiarizedEntry + + +class DiarizedTranscript(UniversalBaseModel): + entries: typing.List[DiarizedEntry] = pydantic.Field() + """ + List of diarized transcript entries. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_create_job_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_create_job_response.py new file mode 100644 index 0000000000000000000000000000000000000000..9bcad338c921bf949a953a4878780ab560b86fa9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_create_job_response.py @@ -0,0 +1,37 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_job_parameters import DocDigitizationJobParameters +from .doc_digitization_job_state import DocDigitizationJobState +from .storage_container_type import StorageContainerType + + +class DocDigitizationCreateJobResponse(UniversalBaseModel): + job_id: str = pydantic.Field() + """ + Unique job identifier (UUID) + """ + + storage_container_type: StorageContainerType = pydantic.Field() + """ + Storage Container Type + """ + + job_parameters: DocDigitizationJobParameters = pydantic.Field() + """ + Job configuration parameters + """ + + job_state: DocDigitizationJobState + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_download_files_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_download_files_response.py new file mode 100644 index 0000000000000000000000000000000000000000..d1693557efb08db3810ea2df7513c54ca51ad0bb --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_download_files_response.py @@ -0,0 +1,47 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_job_state import DocDigitizationJobState +from .file_signed_url_details import FileSignedUrlDetails +from .storage_container_type import StorageContainerType + + +class DocDigitizationDownloadFilesResponse(UniversalBaseModel): + """ + Response for download-files endpoint. + """ + + job_id: str = pydantic.Field() + """ + Job identifier (UUID) + """ + + job_state: DocDigitizationJobState = pydantic.Field() + """ + Current job state + """ + + storage_container_type: StorageContainerType = pydantic.Field() + """ + Storage backend type + """ + + download_urls: typing.Dict[str, FileSignedUrlDetails] = pydantic.Field() + """ + Map of filename to presigned download URL details + """ + + error_code: typing.Optional[str] = None + error_message: typing.Optional[str] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_code.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_code.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b4757840afcf86af540e53b23a38fce25ca1c7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_code.py @@ -0,0 +1,15 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +DocDigitizationErrorCode = typing.Union[ + typing.Literal[ + "invalid_request_error", + "internal_server_error", + "insufficient_quota_error", + "invalid_api_key_error", + "rate_limit_exceeded_error", + "high_load_error", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_details.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_details.py new file mode 100644 index 0000000000000000000000000000000000000000..11f3d46bd89392da6a705739a8054703fa56563e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_details.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_error_code import DocDigitizationErrorCode + + +class DocDigitizationErrorDetails(UniversalBaseModel): + message: str = pydantic.Field() + """ + Message describing the error + """ + + code: DocDigitizationErrorCode = pydantic.Field() + """ + Error code for the specific error that has occurred. + """ + + request_id: typing.Optional[str] = pydantic.Field(default=None) + """ + Unique identifier for the request. Format: date_UUID4 + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_message.py new file mode 100644 index 0000000000000000000000000000000000000000..fc21018d1042c513d74ea1615de3534bc99d50ea --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_error_message.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_error_details import DocDigitizationErrorDetails + + +class DocDigitizationErrorMessage(UniversalBaseModel): + error: DocDigitizationErrorDetails = pydantic.Field() + """ + Error details + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_detail.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_detail.py new file mode 100644 index 0000000000000000000000000000000000000000..56612701ed057e749960aad32bb1d2f7743c25a7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_detail.py @@ -0,0 +1,74 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_job_detail_state import DocDigitizationJobDetailState +from .doc_digitization_page_error import DocDigitizationPageError +from .task_file_details import TaskFileDetails + + +class DocDigitizationJobDetail(UniversalBaseModel): + """ + Processing details for a single input file with page-level metrics. + """ + + inputs: typing.List[TaskFileDetails] = pydantic.Field() + """ + Input file(s) for this task + """ + + outputs: typing.List[TaskFileDetails] = pydantic.Field() + """ + Output file(s) produced + """ + + state: DocDigitizationJobDetailState = pydantic.Field() + """ + Processing state for this file + """ + + total_pages: typing.Optional[int] = pydantic.Field(default=None) + """ + Total pages/images in the input file + """ + + pages_processed: typing.Optional[int] = pydantic.Field(default=None) + """ + Number of pages processed so far + """ + + pages_succeeded: typing.Optional[int] = pydantic.Field(default=None) + """ + Number of pages successfully processed + """ + + pages_failed: typing.Optional[int] = pydantic.Field(default=None) + """ + Number of pages that failed processing + """ + + error_message: typing.Optional[str] = pydantic.Field(default=None) + """ + Error message if processing failed + """ + + error_code: typing.Optional[str] = pydantic.Field(default=None) + """ + Standardized error code if failed + """ + + page_errors: typing.Optional[typing.List[DocDigitizationPageError]] = pydantic.Field(default=None) + """ + Detailed errors for each failed page + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_detail_state.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_detail_state.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f76934404d8711c2ba9199c8500e296440318d --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_detail_state.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +DocDigitizationJobDetailState = typing.Union[ + typing.Literal["Pending", "Running", "Success", "PartialSuccess", "Failed"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..830e8ddc8334952f82f4d4aefea1b3158043998c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_parameters.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_output_format import DocDigitizationOutputFormat +from .doc_digitization_supported_language import DocDigitizationSupportedLanguage + + +class DocDigitizationJobParameters(UniversalBaseModel): + """ + Configuration parameters for Document Intelligence job. Specify the document language and desired output format. + """ + + language: typing.Optional[DocDigitizationSupportedLanguage] = pydantic.Field(default=None) + """ + Primary language of the document in BCP-47 format. This helps optimize text extraction accuracy for the specified language. + """ + + output_format: typing.Optional[DocDigitizationOutputFormat] = pydantic.Field(default=None) + """ + Output format for the extracted content (delivered as a ZIP file). Use 'html' for structured HTML, 'md' for Markdown, or 'json' for structured JSON data. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_state.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_state.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1b69374e28ec7c13da74196354c21b8ae4610f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_state.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +DocDigitizationJobState = typing.Union[ + typing.Literal["Accepted", "Pending", "Running", "Completed", "PartiallyCompleted", "Failed"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_status_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_status_response.py new file mode 100644 index 0000000000000000000000000000000000000000..ecaac887d3481b2200cb1331e5b0d270ff18b41b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_job_status_response.py @@ -0,0 +1,75 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_job_detail import DocDigitizationJobDetail +from .doc_digitization_job_state import DocDigitizationJobState +from .storage_container_type import StorageContainerType + + +class DocDigitizationJobStatusResponse(UniversalBaseModel): + """ + Response model for job status endpoint. + """ + + job_id: str = pydantic.Field() + """ + Job identifier (UUID) + """ + + job_state: DocDigitizationJobState = pydantic.Field() + """ + Current job state + """ + + created_at: dt.datetime = pydantic.Field() + """ + Job creation timestamp (ISO 8601) + """ + + updated_at: dt.datetime = pydantic.Field() + """ + Last update timestamp (ISO 8601) + """ + + storage_container_type: StorageContainerType = pydantic.Field() + """ + Storage backend type + """ + + total_files: typing.Optional[int] = pydantic.Field(default=None) + """ + Total input files (always 1) + """ + + successful_files_count: typing.Optional[int] = pydantic.Field(default=None) + """ + Files that completed successfully + """ + + failed_files_count: typing.Optional[int] = pydantic.Field(default=None) + """ + Files that failed + """ + + error_message: typing.Optional[str] = pydantic.Field(default=None) + """ + Job-level error message + """ + + job_details: typing.Optional[typing.List[DocDigitizationJobDetail]] = pydantic.Field(default=None) + """ + Per-file processing details with page metrics + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_output_format.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_output_format.py new file mode 100644 index 0000000000000000000000000000000000000000..603775c401032264f557bd0a253fc58bd04f558c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_output_format.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +DocDigitizationOutputFormat = typing.Union[typing.Literal["html", "md", "json"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_page_error.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_page_error.py new file mode 100644 index 0000000000000000000000000000000000000000..5ba2701a1daf6d8cd6272c143a6c814d2c6e0e14 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_page_error.py @@ -0,0 +1,36 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class DocDigitizationPageError(UniversalBaseModel): + """ + Error details for a specific page. + """ + + page_number: int = pydantic.Field() + """ + Page number that failed + """ + + error_code: str = pydantic.Field() + """ + Standardized error code + """ + + error_message: str = pydantic.Field() + """ + Human-readable error description + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_supported_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_supported_language.py new file mode 100644 index 0000000000000000000000000000000000000000..42c3531bd035ffbebb793e188b65a5338d3c4689 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_supported_language.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +DocDigitizationSupportedLanguage = typing.Union[ + typing.Literal[ + "hi-IN", + "en-IN", + "bn-IN", + "gu-IN", + "kn-IN", + "ml-IN", + "mr-IN", + "or-IN", + "pa-IN", + "ta-IN", + "te-IN", + "ur-IN", + "as-IN", + "bodo-IN", + "doi-IN", + "ks-IN", + "kok-IN", + "mai-IN", + "mni-IN", + "ne-IN", + "sa-IN", + "sat-IN", + "sd-IN", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_upload_files_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_upload_files_response.py new file mode 100644 index 0000000000000000000000000000000000000000..57c9b83f1d2d0f8f58db9166200e7ae9a9fa807b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_upload_files_response.py @@ -0,0 +1,44 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .doc_digitization_job_state import DocDigitizationJobState +from .file_signed_url_details import FileSignedUrlDetails +from .storage_container_type import StorageContainerType + + +class DocDigitizationUploadFilesResponse(UniversalBaseModel): + """ + Response with presigned upload URLs + """ + + job_id: str = pydantic.Field() + """ + Job identifier + """ + + job_state: DocDigitizationJobState = pydantic.Field() + """ + Current job state + """ + + upload_urls: typing.Dict[str, FileSignedUrlDetails] = pydantic.Field() + """ + Map of filename to presigned upload URL details + """ + + storage_container_type: StorageContainerType = pydantic.Field() + """ + Storage backend type + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_webhook_callback.py b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_webhook_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..3782d6dacbddd6f7ae4cb6f60c7be2d2b34e1987 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/doc_digitization_webhook_callback.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class DocDigitizationWebhookCallback(UniversalBaseModel): + """ + Webhook configuration for job completion notification + """ + + url: str = pydantic.Field() + """ + HTTPS webhook URL to call upon job completion (HTTP not allowed) + """ + + auth_token: typing.Optional[str] = pydantic.Field(default=None) + """ + Authorization token sent as X-SARVAM-JOB-CALLBACK-TOKEN header + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_code.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_code.py new file mode 100644 index 0000000000000000000000000000000000000000..1306148f83e3b98e211dc201a45b4b49a54b2987 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_code.py @@ -0,0 +1,17 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ErrorCode = typing.Union[ + typing.Literal[ + "invalid_request_error", + "internal_server_error", + "unprocessable_entity_error", + "insufficient_quota_error", + "invalid_api_key_error", + "authentication_error", + "not_found_error", + "rate_limit_exceeded_error", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_code2.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_code2.py new file mode 100644 index 0000000000000000000000000000000000000000..09e28388d404da5cdcbebf02f07ab0632425071b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_code2.py @@ -0,0 +1,17 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ErrorCode2 = typing.Union[ + typing.Literal[ + "invalid_request_error", + "internal_server_error", + "unprocessable_entity_error", + "insufficient_quota_error", + "invalid_api_key_error", + "authentication_error", + "rate_limit_exceeded_error", + "not_found_error", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e771561fbc813a90c35479d54d0faafa67ee16d1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_data.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ErrorData(UniversalBaseModel): + error: str = pydantic.Field() + """ + Error message + """ + + code: str = pydantic.Field() + """ + Error code + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_details.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_details.py new file mode 100644 index 0000000000000000000000000000000000000000..dd57f06b1e0e00fbae1e98061a2512dd83a3cd2c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_details.py @@ -0,0 +1,29 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .error_code import ErrorCode + + +class ErrorDetails(UniversalBaseModel): + request_id: typing.Optional[str] = None + message: str = pydantic.Field() + """ + Message describing the error + """ + + code: ErrorCode = pydantic.Field() + """ + Error code for the specific error that has occured. Refer to the error code documentation for more details. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_details2.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_details2.py new file mode 100644 index 0000000000000000000000000000000000000000..964d2d2e593a661d65cd5e55bab3aa774aa1a800 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_details2.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .error_code2 import ErrorCode2 + + +class ErrorDetails2(UniversalBaseModel): + message: str = pydantic.Field() + """ + Message describing the error + """ + + code: ErrorCode2 = pydantic.Field() + """ + Error code for the specific error that has occured. Refer to the error code documentation for more details. + """ + + request_id: typing.Optional[str] = pydantic.Field(default=None) + """ + Unique identifier for the request. Format: date_UUID4 + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_message.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_message.py new file mode 100644 index 0000000000000000000000000000000000000000..be870e4152e33c4fb51edb7b22838bf7f618ed6e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_message.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .error_details import ErrorDetails + + +class ErrorMessage(UniversalBaseModel): + error: ErrorDetails = pydantic.Field() + """ + Error details + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_message2.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_message2.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb223baddbe1124f6c9b42bbc800dcb469ce56f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_message2.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .error_details2 import ErrorDetails2 + + +class ErrorMessage2(UniversalBaseModel): + error: ErrorDetails2 = pydantic.Field() + """ + Error details + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_response.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbfaaa2ce34974b247730ba1eda9b243010f60c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_response.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .error_response_data import ErrorResponseData + + +class ErrorResponse(UniversalBaseModel): + type: typing.Literal["error"] = "error" + data: ErrorResponseData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/error_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/error_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f4e742e4654729e87f7c013140f01fa3c27c61 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/error_response_data.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class ErrorResponseData(UniversalBaseModel): + message: str + code: typing.Optional[int] = pydantic.Field(default=None) + """ + Optional error code for programmatic error handling + """ + + details: typing.Optional[typing.Dict[str, typing.Any]] = pydantic.Field(default=None) + """ + Additional error details and context information + """ + + request_id: typing.Optional[str] = pydantic.Field(default=None) + """ + Unique identifier for the request + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/event_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/event_response.py new file mode 100644 index 0000000000000000000000000000000000000000..d42e4e2e702976f2944951ebe06c58cf3e102651 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/event_response.py @@ -0,0 +1,29 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .event_response_data import EventResponseData + + +class EventResponse(UniversalBaseModel): + """ + Event notification message sent when specific events occur during TTS processing + """ + + type: typing.Literal["event"] = pydantic.Field(default="event") + """ + Message type identifier for events + """ + + data: EventResponseData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/event_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/event_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..927c45536a2721b7d8e575cc50ee1014c61e0888 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/event_response_data.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class EventResponseData(UniversalBaseModel): + event_type: typing.Literal["final"] = pydantic.Field(default="final") + """ + Type of event that occurred + """ + + message: typing.Optional[str] = pydantic.Field(default=None) + """ + Human-readable description of the event + """ + + timestamp: typing.Optional[dt.datetime] = pydantic.Field(default=None) + """ + ISO 8601 timestamp when the event occurred + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/events_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/events_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bf79ba3b852ff29f273ea73cae48226c628227 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/events_data.py @@ -0,0 +1,43 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .events_data_signal_type import EventsDataSignalType + + +class EventsData(UniversalBaseModel): + """ + VAD events are sent when vad_signals=true. Fields may vary by event type. + """ + + event_type: typing.Optional[str] = pydantic.Field(default=None) + """ + Type of event + """ + + timestamp: typing.Optional[dt.datetime] = pydantic.Field(default=None) + """ + Event timestamp + """ + + signal_type: typing.Optional[EventsDataSignalType] = pydantic.Field(default=None) + """ + VAD signal type + """ + + occured_at: typing.Optional[float] = pydantic.Field(default=None) + """ + Epoch timestamp when the event occurred + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/events_data_signal_type.py b/venv/lib/python3.12/site-packages/sarvamai/types/events_data_signal_type.py new file mode 100644 index 0000000000000000000000000000000000000000..ac066dc663cda751de472d664a032ac91a3931f7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/events_data_signal_type.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +EventsDataSignalType = typing.Union[typing.Literal["START_SPEECH", "END_SPEECH"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/file_signed_url_details.py b/venv/lib/python3.12/site-packages/sarvamai/types/file_signed_url_details.py new file mode 100644 index 0000000000000000000000000000000000000000..0598ae7a92de491a30292c1f3ea285ae5b2642d8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/file_signed_url_details.py @@ -0,0 +1,20 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class FileSignedUrlDetails(UniversalBaseModel): + file_url: str + file_metadata: typing.Optional[typing.Dict[str, typing.Any]] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/files_download_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/files_download_response.py new file mode 100644 index 0000000000000000000000000000000000000000..320aeaae78466bc3468a77ab56bfa8172c305e6a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/files_download_response.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .file_signed_url_details import FileSignedUrlDetails +from .job_state import JobState +from .storage_container_type import StorageContainerType + + +class FilesDownloadResponse(UniversalBaseModel): + job_id: str + job_state: JobState + download_urls: typing.Dict[str, FileSignedUrlDetails] + storage_container_type: StorageContainerType + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/files_request.py b/venv/lib/python3.12/site-packages/sarvamai/types/files_request.py new file mode 100644 index 0000000000000000000000000000000000000000..f620b933d4da2218692f576130ebb988569819c2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/files_request.py @@ -0,0 +1,20 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class FilesRequest(UniversalBaseModel): + job_id: str + files: typing.List[str] + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/files_upload_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/files_upload_response.py new file mode 100644 index 0000000000000000000000000000000000000000..c0fcb5f9336794d32a8907db4c492a387c58ad2c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/files_upload_response.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .file_signed_url_details import FileSignedUrlDetails +from .job_state import JobState +from .storage_container_type import StorageContainerType + + +class FilesUploadResponse(UniversalBaseModel): + job_id: str + job_state: JobState + upload_urls: typing.Dict[str, FileSignedUrlDetails] + storage_container_type: StorageContainerType + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/finish_reason.py b/venv/lib/python3.12/site-packages/sarvamai/types/finish_reason.py new file mode 100644 index 0000000000000000000000000000000000000000..1f9a00389c00f87b403294038dd15384540f83dc --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/finish_reason.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +FinishReason = typing.Union[ + typing.Literal["stop", "length", "tool_calls", "content_filter", "function_call"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/flush_signal.py b/venv/lib/python3.12/site-packages/sarvamai/types/flush_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..f9400e8fa60e913ea43bf36e31de8496554c0b54 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/flush_signal.py @@ -0,0 +1,24 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class FlushSignal(UniversalBaseModel): + """ + Forces the text buffer to process immediately, regardless of the min_buffer_size threshold. + Use this when you need to process remaining text that hasn't reached the minimum buffer size. + """ + + type: typing.Literal["flush"] = "flush" + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/function_call.py b/venv/lib/python3.12/site-packages/sarvamai/types/function_call.py new file mode 100644 index 0000000000000000000000000000000000000000..1b02e109303953d6e89aa16898a2e31b004b3764 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/function_call.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class FunctionCall(UniversalBaseModel): + name: str = pydantic.Field() + """ + The name of the function to call. + """ + + arguments: str = pydantic.Field() + """ + The arguments to call the function with, as a JSON string. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/function_definition.py b/venv/lib/python3.12/site-packages/sarvamai/types/function_definition.py new file mode 100644 index 0000000000000000000000000000000000000000..d74151b3aa7ebb472abc83d4d247ae26d2fb18b4 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/function_definition.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class FunctionDefinition(UniversalBaseModel): + name: str = pydantic.Field() + """ + The name of the function to be called. + """ + + description: typing.Optional[str] = pydantic.Field(default=None) + """ + A description of what the function does. + """ + + parameters: typing.Optional[typing.Dict[str, typing.Any]] = pydantic.Field(default=None) + """ + The parameters the function accepts, described as a JSON Schema object. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/input_audio_codec.py b/venv/lib/python3.12/site-packages/sarvamai/types/input_audio_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..558d42f5d4d3a7f4af7d4de84430130b095fd1a6 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/input_audio_codec.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +InputAudioCodec = typing.Union[ + typing.Literal[ + "wav", + "x-wav", + "wave", + "mp3", + "mpeg", + "mpeg3", + "x-mp3", + "x-mpeg-3", + "aac", + "x-aac", + "aiff", + "x-aiff", + "ogg", + "opus", + "flac", + "x-flac", + "mp4", + "x-m4a", + "amr", + "x-ms-wma", + "webm", + "pcm_s16le", + "pcm_l16", + "pcm_raw", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/job_state.py b/venv/lib/python3.12/site-packages/sarvamai/types/job_state.py new file mode 100644 index 0000000000000000000000000000000000000000..c53cf554a8e84c844313fd8686d1311fadb85e61 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/job_state.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +JobState = typing.Union[typing.Literal["Accepted", "Pending", "Running", "Completed", "Failed"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/job_status_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/job_status_response.py new file mode 100644 index 0000000000000000000000000000000000000000..be1ac987def38dcb6359aa2520dfdb9127baa542 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/job_status_response.py @@ -0,0 +1,70 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .job_state import JobState +from .storage_container_type import StorageContainerType +from .task_detail import TaskDetail + + +class JobStatusResponse(UniversalBaseModel): + job_state: JobState = pydantic.Field() + """ + Job State + """ + + created_at: str = pydantic.Field() + """ + Created At + """ + + updated_at: str = pydantic.Field() + """ + Updated At + """ + + job_id: str = pydantic.Field() + """ + Job Id + """ + + total_files: typing.Optional[int] = pydantic.Field(default=None) + """ + Total Files + """ + + successful_files_count: typing.Optional[int] = pydantic.Field(default=None) + """ + Success Count + """ + + failed_files_count: typing.Optional[int] = pydantic.Field(default=None) + """ + Failed Count + """ + + storage_container_type: StorageContainerType = pydantic.Field() + """ + Storage Container Type + """ + + error_message: typing.Optional[str] = pydantic.Field(default=None) + """ + Error Message + """ + + job_details: typing.Optional[typing.List[TaskDetail]] = pydantic.Field(default=None) + """ + Job details at file level. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/language_identification_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/language_identification_response.py new file mode 100644 index 0000000000000000000000000000000000000000..d34423bb5951f64aa81a44efec6443d586fa225a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/language_identification_response.py @@ -0,0 +1,53 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class LanguageIdentificationResponse(UniversalBaseModel): + request_id: typing.Optional[str] = None + language_code: typing.Optional[str] = pydantic.Field(default=None) + """ + The detected language code of the input text. + + Available languages: + - **`en-IN`**: English + - **`hi-IN`**: Hindi + - **`bn-IN`**: Bengali + - **`gu-IN`**: Gujarati + - **`kn-IN`**: Kannada + - **`ml-IN`**: Malayalam + - **`mr-IN`**: Marathi + - **`od-IN`**: Odia + - **`pa-IN`**: Punjabi + - **`ta-IN`**: Tamil + - **`te-IN`**: Telugu + """ + + script_code: typing.Optional[str] = pydantic.Field(default=None) + """ + The detected script code of the input text. + + Available scripts: + - **`Latn`**: Latin (Romanized script) + - **`Deva`**: Devanagari (Hindi, Marathi) + - **`Beng`**: Bengali + - **`Gujr`**: Gujarati + - **`Knda`**: Kannada + - **`Mlym`**: Malayalam + - **`Orya`**: Odia + - **`Guru`**: Gurmukhi + - **`Taml`**: Tamil + - **`Telu`**: Telugu + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/mode.py b/venv/lib/python3.12/site-packages/sarvamai/types/mode.py new file mode 100644 index 0000000000000000000000000000000000000000..298d6dca5f0e43450479565a293a817ee9347af1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/mode.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +Mode = typing.Union[typing.Literal["transcribe", "translate", "verbatim", "translit", "codemix"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/numerals_format.py b/venv/lib/python3.12/site-packages/sarvamai/types/numerals_format.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef07c592713509dbfc15deec9970a7d586ef50d --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/numerals_format.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +NumeralsFormat = typing.Union[typing.Literal["international", "native"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/ping_signal.py b/venv/lib/python3.12/site-packages/sarvamai/types/ping_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..e4add15a3286b7f1df40d6176b79c3c384bc3aa0 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/ping_signal.py @@ -0,0 +1,24 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class PingSignal(UniversalBaseModel): + """ + Send ping signal to keep the WebSocket connection alive. The connection automatically + closes after one minute of inactivity. + """ + + type: typing.Literal["ping"] = "ping" + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0a8a574bf1eaf658fa7d1716ba70ace961a37b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_data.py @@ -0,0 +1,26 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class PronunciationDictionaryData(UniversalBaseModel): + """ + The full pronunciation data for a dictionary. + """ + + pronunciations: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field() + """ + Pronunciation mappings organized by language code (e.g. `hi-IN`, `en-IN`). Each language maps words to their custom pronunciations. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_delete_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_delete_response.py new file mode 100644 index 0000000000000000000000000000000000000000..b0f7d2436275d6d9e90974ace3c3548ae85a6706 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_delete_response.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class PronunciationDictionaryDeleteResponse(UniversalBaseModel): + """ + Response returned after deleting a pronunciation dictionary. + """ + + success: bool = pydantic.Field() + """ + Whether the deletion was successful. + """ + + message: str = pydantic.Field() + """ + Human-readable status message (e.g. "Dictionary 'p_5cb7faa6' deleted successfully"). + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_get_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_get_response.py new file mode 100644 index 0000000000000000000000000000000000000000..e9afbc86b3b47197d719e01b39eee686fd7fe5da --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_get_response.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class PronunciationDictionaryGetResponse(UniversalBaseModel): + """ + Response containing all pronunciation dictionary IDs for the authenticated user. + """ + + dictionary_count: int = pydantic.Field() + """ + Total number of pronunciation dictionaries owned by the user. + """ + + dictionaries: typing.List[str] = pydantic.Field() + """ + List of dictionary IDs. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_response.py new file mode 100644 index 0000000000000000000000000000000000000000..f3d83af3730aec39754c631e63bdd73ed1948ce8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_response.py @@ -0,0 +1,26 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class PronunciationDictionaryResponse(UniversalBaseModel): + """ + Response returned after successfully creating a pronunciation dictionary. + """ + + dictionary_id: str = pydantic.Field() + """ + Unique identifier for the created dictionary (e.g. `p_5cb7faa6`). Use this as the `dict_id` parameter in text-to-speech requests. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_update_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_update_response.py new file mode 100644 index 0000000000000000000000000000000000000000..37a90f05c6ef7dbe048003cd2e274c05d11bd45b --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/pronunciation_dictionary_update_response.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class PronunciationDictionaryUpdateResponse(UniversalBaseModel): + """ + Response returned after successfully updating a pronunciation dictionary. Includes the full updated pronunciation data for verification. + """ + + dictionary_id: str = pydantic.Field() + """ + Unique identifier of the updated dictionary. + """ + + updated_pronunciations: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field() + """ + The new pronunciation data after the update, organized as `{language_code: {word: pronunciation}}`. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/reasoning_effort.py b/venv/lib/python3.12/site-packages/sarvamai/types/reasoning_effort.py new file mode 100644 index 0000000000000000000000000000000000000000..4b52116ebe8eb775dfd859b26f79df57a0d5dd29 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/reasoning_effort.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ReasoningEffort = typing.Union[typing.Literal["low", "medium", "high"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/response_type.py b/venv/lib/python3.12/site-packages/sarvamai/types/response_type.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f93ca44c6ec767fa2deba8f11e93943bf35e42 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/response_type.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +ResponseType = typing.Union[typing.Literal["data", "error", "events"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/role.py b/venv/lib/python3.12/site-packages/sarvamai/types/role.py new file mode 100644 index 0000000000000000000000000000000000000000..a209bce2d749edab4eaf21e2831a88138a90dda8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/role.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +Role = typing.Literal["assistant"] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/sarvam_model_ids.py b/venv/lib/python3.12/site-packages/sarvamai/types/sarvam_model_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..8e6cbdddfe91ac4ce6dba70a5367cefc9fa73c2f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/sarvam_model_ids.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SarvamModelIds = typing.Union[typing.Literal["sarvam-105b", "sarvam-30b", "sarvam-m"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/send_text.py b/venv/lib/python3.12/site-packages/sarvamai/types/send_text.py new file mode 100644 index 0000000000000000000000000000000000000000..21b9ff0d82b3f77e8e268ca90343b429dfb83668 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/send_text.py @@ -0,0 +1,21 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .send_text_data import SendTextData + + +class SendText(UniversalBaseModel): + type: typing.Literal["text"] = "text" + data: SendTextData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/send_text_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/send_text_data.py new file mode 100644 index 0000000000000000000000000000000000000000..63b26eb158f3277be7c15cf62c2dd5db46956ced --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/send_text_data.py @@ -0,0 +1,19 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class SendTextData(UniversalBaseModel): + text: str + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_sample_rate.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_sample_rate.py new file mode 100644 index 0000000000000000000000000000000000000000..76d811c0e827f93a41f8bf901116386a1b9f259a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_sample_rate.py @@ -0,0 +1,3 @@ +# This file was auto-generated by Fern from our API Definition. + +SpeechSampleRate = int diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_stream_bitrate.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_stream_bitrate.py new file mode 100644 index 0000000000000000000000000000000000000000..35465e106a32349760eb431003f09b3c8c563b12 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_stream_bitrate.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechStreamBitrate = typing.Union[typing.Literal["32k", "64k", "96k", "128k", "192k"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_stream_codec.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_stream_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..4d1688271036930adb89b4156ee21148145359c7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_stream_codec.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechStreamCodec = typing.Union[ + typing.Literal["mp3", "linear16", "mulaw", "alaw", "opus", "flac", "aac", "wav"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..c9349ce88f8bc4ebb280c180103c11374cadba2f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_job_parameters.py @@ -0,0 +1,105 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .input_audio_codec import InputAudioCodec +from .mode import Mode +from .speech_to_text_language import SpeechToTextLanguage +from .speech_to_text_model import SpeechToTextModel + + +class SpeechToTextJobParameters(UniversalBaseModel): + language_code: typing.Optional[SpeechToTextLanguage] = pydantic.Field(default=None) + """ + Specifies the language of the input audio in BCP-47 format. + + **Available Options:** + - `unknown` (default): Use when the language is not known; the API will auto-detect. + - `hi-IN`: Hindi + - `bn-IN`: Bengali + - `kn-IN`: Kannada + - `ml-IN`: Malayalam + - `mr-IN`: Marathi + - `od-IN`: Odia + - `pa-IN`: Punjabi + - `ta-IN`: Tamil + - `te-IN`: Telugu + - `en-IN`: English + - `gu-IN`: Gujarati + + **Additional Options (saaras:v3 only):** + - `as-IN`: Assamese + - `ur-IN`: Urdu + - `ne-IN`: Nepali + - `kok-IN`: Konkani + - `ks-IN`: Kashmiri + - `sd-IN`: Sindhi + - `sa-IN`: Sanskrit + - `sat-IN`: Santali + - `mni-IN`: Manipuri + - `brx-IN`: Bodo + - `mai-IN`: Maithili + - `doi-IN`: Dogri + """ + + model: typing.Optional[SpeechToTextModel] = pydantic.Field(default=None) + """ + Model to be used for speech to text. + + - **saarika:v2.5** (default): Transcribes audio in the spoken language. + + - **saaras:v3**: State-of-the-art model with flexible output formats. Supports multiple modes via the `mode` parameter: transcribe, translate, verbatim, translit, codemix. + """ + + mode: typing.Optional[Mode] = pydantic.Field(default=None) + """ + Mode of operation. **Only applicable when using saaras:v3 model.** + + Example audio: 'मेरा फोन नंबर है 9840950950' + + - **transcribe** (default): Standard transcription in the original language with proper formatting and number normalization. + - Output: `मेरा फोन नंबर है 9840950950` + + - **translate**: Translates speech from any supported Indic language to English. + - Output: `My phone number is 9840950950` + + - **verbatim**: Exact word-for-word transcription without normalization, preserving filler words and spoken numbers as-is. + - Output: `मेरा फोन नंबर है नौ आठ चार zero नौ पांच zero नौ पांच zero` + + - **translit**: Romanization - Transliterates speech to Latin/Roman script only. + - Output: `mera phone number hai 9840950950` + + - **codemix**: Code-mixed text with English words in English and Indic words in native script. + - Output: `मेरा phone number है 9840950950` + """ + + with_timestamps: typing.Optional[bool] = pydantic.Field(default=None) + """ + Whether to include timestamps in the response + """ + + with_diarization: typing.Optional[bool] = pydantic.Field(default=None) + """ + Enables speaker diarization, which identifies and separates different speakers in the audio. In beta mode + """ + + num_speakers: typing.Optional[int] = pydantic.Field(default=None) + """ + Number of speakers to be detected in the audio. This is used when with_diarization is true. + """ + + input_audio_codec: typing.Optional[InputAudioCodec] = pydantic.Field(default=None) + """ + Audio codec/format of uploaded files. The API automatically detects most formats; for PCM files (pcm_s16le, pcm_l16, pcm_raw), you must specify this parameter. PCM files are supported only at 16kHz sample rate. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_language.py new file mode 100644 index 0000000000000000000000000000000000000000..2316575179310187687fb0ee357202915e89afef --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_language.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextLanguage = typing.Union[ + typing.Literal[ + "unknown", + "hi-IN", + "bn-IN", + "kn-IN", + "ml-IN", + "mr-IN", + "od-IN", + "pa-IN", + "ta-IN", + "te-IN", + "en-IN", + "gu-IN", + "as-IN", + "ur-IN", + "ne-IN", + "kok-IN", + "ks-IN", + "sd-IN", + "sa-IN", + "sat-IN", + "mni-IN", + "brx-IN", + "mai-IN", + "doi-IN", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_model.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_model.py new file mode 100644 index 0000000000000000000000000000000000000000..6207d9351946f3a6c695d6e914dce7ad95317a22 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextModel = typing.Union[typing.Literal["saarika:v2.5", "saaras:v3"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_response.py new file mode 100644 index 0000000000000000000000000000000000000000..bf3e7d01145b7667bbcd8b3a7773a05fadd23d53 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_response.py @@ -0,0 +1,54 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .diarized_transcript import DiarizedTranscript +from .timestamps_model import TimestampsModel + + +class SpeechToTextResponse(UniversalBaseModel): + request_id: typing.Optional[str] = None + transcript: str = pydantic.Field() + """ + The transcribed text from the provided audio file. + """ + + timestamps: typing.Optional[TimestampsModel] = pydantic.Field(default=None) + """ + Contains timestamps for the transcribed text. This field is included only if with_timestamps is set to true + """ + + diarized_transcript: typing.Optional[DiarizedTranscript] = pydantic.Field(default=None) + """ + Diarized transcript of the provided speech + """ + + language_code: typing.Optional[str] = pydantic.Field(default=None) + """ + This will return the BCP-47 code of language spoken in the input. If multiple languages are detected, this will return language code of most predominant spoken language. If no language is detected, this will be null + """ + + language_probability: typing.Optional[float] = pydantic.Field(default=None) + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2081b53c26fdab6e9911d1a94bee78bff365ea66 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_response_data.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .error_data import ErrorData +from .events_data import EventsData +from .speech_to_text_transcription_data import SpeechToTextTranscriptionData + +SpeechToTextResponseData = typing.Union[SpeechToTextTranscriptionData, ErrorData, EventsData] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_streaming_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_streaming_response.py new file mode 100644 index 0000000000000000000000000000000000000000..15d4b96be5d926e541e7fee6ff5ef636c0b92eb2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_streaming_response.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .response_type import ResponseType +from .speech_to_text_response_data import SpeechToTextResponseData + + +class SpeechToTextStreamingResponse(UniversalBaseModel): + type: ResponseType + data: SpeechToTextResponseData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_transcription_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_transcription_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ee36d629fdfc105f348d54b8c18414b5d4092fec --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_transcription_data.py @@ -0,0 +1,59 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .transcription_metrics import TranscriptionMetrics + + +class SpeechToTextTranscriptionData(UniversalBaseModel): + request_id: str = pydantic.Field() + """ + Unique identifier for the request + """ + + transcript: str = pydantic.Field() + """ + Transcript of the provided speech in original language + """ + + timestamps: typing.Optional[typing.Dict[str, typing.Any]] = pydantic.Field(default=None) + """ + Timestamp information (if available) + """ + + diarized_transcript: typing.Optional[typing.Dict[str, typing.Any]] = pydantic.Field(default=None) + """ + Diarized transcript of the provided speech + """ + + language_code: typing.Optional[str] = pydantic.Field(default=None) + """ + BCP-47 code of detected language + """ + + language_probability: typing.Optional[float] = pydantic.Field(default=None) + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ + + metrics: TranscriptionMetrics + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_job_parameters.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_job_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..94d07084067152abd937ac4855f6c1ab9bd890c6 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_job_parameters.py @@ -0,0 +1,49 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .input_audio_codec import InputAudioCodec +from .speech_to_text_translate_model import SpeechToTextTranslateModel + + +class SpeechToTextTranslateJobParameters(UniversalBaseModel): + prompt: typing.Optional[str] = pydantic.Field(default=None) + """ + Prompt to assist the transcription + """ + + model: typing.Optional[SpeechToTextTranslateModel] = pydantic.Field(default=None) + """ + Model to be used for speech to text translation. + + - **saaras:v2.5** (default): Translation model that translates audio from any spoken Indic language to English. + - Example: Hindi audio → English text output + """ + + with_diarization: typing.Optional[bool] = pydantic.Field(default=None) + """ + Enables speaker diarization, which identifies and separates different speakers in the audio. + When set to true, the API will provide speaker-specific segments in the response. + Note: This parameter is currently in Beta mode. + """ + + num_speakers: typing.Optional[int] = pydantic.Field(default=None) + """ + Number of speakers to be detected in the audio. This is used when with_diarization is set to true. + """ + + input_audio_codec: typing.Optional[InputAudioCodec] = pydantic.Field(default=None) + """ + Audio codec/format of uploaded files. The API automatically detects most formats; for PCM files (pcm_s16le, pcm_l16, pcm_raw), you must specify this parameter. PCM files are supported only at 16kHz sample rate. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_language.py new file mode 100644 index 0000000000000000000000000000000000000000..2805781a7b9f9b6212b5eaf02325dc932f1f5070 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_language.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateLanguage = typing.Union[ + typing.Literal[ + "hi-IN", + "bn-IN", + "kn-IN", + "ml-IN", + "mr-IN", + "od-IN", + "pa-IN", + "ta-IN", + "te-IN", + "gu-IN", + "en-IN", + "as-IN", + "ur-IN", + "ne-IN", + "kok-IN", + "ks-IN", + "sd-IN", + "sa-IN", + "sat-IN", + "mni-IN", + "brx-IN", + "mai-IN", + "doi-IN", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_model.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_model.py new file mode 100644 index 0000000000000000000000000000000000000000..96067b6037442045ff666ef39c13f8ad286b1bb4 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpeechToTextTranslateModel = typing.Literal["saaras:v2.5"] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_response.py new file mode 100644 index 0000000000000000000000000000000000000000..02b6ffb3466b7cf4acb174389ebd05f7d88c987c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_response.py @@ -0,0 +1,49 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .diarized_transcript import DiarizedTranscript +from .speech_to_text_translate_language import SpeechToTextTranslateLanguage + + +class SpeechToTextTranslateResponse(UniversalBaseModel): + request_id: typing.Optional[str] = None + transcript: str = pydantic.Field() + """ + Transcript of the provided speech + """ + + language_code: typing.Optional[SpeechToTextTranslateLanguage] = pydantic.Field(default=None) + """ + This will return the BCP-47 code of language spoken in the input. If multiple languages are detected, this will return language code of most predominant spoken language. If no language is detected, this will be null + """ + + diarized_transcript: typing.Optional[DiarizedTranscript] = pydantic.Field(default=None) + """ + Diarized transcript of the provided speech + """ + + language_probability: typing.Optional[float] = pydantic.Field(default=None) + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_response_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_response_data.py new file mode 100644 index 0000000000000000000000000000000000000000..50d74f6691760ccfe739b1dc2d39905fba8406f1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_response_data.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .error_data import ErrorData +from .events_data import EventsData +from .speech_to_text_translate_transcription_data import SpeechToTextTranslateTranscriptionData + +SpeechToTextTranslateResponseData = typing.Union[SpeechToTextTranslateTranscriptionData, ErrorData, EventsData] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_streaming_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_streaming_response.py new file mode 100644 index 0000000000000000000000000000000000000000..b2352fc07309a1c3c07c98bd63e67c50e23e2972 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_streaming_response.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .response_type import ResponseType +from .speech_to_text_translate_response_data import SpeechToTextTranslateResponseData + + +class SpeechToTextTranslateStreamingResponse(UniversalBaseModel): + type: ResponseType + data: SpeechToTextTranslateResponseData + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_transcription_data.py b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_transcription_data.py new file mode 100644 index 0000000000000000000000000000000000000000..6da755ba8af3971025e2f5a2fdc18461b0a134d9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/speech_to_text_translate_transcription_data.py @@ -0,0 +1,49 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .transcription_metrics import TranscriptionMetrics + + +class SpeechToTextTranslateTranscriptionData(UniversalBaseModel): + request_id: str = pydantic.Field() + """ + Unique identifier for the request + """ + + transcript: str = pydantic.Field() + """ + English translation of the provided speech + """ + + language_code: typing.Optional[str] = pydantic.Field(default=None) + """ + BCP-47 code of detected source language (null when language detection is in progress) + """ + + language_probability: typing.Optional[float] = pydantic.Field(default=None) + """ + Float value (0.0 to 1.0) indicating the probability of the detected language being correct. Higher values indicate higher confidence. + + **When it returns a value:** + - When `language_code` is not provided in the request + - When `language_code` is set to `unknown` + + **When it returns null:** + - When a specific `language_code` is provided (language detection is skipped) + + The parameter is always present in the response. + """ + + metrics: TranscriptionMetrics + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/spoken_form_numerals_format.py b/venv/lib/python3.12/site-packages/sarvamai/types/spoken_form_numerals_format.py new file mode 100644 index 0000000000000000000000000000000000000000..ec22208a4a7148b298bbcd3c734ec1a62c2b8d96 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/spoken_form_numerals_format.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +SpokenFormNumeralsFormat = typing.Union[typing.Literal["english", "native"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/stop_configuration.py b/venv/lib/python3.12/site-packages/sarvamai/types/stop_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..c469a19278499538cf5098e5dd4a6ce0011bb2b8 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/stop_configuration.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +StopConfiguration = typing.Union[str, typing.List[str]] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/storage_container_type.py b/venv/lib/python3.12/site-packages/sarvamai/types/storage_container_type.py new file mode 100644 index 0000000000000000000000000000000000000000..2a3cb2808c5f1957b4e513c582f42af8142aa7a3 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/storage_container_type.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +StorageContainerType = typing.Union[typing.Literal["Azure", "Local", "Google", "Azure_V1"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/stt_flush_signal.py b/venv/lib/python3.12/site-packages/sarvamai/types/stt_flush_signal.py new file mode 100644 index 0000000000000000000000000000000000000000..54c374bcb6dd7435784bf2bda6f1bb04240bf11c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/stt_flush_signal.py @@ -0,0 +1,26 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class SttFlushSignal(UniversalBaseModel): + """ + Signal to flush the audio buffer and force finalize partial transcriptions/translations + """ + + type: typing.Literal["flush"] = pydantic.Field(default="flush") + """ + Type identifier for flush signal + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/task_detail.py b/venv/lib/python3.12/site-packages/sarvamai/types/task_detail.py new file mode 100644 index 0000000000000000000000000000000000000000..0e703a8c8cbd69cbd65a8391c2a4694e5afb939d --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/task_detail.py @@ -0,0 +1,25 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .task_file_details import TaskFileDetails +from .task_state import TaskState + + +class TaskDetail(UniversalBaseModel): + inputs: typing.Optional[typing.List[TaskFileDetails]] = None + outputs: typing.Optional[typing.List[TaskFileDetails]] = None + state: typing.Optional[TaskState] = None + error_message: typing.Optional[str] = None + exception_name: typing.Optional[str] = None + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/task_file_details.py b/venv/lib/python3.12/site-packages/sarvamai/types/task_file_details.py new file mode 100644 index 0000000000000000000000000000000000000000..645173dc57a3b7e29f09b7cdce5b53d6bbb577a1 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/task_file_details.py @@ -0,0 +1,20 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class TaskFileDetails(UniversalBaseModel): + file_name: str + file_id: str + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/task_state.py b/venv/lib/python3.12/site-packages/sarvamai/types/task_state.py new file mode 100644 index 0000000000000000000000000000000000000000..7cb6d3b1aa3bf4c60337c0c8878de3555044dbb0 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/task_state.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TaskState = typing.Union[typing.Literal["Success", "API Error", "Internal Server Error"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_language.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd609c7154918505ccc420b8a884d250180745c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_language.py @@ -0,0 +1,8 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TextToSpeechLanguage = typing.Union[ + typing.Literal["bn-IN", "en-IN", "gu-IN", "hi-IN", "kn-IN", "ml-IN", "mr-IN", "od-IN", "pa-IN", "ta-IN", "te-IN"], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_model.py b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_model.py new file mode 100644 index 0000000000000000000000000000000000000000..37fad78315c65fa6f6859d2103154b50a12faa7e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TextToSpeechModel = typing.Union[typing.Literal["bulbul:v2", "bulbul:v3"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_output_audio_codec.py b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_output_audio_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..b9dd2ceedddcff6d228212fc76b255925bd05123 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_output_audio_codec.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TextToSpeechOutputAudioCodec = typing.Union[ + typing.Literal["mp3", "linear16", "mulaw", "alaw", "opus", "flac", "aac", "wav"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e5bf53eea7b7465cf3bc8885127699183ed6fe6 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_response.py @@ -0,0 +1,23 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class TextToSpeechResponse(UniversalBaseModel): + request_id: typing.Optional[str] = None + audios: typing.List[str] = pydantic.Field() + """ + The output audio files in WAV format, encoded as base64 strings. Each string corresponds to one of the input texts. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_speaker.py b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_speaker.py new file mode 100644 index 0000000000000000000000000000000000000000..b8adb633010131e04e84b182d9de839dd91502b2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/text_to_speech_speaker.py @@ -0,0 +1,53 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TextToSpeechSpeaker = typing.Union[ + typing.Literal[ + "anushka", + "abhilash", + "manisha", + "vidya", + "arya", + "karun", + "hitesh", + "aditya", + "ritu", + "priya", + "neha", + "rahul", + "pooja", + "rohan", + "simran", + "kavya", + "amit", + "dev", + "ishita", + "shreya", + "ratan", + "varun", + "manan", + "sumit", + "roopa", + "kabir", + "aayan", + "shubh", + "ashutosh", + "advait", + "anand", + "tanya", + "tarun", + "sunny", + "mani", + "gokul", + "vijay", + "shruti", + "suhani", + "mohit", + "kavitha", + "rehan", + "soham", + "rupali", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/timestamps_model.py b/venv/lib/python3.12/site-packages/sarvamai/types/timestamps_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a639c9f280844ca9cda45cabee37cecda14175 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/timestamps_model.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class TimestampsModel(UniversalBaseModel): + words: typing.List[str] = pydantic.Field() + """ + List of words in the transcript. + """ + + start_time_seconds: typing.List[float] = pydantic.Field() + """ + List of start times of words in seconds. + """ + + end_time_seconds: typing.List[float] = pydantic.Field() + """ + List of end times of words in seconds. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/tool_choice_option.py b/venv/lib/python3.12/site-packages/sarvamai/types/tool_choice_option.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ece18a106e0c6932c01df28fa43f17e216efc5 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/tool_choice_option.py @@ -0,0 +1,9 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from .chat_completion_named_tool_choice import ChatCompletionNamedToolChoice + +ToolChoiceOption = typing.Union[ + typing.Literal["none"], typing.Literal["auto"], typing.Literal["required"], ChatCompletionNamedToolChoice +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/transcription_metrics.py b/venv/lib/python3.12/site-packages/sarvamai/types/transcription_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..2200d5f0b92b88052eb6f8510d4cfd1332480e4f --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/transcription_metrics.py @@ -0,0 +1,27 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class TranscriptionMetrics(UniversalBaseModel): + audio_duration: float = pydantic.Field() + """ + Duration of processed audio in seconds + """ + + processing_latency: float = pydantic.Field() + """ + Processing latency in seconds + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/translate_mode.py b/venv/lib/python3.12/site-packages/sarvamai/types/translate_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd6bf79efbd05a3292577f2d9b55a3e534e3e9a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/translate_mode.py @@ -0,0 +1,7 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TranslateMode = typing.Union[ + typing.Literal["formal", "modern-colloquial", "classic-colloquial", "code-mixed"], typing.Any +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/translate_model.py b/venv/lib/python3.12/site-packages/sarvamai/types/translate_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3e64fe8d77342c802dc38cdfb81f28654dc7cc1c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/translate_model.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TranslateModel = typing.Union[typing.Literal["mayura:v1", "sarvam-translate:v1"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/translate_source_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/translate_source_language.py new file mode 100644 index 0000000000000000000000000000000000000000..f3514b7944c86f3d84994ae3b25cbf6fbb358cc4 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/translate_source_language.py @@ -0,0 +1,33 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TranslateSourceLanguage = typing.Union[ + typing.Literal[ + "auto", + "bn-IN", + "en-IN", + "gu-IN", + "hi-IN", + "kn-IN", + "ml-IN", + "mr-IN", + "od-IN", + "pa-IN", + "ta-IN", + "te-IN", + "as-IN", + "brx-IN", + "doi-IN", + "kok-IN", + "ks-IN", + "mai-IN", + "mni-IN", + "ne-IN", + "sa-IN", + "sat-IN", + "sd-IN", + "ur-IN", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/translate_speaker_gender.py b/venv/lib/python3.12/site-packages/sarvamai/types/translate_speaker_gender.py new file mode 100644 index 0000000000000000000000000000000000000000..5020788bba0de5e7b9e66f72b2189f623c8c010e --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/translate_speaker_gender.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TranslateSpeakerGender = typing.Union[typing.Literal["Male", "Female"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/translate_target_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/translate_target_language.py new file mode 100644 index 0000000000000000000000000000000000000000..7346f52d2511335e15aa0370ac2919cb6662784a --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/translate_target_language.py @@ -0,0 +1,32 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TranslateTargetLanguage = typing.Union[ + typing.Literal[ + "bn-IN", + "en-IN", + "gu-IN", + "hi-IN", + "kn-IN", + "ml-IN", + "mr-IN", + "od-IN", + "pa-IN", + "ta-IN", + "te-IN", + "as-IN", + "brx-IN", + "doi-IN", + "kok-IN", + "ks-IN", + "mai-IN", + "mni-IN", + "ne-IN", + "sa-IN", + "sat-IN", + "sd-IN", + "ur-IN", + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/translation_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/translation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..275d5c6b6c5756cd867a16685c61041d002d3de2 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/translation_response.py @@ -0,0 +1,28 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class TranslationResponse(UniversalBaseModel): + request_id: typing.Optional[str] = None + translated_text: str = pydantic.Field() + """ + Translated text result in the requested target language. + """ + + source_language_code: str = pydantic.Field() + """ + Detected or provided source language of the input text. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/translatiterate_target_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/translatiterate_target_language.py new file mode 100644 index 0000000000000000000000000000000000000000..94a1aa7432a1f07b9731bdaf6c7a68b9dcbded8c --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/translatiterate_target_language.py @@ -0,0 +1,8 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TranslatiterateTargetLanguage = typing.Union[ + typing.Literal["bn-IN", "en-IN", "gu-IN", "hi-IN", "kn-IN", "ml-IN", "mr-IN", "od-IN", "pa-IN", "ta-IN", "te-IN"], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/transliterate_mode.py b/venv/lib/python3.12/site-packages/sarvamai/types/transliterate_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..8f27e96b7245a36113e0a744a3ecc297797028a7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/transliterate_mode.py @@ -0,0 +1,5 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TransliterateMode = typing.Union[typing.Literal["roman", "fully-native", "spoken-form-in-native"], typing.Any] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/transliterate_source_language.py b/venv/lib/python3.12/site-packages/sarvamai/types/transliterate_source_language.py new file mode 100644 index 0000000000000000000000000000000000000000..3769f94a1b7c3ecc76a60471ec3e4d82b82e0d98 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/transliterate_source_language.py @@ -0,0 +1,10 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +TransliterateSourceLanguage = typing.Union[ + typing.Literal[ + "auto", "bn-IN", "en-IN", "gu-IN", "hi-IN", "kn-IN", "ml-IN", "mr-IN", "od-IN", "pa-IN", "ta-IN", "te-IN" + ], + typing.Any, +] diff --git a/venv/lib/python3.12/site-packages/sarvamai/types/transliteration_response.py b/venv/lib/python3.12/site-packages/sarvamai/types/transliteration_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e81a9a1e46575b3b3f481aa5c7b30f663230b51 --- /dev/null +++ b/venv/lib/python3.12/site-packages/sarvamai/types/transliteration_response.py @@ -0,0 +1,28 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel + + +class TransliterationResponse(UniversalBaseModel): + request_id: typing.Optional[str] = None + transliterated_text: str = pydantic.Field() + """ + Transliterated text result in the requested target language. + """ + + source_language_code: str = pydantic.Field() + """ + Detected or provided source language of the input text. + """ + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + else: + + class Config: + frozen = True + smart_union = True + extra = pydantic.Extra.allow diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06107ab62e606dcd7b9746776d60bf435af3c4ca Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/__main__.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc412e1f188a27ee0538c11797c0fd56ec4d113a Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/__main__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/auth.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2029345cb480385085ca1828fdad4ddfac140471 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/auth.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/cli.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd458661a9fa80544a7e8b454dead3847d9718dd Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/cli.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb86a77fc62ab6f5b87bbfdd20c4ba2e4a626243 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/connection.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b33b3347ddb7c86b361959c06b693604cd499339 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/datastructures.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/datastructures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c7ae869e7276dca34a14d251ee4ea8f95260ee3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/datastructures.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/exceptions.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a56ee85a8605942e693d8c8dd9039be233adaab9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/frames.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/frames.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b46269d7e118c689d342463dc589d3b69d22cd93 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/frames.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/headers.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/headers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbb3ff91d8be99514fe347ffada41676aa62649d Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/headers.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/http.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/http.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7331288610064e47eb97df7f7a4097dda6231daf Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/http.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/http11.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/http11.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..837ae5568e5052e10db70671654ab8dd904937e9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/http11.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/imports.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/imports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8efcabd670ed0d8ff9c95efa06b18e3ead5ba144 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/imports.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/protocol.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d240895824f8526e5ee2d0804d6b1063eb5c160 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/protocol.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/proxy.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/proxy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0189e3b4d61529d50e65ffd4849126e659c091c3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/proxy.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/server.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d415cd7ac99f1249d7f1d22334e97886f0cedc7d Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/server.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/streams.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a1cb07ec4f8cb4007c4ba50bd92f1689215fcb3 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/streams.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/typing.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1e000aae6d231f46fbee2fe289328eea8c8476d Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/typing.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/uri.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/uri.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d89000e750536f7011d82026a93140e3d4a10c8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/uri.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/utils.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2242547e452be0584a875a342dfeca02b3336756 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/__pycache__/version.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f8d7a6c836086eed0cf0ec60b9025232e7b1022 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/__pycache__/version.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__init__.py b/venv/lib/python3.12/site-packages/websockets/asyncio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faaa9d17ff75611857d7cc2370b32722b31b22ad Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57279cff0bcdc54487d4a0f131773c9b41d04dc7 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f852e84909233af3280c7de7be5362ae7620230 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5599e5d2c5e278ccfae3d4f607d5a78ef37472fd Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/connection.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16f2f380e968f5510bc00d596c1d0fad02b05e36 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/messages.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/messages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dd1a900581eab14cbe7e893d6482f72c9356a0c Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/messages.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/router.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41cf2fec15b9a1cdab56c7af463cbf9e2e02730a Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/router.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/server.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fc6cb2f0f01a7bafa73947f7346cc40f4fc5f82 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/asyncio/__pycache__/server.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/async_timeout.py b/venv/lib/python3.12/site-packages/websockets/asyncio/async_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..6ffa899695637829dd5d3c7b58c68683000fc35d --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/asyncio/async_timeout.py @@ -0,0 +1,282 @@ +# From https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py +# Licensed under the Apache License (Apache-2.0) + +import asyncio +import enum +import sys +import warnings +from types import TracebackType +from typing import Optional, Type + + +if sys.version_info >= (3, 11): + from typing import final +else: + # From https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + # Licensed under the Python Software Foundation License (PSF-2.0) + + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + # End https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + + +if sys.version_info >= (3, 11): + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + task.uncancel() + +else: + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + pass + + +__version__ = "4.0.3" + + +__all__ = ("timeout", "timeout_at", "Timeout") + + +def timeout(delay: Optional[float]) -> "Timeout": + """timeout context manager. + + Useful in cases when you want to apply timeout logic around block + of code or in cases when asyncio.wait_for is not suitable. For example: + + >>> async with timeout(0.001): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + delay - value in seconds or None to disable timeout logic + """ + loop = asyncio.get_running_loop() + if delay is not None: + deadline = loop.time() + delay # type: Optional[float] + else: + deadline = None + return Timeout(deadline, loop) + + +def timeout_at(deadline: Optional[float]) -> "Timeout": + """Schedule the timeout at absolute time. + + deadline argument points on the time in the same clock system + as loop.time(). + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + + >>> async with timeout_at(loop.time() + 10): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + """ + loop = asyncio.get_running_loop() + return Timeout(deadline, loop) + + +class _State(enum.Enum): + INIT = "INIT" + ENTER = "ENTER" + TIMEOUT = "TIMEOUT" + EXIT = "EXIT" + + +@final +class Timeout: + # Internal class, please don't instantiate it directly + # Use timeout() and timeout_at() public factories instead. + # + # Implementation note: `async with timeout()` is preferred + # over `with timeout()`. + # While technically the Timeout class implementation + # doesn't need to be async at all, + # the `async with` statement explicitly points that + # the context manager should be used from async function context. + # + # This design allows to avoid many silly misusages. + # + # TimeoutError is raised immediately when scheduled + # if the deadline is passed. + # The purpose is to time out as soon as possible + # without waiting for the next await expression. + + __slots__ = ("_deadline", "_loop", "_state", "_timeout_handler", "_task") + + def __init__( + self, deadline: Optional[float], loop: asyncio.AbstractEventLoop + ) -> None: + self._loop = loop + self._state = _State.INIT + + self._task: Optional["asyncio.Task[object]"] = None + self._timeout_handler = None # type: Optional[asyncio.Handle] + if deadline is None: + self._deadline = None # type: Optional[float] + else: + self.update(deadline) + + def __enter__(self) -> "Timeout": + warnings.warn( + "with timeout() is deprecated, use async with timeout() instead", + DeprecationWarning, + stacklevel=2, + ) + self._do_enter() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + async def __aenter__(self) -> "Timeout": + self._do_enter() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + @property + def expired(self) -> bool: + """Is timeout expired during execution?""" + return self._state == _State.TIMEOUT + + @property + def deadline(self) -> Optional[float]: + return self._deadline + + def reject(self) -> None: + """Reject scheduled timeout if any.""" + # cancel is maybe better name but + # task.cancel() raises CancelledError in asyncio world. + if self._state not in (_State.INIT, _State.ENTER): + raise RuntimeError(f"invalid state {self._state.value}") + self._reject() + + def _reject(self) -> None: + self._task = None + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._timeout_handler = None + + def shift(self, delay: float) -> None: + """Advance timeout on delay seconds. + + The delay can be negative. + + Raise RuntimeError if shift is called when deadline is not scheduled + """ + deadline = self._deadline + if deadline is None: + raise RuntimeError("cannot shift timeout if deadline is not scheduled") + self.update(deadline + delay) + + def update(self, deadline: float) -> None: + """Set deadline to absolute value. + + deadline argument points on the time in the same clock system + as loop.time(). + + If new deadline is in the past the timeout is raised immediately. + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + """ + if self._state == _State.EXIT: + raise RuntimeError("cannot reschedule after exit from context manager") + if self._state == _State.TIMEOUT: + raise RuntimeError("cannot reschedule expired timeout") + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._deadline = deadline + if self._state != _State.INIT: + self._reschedule() + + def _reschedule(self) -> None: + assert self._state == _State.ENTER + deadline = self._deadline + if deadline is None: + return + + now = self._loop.time() + if self._timeout_handler is not None: + self._timeout_handler.cancel() + + self._task = asyncio.current_task() + if deadline <= now: + self._timeout_handler = self._loop.call_soon(self._on_timeout) + else: + self._timeout_handler = self._loop.call_at(deadline, self._on_timeout) + + def _do_enter(self) -> None: + if self._state != _State.INIT: + raise RuntimeError(f"invalid state {self._state.value}") + self._state = _State.ENTER + self._reschedule() + + def _do_exit(self, exc_type: Optional[Type[BaseException]]) -> None: + if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT: + assert self._task is not None + _uncancel_task(self._task) + self._timeout_handler = None + self._task = None + raise asyncio.TimeoutError + # timeout has not expired + self._state = _State.EXIT + self._reject() + return None + + def _on_timeout(self) -> None: + assert self._task is not None + self._task.cancel() + self._state = _State.TIMEOUT + # drop the reference early + self._timeout_handler = None + + +# End https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/client.py b/venv/lib/python3.12/site-packages/websockets/asyncio/client.py new file mode 100644 index 0000000000000000000000000000000000000000..05947f3a07e99e3b02fe3e5fe24be3a01bc58092 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/asyncio/client.py @@ -0,0 +1,804 @@ +from __future__ import annotations + +import asyncio +import logging +import os +import socket +import ssl as ssl_module +import traceback +import urllib.parse +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, Literal, cast + +from ..client import ClientProtocol, backoff +from ..datastructures import HeadersLike +from ..exceptions import ( + InvalidMessage, + InvalidProxyMessage, + InvalidProxyStatus, + InvalidStatus, + ProxyError, + SecurityError, +) +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request +from ..streams import StreamReader +from ..typing import LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .compatibility import TimeoutError, asyncio_timeout +from .connection import Connection + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + +MAX_REDIRECTS = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + +class ClientConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` coroutines + for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`connect`. + + Args: + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ClientProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.response_rcvd: asyncio.Future[None] = self.loop.create_future() + + async def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + ) -> None: + """ + Perform the opening handshake. + + """ + async with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + await asyncio.wait( + [self.response_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + +def process_exception(exc: Exception) -> Exception | None: + """ + Determine whether a connection error is retryable or fatal. + + When reconnecting automatically with ``async for ... in connect(...)``, if a + connection attempt fails, :func:`process_exception` is called to determine + whether to retry connecting or to raise the exception. + + This function defines the default behavior, which is to retry on: + + * :exc:`EOFError`, :exc:`OSError`, :exc:`asyncio.TimeoutError`: network + errors; + * :exc:`~websockets.exceptions.InvalidStatus` when the status code is 500, + 502, 503, or 504: server or proxy errors. + + All other exceptions are considered fatal. + + You can change this behavior with the ``process_exception`` argument of + :func:`connect`. + + Return :obj:`None` if the exception is retryable i.e. when the error could + be transient and trying to reconnect with the same parameters could succeed. + The exception will be logged at the ``INFO`` level. + + Return an exception, either ``exc`` or a new exception, if the exception is + fatal i.e. when trying to reconnect will most likely produce the same error. + That exception will be raised, breaking out of the retry loop. + + """ + # This catches python-socks' ProxyConnectionError and ProxyTimeoutError. + # Remove asyncio.TimeoutError when dropping Python < 3.11. + if isinstance(exc, (OSError, TimeoutError, asyncio.TimeoutError)): + return None + if isinstance(exc, InvalidMessage) and isinstance(exc.__cause__, EOFError): + return None + if isinstance(exc, InvalidStatus) and exc.response.status_code in [ + 500, # Internal Server Error + 502, # Bad Gateway + 503, # Service Unavailable + 504, # Gateway Timeout + ]: + return None + return exc + + +# This is spelled in lower case because it's exposed as a callable in the API. +class connect: + """ + Connect to the WebSocket server at ``uri``. + + This coroutine returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as an asynchronous context manager:: + + from websockets.asyncio.client import connect + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + If the connection fails with a transient error, it is retried with + exponential backoff. If it fails with a fatal error, the exception is + raised, breaking out of the loop. + + The connection is closed automatically after each iteration of the loop. + + Args: + uri: URI of the WebSocket server. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + process_exception: When reconnecting automatically, tell whether an + error is transient or fatal. The default behavior is defined by + :func:`process_exception`. Refer to its documentation for details. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS settings. + When connecting to a ``wss://`` URI, if ``ssl`` isn't provided, a TLS + context is created with :func:`~ssl.create_default_context`. + + * You can set ``server_hostname`` to override the host name from ``uri`` in + the TLS handshake. + + * You can set ``host`` and ``port`` to connect to a different host and port + from those found in ``uri``. This only changes the destination of the TCP + connection. The host name from ``uri`` is still used in the TLS handshake + for secure connections and in the ``Host`` header. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_connection` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_connection` method) to create a suitable + client socket and customize it. + + When using a proxy: + + * Prefix keyword arguments with ``proxy_`` for configuring TLS between the + client and an HTTPS proxy: ``proxy_ssl``, ``proxy_server_hostname``, + ``proxy_ssl_handshake_timeout``, and ``proxy_ssl_shutdown_timeout``. + * Use the standard keyword arguments for configuring TLS between the proxy + and the WebSocket server: ``ssl``, ``server_hostname``, + ``ssl_handshake_timeout``, and ``ssl_shutdown_timeout``. + * Other keyword arguments are used only for connecting to the proxy. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + InvalidProxy: If ``proxy`` isn't a valid proxy. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + def __init__( + self, + uri: str, + *, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + process_exception: Callable[[Exception], Exception | None] = process_exception, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + # Other keyword arguments are passed to loop.create_connection + **kwargs: Any, + ) -> None: + self.uri = uri + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if logger is None: + logger = logging.getLogger("websockets.client") + + if create_connection is None: + create_connection = ClientConnection + + def protocol_factory(uri: WebSocketURI) -> ClientConnection: + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ClientProtocol( + uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + self.proxy = proxy + self.protocol_factory = protocol_factory + self.additional_headers = additional_headers + self.user_agent_header = user_agent_header + self.process_exception = process_exception + self.open_timeout = open_timeout + self.logger = logger + self.connection_kwargs = kwargs + + async def create_connection(self) -> ClientConnection: + """Create TCP or Unix connection.""" + loop = asyncio.get_running_loop() + kwargs = self.connection_kwargs.copy() + + ws_uri = parse_uri(self.uri) + + proxy = self.proxy + if kwargs.get("unix", False): + proxy = None + if kwargs.get("sock") is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + def factory() -> ClientConnection: + return self.protocol_factory(ws_uri) + + if ws_uri.secure: + kwargs.setdefault("ssl", True) + kwargs.setdefault("server_hostname", ws_uri.host) + if kwargs.get("ssl") is None: + raise ValueError("ssl=None is incompatible with a wss:// URI") + else: + if kwargs.get("ssl") is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + if kwargs.pop("unix", False): + _, connection = await loop.create_unix_connection(factory, **kwargs) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = await connect_socks_proxy( + proxy_parsed, + ws_uri, + local_addr=kwargs.pop("local_addr", None), + ) + # Initialize WebSocket connection via the proxy. + _, connection = await loop.create_connection( + factory, + sock=sock, + **kwargs, + ) + elif proxy_parsed.scheme[:4] == "http": + # Split keyword arguments between the proxy and the server. + all_kwargs, proxy_kwargs, kwargs = kwargs, {}, {} + for key, value in all_kwargs.items(): + if key.startswith("ssl") or key == "server_hostname": + kwargs[key] = value + elif key.startswith("proxy_"): + proxy_kwargs[key[6:]] = value + else: + proxy_kwargs[key] = value + # Validate the proxy_ssl argument. + if proxy_parsed.scheme == "https": + proxy_kwargs.setdefault("ssl", True) + if proxy_kwargs.get("ssl") is None: + raise ValueError( + "proxy_ssl=None is incompatible with an https:// proxy" + ) + else: + if proxy_kwargs.get("ssl") is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + transport = await connect_http_proxy( + proxy_parsed, + ws_uri, + user_agent_header=self.user_agent_header, + **proxy_kwargs, + ) + # Initialize WebSocket connection via the proxy. + connection = factory() + transport.set_protocol(connection) + ssl = kwargs.pop("ssl", None) + if ssl is True: + ssl = ssl_module.create_default_context() + if ssl is not None: + new_transport = await loop.start_tls( + transport, connection, ssl, **kwargs + ) + assert new_transport is not None # help mypy + transport = new_transport + connection.connection_made(transport) + else: + raise AssertionError("unsupported proxy") + else: + # Connect to the server directly. + if kwargs.get("sock") is None: + kwargs.setdefault("host", ws_uri.host) + kwargs.setdefault("port", ws_uri.port) + # Initialize WebSocket connection. + _, connection = await loop.create_connection(factory, **kwargs) + return connection + + def process_redirect(self, exc: Exception) -> Exception | str: + """ + Determine whether a connection error is a redirect that can be followed. + + Return the new URI if it's a valid redirect. Else, return an exception. + + """ + if not ( + isinstance(exc, InvalidStatus) + and exc.response.status_code + in [ + 300, # Multiple Choices + 301, # Moved Permanently + 302, # Found + 303, # See Other + 307, # Temporary Redirect + 308, # Permanent Redirect + ] + and "Location" in exc.response.headers + ): + return exc + + old_ws_uri = parse_uri(self.uri) + new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"]) + new_ws_uri = parse_uri(new_uri) + + # If connect() received a socket, it is closed and cannot be reused. + if self.connection_kwargs.get("sock") is not None: + return ValueError( + f"cannot follow redirect to {new_uri} with a preexisting socket" + ) + + # TLS downgrade is forbidden. + if old_ws_uri.secure and not new_ws_uri.secure: + return SecurityError(f"cannot follow redirect to non-secure URI {new_uri}") + + # Apply restrictions to cross-origin redirects. + if ( + old_ws_uri.secure != new_ws_uri.secure + or old_ws_uri.host != new_ws_uri.host + or old_ws_uri.port != new_ws_uri.port + ): + # Cross-origin redirects on Unix sockets don't quite make sense. + if self.connection_kwargs.get("unix", False): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with a Unix socket" + ) + + # Cross-origin redirects when host and port are overridden are ill-defined. + if ( + self.connection_kwargs.get("host") is not None + or self.connection_kwargs.get("port") is not None + ): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with an explicit host or port" + ) + + return new_uri + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, ClientConnection]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> ClientConnection: + try: + async with asyncio_timeout(self.open_timeout): + for _ in range(MAX_REDIRECTS): + self.connection = await self.create_connection() + try: + await self.connection.handshake( + self.additional_headers, + self.user_agent_header, + ) + except asyncio.CancelledError: + self.connection.transport.abort() + raise + except Exception as exc: + # Always close the connection even though keep-alive is + # the default in HTTP/1.1 because create_connection ties + # opening the network connection with initializing the + # protocol. In the current design of connect(), there is + # no easy way to reuse the network connection that works + # in every case nor to reinitialize the protocol. + self.connection.transport.abort() + + uri_or_exc = self.process_redirect(exc) + # Response is a valid redirect; follow it. + if isinstance(uri_or_exc, str): + self.uri = uri_or_exc + continue + # Response isn't a valid redirect; raise the exception. + if uri_or_exc is exc: + raise + else: + raise uri_or_exc from exc + + else: + self.connection.start_keepalive() + return self.connection + else: + raise SecurityError(f"more than {MAX_REDIRECTS} redirects") + + except TimeoutError as exc: + # Re-raise exception with an informative error message. + raise TimeoutError("timed out during opening handshake") from exc + + # ... = yield from connect(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + # async with connect(...) as ...: ... + + async def __aenter__(self) -> ClientConnection: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.connection.close() + + # async for ... in connect(...): + + async def __aiter__(self) -> AsyncIterator[ClientConnection]: + delays: Generator[float] | None = None + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Determine whether the exception is retryable or fatal. + # The API of process_exception is "return an exception or None"; + # "raise an exception" is also supported because it's a frequent + # mistake. It isn't documented in order to keep the API simple. + try: + new_exc = self.process_exception(exc) + except Exception as raised_exc: + new_exc = raised_exc + + # The connection failed with a fatal error. + # Raise the exception and exit the loop. + if new_exc is exc: + raise + if new_exc is not None: + raise new_exc from exc + + # The connection failed with a retryable error. + # Start or continue backoff and reconnect. + if delays is None: + delays = backoff() + delay = next(delays) + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + delay, + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(delay) + continue + + else: + # The connection succeeded. Reset backoff. + delays = None + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> connect: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` argument is provided, to + ``wss://localhost/``. + + """ + if uri is None: + if kwargs.get("ssl") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.async_.asyncio import Proxy as SocksProxy + +except ImportError: + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("connecting through a SOCKS proxy requires python-socks") + +else: + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + # connect() is documented to raise OSError. + # socks_proxy.connect() doesn't raise TimeoutError; it gets canceled. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return await socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except OSError: + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + + +class HTTPProxyConnection(asyncio.Protocol): + def __init__( + self, + ws_uri: WebSocketURI, + proxy: Proxy, + user_agent_header: str | None = None, + ): + self.ws_uri = ws_uri + self.proxy = proxy + self.user_agent_header = user_agent_header + + self.reader = StreamReader() + self.parser = Response.parse( + self.reader.read_line, + self.reader.read_exact, + self.reader.read_to_eof, + proxy=True, + ) + + loop = asyncio.get_running_loop() + self.response: asyncio.Future[Response] = loop.create_future() + + def run_parser(self) -> None: + try: + next(self.parser) + except StopIteration as exc: + response = exc.value + if 200 <= response.status_code < 300: + self.response.set_result(response) + else: + self.response.set_exception(InvalidProxyStatus(response)) + except Exception as exc: + proxy_exc = InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) + proxy_exc.__cause__ = exc + self.response.set_exception(proxy_exc) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.transport = transport + self.transport.write( + prepare_connect_request(self.proxy, self.ws_uri, self.user_agent_header) + ) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + self.run_parser() + + def eof_received(self) -> None: + self.reader.feed_eof() + self.run_parser() + + def connection_lost(self, exc: Exception | None) -> None: + self.reader.feed_eof() + if exc is not None: + self.response.set_exception(exc) + + +async def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + user_agent_header: str | None = None, + **kwargs: Any, +) -> asyncio.Transport: + transport, protocol = await asyncio.get_running_loop().create_connection( + lambda: HTTPProxyConnection(ws_uri, proxy, user_agent_header), + proxy.host, + proxy.port, + **kwargs, + ) + + try: + # This raises exceptions if the connection to the proxy fails. + await protocol.response + except Exception: + transport.close() + raise + + return transport diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/compatibility.py b/venv/lib/python3.12/site-packages/websockets/asyncio/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..e17000069d530bdde8de5194e0d8257a5c5d1770 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/asyncio/compatibility.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import sys + + +__all__ = ["TimeoutError", "aiter", "anext", "asyncio_timeout", "asyncio_timeout_at"] + + +if sys.version_info[:2] >= (3, 11): + TimeoutError = TimeoutError + aiter = aiter + anext = anext + from asyncio import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) + +else: # Python < 3.11 + from asyncio import TimeoutError + + def aiter(async_iterable): + return type(async_iterable).__aiter__(async_iterable) + + async def anext(async_iterator): + return await type(async_iterator).__anext__(async_iterator) + + from .async_timeout import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/connection.py b/venv/lib/python3.12/site-packages/websockets/asyncio/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..205a2be50871cbc2cb85144421587a57a58bc725 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/asyncio/connection.py @@ -0,0 +1,1247 @@ +from __future__ import annotations + +import asyncio +import collections +import contextlib +import logging +import random +import struct +import sys +import traceback +import uuid +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from types import TracebackType +from typing import Any, Literal, cast, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .compatibility import ( + TimeoutError, + aiter, + anext, + asyncio_timeout, + asyncio_timeout_at, +) +from .messages import Assembler + + +__all__ = ["Connection"] + + +class Connection(asyncio.Protocol): + """ + :mod:`asyncio` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.asyncio.client.ClientConnection` or + :class:`~websockets.asyncio.server.ServerConnection`. + + """ + + def __init__( + self, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + self.max_queue_high, self.max_queue_low = max_queue, None + else: + self.max_queue_high, self.max_queue_low = max_queue + if isinstance(write_limit, int): + self.write_limit_high, self.write_limit_low = write_limit, None + else: + self.write_limit_high, self.write_limit_low = write_limit + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Event loop running this connection. + self.loop = asyncio.get_running_loop() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages: Assembler # initialized in connection_made + + # Deadline for the closing handshake. + self.close_deadline: float | None = None + + # Whether we are busy sending a fragmented message. + self.send_in_progress: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pending_pings: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0.0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0.0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task that sends keepalive pings. None when ping_interval is None. + self.keepalive_task: asyncio.Task[None] | None = None + + # Exception raised while reading from the connection, to be chained to + # ConnectionClosed in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Completed when the TCP connection is closed and the WebSocket + # connection state becomes CLOSED. + self.connection_lost_waiter: asyncio.Future[None] = self.loop.create_future() + + # Adapted from asyncio.FlowControlMixin. + self.paused: bool = False + self.drain_waiters: collections.deque[asyncio.Future[None]] = ( + collections.deque() + ) + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.transport.get_extra_info("peername") + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + async def __aenter__(self) -> Connection: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + await self.close() + else: + await self.close(CloseCode.INTERNAL_ERROR) + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages asynchronously in an + infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + @overload + async def recv(self, decode: Literal[True]) -> str: ... + + @overload + async def recv(self, decode: Literal[False]) -> bytes: ... + + @overload + async def recv(self, decode: bool | None = None) -> Data: ... + + async def recv(self, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing data. The next + invocation of :meth:`recv` will return the next message. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + When the message is fragmented, :meth:`recv` waits until all fragments + are received, reassembles them, and returns the whole message. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + return strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return await self.recv_messages.get(decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + asynchronous iterator that yields each fragment as it is received. This + iterator must be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Canceling :meth:`recv_streaming` before receiving the first frame is + safe. Canceling it after receiving one or more frames leaves the + iterator in a partially consumed state, making the connection unusable. + Instead, you should close the connection with :meth:`close`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + yield bytestrings (:class:`bytes`). This improves performance + when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + yield strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + async for frame in self.recv_messages.get_iter(decode): + yield frame + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + async def send( + self, + message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable or asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and the + effect is more obvious: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self.send_in_progress is not None: + await asyncio.shield(self.send_in_progress) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + assert self.send_in_progress is None + self.send_in_progress = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.send_in_progress.set_result(None) + self.send_in_progress = None + + # Fragmented message -- async iterator. + + elif isinstance(message, AsyncIterable): + achunks = aiter(message) + try: + chunk = await anext(achunks) + except StopAsyncIteration: + return + + assert self.send_in_progress is None + self.send_in_progress = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + if text is False: + async with self.send_context(): + self.protocol.send_binary(chunk.encode(), fin=False) + else: + async with self.send_context(): + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + if text is True: + async with self.send_context(): + self.protocol.send_text(chunk, fin=False) + else: + async with self.send_context(): + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("async iterable must contain bytes or str") + + # Other fragments + async for chunk in achunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("async iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.send_in_progress.set_result(None) + self.send_in_progress = None + + else: + raise TypeError("data must be str, bytes, iterable, or async iterable") + + async def close( + self, + code: CloseCode | int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + async with self.send_context(): + if self.send_in_progress is not None: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + :meth:`wait_closed` waits for the closing handshake to complete and for + the TCP connection to terminate. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: DataLike | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_received = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_received + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pending_pings: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pending_pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_received = self.loop.create_future() + ping_timestamp = self.loop.time() + # The event loop's default clock is time.monotonic(). Its resolution + # is a bit low on Windows (~16ms). This is improved in Python 3.13. + self.pending_pings[data] = (pong_received, ping_timestamp) + self.protocol.send_ping(data) + return pong_received + + async def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + # Ignore unsolicited pong. + if data not in self.pending_pings: + return + + pong_timestamp = self.loop.time() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_received, ping_timestamp) in self.pending_pings.items(): + ping_ids.append(ping_id) + latency = pong_timestamp - ping_timestamp + if not pong_received.done(): + pong_received.set_result(latency) + if ping_id == data: + self.latency = latency + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pending_pings. + for ping_id in ping_ids: + del self.pending_pings[ping_id] + + def terminate_pending_pings(self) -> None: + """ + Raise ConnectionClosed in pending pings when the connection is closed. + + """ + assert self.protocol.state is CLOSED + exc = self.protocol.close_exc + + for pong_received, _ping_timestamp in self.pending_pings.values(): + if not pong_received.done(): + pong_received.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_received.cancel() + + self.pending_pings.clear() + + async def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + latency = 0.0 + try: + while True: + # If self.ping_timeout > latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + await asyncio.sleep(self.ping_interval - latency) + + # This cannot raise ConnectionClosed when the connection is + # closing because ping(), via send_context(), waits for the + # connection to be closed before raising ConnectionClosed. + # However, connection_lost() cancels keepalive_task before + # it gets a chance to resume excuting. + pong_received = await self.ping() + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # connection_lost cancels keepalive immediately + # after setting a ConnectionClosed exception on + # pong_received. A CancelledError is raised here, + # not a ConnectionClosed exception. + latency = await pong_received + if self.debug: + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + raise AssertionError( + "send_context() should wait for connection_lost(), " + "which cancels keepalive()" + ) + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a task, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + self.keepalive_task = self.loop.create_task(self.keepalive()) + + @contextlib.asynccontextmanager + async def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> AsyncIterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` checks that the connection is open; on + exit, it writes outgoing data to the socket:: + + async with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the transport and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # Set the close deadline based on the close timeout. + # Since we tested earlier that protocol.state is OPEN + # (or CONNECTING), self.close_deadline is still None. + assert self.close_deadline is None + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + # Write outgoing data to the socket with flow control. + try: + self.send_data() + await self.drain() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + # Calculate close_deadline if it wasn't set yet. + if self.close_deadline is None: + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + raise_close_exc = True + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + try: + async with asyncio_timeout_at(self.close_deadline): + await asyncio.shield(self.connection_lost_waiter) + except TimeoutError: + # There's no risk of overwriting another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the transport in order to get + # proper exception reporting. + raise_close_exc = True + self.set_recv_exc(original_exc) + + # If an error occurred, close the transport to terminate the connection and + # raise an exception. + if raise_close_exc: + self.transport.abort() + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + """ + for data in self.protocol.data_to_send(): + if data: + self.transport.write(data) + else: + # Half-close the TCP connection when possible i.e. no TLS. + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # OSError is plausible. uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except Exception: # pragma: no cover + pass + # Else, close the TCP connection. + else: # pragma: no cover + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + This method must be called only from connection callbacks. + + """ + if self.recv_exc is None: + self.recv_exc = exc + + # asyncio.Protocol methods + + # Connection callbacks + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.recv_messages = Assembler( + self.max_queue_high, + self.max_queue_low, + pause=transport.pause_reading, + resume=transport.resume_reading, + ) + transport.set_write_buffer_limits( + self.write_limit_high, + self.write_limit_low, + ) + self.transport = transport + + def connection_lost(self, exc: Exception | None) -> None: + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + self.set_recv_exc(exc) + + # Abort recv() and pending pings with a ConnectionClosed exception. + self.recv_messages.close() + self.terminate_pending_pings() + + if self.keepalive_task is not None: + self.keepalive_task.cancel() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: # pragma: no cover + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + # Flow control callbacks + + def pause_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert not self.paused + self.paused = True + + def resume_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert self.paused + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + waiter.set_result(None) + + async def drain(self) -> None: # pragma: no cover + # We don't check if the connection is closed because we call drain() + # immediately after write() and write() would fail in that case. + + # Adapted from asyncio.streams.StreamWriter + # Yield to the event loop so that connection_lost() may be called. + if self.transport.is_closing(): + await asyncio.sleep(0) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: + waiter = self.loop.create_future() + self.drain_waiters.append(waiter) + try: + await waiter + finally: + self.drain_waiters.remove(waiter) + + # Streaming protocol callbacks + + def data_received(self, data: bytes) -> None: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the transport. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug("! error while sending data", exc_info=True) + self.set_recv_exc(exc) + + # If needed, set the close deadline based on the close timeout. + if self.protocol.close_expected(): + if self.close_deadline is None: + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + + # If self.send_data raised an exception, then events are lost. + # Given that automatic responses write small amounts of data, + # this should be uncommon, so we don't handle the edge case. + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + def eof_received(self) -> None: + # Feed the end of the data stream to the protocol. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream and it handles errors by itself. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + # The WebSocket protocol has its own closing handshake: endpoints close + # the TCP or TLS connection after sending and receiving a close frame. + # As a consequence, they never need to write after receiving EOF, so + # there's no reason to keep the transport open by returning True. + # Besides, that doesn't work on TLS connections. + + +# broadcast() is defined in the connection module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# Connection class. + + +def broadcast( + connections: Iterable[Connection], + message: DataLike, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.asyncio.connection.Connection.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if isinstance(message, str): + send_method = "send_text" + message = message.encode() + elif isinstance(message, BytesLike): + send_method = "send_binary" + else: + raise TypeError("data must be str or bytes") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions: list[Exception] = [] + + for connection in connections: + exception: Exception + + if connection.protocol.state is not OPEN: + continue + + if connection.send_in_progress is not None: + if raise_exceptions: + exception = ConcurrencyError("sending a fragmented message") + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + # Call connection.protocol.send_text or send_binary. + # Either way, message is already converted to bytes. + getattr(connection.protocol, send_method)(message) + connection.send_data() + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only(write_exception)[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.asyncio.server" diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/messages.py b/venv/lib/python3.12/site-packages/websockets/asyncio/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..f27cb2e7c8724434652f15be0a7efbdd49cf8951 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/asyncio/messages.py @@ -0,0 +1,316 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +from collections.abc import AsyncIterator, Iterable +from typing import Any, Callable, Generic, Literal, TypeVar, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + +T = TypeVar("T") + + +class SimpleQueue(Generic[T]): + """ + Simplified version of :class:`asyncio.Queue`. + + Provides only the subset of functionality needed by :class:`Assembler`. + + """ + + def __init__(self) -> None: + self.loop = asyncio.get_running_loop() + self.get_waiter: asyncio.Future[None] | None = None + self.queue: collections.deque[T] = collections.deque() + + def __len__(self) -> int: + return len(self.queue) + + def put(self, item: T) -> None: + """Put an item into the queue.""" + self.queue.append(item) + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_result(None) + + async def get(self, block: bool = True) -> T: + """Remove and return an item from the queue, waiting if necessary.""" + if not self.queue: + if not block: + raise EOFError("stream of frames ended") + assert self.get_waiter is None, "cannot call get() concurrently" + self.get_waiter = self.loop.create_future() + try: + await self.get_waiter + finally: + self.get_waiter.cancel() + self.get_waiter = None + return self.queue.popleft() + + def reset(self, items: Iterable[T]) -> None: + """Put back items into an empty, idle queue.""" + assert self.get_waiter is None, "cannot reset() while get() is running" + assert not self.queue, "cannot reset() while queue isn't empty" + self.queue.extend(items) + + def abort(self) -> None: + """Close the queue, raising EOFError in get() if necessary.""" + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_exception(EOFError("stream of frames ended")) + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + def __init__( + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Queue of incoming frames. + self.frames: SimpleQueue[Frame] = SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + @overload + async def get(self, decode: Literal[True]) -> str: ... + + @overload + async def get(self, decode: Literal[False]) -> bytes: ... + + @overload + async def get(self, decode: bool | None = None) -> Data: ... + + async def get(self, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or is canceled. + + try: + # Fetch the first frame. + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Fetch subsequent frames for fragmented messages. + while not frame.fin: + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.frames.reset(frames) + raise + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + # This converts frame.data to bytes when it's a bytearray. + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` asynchronously yields a + :class:`str` or :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or is canceled. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # Yield the first frame. + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + self.get_in_progress = False + raise + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + # Yield subsequent frames for fragmented messages. + while not frame.fin: + # We cannot handle asyncio.CancelledError because we don't buffer + # previous fragments — we're streaming them. Canceling get_iter() + # here will leave the assembler in a stuck state. Future calls to + # get() or get_iter() will raise ConcurrencyError. + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled. + if self.high is None: + return + + # Check for "> high" to support high = 0. + if len(self.frames) > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled. + if self.low is None: + return + + # Check for "<= low" to support low = 0. + if len(self.frames) <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + if self.closed: + return + + self.closed = True + + # Unblock get() or get_iter(). + self.frames.abort() diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/router.py b/venv/lib/python3.12/site-packages/websockets/asyncio/router.py new file mode 100644 index 0000000000000000000000000000000000000000..49d2a40feee03ebcda5e05dc43eebeb27ccecab7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/asyncio/router.py @@ -0,0 +1,219 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Awaitable, Callable, Literal + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +try: + from werkzeug.exceptions import NotFound + from werkzeug.routing import Map, RequestRedirect + +except ImportError: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + raise ImportError("route() requires werkzeug") + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + raise ImportError("unix_route() requires werkzeug") + +else: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.asyncio.router import route + from werkzeug.routing import Map, Rule + + async def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with route(url_map, ...) as server: + await stop + + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When + not provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without enabling TLS. + Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] = router.route_request + else: + + async def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if isinstance(response, Awaitable): + response = await response + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.asyncio.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + async def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return await connection.handler(connection, **connection.handler_kwargs) diff --git a/venv/lib/python3.12/site-packages/websockets/asyncio/server.py b/venv/lib/python3.12/site-packages/websockets/asyncio/server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef9bd807f102e05bbc3de212768bfed1679d8764 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/asyncio/server.py @@ -0,0 +1,997 @@ +from __future__ import annotations + +import asyncio +import hmac +import http +import logging +import re +import socket +import sys +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .compatibility import asyncio_timeout +from .connection import Connection, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "ServerConnection", + "Server", + "basic_auth", +] + + +class ServerConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`serve`. + + Args: + protocol: Sans-I/O connection. + server: Server that manages this connection. + + """ + + def __init__( + self, + protocol: ServerProtocol, + server: Server, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ServerProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.server = server + self.request_rcvd: asyncio.Future[None] = self.loop.create_future() + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], Awaitable[None]] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + async def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + ) -> None: + """ + Perform the opening handshake. + + """ + await asyncio.wait( + [self.request_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + if self.request is not None: + async with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + if self.server.is_serving(): + self.response = self.protocol.accept(self.request) + else: + self.response = self.protocol.reject( + http.HTTPStatus.SERVICE_UNAVAILABLE, + "Server is shutting down.\n", + ) + else: + assert isinstance(response, Response) # help mypy + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + assert isinstance(response, Response) # help mypy + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + super().connection_made(transport) + self.server.start_connection_handler(self) + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. ``process_response`` may be a function or a + coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + *, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + open_timeout: float | None = 10, + logger: LoggerLike | None = None, + ) -> None: + self.loop = asyncio.get_running_loop() + self.handler = handler + self.process_request = process_request + self.process_response = process_response + self.server_header = server_header + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.handlers: dict[ServerConnection, asyncio.Task[None]] = {} + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] = self.loop.create_future() + + @property + def connections(self) -> set[ServerConnection]: + """ + Set of active connections. + + This property contains all connections that completed the opening + handshake successfully and didn't start the closing handshake yet. + It can be useful in combination with :func:`~broadcast`. + + """ + return {connection for connection in self.handlers if connection.state is OPEN} + + def wrap(self, server: asyncio.Server) -> None: + """ + Attach to a given :class:`asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`Server` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + async def conn_handler(self, connection: ServerConnection) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller that can handle exceptions, + it attempts to log relevant ones. + + It guarantees that the TCP connection is closed before exiting. + + """ + try: + async with asyncio_timeout(self.open_timeout): + try: + await connection.handshake( + self.process_request, + self.process_response, + self.server_header, + ) + except asyncio.CancelledError: + connection.transport.abort() + raise + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.transport.abort() + return + + if connection.protocol.state is not OPEN: + # process_request or process_response rejected the handshake. + connection.transport.abort() + return + + try: + connection.start_keepalive() + await self.handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + await connection.close(CloseCode.INTERNAL_ERROR) + else: + await connection.close() + + except TimeoutError: + # When the opening handshake times out, there's nothing to log. + pass + + except Exception: # pragma: no cover + # Don't leak connections on unexpected errors. + connection.transport.abort() + + finally: + # Registration is tied to the lifecycle of conn_handler() because + # the server waits for connection handlers to terminate, even if + # all connections are already closed. + del self.handlers[connection] + + def start_connection_handler(self, connection: ServerConnection) -> None: + """ + Register a connection with this server. + + """ + # The connection must be registered in self.handlers immediately. + # If it was registered in conn_handler(), a race condition could + # happen when closing the server after scheduling conn_handler() + # but before it starts executing. + self.handlers[connection] = self.loop.create_task(self.conn_handler(connection)) + + def close( + self, + close_connections: bool = True, + code: CloseCode | int = CloseCode.GOING_AWAY, + reason: str = "", + ) -> None: + """ + Close the server. + + * Close the underlying :class:`asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, close + existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with code 1001 (going away). + ``code`` and ``reason`` can be customized, for example to use code + 1012 (service restart). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections, code, reason) + ) + + async def _close( + self, + close_connections: bool = True, + code: CloseCode | int = CloseCode.GOING_AWAY, + reason: str = "", + ) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`asyncio.Server` object to stop accepting new connections and + then closes open connections. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + # After server.close(), handshake() closes OPENING connections with an + # HTTP 503 error. + + if close_connections: + # Close OPEN connections with code 1001 by default. + close_tasks = [ + asyncio.create_task(connection.close(code, reason)) + for connection in self.handlers + if connection.protocol.state is not CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.handlers: + await asyncio.wait(self.handlers.values()) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~ServerConnection.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~ServerConnection.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: # pragma: no cover + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> tuple[socket.socket, ...]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> Server: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +# This is spelled in lower case because it's exposed as a callable in the API. +class serve: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler`` coroutine. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This coroutine returns a :class:`Server` whose API mirrors + :class:`asyncio.Server`. Treat it as an asynchronous context manager to + ensure that the server will be closed:: + + from websockets.asyncio.server import serve + + def handler(websocket): + ... + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(handler, host, port): + await stop + + Alternatively, call :meth:`~Server.serve_forever` to serve requests and + cancel it to stop the server:: + + server = await serve(handler, host, port) + await server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_response`` may be a function or a coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_server` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_server` method) to create a suitable server + socket and customize it. + + * You can set ``start_serving`` to ``False`` to start accepting connections + only after you call :meth:`~Server.start_serving()` or + :meth:`~Server.serve_forever()`. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + host: str | None = None, + port: int | None = None, + *, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + # Other keyword arguments are passed to loop.create_server + **kwargs: Any, + ) -> None: + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + self.server = Server( + handler, + process_request=process_request, + process_response=process_response, + server_header=server_header, + open_timeout=open_timeout, + logger=logger, + ) + + if kwargs.get("ssl") is not None: + kwargs.setdefault("ssl_handshake_timeout", open_timeout) + if sys.version_info[:2] >= (3, 11): # pragma: no branch + kwargs.setdefault("ssl_shutdown_timeout", close_timeout) + + def factory() -> ServerConnection: + """ + Create an asyncio protocol for managing a WebSocket connection. + + """ + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + self.server, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + loop = asyncio.get_running_loop() + if kwargs.pop("unix", False): + self.create_server = loop.create_unix_server(factory, **kwargs) + else: + # mypy cannot tell that kwargs must provide sock when port is None. + self.create_server = loop.create_server(factory, host, port, **kwargs) # type: ignore[arg-type] + + # async with serve(...) as ...: ... + + async def __aenter__(self) -> Server: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.server.close() + await self.server.wait_closed() + + # ... = await serve(...) + + def __await__(self) -> Generator[Any, None, Server]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> Server: + server = await self.create_server + self.server.wrap(server) + return self.server + + # ... = yield from serve(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +def unix_serve( + handler: Callable[[ServerConnection], Awaitable[None]], + path: str | None = None, + **kwargs: Any, +) -> Awaitable[Server]: + """ + Create a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool] | bool] | None = None, +) -> Callable[[ServerConnection, Request], Awaitable[Response | None]]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.asyncio.server import basic_auth, serve + + async with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function or coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + async def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + valid_credentials = check_credentials(username, password) + if isinstance(valid_credentials, Awaitable): + valid_credentials = await valid_credentials + + if not valid_credentials: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/venv/lib/python3.12/site-packages/websockets/extensions/__init__.py b/venv/lib/python3.12/site-packages/websockets/extensions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02838b98a5335322daad566de9c0d9d0843fc49a --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/extensions/__init__.py @@ -0,0 +1,4 @@ +from .base import * + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] diff --git a/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0981efee96402ef5e329041225b898fcf2dfeaa0 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/base.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5bcbb1b0dcf993a4c5c256c5630f4e00d11d9d4 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/base.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0d43015870c74c7458ef56b5057181ecd4e4bdc Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/extensions/base.py b/venv/lib/python3.12/site-packages/websockets/extensions/base.py new file mode 100644 index 0000000000000000000000000000000000000000..2fdc59f0fdae4d28fdcf18b6f9edf8d62ad22f01 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/extensions/base.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from collections.abc import Sequence + +from ..frames import Frame +from ..typing import ExtensionName, ExtensionParameter + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] + + +class Extension: + """ + Base class for extensions. + + """ + + name: ExtensionName + """Extension identifier.""" + + def decode(self, frame: Frame, *, max_size: int | None = None) -> Frame: + """ + Decode an incoming frame. + + Args: + frame: Incoming frame. + max_size: Maximum payload size in bytes. + + Returns: + Decoded frame. + + Raises: + PayloadTooBig: If decoding the payload exceeds ``max_size``. + + """ + raise NotImplementedError + + def encode(self, frame: Frame) -> Frame: + """ + Encode an outgoing frame. + + Args: + frame: Outgoing frame. + + Returns: + Encoded frame. + + """ + raise NotImplementedError + + +class ClientExtensionFactory: + """ + Base class for client-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build parameters to send to the server for this extension. + + Returns: + Parameters to send to the server. + + """ + raise NotImplementedError + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> Extension: + """ + Process parameters received from the server. + + Args: + params: Parameters received from the server for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + An extension instance. + + Raises: + NegotiationError: If parameters aren't acceptable. + + """ + raise NotImplementedError + + +class ServerExtensionFactory: + """ + Base class for server-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], Extension]: + """ + Process parameters received from the client. + + Args: + params: Parameters received from the client for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + To accept the offer, parameters to send to the client for this + extension and an extension instance. + + Raises: + NegotiationError: To reject the offer, if parameters received from + the client aren't acceptable. + + """ + raise NotImplementedError diff --git a/venv/lib/python3.12/site-packages/websockets/extensions/permessage_deflate.py b/venv/lib/python3.12/site-packages/websockets/extensions/permessage_deflate.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc63d79929321007578d3e1d96338f099fad085 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/extensions/permessage_deflate.py @@ -0,0 +1,699 @@ +from __future__ import annotations + +import zlib +from collections.abc import Sequence +from typing import Any, Literal + +from .. import frames +from ..exceptions import ( + DuplicateParameter, + InvalidParameterName, + InvalidParameterValue, + NegotiationError, + PayloadTooBig, + ProtocolError, +) +from ..typing import BytesLike, ExtensionName, ExtensionParameter +from .base import ClientExtensionFactory, Extension, ServerExtensionFactory + + +__all__ = [ + "PerMessageDeflate", + "ClientPerMessageDeflateFactory", + "enable_client_permessage_deflate", + "ServerPerMessageDeflateFactory", + "enable_server_permessage_deflate", +] + +_EMPTY_UNCOMPRESSED_BLOCK = b"\x00\x00\xff\xff" + +_MAX_WINDOW_BITS_VALUES = [str(bits) for bits in range(8, 16)] + + +class PerMessageDeflate(Extension): + """ + Per-Message Deflate extension. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + remote_no_context_takeover: bool, + local_no_context_takeover: bool, + remote_max_window_bits: int, + local_max_window_bits: int, + compress_settings: dict[Any, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension. + + """ + if compress_settings is None: + compress_settings = {} + + assert remote_no_context_takeover in [False, True] + assert local_no_context_takeover in [False, True] + assert 8 <= remote_max_window_bits <= 15 + assert 8 <= local_max_window_bits <= 15 + assert "wbits" not in compress_settings + + self.remote_no_context_takeover = remote_no_context_takeover + self.local_no_context_takeover = local_no_context_takeover + self.remote_max_window_bits = remote_max_window_bits + self.local_max_window_bits = local_max_window_bits + self.compress_settings = compress_settings + + if not self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + if not self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # To handle continuation frames properly, we must keep track of + # whether that initial frame was encoded. + self.decode_cont_data = False + # There's no need for self.encode_cont_data because we always encode + # outgoing frames, so it would always be True. + + def __repr__(self) -> str: + return ( + f"PerMessageDeflate(" + f"remote_no_context_takeover={self.remote_no_context_takeover}, " + f"local_no_context_takeover={self.local_no_context_takeover}, " + f"remote_max_window_bits={self.remote_max_window_bits}, " + f"local_max_window_bits={self.local_max_window_bits})" + ) + + def decode( + self, + frame: frames.Frame, + *, + max_size: int | None = None, + ) -> frames.Frame: + """ + Decode an incoming frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Handle continuation data frames: + # - skip if the message isn't encoded + # - reset "decode continuation data" flag if it's a final frame + if frame.opcode is frames.OP_CONT: + if not self.decode_cont_data: + return frame + if frame.fin: + self.decode_cont_data = False + + # Handle text and binary data frames: + # - skip if the message isn't encoded + # - unset the rsv1 flag on the first frame of a compressed message + # - set "decode continuation data" flag if it's a non-final frame + else: + if not frame.rsv1: + return frame + if not frame.fin: + self.decode_cont_data = True + + # Re-initialize per-message decoder. + if self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + # Uncompress data. Protect against zip bombs by preventing zlib from + # decompressing more than max_length bytes (except when the limit is + # disabled with max_size = None). + data: BytesLike + if frame.fin and len(frame.data) < 2044: + # Profiling shows that appending four bytes, which makes a copy, is + # faster than calling decompress() again when data is less than 2kB. + data = bytes(frame.data) + _EMPTY_UNCOMPRESSED_BLOCK + else: + data = frame.data + max_length = 0 if max_size is None else max_size + try: + data = self.decoder.decompress(data, max_length) + if self.decoder.unconsumed_tail: + assert max_size is not None # help mypy + raise PayloadTooBig(None, max_size) + if frame.fin and len(frame.data) >= 2044: + # This cannot generate additional data. + self.decoder.decompress(_EMPTY_UNCOMPRESSED_BLOCK) + except zlib.error as exc: + raise ProtocolError("decompression failed") from exc + + # Allow garbage collection of the decoder if it won't be reused. + if frame.fin and self.remote_no_context_takeover: + del self.decoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Unset the rsv1 flag on the first frame of a compressed message. + False, + frame.rsv2, + frame.rsv3, + ) + + def encode(self, frame: frames.Frame) -> frames.Frame: + """ + Encode an outgoing frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Since we always encode messages, there's no "encode continuation + # data" flag similar to "decode continuation data" at this time. + + if frame.opcode is not frames.OP_CONT: + # Re-initialize per-message decoder. + if self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # Compress data. + data: BytesLike + data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH) + if frame.fin: + # Sync flush generates between 5 or 6 bytes, ending with the bytes + # 0x00 0x00 0xff 0xff, which must be removed. + assert data[-4:] == _EMPTY_UNCOMPRESSED_BLOCK + # Making a copy is faster than memoryview(a)[:-4] until 2kB. + if len(data) < 2048: + data = data[:-4] + else: + data = memoryview(data)[:-4] + + # Allow garbage collection of the encoder if it won't be reused. + if frame.fin and self.local_no_context_takeover: + del self.encoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Set the rsv1 flag on the first frame of a compressed message. + frame.opcode is not frames.OP_CONT, + frame.rsv2, + frame.rsv3, + ) + + +def _build_parameters( + server_no_context_takeover: bool, + client_no_context_takeover: bool, + server_max_window_bits: int | None, + client_max_window_bits: int | Literal[True] | None, +) -> list[ExtensionParameter]: + """ + Build a list of ``(name, value)`` pairs for some compression parameters. + + """ + params: list[ExtensionParameter] = [] + if server_no_context_takeover: + params.append(("server_no_context_takeover", None)) + if client_no_context_takeover: + params.append(("client_no_context_takeover", None)) + if server_max_window_bits: + params.append(("server_max_window_bits", str(server_max_window_bits))) + if client_max_window_bits is True: # only in handshake requests + params.append(("client_max_window_bits", None)) + elif client_max_window_bits: + params.append(("client_max_window_bits", str(client_max_window_bits))) + return params + + +def _extract_parameters( + params: Sequence[ExtensionParameter], *, is_server: bool +) -> tuple[bool, bool, int | None, int | Literal[True] | None]: + """ + Extract compression parameters from a list of ``(name, value)`` pairs. + + If ``is_server`` is :obj:`True`, ``client_max_window_bits`` may be + provided without a value. This is only allowed in handshake requests. + + """ + server_no_context_takeover: bool = False + client_no_context_takeover: bool = False + server_max_window_bits: int | None = None + client_max_window_bits: int | Literal[True] | None = None + + for name, value in params: + if name == "server_no_context_takeover": + if server_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + server_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "client_no_context_takeover": + if client_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + client_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "server_max_window_bits": + if server_max_window_bits is not None: + raise DuplicateParameter(name) + if value in _MAX_WINDOW_BITS_VALUES: + server_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + elif name == "client_max_window_bits": + if client_max_window_bits is not None: + raise DuplicateParameter(name) + if is_server and value is None: # only in handshake requests + client_max_window_bits = True + elif value in _MAX_WINDOW_BITS_VALUES: + client_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + else: + raise InvalidParameterName(name) + + return ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) + + +class ClientPerMessageDeflateFactory(ClientExtensionFactory): + """ + Client-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15, or :obj:`True` to indicate support without + setting a limit. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | Literal[True] | None = True, + compress_settings: dict[str, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not ( + client_max_window_bits is None + or client_max_window_bits is True + or 8 <= client_max_window_bits <= 15 + ): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set client_max_window_bits instead" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build request parameters. + + """ + return _build_parameters( + self.server_no_context_takeover, + self.client_no_context_takeover, + self.server_max_window_bits, + self.client_max_window_bits, + ) + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> PerMessageDeflate: + """ + Process response parameters. + + Return an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"received duplicate {self.name}") + + # Request parameters are available in instance variables. + + # Load response parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=False) + + # After comparing the request and the response, the final + # configuration must be available in the local variables. + + # server_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False Error! + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + raise NegotiationError("expected server_no_context_takeover") + + # client_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value + # True True True + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None Error! + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + raise NegotiationError("unsupported server_max_window_bits") + + # client_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 Error! + # True None None + # True 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.client_max_window_bits: + raise NegotiationError("unsupported client_max_window_bits") + + return PerMessageDeflate( + server_no_context_takeover, # remote_no_context_takeover + client_no_context_takeover, # local_no_context_takeover + server_max_window_bits or 15, # remote_max_window_bits + client_max_window_bits or 15, # local_max_window_bits + self.compress_settings, + ) + + +def enable_client_permessage_deflate( + extensions: Sequence[ClientExtensionFactory] | None, +) -> Sequence[ClientExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in client extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + extension_factory.name == ClientPerMessageDeflateFactory.name + for extension_factory in extensions + ): + extensions = list(extensions) + [ + ClientPerMessageDeflateFactory( + compress_settings={"memLevel": 5}, + ) + ] + return extensions + + +class ServerPerMessageDeflateFactory(ServerExtensionFactory): + """ + Server-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + require_client_max_window_bits: Do not enable compression at all if + client doesn't advertise support for ``client_max_window_bits``; + the default behavior is to enable compression without enforcing + ``client_max_window_bits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | None = None, + compress_settings: dict[str, Any] | None = None, + require_client_max_window_bits: bool = False, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set server_max_window_bits instead" + ) + if client_max_window_bits is None and require_client_max_window_bits: + raise ValueError( + "require_client_max_window_bits is enabled, " + "but client_max_window_bits isn't configured" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + self.require_client_max_window_bits = require_client_max_window_bits + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], PerMessageDeflate]: + """ + Process request parameters. + + Return response params and an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"skipped duplicate {self.name}") + + # Load request parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=True) + + # Configuration parameters are available in instance variables. + + # After comparing the request and the configuration, the response must + # be available in the local variables. + + # server_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value to True + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + server_no_context_takeover = True + + # client_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True (or False) + # True False True - must change value to True + # True True True (or False) + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + server_max_window_bits = self.server_max_window_bits + + # client_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None True None - must change value + # None 8≤M≤15 M (or None) + # 8≤N≤15 None None or Error! + # 8≤N≤15 True N - must change value + # 8≤N≤15 8≤M≤N M (or None) + # 8≤N≤15 N Sequence[ServerExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in server extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + ext_factory.name == ServerPerMessageDeflateFactory.name + for ext_factory in extensions + ): + extensions = list(extensions) + [ + ServerPerMessageDeflateFactory( + server_max_window_bits=12, + client_max_window_bits=12, + compress_settings={"memLevel": 5}, + ) + ] + return extensions diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__init__.py b/venv/lib/python3.12/site-packages/websockets/legacy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9aa25064f626754bda8a8bb149d974002a064e --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/__init__.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +import warnings + + +warnings.warn( # deprecated in 14.0 - 2024-11-09 + "websockets.legacy is deprecated; " + "see https://websockets.readthedocs.io/en/stable/howto/upgrade.html " + "for upgrade instructions", + DeprecationWarning, +) diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7ffbc76a97a707c29a83d1ce3e2fb4fdde139e5 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/auth.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e218abd0c9f32f15ee1c9ea8cd16bb184e9f14a2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/auth.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0f0c4c19957fa4777ae4f97c7d56ee8ef92c8e8 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/exceptions.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2ae29e3923208a774d2a4e2e927549248e293f4 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/exceptions.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/framing.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/framing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c2d2beff0882e081c454c16c65f386ef2515c67 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/framing.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/handshake.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/handshake.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96f08ca837e612c49779d296f0d3c1a7230149c2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/handshake.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/http.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/http.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c654c6ebecd43fd63b2036f544bfc9cc50dadccd Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/http.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/protocol.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b27ec2bbdf7d7531d2b4d74b43a023cb7e724279 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/protocol.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/server.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6a9823870b147c20e0ecf03a51e1b09c9be88cd Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/legacy/__pycache__/server.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/auth.py b/venv/lib/python3.12/site-packages/websockets/legacy/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..a262fcd791bc66a1ad0ee9389faed1c62c69e2be --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/auth.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import functools +import hmac +import http +from collections.abc import Awaitable, Iterable +from typing import Any, Callable, cast + +from ..datastructures import Headers +from ..exceptions import InvalidHeader +from ..headers import build_www_authenticate_basic, parse_authorization_basic +from .server import HTTPResponse, WebSocketServerProtocol + + +__all__ = ["BasicAuthWebSocketServerProtocol", "basic_auth_protocol_factory"] + +Credentials = tuple[str, str] + + +def is_credentials(value: Any) -> bool: + try: + username, password = value + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +class BasicAuthWebSocketServerProtocol(WebSocketServerProtocol): + """ + WebSocket server protocol that enforces HTTP Basic Auth. + + """ + + realm: str = "" + """ + Scope of protection. + + If provided, it should contain only ASCII characters because the + encoding of non-ASCII characters is undefined. + """ + + username: str | None = None + """Username of the authenticated user.""" + + def __init__( + self, + *args: Any, + realm: str | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + **kwargs: Any, + ) -> None: + if realm is not None: + self.realm = realm # shadow class attribute + self._check_credentials = check_credentials + super().__init__(*args, **kwargs) + + async def check_credentials(self, username: str, password: str) -> bool: + """ + Check whether credentials are authorized. + + This coroutine may be overridden in a subclass, for example to + authenticate against a database or an external service. + + Args: + username: HTTP Basic Auth username. + password: HTTP Basic Auth password. + + Returns: + :obj:`True` if the handshake should continue; + :obj:`False` if it should fail with an HTTP 401 error. + + """ + if self._check_credentials is not None: + return await self._check_credentials(username, password) + + return False + + async def process_request( + self, + path: str, + request_headers: Headers, + ) -> HTTPResponse | None: + """ + Check HTTP Basic Auth and return an HTTP 401 response if needed. + + """ + try: + authorization = request_headers["Authorization"] + except KeyError: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Missing credentials\n", + ) + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Unsupported credentials\n", + ) + + if not await self.check_credentials(username, password): + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Invalid credentials\n", + ) + + self.username = username + + return await super().process_request(path, request_headers) + + +def basic_auth_protocol_factory( + realm: str | None = None, + credentials: Credentials | Iterable[Credentials] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + create_protocol: Callable[..., BasicAuthWebSocketServerProtocol] | None = None, +) -> Callable[..., BasicAuthWebSocketServerProtocol]: + """ + Protocol factory that enforces HTTP Basic Auth. + + :func:`basic_auth_protocol_factory` is designed to integrate with + :func:`~websockets.legacy.server.serve` like this:: + + serve( + ..., + create_protocol=basic_auth_protocol_factory( + realm="my dev server", + credentials=("hello", "iloveyou"), + ) + ) + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. + Refer to section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments + and returns a :class:`bool`. One of ``credentials`` or + ``check_credentials`` must be provided but not both. + create_protocol: Factory that creates the protocol. By default, this + is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced + by a subclass. + Raises: + TypeError: If the ``credentials`` or ``check_credentials`` argument is + wrong. + + """ + if (credentials is None) == (check_credentials is None): + raise TypeError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(Credentials, credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[Credentials], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + async def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + if create_protocol is None: + create_protocol = BasicAuthWebSocketServerProtocol + + # Help mypy and avoid this error: "type[BasicAuthWebSocketServerProtocol] | + # Callable[..., BasicAuthWebSocketServerProtocol]" not callable [misc] + create_protocol = cast( + Callable[..., BasicAuthWebSocketServerProtocol], create_protocol + ) + return functools.partial( + create_protocol, + realm=realm, + check_credentials=check_credentials, + ) diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/client.py b/venv/lib/python3.12/site-packages/websockets/legacy/client.py new file mode 100644 index 0000000000000000000000000000000000000000..575c84519c35b3aa25481a5a3abf45b9719df630 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/client.py @@ -0,0 +1,703 @@ +from __future__ import annotations + +import asyncio +import functools +import logging +import os +import random +import traceback +import urllib.parse +import warnings +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike +from ..exceptions import ( + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + NegotiationError, + SecurityError, +) +from ..extensions import ClientExtensionFactory, Extension +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import ( + build_authorization_basic, + build_extension, + build_host, + build_subprotocol, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import USER_AGENT +from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .exceptions import InvalidStatusCode, RedirectHandshake +from .handshake import build_request, check_response +from .http import read_response +from .protocol import WebSocketCommonProtocol + + +__all__ = ["connect", "unix_connect", "WebSocketClientProtocol"] + + +class WebSocketClientProtocol(WebSocketCommonProtocol): + """ + WebSocket client connection. + + :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + See :func:`connect` for the documentation of ``logger``, ``origin``, + ``extensions``, ``subprotocols``, ``extra_headers``, and + ``user_agent_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = True + side = "client" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.client") + super().__init__(logger=logger, **kwargs) + self.origin = origin + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.user_agent_header = user_agent_header + + def write_http_request(self, path: str, headers: Headers) -> None: + """ + Write request line and headers to the HTTP request. + + """ + self.path = path + self.request_headers = headers + + if self.debug: + self.logger.debug("> GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + + # Since the path and headers only contain ASCII characters, + # we can keep this simple. + request = f"GET {path} HTTP/1.1\r\n" + request += str(headers) + + self.transport.write(request.encode()) + + async def read_http_response(self) -> tuple[int, Headers]: + """ + Read status line and headers from the HTTP response. + + If the response contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET response. + + """ + try: + status_code, reason, headers = await read_response(self.reader) + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP response") from exc + + if self.debug: + self.logger.debug("< HTTP/1.1 %d %s", status_code, reason) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.response_headers = headers + + return status_code, self.response_headers + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ClientExtensionFactory] | None, + ) -> list[Extension]: + """ + Handle the Sec-WebSocket-Extensions HTTP response header. + + Check that each extension is supported, as well as its parameters. + + Return the list of accepted extensions. + + Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the + connection. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension accepted by + the server, we check for a match with each extension available in the + client configuration. If no match is found, an exception is raised. + + If several variants of the same extension are accepted by the server, + it may be configured several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + """ + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values: + if available_extensions is None: + raise NegotiationError("no extensions supported") + + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, response_params in parsed_header_values: + for extension_factory in available_extensions: + # Skip non-matching extensions based on their name. + if extension_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + extension = extension_factory.process_response_params( + response_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the server sent. Fail the connection. + else: + raise NegotiationError( + f"Unsupported extension: " + f"name = {name}, params = {response_params}" + ) + + return accepted_extensions + + @staticmethod + def process_subprotocol( + headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP response header. + + Check that it contains exactly one supported subprotocol. + + Return the selected subprotocol. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values: + if available_subprotocols is None: + raise NegotiationError("no subprotocols supported") + + parsed_header_values: Sequence[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + if len(parsed_header_values) > 1: + raise InvalidHeaderValue( + "Sec-WebSocket-Protocol", + f"multiple values: {', '.join(parsed_header_values)}", + ) + + subprotocol = parsed_header_values[0] + + if subprotocol not in available_subprotocols: + raise NegotiationError(f"unsupported subprotocol: {subprotocol}") + + return subprotocol + + async def handshake( + self, + wsuri: WebSocketURI, + origin: Origin | None = None, + available_extensions: Sequence[ClientExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + ) -> None: + """ + Perform the client side of the opening handshake. + + Args: + wsuri: URI of the WebSocket server. + origin: Value of the ``Origin`` header. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + request_headers = Headers() + + request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure) + + if wsuri.user_info: + request_headers["Authorization"] = build_authorization_basic( + *wsuri.user_info + ) + + if origin is not None: + request_headers["Origin"] = origin + + key = build_request(request_headers) + + if available_extensions is not None: + extensions_header = build_extension( + [ + (extension_factory.name, extension_factory.get_request_params()) + for extension_factory in available_extensions + ] + ) + request_headers["Sec-WebSocket-Extensions"] = extensions_header + + if available_subprotocols is not None: + protocol_header = build_subprotocol(available_subprotocols) + request_headers["Sec-WebSocket-Protocol"] = protocol_header + + if self.extra_headers is not None: + request_headers.update(self.extra_headers) + + if self.user_agent_header: + request_headers.setdefault("User-Agent", self.user_agent_header) + + self.write_http_request(wsuri.resource_name, request_headers) + + status_code, response_headers = await self.read_http_response() + if status_code in (301, 302, 303, 307, 308): + if "Location" not in response_headers: + raise InvalidHeader("Location") + raise RedirectHandshake(response_headers["Location"]) + elif status_code != 101: + raise InvalidStatusCode(status_code, response_headers) + + check_response(response_headers, key) + + self.extensions = self.process_extensions( + response_headers, available_extensions + ) + + self.subprotocol = self.process_subprotocol( + response_headers, available_subprotocols + ) + + self.connection_open() + + +class Connect: + """ + Connect to the WebSocket server at ``uri``. + + Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which + can then be used to send and receive messages. + + :func:`connect` can be used as a asynchronous context manager:: + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + The connection is closed automatically after each iteration of the loop. + + If an error occurs while establishing the connection, :func:`connect` + retries with exponential backoff. The backoff delay starts at three + seconds and increases up to one minute. + + If an error occurs in the body of the loop, you can handle the exception + and :func:`connect` will reconnect with the next iteration; or you can + let the exception bubble up and break out of the loop. This lets you + decide which errors trigger a reconnection and which errors are fatal. + + Args: + uri: URI of the WebSocket server. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketClientProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS + settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't + provided, a TLS context is created + with :func:`~ssl.create_default_context`. + + * You can set ``host`` and ``port`` to connect to a different host and + port from those found in ``uri``. This only changes the destination of + the TCP connection. The host name from ``uri`` is still used in the TLS + handshake for secure connections and in the ``Host`` header. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + ~asyncio.TimeoutError: If the opening handshake times out. + + """ + + MAX_REDIRECTS_ALLOWED = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + def __init__( + self, + uri: str, + *, + create_protocol: Callable[..., WebSocketClientProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketClientProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketClientProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + wsuri = parse_uri(uri) + if wsuri.secure: + kwargs.setdefault("ssl", True) + elif kwargs.get("ssl") is not None: + raise ValueError( + "connect() received a ssl argument for a ws:// URI, " + "use a wss:// URI to enable TLS" + ) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketClientProtocol] | + # Callable[..., WebSocketClientProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketClientProtocol], create_protocol) + factory = functools.partial( + create_protocol, + logger=logger, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + user_agent_header=user_agent_header, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + host=wsuri.host, + port=wsuri.port, + secure=wsuri.secure, + legacy_recv=legacy_recv, + loop=_loop, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + create_connection = functools.partial( + loop.create_unix_connection, factory, path, **kwargs + ) + else: + host: str | None + port: int | None + if kwargs.get("sock") is None: + host, port = wsuri.host, wsuri.port + else: + # If sock is given, host and port shouldn't be specified. + host, port = None, None + if kwargs.get("ssl"): + kwargs.setdefault("server_hostname", wsuri.host) + # If host and port are given, override values from the URI. + host = kwargs.pop("host", host) + port = kwargs.pop("port", port) + create_connection = functools.partial( + loop.create_connection, factory, host, port, **kwargs + ) + + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.client") + self.logger = logger + + # This is a coroutine function. + self._create_connection = create_connection + self._uri = uri + self._wsuri = wsuri + + def handle_redirect(self, uri: str) -> None: + # Update the state of this instance to connect to a new URI. + old_uri = self._uri + old_wsuri = self._wsuri + new_uri = urllib.parse.urljoin(old_uri, uri) + new_wsuri = parse_uri(new_uri) + + # Forbid TLS downgrade. + if old_wsuri.secure and not new_wsuri.secure: + raise SecurityError("redirect from WSS to WS") + + same_origin = ( + old_wsuri.secure == new_wsuri.secure + and old_wsuri.host == new_wsuri.host + and old_wsuri.port == new_wsuri.port + ) + + # Rewrite secure, host, and port for cross-origin redirects. + # This preserves connection overrides with the host and port + # arguments if the redirect points to the same host and port. + if not same_origin: + factory = self._create_connection.args[0] + # Support TLS upgrade. + if not old_wsuri.secure and new_wsuri.secure: + factory.keywords["secure"] = True + self._create_connection.keywords.setdefault("ssl", True) + # Replace secure, host, and port arguments of the protocol factory. + factory = functools.partial( + factory.func, + *factory.args, + **dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port), + ) + # Replace secure, host, and port arguments of create_connection. + self._create_connection = functools.partial( + self._create_connection.func, + *(factory, new_wsuri.host, new_wsuri.port), + **self._create_connection.keywords, + ) + + # Set the new WebSocket URI. This suffices for same-origin redirects. + self._uri = new_uri + self._wsuri = new_wsuri + + # async for ... in connect(...): + + BACKOFF_INITIAL = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5")) + BACKOFF_MIN = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1")) + BACKOFF_MAX = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0")) + BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618")) + + async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]: + backoff_delay = self.BACKOFF_MIN / self.BACKOFF_FACTOR + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Add a random initial delay between 0 and 5 seconds. + # See 7.2.3. Recovering from Abnormal Closure in RFC 6455. + if backoff_delay == self.BACKOFF_MIN: + initial_delay = random.random() * self.BACKOFF_INITIAL + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + initial_delay, + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(initial_delay) + else: + self.logger.info( + "connect failed again; retrying in %d seconds: %s", + int(backoff_delay), + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(int(backoff_delay)) + # Increase delay with truncated exponential backoff. + backoff_delay = backoff_delay * self.BACKOFF_FACTOR + backoff_delay = min(backoff_delay, self.BACKOFF_MAX) + continue + else: + # Connection succeeded - reset backoff delay + backoff_delay = self.BACKOFF_MIN + + # async with connect(...) as ...: + + async def __aenter__(self) -> WebSocketClientProtocol: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.protocol.close() + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketClientProtocol: + async with asyncio_timeout(self.open_timeout): + for _redirects in range(self.MAX_REDIRECTS_ALLOWED): + _transport, protocol = await self._create_connection() + try: + await protocol.handshake( + self._wsuri, + origin=protocol.origin, + available_extensions=protocol.available_extensions, + available_subprotocols=protocol.available_subprotocols, + extra_headers=protocol.extra_headers, + ) + except RedirectHandshake as exc: + protocol.fail_connection() + await protocol.wait_closed() + self.handle_redirect(exc.uri) + # Avoid leaking a connected socket when the handshake fails. + except (Exception, asyncio.CancelledError): + protocol.fail_connection() + await protocol.wait_closed() + raise + else: + self.protocol = protocol + return protocol + else: + raise SecurityError("too many redirects") + + # ... = yield from connect(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +connect = Connect + + +def unix_connect( + path: str | None = None, + uri: str = "ws://localhost/", + **kwargs: Any, +) -> Connect: + """ + Similar to :func:`connect`, but for connecting to a Unix socket. + + This function builds upon the event loop's + :meth:`~asyncio.loop.create_unix_connection` method. + + It is only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server; the host is used in the TLS + handshake for secure connections and in the ``Host`` header. + + """ + return connect(uri=uri, path=path, unix=True, **kwargs) diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/exceptions.py b/venv/lib/python3.12/site-packages/websockets/legacy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..29a2525b4e73b788f773682ce0b88e13eafc6e26 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/exceptions.py @@ -0,0 +1,71 @@ +import http + +from .. import datastructures +from ..exceptions import ( + InvalidHandshake, + # InvalidMessage was incorrectly moved here in versions 14.0 and 14.1. + InvalidMessage, # noqa: F401 + ProtocolError as WebSocketProtocolError, # noqa: F401 +) +from ..typing import StatusLike + + +class InvalidStatusCode(InvalidHandshake): + """ + Raised when a handshake response status code is invalid. + + """ + + def __init__(self, status_code: int, headers: datastructures.Headers) -> None: + self.status_code = status_code + self.headers = headers + + def __str__(self) -> str: + return f"server rejected WebSocket connection: HTTP {self.status_code}" + + +class AbortHandshake(InvalidHandshake): + """ + Raised to abort the handshake on purpose and return an HTTP response. + + This exception is an implementation detail. + + The public API is + :meth:`~websockets.legacy.server.WebSocketServerProtocol.process_request`. + + Attributes: + status (~http.HTTPStatus): HTTP status code. + headers (Headers): HTTP response headers. + body (bytes): HTTP response body. + """ + + def __init__( + self, + status: StatusLike, + headers: datastructures.HeadersLike, + body: bytes = b"", + ) -> None: + # If a user passes an int instead of an HTTPStatus, fix it automatically. + self.status = http.HTTPStatus(status) + self.headers = datastructures.Headers(headers) + self.body = body + + def __str__(self) -> str: + return ( + f"HTTP {self.status:d}, {len(self.headers)} headers, {len(self.body)} bytes" + ) + + +class RedirectHandshake(InvalidHandshake): + """ + Raised when a handshake gets redirected. + + This exception is an implementation detail. + + """ + + def __init__(self, uri: str) -> None: + self.uri = uri + + def __str__(self) -> str: + return f"redirect to {self.uri}" diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/framing.py b/venv/lib/python3.12/site-packages/websockets/legacy/framing.py new file mode 100644 index 0000000000000000000000000000000000000000..452d2fb34dc45577401321ce76d6a030d2e49597 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/framing.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import struct +from collections.abc import Awaitable, Sequence +from typing import Any, Callable, NamedTuple + +from .. import extensions, frames +from ..exceptions import PayloadTooBig, ProtocolError +from ..typing import BytesLike, DataLike + + +try: + from ..speedups import apply_mask +except ImportError: + from ..utils import apply_mask + + +class Frame(NamedTuple): + fin: bool + opcode: frames.Opcode + data: BytesLike + rsv1: bool = False + rsv2: bool = False + rsv3: bool = False + + @property + def new_frame(self) -> frames.Frame: + return frames.Frame( + self.opcode, + self.data, + self.fin, + self.rsv1, + self.rsv2, + self.rsv3, + ) + + def __str__(self) -> str: + return str(self.new_frame) + + def check(self) -> None: + return self.new_frame.check() + + @classmethod + async def read( + cls, + reader: Callable[[int], Awaitable[bytes]], + *, + mask: bool, + max_size: int | None = None, + extensions: Sequence[extensions.Extension] | None = None, + ) -> Frame: + """ + Read a WebSocket frame. + + Args: + reader: Coroutine that reads exactly the requested number of + bytes, unless the end of file is reached. + mask: Whether the frame should be masked i.e. whether the read + happens on the server side. + max_size: Maximum payload size in bytes. + extensions: List of extensions, applied in reverse order. + + Raises: + PayloadTooBig: If the frame exceeds ``max_size``. + ProtocolError: If the frame contains incorrect values. + + """ + + # Read the header. + data = await reader(2) + head1, head2 = struct.unpack("!BB", data) + + # While not Pythonic, this is marginally faster than calling bool(). + fin = True if head1 & 0b10000000 else False + rsv1 = True if head1 & 0b01000000 else False + rsv2 = True if head1 & 0b00100000 else False + rsv3 = True if head1 & 0b00010000 else False + + try: + opcode = frames.Opcode(head1 & 0b00001111) + except ValueError as exc: + raise ProtocolError("invalid opcode") from exc + + if (True if head2 & 0b10000000 else False) != mask: + raise ProtocolError("incorrect masking") + + length = head2 & 0b01111111 + if length == 126: + data = await reader(2) + (length,) = struct.unpack("!H", data) + elif length == 127: + data = await reader(8) + (length,) = struct.unpack("!Q", data) + if max_size is not None and length > max_size: + raise PayloadTooBig(length, max_size) + if mask: + mask_bits = await reader(4) + + # Read the data. + data = await reader(length) + if mask: + data = apply_mask(data, mask_bits) + + new_frame = frames.Frame(opcode, data, fin, rsv1, rsv2, rsv3) + + if extensions is None: + extensions = [] + for extension in reversed(extensions): + new_frame = extension.decode(new_frame, max_size=max_size) + + new_frame.check() + + return cls( + new_frame.fin, + new_frame.opcode, + new_frame.data, + new_frame.rsv1, + new_frame.rsv2, + new_frame.rsv3, + ) + + def write( + self, + write: Callable[[bytes], Any], + *, + mask: bool, + extensions: Sequence[extensions.Extension] | None = None, + ) -> None: + """ + Write a WebSocket frame. + + Args: + frame: Frame to write. + write: Function that writes bytes. + mask: Whether the frame should be masked i.e. whether the write + happens on the client side. + extensions: List of extensions, applied in order. + + Raises: + ProtocolError: If the frame contains incorrect values. + + """ + # The frame is written in a single call to write in order to prevent + # TCP fragmentation. See #68 for details. This also makes it safe to + # send frames concurrently from multiple coroutines. + write(self.new_frame.serialize(mask=mask, extensions=extensions)) + + +def prepare_data(data: DataLike) -> tuple[int, BytesLike]: + """ + Convert a string or byte-like object to an opcode and a bytes-like object. + + This function is designed for data frames. + + If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes` + object encoding ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return ``OP_BINARY`` and a bytes-like + object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return frames.Opcode.TEXT, data.encode() + elif isinstance(data, BytesLike): + return frames.Opcode.BINARY, data + else: + raise TypeError("data must be str or bytes-like") + + +def prepare_ctrl(data: DataLike) -> bytes: + """ + Convert a string or byte-like object to bytes. + + This function is designed for ping and pong frames. + + If ``data`` is a :class:`str`, return a :class:`bytes` object encoding + ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return a :class:`bytes` object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return data.encode() + elif isinstance(data, BytesLike): + return bytes(data) + else: + raise TypeError("data must be str or bytes-like") + + +# Backwards compatibility with previously documented public APIs +encode_data = prepare_ctrl + +# Backwards compatibility with previously documented public APIs +from ..frames import Close # noqa: E402 F401, I001 + + +def parse_close(data: bytes) -> tuple[int, str]: + """ + Parse the payload from a close frame. + + Returns: + Close code and reason. + + Raises: + ProtocolError: If data is ill-formed. + UnicodeDecodeError: If the reason isn't valid UTF-8. + + """ + close = Close.parse(data) + return close.code, close.reason + + +def serialize_close(code: int, reason: str) -> bytes: + """ + Serialize the payload for a close frame. + + """ + return Close(code, reason).serialize() diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/handshake.py b/venv/lib/python3.12/site-packages/websockets/legacy/handshake.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7157c010720733ca42d363cd810c354bf9d221 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/handshake.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import base64 +import binascii + +from ..datastructures import Headers, MultipleValuesError +from ..exceptions import InvalidHeader, InvalidHeaderValue, InvalidUpgrade +from ..headers import parse_connection, parse_upgrade +from ..typing import ConnectionOption, UpgradeProtocol +from ..utils import accept_key as accept, generate_key + + +__all__ = ["build_request", "check_request", "build_response", "check_response"] + + +def build_request(headers: Headers) -> str: + """ + Build a handshake request to send to the server. + + Update request headers passed in argument. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`check_response`. + + """ + key = generate_key() + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Key"] = key + headers["Sec-WebSocket-Version"] = "13" + return key + + +def check_request(headers: Headers) -> str: + """ + Check a handshake request received from the client. + + This function doesn't verify that the request is an HTTP/1.1 or higher GET + request and doesn't perform ``Host`` and ``Origin`` checks. These controls + are usually performed earlier in the HTTP request handling code. They're + the responsibility of the caller. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`build_response`. + + Raises: + InvalidHandshake: If the handshake request is invalid. + Then, the server must return a 400 Bad Request error. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", ", ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_key = headers["Sec-WebSocket-Key"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Key") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from exc + + try: + raw_key = base64.b64decode(s_w_key.encode(), validate=True) + except binascii.Error as exc: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) from exc + if len(raw_key) != 16: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) + + try: + s_w_version = headers["Sec-WebSocket-Version"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Version") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from exc + + if s_w_version != "13": + raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version) + + return s_w_key + + +def build_response(headers: Headers, key: str) -> None: + """ + Build a handshake response to send to the client. + + Update response headers passed in argument. + + Args: + headers: Handshake response headers. + key: Returned by :func:`check_request`. + + """ + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Accept"] = accept(key) + + +def check_response(headers: Headers, key: str) -> None: + """ + Check a handshake response received from the server. + + This function doesn't verify that the response is an HTTP/1.1 or higher + response with a 101 status code. These controls are the responsibility of + the caller. + + Args: + headers: Handshake response headers. + key: Returned by :func:`build_request`. + + Raises: + InvalidHandshake: If the handshake response is invalid. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", " ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_accept = headers["Sec-WebSocket-Accept"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Accept") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from exc + + if s_w_accept != accept(key): + raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept) diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/http.py b/venv/lib/python3.12/site-packages/websockets/legacy/http.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c8a927e177d36f6a54bcc293dc853e2e15e736 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/http.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import asyncio +import os +import re + +from ..datastructures import Headers +from ..exceptions import SecurityError + + +__all__ = ["read_request", "read_response"] + +MAX_NUM_HEADERS = int(os.environ.get("WEBSOCKETS_MAX_NUM_HEADERS", "128")) +MAX_LINE_LENGTH = int(os.environ.get("WEBSOCKETS_MAX_LINE_LENGTH", "8192")) + + +def d(value: bytes) -> str: + """ + Decode a bytestring for interpolating into an error message. + + """ + return value.decode(errors="backslashreplace") + + +# See https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + +# Regex for validating header names. + +_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + +# Regex for validating header values. + +# We don't attempt to support obsolete line folding. + +# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff). + +# The ABNF is complicated because it attempts to express that optional +# whitespace is ignored. We strip whitespace and don't revalidate that. + +# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 + +_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*") + + +async def read_request(stream: asyncio.StreamReader) -> tuple[str, Headers]: + """ + Read an HTTP/1.1 GET request and return ``(path, headers)``. + + ``path`` isn't URL-decoded or validated in any way. + + ``path`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the request body because + WebSocket handshake requests don't have one. If the request contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the request from. + + Raises: + EOFError: If the connection is closed without a full HTTP request. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1 + + # Parsing is simple because fixed values are expected for method and + # version and because path isn't checked. Since WebSocket software tends + # to implement HTTP/1.1 strictly, there's little need for lenient parsing. + + try: + request_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP request line") from exc + + try: + method, raw_path, version = request_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None + + if method != b"GET": + raise ValueError(f"unsupported HTTP method: {d(method)}") + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + path = raw_path.decode("ascii", "surrogateescape") + + headers = await read_headers(stream) + + return path, headers + + +async def read_response(stream: asyncio.StreamReader) -> tuple[int, str, Headers]: + """ + Read an HTTP/1.1 response and return ``(status_code, reason, headers)``. + + ``reason`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the response body because + WebSocket handshake responses don't have one. If the response contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the response from. + + Raises: + EOFError: If the connection is closed without a full HTTP response. + SecurityError: If the response exceeds a security limit. + ValueError: If the response isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + + # As in read_request, parsing is simple because a fixed value is expected + # for version, status_code is a 3-digit number, and reason can be ignored. + + try: + status_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP status line") from exc + + try: + version, raw_status_code, raw_reason = status_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None + + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + try: + status_code = int(raw_status_code) + except ValueError: # invalid literal for int() with base 10 + raise ValueError(f"invalid HTTP status code: {d(raw_status_code)}") from None + if not 100 <= status_code < 1000: + raise ValueError(f"unsupported HTTP status code: {d(raw_status_code)}") + if not _value_re.fullmatch(raw_reason): + raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}") + reason = raw_reason.decode() + + headers = await read_headers(stream) + + return status_code, reason, headers + + +async def read_headers(stream: asyncio.StreamReader) -> Headers: + """ + Read HTTP headers from ``stream``. + + Non-ASCII characters are represented with surrogate escapes. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + + # We don't attempt to support obsolete line folding. + + headers = Headers() + for _ in range(MAX_NUM_HEADERS + 1): + try: + line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP headers") from exc + if line == b"": + break + + try: + raw_name, raw_value = line.split(b":", 1) + except ValueError: # not enough values to unpack (expected 2, got 1) + raise ValueError(f"invalid HTTP header line: {d(line)}") from None + if not _token_re.fullmatch(raw_name): + raise ValueError(f"invalid HTTP header name: {d(raw_name)}") + raw_value = raw_value.strip(b" \t") + if not _value_re.fullmatch(raw_value): + raise ValueError(f"invalid HTTP header value: {d(raw_value)}") + + name = raw_name.decode("ascii") # guaranteed to be ASCII at this point + value = raw_value.decode("ascii", "surrogateescape") + headers[name] = value + + else: + raise SecurityError("too many HTTP headers") + + return headers + + +async def read_line(stream: asyncio.StreamReader) -> bytes: + """ + Read a single line from ``stream``. + + CRLF is stripped from the return value. + + """ + # Security: this is bounded by the StreamReader's limit (default = 32 KiB). + line = await stream.readline() + # Security: this guarantees header values are small (hard-coded = 8 KiB) + if len(line) > MAX_LINE_LENGTH: + raise SecurityError("line too long") + # Not mandatory but safe - https://datatracker.ietf.org/doc/html/rfc7230#section-3.5 + if not line.endswith(b"\r\n"): + raise EOFError("line without CRLF") + return line[:-2] diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/protocol.py b/venv/lib/python3.12/site-packages/websockets/legacy/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4ec6bcec9ee886a97815239376dff0d166d8f9 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/protocol.py @@ -0,0 +1,1635 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +import logging +import random +import ssl +import struct +import sys +import time +import traceback +import uuid +import warnings +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from typing import Any, Callable, Deque, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers +from ..exceptions import ( + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + InvalidState, + PayloadTooBig, + ProtocolError, +) +from ..extensions import Extension +from ..frames import ( + OK_CLOSE_CODES, + OP_BINARY, + OP_CLOSE, + OP_CONT, + OP_PING, + OP_PONG, + OP_TEXT, + Close, + CloseCode, + Opcode, +) +from ..protocol import State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .framing import Frame, prepare_ctrl, prepare_data + + +__all__ = ["WebSocketCommonProtocol"] + + +# In order to ensure consistency, the code always checks the current value of +# WebSocketCommonProtocol.state before assigning a new value and never yields +# between the check and the assignment. + + +class WebSocketCommonProtocol(asyncio.Protocol): + """ + WebSocket connection. + + :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket + servers and clients. You shouldn't use it directly. Instead, use + :class:`~websockets.legacy.client.WebSocketClientProtocol` or + :class:`~websockets.legacy.server.WebSocketServerProtocol`. + + This documentation focuses on low-level details that aren't covered in the + documentation of :class:`~websockets.legacy.client.WebSocketClientProtocol` + and :class:`~websockets.legacy.server.WebSocketServerProtocol` for the sake + of simplicity. + + Once the connection is open, a Ping_ frame is sent every ``ping_interval`` + seconds. This serves as a keepalive. It helps keeping the connection open, + especially in the presence of proxies with short timeouts on inactive + connections. Set ``ping_interval`` to :obj:`None` to disable this behavior. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + If the corresponding Pong_ frame isn't received within ``ping_timeout`` + seconds, the connection is considered unusable and is closed with code 1011. + This ensures that the remote endpoint remains responsive. Set + ``ping_timeout`` to :obj:`None` to disable this behavior. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + See the discussion of :doc:`keepalive <../../topics/keepalive>` for details. + + The ``close_timeout`` parameter defines a maximum wait time for completing + the closing handshake and terminating the TCP connection. For legacy + reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds + for clients and ``4 * close_timeout`` for servers. + + ``close_timeout`` is a parameter of the protocol because websockets usually + calls :meth:`close` implicitly upon exit: + + * on the client side, when using :func:`~websockets.legacy.client.connect` + as a context manager; + * on the server side, when the connection handler terminates. + + To apply a timeout to any other API, wrap it in :func:`~asyncio.timeout` or + :func:`~asyncio.wait_for`. + + The ``max_size`` parameter enforces the maximum size for incoming messages + in bytes. The default value is 1 MiB. If a larger message is received, + :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError` + and the connection will be closed with code 1009. + + The ``max_queue`` parameter sets the maximum length of the queue that + holds incoming messages. The default value is ``32``. Messages are added + to an in-memory queue when they're received; then :meth:`recv` pops from + that queue. In order to prevent excessive memory consumption when + messages are received faster than they can be processed, the queue must + be bounded. If the queue fills up, the protocol stops processing incoming + data until :meth:`recv` is called. In this situation, various receive + buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the + TCP receive window will shrink, slowing down transmission to avoid packet + loss. + + Since Python can use up to 4 bytes of memory to represent a single + character, each connection may use up to ``4 * max_size * max_queue`` + bytes of memory to store incoming messages. By default, this is 128 MiB. + You may want to lower the limits, depending on your application's + requirements. + + The ``read_limit`` argument sets the high-water limit of the buffer for + incoming bytes. The low-water limit is half the high-water limit. The + default value is 64 KiB, half of asyncio's default (based on the current + implementation of :class:`~asyncio.StreamReader`). + + The ``write_limit`` argument sets the high-water limit of the buffer for + outgoing bytes. The low-water limit is a quarter of the high-water limit. + The default value is 64 KiB, equal to asyncio's default (based on the + current implementation of ``FlowControlMixin``). + + See the discussion of :doc:`memory usage <../../topics/memory>` for details. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.protocol")``. + See the :doc:`logging guide <../../topics/logging>` for details. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + For legacy reasons, the actual timeout is 4 or 5 times larger. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: Maximum number of incoming messages in receive buffer. + :obj:`None` disables the limit. + read_limit: High-water mark of read buffer in bytes. + write_limit: High-water mark of write buffer in bytes. + + """ + + # There are only two differences between the client-side and server-side + # behavior: masking the payload and closing the underlying TCP connection. + # Set is_client = True/False and side = "client"/"server" to pick a side. + is_client: bool + side: str = "undefined" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + # The following arguments are kept only for backwards compatibility. + host: str | None = None, + port: int | None = None, + secure: bool | None = None, + legacy_recv: bool = False, + loop: asyncio.AbstractEventLoop | None = None, + timeout: float | None = None, + ) -> None: + if legacy_recv: # pragma: no cover + warnings.warn("legacy_recv is deprecated", DeprecationWarning) + + # Backwards compatibility: close_timeout used to be called timeout. + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: the loop parameter used to be supported. + if loop is None: + loop = asyncio.get_event_loop() + else: + warnings.warn("remove loop argument", DeprecationWarning) + + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + self.max_size = max_size + self.max_queue = max_queue + self.read_limit = read_limit + self.write_limit = write_limit + + # Unique identifier. For logs. + self.id: uuid.UUID = uuid.uuid4() + """Unique identifier of the connection. Useful in logs.""" + + # Logger or LoggerAdapter for this connection. + if logger is None: + logger = logging.getLogger("websockets.protocol") + self.logger: LoggerLike = logging.LoggerAdapter(logger, {"websocket": self}) + """Logger for this connection.""" + + # Track if DEBUG is enabled. Shortcut logging calls if it isn't. + self.debug = logger.isEnabledFor(logging.DEBUG) + + self.loop = loop + + self._host = host + self._port = port + self._secure = secure + self.legacy_recv = legacy_recv + + # Configure read buffer limits. The high-water limit is defined by + # ``self.read_limit``. The ``limit`` argument controls the line length + # limit and half the buffer limit of :class:`~asyncio.StreamReader`. + # That's why it must be set to half of ``self.read_limit``. + self.reader = asyncio.StreamReader(limit=read_limit // 2, loop=loop) + + # Copied from asyncio.FlowControlMixin + self._paused = False + self._drain_waiter: asyncio.Future[None] | None = None + + # This class implements the data transfer and closing handshake, which + # are shared between the client-side and the server-side. + # Subclasses implement the opening handshake and, on success, execute + # :meth:`connection_open` to change the state to OPEN. + self.state = State.CONNECTING + if self.debug: + self.logger.debug("= connection is CONNECTING") + + # HTTP protocol parameters. + self.path: str + """Path of the opening handshake request.""" + self.request_headers: Headers + """Opening handshake request headers.""" + self.response_headers: Headers + """Opening handshake response headers.""" + + # WebSocket protocol parameters. + self.extensions: list[Extension] = [] + self.subprotocol: Subprotocol | None = None + """Subprotocol, if one was negotiated.""" + + # Close code and reason, set when a close frame is sent or received. + self.close_rcvd: Close | None = None + self.close_sent: Close | None = None + self.close_rcvd_then_sent: bool | None = None + + # Completed when the connection state becomes CLOSED. Translates the + # :meth:`connection_lost` callback to a :class:`~asyncio.Future` + # that can be awaited. (Other :class:`~asyncio.Protocol` callbacks are + # translated by ``self.stream_reader``). + self.connection_lost_waiter: asyncio.Future[None] = loop.create_future() + + # Queue of received messages. + self.messages: Deque[Data] = collections.deque() + self._pop_message_waiter: asyncio.Future[None] | None = None + self._put_message_waiter: asyncio.Future[None] | None = None + + # Protect sending fragmented messages. + self._fragmented_message_waiter: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pings: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task running the data transfer. + self.transfer_data_task: asyncio.Task[None] + + # Exception that occurred during data transfer, if any. + self.transfer_data_exc: BaseException | None = None + + # Task sending keepalive pings. + self.keepalive_ping_task: asyncio.Task[None] + + # Task closing the TCP connection. + self.close_connection_task: asyncio.Task[None] + + # Copied from asyncio.FlowControlMixin + async def _drain_helper(self) -> None: # pragma: no cover + if self.connection_lost_waiter.done(): + raise ConnectionResetError("Connection lost") + if not self._paused: + return + waiter = self._drain_waiter + assert waiter is None or waiter.cancelled() + waiter = self.loop.create_future() + self._drain_waiter = waiter + await waiter + + # Copied from asyncio.StreamWriter + async def _drain(self) -> None: # pragma: no cover + if self.reader is not None: + exc = self.reader.exception() + if exc is not None: + raise exc + if self.transport is not None: + if self.transport.is_closing(): + # Yield to the event loop so connection_lost() may be + # called. Without this, _drain_helper() would return + # immediately, and code that calls + # write(...); yield from drain() + # in a loop would never call connection_lost(), so it + # would not see an error when the socket is closed. + await asyncio.sleep(0) + await self._drain_helper() + + def connection_open(self) -> None: + """ + Callback when the WebSocket opening handshake completes. + + Enter the OPEN state and start the data transfer phase. + + """ + # 4.1. The WebSocket Connection is Established. + assert self.state is State.CONNECTING + self.state = State.OPEN + if self.debug: + self.logger.debug("= connection is OPEN") + # Start the task that receives incoming WebSocket messages. + self.transfer_data_task = self.loop.create_task(self.transfer_data()) + # Start the task that sends pings at regular intervals. + self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping()) + # Start the task that eventually closes the TCP connection. + self.close_connection_task = self.loop.create_task(self.close_connection()) + + @property + def host(self) -> str | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[0] instead of host", DeprecationWarning) + return self._host + + @property + def port(self) -> int | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[1] instead of port", DeprecationWarning) + return self._port + + @property + def secure(self) -> bool | None: + warnings.warn("don't use secure", DeprecationWarning) + return self._secure + + # Public API + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getsockname`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getpeername`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("peername") + + @property + def open(self) -> bool: + """ + :obj:`True` when the connection is open; :obj:`False` otherwise. + + This attribute may be used to detect disconnections. However, this + approach is discouraged per the EAFP_ principle. Instead, you should + handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp + + """ + return self.state is State.OPEN and not self.transfer_data_task.done() + + @property + def closed(self) -> bool: + """ + :obj:`True` when the connection is closed; :obj:`False` otherwise. + + Be aware that both :attr:`open` and :attr:`closed` are :obj:`False` + during the opening and closing sequences. + + """ + return self.state is State.CLOSED + + @property + def close_code(self) -> int | None: + """ + WebSocket close code, defined in `section 7.1.5 of RFC 6455`_. + + .. _section 7.1.5 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return CloseCode.ABNORMAL_CLOSURE + else: + return self.close_rcvd.code + + @property + def close_reason(self) -> str | None: + """ + WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_. + + .. _section 7.1.6 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return "" + else: + return self.close_rcvd.reason + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator exits normally when the connection is closed with the close + code 1000 (OK) or 1001 (going away) or without a close code. + + It raises a :exc:`~websockets.exceptions.ConnectionClosedError` + exception when the connection is closed with any other code. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + async def recv(self) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing the next + message. The next invocation of :meth:`recv` will return it. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + Returns: + A string (:class:`str`) for a Text_ frame. A bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If two coroutines call :meth:`recv` concurrently. + + """ + if self._pop_message_waiter is not None: + raise RuntimeError( + "cannot call recv while another coroutine " + "is already waiting for the next message" + ) + + # Don't await self.ensure_open() here: + # - messages could be available in the queue even if the connection + # is closed; + # - messages could be received before the closing frame even if the + # connection is closing. + + # Wait until there's a message in the queue (if necessary) or the + # connection is closed. + while len(self.messages) <= 0: + pop_message_waiter: asyncio.Future[None] = self.loop.create_future() + self._pop_message_waiter = pop_message_waiter + try: + # If asyncio.wait() is canceled, it doesn't cancel + # pop_message_waiter and self.transfer_data_task. + await asyncio.wait( + [pop_message_waiter, self.transfer_data_task], + return_when=asyncio.FIRST_COMPLETED, + ) + finally: + self._pop_message_waiter = None + + # If asyncio.wait(...) exited because self.transfer_data_task + # completed before receiving a new message, raise a suitable + # exception (or return None if legacy_recv is enabled). + if not pop_message_waiter.done(): + if self.legacy_recv: + return None # type: ignore + else: + # Wait until the connection is closed to raise + # ConnectionClosed with the correct code and reason. + await self.ensure_open() + + # Pop a message from the queue. + message = self.messages.popleft() + + # Notify transfer_data(). + if self._put_message_waiter is not None: + self._put_message_waiter.set_result(None) + self._put_message_waiter = None + + return message + + async def send( + self, + message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike], + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :meth:`send` also accepts an iterable or an asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you want to send the keys of a dict-like object as fragments, call + its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and is + more clear: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + await self.ensure_open() + + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self._fragmented_message_waiter is not None: + await asyncio.shield(self._fragmented_message_waiter) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, (str, bytes, bytearray, memoryview)): + opcode, data = prepare_data(message) + await self.write_frame(True, opcode, data) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + iter_message = iter(message) + try: + fragment = next(iter_message) + except StopIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + for fragment in iter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + # Fragmented message -- asynchronous iterator + + elif isinstance(message, AsyncIterable): + # Implement aiter_message = aiter(message) without aiter + # Work around https://github.com/python/mypy/issues/5738 + aiter_message = cast( + Callable[[AsyncIterable[DataLike]], AsyncIterator[DataLike]], + type(message).__aiter__, + )(message) + try: + # Implement fragment = anext(aiter_message) without anext + # Work around https://github.com/python/mypy/issues/5738 + fragment = await cast( + Callable[[AsyncIterator[DataLike]], Awaitable[DataLike]], + type(aiter_message).__anext__, + )(aiter_message) + except StopAsyncIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + async for fragment in aiter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + else: + raise TypeError("data must be str, bytes-like, or iterable") + + async def close( + self, + code: int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. As a consequence, there's no need + to await :meth:`wait_closed` after :meth:`close`. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given + that errors during connection termination aren't particularly useful. + + Canceling :meth:`close` is discouraged. If it takes too long, you can + set a shorter ``close_timeout``. If you don't want to wait, let the + Python process exit, then the OS will take care of closing the TCP + connection. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + async with asyncio_timeout(self.close_timeout): + await self.write_close_frame(Close(code, reason)) + except asyncio.TimeoutError: + # If the close frame cannot be sent because the send buffers + # are full, the closing handshake won't complete anyway. + # Fail the connection to shut down faster. + self.fail_connection() + + # If no close frame is received within the timeout, asyncio_timeout() + # cancels the data transfer task and raises TimeoutError. + + # If close() is called multiple times concurrently and one of these + # calls hits the timeout, the data transfer task will be canceled. + # Other calls will receive a CancelledError here. + + try: + # If close() is canceled during the wait, self.transfer_data_task + # is canceled before the timeout elapses. + async with asyncio_timeout(self.close_timeout): + await self.transfer_data_task + except (asyncio.TimeoutError, asyncio.CancelledError): + pass + + # Wait for the close connection task to close the TCP connection. + await asyncio.shield(self.close_connection_task) + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + This coroutine is identical to the :attr:`closed` attribute, except it + can be awaited. + + This can make it easier to detect connection termination, regardless + of its cause, in tasks that interact with the WebSocket connection. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: DataLike | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive, as a check that the remote endpoint + received all messages up to this point, or to measure :attr:`latency`. + + Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no + effect. + + Args: + data: Payload of the ping. A string will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_waiter = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_waiter + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + await self.ensure_open() + + if data is not None: + data = prepare_ctrl(data) + + # Protect against duplicates if a payload is explicitly set. + if data in self.pings: + raise RuntimeError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_waiter = self.loop.create_future() + # Resolution of time.monotonic() may be too low on Windows. + ping_timestamp = time.perf_counter() + self.pings[data] = (pong_waiter, ping_timestamp) + + await self.write_frame(True, OP_PING, data) + + return asyncio.shield(pong_waiter) + + async def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Args: + data: Payload of the pong. A string will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + await self.ensure_open() + + data = prepare_ctrl(data) + + await self.write_frame(True, OP_PONG, data) + + # Private methods - no guarantees. + + def connection_closed_exc(self) -> ConnectionClosed: + exc: ConnectionClosed + if ( + self.close_rcvd is not None + and self.close_rcvd.code in OK_CLOSE_CODES + and self.close_sent is not None + and self.close_sent.code in OK_CLOSE_CODES + ): + exc = ConnectionClosedOK( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + else: + exc = ConnectionClosedError( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + # Chain to the exception that terminated data transfer, if any. + exc.__cause__ = self.transfer_data_exc + return exc + + async def ensure_open(self) -> None: + """ + Check that the WebSocket connection is open. + + Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. + + """ + # Handle cases from most common to least common for performance. + if self.state is State.OPEN: + # If self.transfer_data_task exited without a closing handshake, + # self.close_connection_task may be closing the connection, going + # straight from OPEN to CLOSED. + if self.transfer_data_task.done(): + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + else: + return + + if self.state is State.CLOSED: + raise self.connection_closed_exc() + + if self.state is State.CLOSING: + # If we started the closing handshake, wait for its completion to + # get the proper close code and reason. self.close_connection_task + # will complete within 4 or 5 * close_timeout after close(). The + # CLOSING state also occurs when failing the connection. In that + # case self.close_connection_task will complete even faster. + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + + # Control may only reach this point in buggy third-party subclasses. + assert self.state is State.CONNECTING + raise InvalidState("WebSocket connection isn't established yet") + + async def transfer_data(self) -> None: + """ + Read incoming messages and put them in a queue. + + This coroutine runs in a task until the closing handshake is started. + + """ + try: + while True: + message = await self.read_message() + + # Exit the loop when receiving a close frame. + if message is None: + break + + # Wait until there's room in the queue (if necessary). + if self.max_queue is not None: + while len(self.messages) >= self.max_queue: + self._put_message_waiter = self.loop.create_future() + try: + await asyncio.shield(self._put_message_waiter) + finally: + self._put_message_waiter = None + + # Put the message in the queue. + self.messages.append(message) + + # Notify recv(). + if self._pop_message_waiter is not None: + self._pop_message_waiter.set_result(None) + self._pop_message_waiter = None + + except asyncio.CancelledError as exc: + self.transfer_data_exc = exc + # If fail_connection() cancels this task, avoid logging the error + # twice and failing the connection again. + raise + + except ProtocolError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.PROTOCOL_ERROR) + + except (ConnectionError, TimeoutError, EOFError, ssl.SSLError) as exc: + # Reading data with self.reader.readexactly may raise: + # - most subclasses of ConnectionError if the TCP connection + # breaks, is reset, or is aborted; + # - TimeoutError if the TCP connection times out; + # - IncompleteReadError, a subclass of EOFError, if fewer + # bytes are available than requested; + # - ssl.SSLError if the other side infringes the TLS protocol. + self.transfer_data_exc = exc + self.fail_connection(CloseCode.ABNORMAL_CLOSURE) + + except UnicodeDecodeError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INVALID_DATA) + + except PayloadTooBig as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.MESSAGE_TOO_BIG) + + except Exception as exc: + # This shouldn't happen often because exceptions expected under + # regular circumstances are handled above. If it does, consider + # catching and handling more exceptions. + self.logger.error("data transfer failed", exc_info=True) + + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INTERNAL_ERROR) + + async def read_message(self) -> Data | None: + """ + Read a single message from the connection. + + Re-assemble data frames if the message is fragmented. + + Return :obj:`None` when the closing handshake is started. + + """ + frame = await self.read_data_frame(max_size=self.max_size) + + # A close frame was received. + if frame is None: + return None + + if frame.opcode == OP_TEXT: + text = True + elif frame.opcode == OP_BINARY: + text = False + else: # frame.opcode == OP_CONT + raise ProtocolError("unexpected opcode") + + # Shortcut for the common case - no fragmentation + if frame.fin: + if isinstance(frame.data, memoryview): + raise AssertionError("only compressed outgoing frames use memoryview") + return frame.data.decode() if text else bytes(frame.data) + + # 5.4. Fragmentation + fragments: list[DataLike] = [] + max_size = self.max_size + if text: + decoder_factory = codecs.getincrementaldecoder("utf-8") + decoder = decoder_factory(errors="strict") + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(decoder.decode(frame.data, frame.fin)) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(decoder.decode(frame.data, frame.fin)) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + else: + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(frame.data) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(frame.data) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + append(frame) + + while not frame.fin: + frame = await self.read_data_frame(max_size=max_size) + if frame is None: + raise ProtocolError("incomplete fragmented message") + if frame.opcode != OP_CONT: + raise ProtocolError("unexpected opcode") + append(frame) + + return ("" if text else b"").join(fragments) + + async def read_data_frame(self, max_size: int | None) -> Frame | None: + """ + Read a single data frame from the connection. + + Process control frames received before the next data frame. + + Return :obj:`None` if a close frame is encountered before any data frame. + + """ + # 6.2. Receiving Data + while True: + frame = await self.read_frame(max_size) + + # 5.5. Control Frames + if frame.opcode == OP_CLOSE: + # 7.1.5. The WebSocket Connection Close Code + # 7.1.6. The WebSocket Connection Close Reason + self.close_rcvd = Close.parse(frame.data) + if self.close_sent is not None: + self.close_rcvd_then_sent = False + try: + # Echo the original data instead of re-serializing it with + # Close.serialize() because that fails when the close frame + # is empty and Close.parse() synthesizes a 1005 close code. + await self.write_close_frame(self.close_rcvd, frame.data) + except ConnectionClosed: + # Connection closed before we could echo the close frame. + pass + return None + + elif frame.opcode == OP_PING: + # Answer pings, unless connection is CLOSING. + if self.state is State.OPEN: + try: + await self.pong(frame.data) + except ConnectionClosed: + # Connection closed while draining write buffer. + pass + + elif frame.opcode == OP_PONG: + if frame.data in self.pings: + pong_timestamp = time.perf_counter() + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_waiter, ping_timestamp) in self.pings.items(): + ping_ids.append(ping_id) + if not pong_waiter.done(): + pong_waiter.set_result(pong_timestamp - ping_timestamp) + if ping_id == frame.data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + # Remove acknowledged pings from self.pings. + for ping_id in ping_ids: + del self.pings[ping_id] + + # 5.6. Data Frames + else: + return frame + + async def read_frame(self, max_size: int | None) -> Frame: + """ + Read a single frame from the connection. + + """ + frame = await Frame.read( + self.reader.readexactly, + mask=not self.is_client, + max_size=max_size, + extensions=self.extensions, + ) + if self.debug: + self.logger.debug("< %s", frame) + return frame + + def write_frame_sync(self, fin: bool, opcode: int, data: BytesLike) -> None: + frame = Frame(fin, Opcode(opcode), data) + if self.debug: + self.logger.debug("> %s", frame) + frame.write( + self.transport.write, + mask=self.is_client, + extensions=self.extensions, + ) + + async def drain(self) -> None: + try: + # Handle flow control automatically. + await self._drain() + except ConnectionError: + # Terminate the connection if the socket died. + self.fail_connection() + # Wait until the connection is closed to raise ConnectionClosed + # with the correct code and reason. + await self.ensure_open() + + async def write_frame( + self, fin: bool, opcode: int, data: BytesLike, *, _state: int = State.OPEN + ) -> None: + # Defensive assertion for protocol compliance. + if self.state is not _state: # pragma: no cover + raise InvalidState( + f"Cannot write to a WebSocket in the {self.state.name} state" + ) + self.write_frame_sync(fin, opcode, data) + await self.drain() + + async def write_close_frame( + self, close: Close, data: BytesLike | None = None + ) -> None: + """ + Write a close frame if and only if the connection state is OPEN. + + This dedicated coroutine must be used for writing close frames to + ensure that at most one close frame is sent on a given connection. + + """ + # Test and set the connection state before sending the close frame to + # avoid sending two frames in case of concurrent calls. + if self.state is State.OPEN: + # 7.1.3. The WebSocket Closing Handshake is Started + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + self.close_sent = close + if self.close_rcvd is not None: + self.close_rcvd_then_sent = True + if data is None: + data = close.serialize() + + # 7.1.2. Start the WebSocket Closing Handshake + await self.write_frame(True, OP_CLOSE, data, _state=State.CLOSING) + + async def keepalive_ping(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + This coroutine exits when the connection terminates and one of the + following happens: + + - :meth:`ping` raises :exc:`ConnectionClosed`, or + - :meth:`close_connection` cancels :attr:`keepalive_ping_task`. + + """ + if self.ping_interval is None: + return + + try: + while True: + await asyncio.sleep(self.ping_interval) + + if self.debug: + self.logger.debug("% sending keepalive ping") + pong_waiter = await self.ping() + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # Raises CancelledError if the connection is closed, + # when close_connection() cancels keepalive_ping(). + # Raises ConnectionClosed if the connection is lost, + # when connection_lost() calls abort_pings(). + await pong_waiter + if self.debug: + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + self.fail_connection( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + + except ConnectionClosed: + pass + + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + async def close_connection(self) -> None: + """ + 7.1.1. Close the WebSocket Connection + + When the opening handshake succeeds, :meth:`connection_open` starts + this coroutine in a task. It waits for the data transfer phase to + complete then it closes the TCP connection cleanly. + + When the opening handshake fails, :meth:`fail_connection` does the + same. There's no data transfer phase in that case. + + """ + try: + # Wait for the data transfer phase to complete. + if hasattr(self, "transfer_data_task"): + try: + await self.transfer_data_task + except asyncio.CancelledError: + pass + + # Cancel the keepalive ping task. + if hasattr(self, "keepalive_ping_task"): + self.keepalive_ping_task.cancel() + + # A client should wait for a TCP close from the server. + if self.is_client and hasattr(self, "transfer_data_task"): + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Half-close the TCP connection if possible (when there's no TLS). + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # "[Errno 107] Transport endpoint is not connected" happens + # but it isn't completely clear under which circumstances. + # uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except (OSError, RuntimeError): # pragma: no cover + pass + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + finally: + # The try/finally ensures that the transport never remains open, + # even if this coroutine is canceled (for example). + await self.close_transport() + + async def close_transport(self) -> None: + """ + Close the TCP connection. + + """ + # If connection_lost() was called, the TCP connection is closed. + # However, if TLS is enabled, the transport still needs closing. + # Else asyncio complains: ResourceWarning: unclosed transport. + if self.connection_lost_waiter.done() and self.transport.is_closing(): + return + + # Close the TCP connection. Buffers are flushed asynchronously. + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Abort the TCP connection. Buffers are discarded. + if self.debug: + self.logger.debug("x aborting TCP connection") + self.transport.abort() + + # connection_lost() is called quickly after aborting. + await self.wait_for_connection_lost() + + async def wait_for_connection_lost(self) -> bool: + """ + Wait until the TCP connection is closed or ``self.close_timeout`` elapses. + + Return :obj:`True` if the connection is closed and :obj:`False` + otherwise. + + """ + if not self.connection_lost_waiter.done(): + try: + async with asyncio_timeout(self.close_timeout): + await asyncio.shield(self.connection_lost_waiter) + except asyncio.TimeoutError: + pass + # Re-check self.connection_lost_waiter.done() synchronously because + # connection_lost() could run between the moment the timeout occurs + # and the moment this coroutine resumes running. + return self.connection_lost_waiter.done() + + def fail_connection( + self, + code: int = CloseCode.ABNORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + 7.1.7. Fail the WebSocket Connection + + This requires: + + 1. Stopping all processing of incoming data, which means canceling + :attr:`transfer_data_task`. The close code will be 1006 unless a + close frame was received earlier. + + 2. Sending a close frame with an appropriate code if the opening + handshake succeeded and the other side is likely to process it. + + 3. Closing the connection. :meth:`close_connection` takes care of + this once :attr:`transfer_data_task` exits after being canceled. + + (The specification describes these steps in the opposite order.) + + """ + if self.debug: + self.logger.debug("! failing connection with code %d", code) + + # Cancel transfer_data_task if the opening handshake succeeded. + # cancel() is idempotent and ignored if the task is done already. + if hasattr(self, "transfer_data_task"): + self.transfer_data_task.cancel() + + # Send a close frame when the state is OPEN (a close frame was already + # sent if it's CLOSING), except when failing the connection because of + # an error reading from or writing to the network. + # Don't send a close frame if the connection is broken. + if code != CloseCode.ABNORMAL_CLOSURE and self.state is State.OPEN: + close = Close(code, reason) + + # Write the close frame without draining the write buffer. + + # Keeping fail_connection() synchronous guarantees it can't + # get stuck and simplifies the implementation of the callers. + # Not drainig the write buffer is acceptable in this context. + + # This duplicates a few lines of code from write_close_frame(). + + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + # If self.close_rcvd was set, the connection state would be + # CLOSING. Therefore self.close_rcvd isn't set and we don't + # have to set self.close_rcvd_then_sent. + assert self.close_rcvd is None + self.close_sent = close + + self.write_frame_sync(True, OP_CLOSE, close.serialize()) + + # Start close_connection_task if the opening handshake didn't succeed. + if not hasattr(self, "close_connection_task"): + self.close_connection_task = self.loop.create_task(self.close_connection()) + + def abort_pings(self) -> None: + """ + Raise ConnectionClosed in pending keepalive pings. + + They'll never receive a pong once the connection is closed. + + """ + assert self.state is State.CLOSED + exc = self.connection_closed_exc() + + for pong_waiter, _ping_timestamp in self.pings.values(): + pong_waiter.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_waiter.cancel() + + # asyncio.Protocol methods + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Configure write buffer limits. + + The high-water limit is defined by ``self.write_limit``. + + The low-water limit currently defaults to ``self.write_limit // 4`` in + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should + be all right for reasonable use cases of this library. + + This is the earliest point where we can get hold of the transport, + which means it's the best point for configuring it. + + """ + transport = cast(asyncio.Transport, transport) + transport.set_write_buffer_limits(self.write_limit) + self.transport = transport + + # Copied from asyncio.StreamReaderProtocol + self.reader.set_transport(transport) + + def connection_lost(self, exc: Exception | None) -> None: + """ + 7.1.4. The WebSocket Connection is Closed. + + """ + self.state = State.CLOSED + if self.debug: + self.logger.debug("= connection is CLOSED") + + self.abort_pings() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + if True: # pragma: no cover + # Copied from asyncio.StreamReaderProtocol + if self.reader is not None: + if exc is None: + self.reader.feed_eof() + else: + self.reader.set_exception(exc) + + # Copied from asyncio.FlowControlMixin + # Wake up the writer if currently paused. + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + return + self._drain_waiter = None + if waiter.done(): + return + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + def pause_writing(self) -> None: # pragma: no cover + assert not self._paused + self._paused = True + + def resume_writing(self) -> None: # pragma: no cover + assert self._paused + self._paused = False + + waiter = self._drain_waiter + if waiter is not None: + self._drain_waiter = None + if not waiter.done(): + waiter.set_result(None) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + + def eof_received(self) -> None: + """ + Close the transport after receiving EOF. + + The WebSocket protocol has its own closing handshake: endpoints close + the TCP or TLS connection after sending and receiving a close frame. + + As a consequence, they never need to write after receiving EOF, so + there's no reason to keep the transport open by returning :obj:`True`. + + Besides, that doesn't work on TLS connections. + + """ + self.reader.feed_eof() + + +# broadcast() is defined in the protocol module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# WebSocketCommonProtocol class. + + +def broadcast( + websockets: Iterable[WebSocketCommonProtocol], + message: DataLike, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.legacy.protocol.WebSocketCommonProtocol.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if not isinstance(message, (str, bytes, bytearray, memoryview)): + raise TypeError("data must be str or bytes-like") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions = [] + + opcode, data = prepare_data(message) + + for websocket in websockets: + if websocket.state is not State.OPEN: + continue + + if websocket._fragmented_message_waiter is not None: + if raise_exceptions: + exception = RuntimeError("sending a fragmented message") + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + websocket.write_frame_sync(True, opcode, data) + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only(write_exception)[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.legacy.server" diff --git a/venv/lib/python3.12/site-packages/websockets/legacy/server.py b/venv/lib/python3.12/site-packages/websockets/legacy/server.py new file mode 100644 index 0000000000000000000000000000000000000000..d2a69c716c34083020033b089a7d4156fbc1e93e --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/legacy/server.py @@ -0,0 +1,1191 @@ +from __future__ import annotations + +import asyncio +import email.utils +import functools +import http +import inspect +import logging +import socket +import warnings +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike, MultipleValuesError +from ..exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidMessage, + InvalidOrigin, + InvalidUpgrade, + NegotiationError, +) +from ..extensions import Extension, ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..headers import ( + build_extension, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import SERVER +from ..protocol import State +from ..typing import ExtensionHeader, LoggerLike, Origin, StatusLike, Subprotocol +from .exceptions import AbortHandshake +from .handshake import build_response, check_request +from .http import read_request +from .protocol import WebSocketCommonProtocol, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "WebSocketServerProtocol", + "WebSocketServer", +] + + +HeadersLikeOrCallable = HeadersLike | Callable[[str, Headers], HeadersLike] + +HTTPResponse = tuple[StatusLike, HeadersLike, bytes] + + +class WebSocketServerProtocol(WebSocketCommonProtocol): + """ + WebSocket server connection. + + :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + You may customize the opening handshake in a subclass by + overriding :meth:`process_request` or :meth:`select_subprotocol`. + + Args: + ws_server: WebSocket server that created this connection. + + See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``, + ``extensions``, ``subprotocols``, ``extra_headers``, and ``server_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = False + side = "server" + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + ws_server: WebSocketServer, + *, + logger: LoggerLike | None = None, + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + super().__init__(logger=logger, **kwargs) + # For backwards compatibility with 6.0 or earlier. + if origins is not None and "" in origins: + warnings.warn("use None instead of '' in origins", DeprecationWarning) + origins = [None if origin == "" else origin for origin in origins] + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to serve to trigger the deprecation warning on direct + # use of WebSocketServerProtocol. + self.ws_handler = remove_path_argument(ws_handler) + self.ws_server = ws_server + self.origins = origins + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.server_header = server_header + self._process_request = process_request + self._select_subprotocol = select_subprotocol + self.open_timeout = open_timeout + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Register connection and initialize a task to handle it. + + """ + super().connection_made(transport) + # Register the connection with the server before creating the handler + # task. Registering at the beginning of the handler coroutine would + # create a race condition between the creation of the task, which + # schedules its execution, and the moment the handler starts running. + self.ws_server.register(self) + self.handler_task = self.loop.create_task(self.handler()) + + async def handler(self) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller able to handle exceptions, it + attempts to log relevant ones and guarantees that the TCP connection is + closed before exiting. + + """ + try: + try: + async with asyncio_timeout(self.open_timeout): + await self.handshake( + origins=self.origins, + available_extensions=self.available_extensions, + available_subprotocols=self.available_subprotocols, + extra_headers=self.extra_headers, + ) + except asyncio.TimeoutError: # pragma: no cover + raise + except ConnectionError: + raise + except Exception as exc: + if isinstance(exc, AbortHandshake): + status, headers, body = exc.status, exc.headers, exc.body + elif isinstance(exc, InvalidOrigin): + if self.debug: + self.logger.debug("! invalid origin", exc_info=True) + status, headers, body = ( + http.HTTPStatus.FORBIDDEN, + Headers(), + f"Failed to open a WebSocket connection: {exc}.\n".encode(), + ) + elif isinstance(exc, InvalidUpgrade): + if self.debug: + self.logger.debug("! invalid upgrade", exc_info=True) + status, headers, body = ( + http.HTTPStatus.UPGRADE_REQUIRED, + Headers([("Upgrade", "websocket")]), + ( + f"Failed to open a WebSocket connection: {exc}.\n" + f"\n" + f"You cannot access a WebSocket server directly " + f"with a browser. You need a WebSocket client.\n" + ).encode(), + ) + elif isinstance(exc, InvalidHandshake): + if self.debug: + self.logger.debug("! invalid handshake", exc_info=True) + exc_chain = cast(BaseException, exc) + exc_str = f"{exc_chain}" + while exc_chain.__cause__ is not None: + exc_chain = exc_chain.__cause__ + exc_str += f"; {exc_chain}" + status, headers, body = ( + http.HTTPStatus.BAD_REQUEST, + Headers(), + f"Failed to open a WebSocket connection: {exc_str}.\n".encode(), + ) + else: + self.logger.error("opening handshake failed", exc_info=True) + status, headers, body = ( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + Headers(), + ( + b"Failed to open a WebSocket connection.\n" + b"See server log for more information.\n" + ), + ) + + headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header: + headers.setdefault("Server", self.server_header) + + headers.setdefault("Content-Length", str(len(body))) + headers.setdefault("Content-Type", "text/plain") + headers.setdefault("Connection", "close") + + self.write_http_response(status, headers, body) + self.logger.info( + "connection rejected (%d %s)", status.value, status.phrase + ) + await self.close_transport() + return + + try: + await self.ws_handler(self) + except Exception: + self.logger.error("connection handler failed", exc_info=True) + if not self.closed: + self.fail_connection(1011) + raise + + try: + await self.close() + except ConnectionError: + raise + except Exception: + self.logger.error("closing handshake failed", exc_info=True) + raise + + except Exception: + # Last-ditch attempt to avoid leaking connections on errors. + try: + self.transport.close() + except Exception: # pragma: no cover + pass + + finally: + # Unregister the connection with the server when the handler task + # terminates. Registration is tied to the lifecycle of the handler + # task because the server waits for tasks attached to registered + # connections before terminating. + self.ws_server.unregister(self) + self.logger.info("connection closed") + + async def read_http_request(self) -> tuple[str, Headers]: + """ + Read request line and headers from the HTTP request. + + If the request contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET request. + + """ + try: + path, headers = await read_request(self.reader) + except asyncio.CancelledError: # pragma: no cover + raise + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP request") from exc + + if self.debug: + self.logger.debug("< GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.path = path + self.request_headers = headers + + return path, headers + + def write_http_response( + self, status: http.HTTPStatus, headers: Headers, body: bytes | None = None + ) -> None: + """ + Write status line and headers to the HTTP response. + + This coroutine is also able to write a response body. + + """ + self.response_headers = headers + + if self.debug: + self.logger.debug("> HTTP/1.1 %d %s", status.value, status.phrase) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + if body is not None: + self.logger.debug("> [body] (%d bytes)", len(body)) + + # Since the status line and headers only contain ASCII characters, + # we can keep this simple. + response = f"HTTP/1.1 {status.value} {status.phrase}\r\n" + response += str(headers) + + self.transport.write(response.encode()) + + if body is not None: + self.transport.write(body) + + async def process_request( + self, path: str, request_headers: Headers + ) -> HTTPResponse | None: + """ + Intercept the HTTP request and return an HTTP response if appropriate. + + You may override this method in a :class:`WebSocketServerProtocol` + subclass, for example: + + * to return an HTTP 200 OK response on a given path; then a load + balancer can use this path for a health check; + * to authenticate the request and return an HTTP 401 Unauthorized or an + HTTP 403 Forbidden when authentication fails. + + You may also override this method with the ``process_request`` + argument of :func:`serve` and :class:`WebSocketServerProtocol`. This + is equivalent, except ``process_request`` won't have access to the + protocol instance, so it can't store information for later use. + + :meth:`process_request` is expected to complete quickly. If it may run + for a long time, then it should await :meth:`wait_closed` and exit if + :meth:`wait_closed` completes, or else it could prevent the server + from shutting down. + + Args: + path: Request path, including optional query string. + request_headers: Request headers. + + Returns: + tuple[StatusLike, HeadersLike, bytes] | None: :obj:`None` to + continue the WebSocket handshake normally. + + An HTTP response, represented by a 3-uple of the response status, + headers, and body, to abort the WebSocket handshake and return + that HTTP response instead. + + """ + if self._process_request is not None: + response = self._process_request(path, request_headers) + if isinstance(response, Awaitable): + return await response + else: + # For backwards compatibility with 7.0. + warnings.warn( + "declare process_request as a coroutine", DeprecationWarning + ) + return response + return None + + @staticmethod + def process_origin( + headers: Headers, origins: Sequence[Origin | None] | None = None + ) -> Origin | None: + """ + Handle the Origin HTTP request header. + + Args: + headers: Request headers. + origins: Optional list of acceptable origins. + + Raises: + InvalidOrigin: If the origin isn't acceptable. + + """ + # "The user agent MUST NOT include more than one Origin header field" + # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3. + try: + origin = headers.get("Origin") + except MultipleValuesError as exc: + raise InvalidHeader("Origin", "multiple values") from exc + if origin is not None: + origin = cast(Origin, origin) + if origins is not None: + if origin not in origins: + raise InvalidOrigin(origin) + return origin + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ServerExtensionFactory] | None, + ) -> tuple[str | None, list[Extension]]: + """ + Handle the Sec-WebSocket-Extensions HTTP request header. + + Accept or reject each extension proposed in the client request. + Negotiate parameters for accepted extensions. + + Return the Sec-WebSocket-Extensions HTTP response header and the list + of accepted extensions. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension proposed by + the client, we check for a match with each extension available in the + server configuration. If no match is found, the extension is ignored. + + If several variants of the same extension are proposed by the client, + it may be accepted several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + This process doesn't allow the server to reorder extensions. It can + only select a subset of the extensions proposed by the client. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: Request headers. + extensions: Optional list of supported extensions. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + response_header_value: str | None = None + + extension_headers: list[ExtensionHeader] = [] + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values and available_extensions: + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, request_params in parsed_header_values: + for ext_factory in available_extensions: + # Skip non-matching extensions based on their name. + if ext_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + response_params, extension = ext_factory.process_request_params( + request_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + extension_headers.append((name, response_params)) + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the client sent. The extension is declined. + + # Serialize extension header. + if extension_headers: + response_header_value = build_extension(extension_headers) + + return response_header_value, accepted_extensions + + # Not @staticmethod because it calls self.select_subprotocol() + def process_subprotocol( + self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP request header. + + Return Sec-WebSocket-Protocol HTTP response header, which is the same + as the selected subprotocol. + + Args: + headers: Request headers. + available_subprotocols: Optional list of supported subprotocols. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values and available_subprotocols: + parsed_header_values: list[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + subprotocol = self.select_subprotocol( + parsed_header_values, available_subprotocols + ) + + return subprotocol + + def select_subprotocol( + self, + client_subprotocols: Sequence[Subprotocol], + server_subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + """ + Pick a subprotocol among those supported by the client and the server. + + If several subprotocols are available, select the preferred subprotocol + by giving equal weight to the preferences of the client and the server. + + If no subprotocol is available, proceed without a subprotocol. + + You may provide a ``select_subprotocol`` argument to :func:`serve` or + :class:`WebSocketServerProtocol` to override this logic. For example, + you could reject the handshake if the client doesn't support a + particular subprotocol, rather than accept the handshake without that + subprotocol. + + Args: + client_subprotocols: List of subprotocols offered by the client. + server_subprotocols: List of subprotocols available on the server. + + Returns: + Selected subprotocol, if a common subprotocol was found. + + :obj:`None` to continue without a subprotocol. + + """ + if self._select_subprotocol is not None: + return self._select_subprotocol(client_subprotocols, server_subprotocols) + + subprotocols = set(client_subprotocols) & set(server_subprotocols) + if not subprotocols: + return None + return sorted( + subprotocols, + key=lambda p: client_subprotocols.index(p) + server_subprotocols.index(p), + )[0] + + async def handshake( + self, + origins: Sequence[Origin | None] | None = None, + available_extensions: Sequence[ServerExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + ) -> str: + """ + Perform the server side of the opening handshake. + + Args: + origins: List of acceptable values of the Origin HTTP header; + include :obj:`None` if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of + decreasing preference. + extra_headers: Arbitrary HTTP headers to add to the response when + the handshake succeeds. + + Returns: + path of the URI of the request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + path, request_headers = await self.read_http_request() + + # Hook for customizing request handling, for example checking + # authentication or treating some paths as plain HTTP endpoints. + early_response_awaitable = self.process_request(path, request_headers) + if isinstance(early_response_awaitable, Awaitable): + early_response = await early_response_awaitable + else: + # For backwards compatibility with 7.0. + warnings.warn("declare process_request as a coroutine", DeprecationWarning) + early_response = early_response_awaitable + + # The connection may drop while process_request is running. + if self.state is State.CLOSED: + # This subclass of ConnectionError is silently ignored in handler(). + raise BrokenPipeError("connection closed during opening handshake") + + # Change the response to a 503 error if the server is shutting down. + if not self.ws_server.is_serving(): + early_response = ( + http.HTTPStatus.SERVICE_UNAVAILABLE, + [], + b"Server is shutting down.\n", + ) + + if early_response is not None: + raise AbortHandshake(*early_response) + + key = check_request(request_headers) + + self.origin = self.process_origin(request_headers, origins) + + extensions_header, self.extensions = self.process_extensions( + request_headers, available_extensions + ) + + protocol_header = self.subprotocol = self.process_subprotocol( + request_headers, available_subprotocols + ) + + response_headers = Headers() + + build_response(response_headers, key) + + if extensions_header is not None: + response_headers["Sec-WebSocket-Extensions"] = extensions_header + + if protocol_header is not None: + response_headers["Sec-WebSocket-Protocol"] = protocol_header + + if callable(extra_headers): + extra_headers = extra_headers(path, self.request_headers) + if extra_headers is not None: + response_headers.update(extra_headers) + + response_headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header is not None: + response_headers.setdefault("Server", self.server_header) + + self.write_http_response(http.HTTPStatus.SWITCHING_PROTOCOLS, response_headers) + + self.logger.info("connection open") + + self.connection_open() + + return path + + +class WebSocketServer: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__(self, logger: LoggerLike | None = None) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.websockets: set[WebSocketServerProtocol] = set() + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] + + def wrap(self, server: asyncio.base_events.Server) -> None: + """ + Attach to a given :class:`~asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`WebSocketServer` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`~asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + # Initialized here because we need a reference to the event loop. + # This could be moved back to __init__ now that Python < 3.10 isn't + # supported anymore, but I'm not taking that risk in legacy code. + self.closed_waiter = server.get_loop().create_future() + + def register(self, protocol: WebSocketServerProtocol) -> None: + """ + Register a connection with this server. + + """ + self.websockets.add(protocol) + + def unregister(self, protocol: WebSocketServerProtocol) -> None: + """ + Unregister a connection with this server. + + """ + self.websockets.remove(protocol) + + def close(self, close_connections: bool = True) -> None: + """ + Close the server. + + * Close the underlying :class:`~asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, + close existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with close code 1001 (going away). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections) + ) + + async def _close(self, close_connections: bool) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`~asyncio.Server` object to stop accepting new connections and + then closes open connections with close code 1001. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + if close_connections: + # Close OPEN connections with close code 1001. After server.close(), + # handshake() closes OPENING connections with an HTTP 503 error. + close_tasks = [ + asyncio.create_task(websocket.close(1001)) + for websocket in self.websockets + if websocket.state is not State.CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.websockets: + await asyncio.wait( + [websocket.handler_task for websocket in self.websockets] + ) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> Iterable[socket.socket]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> WebSocketServer: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +class Serve: + """ + Start a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a + :class:`WebSocketServerProtocol`, performs the opening handshake, and + delegates to the connection handler, ``ws_handler``. + + The handler receives the :class:`WebSocketServerProtocol` and uses it to + send and receive messages. + + Once the handler completes, either normally or with an exception, the + server performs the closing handshake and closes the connection. + + Awaiting :func:`serve` yields a :class:`WebSocketServer`. This object + provides a :meth:`~WebSocketServer.close` method to shut down the server:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + server = await serve(...) + await stop + server.close() + await server.wait_closed() + + :func:`serve` can be used as an asynchronous context manager. Then, the + server is shut down automatically when exiting the context:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(...): + await stop + + Args: + ws_handler: Connection handler. It receives the WebSocket connection, + which is a :class:`WebSocketServerProtocol`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketServerProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Include :obj:`None` + in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers (HeadersLike | Callable[[str, Headers] | HeadersLike]): + Arbitrary HTTP headers to add to the response. This can be + a :data:`~websockets.datastructures.HeadersLike` or a callable + taking the request path and headers in arguments and returning + a :data:`~websockets.datastructures.HeadersLike`. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + process_request (Callable[[str, Headers], \ + Awaitable[tuple[StatusLike, HeadersLike, bytes] | None]] | None): + Intercept HTTP request before the opening handshake. + See :meth:`~WebSocketServerProtocol.process_request` for details. + select_subprotocol: Select a subprotocol supported by the client. + See :meth:`~WebSocketServerProtocol.select_subprotocol` for details. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to a :obj:`~socket.socket` that you created + outside of websockets. + + Returns: + WebSocket server. + + """ + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + host: str | Sequence[str] | None = None, + port: int | None = None, + *, + create_protocol: Callable[..., WebSocketServerProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketServerProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketServerProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + ws_server = WebSocketServer(logger=logger) + + secure = kwargs.get("ssl") is not None + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketServerProtocol] | + # Callable[..., WebSocketServerProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketServerProtocol], create_protocol) + factory = functools.partial( + create_protocol, + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to WebSocketServerProtocol to trigger the deprecation + # warning once per serve() call rather than once per connection. + remove_path_argument(ws_handler), + ws_server, + host=host, + port=port, + secure=secure, + open_timeout=open_timeout, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + loop=_loop, + legacy_recv=legacy_recv, + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + server_header=server_header, + process_request=process_request, + select_subprotocol=select_subprotocol, + logger=logger, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + # unix_serve(path) must not specify host and port parameters. + assert host is None and port is None + create_server = functools.partial( + loop.create_unix_server, factory, path, **kwargs + ) + else: + create_server = functools.partial( + loop.create_server, factory, host, port, **kwargs + ) + + # This is a coroutine function. + self._create_server = create_server + self.ws_server = ws_server + + # async with serve(...) + + async def __aenter__(self) -> WebSocketServer: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.ws_server.close() + await self.ws_server.wait_closed() + + # await serve(...) + + def __await__(self) -> Generator[Any, None, WebSocketServer]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketServer: + server = await self._create_server() + self.ws_server.wrap(server) + return self.ws_server + + # yield from serve(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +serve = Serve + + +def unix_serve( + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + path: str | None = None, + **kwargs: Any, +) -> Serve: + """ + Start a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It is only available on Unix. + + Unrecognized keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_unix_server` method. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + path: File system path to the Unix socket. + + """ + return serve(ws_handler, path=path, unix=True, **kwargs) + + +def remove_path_argument( + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), +) -> Callable[[WebSocketServerProtocol], Awaitable[Any]]: + try: + inspect.signature(ws_handler).bind(None) + except TypeError: + try: + inspect.signature(ws_handler).bind(None, "") + except TypeError: # pragma: no cover + # ws_handler accepts neither one nor two arguments; leave it alone. + pass + else: + # ws_handler accepts two arguments; activate backwards compatibility. + warnings.warn("remove second argument of ws_handler", DeprecationWarning) + + async def _ws_handler(websocket: WebSocketServerProtocol) -> Any: + return await cast( + Callable[[WebSocketServerProtocol, str], Awaitable[Any]], + ws_handler, + )(websocket, websocket.path) + + return _ws_handler + + return cast( + Callable[[WebSocketServerProtocol], Awaitable[Any]], + ws_handler, + ) diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__init__.py b/venv/lib/python3.12/site-packages/websockets/sync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/__init__.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e55f18b3302efb32fc0aedb4c8b9f0c49f9241c2 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/__init__.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/client.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c83794488ceeabdfc1a7e1255938d596f3bc5cc Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/client.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/connection.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..473bd84204a1ab695c2c0120e151bd5c036c61f9 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/connection.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/messages.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/messages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08164e2d71999eff85827b045e5ae562a0114817 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/messages.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/router.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ba5863dabd3233dd1c4d5ed0bc10e2b4b5a6c4b Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/router.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/server.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe55a0bccb71a8269ea3190aa3c98f0941269450 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/server.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/utils.cpython-312.pyc b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833c5f130439d2f456da1bbde2336d52715c8826 Binary files /dev/null and b/venv/lib/python3.12/site-packages/websockets/sync/__pycache__/utils.cpython-312.pyc differ diff --git a/venv/lib/python3.12/site-packages/websockets/sync/client.py b/venv/lib/python3.12/site-packages/websockets/sync/client.py new file mode 100644 index 0000000000000000000000000000000000000000..b3fff44eee51ca2961f40c0994d7078c0670a9da --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/sync/client.py @@ -0,0 +1,633 @@ +from __future__ import annotations + +import socket +import ssl as ssl_module +import threading +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Literal, TypeVar, cast + +from ..client import ClientProtocol +from ..datastructures import HeadersLike +from ..exceptions import InvalidProxyMessage, InvalidProxyStatus, ProxyError +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request +from ..streams import StreamReader +from ..typing import BytesLike, LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .connection import Connection +from .utils import Deadline + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + + +class ClientConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`connect`. + + Args: + socket: Socket connected to a WebSocket server. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ClientProtocol + self.response_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + + def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + if not self.response_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake response") + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.response_rcvd.set() + + +def connect( + uri: str, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + proxy_ssl: ssl_module.SSLContext | None = None, + proxy_server_hostname: str | None = None, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to the WebSocket server at ``uri``. + + This function returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as a context manager:: + + from websockets.sync.client import connect + + with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + Args: + uri: URI of the WebSocket server. + sock: Preexisting TCP socket. ``sock`` overrides the host and port + from ``uri``. You may call :func:`socket.create_connection` to + create a suitable TCP socket. + ssl: Configuration for enabling TLS on the connection. + server_hostname: Host name for the TLS handshake. ``server_hostname`` + overrides the host name from ``uri``. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + proxy_ssl: Configuration for enabling TLS on the proxy connection. + proxy_server_hostname: Host name for the TLS handshake with the proxy. + ``proxy_server_hostname`` overrides the host name from ``proxy``. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_connection`. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + ws_uri = parse_uri(uri) + if not ws_uri.secure and ssl is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if unix: + if path is None and sock is None: + raise ValueError("missing path argument") + elif path is not None and sock is not None: + raise ValueError("path and sock arguments are incompatible") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if unix: + proxy = None + if sock is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + # Calculate timeouts on the TCP, TLS, and WebSocket handshakes. + # The TCP and TLS timeouts must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + if create_connection is None: + create_connection = ClientConnection + + try: + # Connect socket + + if sock is None: + if unix: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(deadline.timeout()) + assert path is not None # mypy cannot figure this out + sock.connect(path) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = connect_socks_proxy( + proxy_parsed, + ws_uri, + deadline, + # websockets is consistent with the socket module while + # python_socks is consistent across implementations. + local_addr=kwargs.pop("source_address", None), + ) + elif proxy_parsed.scheme[:4] == "http": + # Validate the proxy_ssl argument. + if proxy_parsed.scheme != "https" and proxy_ssl is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + sock = connect_http_proxy( + proxy_parsed, + ws_uri, + deadline, + user_agent_header=user_agent_header, + ssl=proxy_ssl, + server_hostname=proxy_server_hostname, + **kwargs, + ) + else: + raise AssertionError("unsupported proxy") + else: + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection( + (ws_uri.host, ws_uri.port), + **kwargs, + ) + sock.settimeout(None) + + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Initialize TLS wrapper and perform TLS handshake + + if ws_uri.secure: + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = ws_uri.host + sock.settimeout(deadline.timeout()) + if proxy_ssl is None: + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + else: + sock_2 = SSLSSLSocket(sock, ssl, server_hostname=server_hostname) + # Let's pretend that sock is a socket, even though it isn't. + sock = cast(socket.socket, sock_2) + sock.settimeout(None) + + # Initialize WebSocket protocol + + protocol = ClientProtocol( + ws_uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + if sock is not None: + sock.close() + raise + + try: + connection.handshake( + additional_headers, + user_agent_header, + deadline.timeout(), + ) + except Exception: + connection.close_socket() + connection.recv_events_thread.join() + raise + + connection.start_keepalive() + return connection + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` is provided, to + ``wss://localhost/``. + + """ + if uri is None: + # Backwards compatibility: ssl used to be called ssl_context. + if kwargs.get("ssl") is None and kwargs.get("ssl_context") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.sync import Proxy as SocksProxy + +except ImportError: + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("connecting through a SOCKS proxy requires python-socks") + +else: + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + kwargs.setdefault("timeout", deadline.timeout()) + # connect() is documented to raise OSError and TimeoutError. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except (OSError, TimeoutError, socket.timeout): + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + + +def read_connect_response(sock: socket.socket, deadline: Deadline) -> Response: + reader = StreamReader() + parser = Response.parse( + reader.read_line, + reader.read_exact, + reader.read_to_eof, + proxy=True, + ) + try: + while True: + sock.settimeout(deadline.timeout()) + data = sock.recv(4096) + if data: + reader.feed_data(data) + else: + reader.feed_eof() + next(parser) + except StopIteration as exc: + assert isinstance(exc.value, Response) # help mypy + response = exc.value + if 200 <= response.status_code < 300: + return response + else: + raise InvalidProxyStatus(response) + except socket.timeout: + raise TimeoutError("timed out while connecting to HTTP proxy") + except Exception as exc: + raise InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) from exc + finally: + sock.settimeout(None) + + +def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + *, + user_agent_header: str | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + **kwargs: Any, +) -> socket.socket: + # Connect socket + + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection((proxy.host, proxy.port), **kwargs) + + # Initialize TLS wrapper and perform TLS handshake + + if proxy.scheme == "https": + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = proxy.host + sock.settimeout(deadline.timeout()) + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + sock.settimeout(None) + + # Send CONNECT request to the proxy and read response. + + sock.sendall(prepare_connect_request(proxy, ws_uri, user_agent_header)) + try: + read_connect_response(sock, deadline) + except Exception: + sock.close() + raise + + return sock + + +T = TypeVar("T") +F = TypeVar("F", bound=Callable[..., T]) + + +class SSLSSLSocket: + """ + Socket-like object providing TLS-in-TLS. + + Only methods that are used by websockets are implemented. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + sock: socket.socket, + ssl_context: ssl_module.SSLContext, + server_hostname: str | None = None, + ) -> None: + self.incoming = ssl_module.MemoryBIO() + self.outgoing = ssl_module.MemoryBIO() + self.ssl_socket = sock + self.ssl_object = ssl_context.wrap_bio( + self.incoming, + self.outgoing, + server_hostname=server_hostname, + ) + self.run_io(self.ssl_object.do_handshake) + + def run_io(self, func: Callable[..., T], *args: Any) -> T: + while True: + want_read = False + want_write = False + try: + result = func(*args) + except ssl_module.SSLWantReadError: + want_read = True + except ssl_module.SSLWantWriteError: # pragma: no cover + want_write = True + + # Write outgoing data in all cases. + data = self.outgoing.read() + if data: + self.ssl_socket.sendall(data) + + # Read incoming data and retry on SSLWantReadError. + if want_read: + data = self.ssl_socket.recv(self.recv_bufsize) + if data: + self.incoming.write(data) + else: + self.incoming.write_eof() + continue + # Retry after writing outgoing data on SSLWantWriteError. + if want_write: # pragma: no cover + continue + # Return result if no error happened. + return result + + def recv(self, buflen: int) -> bytes: + try: + return self.run_io(self.ssl_object.read, buflen) + except ssl_module.SSLEOFError: + return b"" # always ignore ragged EOFs + + def send(self, data: BytesLike) -> int: + return self.run_io(self.ssl_object.write, data) + + def sendall(self, data: BytesLike) -> None: + # adapted from ssl_module.SSLSocket.sendall() + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + count += self.send(byte_view[count:]) + + # recv_into(), recvfrom(), recvfrom_into(), sendto(), unwrap(), and the + # flags argument aren't implemented because websockets doesn't need them. + + def __getattr__(self, name: str) -> Any: + return getattr(self.ssl_socket, name) diff --git a/venv/lib/python3.12/site-packages/websockets/sync/connection.py b/venv/lib/python3.12/site-packages/websockets/sync/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..665f478ac9377174ca5c912f5939f81bdd8db3d7 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/sync/connection.py @@ -0,0 +1,1078 @@ +from __future__ import annotations + +import contextlib +import logging +import random +import socket +import struct +import threading +import time +import uuid +from collections.abc import Iterable, Iterator, Mapping +from types import TracebackType +from typing import Any, Literal, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .messages import Assembler +from .utils import Deadline + + +__all__ = ["Connection"] + + +class Connection: + """ + :mod:`threading` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.sync.client.ClientConnection` or + :class:`~websockets.sync.server.ServerConnection`. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + socket: socket.socket, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.socket = socket + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + max_queue_high, max_queue_low = max_queue, None + else: + max_queue_high, max_queue_low = max_queue + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Mutex serializing interactions with the protocol. + self.protocol_mutex = threading.Lock() + + # Lock stopping reads when the assembler buffer is full. + self.recv_flow_control = threading.Lock() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages = Assembler( + max_queue_high, + max_queue_low, + pause=self.recv_flow_control.acquire, + resume=self.recv_flow_control.release, + ) + + # Deadline for the closing handshake. + self.close_deadline: Deadline | None = None + + # Whether we are busy sending a fragmented message. + self.send_in_progress = False + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pending_pings: dict[bytes, tuple[threading.Event, float, bool]] = {} + + self.latency: float = 0.0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0.0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Thread that sends keepalive pings. None when ping_interval is None. + self.keepalive_thread: threading.Thread | None = None + + # Exception raised while reading from the connection, to be chained to + # ConnectionClosed in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Receiving events from the socket. This thread is marked as daemon to + # allow creating a connection in a non-daemon thread and using it in a + # daemon thread. This mustn't prevent the interpreter from exiting. + self.recv_events_thread = threading.Thread( + target=self.recv_events, + daemon=True, + ) + + # Start recv_events only after all attributes are initialized. + self.recv_events_thread.start() + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.socket.getsockname() + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.socket.getpeername() + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + def __enter__(self) -> Connection: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + self.close() + else: + self.close(CloseCode.INTERNAL_ERROR) + + def __iter__(self) -> Iterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages in an infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield self.recv() + except ConnectionClosedOK: + return + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def recv(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def recv(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def recv(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def recv( + self, timeout: float | None = None, *, decode: Literal[False] + ) -> bytes: ... + + @overload + def recv( + self, timeout: float | None = None, decode: bool | None = None + ) -> Data: ... + + def recv(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + If ``timeout`` is :obj:`None`, block until a message is received. If + ``timeout`` is set, wait up to ``timeout`` seconds for a message to be + received and return it, else raise :exc:`TimeoutError`. If ``timeout`` + is ``0`` or negative, check if a message has been received already and + return it, else raise :exc:`TimeoutError`. + + When the message is fragmented, :meth:`recv` waits until all fragments + are received, reassembles them, and returns the whole message. + + Args: + timeout: Timeout for receiving a message in seconds. + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + return strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return self.recv_messages.get(timeout, decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: ... + + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + iterator that yields each fragment as it is received. This iterator must + be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + yield bytestrings (:class:`bytes`). This improves performance + when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + yield strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + yield from self.recv_messages.get_iter(decode) + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + def send( + self, + message: DataLike | Iterable[DataLike], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable of strings, bytestrings, or + bytes-like objects to enable fragmentation_. Each item is treated as a + message fragment and sent in its own frame. All items must be of the + same type, or else :meth:`send` will raise a :exc:`TypeError` and the + connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If the connection is sending a fragmented message. + TypeError: If ``message`` doesn't have a supported type. + + """ + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + try: + # First fragment. + if isinstance(chunk, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("iterable must contain uniform types") + + # Final fragment. + with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + self.send_in_progress = False + + except ConcurrencyError: + # We didn't start sending a fragmented message. + # The connection is still usable. + raise + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + else: + raise TypeError("data must be str, bytes, or iterable") + + def close( + self, + code: CloseCode | int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + with self.send_context(): + if self.send_in_progress: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + def ping( + self, + data: DataLike | None = None, + ack_on_close: bool = False, + ) -> threading.Event: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + ack_on_close: when this option is :obj:`True`, the event will also + be set when the connection is closed. While this avoids getting + stuck waiting for a pong that will never arrive, it requires + checking that the state of the connection is still ``OPEN`` to + confirm that a pong was received, rather than the connection + being closed. + + Returns: + An event that will be set when the corresponding pong is received. + You can ignore it if you don't intend to wait. + + :: + + pong_received = ws.ping() + # only if you want to wait for the corresponding pong + pong_received.wait() + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pending_pings: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pending_pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_received = threading.Event() + ping_timestamp = time.monotonic() + self.pending_pings[data] = (pong_received, ping_timestamp, ack_on_close) + self.protocol.send_ping(data) + return pong_received + + def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + with self.protocol_mutex: + # Ignore unsolicited pong. + if data not in self.pending_pings: + return + + pong_timestamp = time.monotonic() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, ( + pong_received, + ping_timestamp, + _ack_on_close, + ) in self.pending_pings.items(): + ping_ids.append(ping_id) + pong_received.set() + if ping_id == data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pending_pings. + for ping_id in ping_ids: + del self.pending_pings[ping_id] + + def terminate_pending_pings(self) -> None: + """ + Acknowledge pending pings when the connection is closed. + + """ + assert self.protocol_mutex.locked() + assert self.protocol.state is CLOSED + + for pong_received, _ping_timestamp, ack_on_close in self.pending_pings.values(): + if ack_on_close: + pong_received.set() + + self.pending_pings.clear() + + def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + try: + while True: + # If self.ping_timeout > self.latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + self.recv_events_thread.join(self.ping_interval - self.latency) + if not self.recv_events_thread.is_alive(): + break + + try: + pong_received = self.ping(ack_on_close=True) + except ConnectionClosed: + break + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + if pong_received.wait(self.ping_timeout): + if self.debug: + self.logger.debug("% received keepalive pong") + else: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a thread, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + # This thread is marked as daemon like self.recv_events_thread. + self.keepalive_thread = threading.Thread( + target=self.keepalive, + daemon=True, + ) + self.keepalive_thread.start() + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + Run this method in a thread as long as the connection is alive. + + ``recv_events()`` exits immediately when ``self.socket`` is closed. + + """ + try: + while True: + try: + # If the assembler buffer is full, block until it drains. + with self.recv_flow_control: + pass + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + data = self.socket.recv(self.recv_bufsize) + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while receiving data", + exc_info=True, + ) + # When the closing handshake is initiated by our side, + # recv() may block until send_context() closes the socket. + # In that case, send_context() already set recv_exc. + # Calling set_recv_exc() avoids overwriting it. + with self.protocol_mutex: + self.set_recv_exc(exc) + break + + if data == b"": + break + + # Acquire the connection lock. + with self.protocol_mutex: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # Similarly to the above, avoid overriding an exception + # set by send_context(), in case of a race condition + # i.e. send_context() closes the socket after recv() + # returns above but before send_data() calls send(). + self.set_recv_exc(exc) + break + + # If needed, set the close deadline based on the close timeout. + if self.protocol.close_expected(): + if self.close_deadline is None: + self.close_deadline = Deadline(self.close_timeout) + + # Unlock conn_mutex before processing events. Else, the + # application can't send messages in response to events. + + # If self.send_data raised an exception, then events are lost. + # Given that automatic responses write small amounts of data, + # this should be uncommon, so we don't handle the edge case. + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + # Breaking out of the while True: ... loop means that we believe + # that the socket doesn't work anymore. + + with self.protocol_mutex: + # Feed the end of the data stream to the protocol. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream and it handles errors by itself. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + except Exception as exc: + # This branch should never run. It's a safety net in case of bugs. + self.logger.error("unexpected internal error", exc_info=True) + with self.protocol_mutex: + self.set_recv_exc(exc) + finally: + # This isn't expected to raise an exception. + self.close_socket() + + @contextlib.contextmanager + def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> Iterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` acquires the connection lock and checks + that the connection is open; on exit, it writes outgoing data to the + socket and releases the connection lock:: + + with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the socket and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + # Acquire the protocol lock. + with self.protocol_mutex: + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # Set the close deadline based on the close timeout. + # Since we tested earlier that protocol.state is OPEN + # (or CONNECTING) and we didn't release protocol_mutex, + # self.close_deadline is still None. + assert self.close_deadline is None + self.close_deadline = Deadline(self.close_timeout) + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + # Calculate close_deadline if it wasn't set yet. + if self.close_deadline is None: + self.close_deadline = Deadline(self.close_timeout) + raise_close_exc = True + + # To avoid a deadlock, release the connection lock by exiting the + # context manager before waiting for recv_events() to terminate. + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + # Thread.join() returns immediately if timeout is negative. + assert self.close_deadline is not None + timeout = self.close_deadline.timeout(raise_if_elapsed=False) + self.recv_events_thread.join(timeout) + if self.recv_events_thread.is_alive(): + # There's no risk of overwriting another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the socket in order to get + # proper exception reporting. + raise_close_exc = True + with self.protocol_mutex: + self.set_recv_exc(original_exc) + + # If an error occurred, close the socket to terminate the connection and + # raise an exception. + if raise_close_exc: + self.close_socket() + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + This method requires holding protocol_mutex. + + """ + assert self.protocol_mutex.locked() + for data in self.protocol.data_to_send(): + if data: + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + self.socket.sendall(data) + else: + try: + self.socket.shutdown(socket.SHUT_WR) + except OSError: # socket already closed + pass + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + This method requires holding protocol_mutex and must be called only from + the thread running recv_events(). + + """ + assert self.protocol_mutex.locked() + if self.recv_exc is None: + self.recv_exc = exc + + def close_socket(self) -> None: + """ + Shutdown and close socket. Close message assembler. + + Calling close_socket() guarantees that recv_events() terminates. Indeed, + recv_events() may block only on socket.recv() or on recv_messages.put(). + + """ + # shutdown() is required to interrupt recv() on Linux. + try: + self.socket.shutdown(socket.SHUT_RDWR) + except OSError: # socket already closed + pass + self.socket.close() + + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + with self.protocol_mutex: + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + # Abort recv() with a ConnectionClosed exception. + self.recv_messages.close() + + # Acknowledge pings sent with the ack_on_close option. + self.terminate_pending_pings() diff --git a/venv/lib/python3.12/site-packages/websockets/sync/messages.py b/venv/lib/python3.12/site-packages/websockets/sync/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..d95519f63ecfb20e681de13ed6bf3481c966d2d3 --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/sync/messages.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import codecs +import queue +import threading +from typing import Any, Callable, Iterable, Iterator, Literal, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data +from .utils import Deadline + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + def __init__( + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Serialize reads and writes -- except for reads via synchronization + # primitives provided by the threading and queue modules. + self.mutex = threading.Lock() + + # Queue of incoming frames. + self.frames: queue.SimpleQueue[Frame | None] = queue.SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + def get_next_frame(self, timeout: float | None = None) -> Frame: + # Helper to factor out the logic for getting the next frame from the + # queue, while handling timeouts and reaching the end of the stream. + if self.closed: + try: + frame = self.frames.get(block=False) + except queue.Empty: + raise EOFError("stream of frames ended") from None + else: + try: + # Check for a frame that's already received if timeout <= 0. + # SimpleQueue.get() doesn't support negative timeout values. + if timeout is not None and timeout <= 0: + frame = self.frames.get(block=False) + else: + frame = self.frames.get(block=True, timeout=timeout) + except queue.Empty: + raise TimeoutError(f"timed out in {timeout:.1f}s") from None + if frame is None: + raise EOFError("stream of frames ended") + return frame + + def reset_queue(self, frames: Iterable[Frame]) -> None: + # Helper to put frames back into the queue after they were fetched. + # This happens only when the queue is empty. However, by the time + # we acquire self.mutex, put() may have added items in the queue. + # Therefore, we must handle the case where the queue is not empty. + frame: Frame | None + with self.mutex: + queued = [] + try: + while True: + queued.append(self.frames.get(block=False)) + except queue.Empty: + pass + for frame in frames: + self.frames.put(frame) + # This loop runs only when a race condition occurs. + for frame in queued: # pragma: no cover + self.frames.put(frame) + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def get(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: ... + + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + timeout: If a timeout is provided and elapses before a complete + message is received, :meth:`get` raises :exc:`TimeoutError`. + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + TimeoutError: If a timeout is provided and elapses before a + complete message is received. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or times out. + + try: + deadline = Deadline(timeout) + + # Fetch the first frame. + frame = self.get_next_frame(deadline.timeout(raise_if_elapsed=False)) + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Fetch subsequent frames for fragmented messages. + while not frame.fin: + try: + frame = self.get_next_frame( + deadline.timeout(raise_if_elapsed=False) + ) + except TimeoutError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.reset_queue(frames) + raise + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + # This converts frame.data to bytes when it's a bytearray. + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: ... + + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` yields a :class:`str` or + :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or times out. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # Yield the first frame. + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + # Yield subsequent frames for fragmented messages. + while not frame.fin: + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + with self.mutex: + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + # put() and get/get_iter() call maybe_pause() and maybe_resume() while + # holding self.mutex. This guarantees that the calls interleave properly. + # Specifically, it prevents a race condition where maybe_resume() would + # run before maybe_pause(), leaving the connection incorrectly paused. + + # A race condition is possible when get/get_iter() call self.frames.get() + # without holding self.mutex. However, it's harmless — and even beneficial! + # It can only result in popping an item from the queue before maybe_resume() + # runs and skipping a pause() - resume() cycle that would otherwise occur. + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled. + if self.high is None: + return + + assert self.mutex.locked() + + # Check for "> high" to support high = 0. + if self.frames.qsize() > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled. + if self.low is None: + return + + assert self.mutex.locked() + + # Check for "<= low" to support low = 0. + if self.frames.qsize() <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + with self.mutex: + if self.closed: + return + + self.closed = True + + if self.get_in_progress: + # Unblock get() or get_iter(). + self.frames.put(None) + + if self.paused: + # Unblock recv_events(). + self.paused = False + self.resume() diff --git a/venv/lib/python3.12/site-packages/websockets/sync/router.py b/venv/lib/python3.12/site-packages/websockets/sync/router.py new file mode 100644 index 0000000000000000000000000000000000000000..1c35e8aaea909b3dd1a16f9346cd94f5063aa17c --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/sync/router.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Callable, Literal + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +try: + from werkzeug.exceptions import NotFound + from werkzeug.routing import Map, RequestRedirect + +except ImportError: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Server: + raise ImportError("route() requires werkzeug") + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Server: + raise ImportError("unix_route() requires werkzeug") + +else: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Server: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.sync.router import route + from werkzeug.routing import Map, Rule + + def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + with route(url_map, ...) as server: + server.serve_forever() + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When + not provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without enabling TLS. + Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Response | None, + ] = router.route_request + else: + + def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Server: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.sync.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return connection.handler(connection, **connection.handler_kwargs) diff --git a/venv/lib/python3.12/site-packages/websockets/sync/server.py b/venv/lib/python3.12/site-packages/websockets/sync/server.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd82fbad36e10e2f7a6a96cbcfba432b7ee780c --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/sync/server.py @@ -0,0 +1,765 @@ +from __future__ import annotations + +import hmac +import http +import logging +import os +import re +import selectors +import socket +import ssl as ssl_module +import sys +import threading +import warnings +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .connection import Connection +from .utils import Deadline + + +__all__ = ["serve", "unix_serve", "ServerConnection", "Server", "basic_auth"] + + +class ServerConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`serve`. + + Args: + socket: Socket connected to a WebSocket client. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ServerProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ServerProtocol + self.request_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], None] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + if not self.request_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake request") + + if self.request is not None: + with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + self.response = self.protocol.accept(self.request) + else: + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.request_rcvd.set() + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~socketserver.BaseServer`, notably the + :meth:`~socketserver.BaseServer.serve_forever` and + :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context + manager protocol. + + Args: + socket: Server socket listening for new connections. + handler: Handler for one connection. Receives the socket and address + returned by :meth:`~socket.socket.accept`. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + socket: socket.socket, + handler: Callable[[socket.socket, Any], None], + logger: LoggerLike | None = None, + ) -> None: + self.socket = socket + self.handler = handler + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + if sys.platform != "win32": + self.shutdown_watcher, self.shutdown_notifier = os.pipe() + + def serve_forever(self) -> None: + """ + See :meth:`socketserver.BaseServer.serve_forever`. + + This method doesn't return. Calling :meth:`shutdown` from another thread + stops the server. + + Typical use:: + + with serve(...) as server: + server.serve_forever() + + """ + poller = selectors.DefaultSelector() + try: + poller.register(self.socket, selectors.EVENT_READ) + except ValueError: # pragma: no cover + # If shutdown() is called before poller.register(), + # the socket is closed and poller.register() raises + # ValueError: Invalid file descriptor: -1 + return + if sys.platform != "win32": + poller.register(self.shutdown_watcher, selectors.EVENT_READ) + + while True: + poller.select() + try: + # If the socket is closed, this will raise an exception and exit + # the loop. So we don't need to check the return value of select(). + sock, addr = self.socket.accept() + except OSError: + break + # Since there isn't a mechanism for tracking connections and waiting + # for them to terminate, we cannot use daemon threads, or else all + # connections would be terminate brutally when closing the server. + thread = threading.Thread(target=self.handler, args=(sock, addr)) + thread.start() + + def shutdown(self) -> None: + """ + See :meth:`socketserver.BaseServer.shutdown`. + + """ + self.socket.close() + if sys.platform != "win32": + os.write(self.shutdown_notifier, b"x") + + def fileno(self) -> int: + """ + See :meth:`socketserver.BaseServer.fileno`. + + """ + return self.socket.fileno() + + def __enter__(self) -> Server: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.shutdown() + + +def __getattr__(name: str) -> Any: + if name == "WebSocketServer": + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "WebSocketServer was renamed to Server", + DeprecationWarning, + ) + return Server + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def serve( + handler: Callable[[ServerConnection], None], + host: str | None = None, + port: int | None = None, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler``. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This function returns a :class:`Server` whose API mirrors + :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure + that it will be closed and call :meth:`~Server.serve_forever` to serve + requests:: + + from websockets.sync.server import serve + + def handler(websocket): + ... + + with serve(handler, ...) as server: + server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :func:`~socket.create_server` for details. + port: TCP port the server listens on. + See :func:`~socket.create_server` for details. + sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``. + You may call :func:`socket.create_server` to create a suitable TCP + socket. + ssl: Configuration for enabling TLS on the connection. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_server`. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + # Bind socket and listen + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if sock is None: + if unix: + if path is None: + raise ValueError("missing path argument") + kwargs.setdefault("family", socket.AF_UNIX) + sock = socket.create_server(path, **kwargs) + else: + sock = socket.create_server((host, port), **kwargs) + else: + if path is not None: + raise ValueError("path and sock arguments are incompatible") + + # Initialize TLS wrapper + + if ssl is not None: + sock = ssl.wrap_socket( + sock, + server_side=True, + # Delay TLS handshake until after we set a timeout on the socket. + do_handshake_on_connect=False, + ) + + # Define request handler + + def conn_handler(sock: socket.socket, addr: Any) -> None: + # Calculate timeouts on the TLS and WebSocket handshakes. + # The TLS timeout must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + try: + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Perform TLS handshake + + if ssl is not None: + sock.settimeout(deadline.timeout()) + # mypy cannot figure this out + assert isinstance(sock, ssl_module.SSLSocket) + sock.do_handshake() + sock.settimeout(None) + + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # Initialize WebSocket protocol + + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + assert create_connection is not None # help mypy + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + sock.close() + return + + try: + try: + connection.handshake( + process_request, + process_response, + server_header, + deadline.timeout(), + ) + except TimeoutError: + connection.close_socket() + connection.recv_events_thread.join() + return + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.close_socket() + connection.recv_events_thread.join() + return + + assert connection.protocol.state is OPEN + try: + connection.start_keepalive() + handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + connection.close(CloseCode.INTERNAL_ERROR) + else: + connection.close() + + except Exception: # pragma: no cover + # Don't leak sockets on unexpected errors. + sock.close() + + # Initialize server + + return Server(sock, conn_handler, logger) + + +def unix_serve( + handler: Callable[[ServerConnection], None], + path: str | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`serve`. + + It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], bool] | None = None, +) -> Callable[[ServerConnection, Request], Response | None]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.sync.server import basic_auth, serve + + with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + if not check_credentials(username, password): + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/venv/lib/python3.12/site-packages/websockets/sync/utils.py b/venv/lib/python3.12/site-packages/websockets/sync/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..00bce2cc6bb19fa280a6ef2b3481403e6f6ba74f --- /dev/null +++ b/venv/lib/python3.12/site-packages/websockets/sync/utils.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import time + + +__all__ = ["Deadline"] + + +class Deadline: + """ + Manage timeouts across multiple steps. + + Args: + timeout: Time available in seconds or :obj:`None` if there is no limit. + + """ + + def __init__(self, timeout: float | None) -> None: + self.deadline: float | None + if timeout is None: + self.deadline = None + else: + self.deadline = time.monotonic() + timeout + + def timeout(self, *, raise_if_elapsed: bool = True) -> float | None: + """ + Calculate a timeout from a deadline. + + Args: + raise_if_elapsed: Whether to raise :exc:`TimeoutError` + if the deadline lapsed. + + Raises: + TimeoutError: If the deadline lapsed. + + Returns: + Time left in seconds or :obj:`None` if there is no limit. + + """ + if self.deadline is None: + return None + timeout = self.deadline - time.monotonic() + if raise_if_elapsed and timeout <= 0: + raise TimeoutError("timed out") + return timeout