From f7e83c7cf69e17f35387a44ddfeacae53a6a5d69 Mon Sep 17 00:00:00 2001 From: Zeptiny Date: Mon, 9 Nov 2026 13:31:42 -0300 Subject: [PATCH 1/2] feat(voice): real-time voice calls with /voz /voz entrar brings the bot into the caller's voice channel and connects it to Qwen-Audio realtime (speech in, speech out); /voz sair ends the call. discord.py sends voice but can't receive it, and Discord has required DAVE end-to-end encryption since March 2026. core/voice_receive.py adds receive on discord.py's own hooks: the voice websocket maps each RTP ssrc to a user, every UDP packet loses its transport encryption and RTP padding, then the DAVE layer (discord.py's davey session), then opus. core/voice_call.py runs a call: everyone but bots mixed into one 16 kHz stream that never pauses (the server's turn detection measures silence on it), the model's audio played back, barge-in after ~0.7 s of someone talking over the bot (smart_turn_v2 only reports speech once the turn is over), transcripts in the call's chat in conversation order with who spoke, and a watchdog for empty, idle, over-long or disconnected calls. The idle default (2.5 min) stays under the model's 180 s no-response limit. Off unless VOICE_ENABLED, VOICE_API_KEY and VOICE_REALTIME_URL are set, and each server opts in with the `voice` setting. davey stays below 0.2 and discord.py below 2.8 (davey 0.2 breaks discord.py 2.7's voice: Rapptz/discord.py#10549). The image and CI install libopus. Co-Authored-By: Claude Opus 5.5 --- .env.example | 17 ++ .github/workflows/ci.yml | 4 + Dockerfile | 5 + README.md | 49 +++- SETUP.md | 5 + cogs/voice.py | 267 ++++++++++++++++++ config.py | 32 +++ core/prompts.py | 57 ++++ core/realtime_voice.py | 194 +++++++++++++ core/settings.py | 5 + core/voice_audio.py | 268 ++++++++++++++++++ core/voice_call.py | 534 +++++++++++++++++++++++++++++++++++ core/voice_receive.py | 273 ++++++++++++++++++ main.py | 1 + requirements.txt | 7 +- tests/test_realtime_voice.py | 148 ++++++++++ tests/test_voice_audio.py | 205 ++++++++++++++ tests/test_voice_call.py | 528 ++++++++++++++++++++++++++++++++++ tests/test_voice_receive.py | 244 ++++++++++++++++ 19 files changed, 2841 insertions(+), 2 deletions(-) create mode 100644 cogs/voice.py create mode 100644 core/realtime_voice.py create mode 100644 core/voice_audio.py create mode 100644 core/voice_call.py create mode 100644 core/voice_receive.py create mode 100644 tests/test_realtime_voice.py create mode 100644 tests/test_voice_audio.py create mode 100644 tests/test_voice_call.py create mode 100644 tests/test_voice_receive.py diff --git a/.env.example b/.env.example index fcd2226..8fe9b35 100644 --- a/.env.example +++ b/.env.example @@ -130,6 +130,23 @@ TAVILY_API_KEY= # --- Server Wrapped (/wrapped, server_wrapped tool, automatic recaps) --- # WRAPPED_ENABLED=true # WRAPPED_HOUR=10 # Brasília hour automatic recaps go out (Mondays weekly / the 1st monthly; turn on with /config servidor) +# --- Voice calls (/voz entrar | sair: real-time voice conversation in voice channels) --- +# Speech-to-speech with Qwen-Audio realtime (Alibaba Cloud Model Studio). Needs libopus on the host. +# Servers also opt in: /config servidor opcao:Conversa por voz valor:sim +# VOICE_ENABLED=false +# VOICE_API_KEY=sk-... +# Pay-as-you-go key (sk-...): your workspace's endpoint +# VOICE_REALTIME_URL=wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime +# Token Plan key (sk-sp-...): wss://token-plan.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime +# (Personal Edition terms allow interactive personal use only, not a bot shared by a community) +# VOICE_MODEL=qwen-audio-3.0-realtime-plus +# VOICE_VOICE=longanqian # longanqian | longanlingxin | longanlingxi | longanxiaoxin | longanlufeng +# VOICE_TURN_DETECTION=smart_turn_v2 # smart_turn_v2 (best with several people) | smart_turn | server_vad +# VOICE_WEB_SEARCH=false # let the model search the web on its own +# VOICE_TRANSCRIPTS=true # post what was heard and said in the call's text chat +# VOICE_MAX_CALLS=1 # simultaneous calls across all servers +# VOICE_MAX_MINUTES=30 # a call ends after this long +# VOICE_IDLE_MINUTES=2.5 # ...or after this long with nobody talking (keep under 3: the model drops sessions idle for 180 s) # --- Channel summaries (/resumo + summarize_channel tool) --- # SUMMARY_ENABLED=true # SUMMARY_MODEL= # defaults to CHAT_MODEL; a cheaper model is usually fine diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d6b0810..4db44ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,10 @@ jobs: - name: Install dependencies run: python -m pip install -r requirements-dev.txt + # The voice tests encode and decode real opus frames (they skip without it). + - name: Install libopus + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libopus0 + - name: Lint run: ruff check . diff --git a/Dockerfile b/Dockerfile index 7b3f32c..b0f1627 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,10 @@ FROM python:3.11-slim +# libopus: discord.py encodes the bot's voice and decodes the call's with it (/voz). +RUN apt-get update \ + && apt-get install -y --no-install-recommends libopus0 \ + && rm -rf /var/lib/apt/lists/* + WORKDIR /app COPY requirements.txt . diff --git a/README.md b/README.md index 9499dbc..8840fb0 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ Built with [discord.py](https://discordpy.readthedocs.io/) + RAG (Retrieval-Augm | **Server Tools** | JVM flags, server status checks, docs changelog | | **Channel Summaries** | `/resumo` and natural-language "o que perdi?" — map-reduce summaries of a channel or thread over any period, with jump links and permission checks | | **Monitors** | Standing triggers (channels, authors, mentions of a user, a content regex) that call the bot on matching messages; it answers like a mention, knows a monitor sent it, and may stay silent. Managed with `/monitor` or by asking the bot | +| **Voice Calls** | `/voz entrar`: the bot joins your voice channel and talks in real time (speech-to-speech with Qwen-Audio realtime) — hears everyone in the call, stops when talked over, optionally writes the conversation in the call's chat. Off unless configured, and each server opts in | | **Persistent Memory** | The bot remembers: atomic facts about the server and its members, auto-injected into every conversation, with inline LLM writes, pinning, dedupe, full audit history and admin control. Each memory records who said it — a fact about someone told by someone else is shown as a report ("segundo Fulano") | All AI responses are in **Brazilian Portuguese**. @@ -245,9 +246,24 @@ A recap of the server over a period (`semana` = 7 days, default; `mes`; `ano`; o | `instructions` | channel | text the model follows in that channel ("seja direto e técnico", "aqui é papo livre") | | `aliases` | server | extra names the bot answers to, comma-separated | | `wrapped`, `wrapped_channel` | server | automatic Wrapped: `off`/`weekly`/`monthly` and where | +| `voice` | server | allow `/voz entrar` (default off: a call's audio goes to the voice model) | Stored in `SETTINGS_DB_PATH`. +#### `/voz entrar` · `/voz sair` — Voice calls +The bot joins the voice channel you're in and talks with the call in real time. It's a speech-to-speech model ([Qwen-Audio realtime](https://www.alibabacloud.com/help/en/model-studio/qwen-audio-realtime-user-guides), Alibaba Cloud Model Studio): audio goes in, audio comes out, no separate speech-to-text and text-to-speech steps, so answers start a second or two after someone stops talking. + +- **Who it hears:** everyone in the call, mixed into one stream (other bots, like music bots, are left out). The model can't tell voices apart, so it doesn't call people by name unless they say who they are +- **Turns:** the model decides when someone finished (`VOICE_TURN_DETECTION`; `smart_turn_v2` understands turns semantically and ignores most cross-talk and "uhum"s) +- **Interrupting:** talking over the bot for ~0.7 s stops it mid-sentence and cancels the rest of its answer +- **Personality:** the server's `` block, plus voice rules (short spoken sentences, no markdown or links). No tools in calls: memories, history and docs stay in the text chat, and the bot says so instead of guessing +- **Transcripts** (`VOICE_TRANSCRIPTS`): what was heard (`🎙️ **Ana:** …`, attributed by who was talking when) and what the bot said (`🔊 …`, with `…` where it was cut off) go to the call's text chat +- **Leaving:** `/voz sair` (anyone in the call, or Move Members / Manage Server), everyone leaving, `VOICE_IDLE_MINUTES` without anyone talking, or `VOICE_MAX_MINUTES` in the call +- **Enabling:** `VOICE_ENABLED`, `VOICE_API_KEY` and `VOICE_REALTIME_URL` (see [Voice Calls](#voice-calls) under Configuration), libopus on the host, then per server `/config servidor opcao:Conversa por voz valor:sim`. When joining, the bot says it's listening and posts that the call's audio goes to the voice model +- **Not supported:** stage channels; several calls in one server at once (one per server, `VOICE_MAX_CALLS` across all servers) + +discord.py has no voice receive, so `core/voice_receive.py` adds it on discord.py's own hooks: the voice websocket says which user sends each RTP stream, every UDP packet is unwrapped from the transport encryption, then from Discord's DAVE end-to-end encryption (with the MLS keys of discord.py's `davey` session), then decoded from opus. + --- ### Utility Commands @@ -441,6 +457,10 @@ QuillBot/ │ ├── image_store.py # Persisted, re-encoded images for vision │ ├── tavily_tools.py # Tavily web_search / web_extract │ ├── local_inference.py# Single-thread executor for local models +│ ├── voice_receive.py # Voice receive for discord.py: RTP transport decryption, DAVE, opus, ListeningVoiceClient +│ ├── voice_audio.py # Resampling (48k↔16k/24k), the per-speaker mixer, the playback buffer/source +│ ├── voice_call.py # One live call: audio both ways, barge-in, transcripts, watchdog +│ ├── realtime_voice.py # Qwen-Audio realtime WebSocket client │ └── ui.py # PaginatedEmbedView, source pages ├── cogs/ │ ├── chat.py # /chat, /ask, the chat router handler, edit/delete events, the episode worker @@ -448,6 +468,7 @@ QuillBot/ │ ├── server_config.py # /config — server and channel settings │ ├── persona.py # /persona, the persona_update tool, change log with Revert │ ├── wrapped.py # /wrapped, server_wrapped tool, automatic weekly/monthly recaps +│ ├── voice.py # /voz entrar | sair — real-time voice calls │ ├── docs_rag.py # Docs RAG — indexing, search, reranking, /reindex, search_docs/search_plugins tools │ ├── history_rag.py # Server-wide history RAG — backfill, live ingestion, reactions, history tools, Wrapped stats │ ├── log_analyzer.py # Passive log detection, pattern matching, /analyze, file upload to mclo.gs @@ -484,11 +505,13 @@ cd QuillBot pip install -r requirements.txt ``` +Voice calls (`/voz`) also need libopus: `apt install libopus0` (the Docker image has it). + ### Discord Bot Setup 1. Create a bot at https://discord.com/developers/applications 2. Under **Bot → Privileged Gateway Intents** enable **Message Content Intent** -3. Invite with scopes `bot` + `applications.commands` and permissions: Send Messages, Embed Links, Read Message History, Add Reactions, Use Application Commands +3. Invite with scopes `bot` + `applications.commands` and permissions: Send Messages, Embed Links, Read Message History, Add Reactions, Use Application Commands (plus Connect and Speak for voice calls) --- @@ -679,6 +702,26 @@ cp .env.example .env # if available, otherwise create .env manually | `WRAPPED_ENABLED` | `true` | `/wrapped`, the `server_wrapped` tool and automatic recaps | | `WRAPPED_HOUR` | `10` | Brasília hour automatic recaps are posted (Mondays / the 1st) | +### Voice Calls + +`/voz` exists only when `VOICE_ENABLED=true`, both `VOICE_API_KEY` and `VOICE_REALTIME_URL` are set, and libopus is installed (the startup log says which one is missing). Servers then opt in with the `voice` setting. + +| Variable | Default | Description | +|---|---|---| +| `VOICE_ENABLED` | `false` | Master switch | +| `VOICE_API_KEY` | — | Model Studio key: pay-as-you-go (`sk-…`) or Token Plan (`sk-sp-…`) | +| `VOICE_REALTIME_URL` | — | Realtime WebSocket endpoint for that key, without `?model=`. Pay-as-you-go: `wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime`. Token Plan: `wss://token-plan.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime` — but Token Plan *Personal* Edition is for one person's interactive use and forbids production services and sharing a key, which a community bot is | +| `VOICE_MODEL` | `qwen-audio-3.0-realtime-plus` | Realtime model | +| `VOICE_VOICE` | `longanqian` | 3.0 voices: `longanqian`, `longanlingxin`, `longanlingxi`, `longanxiaoxin`, `longanlufeng`, or a cloned `voice_id` | +| `VOICE_TURN_DETECTION` | `smart_turn_v2` | `smart_turn_v2` (semantic, best with several people), `smart_turn`, or `server_vad` (silence only; answers faster, interrupts more easily) | +| `VOICE_WEB_SEARCH` | `false` | Let the model search the web on its own | +| `VOICE_TRANSCRIPTS` | `true` | Post what was heard and said in the call's text chat | +| `VOICE_MAX_CALLS` | `1` | Simultaneous calls across all servers | +| `VOICE_MAX_MINUTES` | `30` | A call ends after this long | +| `VOICE_IDLE_MINUTES` | `2.5` | …or after this long with nobody talking. Keep it under 3: the model closes a session that goes 180 s without answering (`response_idle_timeout`) | + +Audio streams to the model the whole time the bot is in a call, silence included: its turn detection measures pauses on that stream (in testing, the usage the model reported covered the detected speech, not the silence). `davey` stays below 0.2 until discord.py supports it (see `requirements.txt`). + ### Other | Variable | Default | Description | @@ -775,6 +818,10 @@ ruff check . # lint (rules configured in pyproject.toml) | `test_summary.py` | `/resumo`: period parsing, fetching, map-reduce, permissions | | `test_tool_loop.py` | Tool errors reported to the model instead of aborting the turn | | `test_trajectory_replay.py` | Trajectory capture, verbatim replay, text tool-call recovery | +| `test_realtime_voice.py` | The realtime voice client against a local fake server: handshake, auth, audio, events, refused keys and settings, timeouts | +| `test_voice_audio.py` | Resampling (band kept, aliasing and imaging removed, seamless across chunks), the per-speaker mixer and its jitter buffer, the playback buffer | +| `test_voice_call.py` | A call with Discord and the model faked: people (not bots) reach the model, playback, transcripts in order with who spoke, barge-in from both sides, cut lines edited, the watchdog, ending | +| `test_voice_receive.py` | RTP transport decryption (incl. discord.py's own packets), header extensions, the DAVE layer, opus decoding, the voice websocket hook | | `test_wrapped.py` | Wrapped numbers, weekly/monthly schedule, automatic posts once per period, the tool | `tests/conftest.py` puts the repo root on the import path, runs `async def` tests without a plugin, and provides a `tmpdb` fixture. `tests/helpers.py` has `check(label, condition, detail)`, a labelled assert. `tests/chat_fakes.py` has fake Discord objects and `make_engine`, a real chat engine on temp stores whose turns answer from a script. New tests go in the file for the module they cover, or a new `test_.py`. diff --git a/SETUP.md b/SETUP.md index 39087ae..89a0162 100644 --- a/SETUP.md +++ b/SETUP.md @@ -97,6 +97,10 @@ Notes: - Bodies are captured for **httpx/httpx2-based** services (`openai`, `tavily`); **aiohttp-based** services (Discord REST, GitHub, Modrinth/Hangar/SpigotMC, mclo.gs, spark) log metadata only. - Headers are never logged; API keys travel in headers. Sensitive query-string values (`token`, `key`, …) are redacted to `REDACTED`. +### Optional — Voice calls (`/voz`) + +Off by default. Set `VOICE_ENABLED=true`, `VOICE_API_KEY` and `VOICE_REALTIME_URL`, install libopus (`apt install libopus0`; the Docker image has it), then turn it on per server with `/config servidor opcao:Conversa por voz valor:sim`. See the README's *Voice Calls* section for every variable. + ### Optional — RAG / Docs | Variable | Default | Description | @@ -164,6 +168,7 @@ After adding a source, restart the bot or run `/reindex` (admin-only) to index i - **Add Reactions** — the 👀 reaction on detected paste links - **Use Application Commands** — slash commands - **Create Public Threads** and **Send Messages in Threads** — move long or off-topic chats into threads (without them the bot answers in the channel) +- **Connect** and **Speak** — voice calls (`/voz`), only if enabled ### Required Intents diff --git a/cogs/voice.py b/cogs/voice.py new file mode 100644 index 0000000..aabcb64 --- /dev/null +++ b/cogs/voice.py @@ -0,0 +1,267 @@ +"""``/voz`` — real-time voice conversation in voice channels. + +``/voz entrar`` brings the bot into the caller's voice channel and connects it +to a speech-to-speech model (Qwen-Audio realtime, :mod:`core.realtime_voice`); +``/voz sair`` ends the call. Everything that happens during the call — audio +in and out, barge-in, transcripts, ending idle calls — is +:class:`core.voice_call.VoiceCall`. + +Loaded only when the bot is configured for it (``VOICE_ENABLED``, +``VOICE_API_KEY``, ``VOICE_REALTIME_URL``, libopus and davey present), and a +server still has to opt in (``/config servidor`` → Conversa por voz), since a +call's audio goes to that model. +""" + +from __future__ import annotations + +import datetime +import logging + +import discord +from discord import app_commands +from discord.ext import commands + +from config import ( + BR_TZ, + VOICE_API_KEY, + VOICE_AVAILABLE, + VOICE_ENABLED, + VOICE_IDLE_MINUTES, + VOICE_MAX_CALLS, + VOICE_MAX_MINUTES, + VOICE_MODEL, + VOICE_REALTIME_URL, + VOICE_TRANSCRIPTS, + VOICE_TURN_DETECTION, + VOICE_VOICE, + VOICE_WEB_SEARCH, +) +from core.prompts import voice_greeting, voice_instructions +from core.realtime_voice import RealtimeError, RealtimeVoiceClient +from core.voice_call import VoiceCall + +logger = logging.getLogger(__name__) + + +def session_config(instructions: str) -> dict: + """The realtime session the bot asks for (``session.update``).""" + config = { + 'modalities': ['audio', 'text'], + 'voice': VOICE_VOICE, + 'instructions': instructions, + 'input_audio_format': 'pcm', + 'output_audio_format': 'pcm', + 'turn_detection': {'type': VOICE_TURN_DETECTION}, + } + if VOICE_WEB_SEARCH: + config['enable_search'] = True + return config + + +def missing_dependency() -> str | None: + """What keeps this machine from doing voice, if anything.""" + try: + import davey # noqa: F401 + import nacl.bindings # noqa: F401 + except ImportError as e: + return f'{e.name} is not installed (pip install -r requirements.txt)' + try: + discord.opus.Decoder() # loads libopus + except discord.opus.OpusNotLoaded: + return 'libopus was not found (apt install libopus0)' + return None + + +class _JoinError(Exception): + """Why the bot couldn't join (user-facing).""" + + +class Voice(commands.Cog): + """Voice calls: /voz entrar | sair.""" + + def __init__(self, bot: commands.Bot): + self.bot = bot + self.services = bot.services + self.calls: dict[int, VoiceCall] = {} + self._joining: set[int] = set() + + voz = app_commands.Group(name='voz', description='Conversa por voz com o bot nas calls', guild_only=True) + + async def cog_unload(self) -> None: + for call in list(self.calls.values()): + await call.end('o bot está reiniciando') + + # --- commands --- + + @voz.command(name='entrar', description='Chama o bot para a call em que você está') + async def entrar(self, interaction: discord.Interaction): + guild = interaction.guild + member = interaction.user + assert guild is not None and isinstance(member, discord.Member) + problem = self._join_problem(guild, member) + if problem: + await interaction.response.send_message(problem, ephemeral=True) + return + channel = member.voice.channel if member.voice else None + assert isinstance(channel, discord.VoiceChannel) # _join_problem made sure + await interaction.response.defer(thinking=True) + self._joining.add(guild.id) + try: + call = await self._start_call(guild, channel, member) + except _JoinError as e: + await interaction.followup.send(f'⚠️ {e}') + return + finally: + self._joining.discard(guild.id) + transcribed = ' e eu escrevo a conversa no chat da call' if call.transcripts else '' + await interaction.followup.send( + f'🎙️ Entrei em {channel.mention}. Enquanto eu estiver lá, o que vocês falarem vai para a ' + f'IA de voz (Qwen, da Alibaba Cloud){transcribed}. Para me tirar: `/voz sair`.' + ) + + @voz.command(name='sair', description='Tira o bot da call') + async def sair(self, interaction: discord.Interaction): + guild = interaction.guild + member = interaction.user + assert guild is not None and isinstance(member, discord.Member) + call = self.calls.get(guild.id) + if call is None: + stray = guild.voice_client + if stray is not None: # a connection that outlived its call + await stray.disconnect(force=True) + await interaction.response.send_message('👋 Saí da call.', ephemeral=True) + return + await interaction.response.send_message('Não estou em nenhuma call aqui.', ephemeral=True) + return + in_call = member.voice is not None and member.voice.channel == call.channel + perms = member.guild_permissions + if not (in_call or perms.move_members or perms.manage_guild): + await interaction.response.send_message( + 'Só quem está na call (ou quem pode mover membros) me tira de lá.', ephemeral=True, + ) + return + await interaction.response.send_message(f'👋 Saindo de {call.channel.mention}.') + await call.end(f'pedido de {member.display_name}') + + # --- joining --- + + def _join_problem(self, guild: discord.Guild, member: discord.Member) -> str | None: + if not self.services.settings.get(guild.id, None, 'voice'): + perms = member.guild_permissions + how = ( + 'Ligue com `/config servidor opcao:Conversa por voz valor:sim`.' + if perms.manage_guild or perms.administrator + else 'Um admin pode ligar em `/config servidor`.' + ) + return f'A conversa por voz está desligada neste servidor. {how}' + channel = member.voice.channel if member.voice else None + if channel is None: + return 'Entre numa call e use `/voz entrar` de novo.' + if isinstance(channel, discord.StageChannel): + return 'Em palcos (stage) eu ainda não falo, só em canais de voz comuns.' + call = self.calls.get(guild.id) + if call is not None: + if call.ended: + return 'Ainda estou saindo da call anterior; tente de novo em alguns segundos.' + if call.channel == channel: + return 'Já estou nesta call.' + return f'Já estou em outra call deste servidor: {call.channel.mention}.' + if guild.id in self._joining: + return 'Já estou entrando numa call…' + if len(self.calls) + len(self._joining) >= VOICE_MAX_CALLS: + return 'Já estou no máximo de calls ao mesmo tempo. Tente de novo mais tarde.' + perms = channel.permissions_for(guild.me) + missing = [name for name, ok in (('Conectar', perms.connect), ('Falar', perms.speak)) if not ok] + if missing: + return f'Não tenho permissão de {" e ".join(missing)} em {channel.mention}.' + if channel.user_limit and len(channel.members) >= channel.user_limit and not perms.move_members: + return f'{channel.mention} está cheia.' + return None + + async def _start_call( + self, guild: discord.Guild, channel: discord.VoiceChannel, member: discord.Member, + ) -> VoiceCall: + from core.voice_receive import ListeningVoiceClient + + participants = [m.display_name for m in channel.members if not m.bot] + persona = self.services.persona.block(guild.id) if self.services.persona is not None else '' + instructions = voice_instructions( + server=guild.name, + channel=channel.name, + caller=member.display_name, + participants=participants, + now=datetime.datetime.now(BR_TZ).strftime('%d/%m/%Y %H:%M'), + persona=persona, + ) + assert VOICE_API_KEY is not None + realtime = RealtimeVoiceClient(VOICE_REALTIME_URL, VOICE_API_KEY, VOICE_MODEL) + try: + await realtime.connect(session_config(instructions)) + except RealtimeError as e: + logger.warning('[voice] realtime session failed in guild %s: %s', guild.id, e) + raise _JoinError(f'Não consegui abrir a conversa com a IA de voz: {e}.') from None + + if guild.voice_client is not None: # a connection that outlived its call + await guild.voice_client.disconnect(force=True) + try: + vc = await channel.connect(cls=ListeningVoiceClient, timeout=20, self_deaf=False) + except Exception as e: + await realtime.close() + logger.warning('[voice] could not join #%s (%s): %r', channel.name, guild.id, e) + raise _JoinError(f'Não consegui entrar em {channel.mention} ({type(e).__name__}).') from None + + call = VoiceCall( + voice_client=vc, + realtime=realtime, + is_bot=lambda uid: bool(getattr(guild.get_member(uid), 'bot', False)), + name_of=lambda uid: getattr(guild.get_member(uid), 'display_name', None) or str(uid), + transcripts=VOICE_TRANSCRIPTS, + idle_seconds=VOICE_IDLE_MINUTES * 60, + max_seconds=VOICE_MAX_MINUTES * 60, + on_end=lambda ended: self._forget(guild.id, ended), + ) + self.calls[guild.id] = call + try: + await call.start(greeting=voice_greeting(member.display_name)) + except Exception: + logger.exception('[voice] starting the call in #%s (%s) failed', channel.name, guild.id) + await call.end('não consegui começar a conversa') + raise _JoinError('Entrei, mas não consegui começar a conversa.') from None + logger.info('[voice] call started in #%s (%s) by %s', channel.name, guild.id, member) + return call + + def _forget(self, guild_id: int, call: VoiceCall) -> None: + if self.calls.get(guild_id) is call: + del self.calls[guild_id] + + # --- the bot's own voice state --- + + @commands.Cog.listener() + async def on_voice_state_update( + self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState, + ): + call = self.calls.get(member.guild.id) + if call is None or call.ended: + return + me = self.bot.user + if me is not None and member.id == me.id: + if after.channel is None: + await call.end('fui desconectado da call') + return + if before.channel == call.channel and after.channel != call.channel: + if not any(not m.bot for m in call.channel.members): + await call.end('todo mundo saiu da call') + + +async def setup(bot: commands.Bot): + if not VOICE_ENABLED: + logger.info('Voice calls disabled via VOICE_ENABLED=false') + return + if not VOICE_AVAILABLE: + logger.warning('Voice calls disabled: VOICE_API_KEY and VOICE_REALTIME_URL must both be set') + return + missing = missing_dependency() + if missing: + logger.error('Voice calls disabled: %s', missing) + return + await bot.add_cog(Voice(bot)) diff --git a/config.py b/config.py index 914a495..4701ae7 100644 --- a/config.py +++ b/config.py @@ -337,6 +337,31 @@ def _is_openrouter_url(url: str) -> bool: # Rendered messages per LLM call; longer ranges are summarized map-reduce style. SUMMARY_SEGMENT_CHARS: Final[int] = int(os.getenv('SUMMARY_SEGMENT_CHARS', '24000')) +# --- Voice calls (/voz: real-time voice conversation in voice channels) --- +# Speech-to-speech through Qwen-Audio realtime (Alibaba Cloud Model Studio). Off +# unless enabled, keyed and pointed at an endpoint; servers also opt in with +# /config servidor (setting `voice`), since a call's audio goes to that model. +VOICE_ENABLED: Final[bool] = _flag('VOICE_ENABLED', 'false') +VOICE_API_KEY: Final[str | None] = os.getenv('VOICE_API_KEY') or None +# The realtime WebSocket endpoint, without ?model=. Pay-as-you-go keys (sk-…) use +# the workspace's: wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime +# Token Plan keys (sk-sp-…): wss://token-plan.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime +VOICE_REALTIME_URL: Final[str] = os.getenv('VOICE_REALTIME_URL', '').strip() +VOICE_MODEL: Final[str] = os.getenv('VOICE_MODEL', 'qwen-audio-3.0-realtime-plus').strip() +# 3.0 models: longanqian, longanlingxin, longanlingxi, longanxiaoxin, longanlufeng (or a cloned voice_id). +VOICE_VOICE: Final[str] = os.getenv('VOICE_VOICE', 'longanqian').strip() +# smart_turn_v2 understands turns semantically and copes best with several people in a call; +# server_vad ends a turn on silence alone. +VOICE_TURN_DETECTION: Final[str] = os.getenv('VOICE_TURN_DETECTION', 'smart_turn_v2').strip().lower() +VOICE_WEB_SEARCH: Final[bool] = _flag('VOICE_WEB_SEARCH', 'false') # the model's built-in web search +VOICE_TRANSCRIPTS: Final[bool] = _flag('VOICE_TRANSCRIPTS') # post what was heard and said in the call's chat +VOICE_MAX_CALLS: Final[int] = max(1, int(os.getenv('VOICE_MAX_CALLS', '1'))) # simultaneous calls, all servers +VOICE_MAX_MINUTES: Final[float] = float(os.getenv('VOICE_MAX_MINUTES', '30')) +# Below 3: the model closes a session that went 180 s without answering anything +# (response_idle_timeout), and leaving first says why. +VOICE_IDLE_MINUTES: Final[float] = float(os.getenv('VOICE_IDLE_MINUTES', '2.5')) +VOICE_AVAILABLE: Final[bool] = VOICE_ENABLED and bool(VOICE_API_KEY) and bool(VOICE_REALTIME_URL) + # --- Rate Limiting (per-user) --- COOLDOWN_RATE: Final[int] = int(os.getenv('COOLDOWN_RATE', '1')) COOLDOWN_PER: Final[float] = float(os.getenv('COOLDOWN_PER', '30')) @@ -449,3 +474,10 @@ def validate_config() -> None: 'Web search will be disabled.', file=sys.stderr, ) + if VOICE_ENABLED and not VOICE_AVAILABLE: + missing = [n for n, v in (('VOICE_API_KEY', VOICE_API_KEY), ('VOICE_REALTIME_URL', VOICE_REALTIME_URL)) if not v] + print( + f'WARNING: VOICE_ENABLED is true but {", ".join(missing)} is not set. ' + 'Voice calls will be disabled.', + file=sys.stderr, + ) diff --git a/core/prompts.py b/core/prompts.py index b0e7b6f..ad58f06 100644 --- a/core/prompts.py +++ b/core/prompts.py @@ -353,3 +353,60 @@ def lag_spike_warning(threshold_ms: float) -> str: 'Não sugira otimizações gerais de desempenho como resposta primária.\n' '' ) + + +# --- Voice calls (/voz) --- +# The realtime voice model gets one system prompt for the whole call; whatever it +# writes is spoken, so the text rules are about speech, not Discord formatting. +VOICE_ROLE = ( + "\n" + "Você é o bot deste servidor do Discord e entrou numa call de voz com a comunidade. " + "Fale sempre em português brasileiro.\n" + "Sua personalidade e seu jeito de falar são definidos pelo próprio servidor: siga o bloco " + " quando houver.\n" + "" +) + +VOICE_RULES = ( + "\n" + "- Tudo o que você responde vira fala. Fale como numa conversa: frases curtas e naturais, " + "uma ou duas por vez, e deixe espaço para as pessoas responderem.\n" + "- Nada de markdown, listas, links, emojis ou blocos de código. Números, siglas e termos " + "técnicos do jeito que se falam.\n" + "- Várias pessoas podem estar na call, e às vezes conversam entre si. Se uma fala " + "claramente não foi para você, responda bem curto ou só concorde, sem puxar o assunto.\n" + "- Você ouve todo mundo num áudio só e não sabe quem está falando: não chame ninguém pelo " + "nome, a não ser que a pessoa diga quem é.\n" + "- Se pedirem uma explicação longa, explique falando: os pontos principais em poucas " + "frases, e pergunte se querem que você continue. Só mande para o chat de texto o que " + "precisa ser lido, como um comando longo, uma configuração ou um link.\n" + "- Responda com o que você sabe. Nesta call você não tem as memórias do servidor, o " + "histórico nem a documentação: quando a resposta depender disso, ou se não tiver certeza, " + "diga isso em vez de inventar.\n" + "" +) + + +def voice_instructions( + *, server: str, channel: str, caller: str, participants: list[str], now: str, persona: str = '', +) -> str: + """The system prompt of a voice call.""" + people = ', '.join(participants) if participants else caller + context = ( + "\n" + f"Servidor: {server}. Call: {channel}. Quem chamou você: {caller}. " + f"Na call quando você entrou: {people}. Agora: {now} (horário de Brasília).\n" + "" + ) + parts = [VOICE_ROLE, VOICE_RULES, context] + if persona: + parts.append(persona) + return '\n\n'.join(parts) + + +def voice_greeting(caller: str) -> str: + """The turn that makes the bot say hello when it joins (so everyone knows it's listening).""" + return ( + f"[{caller} acabou de chamar você para a call. Cumprimente a call numa frase curta e " + "diga que está ouvindo.]" + ) diff --git a/core/realtime_voice.py b/core/realtime_voice.py new file mode 100644 index 0000000..1a6f0b8 --- /dev/null +++ b/core/realtime_voice.py @@ -0,0 +1,194 @@ +"""Client for Qwen-Audio realtime voice conversation (Alibaba Cloud Model Studio). + +One WebSocket per call. The client streams 16 kHz mono PCM in +(``input_audio_buffer.append``); the server finds the turns itself (VAD or +semantic turn detection), answers with 24 kHz mono PCM +(``response.audio.delta``) plus transcripts of both sides, and everything +else is JSON events named after OpenAI's Realtime API. Reference: +https://www.alibabacloud.com/help/en/model-studio/fun-audiochat-client-events + +The endpoint and key are configuration: a Model Studio pay-as-you-go key +(``sk-…``) uses the workspace's realtime URL, a Token Plan key (``sk-sp-…``) +the Token Plan one. +""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import logging +from collections.abc import AsyncIterator +from typing import Any +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + +import aiohttp + +logger = logging.getLogger(__name__) + + +class RealtimeError(RuntimeError): + """The realtime session couldn't be opened or configured (message is user-facing).""" + + +def realtime_url(base: str, model: str) -> str: + """*base* with ``?model=`` set, unless it already names one.""" + parts = urlsplit(base) + query = parse_qsl(parts.query, keep_blank_values=True) + if not any(k == 'model' for k, _ in query): + query.append(('model', model)) + return urlunsplit(parts._replace(query=urlencode(query))) + + +def error_code(event: dict) -> str: + err = event.get('error') + return str(err.get('code') or '')[:64] if isinstance(err, dict) else '' + + +def error_message(event: dict) -> str: + err = event.get('error') + if isinstance(err, dict): + text = err.get('message') or err.get('code') or err + else: + text = err or event + return str(text)[:300] + + +class RealtimeVoiceClient: + """One realtime conversation: :meth:`connect`, stream audio, iterate :meth:`events`.""" + + def __init__( + self, + url: str, + api_key: str, + model: str, + *, + http: aiohttp.ClientSession | None = None, + timeout: float = 15.0, + ) -> None: + self.url = realtime_url(url, model) + self.model = model + self._api_key = api_key + self._http = http + self._owns_http = http is None + self._timeout = timeout + self._ws: aiohttp.ClientWebSocketResponse | None = None + self._send_lock = asyncio.Lock() + self.session: dict = {} + self.audio_bytes_sent = 0 + + @property + def closed(self) -> bool: + return self._ws is None or self._ws.closed + + @property + def close_code(self) -> int | None: + return None if self._ws is None else self._ws.close_code + + async def connect(self, session_config: dict) -> dict: + """Open the socket and apply *session_config*; returns the session the server confirmed.""" + if self._http is None: + self._http = aiohttp.ClientSession() + try: + self._ws = await asyncio.wait_for( + self._http.ws_connect( + self.url, + headers={'Authorization': f'Bearer {self._api_key}'}, + max_msg_size=0, + ), + self._timeout, + ) + except aiohttp.WSServerHandshakeError as e: + await self.close() + if e.status in (401, 403): + raise RealtimeError(f'a chave da API de voz foi recusada ({e.status})') from None + raise RealtimeError(f'o servidor de voz recusou a conexão ({e.status})') from None + except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as e: + await self.close() + raise RealtimeError(f'não consegui conectar ao servidor de voz ({type(e).__name__})') from None + try: + await self._expect('session.created') + await self.send({'type': 'session.update', 'session': session_config}) + updated = await self._expect('session.updated') + except BaseException: + await self.close() + raise + self.session = updated.get('session') or {} + return self.session + + async def _expect(self, event_type: str) -> dict: + """The next *event_type* event, failing on an ``error`` event, a close or the timeout.""" + assert self._ws is not None + loop = asyncio.get_running_loop() + deadline = loop.time() + self._timeout + while True: + remaining = deadline - loop.time() + if remaining <= 0: + raise RealtimeError(f'o servidor de voz não respondeu ({event_type})') + try: + msg = await self._ws.receive(timeout=remaining) + except asyncio.TimeoutError: + raise RealtimeError(f'o servidor de voz não respondeu ({event_type})') from None + if msg.type != aiohttp.WSMsgType.TEXT: + raise RealtimeError(f'o servidor de voz fechou a conexão ({self._ws.close_code})') + try: + event = json.loads(msg.data) + except ValueError: + continue + if event.get('type') == 'error': + # The message can echo what was sent (the instructions, say): it goes + # to the log; people see the code. + logger.warning('[voice] realtime session refused: %s', error_message(event)) + raise RealtimeError(f'o servidor de voz recusou a sessão ({error_code(event) or "sem código"})') + if event.get('type') == event_type: + return event + + async def events(self) -> AsyncIterator[dict]: + """Server events until the connection closes.""" + if self._ws is None: + return + async for msg in self._ws: + if msg.type == aiohttp.WSMsgType.TEXT: + try: + event = json.loads(msg.data) + except ValueError: + continue + if isinstance(event, dict): + yield event + elif msg.type == aiohttp.WSMsgType.ERROR: + logger.warning('[voice] realtime socket error: %s', self._ws.exception()) + break + + async def send(self, event: dict[str, Any]) -> None: + ws = self._ws + if ws is None or ws.closed: + raise ConnectionError('realtime session is closed') + async with self._send_lock: + await ws.send_str(json.dumps(event, ensure_ascii=False)) + + async def append_audio(self, pcm16k: bytes) -> None: + await self.send({'type': 'input_audio_buffer.append', 'audio': base64.b64encode(pcm16k).decode()}) + self.audio_bytes_sent += len(pcm16k) + + async def add_message(self, role: str, text: str) -> None: + """Add a text item to the conversation (``system`` or ``user``).""" + await self.send({ + 'type': 'conversation.item.create', + 'item': {'type': 'message', 'role': role, 'content': [{'type': 'input_text', 'text': text}]}, + }) + + async def create_response(self) -> None: + await self.send({'type': 'response.create'}) + + async def cancel_response(self) -> None: + await self.send({'type': 'response.cancel'}) + + async def close(self) -> None: + ws = self._ws # kept, so close_code stays readable + try: + if ws is not None and not ws.closed: + await ws.close() + except Exception: + logger.debug('[voice] closing the realtime socket failed', exc_info=True) + if self._owns_http and self._http is not None and not self._http.closed: + await self._http.close() diff --git a/core/settings.py b/core/settings.py index d1133ba..7fe8604 100644 --- a/core/settings.py +++ b/core/settings.py @@ -84,6 +84,11 @@ class Setting: 'wrapped_channel', 'guild', 'channel', '', 'Canal do Wrapped', 'Canal onde a retrospectiva automática é publicada.', ), + Setting( + 'voice', 'guild', 'bool', False, 'Conversa por voz', + 'Deixa o bot entrar nas calls com /voz entrar e conversar por voz. Enquanto ele está ' + 'na call, o áudio de quem fala vai para a IA de voz (Qwen, da Alibaba Cloud).', + ), )} diff --git a/core/voice_audio.py b/core/voice_audio.py new file mode 100644 index 0000000..aea94f8 --- /dev/null +++ b/core/voice_audio.py @@ -0,0 +1,268 @@ +"""Audio plumbing for voice calls: resampling, mixing and the playback buffer. + +Discord carries 48 kHz stereo 16-bit PCM in 20 ms frames (once opus is +decoded). The realtime voice model listens to 16 kHz mono and talks in 24 kHz +mono, both 16-bit little-endian. Three threads touch this audio — discord.py's +voice socket reader (what people say), the asyncio loop (the model's side) and +discord.py's audio player (what the bot says) — so the stateful pieces here +take a lock, and everything is plain numpy the tests can drive without Discord. +""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable +from dataclasses import dataclass, field + +import numpy as np + +import discord + +DISCORD_RATE = 48000 +# One 20 ms frame of 48 kHz stereo s16le: what discord.py's player reads each tick. +DISCORD_FRAME_BYTES = 3840 +INPUT_RATE = 16000 # what the model listens to +OUTPUT_RATE = 24000 # what the model speaks + +_SILENCE_FRAME = bytes(DISCORD_FRAME_BYTES) + + +def lowpass_taps(num_taps: int, cutoff: float) -> np.ndarray: + """Blackman-windowed sinc low-pass, unity gain at DC. + + ``cutoff`` is a fraction of the sample rate (0–0.5). + """ + n = np.arange(num_taps, dtype=np.float64) - (num_taps - 1) / 2 + taps = 2 * cutoff * np.sinc(2 * cutoff * n) * np.blackman(num_taps) + return (taps / taps.sum()).astype(np.float32) + + +# 48 → 16 kHz: speech lives below 7 kHz; the band edge stays under the new 8 kHz Nyquist. +_DOWN_TAPS = lowpass_taps(96, 7000 / DISCORD_RATE) +# 24 → 48 kHz: keeps the model's band (< 12 kHz) and removes the images zero-stuffing creates. +_UP_TAPS = lowpass_taps(64, 11000 / DISCORD_RATE) + + +def _int16(x: np.ndarray) -> np.ndarray: + return np.clip(np.rint(x), -32768, 32767).astype(' None: + self._hist = np.zeros(len(_DOWN_TAPS) - 1, dtype=np.float32) + self._phase = 0 + + def process(self, pcm: bytes) -> np.ndarray: + x = np.frombuffer(pcm, dtype=' None: + taps = _UP_TAPS * 2 # each phase carries half the gain + self._even, self._odd = taps[0::2], taps[1::2] + self._hist = np.zeros(len(self._even) - 1, dtype=np.float32) + + def process(self, pcm: bytes) -> bytes: + x = np.frombuffer(pcm[: len(pcm) - len(pcm) % 2], dtype=' None: + self.frame = frame + self.prime = prime + self.max_buffer = max_buffer + self.flush_after = flush_after + self._clock = clock + self._lock = threading.Lock() + self._streams: dict[int, _Stream] = {} + + def push(self, speaker: int, samples: np.ndarray) -> None: + """Queue *samples* (16 kHz mono int16) from *speaker*. Any thread.""" + if not samples.size: + return + with self._lock: + stream = self._streams.get(speaker) + if stream is None: + stream = self._streams[speaker] = _Stream() + buf = np.concatenate((stream.buf, samples.astype(' self.max_buffer: + buf = buf[buf.size - self.prime:] + stream.buf = buf + stream.last_push = self._clock() + + def pull(self) -> tuple[bytes | None, set[int]]: + """One frame of everyone mixed, and who is in it; ``(None, set())`` when nobody is.""" + now = self._clock() + parts: list[np.ndarray] = [] + speakers: set[int] = set() + with self._lock: + for speaker, stream in list(self._streams.items()): + n = stream.buf.size + if not stream.primed: + if n >= self.prime or (n and now - stream.last_push >= self.flush_after): + stream.primed = True + else: + if not n and now - stream.last_push > 5.0: + del self._streams[speaker] + continue + take = min(n, self.frame) + if take < self.frame: + stream.primed = False # ran dry: wait for a fresh cushion + if not take: + continue + parts.append(stream.buf[:take]) + stream.buf = stream.buf[take:] + speakers.add(speaker) + if not parts: + return None, speakers + mix = np.zeros(self.frame, dtype=np.int32) + for part in parts: + mix[: part.size] += part + return _int16(mix).tobytes(), speakers + + def forget(self, speaker: int) -> None: + with self._lock: + self._streams.pop(speaker, None) + + +class PlaybackBuffer: + """The model's answer, queued as 48 kHz stereo frames for discord.py's player. + + :meth:`begin` / :meth:`feed` / :meth:`finish` come from the asyncio loop as + the response streams in; :meth:`read_frame` from the player thread every + 20 ms. While a response is still streaming, an empty buffer plays silence + (the model sends audio faster than real time, so that's a brief gap); once + it's finished and drained, :meth:`read_frame` returns ``b''`` and the + player stops — the bot only "speaks" while it has something to say. + """ + + def __init__(self, *, max_underrun_frames: int = 250) -> None: + self._lock = threading.Lock() + self._buf = bytearray() + self._open = False + self._underrun = 0 + self._max_underrun = max_underrun_frames # 5 s of waiting for a stalled response + self._up = Upsampler() + + def begin(self) -> None: + with self._lock: + self._open = True + self._underrun = 0 + + def feed(self, pcm24k: bytes) -> None: + data = self._up.process(pcm24k) + with self._lock: + self._buf += data + + def finish(self) -> None: + with self._lock: + self._open = False + + def clear(self) -> None: + """Drop everything queued (the bot was interrupted).""" + with self._lock: + self._buf.clear() + self._open = False + self._up = Upsampler() + + @property + def has_audio(self) -> bool: + with self._lock: + return bool(self._buf) + + @property + def queued_seconds(self) -> float: + with self._lock: + return len(self._buf) / (DISCORD_FRAME_BYTES * 50) + + def read_frame(self) -> bytes: + with self._lock: + if len(self._buf) >= DISCORD_FRAME_BYTES: + frame = bytes(self._buf[:DISCORD_FRAME_BYTES]) + del self._buf[:DISCORD_FRAME_BYTES] + self._underrun = 0 + return frame + if self._open: + self._underrun += 1 + if self._underrun <= self._max_underrun: + return _SILENCE_FRAME + self._open = False + if self._buf: + frame = bytes(self._buf) + bytes(DISCORD_FRAME_BYTES - len(self._buf)) + self._buf.clear() + return frame + return b'' + + +class PlaybackSource(discord.AudioSource): + """What ``VoiceClient.play`` reads: frames from a shared :class:`PlaybackBuffer`. + + A new source is started for each stretch of speech; ``cleanup`` leaves the + shared buffer alone. + """ + + def __init__(self, buffer: PlaybackBuffer) -> None: + self.buffer = buffer + + def read(self) -> bytes: + return self.buffer.read_frame() + + def is_opus(self) -> bool: + return False diff --git a/core/voice_call.py b/core/voice_call.py new file mode 100644 index 0000000..7bda1f1 --- /dev/null +++ b/core/voice_call.py @@ -0,0 +1,534 @@ +"""One live voice call: the bot in a voice channel, talking through a realtime model. + + people speak ─▶ ListeningVoiceClient (socket thread) ─▶ Downsampler per person + ─▶ Mixer ─▶ one 40 ms frame at a time ─▶ RealtimeVoiceClient + model answers ─▶ audio deltas ─▶ PlaybackBuffer ─▶ VoiceClient.play + ─▶ transcripts ─▶ the voice channel's chat (optional) + +The audio stream to the model never pauses (silence while nobody talks), so +the server's turn detection always has a clock to measure pauses against. +Someone talking over the bot cuts its playback and cancels the response +(barge-in). A watchdog ends the call when everyone left, nobody spoke for a +while, the call reached its time limit, or the voice connection is gone. +""" + +from __future__ import annotations + +import asyncio +import base64 +import inspect +import logging +import time +from collections import deque +from collections.abc import Awaitable, Callable +from typing import Any + +import discord + +from core.realtime_voice import error_code, error_message +from core.voice_audio import INPUT_RATE, Downsampler, Mixer, PlaybackBuffer, PlaybackSource + +logger = logging.getLogger(__name__) + +_ATTRIBUTION_SLACK_MS = 300 # VAD timestamps vs. when each speaker's audio went out +_TIMELINE_MS = 300_000 + + +def user_line(names: list[str], text: str) -> str: + who = ', '.join(discord.utils.escape_markdown(n) for n in names) + return f'🎙️ **{who}:** {text}' if who else f'🎙️ {text}' + + +class _Line: + """One transcript line: queued in conversation order, posted once its text is known. + + A bot line is marked ``cut`` when someone talks over it — which usually + happens after the model finished generating (it streams faster than it + speaks), so a line that's already posted gets edited to show it. + """ + + __slots__ = ('ready', 'text', 'cut', 'message') + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self.ready: asyncio.Future = loop.create_future() + self.text: str | None = None + self.cut = False + self.message: Any = None + + @property + def resolved(self) -> bool: + return self.ready.done() + + def resolve(self, text: str | None) -> None: + if not self.ready.done(): + self.text = text or None + self.ready.set_result(None) + + def render(self) -> str | None: + if self.text and self.cut: + return f'{self.text} …' + return self.text + + +class VoiceCall: + MIX_INTERVAL = 0.04 + # Someone talking this long while the bot speaks cuts it off. Discord only sends + # audio while a person's client hears speech, so this works in every turn + # detection mode — smart_turn_v2 reports speech only once it has judged the turn, + # usually after the person finished — and short "uhum"s and laughs don't count. + BARGE_IN_MS = 700 + + def __init__( + self, + *, + voice_client: Any, + realtime: Any, + is_bot: Callable[[int], bool], + name_of: Callable[[int], str], + transcripts: bool = True, + idle_seconds: float = 300.0, + max_seconds: float = 1800.0, + on_end: Callable[[VoiceCall], Awaitable[None] | None] | None = None, + watchdog_interval: float = 10.0, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self.vc = voice_client + self.rt = realtime + self._is_bot = is_bot + self._name_of = name_of + self.transcripts = transcripts + self.idle_seconds = idle_seconds + self.max_seconds = max_seconds + self._on_end = on_end + self._watch_interval = watchdog_interval + self._clock = clock + + self.mixer = Mixer(clock=clock) + self.playback = PlaybackBuffer() + self._downsamplers: dict[int, Downsampler] = {} # socket thread only + self._bots: dict[int, bool] = {} # socket thread only + + self.started_at = clock() + self.last_activity = self.started_at + self._lost_since: float | None = None + self._loop: asyncio.AbstractEventLoop | None = None + self._tasks: list[asyncio.Task] = [] + self._ended = False + self.end_reason = '' + + # Model state + self._responding = False + self._suppress = False # drop audio of a response we cancelled + self._talk_ms = 0 # how long people have been talking (for barge-in) + self._bot_text: list[str] = [] + self._bot_transcript = '' + + # Who spoke when, on the stream clock the server's VAD timestamps use. + self._sent_ms = 0 + self._timeline: deque[tuple[int, frozenset[int]]] = deque() + self._speech_start: dict[str, int | None] = {} + self._item_speakers: dict[str, list[str]] = {} + + # Transcript lines, posted in conversation order as their text arrives. + self._lines: asyncio.Queue[_Line | None] = asyncio.Queue() + self._user_lines: dict[str, _Line] = {} + self._bot_line: _Line | None = None + self._post_failed = False + self._side_tasks: set[asyncio.Task] = set() + + # Stats for the end-of-call log + self.turns = 0 + self.interruptions = 0 + self.errors = 0 + self._last_error = '' + self.tokens_in = 0 + self.tokens_out = 0 + self._receive_warned = False + + @property + def channel(self) -> Any: + return self.vc.channel + + @property + def ended(self) -> bool: + return self._ended + + # --- lifecycle --- + + async def start(self, greeting: str | None = None) -> None: + self._loop = asyncio.get_running_loop() + self.vc.listen(self._on_pcm) + spawn = self._loop.create_task + self._tasks = [ + spawn(self._mix_loop(), name='voice-mix'), + spawn(self._event_loop(), name='voice-events'), + spawn(self._watchdog(), name='voice-watchdog'), + ] + if self.transcripts: + self._tasks.append(spawn(self._poster(), name='voice-transcripts')) + if greeting: + try: + await self.rt.add_message('user', greeting) + await self.rt.create_response() + except ConnectionError: + pass # the event loop notices the closed socket and ends the call + + async def end(self, reason: str) -> None: + """Leave the call (idempotent): stop listening, close the model session, disconnect.""" + if self._ended: + return + self._ended = True + self.end_reason = reason + try: + await self._shutdown(reason) + finally: + if self._on_end is not None: + result = self._on_end(self) + if inspect.isawaitable(result): + await result + + async def _shutdown(self, reason: str) -> None: + current = asyncio.current_task() + poster = None + for task in self._tasks: + if task.get_name() == 'voice-transcripts': + poster = task + elif task is not current and not task.done(): + task.cancel() + try: + self.vc.stop_listening() + except Exception: + logger.debug('[voice] stop_listening failed', exc_info=True) + self.playback.clear() + try: + if self.vc.is_playing(): + self.vc.stop() + except Exception: + logger.debug('[voice] stopping playback failed', exc_info=True) + try: + await self.rt.close() + except Exception: + logger.debug('[voice] closing the realtime session failed', exc_info=True) + try: + await self.vc.disconnect(force=True) + except Exception: + logger.debug('[voice] disconnect failed', exc_info=True) + + # Let the transcript lines already waiting go out, then say goodbye. + line = self._bot_line + if line is not None and not line.resolved: + partial = self._bot_transcript or ''.join(self._bot_text).strip() + line.cut = True + line.resolve(f'🔊 {partial}' if partial else None) + for pending in self._user_lines.values(): + pending.resolve(None) + if poster is not None and poster is not current: + self._lines.put_nowait(None) + try: + await asyncio.wait_for(poster, 5) + except (asyncio.TimeoutError, asyncio.CancelledError): + poster.cancel() + await self._post(f'📴 Saí da call: {reason}.') + + receiver = getattr(self.vc, 'receiver', None) + logger.info( + '[voice] call ended in #%s after %.0fs (%s): turns=%d interruptions=%d errors=%d ' + 'tokens=%d/%d audio_sent=%.0fs receive=%s', + getattr(self.channel, 'name', '?'), self._clock() - self.started_at, reason, + self.turns, self.interruptions, self.errors, self.tokens_in, self.tokens_out, + self._sent_ms / 1000, dict(getattr(receiver, 'stats', {}) or {}), + ) + others = [t for t in self._tasks if t is not current] + if others: + await asyncio.gather(*others, return_exceptions=True) + + # --- people → model --- + + def _on_pcm(self, user_id: int, pcm: bytes) -> None: + """20 ms of someone's audio (48 kHz stereo). discord.py's socket reader thread.""" + if self._ended: + return + bot = self._bots.get(user_id) + if bot is None: + bot = self._bots[user_id] = bool(self._is_bot(user_id)) + if bot: + return # music bots and other bots aren't part of the conversation + down = self._downsamplers.get(user_id) + if down is None: + down = self._downsamplers[user_id] = Downsampler() + self.mixer.push(user_id, down.process(pcm)) + + async def _mix_loop(self) -> None: + loop = asyncio.get_running_loop() + silence = bytes(self.mixer.frame * 2) + frame_ms = self.mixer.frame * 1000 // INPUT_RATE + next_tick = loop.time() + while not self._ended: + next_tick += self.MIX_INTERVAL + delay = next_tick - loop.time() + if delay > 0: + await asyncio.sleep(delay) + elif delay < -1.0: + next_tick = loop.time() # the loop stalled: don't burst to catch up + frame, speakers = self.mixer.pull() + if speakers: + self.last_activity = self._clock() + self._timeline.append((self._sent_ms, frozenset(speakers))) + while self._timeline and self._timeline[0][0] < self._sent_ms - _TIMELINE_MS: + self._timeline.popleft() + self._talk_ms += frame_ms + if self._talk_ms >= self.BARGE_IN_MS and self._bot_speaking(): + self._talk_ms = 0 + await self._barge_in() + else: + self._talk_ms = max(0, self._talk_ms - 2 * frame_ms) # a jitter gap isn't a pause + try: + await self.rt.append_audio(frame or silence) + except ConnectionError: + return + self._sent_ms += frame_ms + + def _speakers_between(self, start_ms: int | None, end_ms: int | None) -> list[str]: + if start_ms is None or end_ms is None: + lo, hi = self._sent_ms - 10_000, self._sent_ms + else: + lo, hi = start_ms - _ATTRIBUTION_SLACK_MS, end_ms + _ATTRIBUTION_SLACK_MS + seen: list[int] = [] + for at, speakers in self._timeline: + if lo <= at <= hi: + seen.extend(s for s in sorted(speakers) if s not in seen) + return [self._name_of(s) for s in seen] + + # --- model → people --- + + async def _event_loop(self) -> None: + async for event in self.rt.events(): + if self._ended: + return + try: + await self._handle(event) + except Exception: + logger.exception('[voice] handling %s failed', event.get('type')) + if not self._ended: + if self._last_error == 'response_idle_timeout': + await self.end('a IA de voz encerrou a sessão depois de um tempo sem conversa') + else: + await self.end('a conexão com a IA de voz caiu') + + async def _handle(self, event: dict) -> None: + kind = event.get('type', '') + item = event.get('item_id') or '' + if kind == 'response.audio.delta': + if not self._suppress: + data = base64.b64decode(event.get('delta') or '') + if data: + self.playback.feed(data) + self._ensure_playing() + elif kind == 'response.audio_transcript.delta': + self._bot_text.append(event.get('delta') or '') + elif kind == 'input_audio_buffer.speech_started': + self.last_activity = self._clock() + self._speech_start[item] = event.get('audio_start_ms') + await self._barge_in() + elif kind == 'input_audio_buffer.speech_stopped': + start = self._speech_start.pop(item, None) + if self.transcripts: + self._item_speakers[item] = self._speakers_between(start, event.get('audio_end_ms')) + elif kind == 'input_audio_buffer.committed': + if self.transcripts and self._loop is not None: + line = self._user_lines[item] = _Line(self._loop) + self._lines.put_nowait(line) + elif kind == 'conversation.item.input_audio_transcription.completed': + text = (event.get('transcript') or '').strip() + names = self._item_speakers.pop(item, []) + line = self._user_lines.pop(item, None) + if line is not None: + line.resolve(user_line(names, text) if text else None) + elif kind == 'conversation.item.input_audio_transcription.failed': + self._item_speakers.pop(item, None) + line = self._user_lines.pop(item, None) + if line is not None: + line.resolve(None) + elif kind == 'response.created': + self._responding = True + self._suppress = False + self._talk_ms = 0 # only speech that starts over the answer interrupts it + self._bot_text = [] + self._bot_transcript = '' + self.playback.begin() + self._bot_line = None + if self.transcripts and self._loop is not None: + self._bot_line = _Line(self._loop) + self._lines.put_nowait(self._bot_line) + elif kind == 'response.audio_transcript.done': + # The whole text often arrives before the audio is cut short, so the + # line waits for response.done to know whether it was. + self._bot_transcript = (event.get('transcript') or '').strip() + elif kind == 'response.done': + self._finish_response(event.get('response') or {}) + elif kind == 'error': + err = event.get('error') + if isinstance(err, dict) and err.get('param') == 'response.cancel': + # Our barge-in raced the server ending (or cancelling) the response itself. + logger.debug('[voice] cancel had nothing to cancel: %s', error_message(event)) + return + self.errors += 1 + self._last_error = error_code(event) + logger.warning('[voice] realtime error in #%s: %s', getattr(self.channel, 'name', '?'), error_message(event)) + + def _finish_response(self, response: dict) -> None: + self._responding = False + self.playback.finish() + self._ensure_playing() # flush a last partial frame + status = response.get('status') + usage = response.get('usage') or {} + self.tokens_in += int(usage.get('input_tokens') or 0) + self.tokens_out += int(usage.get('output_tokens') or 0) + if status == 'completed': + self.turns += 1 + elif status == 'failed': + logger.warning('[voice] response failed: %s', response.get('status_details')) + line = self._bot_line + if line is not None: + text = self._bot_transcript or ''.join(self._bot_text).strip() + if status == 'cancelled': + line.cut = True + line.resolve(f'🔊 {text}' if text else None) + + def _bot_speaking(self) -> bool: + return self._responding or self.playback.has_audio or self.vc.is_playing() + + async def _barge_in(self) -> None: + """Someone started talking: stop talking over them.""" + cut = False + if self._responding: + cut = True + self._suppress = True + self._responding = False + try: + await self.rt.cancel_response() + except ConnectionError: + pass + if self.playback.has_audio or self.vc.is_playing(): + cut = True + self.playback.clear() + if self.vc.is_playing(): + self.vc.stop() + if not cut: + return + self.interruptions += 1 + line = self._bot_line + if line is not None and not line.cut: + line.cut = True + if line.message is not None: # already posted whole: show where it stopped + text = line.render() + if text: + task = asyncio.get_running_loop().create_task(self._edit(line.message, text)) + self._side_tasks.add(task) # the loop only keeps weak references + task.add_done_callback(self._side_tasks.discard) + + def _ensure_playing(self) -> None: + if self._ended or not self.playback.has_audio: + return + vc = self.vc + if not vc.is_connected() or vc.is_playing(): + return + try: + vc.play( + PlaybackSource(self.playback), after=self._after_play, + application='voip', signal_type='voice', bitrate=64, + ) + except discord.ClientException: + pass # a player is just finishing; its after-callback starts the next one + + def _after_play(self, error: Exception | None) -> None: + """discord.py's player thread, when a stretch of speech ends.""" + if error is not None: + logger.warning('[voice] playback error: %s', error) + loop = self._loop + if loop is not None and not loop.is_closed(): + try: + loop.call_soon_threadsafe(self._ensure_playing) + except RuntimeError: + pass + + # --- transcripts --- + + async def _poster(self) -> None: + while True: + line = await self._lines.get() + if line is None: + return + try: + await asyncio.wait_for(asyncio.shield(line.ready), 30) + except asyncio.TimeoutError: + continue + text = line.render() + if text: + line.message = await self._post(text) + cut_text = line.render() + if line.message is not None and cut_text != text: # talked over while it was being sent + await self._edit(line.message, cut_text or text) + + async def _post(self, text: str) -> Any: + if self._post_failed: + return None + try: + return await self.channel.send(text[:2000], allowed_mentions=discord.AllowedMentions.none()) + except discord.Forbidden: + self._post_failed = True + logger.info('[voice] cannot post in the chat of #%s; transcripts off for this call', + getattr(self.channel, 'name', '?')) + except Exception: + logger.debug('[voice] posting a transcript failed', exc_info=True) + return None + + async def _edit(self, message: Any, text: str) -> None: + try: + await message.edit(content=text[:2000], allowed_mentions=discord.AllowedMentions.none()) + except Exception: + logger.debug('[voice] editing a transcript failed', exc_info=True) + + # --- watchdog --- + + async def _watchdog(self) -> None: + while not self._ended: + await asyncio.sleep(self._watch_interval) + reason = self.check() + if reason: + await self.end(reason) + return + + def check(self) -> str | None: + """Why the call should end now, if it should.""" + now = self._clock() + if not self.vc.is_connected(): + if self._lost_since is None: + self._lost_since = now + elif now - self._lost_since > 30: + return 'perdi a conexão com a call' + return None + self._lost_since = None + if not any(not m.bot for m in getattr(self.channel, 'members', ())): + return 'todo mundo saiu da call' + if now - self.last_activity > self.idle_seconds: + return f'ninguém falou nada por {round(self.idle_seconds / 60)} min' + if now - self.started_at > self.max_seconds: + return f'a call chegou ao limite de {round(self.max_seconds / 60)} min' + self._check_receive() + return None + + def _check_receive(self) -> None: + stats = getattr(getattr(self.vc, 'receiver', None), 'stats', None) + if not stats or self._receive_warned: + return + if stats.get('packets', 0) >= 250 and not stats.get('decoded', 0): + self._receive_warned = True + state = getattr(self.vc, '_connection', None) + session = getattr(state, 'dave_session', None) + logger.warning( + '[voice] %d packets from the voice server in #%s but none decoded: %s ' + '(dave protocol=%s ready=%s)', + stats['packets'], getattr(self.channel, 'name', '?'), dict(stats), + getattr(state, 'dave_protocol_version', None), getattr(session, 'ready', None), + ) diff --git a/core/voice_receive.py b/core/voice_receive.py new file mode 100644 index 0000000..eaab3e9 --- /dev/null +++ b/core/voice_receive.py @@ -0,0 +1,273 @@ +"""Hearing a Discord voice channel with discord.py, which only knows how to speak. + +discord.py 2.7 sends voice — including Discord's DAVE end-to-end encryption, +mandatory since March 2026 — but has no receive API (the old +``discord-ext-voice-recv`` extension predates DAVE and is unmaintained). It +does expose the three hooks a receiver needs, and :class:`ListeningVoiceClient` +uses them: + +- the voice websocket ``hook``: SPEAKING (op 5) says which user sends each RTP + ``ssrc``; CLIENT_DISCONNECT (op 13) says when they leave; +- ``add_socket_listener``: every UDP datagram from the voice server, on + discord.py's socket reader thread; +- the connection's live ``davey.DaveSession``: the MLS group keys. + +Each packet is unwrapped in three layers — the transport encryption +(``aead_xchacha20_poly1305_rtpsize``, the only mode discord.py offers that +Discord still accepts), then DAVE (keyed per sender), then opus — and the +result, 20 ms of 48 kHz stereo PCM, goes to a callback on that same thread. +""" + +from __future__ import annotations + +import logging +import struct +from collections import Counter +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import discord +import nacl.bindings +import nacl.exceptions +from discord import opus +from discord.gateway import DiscordVoiceWebSocket +from discord.voice_state import VoiceConnectionState + +try: + import davey # type: ignore +except ImportError: # discord.py refuses to open voice without it anyway + davey = None + +logger = logging.getLogger(__name__) + +_RTP_HEADER = struct.Struct('>BBHII') +OPUS_PAYLOAD_TYPE = 0x78 +# The one transport mode decrypt_rtp handles: the only one discord.py offers that +# Discord still accepts (the xsalsa20 modes were retired in November 2024). +TRANSPORT_MODE = 'aead_xchacha20_poly1305_rtpsize' +# What Discord clients send when they stop talking; never DAVE-encrypted. +SILENCE_FRAME = b'\xf8\xff\xfe' +_TAG = 16 # Poly1305 tag +_NONCE = 4 # rtpsize modes append a 32-bit counter instead of a full nonce + +AudioCallback = Callable[[int, bytes], None] + + +class PacketError(ValueError): + """Not a well-formed RTP packet.""" + + +class DaveError(RuntimeError): + """The E2EE layer couldn't be removed (yet).""" + + +@dataclass(frozen=True) +class RtpPacket: + sequence: int + timestamp: int + ssrc: int + payload: bytes # transport-decrypted, header extension stripped + + +def is_rtcp(data: bytes) -> bool: + """RTCP shares the socket; its packet types (200–204) fill the second byte.""" + return len(data) > 1 and 200 <= data[1] <= 204 + + +def decrypt_rtp(data: bytes, key: bytes) -> RtpPacket | None: + """Remove the transport encryption from one RTP packet. + + In the ``rtpsize`` modes the fixed header, the CSRCs and the 4-byte + extension header are authenticated but left in clear; the extension body + is encrypted along with the payload, so it's stripped after decrypting. + The nonce is the 32-bit counter appended to the packet, zero-padded. + Returns None for packets that aren't opus audio. Raises + :class:`PacketError` or ``nacl.exceptions.CryptoError``. + """ + if len(data) < 12 + _TAG + _NONCE: + raise PacketError(f'{len(data)} bytes') + b0, b1, sequence, timestamp, ssrc = _RTP_HEADER.unpack_from(data) + if b0 >> 6 != 2: + raise PacketError('not RTP v2') + if b1 & 0x7F != OPUS_PAYLOAD_TYPE: + return None + header_len = 12 + 4 * (b0 & 0x0F) + ext_words = 0 + if b0 & 0x10: + if len(data) < header_len + 4: + raise PacketError('truncated extension header') + ext_words = struct.unpack_from('>H', data, header_len + 2)[0] + header_len += 4 + if len(data) < header_len + _TAG + _NONCE: + raise PacketError('no payload') + nonce = data[-_NONCE:] + bytes(24 - _NONCE) + plain = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_decrypt( + bytes(data[header_len:-_NONCE]), bytes(data[:header_len]), nonce, key, + ) + if ext_words: + plain = plain[4 * ext_words:] + if b0 & 0x20 and plain: # RTP padding: the last byte says how much + plain = plain[: len(plain) - plain[-1]] + return RtpPacket(sequence, timestamp, ssrc, plain) + + +def strip_dave(state: Any, user_id: int, frame: bytes) -> bytes: + """The opus frame inside DAVE's per-sender encryption. + + *state* is discord.py's ``VoiceConnectionState``, which owns the session + and follows Discord's protocol transitions. Calls that aren't E2EE + (protocol 0, or downgraded) pass frames through. Raises :class:`DaveError`. + """ + if not getattr(state, 'dave_protocol_version', 0): + return frame + session = getattr(state, 'dave_session', None) + if session is None or not session.ready or davey is None: + raise DaveError('session not ready') + try: + return session.decrypt(user_id, davey.MediaType.audio, frame) + except BaseException as e: # pyo3 panics derive from BaseException + if isinstance(e, (KeyboardInterrupt, SystemExit)): + raise + reason = str(e) or repr(e) + if 'UnencryptedWhenPassthroughDisabled' in reason: + # A sender still outside the MLS group (a transition gap) sends + # plain opus; it decodes fine as it is. + return frame + raise DaveError(reason) from None + + +class VoiceReceiver: + """Turns the voice server's datagrams into ``on_audio(user_id, pcm)`` calls. + + ``pcm`` is 20 ms of 48 kHz stereo s16le per packet. Runs on discord.py's + socket reader thread; the SSRC map is filled from the voice websocket on + the event loop (plain dict operations, atomic under the GIL). ``stats`` + counts what happened to every packet, for the logs. + """ + + def __init__(self, voice_client: Any, on_audio: AudioCallback | None = None) -> None: + self.voice_client = voice_client + self.on_audio = on_audio + self.ssrc_users: dict[int, int] = {} + self._decoders: dict[int, opus.Decoder] = {} + self._key_src: Any = None + self._key = b'' + self.stats: Counter[str] = Counter() + self._logged_error = False + + # --- voice websocket side (event loop) --- + + def on_ws_message(self, msg: dict) -> None: + op = msg.get('op') + data = msg.get('d') or {} + if op == DiscordVoiceWebSocket.SPEAKING: + ssrc, user_id = data.get('ssrc'), data.get('user_id') + if ssrc is not None and user_id is not None: + self.ssrc_users[int(ssrc)] = int(user_id) + elif op == DiscordVoiceWebSocket.CLIENT_DISCONNECT: + user_id = data.get('user_id') + if user_id is not None: + self.forget_user(int(user_id)) + elif op == DiscordVoiceWebSocket.SESSION_DESCRIPTION: + # A new voice session (first connect or a reconnect): the decoders' + # state belongs to the old streams. + self._decoders.clear() + + def forget_user(self, user_id: int) -> None: + for ssrc in [s for s, u in self.ssrc_users.items() if u == user_id]: + self.ssrc_users.pop(ssrc, None) + self._decoders.pop(ssrc, None) + + # --- socket side (reader thread) --- + + def _secret_key(self) -> bytes: + """The session's transport key ('' before Discord sent one).""" + src = self.voice_client.secret_key + if src is not self._key_src: + self._key_src = src + self._key = bytes(src) if isinstance(src, (list, bytes, bytearray)) else b'' + return self._key + + def feed(self, data: bytes) -> None: + stats = self.stats + stats['packets'] += 1 + try: + if is_rtcp(data): + stats['rtcp'] += 1 + return + key = self._secret_key() + if not key: + stats['no_key'] += 1 + return + if getattr(self.voice_client, 'mode', TRANSPORT_MODE) != TRANSPORT_MODE: + stats['unsupported_mode'] += 1 + return + packet = decrypt_rtp(data, key) + if packet is None: + stats['not_audio'] += 1 + return + user_id = self.ssrc_users.get(packet.ssrc) + if user_id is None: + stats['unknown_ssrc'] += 1 + return + if packet.payload == SILENCE_FRAME: + stats['silence'] += 1 + return + frame = strip_dave(self.voice_client._connection, user_id, packet.payload) + decoder = self._decoders.get(packet.ssrc) + if decoder is None: + decoder = self._decoders[packet.ssrc] = opus.Decoder() + pcm = decoder.decode(frame, fec=False) + except nacl.exceptions.CryptoError: + stats['transport_fail'] += 1 + return + except DaveError: + stats['dave_fail'] += 1 + return + except opus.OpusError: + stats['opus_fail'] += 1 + return + except PacketError: + stats['malformed'] += 1 + return + except Exception: + stats['errors'] += 1 + if not self._logged_error: + self._logged_error = True + logger.exception('[voice] receive failed on a packet') + return + stats['decoded'] += 1 + callback = self.on_audio + if callback is not None: + try: + callback(user_id, pcm) + except Exception: + stats['callback_errors'] += 1 + logger.exception('[voice] audio callback failed') + + +class ListeningVoiceClient(discord.VoiceClient): + """A ``VoiceClient`` that can also hear the channel. + + ``channel.connect(cls=ListeningVoiceClient)``, then :meth:`listen`. + """ + + def __init__(self, client: discord.Client, channel: discord.abc.Connectable) -> None: + # Before super(): the connection state it creates holds our websocket hook. + self.receiver = VoiceReceiver(self) + super().__init__(client, channel) + + def create_connection_state(self) -> VoiceConnectionState: + return VoiceConnectionState(self, hook=self._voice_ws_hook) + + async def _voice_ws_hook(self, ws: DiscordVoiceWebSocket, msg: dict) -> None: + self.receiver.on_ws_message(msg) + + def listen(self, on_audio: AudioCallback) -> None: + self.receiver.on_audio = on_audio + self._connection.add_socket_listener(self.receiver.feed) + + def stop_listening(self) -> None: + self._connection.remove_socket_listener(self.receiver.feed) + self.receiver.on_audio = None diff --git a/main.py b/main.py index fea441e..ddbf4d7 100644 --- a/main.py +++ b/main.py @@ -60,6 +60,7 @@ 'cogs.monitors', 'cogs.summary', 'cogs.wrapped', + 'cogs.voice', ] diff --git a/requirements.txt b/requirements.txt index 6c8453e..71a4f77 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,12 @@ aiohttp>=3.11.0 mcp>=1.10.0,<2 cachetools>=5.5.0 -discord.py>=2.5.0 +# [voice] adds PyNaCl and davey, for /voz. Capped below 2.8 because voice receive +# (core/voice_receive.py) builds on discord.py's voice internals: recheck it on upgrade. +discord.py[voice]>=2.7.0,<2.8 +# davey 0.2 changed how DAVE keys rotate and discord.py 2.7 doesn't follow yet: the bot +# joins calls but nobody hears it (Rapptz/discord.py#10549, fix pending in #10548). +davey>=0.1.7,<0.2 numpy>=1.26.0 openai>=1.30.0 Pillow>=10.0.0 diff --git a/tests/test_realtime_voice.py b/tests/test_realtime_voice.py new file mode 100644 index 0000000..8075238 --- /dev/null +++ b/tests/test_realtime_voice.py @@ -0,0 +1,148 @@ +"""The Qwen-Audio realtime client, against a local fake of the server.""" + +import base64 +import json + +from aiohttp import web +import pytest + +from core.realtime_voice import RealtimeError, RealtimeVoiceClient, error_message, realtime_url + +from helpers import check + + +class FakeServer: + """Speaks just enough of the realtime protocol: session handshake, audio in, one response.""" + + def __init__(self, *, reject=None, bad_update=False, silent=False, hang_up=False): + self.reject = reject + self.bad_update = bad_update + self.silent = silent + self.hang_up = hang_up + self.headers = {} + self.query = {} + self.events = [] + self.audio = bytearray() + + async def handler(self, request): + self.headers = dict(request.headers) + self.query = dict(request.query) + if self.reject: + return web.Response(status=self.reject) + ws = web.WebSocketResponse() + await ws.prepare(request) + if self.hang_up: + await ws.close() + return ws + if not self.silent: + await ws.send_json({'type': 'session.created', 'session': {'id': 'sess_1'}}) + async for msg in ws: + event = json.loads(msg.data) + self.events.append(event) + kind = event['type'] + if kind == 'session.update': + if self.bad_update: + await ws.send_json({'type': 'error', 'error': {'message': 'Voice not supported: nope', 'code': 'invalid_value', 'param': 'voice'}}) + else: + await ws.send_json({'type': 'session.updated', 'session': event['session']}) + elif kind == 'input_audio_buffer.append': + self.audio += base64.b64decode(event['audio']) + elif kind == 'response.create': + await ws.send_json({'type': 'response.created', 'response': {'id': 'r1'}}) + await ws.send_str('not json') + await ws.send_json({'type': 'response.audio.delta', 'delta': base64.b64encode(b'\x01\x00' * 4).decode()}) + await ws.send_json({'type': 'response.done', 'response': {'status': 'completed'}}) + await ws.close() + return ws + + +async def serve(fake): + app = web.Application() + app.router.add_get('/api-ws/v1/realtime', fake.handler) + runner = web.AppRunner(app) + await runner.setup() + await web.TCPSite(runner, '127.0.0.1', 0).start() + return runner, f'ws://127.0.0.1:{runner.addresses[0][1]}/api-ws/v1/realtime' + + +def test_url_gets_the_model(): + check('appended', realtime_url('wss://h/api-ws/v1/realtime', 'm1') == 'wss://h/api-ws/v1/realtime?model=m1') + check('kept when given', realtime_url('wss://h/x?model=m0', 'm1') == 'wss://h/x?model=m0') + check('other params kept', realtime_url('wss://h/x?a=1', 'm1') == 'wss://h/x?a=1&model=m1') + + +def test_error_messages(): + check('message', error_message({'type': 'error', 'error': {'message': 'bad', 'code': 'x'}}) == 'bad') + check('code when no message', error_message({'error': {'code': 'quota'}}) == 'quota') + check('plain string', error_message({'error': 'oops'}) == 'oops') + + +async def test_full_exchange(): + fake = FakeServer() + runner, url = await serve(fake) + try: + client = RealtimeVoiceClient(url, 'sk-test', 'qwen-audio-3.0-realtime-plus') + session = await client.connect({'voice': 'longanqian', 'instructions': 'oi'}) + check('bearer key', fake.headers.get('Authorization') == 'Bearer sk-test', fake.headers) + check('model in the URL', fake.query.get('model') == 'qwen-audio-3.0-realtime-plus', fake.query) + check('confirmed session returned', session == {'voice': 'longanqian', 'instructions': 'oi'}, session) + check('open', not client.closed) + + await client.append_audio(b'\x02\x00' * 320) + await client.add_message('user', '[cumprimente]') + await client.create_response() + events = [e['type'] async for e in client.events()] + check('server events, bad frames skipped', events == ['response.created', 'response.audio.delta', 'response.done'], events) + check('audio arrived', bytes(fake.audio) == b'\x02\x00' * 320 and client.audio_bytes_sent == 640) + item = next(e for e in fake.events if e['type'] == 'conversation.item.create')['item'] + check('text item', item == {'type': 'message', 'role': 'user', 'content': [{'type': 'input_text', 'text': '[cumprimente]'}]}, item) + + await client.close() + check('closed', client.closed) + with pytest.raises(ConnectionError): + await client.cancel_response() + finally: + await runner.cleanup() + + +async def test_refused_key(): + runner, url = await serve(FakeServer(reject=401)) + try: + client = RealtimeVoiceClient(url, 'sk-bad', 'm') + with pytest.raises(RealtimeError, match='chave'): + await client.connect({}) + check('cleaned up', client.closed) + finally: + await runner.cleanup() + + +async def test_rejected_session_settings(): + runner, url = await serve(FakeServer(bad_update=True)) + try: + client = RealtimeVoiceClient(url, 'k', 'm') + with pytest.raises(RealtimeError, match=r'\(invalid_value\)') as refused: + await client.connect({'voice': 'nope'}) + check('people see the code, not what the server echoed', 'nope' not in str(refused.value), str(refused.value)) + check('socket closed after the failure', client.closed) + finally: + await runner.cleanup() + + +async def test_server_that_never_answers_or_hangs_up(): + runner, url = await serve(FakeServer(silent=True)) + try: + with pytest.raises(RealtimeError, match='não respondeu'): + await RealtimeVoiceClient(url, 'k', 'm', timeout=0.3).connect({}) + finally: + await runner.cleanup() + runner, url = await serve(FakeServer(hang_up=True)) + try: + with pytest.raises(RealtimeError, match='fechou'): + await RealtimeVoiceClient(url, 'k', 'm').connect({}) + finally: + await runner.cleanup() + + +async def test_nothing_listening(): + with pytest.raises(RealtimeError, match='conectar'): + await RealtimeVoiceClient('ws://127.0.0.1:1/x', 'k', 'm', timeout=2).connect({}) diff --git a/tests/test_voice_audio.py b/tests/test_voice_audio.py new file mode 100644 index 0000000..554e928 --- /dev/null +++ b/tests/test_voice_audio.py @@ -0,0 +1,205 @@ +"""Voice-call audio: resampling, the per-speaker mixer and the playback buffer.""" + +import numpy as np + +from core.voice_audio import ( + DISCORD_FRAME_BYTES, + Downsampler, + Mixer, + PlaybackBuffer, + PlaybackSource, + Upsampler, +) + +from helpers import check + + +def tone(freq, seconds, rate, amp=8000): + t = np.arange(int(seconds * rate)) / rate + return (amp * np.sin(2 * np.pi * freq * t)).astype(' 13000].sum() / spec.sum() + check('the 23 kHz image of zero-stuffing is gone (< -50 dB)', image < 1e-5, image) + + +def test_upsampler_is_seamless_across_uneven_chunks(): + pcm = tone(700, 0.5, 24000).tobytes() + whole = Upsampler().process(pcm) + u = Upsampler() + check('same samples whole or in pieces', b''.join(chunked(u.process, pcm, 2)) == whole) + check('empty input, empty output', Upsampler().process(b'') == b'') + + +class Clock: + def __init__(self): + self.t = 100.0 + + def __call__(self): + return self.t + + +def samples(*values): + return np.array(values, dtype=' deadline: + raise AssertionError('condition not reached') + await asyncio.sleep(0.01) + + +async def test_people_reach_the_model_and_bots_dont(): + call, vc, rt, _, _ = make_call() + await call.start() + for _ in range(10): + vc.on_audio(ANA, speech()) + vc.on_audio(MUSIC_BOT, speech(freq=1000)) + await wait_for(lambda: rt.frames >= 8) + heard = set().union(*(s for _, s in call._timeline)) + check('Ana mixed in, the music bot never', heard == {ANA}, heard) + samples = np.frombuffer(bytes(rt.audio), ' 1000, len(rt.audio)) + frames = rt.frames + await wait_for(lambda: rt.frames >= frames + 3) # nobody talking: silence keeps the server's clock running + check('silence after the speech', not np.frombuffer(bytes(rt.audio[-1280:]), '')) + check('no personality, no block', '\n' not in voice_instructions( + server='S', channel='c', caller='a', participants=[], now='n')) + + +def test_servers_opt_in(): + setting = SETTINGS['voice'] + check('per server, off by default', (setting.scope, setting.kind, setting.default) == ('guild', 'bool', False)) + + +async def test_voice_cog_stays_out_unless_enabled(): + import cogs.voice as voice_cog + + added = [] + await voice_cog.setup(NS(add_cog=lambda cog: added.append(cog))) + check('VOICE_ENABLED is off in tests', added == []) + config = voice_cog.session_config('instr') + check('session asks for speech in and out', + config['modalities'] == ['audio', 'text'] and config['instructions'] == 'instr' + and config['turn_detection']['type'] == voice_cog.VOICE_TURN_DETECTION + and config['input_audio_format'] == config['output_audio_format'] == 'pcm', config) + + +async def test_a_failing_cleanup_still_releases_the_call(): + call, vc, rt, _, ended = make_call() + await call.start() + + async def broken_close(): + raise RuntimeError('socket exploded') + + rt.close = broken_close + await call.end('fim') + check('forgotten anyway, voice left', ended == [call] and vc.disconnected) + + +def voice_cog(*, enabled=True, calls=None): + import cogs.voice as voice_cog_mod + + cog = voice_cog_mod.Voice(NS(services=NS(settings=NS(get=lambda gid, ch, key: enabled)))) + cog.calls.update(calls or {}) + return cog + + +def guild_and_member(channel, *, admin=False): + me = NS(id=1) + guild = NS(id=10, me=me) + perms = NS(manage_guild=admin, administrator=False, move_members=False) + member = NS(voice=NS(channel=channel) if channel is not None else None, guild_permissions=perms) + return guild, member + + +class VoiceChannelStub: + mention = '<#20>' + + def __init__(self, *, connect=True, speak=True, user_limit=0, members=2): + self._perms = NS(connect=connect, speak=speak, move_members=False) + self.user_limit = user_limit + self.members = [NS(bot=False)] * members + + def permissions_for(self, who): + return self._perms + + +def test_voice_cog_join_checks(): + channel = VoiceChannelStub() + guild, member = guild_and_member(channel) + check('all good', voice_cog()._join_problem(guild, member) is None) + + off = voice_cog(enabled=False) + check('server opted out (member)', 'Um admin' in off._join_problem(guild, member)) + check('server opted out (admin gets the command)', + '/config servidor opcao:Conversa por voz' in off._join_problem(*guild_and_member(channel, admin=True))) + check('not in a call', 'Entre numa call' in voice_cog()._join_problem(*guild_and_member(None))) + + busy = NS(ended=False, channel=channel) + check('already here', voice_cog(calls={10: busy})._join_problem(guild, member) == 'Já estou nesta call.') + elsewhere = NS(ended=False, channel=NS(mention='<#30>')) + check('in another call here', '<#30>' in voice_cog(calls={10: elsewhere})._join_problem(guild, member)) + leaving = NS(ended=True, channel=channel) + check('still leaving the last one', 'saindo' in voice_cog(calls={10: leaving})._join_problem(guild, member)) + check('global cap', 'máximo' in voice_cog(calls={99: busy})._join_problem(guild, member)) + + mute = VoiceChannelStub(speak=False) + check('needs Speak', 'Falar' in voice_cog()._join_problem(*guild_and_member(mute))) + full = VoiceChannelStub(user_limit=2, members=2) + check('full call', 'cheia' in voice_cog()._join_problem(*guild_and_member(full))) + + +async def test_cut_while_its_line_is_being_sent_still_shows(): + call, vc, rt, channel, _ = make_call() + sending = asyncio.Event() + release = asyncio.Event() + plain_send = channel.send + + async def slow_send(text, **kw): # Discord takes a moment to answer + sending.set() + await release.wait() + return await plain_send(text, **kw) + + channel.send = slow_send + await call.start() + rt.emit('response.created', response={'id': 'r1'}) + rt.emit('response.audio.delta', delta=answer_audio(3.0)) + rt.emit('response.audio_transcript.done', transcript='Resposta') + rt.emit('response.done', response={'status': 'completed'}) + await asyncio.wait_for(sending.wait(), 2) + rt.emit('input_audio_buffer.speech_started', item_id='i9', audio_start_ms=100) + await wait_for(lambda: call.interruptions == 1) + release.set() + await wait_for(lambda: channel.messages and channel.messages[0].edits) + check('fixed up once it was sent', channel.posts == ['🔊 Resposta …'], channel.posts) + await call.end('fim') + + +async def test_the_model_hanging_up_on_a_quiet_call_says_so(): + call, _, rt, channel, ended = make_call() + await call.start() + rt.emit('error', error={'code': 'response_idle_timeout', 'message': 'Response idle timeout'}) + await rt.close() + await wait_for(lambda: ended) + check('honest reason', 'sem conversa' in call.end_reason, call.end_reason) diff --git a/tests/test_voice_receive.py b/tests/test_voice_receive.py new file mode 100644 index 0000000..9268f1e --- /dev/null +++ b/tests/test_voice_receive.py @@ -0,0 +1,244 @@ +"""Voice receive: RTP transport decryption, the DAVE layer, opus, and the discord.py hooks.""" + +import asyncio +import struct +from types import SimpleNamespace as NS + +import davey +import discord +import nacl.exceptions +import nacl.secret +import numpy as np +import pytest + +from core.voice_receive import ( + SILENCE_FRAME, + DaveError, + ListeningVoiceClient, + PacketError, + VoiceReceiver, + decrypt_rtp, + is_rtcp, + strip_dave, +) + +from helpers import check + +KEY = bytes(range(32)) + +try: + discord.opus.Decoder() + HAVE_OPUS = True +except discord.opus.OpusNotLoaded: + HAVE_OPUS = False +needs_opus = pytest.mark.skipif(not HAVE_OPUS, reason='libopus not installed') + + +def rtp(payload, *, ssrc=111, seq=1, ext=b'', csrcs=(), counter=7, pt=0x78, key=KEY): + """A packet the way Discord sends one in aead_xchacha20_poly1305_rtpsize.""" + b0 = 0x80 | len(csrcs) | (0x10 if ext else 0) + header = struct.pack('>BBHII', b0, pt, seq, seq * 960, ssrc) + header += b''.join(struct.pack('>I', c) for c in csrcs) + plain = payload + if ext: # the 4-byte extension header stays in clear; its body is encrypted with the payload + header += b'\xbe\xde' + struct.pack('>H', len(ext) // 4) + plain = ext + payload + nonce = struct.pack('>I', counter) + bytes(20) + return header + nacl.secret.Aead(key).encrypt(plain, header, nonce).ciphertext + nonce[:4] + + +def test_decrypts_the_rtpsize_transport(): + packet = decrypt_rtp(rtp(b'opus-frame', ssrc=42, seq=9), KEY) + check('payload', packet.payload == b'opus-frame', packet) + check('header fields', (packet.ssrc, packet.sequence, packet.timestamp) == (42, 9, 9 * 960), packet) + + +def test_strips_the_encrypted_header_extension(): + ext = b'\x10\xff\x00\x00' + b'\x22\x01\x02\x00' # audio level + another element, 2 words + check('extension body removed', decrypt_rtp(rtp(b'opus', ext=ext), KEY).payload == b'opus') + + +def test_skips_csrcs(): + check('payload after the CSRC list', decrypt_rtp(rtp(b'opus', csrcs=(5, 6)), KEY).payload == b'opus') + + +def test_reads_what_discord_py_itself_sends(): + """Same packet layout as discord.py's sender (which is Discord's).""" + sender = NS(secret_key=list(KEY), _incr_nonce=3, checked_add=lambda *a: None) + header = bytearray(12) + header[0], header[1] = 0x80, 0x78 + struct.pack_into('>HII', header, 2, 7, 6720, 99) + data = discord.VoiceClient._encrypt_aead_xchacha20_poly1305_rtpsize(sender, bytes(header), b'frame') + packet = decrypt_rtp(data, KEY) + check('round trip through discord.py', packet.payload == b'frame' and packet.ssrc == 99, packet) + + +def test_rejects_bad_packets(): + with pytest.raises(nacl.exceptions.CryptoError): + decrypt_rtp(rtp(b'opus', key=bytes(32)), KEY) + tampered = bytearray(rtp(b'opus')) + tampered[14] ^= 1 + with pytest.raises(nacl.exceptions.CryptoError): + decrypt_rtp(bytes(tampered), KEY) + with pytest.raises(PacketError): + decrypt_rtp(b'\x80\x78' + bytes(10), KEY) + with pytest.raises(PacketError): + decrypt_rtp(b'\x40' + rtp(b'opus')[1:], KEY) # RTP version 1 + check('non-opus payload type ignored', decrypt_rtp(rtp(b'x', pt=0x60), KEY) is None) + + +def test_tells_rtcp_from_rtp(): + check('RTCP receiver report', is_rtcp(bytes([0x81, 201]) + bytes(30))) + check('RTP audio', not is_rtcp(rtp(b'opus'))) + + +class FakeDave: + def __init__(self, *, ready=True, error=None): + self.ready = ready + self.error = error + self.calls = [] + + def decrypt(self, user_id, media_type, frame): + self.calls.append((user_id, media_type)) + if self.error is not None: + raise self.error + return frame[2:] # "decrypt": drop a 2-byte wrapper + + +class PanicException(BaseException): + """What pyo3 raises when Rust code panics.""" + + +def test_dave_layer(): + plain = NS(dave_protocol_version=0, dave_session=None) + check('no E2EE: frame untouched', strip_dave(plain, 1, b'abc') == b'abc') + + session = FakeDave() + state = NS(dave_protocol_version=1, dave_session=session) + check('decrypted with the sender\'s id', strip_dave(state, 42, b'XXopus') == b'opus') + check('as audio', session.calls == [(42, davey.MediaType.audio)], session.calls) + + with pytest.raises(DaveError): + strip_dave(NS(dave_protocol_version=1, dave_session=None), 1, b'x') + with pytest.raises(DaveError): + strip_dave(NS(dave_protocol_version=1, dave_session=FakeDave(ready=False)), 1, b'x') + + in_transition = FakeDave(error=RuntimeError('DecryptionFailed(UnencryptedWhenPassthroughDisabled)')) + check('plain opus from a sender not in the group yet passes', + strip_dave(NS(dave_protocol_version=1, dave_session=in_transition), 1, b'opus') == b'opus') + with pytest.raises(DaveError): + strip_dave(NS(dave_protocol_version=1, dave_session=FakeDave(error=PanicException('boom'))), 1, b'x') + + +def test_a_real_dave_session_without_a_group_is_not_ready(): + session = davey.DaveSession(1, 1234, 5678) + with pytest.raises(DaveError): + strip_dave(NS(dave_protocol_version=1, dave_session=session), 1, b'frame') + + +def voice_client(protocol=0, session=None): + return NS(secret_key=list(KEY), _connection=NS(dave_protocol_version=protocol, dave_session=session)) + + +def opus_frame(freq=440): + pcm = np.repeat((8000 * np.sin(2 * np.pi * freq * np.arange(960) / 48000)).astype('BBHII', 0x80 | 0x20, 0x78, 1, 960, 111) + nonce = struct.pack('>I', 1) + bytes(20) + data = header + nacl.secret.Aead(KEY).encrypt(padded, header, nonce).ciphertext + nonce[:4] + check('padding removed', decrypt_rtp(data, KEY).payload == b'opus') From fa6a6f9244caf2b4ea45418038ce2abe0c9e6423 Mon Sep 17 00:00:00 2001 From: Zeptiny Date: Mon, 9 Nov 2026 14:09:10 -0300 Subject: [PATCH 2/2] feat(voice): choose when to answer: wake words, silence tool, barge-in setting - VOICE_BARGE_IN_MS: how long talking over the bot stops it (0 = never). The server's speech_started no longer cuts by itself (smart_turn reports side talk it later rejects); a new answer starting still cuts the last. - VOICE_WAKE_WORDS: answer only turns whose transcript names the bot. The answer is held until that transcript arrives, then played or cancelled, unposted and deleted from the conversation. - VOICE_CAN_STAY_SILENT: a ficar_em_silencio tool the model calls instead of speaking; the prompt no longer tells it to always reply. Off when web search is on (Qwen-Audio 3.0 can't combine them). - The prompt names the bot; the greeting and join message give the wake word. Co-Authored-By: Claude Opus 5.5 --- .env.example | 3 + README.md | 11 +- cogs/voice.py | 25 ++- config.py | 16 ++ core/prompts.py | 57 +++++-- core/realtime_voice.py | 4 + core/voice_call.py | 305 ++++++++++++++++++++++++++--------- tests/test_realtime_voice.py | 2 + tests/test_voice_call.py | 219 +++++++++++++++++++++++-- 9 files changed, 534 insertions(+), 108 deletions(-) diff --git a/.env.example b/.env.example index 8fe9b35..5fcf0de 100644 --- a/.env.example +++ b/.env.example @@ -143,6 +143,9 @@ TAVILY_API_KEY= # VOICE_VOICE=longanqian # longanqian | longanlingxin | longanlingxi | longanxiaoxin | longanlufeng # VOICE_TURN_DETECTION=smart_turn_v2 # smart_turn_v2 (best with several people) | smart_turn | server_vad # VOICE_WEB_SEARCH=false # let the model search the web on its own +# VOICE_BARGE_IN_MS=700 # talking over the bot this long (ms) stops it; 0 = it always finishes +# VOICE_WAKE_WORDS= # e.g. Quill,Quil,Kill: answer only turns that say one (spellings the transcription uses) +# VOICE_CAN_STAY_SILENT=true # the model may say nothing when people talk among themselves (off while web search is on) # VOICE_TRANSCRIPTS=true # post what was heard and said in the call's text chat # VOICE_MAX_CALLS=1 # simultaneous calls across all servers # VOICE_MAX_MINUTES=30 # a call ends after this long diff --git a/README.md b/README.md index 8840fb0..e15e30d 100644 --- a/README.md +++ b/README.md @@ -255,7 +255,9 @@ The bot joins the voice channel you're in and talks with the call in real time. - **Who it hears:** everyone in the call, mixed into one stream (other bots, like music bots, are left out). The model can't tell voices apart, so it doesn't call people by name unless they say who they are - **Turns:** the model decides when someone finished (`VOICE_TURN_DETECTION`; `smart_turn_v2` understands turns semantically and ignores most cross-talk and "uhum"s) -- **Interrupting:** talking over the bot for ~0.7 s stops it mid-sentence and cancels the rest of its answer +- **Staying quiet:** people talking among themselves don't get an answer: `smart_turn_v2` already passes over most of it, and the model can also choose silence (`VOICE_CAN_STAY_SILENT`, a tool it calls instead of speaking) +- **Wake word** (`VOICE_WAKE_WORDS`, optional): the bot answers only turns that call it by name; an answer waits (≈0.3 s) for its turn's transcript and is dropped, unheard and forgotten by the model, when the name isn't in it +- **Interrupting:** talking over the bot for `VOICE_BARGE_IN_MS` (0.7 s) stops it mid-sentence and cancels the rest of its answer; so does a new answer starting while the last one is still playing - **Personality:** the server's `` block, plus voice rules (short spoken sentences, no markdown or links). No tools in calls: memories, history and docs stay in the text chat, and the bot says so instead of guessing - **Transcripts** (`VOICE_TRANSCRIPTS`): what was heard (`🎙️ **Ana:** …`, attributed by who was talking when) and what the bot said (`🔊 …`, with `…` where it was cut off) go to the call's text chat - **Leaving:** `/voz sair` (anyone in the call, or Move Members / Manage Server), everyone leaving, `VOICE_IDLE_MINUTES` without anyone talking, or `VOICE_MAX_MINUTES` in the call @@ -459,7 +461,7 @@ QuillBot/ │ ├── local_inference.py# Single-thread executor for local models │ ├── voice_receive.py # Voice receive for discord.py: RTP transport decryption, DAVE, opus, ListeningVoiceClient │ ├── voice_audio.py # Resampling (48k↔16k/24k), the per-speaker mixer, the playback buffer/source -│ ├── voice_call.py # One live call: audio both ways, barge-in, transcripts, watchdog +│ ├── voice_call.py # One live call: audio both ways, who gets an answer, barge-in, transcripts, watchdog │ ├── realtime_voice.py # Qwen-Audio realtime WebSocket client │ └── ui.py # PaginatedEmbedView, source pages ├── cogs/ @@ -715,6 +717,9 @@ cp .env.example .env # if available, otherwise create .env manually | `VOICE_VOICE` | `longanqian` | 3.0 voices: `longanqian`, `longanlingxin`, `longanlingxi`, `longanxiaoxin`, `longanlufeng`, or a cloned `voice_id` | | `VOICE_TURN_DETECTION` | `smart_turn_v2` | `smart_turn_v2` (semantic, best with several people), `smart_turn`, or `server_vad` (silence only; answers faster, interrupts more easily) | | `VOICE_WEB_SEARCH` | `false` | Let the model search the web on its own | +| `VOICE_BARGE_IN_MS` | `700` | How long someone talks over the bot before it stops and listens; `0` = it always finishes what it's saying | +| `VOICE_WAKE_WORDS` | — | Comma-separated. When set, the bot answers only turns whose transcript says one of them (case and accents ignored, whole words). List the spellings the transcription gives the name, e.g. `Quill,Quil,Kill`; the first one is what the bot tells people to call it | +| `VOICE_CAN_STAY_SILENT` | `true` | Let the model decide to say nothing when the speech wasn't for it. It's a tool call, which Qwen-Audio 3.0 can't combine with `VOICE_WEB_SEARCH`, so web search turns it off | | `VOICE_TRANSCRIPTS` | `true` | Post what was heard and said in the call's text chat | | `VOICE_MAX_CALLS` | `1` | Simultaneous calls across all servers | | `VOICE_MAX_MINUTES` | `30` | A call ends after this long | @@ -820,7 +825,7 @@ ruff check . # lint (rules configured in pyproject.toml) | `test_trajectory_replay.py` | Trajectory capture, verbatim replay, text tool-call recovery | | `test_realtime_voice.py` | The realtime voice client against a local fake server: handshake, auth, audio, events, refused keys and settings, timeouts | | `test_voice_audio.py` | Resampling (band kept, aliasing and imaging removed, seamless across chunks), the per-speaker mixer and its jitter buffer, the playback buffer | -| `test_voice_call.py` | A call with Discord and the model faked: people (not bots) reach the model, playback, transcripts in order with who spoke, barge-in from both sides, cut lines edited, the watchdog, ending | +| `test_voice_call.py` | A call with Discord and the model faked: people (not bots) reach the model, playback, transcripts in order with who spoke, barge-in (and its setting), a new answer cutting the last, the silence tool, wake words (held, released, dropped and deleted), cut lines edited, the watchdog, ending | | `test_voice_receive.py` | RTP transport decryption (incl. discord.py's own packets), header extensions, the DAVE layer, opus decoding, the voice websocket hook | | `test_wrapped.py` | Wrapped numbers, weekly/monthly schedule, automatic posts once per period, the tool | diff --git a/cogs/voice.py b/cogs/voice.py index aabcb64..dec047d 100644 --- a/cogs/voice.py +++ b/cogs/voice.py @@ -25,6 +25,8 @@ BR_TZ, VOICE_API_KEY, VOICE_AVAILABLE, + VOICE_BARGE_IN_MS, + VOICE_CAN_STAY_SILENT, VOICE_ENABLED, VOICE_IDLE_MINUTES, VOICE_MAX_CALLS, @@ -34,18 +36,24 @@ VOICE_TRANSCRIPTS, VOICE_TURN_DETECTION, VOICE_VOICE, + VOICE_WAKE_WORDS, VOICE_WEB_SEARCH, ) -from core.prompts import voice_greeting, voice_instructions +from core.prompts import VOICE_SILENCE_TOOL, voice_greeting, voice_instructions from core.realtime_voice import RealtimeError, RealtimeVoiceClient from core.voice_call import VoiceCall logger = logging.getLogger(__name__) +def can_stay_silent() -> bool: + """Whether the model gets the silence tool (Qwen-Audio 3.0 takes tools or web search, not both).""" + return VOICE_CAN_STAY_SILENT and not VOICE_WEB_SEARCH + + def session_config(instructions: str) -> dict: """The realtime session the bot asks for (``session.update``).""" - config = { + config: dict = { 'modalities': ['audio', 'text'], 'voice': VOICE_VOICE, 'instructions': instructions, @@ -55,6 +63,8 @@ def session_config(instructions: str) -> dict: } if VOICE_WEB_SEARCH: config['enable_search'] = True + elif can_stay_silent(): + config['tools'] = [VOICE_SILENCE_TOOL] return config @@ -114,9 +124,10 @@ async def entrar(self, interaction: discord.Interaction): finally: self._joining.discard(guild.id) transcribed = ' e eu escrevo a conversa no chat da call' if call.transcripts else '' + wake = f' Eu só respondo quando alguém me chama de “{VOICE_WAKE_WORDS[0]}”.' if VOICE_WAKE_WORDS else '' await interaction.followup.send( f'🎙️ Entrei em {channel.mention}. Enquanto eu estiver lá, o que vocês falarem vai para a ' - f'IA de voz (Qwen, da Alibaba Cloud){transcribed}. Para me tirar: `/voz sair`.' + f'IA de voz (Qwen, da Alibaba Cloud){transcribed}.{wake} Para me tirar: `/voz sair`.' ) @voz.command(name='sair', description='Tira o bot da call') @@ -191,7 +202,9 @@ async def _start_call( caller=member.display_name, participants=participants, now=datetime.datetime.now(BR_TZ).strftime('%d/%m/%Y %H:%M'), + name=VOICE_WAKE_WORDS[0] if VOICE_WAKE_WORDS else guild.me.display_name, persona=persona, + can_stay_silent=can_stay_silent(), ) assert VOICE_API_KEY is not None realtime = RealtimeVoiceClient(VOICE_REALTIME_URL, VOICE_API_KEY, VOICE_MODEL) @@ -216,13 +229,17 @@ async def _start_call( is_bot=lambda uid: bool(getattr(guild.get_member(uid), 'bot', False)), name_of=lambda uid: getattr(guild.get_member(uid), 'display_name', None) or str(uid), transcripts=VOICE_TRANSCRIPTS, + barge_in_ms=VOICE_BARGE_IN_MS, + wake_words=VOICE_WAKE_WORDS, idle_seconds=VOICE_IDLE_MINUTES * 60, max_seconds=VOICE_MAX_MINUTES * 60, on_end=lambda ended: self._forget(guild.id, ended), ) self.calls[guild.id] = call try: - await call.start(greeting=voice_greeting(member.display_name)) + await call.start(greeting=voice_greeting( + member.display_name, VOICE_WAKE_WORDS[0] if VOICE_WAKE_WORDS else None, + )) except Exception: logger.exception('[voice] starting the call in #%s (%s) failed', channel.name, guild.id) await call.end('não consegui começar a conversa') diff --git a/config.py b/config.py index 4701ae7..19ee812 100644 --- a/config.py +++ b/config.py @@ -354,6 +354,16 @@ def _is_openrouter_url(url: str) -> bool: # server_vad ends a turn on silence alone. VOICE_TURN_DETECTION: Final[str] = os.getenv('VOICE_TURN_DETECTION', 'smart_turn_v2').strip().lower() VOICE_WEB_SEARCH: Final[bool] = _flag('VOICE_WEB_SEARCH', 'false') # the model's built-in web search +# Someone talking over the bot this long (ms) makes it stop and listen; 0 = it always finishes. +VOICE_BARGE_IN_MS: Final[int] = max(0, int(os.getenv('VOICE_BARGE_IN_MS', '700'))) +# Comma-separated: when set, the bot only answers a turn whose transcript says one of these +# (its name, plus the spellings the transcription gives it, e.g. "Quill,Quil,Kill"). +VOICE_WAKE_WORDS: Final[tuple[str, ...]] = tuple( + w.strip() for w in os.getenv('VOICE_WAKE_WORDS', '').split(',') if w.strip() +) +# Let the model decide to say nothing when people are talking among themselves. It's a +# tool call, and Qwen-Audio 3.0 can't have tools and web search on together: web search wins. +VOICE_CAN_STAY_SILENT: Final[bool] = _flag('VOICE_CAN_STAY_SILENT') VOICE_TRANSCRIPTS: Final[bool] = _flag('VOICE_TRANSCRIPTS') # post what was heard and said in the call's chat VOICE_MAX_CALLS: Final[int] = max(1, int(os.getenv('VOICE_MAX_CALLS', '1'))) # simultaneous calls, all servers VOICE_MAX_MINUTES: Final[float] = float(os.getenv('VOICE_MAX_MINUTES', '30')) @@ -481,3 +491,9 @@ def validate_config() -> None: 'Voice calls will be disabled.', file=sys.stderr, ) + if VOICE_ENABLED and VOICE_WEB_SEARCH and VOICE_CAN_STAY_SILENT: + print( + 'WARNING: VOICE_WEB_SEARCH is on, so the voice model cannot choose to stay silent ' + '(VOICE_CAN_STAY_SILENT needs a tool, and the model cannot use tools and web search together).', + file=sys.stderr, + ) diff --git a/core/prompts.py b/core/prompts.py index ad58f06..c8c4bc6 100644 --- a/core/prompts.py +++ b/core/prompts.py @@ -367,14 +367,35 @@ def lag_spike_warning(threshold_ms: float) -> str: "" ) -VOICE_RULES = ( - "\n" +# The tool a voice model calls to say nothing (VOICE_CAN_STAY_SILENT): a speech model +# answers every turn it's given, so choosing silence has to be an action of its own. +VOICE_SILENCE_TOOL_NAME = 'ficar_em_silencio' +VOICE_SILENCE_TOOL = { + 'type': 'function', + 'function': { + 'name': VOICE_SILENCE_TOOL_NAME, + 'description': 'Não dizer nada desta vez, porque a fala não era para você ou não pede resposta.', + 'parameters': {'type': 'object', 'properties': {}}, + }, +} + +_VOICE_SPEECH = ( "- Tudo o que você responde vira fala. Fale como numa conversa: frases curtas e naturais, " "uma ou duas por vez, e deixe espaço para as pessoas responderem.\n" "- Nada de markdown, listas, links, emojis ou blocos de código. Números, siglas e termos " "técnicos do jeito que se falam.\n" +) +_VOICE_GROUP = ( "- Várias pessoas podem estar na call, e às vezes conversam entre si. Se uma fala " "claramente não foi para você, responda bem curto ou só concorde, sem puxar o assunto.\n" +) +_VOICE_GROUP_SILENT = ( + "- Várias pessoas podem estar na call, e muitas vezes conversam entre si. Nem toda fala é " + f"para você: quando falarem com outra pessoa, comentarem algo entre si ou a fala não pedir " + f"resposta sua, chame {VOICE_SILENCE_TOOL_NAME} e não diga nada. Responda quando falarem " + "com você ou fizerem ao grupo uma pergunta em que você pode ajudar.\n" +) +_VOICE_THE_REST = ( "- Você ouve todo mundo num áudio só e não sabe quem está falando: não chame ninguém pelo " "nome, a não ser que a pessoa diga quem é.\n" "- Se pedirem uma explicação longa, explique falando: os pontos principais em poucas " @@ -383,30 +404,44 @@ def lag_spike_warning(threshold_ms: float) -> str: "- Responda com o que você sabe. Nesta call você não tem as memórias do servidor, o " "histórico nem a documentação: quando a resposta depender disso, ou se não tiver certeza, " "diga isso em vez de inventar.\n" - "" ) +def voice_rules(*, can_stay_silent: bool = False) -> str: + group = _VOICE_GROUP_SILENT if can_stay_silent else _VOICE_GROUP + return f"\n{_VOICE_SPEECH}{group}{_VOICE_THE_REST}" + + def voice_instructions( - *, server: str, channel: str, caller: str, participants: list[str], now: str, persona: str = '', + *, + server: str, + channel: str, + caller: str, + participants: list[str], + now: str, + name: str = '', + persona: str = '', + can_stay_silent: bool = False, ) -> str: - """The system prompt of a voice call.""" + """The system prompt of a voice call (*name*: what the bot is called on this server).""" people = ', '.join(participants) if participants else caller + you = f"Seu nome aqui: {name}. " if name else '' context = ( "\n" - f"Servidor: {server}. Call: {channel}. Quem chamou você: {caller}. " + f"{you}Servidor: {server}. Call: {channel}. Quem chamou você: {caller}. " f"Na call quando você entrou: {people}. Agora: {now} (horário de Brasília).\n" "" ) - parts = [VOICE_ROLE, VOICE_RULES, context] + parts = [VOICE_ROLE, voice_rules(can_stay_silent=can_stay_silent), context] if persona: parts.append(persona) return '\n\n'.join(parts) -def voice_greeting(caller: str) -> str: +def voice_greeting(caller: str, wake_word: str | None = None) -> str: """The turn that makes the bot say hello when it joins (so everyone knows it's listening).""" - return ( - f"[{caller} acabou de chamar você para a call. Cumprimente a call numa frase curta e " - "diga que está ouvindo.]" + how = ( + f"diga que só responde quando alguém chama você de \"{wake_word}\"" + if wake_word else "diga que está ouvindo" ) + return f"[{caller} acabou de chamar você para a call. Cumprimente a call numa frase curta e {how}.]" diff --git a/core/realtime_voice.py b/core/realtime_voice.py index 1a6f0b8..4490ef5 100644 --- a/core/realtime_voice.py +++ b/core/realtime_voice.py @@ -177,6 +177,10 @@ async def add_message(self, role: str, text: str) -> None: 'item': {'type': 'message', 'role': role, 'content': [{'type': 'input_text', 'text': text}]}, }) + async def delete_item(self, item_id: str) -> None: + """Take an item out of the conversation, so the model doesn't remember it.""" + await self.send({'type': 'conversation.item.delete', 'item_id': item_id}) + async def create_response(self) -> None: await self.send({'type': 'response.create'}) diff --git a/core/voice_call.py b/core/voice_call.py index 7bda1f1..b5d5a8e 100644 --- a/core/voice_call.py +++ b/core/voice_call.py @@ -7,9 +7,15 @@ The audio stream to the model never pauses (silence while nobody talks), so the server's turn detection always has a clock to measure pauses against. -Someone talking over the bot cuts its playback and cancels the response -(barge-in). A watchdog ends the call when everyone left, nobody spoke for a -while, the call reached its time limit, or the voice connection is gone. + +The server decides which speech is a turn for the bot and answers it; the +model can also answer with the silence tool instead of speaking. With wake +words, an answer is held back until its turn's transcript shows someone +called the bot, and dropped otherwise. Someone talking over the bot for +``barge_in_ms`` cuts it off, and so does a new answer starting while the +last one is still playing. A watchdog ends the call when everyone left, +nobody spoke for a while, the call reached its time limit, or the voice +connection is gone. """ from __future__ import annotations @@ -18,13 +24,16 @@ import base64 import inspect import logging +import re import time +import unicodedata from collections import deque -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Iterable from typing import Any import discord +from core.prompts import VOICE_SILENCE_TOOL_NAME from core.realtime_voice import error_code, error_message from core.voice_audio import INPUT_RATE, Downsampler, Mixer, PlaybackBuffer, PlaybackSource @@ -39,6 +48,19 @@ def user_line(names: list[str], text: str) -> str: return f'🎙️ **{who}:** {text}' if who else f'🎙️ {text}' +def _fold(text: str) -> str: + """Lowercase words without accents, space-separated and space-padded, for whole-word matching.""" + text = unicodedata.normalize('NFKD', text.casefold()) + text = ''.join(c for c in text if not unicodedata.combining(c)) + return ' ' + ' '.join(re.findall(r'\w+', text)) + ' ' + + +def mentions(text: str, words: Iterable[str]) -> bool: + """Whether *text* says one of *words* (each a word or phrase, matched whole).""" + folded = _fold(text) + return any(f in folded for f in (_fold(w) for w in words) if f.strip()) + + class _Line: """One transcript line: queued in conversation order, posted once its text is known. @@ -70,13 +92,27 @@ def render(self) -> str | None: return self.text +class _Reply: + """One response of the model, from ``response.created`` until it's been heard or dropped.""" + + __slots__ = ('line', 'waits_for', 'held', 'text', 'transcript', 'done', 'muted', 'dropped') + + def __init__(self, line: _Line | None, waits_for: str | None) -> None: + self.line = line + self.waits_for = waits_for # the turn whose transcript has to call the bot first + self.held: list[bytes] = [] # its audio, meanwhile + self.text: list[str] = [] + self.transcript = '' + self.done: dict | None = None # the finished response, once generated + self.muted = False # cut off: the rest of its audio is dropped + self.dropped = False # not for the bot after all: never played, never posted, forgotten + + def said(self) -> str: + return self.transcript or ''.join(self.text).strip() + + class VoiceCall: MIX_INTERVAL = 0.04 - # Someone talking this long while the bot speaks cuts it off. Discord only sends - # audio while a person's client hears speech, so this works in every turn - # detection mode — smart_turn_v2 reports speech only once it has judged the turn, - # usually after the person finished — and short "uhum"s and laughs don't count. - BARGE_IN_MS = 700 def __init__( self, @@ -86,6 +122,8 @@ def __init__( is_bot: Callable[[int], bool], name_of: Callable[[int], str], transcripts: bool = True, + barge_in_ms: int = 700, + wake_words: Iterable[str] = (), idle_seconds: float = 300.0, max_seconds: float = 1800.0, on_end: Callable[[VoiceCall], Awaitable[None] | None] | None = None, @@ -97,6 +135,11 @@ def __init__( self._is_bot = is_bot self._name_of = name_of self.transcripts = transcripts + # Someone talking this long while the bot speaks cuts it off (0: never). Discord + # only sends audio while a person's client hears speech, so this works in every + # turn detection mode, and short "uhum"s and laughs don't count. + self.barge_in_ms = barge_in_ms + self.wake_words = tuple(w for w in wake_words if _fold(w).strip()) self.idle_seconds = idle_seconds self.max_seconds = max_seconds self._on_end = on_end @@ -117,11 +160,12 @@ def __init__( self.end_reason = '' # Model state - self._responding = False - self._suppress = False # drop audio of a response we cancelled + self._responding = False # a response is being generated + self._reply: _Reply | None = None # the latest response + self._speaking: _Reply | None = None # the one whose audio is in the playback buffer self._talk_ms = 0 # how long people have been talking (for barge-in) - self._bot_text: list[str] = [] - self._bot_transcript = '' + self._turn: str | None = None # the turn the next response answers + self._heard: dict[str, str] = {} # transcripts that came before their response (wake words) # Who spoke when, on the stream clock the server's VAD timestamps use. self._sent_ms = 0 @@ -132,12 +176,13 @@ def __init__( # Transcript lines, posted in conversation order as their text arrives. self._lines: asyncio.Queue[_Line | None] = asyncio.Queue() self._user_lines: dict[str, _Line] = {} - self._bot_line: _Line | None = None self._post_failed = False self._side_tasks: set[asyncio.Task] = set() # Stats for the end-of-call log self.turns = 0 + self.silences = 0 # the model chose not to answer + self.unaddressed = 0 # answers dropped: the turn didn't call the bot self.interruptions = 0 self.errors = 0 self._last_error = '' @@ -215,11 +260,11 @@ async def _shutdown(self, reason: str) -> None: logger.debug('[voice] disconnect failed', exc_info=True) # Let the transcript lines already waiting go out, then say goodbye. - line = self._bot_line - if line is not None and not line.resolved: - partial = self._bot_transcript or ''.join(self._bot_text).strip() - line.cut = True - line.resolve(f'🔊 {partial}' if partial else None) + reply = self._reply + if reply is not None and reply.line is not None and not reply.line.resolved: + partial = '' if reply.dropped or reply.waits_for is not None else reply.said() + reply.line.cut = True + reply.line.resolve(f'🔊 {partial}' if partial else None) for pending in self._user_lines.values(): pending.resolve(None) if poster is not None and poster is not current: @@ -232,11 +277,11 @@ async def _shutdown(self, reason: str) -> None: receiver = getattr(self.vc, 'receiver', None) logger.info( - '[voice] call ended in #%s after %.0fs (%s): turns=%d interruptions=%d errors=%d ' - 'tokens=%d/%d audio_sent=%.0fs receive=%s', + '[voice] call ended in #%s after %.0fs (%s): turns=%d silent=%d unaddressed=%d ' + 'interruptions=%d errors=%d tokens=%d/%d audio_sent=%.0fs receive=%s', getattr(self.channel, 'name', '?'), self._clock() - self.started_at, reason, - self.turns, self.interruptions, self.errors, self.tokens_in, self.tokens_out, - self._sent_ms / 1000, dict(getattr(receiver, 'stats', {}) or {}), + self.turns, self.silences, self.unaddressed, self.interruptions, self.errors, + self.tokens_in, self.tokens_out, self._sent_ms / 1000, dict(getattr(receiver, 'stats', {}) or {}), ) others = [t for t in self._tasks if t is not current] if others: @@ -277,7 +322,7 @@ async def _mix_loop(self) -> None: while self._timeline and self._timeline[0][0] < self._sent_ms - _TIMELINE_MS: self._timeline.popleft() self._talk_ms += frame_ms - if self._talk_ms >= self.BARGE_IN_MS and self._bot_speaking(): + if self.barge_in_ms and self._talk_ms >= self.barge_in_ms and self._bot_speaking(): self._talk_ms = 0 await self._barge_in() else: @@ -318,23 +363,28 @@ async def _event_loop(self) -> None: async def _handle(self, event: dict) -> None: kind = event.get('type', '') item = event.get('item_id') or '' + reply = self._reply if kind == 'response.audio.delta': - if not self._suppress: + if reply is not None and not reply.muted: data = base64.b64decode(event.get('delta') or '') - if data: - self.playback.feed(data) - self._ensure_playing() + if data and reply.waits_for is not None: + reply.held.append(data) + elif data: + self._play(reply, data) elif kind == 'response.audio_transcript.delta': - self._bot_text.append(event.get('delta') or '') + if reply is not None: + reply.text.append(event.get('delta') or '') elif kind == 'input_audio_buffer.speech_started': + # Not a barge-in by itself: smart_turn reports speech it later finds wasn't + # a turn for the bot (people talking among themselves). self.last_activity = self._clock() self._speech_start[item] = event.get('audio_start_ms') - await self._barge_in() elif kind == 'input_audio_buffer.speech_stopped': start = self._speech_start.pop(item, None) if self.transcripts: self._item_speakers[item] = self._speakers_between(start, event.get('audio_end_ms')) elif kind == 'input_audio_buffer.committed': + self._turn = item if self.transcripts and self._loop is not None: line = self._user_lines[item] = _Line(self._loop) self._lines.put_nowait(line) @@ -344,28 +394,22 @@ async def _handle(self, event: dict) -> None: line = self._user_lines.pop(item, None) if line is not None: line.resolve(user_line(names, text) if text else None) + await self._turn_heard(item, text) elif kind == 'conversation.item.input_audio_transcription.failed': self._item_speakers.pop(item, None) line = self._user_lines.pop(item, None) if line is not None: line.resolve(None) + await self._turn_heard(item, '') elif kind == 'response.created': - self._responding = True - self._suppress = False - self._talk_ms = 0 # only speech that starts over the answer interrupts it - self._bot_text = [] - self._bot_transcript = '' - self.playback.begin() - self._bot_line = None - if self.transcripts and self._loop is not None: - self._bot_line = _Line(self._loop) - self._lines.put_nowait(self._bot_line) + await self._start_response() elif kind == 'response.audio_transcript.done': # The whole text often arrives before the audio is cut short, so the # line waits for response.done to know whether it was. - self._bot_transcript = (event.get('transcript') or '').strip() + if reply is not None: + reply.transcript = (event.get('transcript') or '').strip() elif kind == 'response.done': - self._finish_response(event.get('response') or {}) + await self._finish_response(event.get('response') or {}) elif kind == 'error': err = event.get('error') if isinstance(err, dict) and err.get('param') == 'response.cancel': @@ -376,56 +420,171 @@ async def _handle(self, event: dict) -> None: self._last_error = error_code(event) logger.warning('[voice] realtime error in #%s: %s', getattr(self.channel, 'name', '?'), error_message(event)) - def _finish_response(self, response: dict) -> None: + async def _start_response(self) -> None: + turn, self._turn = self._turn, None + previous = self._reply + self._responding = False # the server starts a response only once the last one is over + if previous is not None and previous.waits_for is not None: + await self._drop(previous) # a newer turn came before its transcript did + self._responding = True + line = None + if self.transcripts and self._loop is not None: + line = _Line(self._loop) + self._lines.put_nowait(line) + # Only answers to people's speech are checked for the wake word (not the greeting). + reply = self._reply = _Reply(line, turn if self.wake_words else None) + if turn is not None and turn in self._heard: + await self._decide(reply, self._heard.pop(turn)) + + async def _turn_heard(self, item: str, text: str) -> None: + """The transcript of a turn: with wake words, it decides whether that turn's answer is heard.""" + if not self.wake_words: + return + reply = self._reply + if reply is not None and reply.waits_for == item: + await self._decide(reply, text) + else: + self._heard[item] = text # its response hasn't started yet + while len(self._heard) > 8: + del self._heard[next(iter(self._heard))] + + async def _decide(self, reply: _Reply, transcript: str) -> None: + if reply.waits_for is None: + return + if not mentions(transcript, self.wake_words): + self.unaddressed += 1 + await self._drop(reply) + return + reply.waits_for = None + held, reply.held = reply.held, [] + for chunk in held: + self._play(reply, chunk) + if reply.done is not None: + self._settle(reply) + + async def _drop(self, reply: _Reply) -> None: + """Make *reply* as if it never happened: unheard, unposted, out of the model's memory.""" + reply.dropped = reply.muted = True + reply.waits_for = None + reply.held = [] + if reply.line is not None: + reply.line.resolve(None) + if reply.done is not None: + await self._forget(reply) + elif self._responding and reply is self._reply: + self._responding = False + try: + await self.rt.cancel_response() # its items are forgotten once response.done lists them + except ConnectionError: + pass + + async def _forget(self, reply: _Reply) -> None: + for out in (reply.done or {}).get('output') or []: + if isinstance(out, dict) and out.get('id'): + try: + await self.rt.delete_item(out['id']) + except ConnectionError: + return + + async def _finish_response(self, response: dict) -> None: self._responding = False - self.playback.finish() - self._ensure_playing() # flush a last partial frame - status = response.get('status') usage = response.get('usage') or {} self.tokens_in += int(usage.get('input_tokens') or 0) self.tokens_out += int(usage.get('output_tokens') or 0) - if status == 'completed': + reply = self._reply + if reply is None: + return + reply.done = response + if reply.dropped: + await self._forget(reply) + elif reply.waits_for is None: + self._settle(reply) + # else: settled once its turn's transcript says whether it was for the bot + + def _settle(self, reply: _Reply) -> None: + """A generated reply that's being heard: let playback run out, count it, post its line.""" + if reply is self._speaking: + self.playback.finish() + self._ensure_playing() # flush a last partial frame + response = reply.done or {} + status = response.get('status') + outputs = [o for o in response.get('output') or [] if isinstance(o, dict)] + if any(o.get('type') == 'function_call' and o.get('name') == VOICE_SILENCE_TOOL_NAME for o in outputs): + self.silences += 1 + elif status == 'completed': self.turns += 1 elif status == 'failed': logger.warning('[voice] response failed: %s', response.get('status_details')) - line = self._bot_line + line = reply.line if line is not None: - text = self._bot_transcript or ''.join(self._bot_text).strip() + text = reply.said() if status == 'cancelled': line.cut = True line.resolve(f'🔊 {text}' if text else None) + def _play(self, reply: _Reply, pcm24k: bytes) -> None: + if self._speaking is not reply: + self._take_over(reply) + self.playback.feed(pcm24k) + self._ensure_playing() + + def _take_over(self, reply: _Reply) -> None: + """*reply* starts to be heard. Whatever is left of the last one stops: the server + only answers again after someone took a turn.""" + previous = self._speaking + if previous is not None and self._stop_playback(): + self._mark_cut(previous) + self.interruptions += 1 + self._speaking = reply + self._talk_ms = 0 # only speech that starts over this answer interrupts it + self.playback.begin() + def _bot_speaking(self) -> bool: return self._responding or self.playback.has_audio or self.vc.is_playing() - async def _barge_in(self) -> None: - """Someone started talking: stop talking over them.""" - cut = False - if self._responding: - cut = True - self._suppress = True - self._responding = False - try: - await self.rt.cancel_response() - except ConnectionError: - pass - if self.playback.has_audio or self.vc.is_playing(): - cut = True + def _stop_playback(self) -> bool: + """Silence the bot now; whether it was saying anything.""" + audible = self.playback.has_audio or self.vc.is_playing() + if audible: self.playback.clear() if self.vc.is_playing(): self.vc.stop() - if not cut: + return audible + + async def _barge_in(self) -> None: + """Someone is talking over the bot: stop talking, and stop the answer being generated.""" + cut = False + reply = self._reply + if self._responding and reply is not None: + if reply.waits_for is not None: + await self._drop(reply) # none of it was heard yet + else: + cut = True + reply.muted = True + self._responding = False + self._mark_cut(reply) + try: + await self.rt.cancel_response() + except ConnectionError: + pass + if self._stop_playback(): + cut = True + if self._speaking is not None: + self._mark_cut(self._speaking) + if cut: + self.interruptions += 1 + + def _mark_cut(self, reply: _Reply) -> None: + line = reply.line + if line is None or line.cut: return - self.interruptions += 1 - line = self._bot_line - if line is not None and not line.cut: - line.cut = True - if line.message is not None: # already posted whole: show where it stopped - text = line.render() - if text: - task = asyncio.get_running_loop().create_task(self._edit(line.message, text)) - self._side_tasks.add(task) # the loop only keeps weak references - task.add_done_callback(self._side_tasks.discard) + line.cut = True + if line.message is not None: # already posted whole: show where it stopped + text = line.render() + if text: + task = asyncio.get_running_loop().create_task(self._edit(line.message, text)) + self._side_tasks.add(task) # the loop only keeps weak references + task.add_done_callback(self._side_tasks.discard) def _ensure_playing(self) -> None: if self._ended or not self.playback.has_audio: diff --git a/tests/test_realtime_voice.py b/tests/test_realtime_voice.py index 8075238..58bf493 100644 --- a/tests/test_realtime_voice.py +++ b/tests/test_realtime_voice.py @@ -90,12 +90,14 @@ async def test_full_exchange(): await client.append_audio(b'\x02\x00' * 320) await client.add_message('user', '[cumprimente]') + await client.delete_item('item_9') await client.create_response() events = [e['type'] async for e in client.events()] check('server events, bad frames skipped', events == ['response.created', 'response.audio.delta', 'response.done'], events) check('audio arrived', bytes(fake.audio) == b'\x02\x00' * 320 and client.audio_bytes_sent == 640) item = next(e for e in fake.events if e['type'] == 'conversation.item.create')['item'] check('text item', item == {'type': 'message', 'role': 'user', 'content': [{'type': 'input_text', 'text': '[cumprimente]'}]}, item) + check('item deleted', {'type': 'conversation.item.delete', 'item_id': 'item_9'} in fake.events) await client.close() check('closed', client.closed) diff --git a/tests/test_voice_call.py b/tests/test_voice_call.py index afe1a6f..6f0975c 100644 --- a/tests/test_voice_call.py +++ b/tests/test_voice_call.py @@ -8,9 +8,9 @@ import discord import numpy as np -from core.prompts import voice_greeting, voice_instructions +from core.prompts import VOICE_SILENCE_TOOL_NAME, voice_greeting, voice_instructions from core.settings import SETTINGS -from core.voice_call import VoiceCall, user_line +from core.voice_call import VoiceCall, mentions, user_line from helpers import check @@ -25,6 +25,7 @@ def __init__(self): self.frames = 0 self.sent = [] self.cancels = 0 + self.deleted = [] self.closed = False async def events(self): @@ -52,6 +53,9 @@ async def create_response(self): async def cancel_response(self): self.cancels += 1 + async def delete_item(self, item_id): + self.deleted.append(item_id) + async def close(self): if not self.closed: self.closed = True @@ -158,6 +162,12 @@ def speech(ms=20, freq=300): return np.repeat(mono, 2).tobytes() +def talk(vc, who, ms): + """*who* talking for *ms*, as Discord delivers it (one packet per 20 ms).""" + for _ in range(ms // 20): + vc.on_audio(who, speech()) + + def answer_audio(seconds=0.5): """A ``response.audio.delta`` payload: *seconds* of 24 kHz mono, base64.""" pcm = (3000 * np.sin(np.arange(int(24000 * seconds)) / 5)).astype('