Files
scrapyard-cogworks/transcribe/transcribe.py
T
kingston 51932b1cd7 Add Transcribe cog
Voice messages become text via the local whisper-server, with optional
translation through nllb-server. English uses Whisper's own translate task so
the common case needs no second model; other targets transcribe first and
translate after, and skip translation when Whisper's language confidence is
too low to trust.
2026-11-02 15:44:47 -06:00

333 lines
15 KiB
Python

"""Transcribe voice messages with Whisper, optionally translating them."""
from __future__ import annotations
import logging
from typing import Optional
import aiohttp
import discord
from redbot.core import Config, commands
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
HISTORY_SCAN = 25
# 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", "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", "ka": "Georgian", "kk": "Kazakh",
"km": "Khmer", "kn": "Kannada", "ko": "Korean", "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",
"zu": "Zulu",
}
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_audio_attachment(message: discord.Message) -> Optional[discord.Attachment]:
"""Return the first attachment that looks like recorded audio."""
for attachment in message.attachments:
content_type = (attachment.content_type or "").lower()
name = (attachment.filename or "").lower()
if content_type.startswith("audio/"):
return attachment
if name.endswith((".ogg", ".opus", ".wav", ".mp3", ".m4a", ".flac", ".webm")):
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."""
if ctx.message.reference is not None:
replied = ctx.message.reference.resolved
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)
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)
if attachment is not None:
return attachment
return None
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]
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)_"
# ----------------------------------------------------------------- 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 = await self._find_attachment(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."
)
return
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))
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)}"
)
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))
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.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'}**")