Skip to content

[Plugin] Palabra TTS (+ voice cloning) - #627

Open
DaemonLoki wants to merge 3 commits into
mainfrom
add-palabra-tts
Open

[Plugin] Palabra TTS (+ voice cloning)#627
DaemonLoki wants to merge 3 commits into
mainfrom
add-palabra-tts

Conversation

@DaemonLoki

@DaemonLoki DaemonLoki commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Why

  • Support for Palabra.ai's TTS and voice cloning
  • We didn't have support for it, yet

Changes

  • add regular TTS plugin
  • add support for voice cloning
  • examples for both use-cases
palabra-tts.mp4

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added the Palabra plugin to the workspace and optional dependencies. Implemented persistent WebSocket streaming TTS with cancellation, retries, idle timeouts, and PCM output. Added REST-based voice cloning with validation, polling, quota management, and lifecycle operations. Added public exports, tests, runnable examples, project configuration, and documentation.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (6)
plugins/palabra/vision_agents/plugins/palabra/__init__.py (1)

1-5: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use an explicit standard-library import.

Import extend_path from pkgutil before the relative imports. Replace __import__("pkgutil") with the imported symbol.

Proposed change
+from pkgutil import extend_path
+
 from .tts import TTS, WS_URL_EU, WS_URL_US, PalabraTTSError
 from .voices import ClonedVoice, PalabraVoiceError, VoiceLimits, Voices
 
 # Re-export under the new namespace for convenience
-__path__ = __import__("pkgutil").extend_path(__path__, __name__)
+__path__ = extend_path(__path__, __name__)

As per coding guidelines, imports must be at module scope and ordered standard library before local package imports.

Source: Coding guidelines

plugins/palabra/vision_agents/plugins/palabra/voices.py (1)

313-320: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Bare dict annotations do not meet the typing guideline.

_request uses json: Optional[dict] and params: Optional[dict] and returns dict. _parse_voice (line 103) takes data: dict and _upload_sample (line 274) takes sample: dict. The guidelines require parameterized generics. Note that clone already builds payload: dict[str, object] and list already builds params: dict[str, str | int], so the concrete types are known.

Also annotate __aexit__ (line 343) rather than leaving *_ untyped.

Proposed change
     async def _request(
         self,
         method: str,
         path: str,
         *,
-        json: Optional[dict] = None,
-        params: Optional[dict] = None,
-    ) -> dict:
+        json: Optional[dict[str, object]] = None,
+        params: Optional[dict[str, str | int]] = None,
+    ) -> dict[str, object]:
-def _parse_voice(data: dict) -> ClonedVoice:
+def _parse_voice(data: dict[str, object]) -> ClonedVoice:
     async def _upload_sample(
-        self, sample: dict, filename: str, data: bytes, mime_type: str
+        self, sample: dict[str, object], filename: str, data: bytes, mime_type: str
     ) -> None:
-    async def __aexit__(self, *_) -> None:
+    async def __aexit__(
+        self,
+        exc_type: Optional[type[BaseException]],
+        exc: Optional[BaseException],
+        tb: Optional[TracebackType],
+    ) -> None:
         await self.close()

_parse_voice and limits then need explicit narrowing (cast or local str(...)/int(...) conversion) to stay type-clean. If that churn is unwanted, a small TypedDict per endpoint response is the cleaner alternative.

As per coding guidelines: "Use type annotations everywhere. Modern syntax: X | Y unions, dict[str, T] generics, full Callable signatures".

Source: Coding guidelines

plugins/palabra/tests/test_voices.py (2)

89-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the type assertion.

assert isinstance(listed, list) restates the annotated return type of list(). It tests no behavior. The second assertion already covers the useful property.

Proposed change
         listed = await voices.list(page_size=5)
 
-        assert isinstance(listed, list)
         assert all(voice.voice_id for voice in listed)
+        assert len(listed) <= 5

As per path instructions: "Assert behavior and outputs, not initialization or call paths" and "Discourage verbosity and redundant tests".

Source: Path instructions


95-131: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Align the cloned-TTS audio path to one streaming API shape.

pytest-timeout is declared in the dev dependencies, so pytest.mark.timeout(300) is supported. Palabra.TTS also supports both send_iter(line) and stream_audio(...), but use one iteration shape for this test. stream_audio(...) already returns an async iterator, so do not await it before iteration.

plugins/palabra/example/clone_voice.py (1)

50-85: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the duplicated WAV writer.

write_sample and speak repeat the same five-line WAV write plus the same duration calculation. One helper covers both.

Proposed change
+def _write_wav(path: Path, audio: bytes, rate: int) -> float:
+    """Write mono 16-bit PCM to ``path`` and return its duration in seconds."""
+    with wave.open(str(path), "wb") as wav:
+        wav.setnchannels(1)
+        wav.setsampwidth(2)
+        wav.setframerate(rate)
+        wav.writeframes(audio)
+    return len(audio) / 2 / rate
+
+
 async def write_sample(tts: palabra.TTS, path: Path) -> float:
     """Synthesize the passage into a WAV file and return its duration."""
     audio = bytearray()
     for line in SAMPLE_SCRIPT:
         async for chunk in tts.send_iter(line):
             if chunk.data is not None:
                 audio += chunk.data.samples.tobytes()
