diff --git a/README.md b/README.md index bf3ee90..94b4d84 100644 --- a/README.md +++ b/README.md @@ -377,9 +377,9 @@ client = FishAudio(httpx_client=http_client) ```python from fishaudio.exceptions import ( + APIError, AuthenticationError, RateLimitError, - ValidationError, FishAudioError, ) @@ -389,12 +389,15 @@ except AuthenticationError: print("Invalid API key") except RateLimitError: print("Rate limit exceeded") -except ValidationError as e: - print(f"Invalid request: {e}") +except APIError as e: + # Any other error response, such as 400 for a request the API rejects + print(f"API error {e.status}: {e.message}") except FishAudioError as e: - print(f"API error: {e}") + print(f"Error: {e}") ``` +A value the SDK can check before sending, such as a `speed` outside 0.5 to 2.0, raises pydantic's `ValidationError` instead, and no request is sent. `fishaudio.exceptions.ValidationError` is not raised by the SDK. + Every `APIError` carries the headers of the error response. When you contact support, include the trace id and the error code. Either can be absent. ```python diff --git a/src/fishaudio/client.py b/src/fishaudio/client.py index 11f2aa2..2398ae6 100644 --- a/src/fishaudio/client.py +++ b/src/fishaudio/client.py @@ -30,8 +30,7 @@ class FishAudio: # Generate speech audio = client.tts.convert(text="Hello world") with open("output.mp3", "wb") as f: - for chunk in audio: - f.write(chunk) + f.write(audio) # List voices voices = client.voices.list(page_size=20) @@ -114,16 +113,17 @@ class AsyncFishAudio: Example: ```python + import asyncio + from fishaudio import AsyncFishAudio async def main(): client = AsyncFishAudio(api_key="your_api_key") # Generate speech - audio = client.tts.convert(text="Hello world") - async with aiofiles.open("output.mp3", "wb") as f: - async for chunk in audio: - await f.write(chunk) + audio = await client.tts.convert(text="Hello world") + with open("output.mp3", "wb") as f: + f.write(audio) # List voices voices = await client.voices.list(page_size=20) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index e18c1df..dcd4290 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -1,5 +1,6 @@ """HTTP client wrapper for managing requests and authentication.""" +import json import os import platform import re @@ -74,6 +75,7 @@ def _raise_for_status(response: httpx.Response) -> None: If the body is a JSON object with a truthy ``message`` field, that is the message; otherwise its truthy ``detail`` field. In every other case the message is the body text, or the status phrase when the text is empty. + A field that is not a string is turned into JSON text. """ status = response.status_code data, text = _read_error_body(response) @@ -81,6 +83,10 @@ def _raise_for_status(response: httpx.Response) -> None: message = None if isinstance(data, dict): message = data.get("message") or data.get("detail") + if message and not isinstance(message, str): + # A structured field (a 422's list of problems, say) becomes text: + # APIError.message is a str. The body keeps the content as sent. + message = json.dumps(message, ensure_ascii=False) raise _api_error( status, diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index 00a9c01..d4281e8 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -1,11 +1,23 @@ """Custom exceptions for the Fish Audio SDK.""" from collections.abc import Mapping -from typing import Optional +from typing import Any, Optional import httpx +def _builds_as(error: BaseException, cls: type) -> bool: + """Whether error's class is constructed exactly as cls is (the SDK's own + construction), not by a subclass that changed __init__ or __new__, or + whose metaclass does the constructing.""" + kind = type(error) + return ( + type(kind) is type(cls) + and kind.__init__ is cls.__init__ + and kind.__new__ is cls.__new__ + ) + + class FishAudioError(Exception): """Base exception for all Fish Audio SDK errors.""" @@ -38,6 +50,17 @@ def __init__( self.headers = httpx.Headers(headers, encoding="utf-8") super().__init__(f"HTTP {status}: {message}") + def __reduce__(self) -> Any: + # Pickle (worker pools, multiprocessing) calls the class with args, + # which hold only the formatted text. For the SDK's own construction, + # pass the constructor's arguments instead (the headers as they are, + # raw bytes kept); __dict__ carries the rest. A subclass that changes + # construction pickles as any exception does. + if _builds_as(self, APIError): + args = (self.status, self.message, self.body, self.headers) + return (type(self), args, self.__dict__) + return super().__reduce__() + class AuthenticationError(APIError): """Raised when authentication fails (401).""" @@ -117,3 +140,10 @@ def __init__(self, dependency: str, install_command: str): f"Missing required dependency: {dependency}\n" f"Install it with: {install_command}" ) + + def __reduce__(self) -> Any: + # As APIError.__reduce__: the SDK's own construction only. + if _builds_as(self, DependencyError): + args = (self.dependency, self.install_command) + return (type(self), args, self.__dict__) + return super().__reduce__() diff --git a/src/fishaudio/py.typed b/src/fishaudio/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 0c6a86a..3699273 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -104,12 +104,17 @@ def transcribe( (and speaker turns, on models that return them) model: ASR model, e.g. "transcribe-2-pro" (recommended). Sent as the ``model`` header and takes precedence over one in request_options. - If not provided and request_options sets no ``model`` header, the - request runs on the API's default model, transcribe-1. + When the outgoing request carries no ``model`` header (from + this argument, request_options, or headers set on a custom + httpx client), it runs on the API's default model, transcribe-1. transcribe-1 is deprecated and will be retired on December 31, 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. - Passing "transcribe-1" emits a FutureWarning. + Pass model="transcribe-2-pro" to move to it now; a request + without a model gets no warning. "transcribe-1" given as + ``model``, or as a ``model`` header in request_options when + ``model`` is not given, emits a FutureWarning; one set only + in a custom httpx client's headers is not seen. request_options: Request-level overrides Returns: @@ -301,12 +306,17 @@ async def transcribe( (and speaker turns, on models that return them) model: ASR model, e.g. "transcribe-2-pro" (recommended). Sent as the ``model`` header and takes precedence over one in request_options. - If not provided and request_options sets no ``model`` header, the - request runs on the API's default model, transcribe-1. + When the outgoing request carries no ``model`` header (from + this argument, request_options, or headers set on a custom + httpx client), it runs on the API's default model, transcribe-1. transcribe-1 is deprecated and will be retired on December 31, 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. - Passing "transcribe-1" emits a FutureWarning. + Pass model="transcribe-2-pro" to move to it now; a request + without a model gets no warning. "transcribe-1" given as + ``model``, or as a ``model`` header in request_options when + ``model`` is not given, emits a FutureWarning; one set only + in a custom httpx client's headers is not seen. request_options: Request-level overrides Returns: diff --git a/src/fishaudio/utils/play.py b/src/fishaudio/utils/play.py index 4ff25b3..199c652 100644 --- a/src/fishaudio/utils/play.py +++ b/src/fishaudio/utils/play.py @@ -25,11 +25,25 @@ def play( Args: audio: Audio bytes or iterable of bytes - notebook: Use Jupyter notebook playback (IPython.display.Audio) - use_ffmpeg: Use ffplay for playback (default, falls back to sounddevice) + notebook: Use Jupyter notebook playback (IPython.display.Audio). + ``use_ffmpeg`` is then ignored: neither ffplay nor sounddevice + is used. + use_ffmpeg: Outside notebook mode, play with ffplay (the default). If ffplay is not + installed, DependencyError is raised; there is no fallback. + Playback falls back to sounddevice only when ffplay exits with a + non-zero status (an ffplay that reports a problem but exits with + 0 counts as played). False plays with sounddevice (the + ``[utils]`` extra). Raises: - DependencyError: If required playback tool is not installed + DependencyError: If IPython is not installed (``notebook=True``, which + is checked first), if ffplay is not installed (``use_ffmpeg=True``), or + sounddevice or soundfile cannot be imported when sounddevice is + used: any ImportError from importing them (a missing package, or + a missing native binding) is raised as DependencyError, with the + original error chained to it. Other errors from importing them + (an OSError for a missing PortAudio library, say) are raised as + they are. Examples: ```python @@ -44,7 +58,7 @@ def play( # In Jupyter notebook play(audio, notebook=True) - # Force sounddevice fallback + # Play with sounddevice instead of ffplay play(audio, use_ffmpeg=False) ``` """ diff --git a/src/fishaudio/utils/stream.py b/src/fishaudio/utils/stream.py index 3e50537..1e64d53 100644 --- a/src/fishaudio/utils/stream.py +++ b/src/fishaudio/utils/stream.py @@ -2,7 +2,7 @@ import shutil import subprocess -from collections.abc import Iterator +from collections.abc import Iterable from fishaudio.exceptions import DependencyError @@ -12,7 +12,7 @@ def _is_installed(command: str) -> bool: return shutil.which(command) is not None -def stream(audio_stream: Iterator[bytes]) -> bytes: +def stream(audio_stream: Iterable[bytes]) -> bytes: """ Stream audio in real-time while playing it with mpv. @@ -20,7 +20,7 @@ def stream(audio_stream: Iterator[bytes]) -> bytes: simultaneously captures it to return the complete audio buffer. Args: - audio_stream: Iterator of audio byte chunks + audio_stream: Audio byte chunks, such as ``client.tts.stream(...)`` Returns: Complete audio bytes after streaming finishes @@ -33,10 +33,11 @@ def stream(audio_stream: Iterator[bytes]) -> bytes: from fishaudio import FishAudio, stream client = FishAudio(api_key="...") - audio_stream = client.tts.convert(text="Hello world") - # Stream and play in real-time, get complete audio - complete_audio = stream(audio_stream) + # Stream and play in real-time, get complete audio. The with block + # closes the response even if playback fails (mpv missing, say). + with client.tts.stream(text="Hello world") as audio_stream: + complete_audio = stream(audio_stream) # Save the captured audio with open("output.mp3", "wb") as f: diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index 785a86f..c394eb0 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -5,6 +5,7 @@ """ import contextlib +import pickle import threading from http.server import BaseHTTPRequestHandler, HTTPServer @@ -15,6 +16,7 @@ from fishaudio import APIError, AsyncFishAudio, AuthenticationError, FishAudio from fishaudio.core.client_wrapper import _raise_for_status from fishaudio.exceptions import ( + DependencyError, NotFoundError, PermissionError, RateLimitError, @@ -179,3 +181,181 @@ def test_an_error_whose_body_is_not_an_object_carries_the_headers(body): with pytest.raises(APIError) as caught: _raise_for_status(response) assert caught.value.headers["x-fish-trace-id"] == "trace-123" + + +@pytest.mark.parametrize("error_class", [APIError, AuthenticationError, RateLimitError]) +def test_error_survives_pickle(error_class): + """Errors cross process boundaries (worker pools) intact.""" + error = error_class( + 429, + "Too Many Requests", + body='{"detail": "slow down"}', + headers=[("x-fish-trace-id", "t"), ("set-cookie", "a"), ("set-cookie", "b")], + ) + copy = pickle.loads(pickle.dumps(error)) + assert type(copy) is error_class + assert (copy.status, copy.message, copy.body) == ( + error.status, + error.message, + error.body, + ) + assert copy.headers.multi_items() == error.headers.multi_items() + assert str(copy) == str(error) + + +def test_dependency_error_survives_pickle(): + copy = pickle.loads(pickle.dumps(DependencyError("sounddevice", "pip install x"))) + assert (copy.dependency, copy.install_command) == ("sounddevice", "pip install x") + + +def test_error_pickle_keeps_raw_header_bytes_and_extra_state(): + headers = httpx.Headers([(b"x-raw", b"\xff"), (b"x-fish-trace-id", b"t")]) + error = AuthenticationError(401, "Unauthorized", headers=headers) + error.job = "job 42" # extra state a caller attached, as add_note does + copy = pickle.loads(pickle.dumps(error)) + assert copy.headers.raw == error.headers.raw + assert copy.job == "job 42" + if hasattr(error, "add_note"): # Python 3.11+ + error.add_note("job 42") + assert pickle.loads(pickle.dumps(error)).__notes__ == ["job 42"] + + +# A caller's subclasses that change construction pickle exactly as any +# exception does (as on 1.8.1): these tests pass on origin/main too. + + +class _QuotaError(APIError): + """One constructor argument, kept in args.""" + + def __init__(self, job): + super().__init__(429, f"quota for {job}") + self.args = (job,) + self.job = job + + +class _JobError(APIError): + """A __new__ that needs its argument.""" + + def __new__(cls, job): + return super().__new__(cls, job) + + def __init__(self, job): + super().__init__(500, f"job {job} failed") + self.args = (job,) + self.job = job + + +class _SlotError(APIError): + """A field kept in a slot, set in __init__.""" + + __slots__ = ("job",) + + def __init__(self, job): + super().__init__(400, f"job {job} rejected") + self.args = (job,) + self.job = job + + +class _OneArgument(type): + """A metaclass that constructs the error from one argument.""" + + def __call__(cls, job): + error = cls.__new__(cls) + APIError.__init__(error, 409, f"job {job} conflicts") + error.args = (job,) + error.job = job + return error + + +class _MetaError(APIError, metaclass=_OneArgument): + """__init__ and __new__ are the SDK's; the metaclass constructs.""" + + +class _ToolMissing(DependencyError): + def __init__(self, tool): + super().__init__(tool, f"pip install {tool}") + self.args = (tool,) + + +def _raise(kind, job): + raise kind(job) + + +def _double(value): + return value * 2 + + +@pytest.mark.parametrize( + "kind", [_QuotaError, _JobError, _SlotError, _MetaError, _ToolMissing] +) +def test_a_subclass_that_changes_construction_pickles_as_any_exception(kind): + error = kind("job 7") + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + copy = pickle.loads(pickle.dumps(error, protocol)) + assert type(copy) is kind + assert copy.args == error.args + assert str(copy) == str(error) + if kind is not _ToolMissing: + assert (copy.job, copy.status, copy.message) == ( + error.job, + error.status, + error.message, + ) + + +@pytest.mark.parametrize("kind", [_QuotaError, _JobError, _MetaError]) +def test_a_worker_pool_delivers_a_subclass_error_and_takes_the_next_job(kind): + from concurrent.futures import ProcessPoolExecutor + + with ProcessPoolExecutor(max_workers=1) as pool: + with pytest.raises(kind) as caught: + pool.submit(_raise, kind, "job 7").result(timeout=60) + assert caught.value.job == "job 7" + assert pool.submit(_double, 21).result(timeout=60) == 42 + + +def test_a_worker_pool_delivers_the_sdks_own_error_and_takes_the_next_job(): + from concurrent.futures import ProcessPoolExecutor + + with ProcessPoolExecutor(max_workers=1) as pool: + with pytest.raises(RateLimitError) as caught: + pool.submit(_raise_rate_limit).result(timeout=60) + assert caught.value.headers.multi_items() == [ + ("set-cookie", "a"), + ("set-cookie", "b"), + ] + assert pool.submit(_double, 21).result(timeout=60) == 42 + + +def _raise_rate_limit(): + raise RateLimitError( + 429, "Too Many Requests", headers=[("set-cookie", "a"), ("set-cookie", "b")] + ) + + +def test_realtime_asr_error_survives_pickle(): + from fishaudio.exceptions import ASRRealtimeError + + error = ASRRealtimeError( + "bad config", error_type="invalid_config", request_id="req", close_code=4400 + ) + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + copy = pickle.loads(pickle.dumps(error, protocol)) + assert copy.__dict__ == error.__dict__ + assert copy.args == error.args + + +def test_a_structured_message_becomes_text_and_the_body_keeps_it(): + import json + + detail = [{"loc": ["body", "text"], "msg": "field required"}] + response = httpx.Response( + 422, + json={"detail": detail}, + request=httpx.Request("POST", "https://api.fish.audio/v1/tts"), + ) + with pytest.raises(APIError) as caught: + _raise_for_status(response) + assert isinstance(caught.value.message, str) + assert json.loads(caught.value.message) == detail + assert json.loads(caught.value.body)["detail"] == detail diff --git a/tests/unit/test_type_hints.py b/tests/unit/test_type_hints.py index 1fa5315..c05e44f 100644 --- a/tests/unit/test_type_hints.py +++ b/tests/unit/test_type_hints.py @@ -1,10 +1,12 @@ """Annotations on the public stream classes resolve at runtime.""" import typing +from pathlib import Path import pytest from typing_extensions import Self +import fishaudio from fishaudio.core.iterators import ( AsyncAudioStream, AsyncTTSTimestampStream, @@ -57,3 +59,8 @@ def test_stream_method_annotations_resolve(method): ) def test_enter_methods_resolve_to_self(method): assert typing.get_type_hints(method) == {"return": Self} + + +def test_package_is_marked_as_typed(): + """PEP 561: without py.typed, mypy reports the installed package as untyped.""" + assert (Path(fishaudio.__file__).parent / "py.typed").is_file()