diff --git a/transcribe/transcribe.py b/transcribe/transcribe.py index 6894a97..158e6c9 100644 --- a/transcribe/transcribe.py +++ b/transcribe/transcribe.py @@ -26,9 +26,15 @@ NLLB_URL = "http://127.0.0.1:8200" REQUEST_TIMEOUT = aiohttp.ClientTimeout(total=300) MAX_AUDIO_BYTES = 20 * 1024 * 1024 -HISTORY_SCAN = 25 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 # guessed language produces fluent nonsense, so we show the transcript instead. MIN_LANGUAGE_CONFIDENCE = 0.5 @@ -126,42 +132,52 @@ class Transcribe(commands.Cog): # ------------------------------------------------------------------ helpers @staticmethod - def _is_audio_attachment(message: discord.Message) -> Optional[discord.Attachment]: - """Return the first attachment that looks like recorded audio.""" + def _is_media_attachment(message: discord.Message) -> Optional[discord.Attachment]: + """First attachment carrying audio, including video containers.""" for attachment in message.attachments: content_type = (attachment.content_type or "").lower() name = (attachment.filename or "").lower() - if content_type.startswith("audio/"): + if content_type.startswith(("audio/", "video/")): return attachment - if name.endswith((".ogg", ".opus", ".wav", ".mp3", ".m4a", ".flac", ".webm")): + if name.endswith(MEDIA_EXTENSIONS): return attachment return None - async def _find_attachment(self, ctx: commands.Context) -> Optional[discord.Attachment]: - """Audio from the replied-to message if any, else the newest in channel.""" - reference = ctx.message.reference - if reference is not None: - 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 + async def _find_media( + self, ctx: commands.Context + ) -> tuple[Optional[discord.Attachment], Optional[discord.Message]]: + """Media from the reply, this message, or the message immediately before. - attachment = self._is_audio_attachment(ctx.message) - if attachment is not None: - return attachment - - async for message in ctx.channel.history(limit=HISTORY_SCAN, before=ctx.message): - attachment = self._is_audio_attachment(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: - return attachment - return None + return attachment, replied + + attachment = self._is_media_attachment(ctx.message) + if attachment is not None: + return attachment, ctx.message + + 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: if attachment.size and attachment.size > MAX_AUDIO_BYTES: @@ -338,13 +354,14 @@ class Transcribe(commands.Cog): await ctx.send(str(exc)) return - attachment = await self._find_attachment(ctx) + attachment, origin_message = await self._find_media(ctx) if attachment is None: await ctx.send( - "I couldn't find a voice message. Reply to one, or post audio " - f"and I'll use the newest within the last {HISTORY_SCAN} messages." + "I don't see audio or video here. Reply to the message you want " + "transcribed, or attach the file to your command." ) return + origin = self._origin_note(origin_message) async with ctx.typing(): try: @@ -367,7 +384,7 @@ class Transcribe(commands.Cog): if not text: await ctx.send("No speech detected in that message.") return - await ctx.send(self._clip(text)) + await ctx.send(self._clip(text) + origin) return result = await self._transcribe( @@ -389,6 +406,7 @@ class Transcribe(commands.Cog): await ctx.send( f"{self._label(detected)} already — no translation needed:\n" f"{self._clip(source_text, 1700)}" + f"{origin}" ) return @@ -409,7 +427,7 @@ class Transcribe(commands.Cog): body = f"**{self._label(detected)} → {self._label(target)}**\n{translated_text}" if await self.config.guild(ctx.guild).show_original(): body += f"\n\n-# Original: {source_text}" - await ctx.send(self._clip(body)) + await ctx.send(self._clip(body) + origin) except ServiceError as exc: await ctx.send(f"⚠️ {exc}")