-
-    with wave.open(str(path), "wb") as wav:
-        wav.setnchannels(1)
-        wav.setsampwidth(2)
-        wav.setframerate(tts.sample_rate)
-        wav.writeframes(audio)
-    return len(audio) / 2 / tts.sample_rate
+    return _write_wav(path, bytes(audio), tts.sample_rate)
             if chunk.data is not None:
                 audio += chunk.data.samples.tobytes()
         rate = tts.sample_rate
     finally:
         await tts.close()
-
-    with wave.open(str(path), "wb") as wav:
-        wav.setnchannels(1)
-        wav.setsampwidth(2)
-        wav.setframerate(rate)
-        wav.writeframes(audio)
-    return len(audio) / 2 / rate
+    return _write_wav(path, bytes(audio), rate)
plugins/palabra/tests/test_tts.py (1)

36-63: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace private-state assertions with public behavior tests.

These tests depend on private fields. Refactoring serialization or connection storage can break them without changing public behavior.

  • plugins/palabra/tests/test_tts.py#L36-L63: verify configured synthesis through the public TTS API instead of parsing _init_message.
  • plugins/palabra/tests/test_tts.py#L178-L188: verify successful consecutive utterances instead of comparing _websocket identity.

As per coding guidelines and path instructions, tests must assert behavior and outputs, not initialization or call paths.

Sources: Coding guidelines, Path instructions


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c292ef97-130c-43f1-b99f-cefa4b366c57

📥 Commits

Reviewing files that changed from the base of the PR and between 7b5084c and e24f460.

⛔ Files ignored due to path filters (2)
  • plugins/palabra/example/palabra_smoke.wav is excluded by !**/*.wav
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (18)
  • CHANGELOG.md
  • agents-core/pyproject.toml
  • plugins/palabra/README.md
  • plugins/palabra/example/.env.example
  • plugins/palabra/example/README.md
  • plugins/palabra/example/clone_voice.py
  • plugins/palabra/example/main.py
  • plugins/palabra/example/pyproject.toml
  • plugins/palabra/example/tts_smoke.py
  • plugins/palabra/py.typed
  • plugins/palabra/pyproject.toml
  • plugins/palabra/tests/__init__.py
  • plugins/palabra/tests/test_tts.py
  • plugins/palabra/tests/test_voices.py
  • plugins/palabra/vision_agents/plugins/palabra/__init__.py
  • plugins/palabra/vision_agents/plugins/palabra/tts.py
  • plugins/palabra/vision_agents/plugins/palabra/voices.py
  • pyproject.toml

Comment thread CHANGELOG.md Outdated
Comment thread plugins/palabra/vision_agents/plugins/palabra/tts.py
Comment thread plugins/palabra/vision_agents/plugins/palabra/tts.py
Comment thread plugins/palabra/vision_agents/plugins/palabra/voices.py Outdated
Comment thread plugins/palabra/vision_agents/plugins/palabra/voices.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 62b2ee99-719f-431c-8913-09380fa17bda

📥 Commits

Reviewing files that changed from the base of the PR and between e24f460 and 8d76d64.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • plugins/palabra/tests/test_tts.py
  • plugins/palabra/tests/test_voices.py
  • plugins/palabra/vision_agents/plugins/palabra/tts.py
  • plugins/palabra/vision_agents/plugins/palabra/voices.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • plugins/palabra/tests/test_tts.py
  • CHANGELOG.md
  • plugins/palabra/vision_agents/plugins/palabra/voices.py
  • plugins/palabra/vision_agents/plugins/palabra/tts.py

Comment on lines +128 to +132
before = await voices.limits()
with pytest.raises(PalabraVoiceError):
await voices.clone("Rejected sample", sample, timeout=180, poll_interval=5)

assert (await voices.limits()).total == before.total

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Delete a voice if the rejection assertion fails.

If Palabra accepts the sample, voices.clone() returns a voice and pytest.raises fails. The test has no cleanup path for that voice. It can leave quota allocated and block later cloning tests.

Proposed fix
         before = await voices.limits()
-        with pytest.raises(PalabraVoiceError):
-            await voices.clone("Rejected sample", sample, timeout=180, poll_interval=5)
+        created_voice: palabra.ClonedVoice | None = None
+        try:
+            with pytest.raises(PalabraVoiceError):
+                created_voice = await voices.clone(
+                    "Rejected sample", sample, timeout=180, poll_interval=5
+                )
+        finally:
+            if created_voice is not None:
+                await voices.delete(created_voice.voice_id)
 
         assert (await voices.limits()).total == before.total

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant