diff --git a/ttstoy/README.md b/ttstoy/README.md index 68cd960..acb19cd 100644 --- a/ttstoy/README.md +++ b/ttstoy/README.md @@ -11,6 +11,7 @@ A RedBot cog for text-to-speech in voice chat with multiple TTS engines, emoji s | `dectalk` | Classic 1980s robotic voice | DECTalk server | | `morshu` | Morshu from CD-i Zelda | g2p_en, numpy, pydub | | `vox` | Black Mesa VOX announcer | Built-in | +| `piper` | Local Piper neural TTS, fast voices | Piper HTTP server | Switch modes: `[p]ttstoy mode ` @@ -75,6 +76,29 @@ DECTalk voices are controlled in-text: `[:np]` Paul, `[:nb]` Betty, `[:nh]` Harr | `[p]ttstoy voxpack [vox\|vox2]` | Switch VOX voice pack | | `[p]ttstoy voxwords` | List available words | +### Piper + +| Command | Description | +|---------|-------------| +| `[p]ttstoy piperurl [url]` | Show or set the Piper server URL (default http://127.0.0.1:5006) | +| `[p]ttstoy pipervoice [model_id]` | Set the Piper voice model (e.g. en_US-ryan-medium); `reset` for server default | + +Piper speaks via a Piper HTTP server's `/synthesize` endpoint. Any model id +whose `.onnx` is in the server's data dir can be selected, even if it is not +in the `/voices` listing. + +### Accessibility + +Accessibility mode forces a single robotic/neural engine, disables emoji SFX, +and auto-reads the side chat of the voice channel the bot is in (no command +prefix needed). The first message from a user since someone else last spoke is +prefixed `Name said:`; links, images, and files are announced instead of read. + +| Command | Description | +|---------|-------------| +| `[p]ttstoy accessibility` | Toggle accessibility mode | +| `[p]ttstoy accessibilityengine [dectalk\|piper]` | Choose the engine accessibility uses | + ## Emoji SFX Include emoji in your TTS text to trigger sound effects: diff --git a/ttstoy/ttstoy.py b/ttstoy/ttstoy.py index cc8fc5f..ab47bf0 100644 --- a/ttstoy/ttstoy.py +++ b/ttstoy/ttstoy.py @@ -80,6 +80,7 @@ DECTALK_VOICES = { } CHATTERBOX_DEFAULT_URL = "http://127.0.0.1:8099" +PIPER_DEFAULT_URL = "http://127.0.0.1:5006" _DEFAULT_EMOJI_SFX = { "🎉": "party", @@ -140,7 +141,7 @@ VOICE_SWITCH_PATTERN = re.compile( r"\[([a-zA-Z]+)(?:\|([^\]]+))?\]" ) -VALID_VOICE_MODES = {"minimax", "chatterbox", "dectalk", "morshu", "vox"} +VALID_VOICE_MODES = {"minimax", "chatterbox", "dectalk", "morshu", "vox", "piper"} # Pattern for detecting a URL/link anywhere in message text (accessibility auto-read) URL_PATTERN = re.compile(r"https?://\S+", re.IGNORECASE) @@ -403,7 +404,10 @@ class TtsToy(Cog): tts_mode="minimax", chatterbox_api_url=CHATTERBOX_DEFAULT_URL, dectalk_api_url=f"http://127.0.0.1:33001", + piper_api_url=PIPER_DEFAULT_URL, + piper_voice=None, # optional model_id override for the piper server accessibility_mode=False, + accessibility_engine="dectalk", # "dectalk" or "piper" for auto-read + forced TTS vox_pack="vox", webui_tts_channel_id=None, # channel to post web UI TTS transcripts/audio webui_public_url="https://ttstoy.kingstons-scrapyard.net", # public URL shown in login DMs @@ -497,6 +501,10 @@ class TtsToy(Cog): """Get DECTalk API URL.""" return await self.config.dectalk_api_url() + async def _get_piper_api_url(self): + """Get Piper TTS Server API URL.""" + return await self.config.piper_api_url() + async def _get_effective_minimax_voice(self, user: discord.abc.User) -> str: mode = await self._get_tts_mode() @@ -708,6 +716,55 @@ class TtsToy(Cog): with open(audio_path, "wb") as f: f.write(r.content) + def _save_piper_tts(self, text: str, audio_path: str, piper_url: str, voice: str = None, volume_db: float = 0.0): + """ + Generate TTS audio using a Piper HTTP server's /synthesize endpoint. + + The server returns a WAV. `voice` is an optional model id (the .onnx + filename without extension); when omitted the server's default model + is used. + """ + url = f"{piper_url.rstrip('/')}/synthesize" + payload = {"text": text} + if voice: + payload["voice"] = voice + log.info(f"[Piper] POST {url} | voice={voice} | text={text[:80]!r}") + try: + r = requests.post(url, json=payload, timeout=120) + log.info(f"[Piper] Response: {r.status_code} | {len(r.content)} bytes") + r.raise_for_status() + except requests.exceptions.HTTPError: + try: + body = r.text[:500] + except Exception: + body = "(could not read body)" + log.error(f"[Piper] HTTP {r.status_code} error. Body: {body}") + raise + + if len(r.content) < 100: + raise RuntimeError(f"Piper returned too little audio data ({len(r.content)} bytes)") + + # Apply volume offset if non-zero + if volume_db and volume_db != 0.0: + tmp_raw = audio_path + ".raw.wav" + with open(tmp_raw, "wb") as f: + f.write(r.content) + try: + subprocess.run( + [ + "ffmpeg", "-y", "-i", tmp_raw, + "-filter:a", f"volume={volume_db}dB", + "-vn", audio_path, + ], + check=True, capture_output=True, text=True, + ) + finally: + if os.path.exists(tmp_raw): + os.remove(tmp_raw) + else: + with open(audio_path, "wb") as f: + f.write(r.content) + def _ensure_sfx_folders(self): self.sfx_root.mkdir(parents=True, exist_ok=True) # Seed the JSON map file if it doesn't exist yet @@ -821,7 +878,7 @@ class TtsToy(Cog): ) subprocess.run(cmd, check=True, capture_output=True, text=True) - def _save_prompt_audio(self, api_key, model, voice_id, text, output_path: str, sfx_volume: int, mode="minimax", dectalk_url=None, vox_pack="vox", chatterbox_url=None, chatterbox_temperature=None, chatterbox_exaggeration=None, chatterbox_volume_db=0.0, chatterbox_speed=None, all_chatterbox_voices=None): + def _save_prompt_audio(self, api_key, model, voice_id, text, output_path: str, sfx_volume: int, mode="minimax", dectalk_url=None, vox_pack="vox", chatterbox_url=None, chatterbox_temperature=None, chatterbox_exaggeration=None, chatterbox_volume_db=0.0, chatterbox_speed=None, all_chatterbox_voices=None, piper_url=None, piper_voice=None): """ Save prompt audio with SFX and multi-voice support. @@ -841,6 +898,7 @@ class TtsToy(Cog): mode, dectalk_url, vox_pack, chatterbox_url, chatterbox_temperature, chatterbox_exaggeration, chatterbox_volume_db, chatterbox_speed, + piper_url, piper_voice, ) # Multi-voice path: render each voice segment separately, then concat @@ -887,6 +945,7 @@ class TtsToy(Cog): api_key, model, dectalk_url, vox_pack, chatterbox_url, chatterbox_temperature, chatterbox_exaggeration, chatterbox_volume_db, chatterbox_speed, + piper_url, piper_voice, ) all_parts.append(part_path) @@ -900,7 +959,8 @@ class TtsToy(Cog): def _render_tts_part(self, text, part_path, mode, voice_id, api_key, model, dectalk_url, vox_pack, chatterbox_url, - cb_temp, cb_exag, cb_vol_db, cb_speed): + cb_temp, cb_exag, cb_vol_db, cb_speed, + piper_url=None, piper_voice=None): """Render a single TTS text segment with the given engine and voice.""" if mode == "morshu": self._save_morshu_tts(text, part_path) @@ -914,13 +974,18 @@ class TtsToy(Cog): temperature=cb_temp, exaggeration=cb_exag, volume_db=cb_vol_db, speed_factor=cb_speed, ) + elif mode == "piper": + if not piper_url: + raise RuntimeError("Piper API URL not configured") + self._save_piper_tts(text, part_path, piper_url, voice=piper_voice) else: # minimax or dectalk self._save_minimax_tts(api_key, model, voice_id, text, part_path, mode, dectalk_url) def _render_single_mode(self, api_key, model, voice_id, text, output_path, sfx_volume, mode, dectalk_url, vox_pack, chatterbox_url, - cb_temp, cb_exag, cb_vol_db, cb_speed): + cb_temp, cb_exag, cb_vol_db, cb_speed, + piper_url=None, piper_voice=None): """Original single-mode render path (no inline voice switches).""" # Morshu mode bypasses SFX splitting if mode == "morshu": @@ -968,6 +1033,41 @@ class TtsToy(Cog): shutil.rmtree(temp_dir, ignore_errors=True) return {"language": "CHATTERBOX"} + # Piper mode + if mode == "piper": + if not piper_url: + raise RuntimeError("Piper API URL not configured") + segments = self._split_prompt_segments(text) + if not segments: + raise RuntimeError("Prompt had no content to synthesize.") + if not any(kind == "sfx" for kind, _ in segments): + self._save_piper_tts(text, output_path, piper_url, voice=piper_voice) + return {"language": "PIPER"} + part_paths = [] + temp_dir = os.path.join(self.tts_storage, f"parts_{os.path.basename(output_path)}") + os.makedirs(temp_dir, exist_ok=True) + try: + for index, (kind, value) in enumerate(segments): + part_path = os.path.join(temp_dir, f"part_{index:03}.mp3") + if kind == "tts": + if not value.strip(): + continue + self._save_piper_tts(value, part_path, piper_url, voice=piper_voice) + else: + sfx_source = self._get_sfx_source_for_trigger(value) + if sfx_source is None: + normalized_text = _normalize_sfx_trigger(value) + self._save_piper_tts(normalized_text, part_path, piper_url, voice=piper_voice) + else: + self._render_sfx_part(sfx_source, part_path, sfx_volume) + part_paths.append(part_path) + if not part_paths: + raise RuntimeError("Prompt resulted in no playable audio segments.") + self._concat_audio_parts(part_paths, output_path) + finally: + shutil.rmtree(temp_dir, ignore_errors=True) + return {"language": "PIPER"} + # MiniMax / DECTalk path segments = self._split_prompt_segments(text) if not segments: @@ -1241,6 +1341,7 @@ class TtsToy(Cog): "- `dectalk` - Use DECTalk API (classic robotic voice)", f"- `morshu` - Use MorshuTalk ({'available' if MORSHU_AVAILABLE else 'not installed'})", f"- `vox` - Black Mesa VOX announcer ({'available' if VOX_AVAILABLE else 'not installed'})", + "- `piper` - Use a local Piper TTS server (fast neural voices)", "", ] @@ -1267,8 +1368,8 @@ class TtsToy(Cog): # Accept "local" as alias for "chatterbox" for backwards compat if mode == "local": mode = "chatterbox" - if mode not in ["minimax", "chatterbox", "dectalk", "morshu", "vox"]: - return await ctx.send("Mode must be `minimax`, `chatterbox`, `dectalk`, `morshu`, or `vox`.") + if mode not in ["minimax", "chatterbox", "dectalk", "morshu", "vox", "piper"]: + return await ctx.send("Mode must be `minimax`, `chatterbox`, `dectalk`, `morshu`, `vox`, or `piper`.") if mode == "morshu" and not MORSHU_AVAILABLE: return await ctx.send( @@ -1312,6 +1413,15 @@ class TtsToy(Cog): "`sudo systemctl status dectalk-tts-server`" ) await ctx.send(msg) + elif mode == "piper": + piper_url = await self._get_piper_api_url() + piper_voice = await self.config.piper_voice() + await ctx.send( + f"TTS mode set to **PIPER**\n" + f"Using Piper TTS server at: `{piper_url}`\n" + f"Voice: `{piper_voice or 'server default'}` " + f"(change with `{ctx.clean_prefix}ttstoy pipervoice `)" + ) else: await ctx.send( f"✅ TTS mode set to {mode_emoji} **MINIMAX**\n" @@ -1948,6 +2058,84 @@ class TtsToy(Cog): else: await ctx.send("**Accessibility mode disabled.** Normal TTS settings restored.") + @ttstoy_group.command(name="accessibilityengine", aliases=["accessengine", "accessibilitytts"]) + @commands.is_owner() + async def accessibility_engine_cmd(self, ctx: commands.Context, engine: Optional[str] = None): + """ + Show or set the engine accessibility mode uses: dectalk or piper. + + - `[p]ttstoy accessibilityengine` -> show current engine + - `[p]ttstoy accessibilityengine piper` -> use the Piper TTS server + - `[p]ttstoy accessibilityengine dectalk` -> use the DECTalk server + """ + if engine is None: + current = await self.config.accessibility_engine() + return await ctx.send(f"Accessibility engine: `{current}`\nSet with `{ctx.clean_prefix}ttstoy accessibilityengine `") + + engine = engine.strip().lower() + if engine not in ("dectalk", "piper"): + return await ctx.send("Engine must be `dectalk` or `piper`.") + await self.config.accessibility_engine.set(engine) + await ctx.send(f"Accessibility engine set to `{engine}`.") + + @ttstoy_group.command(name="piperurl") + @commands.is_owner() + async def piper_url_cmd(self, ctx: commands.Context, url: Optional[str] = None): + """ + Show or set the Piper TTS server URL. + + - `[p]ttstoy piperurl` -> show current URL (and reachability) + - `[p]ttstoy piperurl http://127.0.0.1:5006` -> set URL + """ + if url is None: + current = await self._get_piper_api_url() + lines = [f"Piper URL: `{current}`"] + try: + r = requests.get(f"{current.rstrip('/')}/", timeout=2) + lines.append("Piper server is reachable" if r.status_code == 200 else f"Piper server returned status {r.status_code}") + except Exception as e: + lines.append(f"Cannot reach Piper server: {e}") + return await ctx.send("\n".join(lines)) + + url = url.strip().rstrip('/') + if not url.startswith(('http://', 'https://')): + return await ctx.send("URL must start with http:// or https://") + await self.config.piper_api_url.set(url) + await ctx.send(f"Piper URL set to: `{url}`") + + @ttstoy_group.command(name="pipervoice") + @commands.is_owner() + async def piper_voice_cmd(self, ctx: commands.Context, voice: Optional[str] = None): + """ + Show or set the Piper voice (model id, e.g. en_US-ryan-medium). + + - `[p]ttstoy pipervoice` -> show current voice and list available models + - `[p]ttstoy pipervoice en_US-ryan-medium` -> set the model id + - `[p]ttstoy pipervoice reset` -> use the server default model + """ + piper_url = await self._get_piper_api_url() + if voice is None: + current = await self.config.piper_voice() + lines = [f"Piper voice: `{current or 'server default'}`"] + try: + r = requests.get(f"{piper_url.rstrip('/')}/voices", timeout=3) + if r.status_code == 200: + data = r.json() + names = list(data.keys()) if isinstance(data, dict) else [v.get("key") or v.get("name") for v in data] + names = [n for n in names if n] + if names: + lines.append("Available: " + ", ".join(f"`{n}`" for n in names[:40])) + except Exception: + pass + return await ctx.send("\n".join(lines)) + + voice = voice.strip() + if voice.lower() == "reset": + await self.config.piper_voice.set(None) + return await ctx.send("Piper voice reset to the server default model.") + await self.config.piper_voice.set(voice) + await ctx.send(f"Piper voice set to: `{voice}`") + @ttstoy_group.command(name="voxpack") @commands.is_owner() async def vox_pack_cmd(self, ctx: commands.Context, pack: Optional[str] = None): @@ -2504,7 +2692,12 @@ class TtsToy(Cog): spoken = f"{message.author.display_name} said: {spoken}" self._access_last_speaker[guild.id] = message.author.id + engine = await self.config.accessibility_engine() + if engine not in ("dectalk", "piper"): + engine = "dectalk" dectalk_url = await self._get_dectalk_api_url() + piper_url = await self._get_piper_api_url() + piper_voice = await self.config.piper_voice() sfx_volume = await self.config.sfx_volume() self.tts_storage.mkdir(parents=True, exist_ok=True) @@ -2514,10 +2707,11 @@ class TtsToy(Cog): await asyncio.to_thread( self._save_prompt_audio, None, None, None, spoken, audio_path, sfx_volume, - "dectalk", dectalk_url, "vox", None, None, None, 0.0, None, + engine, dectalk_url, "vox", None, None, None, 0.0, None, None, + piper_url, piper_voice, ) except Exception: - log.exception("[Accessibility] Failed to generate DECTalk audio") + log.exception("[Accessibility] Failed to generate %s audio", engine) return if not os.path.exists(audio_path): @@ -2580,12 +2774,17 @@ class TtsToy(Cog): chatterbox_url = await self._get_chatterbox_api_url() dectalk_url = await self._get_dectalk_api_url() + piper_url = await self._get_piper_api_url() + piper_voice = await self.config.piper_voice() api_key, model, _ = await self._get_minimax_settings() - # Accessibility mode: force dectalk, strip emoji SFX + # Accessibility mode: force the configured accessibility engine + # (dectalk or piper), strip emoji SFX accessibility = await self.config.accessibility_mode() if accessibility: - mode = "dectalk" + mode = await self.config.accessibility_engine() + if mode not in ("dectalk", "piper"): + mode = "dectalk" # Strip emoji triggers so they're read as text, not played as SFX text = EMOJI_CANDIDATE_PATTERN.sub( lambda m: _normalize_sfx_trigger(m.group(0)) if _normalize_sfx_trigger(m.group(0)) in EMOJI_SFX_FOLDERS else m.group(0), @@ -2630,6 +2829,15 @@ class TtsToy(Cog): except Exception as e: return await ctx.send(f"❌ Cannot reach DECTalk API: {e}\nMake sure the server is running at `{dectalk_url}`") + if mode == "piper": + # Test Piper API availability + try: + r = requests.get(f"{piper_url.rstrip('/')}/", timeout=2) + if r.status_code != 200: + return await ctx.send(f"❌ Piper TTS not responding (status {r.status_code}). Check if server is running.") + except Exception as e: + return await ctx.send(f"❌ Cannot reach Piper TTS: {e}\nMake sure the server is running at `{piper_url}`") + voice_id = await self._get_effective_minimax_voice(ctx.author) sfx_volume = await self.config.sfx_volume() vox_pack = await self.config.vox_pack() @@ -2663,7 +2871,7 @@ class TtsToy(Cog): try: result = await asyncio.to_thread( - self._save_prompt_audio, api_key, model, voice_id, text, audio_path, sfx_volume, mode, dectalk_url, vox_pack, chatterbox_url, cb_temp, cb_exag, cb_vol_db, cb_speed, all_cb_voices + self._save_prompt_audio, api_key, model, voice_id, text, audio_path, sfx_volume, mode, dectalk_url, vox_pack, chatterbox_url, cb_temp, cb_exag, cb_vol_db, cb_speed, all_cb_voices, piper_url, piper_voice ) detected_language = result.get("language") if result else None except Exception as e: