From 2a6278dd7955e68db03576ed7abc3e4cb494f860 Mon Sep 17 00:00:00 2001 From: kingston Date: Mon, 19 Oct 2026 00:18:38 -0500 Subject: [PATCH] ttstoy: persist accessibility voices across sessions --- ttstoy/ttstoy.py | 101 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 81 insertions(+), 20 deletions(-) diff --git a/ttstoy/ttstoy.py b/ttstoy/ttstoy.py index 77dc0e9..12f7863 100644 --- a/ttstoy/ttstoy.py +++ b/ttstoy/ttstoy.py @@ -435,6 +435,14 @@ class TtsToy(Cog): webui_tts_channel_id=None, # per-guild channel for web UI TTS posts ) + # Per-member (guild+user) persistent accessibility voice. Survives + # reloads/restarts. engine_map: {"dectalk": voice, "piper": voice} + # with an "explicit" flag so auto-assignments and user picks are + # distinguished across restarts. + self.config.register_member( + access_voice={}, # {engine: {"voice": str, "explicit": bool}} + ) + self.config.register_user( minimax_voice=None, chatterbox_voices=[], # list of voice filenames this user has uploaded @@ -2078,18 +2086,15 @@ class TtsToy(Cog): """Enable accessibility mode.""" await self.config.accessibility_mode.set(True) engine = await self.config.accessibility_engine() - # Fresh session: clear any lingering per-user voice assignments. + # Keep persisted per-user voices; only reset the name-prefix tracker. if ctx.guild: - self._access_user_override.pop(ctx.guild.id, None) - self._access_auto_voice.pop(ctx.guild.id, None) - self._access_assign_idx.pop(ctx.guild.id, None) self._access_last_speaker.pop(ctx.guild.id, None) await ctx.send( "**Accessibility mode started.**\n" f"- Engine: `{engine}`\n" "- Emoji SFX disabled (emojis read as text instead)\n" "- Auto-reads the side chat of the voice channel the bot is in (no command prefix needed)\n" - "- Each speaker is auto-assigned a distinct voice so they can be told apart\n" + "- Each speaker keeps a distinct voice so they can be told apart (saved between sessions)\n" f"- Change your own voice with `{ctx.clean_prefix}ttstoy accessibility voice`" ) @@ -2098,13 +2103,11 @@ class TtsToy(Cog): async def accessibility_stop(self, ctx: commands.Context): """Disable accessibility mode.""" await self.config.accessibility_mode.set(False) - # Drop all in-memory per-user voice assignments (never persisted anyway). + # Keep persisted per-user voices across stop/start; only reset the + # name-prefix tracker. if ctx.guild: - self._access_user_override.pop(ctx.guild.id, None) - self._access_auto_voice.pop(ctx.guild.id, None) - self._access_assign_idx.pop(ctx.guild.id, None) self._access_last_speaker.pop(ctx.guild.id, None) - await ctx.send("**Accessibility mode stopped.** Normal TTS settings restored.") + await ctx.send("**Accessibility mode stopped.** Normal TTS settings restored. Saved voices are kept.") @accessibility_group.command(name="engine", aliases=["tts"]) @commands.is_owner() @@ -2123,12 +2126,10 @@ class TtsToy(Cog): if engine not in ("dectalk", "piper"): return await ctx.send("Engine must be `dectalk` or `piper`.") await self.config.accessibility_engine.set(engine) - if ctx.guild: - # Clear only auto-assignments; explicit overrides persist and are - # re-validated against the new engine's pool on next resolve. - self._access_auto_voice.pop(ctx.guild.id, None) - self._access_assign_idx.pop(ctx.guild.id, None) - await ctx.send(f"Accessibility engine set to `{engine}`. Auto-assigned voices reset; your own picks are kept if valid for `{engine}`.") + # Keep voices. The resolver reassigns any stored voice that is not valid + # for the new engine's pool and persists the replacement, so nothing is + # wiped here. + await ctx.send(f"Accessibility engine set to `{engine}`. Saved voices are kept (a voice not available on `{engine}` is swapped for a valid one automatically).") @accessibility_group.command(name="voice") @commands.guild_only() @@ -2140,7 +2141,7 @@ class TtsToy(Cog): - `[p]ttstoy accessibility voice ` -> set your voice - `[p]ttstoy accessibility voice auto` -> go back to an auto-assigned voice - Voices are not saved between sessions. + Voices are saved and persist between sessions. """ engine = await self.config.accessibility_engine() if engine not in ("dectalk", "piper"): @@ -2163,6 +2164,12 @@ class TtsToy(Cog): self._access_user_override.get(ctx.guild.id, {}).pop(ctx.author.id, None) # Drop any stale auto-assignment too so a fresh distinct one is picked. self._access_auto_voice.get(ctx.guild.id, {}).pop(ctx.author.id, None) + # Clear the persisted record for this engine; the fresh auto-assign + # below will persist its own. + cur = dict(await self.config.member(ctx.author).access_voice() or {}) + if engine in cur: + cur.pop(engine, None) + await self.config.member(ctx.author).access_voice.set(cur) new_voice = self._access_voice_for(ctx.guild.id, ctx.author.id, engine) return await ctx.send( f"Your accessibility voice is now auto-assigned: " @@ -2177,9 +2184,11 @@ class TtsToy(Cog): self._access_user_override.setdefault(ctx.guild.id, {})[ctx.author.id] = match # Clear any auto-assignment so the override is unambiguous. self._access_auto_voice.get(ctx.guild.id, {}).pop(ctx.author.id, None) + # Persist the explicit pick so it survives reloads/restarts. + self._access_persist_voice(ctx.guild.id, ctx.author.id, engine, match, explicit=True) await ctx.send( f"Your accessibility voice is now `{self._access_voice_label(engine, match)}` " - f"(not saved between sessions)." + f"(saved)." ) @ttstoy_group.command(name="piperurl") @@ -2772,8 +2781,8 @@ class TtsToy(Cog): An explicit override (set via the `voice` command) always wins and is sticky: it survives VC flicker and engine-neutral resets. Otherwise the user gets an auto-assigned voice from the engine's pool (round-robin, so - concurrent speakers get distinct voices). Both maps live in memory only - and are not persisted between sessions. + concurrent speakers get distinct voices). Assignments are persisted per + member via Config, so they survive reloads and restarts. """ pool = self._access_voice_pool(engine) if not pool: @@ -2807,8 +2816,35 @@ class TtsToy(Cog): idx = self._access_assign_idx.get(guild_id, 0) + 1 self._access_assign_idx[guild_id] = idx auto[user_id] = chosen + # Persist the new auto-assignment so it survives reloads/restarts. + self._access_persist_voice(guild_id, user_id, engine, chosen, explicit=False) return chosen + def _access_persist_voice(self, guild_id: int, user_id: int, engine: str, voice: str, explicit: bool): + """Write-through a voice assignment to Config (fire-and-forget). + + Called from the sync resolver and the async command. Schedules the + async Config write on the running loop so the sync path does not block. + """ + async def _save(): + try: + guild = self.bot.get_guild(guild_id) + if guild is None: + return + member = guild.get_member(user_id) + if member is None: + return + cur = await self.config.member(member).access_voice() + cur = dict(cur or {}) + cur[engine] = {"voice": voice, "explicit": explicit} + await self.config.member(member).access_voice.set(cur) + except Exception: + log.exception("[Accessibility] failed to persist voice") + try: + asyncio.get_running_loop().create_task(_save()) + except RuntimeError: + pass # no running loop (shouldn't happen in the listener path) + def _access_describe_message(self, message: discord.Message) -> Optional[str]: """Build the spoken text for an accessibility auto-read of a VC side-chat message. @@ -3547,6 +3583,31 @@ class TtsToy(Cog): # services (managed outside the bot), so the cog no longer starts them. # It simply connects to them over HTTP on their fixed ports. + # Restore persisted per-user accessibility voices into the in-memory + # maps so they survive reloads/restarts. Stored per member as + # {engine: {"voice": str, "explicit": bool}}. + try: + all_members = await self.config.all_members() + for guild_id, members in all_members.items(): + for user_id, data in members.items(): + av = (data or {}).get("access_voice") or {} + for engine, rec in av.items(): + if not rec: + continue + voice = rec.get("voice") + if not voice: + continue + # Only the active engine's voice goes into the live + # maps; the other engine's persists in Config until + # that engine is selected (resolved lazily there). + if rec.get("explicit"): + self._access_user_override.setdefault(guild_id, {})[user_id] = voice + else: + self._access_auto_voice.setdefault(guild_id, {})[user_id] = voice + log.info("[Accessibility] restored persisted voices for %d guild(s)", len(all_members)) + except Exception: + log.exception("[Accessibility] failed to restore persisted voices") + # Start health HTTP server try: _HealthHandler.cog_ref = self