Files
scrapyard-cogworks/transcribe/transcribe.py
T
kingston ca99bd59df 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.
2026-11-02 16:12:34 -06:00

529 lines
23 KiB
Python

"""Transcribe voice messages with Whisper, optionally translating them."""
from __future__ import annotations
import logging
import re
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",
)
# 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
# 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 _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/", "video/")):
return attachment
if name.endswith(MEDIA_EXTENSIONS):
return attachment
return None
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.
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, 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:
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 <target> from <source>`."
)
# 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 <target> from <source>`."
)
try:
guesses = detect_langs(text)
except LangDetectException as exc:
raise ServiceError(
"I couldn't tell what language that is. "
"Try `[p]translate <target> from <source>`."
) 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 <target> from <source>`."
)
code = top.lang.lower()
return {
"zh-cn": "zho_Hans", "zh-hans": "zho_Hans",
"zh-tw": "zho_Hant", "zh-hant": "zho_Hant",
}.get(code, code)
# ----------------------------------------------------------------- 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 just run it and the most recent one in the
channel is used.
**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 = 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, or attach the file to your command."
)
return
origin = self._origin_note(origin_message)
async with ctx.typing():
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)}"
)
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 <language>`
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 <language>`, 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'}**")