transcribe: accept video audio, stop reusing older clips

A video that did not match the extension list made _find_attachment scan 25
messages back and silently resend the previous clip, so every request
transcribed the same audio (visible in the service log as repeated 15.4s and
4.7s durations). Accept video containers, which Whisper decodes the audio track
from, restrict the fallback to the message immediately before, and state which
message was transcribed in the reply.
This commit is contained in:
2026-11-02 16:12:34 -06:00
parent eb4f7139a2
commit ca99bd59df
+49 -31
View File
@@ -26,9 +26,15 @@ NLLB_URL = "http://127.0.0.1:8200"
REQUEST_TIMEOUT = aiohttp.ClientTimeout(total=300) REQUEST_TIMEOUT = aiohttp.ClientTimeout(total=300)
MAX_AUDIO_BYTES = 20 * 1024 * 1024 MAX_AUDIO_BYTES = 20 * 1024 * 1024
HISTORY_SCAN = 25
MAX_TRANSLATE_CHARS = 8000 MAX_TRANSLATE_CHARS = 8000
# Whisper decodes the audio track out of video containers too, and people do
# send videos expecting them to be transcribed.
MEDIA_EXTENSIONS = (
".ogg", ".opus", ".wav", ".mp3", ".m4a", ".flac", ".aac", ".wma",
".mp4", ".mov", ".m4v", ".mkv", ".webm", ".avi",
)
# Below this, Whisper is guessing which language it heard. Translating from a # Below this, Whisper is guessing which language it heard. Translating from a
# guessed language produces fluent nonsense, so we show the transcript instead. # guessed language produces fluent nonsense, so we show the transcript instead.
MIN_LANGUAGE_CONFIDENCE = 0.5 MIN_LANGUAGE_CONFIDENCE = 0.5
@@ -126,42 +132,52 @@ class Transcribe(commands.Cog):
# ------------------------------------------------------------------ helpers # ------------------------------------------------------------------ helpers
@staticmethod @staticmethod
def _is_audio_attachment(message: discord.Message) -> Optional[discord.Attachment]: def _is_media_attachment(message: discord.Message) -> Optional[discord.Attachment]:
"""Return the first attachment that looks like recorded audio.""" """First attachment carrying audio, including video containers."""
for attachment in message.attachments: for attachment in message.attachments:
content_type = (attachment.content_type or "").lower() content_type = (attachment.content_type or "").lower()
name = (attachment.filename or "").lower() name = (attachment.filename or "").lower()
if content_type.startswith("audio/"): if content_type.startswith(("audio/", "video/")):
return attachment return attachment
if name.endswith((".ogg", ".opus", ".wav", ".mp3", ".m4a", ".flac", ".webm")): if name.endswith(MEDIA_EXTENSIONS):
return attachment return attachment
return None return None
async def _find_attachment(self, ctx: commands.Context) -> Optional[discord.Attachment]: async def _find_media(
"""Audio from the replied-to message if any, else the newest in channel.""" self, ctx: commands.Context
reference = ctx.message.reference ) -> tuple[Optional[discord.Attachment], Optional[discord.Message]]:
if reference is not None: """Media from the reply, this message, or the message immediately before.
replied = reference.resolved
if not isinstance(replied, discord.Message):
# Replying to a message outside the cache still resolves.
try:
replied = await ctx.channel.fetch_message(reference.message_id)
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
replied = None
if isinstance(replied, discord.Message):
attachment = self._is_audio_attachment(replied)
if attachment is not None:
return attachment
attachment = self._is_audio_attachment(ctx.message) Deliberately shallow. The first version scanned 25 messages back, so a
new video that did not match the extension list silently fell through to
whatever older clip it found - every request then transcribed the same
audio. Better to say "nothing here" than to guess.
"""
replied = await self._replied_message(ctx)
if replied is not None:
attachment = self._is_media_attachment(replied)
if attachment is not None: if attachment is not None:
return attachment return attachment, replied
async for message in ctx.channel.history(limit=HISTORY_SCAN, before=ctx.message): attachment = self._is_media_attachment(ctx.message)
attachment = self._is_audio_attachment(message)
if attachment is not None: if attachment is not None:
return attachment return attachment, ctx.message
return None
async for previous in ctx.channel.history(limit=1, before=ctx.message):
attachment = self._is_media_attachment(previous)
if attachment is not None:
return attachment, previous
return None, None
@staticmethod
def _origin_note(message: Optional[discord.Message]) -> str:
"""Say which message was transcribed, so a wrong pick is obvious."""
if message is None:
return ""
return (
f"\n\n-# Transcribed {message.author.display_name}'s message"
f" ({message.jump_url})"
)
async def _download(self, attachment: discord.Attachment) -> bytes: async def _download(self, attachment: discord.Attachment) -> bytes:
if attachment.size and attachment.size > MAX_AUDIO_BYTES: if attachment.size and attachment.size > MAX_AUDIO_BYTES:
@@ -338,13 +354,14 @@ class Transcribe(commands.Cog):
await ctx.send(str(exc)) await ctx.send(str(exc))
return return
attachment = await self._find_attachment(ctx) attachment, origin_message = await self._find_media(ctx)
if attachment is None: if attachment is None:
await ctx.send( await ctx.send(
"I couldn't find a voice message. Reply to one, or post audio " "I don't see audio or video here. Reply to the message you want "
f"and I'll use the newest within the last {HISTORY_SCAN} messages." "transcribed, or attach the file to your command."
) )
return return
origin = self._origin_note(origin_message)
async with ctx.typing(): async with ctx.typing():
try: try:
@@ -367,7 +384,7 @@ class Transcribe(commands.Cog):
if not text: if not text:
await ctx.send("No speech detected in that message.") await ctx.send("No speech detected in that message.")
return return
await ctx.send(self._clip(text)) await ctx.send(self._clip(text) + origin)
return return
result = await self._transcribe( result = await self._transcribe(
@@ -389,6 +406,7 @@ class Transcribe(commands.Cog):
await ctx.send( await ctx.send(
f"{self._label(detected)} already — no translation needed:\n" f"{self._label(detected)} already — no translation needed:\n"
f"{self._clip(source_text, 1700)}" f"{self._clip(source_text, 1700)}"
f"{origin}"
) )
return return
@@ -409,7 +427,7 @@ class Transcribe(commands.Cog):
body = f"**{self._label(detected)} → {self._label(target)}**\n{translated_text}" body = f"**{self._label(detected)} → {self._label(target)}**\n{translated_text}"
if await self.config.guild(ctx.guild).show_original(): if await self.config.guild(ctx.guild).show_original():
body += f"\n\n-# Original: {source_text}" body += f"\n\n-# Original: {source_text}"
await ctx.send(self._clip(body)) await ctx.send(self._clip(body) + origin)
except ServiceError as exc: except ServiceError as exc:
await ctx.send(f"⚠️ {exc}") await ctx.send(f"⚠️ {exc}")