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.
This commit is contained in:
2026-11-02 15:44:47 -06:00
parent f3da940d0f
commit 51932b1cd7
4 changed files with 393 additions and 0 deletions
+20
View File
@@ -45,6 +45,9 @@ Homepage: https://homepage.kingstons-scrapyard.net/
- [Web UI](#web-ui)
- [MiniMax Voices (Presets)](#minimax-voices-presets)
**Transcribe**
- [Transcribe](#transcribe)
---
## Installation
@@ -1339,3 +1342,20 @@ Rename users with admin-only commands.
- `[p]renamer rename <member> [nickname]` - Rename a member. Leave nickname empty to clear it (admin only).
- `[p]renamer bulkrename <members...> <nickname>` - Rename multiple members to the same nickname (admin only).
- `[p]renamer massrename <role> <nickname>` - Rename all members with a specific role (admin only).
## Transcribe
Transcribe Discord voice messages with Whisper, and optionally translate them with NLLB. Both models run locally, so no audio leaves the machine and there is no cloud API to pay for.
- `[p]transcribe` - Transcribe the message and translate it into English.
- `[p]transcribe <language>` - Translate into another language, by English name (`french`) or ISO code (`fr`).
- `[p]transcribeset showoriginal <true|false>` - Show the original text under a translation (default: on).
Reply to a voice message, or just run the command and the newest voice message within the last 25 messages is used. Attachments are accepted too, as long as they are audio (`ogg`, `opus`, `wav`, `mp3`, `m4a`, `flac`, `webm`).
The cog talks to two local services:
- `whisper-server` on `127.0.0.1:8201` for speech to text (faster-whisper, CPU)
- `nllb-server` on `127.0.0.1:8200` for translation (NLLB-200, GPU)
English needs only the first one: Whisper's own `translate` task handles it in a single pass. Everything else transcribes first, then translates. If Whisper is less than 50% confident about which language it heard, the cog prints the transcript and skips the translation rather than translating a guess.
+16
View File
@@ -0,0 +1,16 @@
"""Package for Transcribe cog."""
import json
from pathlib import Path
from redbot.core.bot import Red
from .transcribe import Transcribe
with Path(__file__).parent.joinpath("info.json").open() as fp:
__red_end_user_data_statement__ = json.load(fp)["end_user_data_statement"]
async def setup(bot: Red) -> None:
"""Load Transcribe cog."""
await bot.add_cog(Transcribe(bot))
+25
View File
@@ -0,0 +1,25 @@
{
"name": "Transcribe",
"author": [
"Scrapyard Cogworks"
],
"short": "Transcribe voice messages with Whisper, optionally translate them.",
"description": "Transcribes Discord voice messages and audio attachments using the local whisper-server, then optionally translates the result into another language with the local NLLB service. No cloud APIs are involved and no audio leaves the machine.",
"install_msg": "Thanks for installing Transcribe from Scrapyard Cogworks! It expects whisper-server on 127.0.0.1:8201 and nllb-server on 127.0.0.1:8200. Use `[p]transcribe` to transcribe to English, or `[p]transcribe french` to translate.",
"requirements": [],
"tags": [
"transcribe",
"whisper",
"speech",
"voice",
"translate",
"stt"
],
"min_bot_version": "3.5.0",
"min_python_version": [
3,
11,
0
],
"end_user_data_statement": "This cog sends the audio of the message being transcribed to a local service and does not store it. Only a per-server display preference is saved."
}
+332
View File
@@ -0,0 +1,332 @@
"""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'}**")