"""Transcribe voice messages with Whisper, optionally translating them.""" from __future__ import annotations import asyncio import logging import re from contextlib import asynccontextmanager, suppress from typing import Optional import aiohttp import discord from redbot.core import Config, commands try: # installed from info.json requirements from langdetect import DetectorFactory, LangDetectException, detect_langs DetectorFactory.seed = 0 # deterministic results across runs LANGDETECT_AVAILABLE = True except ImportError: # pragma: no cover - reported to the user when they translate LANGDETECT_AVAILABLE = False log = logging.getLogger("red.scrapyard.transcribe") # Local services (see whisper-server and nllb-server repos on the same host). WHISPER_URL = "http://127.0.0.1:8201" NLLB_URL = "http://127.0.0.1:8200" REQUEST_TIMEOUT = aiohttp.ClientTimeout(total=300) MAX_AUDIO_BYTES = 20 * 1024 * 1024 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", ".mpeg", ".mpg", ) # 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 # Post a progress note when a request is still running after this many seconds. # Long voice messages and slow CPU inference both cross this line; short clips # finish before the notice is sent, so they never see it. SLOW_REQUEST_NOTICE_SECONDS = 3.0 # English language names -> ISO-639-1, so `[p]transcribe french` works. LANGUAGE_NAMES = { "afrikaans": "af", "albanian": "sq", "amharic": "am", "arabic": "ar", "armenian": "hy", "assamese": "as", "azerbaijani": "az", "bashkir": "ba", "basque": "eu", "belarusian": "be", "bengali": "bn", "bosnian": "bs", "breton": "br", "bulgarian": "bg", "burmese": "my", "cantonese": "yue", "catalan": "ca", "chinese": "zh", "croatian": "hr", "czech": "cs", "danish": "da", "dutch": "nl", "english": "en", "estonian": "et", "faroese": "fo", "finnish": "fi", "flemish": "nl", "french": "fr", "galician": "gl", "georgian": "ka", "german": "de", "greek": "el", "gujarati": "gu", "haitian creole": "ht", "hausa": "ha", "hebrew": "he", "hindi": "hi", "hungarian": "hu", "icelandic": "is", "igbo": "ig", "indonesian": "id", "irish": "ga", "italian": "it", "japanese": "ja", "javanese": "jw", "kannada": "kn", "kazakh": "kk", "khmer": "km", "korean": "ko", "lao": "lo", "latin": "la", "latvian": "lv", "lithuanian": "lt", "luxembourgish": "lb", "macedonian": "mk", "malagasy": "mg", "malay": "ms", "malayalam": "ml", "maltese": "mt", "maori": "mi", "marathi": "mr", "mongolian": "mn", "nepali": "ne", "norwegian": "no", "occitan": "oc", "pashto": "ps", "persian": "fa", "polish": "pl", "portuguese": "pt", "punjabi": "pa", "romanian": "ro", "russian": "ru", "sanskrit": "sa", "serbian": "sr", "shona": "sn", "sindhi": "sd", "sinhala": "si", "slovak": "sk", "slovenian": "sl", "somali": "so", "spanish": "es", "sundanese": "su", "swahili": "sw", "swedish": "sv", "tagalog": "tl", "tajik": "tg", "tamil": "ta", "tatar": "tt", "telugu": "te", "thai": "th", "turkish": "tr", "turkmen": "tk", "ukrainian": "uk", "urdu": "ur", "uzbek": "uz", "vietnamese": "vi", "welsh": "cy", "yiddish": "yi", "yoruba": "yo", "zulu": "zu", } # ISO-639-1 -> display name, for the reply header. LANGUAGE_LABELS = { "af": "Afrikaans", "am": "Amharic", "ar": "Arabic", "as": "Assamese", "az": "Azerbaijani", "ba": "Bashkir", "be": "Belarusian", "bg": "Bulgarian", "bn": "Bengali", "bo": "Tibetan", "br": "Breton", "bs": "Bosnian", "ca": "Catalan", "cs": "Czech", "cy": "Welsh", "da": "Danish", "de": "German", "el": "Greek", "en": "English", "eo": "Esperanto", "es": "Spanish", "et": "Estonian", "eu": "Basque", "fa": "Persian", "fi": "Finnish", "fo": "Faroese", "fr": "French", "ga": "Irish", "gl": "Galician", "gu": "Gujarati", "ha": "Hausa", "he": "Hebrew", "hi": "Hindi", "hr": "Croatian", "ht": "Haitian Creole", "hu": "Hungarian", "hy": "Armenian", "id": "Indonesian", "ig": "Igbo", "is": "Icelandic", "it": "Italian", "ja": "Japanese", "jv": "Javanese", "jw": "Javanese", "ka": "Georgian", "kk": "Kazakh", "km": "Khmer", "kn": "Kannada", "ko": "Korean", "la": "Latin", "lb": "Luxembourgish", "ln": "Lingala", "lo": "Lao", "lt": "Lithuanian", "lv": "Latvian", "mg": "Malagasy", "mi": "Maori", "mk": "Macedonian", "ml": "Malayalam", "mn": "Mongolian", "mr": "Marathi", "ms": "Malay", "mt": "Maltese", "my": "Burmese", "ne": "Nepali", "nl": "Dutch", "nn": "Norwegian Nynorsk", "no": "Norwegian", "oc": "Occitan", "pa": "Punjabi", "pl": "Polish", "ps": "Pashto", "pt": "Portuguese", "ro": "Romanian", "ru": "Russian", "sa": "Sanskrit", "sd": "Sindhi", "si": "Sinhala", "sk": "Slovak", "sl": "Slovenian", "sn": "Shona", "so": "Somali", "sq": "Albanian", "sr": "Serbian", "su": "Sundanese", "sv": "Swedish", "sw": "Swahili", "ta": "Tamil", "te": "Telugu", "tg": "Tajik", "th": "Thai", "tk": "Turkmen", "tl": "Tagalog", "tr": "Turkish", "tt": "Tatar", "uk": "Ukrainian", "ur": "Urdu", "uz": "Uzbek", "vi": "Vietnamese", "yi": "Yiddish", "yo": "Yoruba", "yue": "Cantonese", "zh": "Chinese", "zho_Hans": "Simplified Chinese", "zho_Hant": "Traditional Chinese", "zu": "Zulu", } # Script variants that a bare ISO code would flatten into the wrong script. SCRIPT_VARIANTS = { "zh-hant": "zho_Hant", "zh-tw": "zho_Hant", "zh-hk": "zho_Hant", "traditional chinese": "zho_Hant", "cantonese traditional": "yue_Hant", "zh-hans": "zho_Hans", "zh-cn": "zho_Hans", "zh-sg": "zho_Hans", "simplified chinese": "zho_Hans", } # NLLB also accepts FLORES-200 tags directly; pass those straight through. FLORES_TAG = re.compile(r"^[a-z]{3}_[A-Z][a-z]{3}$") class ServiceError(Exception): """Raised when a local transcription/translation service misbehaves.""" class Transcribe(commands.Cog): """Transcribe voice messages, optionally translated.""" def __init__(self, bot): self.bot = bot self.session = aiohttp.ClientSession() self.config = Config.get_conf(self, identifier=481516234) self.config.register_guild(show_original=True) async def cog_unload(self): await self.session.close() # ------------------------------------------------------------------ helpers @staticmethod def _media_attachment(attachments) -> Optional[discord.Attachment]: """First attachment in a list carrying audio, including video containers.""" for attachment in attachments: content_type = (attachment.content_type or "").lower() name = (attachment.filename or "").lower() if content_type.startswith(("audio/", "video/")): return attachment if name.endswith(MEDIA_EXTENSIONS): return attachment return None def _message_media( self, message: discord.Message ) -> tuple[Optional[discord.Attachment], bool]: """Audio from a message, including media inside forwarded snapshots. A forwarded message has no top-level attachments; the original content and files live in `message_snapshots`. Both are checked so forwarding a voice message works the same as posting the file directly. """ attachment = self._media_attachment(message.attachments) if attachment is not None: return attachment, False for snapshot in getattr(message, "message_snapshots", ()) or (): attachment = self._media_attachment(snapshot.attachments) if attachment is not None: return attachment, True return None, False async def _find_media( self, ctx: commands.Context ) -> tuple[Optional[discord.Attachment], Optional[discord.Message], bool]: """Media from the reply, this message, or the message immediately before. 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. The third value says the attachment came from a forwarded snapshot, so the origin note can say so instead of implying the sender recorded it. """ replied = await self._replied_message(ctx) if replied is not None: attachment, forwarded = self._message_media(replied) if attachment is not None: return attachment, replied, forwarded attachment, forwarded = self._message_media(ctx.message) if attachment is not None: return attachment, ctx.message, forwarded async for previous in ctx.channel.history(limit=1, before=ctx.message): attachment, forwarded = self._message_media(previous) if attachment is not None: return attachment, previous, forwarded return None, None, False @staticmethod def _origin_note(message: Optional[discord.Message], forwarded: bool = False) -> str: """Say which message was transcribed, so a wrong pick is obvious.""" if message is None: return "" kind = "forwarded message" if forwarded else "message" return ( f"\n\n-# Transcribed {message.author.display_name}'s {kind}" f" ({message.jump_url})" ) async def _download(self, attachment: discord.Attachment) -> bytes: if attachment.size and attachment.size > MAX_AUDIO_BYTES: raise ServiceError( f"That audio is {attachment.size / 1_048_576:.1f} MB, " f"over the {MAX_AUDIO_BYTES // 1_048_576} MB limit." ) async with self.session.get(attachment.url) as resp: if resp.status != 200: raise ServiceError(f"Could not download the audio (HTTP {resp.status}).") return await resp.read() async def _transcribe( self, data: bytes, filename: str, content_type: str, language: Optional[str], task: str ) -> dict: form = aiohttp.FormData() form.add_field("file", data, filename=filename, content_type=content_type) form.add_field("task", task) form.add_field("vad", "true") if language: form.add_field("language", language) try: async with self.session.post( f"{WHISPER_URL}/transcribe", data=form, timeout=REQUEST_TIMEOUT ) as resp: payload = await resp.json(content_type=None) if resp.status != 200: detail = payload.get("detail", resp.reason) if isinstance(payload, dict) else resp.reason raise ServiceError(f"Transcription failed: {detail}") return payload except aiohttp.ClientConnectorError as exc: raise ServiceError( "The transcription service is not reachable on port 8201." ) from exc except aiohttp.ServerTimeoutError as exc: raise ServiceError("The transcription service timed out.") from exc async def _translate(self, text: str, source: str, target: str) -> dict: try: async with self.session.post( f"{NLLB_URL}/translate", json={"text": text, "source": source, "target": target}, timeout=REQUEST_TIMEOUT, ) as resp: payload = await resp.json(content_type=None) if resp.status != 200: detail = payload.get("detail", resp.reason) if isinstance(payload, dict) else resp.reason raise ServiceError(f"Translation failed: {detail}") return payload except aiohttp.ClientConnectorError as exc: raise ServiceError("The translation service is not reachable on port 8200.") from exc except aiohttp.ServerTimeoutError as exc: raise ServiceError("The translation service timed out.") from exc @staticmethod def _resolve_language(raw: str) -> str: """`french`, `French`, `fr` and `pt-BR` all resolve to an ISO code.""" token = raw.strip().lower().replace("_", " ") if token in LANGUAGE_NAMES: return LANGUAGE_NAMES[token] variant = SCRIPT_VARIANTS.get(raw.strip().lower()) if variant: return variant if FLORES_TAG.match(raw.strip()): return raw.strip() code = raw.strip().lower().split("-")[0] if code in LANGUAGE_LABELS: return code raise ServiceError( f"I don't know the language `{raw}`. Try an English name (`french`) " f"or an ISO code (`fr`)." ) @staticmethod def _label(code: Optional[str]) -> str: if not code: return "unknown" return LANGUAGE_LABELS.get(code, code) @staticmethod def _clip(text: str, limit: int = 1900) -> str: if len(text) <= limit: return text return text[: limit - 12].rstrip() + " _(cut off)_" @staticmethod def _message_text(message: discord.Message) -> str: """Everything readable in a message: content plus embed text.""" parts: list[str] = [] if message.content: parts.append(message.content.strip()) for embed in message.embeds: footer = embed.footer.text if embed.footer else None for chunk in (embed.title, embed.description, footer): if chunk: parts.append(chunk.strip()) for field in embed.fields: if field.value: parts.append(field.value.strip()) return "\n".join(part for part in parts if part).strip() async def _replied_message(self, ctx: commands.Context) -> Optional[discord.Message]: """The message this command replies to, fetched if it isn't cached.""" reference = ctx.message.reference if reference is None: return None replied = reference.resolved if isinstance(replied, discord.Message): return replied try: return await ctx.channel.fetch_message(reference.message_id) except (discord.NotFound, discord.Forbidden, discord.HTTPException): return None @staticmethod def _detect_source(text: str) -> str: """Guess the source language, refusing rather than guessing when unsure.""" if not LANGDETECT_AVAILABLE: raise ServiceError( "Language detection isn't installed. Reinstall the cog so its " "requirements install, or use `[p]translate from `." ) # Short strings get confident nonsense out of langdetect ("ok" reads as # Slovak), so require enough text before trusting a guess. if len(text.strip()) < 12: raise ServiceError( "That's too short to identify the language reliably. " "Use `[p]translate from `." ) try: guesses = detect_langs(text) except LangDetectException as exc: raise ServiceError( "I couldn't tell what language that is. " "Try `[p]translate from `." ) from exc if not guesses: raise ServiceError("I couldn't tell what language that is.") top = guesses[0] runner_up = guesses[1].prob if len(guesses) > 1 else 0.0 if top.prob < 0.70 or (top.prob - runner_up) < 0.15: raise ServiceError( f"I'm not confident that's {Transcribe._label(top.lang)} " f"({top.prob:.0%}). Use `[p]translate from `." ) code = top.lang.lower() return { "zh-cn": "zho_Hans", "zh-hans": "zho_Hans", "zh-tw": "zho_Hant", "zh-hant": "zho_Hant", }.get(code, code) @asynccontextmanager async def _slow_notice(self, ctx: commands.Context, delay: float = SLOW_REQUEST_NOTICE_SECONDS): """Tell the channel that a long transcription is still running. Waits `delay` seconds before posting, and removes the notice when the surrounding block exits, whether it succeeded, failed or returned early. """ holder: dict[str, Optional[discord.Message]] = {"message": None} async def announce(): await asyncio.sleep(delay) try: holder["message"] = await ctx.send( "Still transcribing. Longer recordings can take a moment." ) except discord.HTTPException: pass task = asyncio.create_task(announce()) try: yield finally: task.cancel() with suppress(asyncio.CancelledError): await task message = holder["message"] if message is not None: with suppress(discord.HTTPException): await message.delete() # ----------------------------------------------------------------- commands @commands.command(name="transcribe", aliases=["stt"]) @commands.guild_only() @commands.cooldown(2, 60, commands.BucketType.user) @commands.max_concurrency(1, commands.BucketType.default, wait=True) @commands.bot_has_permissions(read_message_history=True) async def transcribe(self, ctx: commands.Context, *, language: Optional[str] = None): """Transcribe a voice message, or translate it into another language. Reply to a voice message or video, or attach one to the command. Running it bare uses the message posted immediately before it. **Examples** `[p]transcribe` — transcribe and translate to English `[p]transcribe french` — transcribe and translate to French """ target = None if language: try: target = self._resolve_language(language) except ServiceError as exc: await ctx.send(str(exc)) return attachment, origin_message, forwarded = await self._find_media(ctx) if attachment is None: await ctx.send( "I don't see audio or video here. Reply to the message you want " "transcribed, attach the file to your command, or forward the " "voice message and run this again." ) return origin = self._origin_note(origin_message, forwarded) async with ctx.typing(), self._slow_notice(ctx): try: data = await self._download(attachment) if not data: await ctx.send("That audio file is empty.") return # English (or no target) uses Whisper's own translate task: one # model pass, no translator needed. if target in (None, "en"): result = await self._transcribe( data, attachment.filename or "audio.ogg", attachment.content_type or "application/octet-stream", None, "translate", ) text = (result.get("text") or "").strip() if not text: await ctx.send("No speech detected in that message.") return await ctx.send(self._clip(text) + origin) return result = await self._transcribe( data, attachment.filename or "audio.ogg", attachment.content_type or "application/octet-stream", None, "transcribe", ) source_text = (result.get("text") or "").strip() if not source_text: await ctx.send("No speech detected in that message.") return detected = result.get("language") or "en" confidence = result.get("language_probability") or 0.0 if detected == target: await ctx.send( f"{self._label(detected)} already — no translation needed:\n" f"{self._clip(source_text, 1700)}" f"{origin}" ) return if confidence < MIN_LANGUAGE_CONFIDENCE: await ctx.send( f"I only detected **{self._label(detected)}** " f"({confidence:.0%} confident), so I won't translate from a guess.\n" f"{self._clip(source_text, 1600)}" f"{origin}" ) return translation = await self._translate(source_text, detected, target) translated_text = (translation.get("translation") or "").strip() if not translated_text: await ctx.send("The translation came back empty.") return 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) + origin) except ServiceError as exc: await ctx.send(f"⚠️ {exc}") except Exception: # noqa: BLE001 - never let a cog command dump a traceback log.exception("transcribe failed") await ctx.send("Something went wrong while transcribing that audio.") @commands.command(name="translate") @commands.guild_only() @commands.cooldown(4, 60, commands.BucketType.user) @commands.max_concurrency(1, commands.BucketType.default, wait=True) async def translate_message( self, ctx: commands.Context, language: str, *, extra: Optional[str] = None ): """Translate the message you reply to (or text you type) into a language. The source language is detected automatically. Add `from ` when the detection is wrong or you want to be explicit. **Examples** `[p]translate spanish` — translate the message you replied to `[p]translate german from french` — state the source language `[p]translate french good morning` — translate text you type """ try: target = self._resolve_language(language) except ServiceError as exc: await ctx.send(str(exc)) return source_override = None inline_text = (extra or "").strip() if inline_text.lower().startswith("from "): try: source_override = self._resolve_language(inline_text[5:]) except ServiceError as exc: await ctx.send(str(exc)) return inline_text = "" replied = await self._replied_message(ctx) source_text = self._message_text(replied) if replied is not None else "" if not source_text: source_text = inline_text if not source_text: await ctx.send( "Reply to a message with `[p]translate `, or give me the text: " "`[p]translate french good morning`." "\n-# For voice messages, use `[p]transcribe`." ) return note = "" if len(source_text) > MAX_TRANSLATE_CHARS: source_text = source_text[:MAX_TRANSLATE_CHARS] note = f"\n\n-# Only the first {MAX_TRANSLATE_CHARS} characters were translated." async with ctx.typing(): try: source = source_override or self._detect_source(source_text) if source == target: await ctx.send(f"That's already {self._label(target)} — nothing to do.") return result = await self._translate(source_text, source, target) translated = (result.get("translation") or "").strip() if not translated: await ctx.send("The translation came back empty.") return if translated.lower() == source_text.lower(): await ctx.send(f"That already reads as {self._label(target)}.") return await ctx.send( f"**{self._label(source)} → {self._label(target)}**\n" f"{self._clip(translated, 1800)}{note}" ) except ServiceError as exc: await ctx.send(f"⚠️ {exc}") except Exception: # noqa: BLE001 - never surface a traceback in chat log.exception("translate failed") await ctx.send("Something went wrong while translating that message.") @commands.group(name="transcribeset", aliases=["sttset"], invoke_without_command=True) @commands.guild_only() @commands.admin_or_permissions(manage_guild=True) async def transcribeset(self, ctx: commands.Context): """Settings for the Transcribe cog.""" show = await self.config.guild(ctx.guild).show_original() await ctx.send(f"Show the original text with translations: **{'on' if show else 'off'}**") @transcribeset.command(name="showoriginal") @commands.guild_only() @commands.admin_or_permissions(manage_guild=True) async def transcribeset_showoriginal(self, ctx: commands.Context, enabled: bool): """Show the original transcript underneath a translation.""" await self.config.guild(ctx.guild).show_original.set(enabled) await ctx.send(f"Show original text: **{'on' if enabled else 'off'}**")