transcribe: add [p]translate for text messages
Reply to any message with '[p]translate spanish' to translate it. The source language is detected with langdetect and the command refuses to translate when detection is ambiguous, pointing at the explicit 'from <language>' form rather than guessing.
This commit is contained in:
@@ -10,6 +10,14 @@ 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).
|
||||
@@ -19,6 +27,7 @@ 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
|
||||
|
||||
# Below this, Whisper is guessing which language it heard. Translating from a
|
||||
# guessed language produces fluent nonsense, so we show the transcript instead.
|
||||
@@ -239,6 +248,65 @@ class Transcribe(commands.Cog):
|
||||
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>`."
|
||||
)
|
||||
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()
|
||||
@@ -342,6 +410,82 @@ class Transcribe(commands.Cog):
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user