mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 01:19:31 +08:00
Automatic book language detection matched its English-word cues as bare substrings, so a topic that only mentioned a place or a subject forced the book into another language: "energy policy in Germany" and "Berlin German dialects" became German, "the main English clubs" became English over the interface language, and any mention of "Traditional Chinese Medicine" became Traditional Chinese. Bound the Latin and Cyrillic cues with word boundaries and require the phrased "in Traditional Chinese" form, matching how every other English cue is written. CJK cues are unchanged.
118 lines
4.4 KiB
Python
118 lines
4.4 KiB
Python
"""Deterministic language selection for book creation."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import unicodedata
|
||
|
||
from deeptutor.services.prompt.language import normalize_language
|
||
|
||
_AUTO_LANGUAGE = "auto"
|
||
|
||
# Only phrased requests are treated as explicit language selection. Merely
|
||
# mentioning "Japanese history" must not force a Japanese book. Word cues are
|
||
# bounded so "in Germany" or "Berlin German" is not read as "in German".
|
||
_LANGUAGE_CUES: tuple[tuple[str, str], ...] = (
|
||
("zh-tw", r"(?:繁體中文|正體中文|\bin\s+traditional\s+chinese\b)"),
|
||
("zh", r"(?:用(?:简体中文|中文|汉语)|以(?:中文|汉语)|\bin\s+chinese\b|\bin\s+mandarin\b)"),
|
||
("ja", r"(?:日本語で|用(?:日语|日文)|\bin\s+japanese\b)"),
|
||
("ko", r"(?:한국어로|用(?:韩语|韓語)|\bin\s+korean\b)"),
|
||
("ru", r"(?:\bпо-русски\b|\bна\s+русском\b|\bin\s+russian\b)"),
|
||
(
|
||
"es",
|
||
r"(?:\ben\s+español\b|\ben\s+espanol\b|\bin\s+spanish\b|\bcastellano\b"
|
||
r"|用(?:西班牙语|西班牙文))",
|
||
),
|
||
("fr", r"(?:\ben\s+français\b|\ben\s+francais\b|\bin\s+french\b|用(?:法语|法文))"),
|
||
("de", r"(?:\bauf\s+deutsch\b|\bin\s+german\b|用(?:德语|德文))"),
|
||
(
|
||
"pt",
|
||
r"(?:\bem\s+português\b|\bem\s+portugues\b|\bin\s+portuguese\b|用(?:葡萄牙语|葡萄牙文))",
|
||
),
|
||
("it", r"(?:\bin\s+italiano\b|\bin\s+italian\b|用(?:意大利语|意大利文))"),
|
||
(
|
||
"vi",
|
||
r"(?:\bbằng\s+tiếng\s+việt\b|\bbang\s+tieng\s+viet\b|\bin\s+vietnamese\b"
|
||
r"|用越南(?:语|語|文))",
|
||
),
|
||
("tr", r"(?:\btürkçe\s+olarak\b|\btürkçe\s+yaz(?:ın)?\b|\bin\s+turkish\b|用土耳其(?:语|文))"),
|
||
("hu", r"(?:\bmagyarul\b|\bmagyar\s+nyelven\b|\bin\s+hungarian\b|\bauf\s+ungarisch\b)"),
|
||
("en", r"(?:\bin\s+english\b|英語で|用(?:英语|英文)|\ben\s+anglais\b|\ben\s+inglés\b)"),
|
||
)
|
||
|
||
_COMPILED_CUES = tuple(
|
||
(language, re.compile(pattern, re.IGNORECASE | re.UNICODE))
|
||
for language, pattern in _LANGUAGE_CUES
|
||
)
|
||
|
||
|
||
def _explicit_language(user_intent: str) -> str | None:
|
||
"""Return the last explicit language request in the intent."""
|
||
matches: list[tuple[int, str]] = []
|
||
for language, pattern in _COMPILED_CUES:
|
||
for match in pattern.finditer(user_intent):
|
||
matches.append((match.start(), language))
|
||
if not matches:
|
||
return None
|
||
return max(matches, key=lambda item: item[0])[1]
|
||
|
||
|
||
def _script_language(user_intent: str) -> str | None:
|
||
"""Infer high-confidence scripts without a language-detection dependency."""
|
||
counts = {"latin": 0, "han": 0, "kana": 0, "hangul": 0, "cyrillic": 0}
|
||
|
||
for char in user_intent:
|
||
if not char.isalpha():
|
||
continue
|
||
script = unicodedata.name(char, "").split(" ", 1)[0]
|
||
if script == "LATIN":
|
||
counts["latin"] += 1
|
||
elif script in {"HIRAGANA", "KATAKANA"}:
|
||
counts["kana"] += 1
|
||
elif script == "HANGUL":
|
||
counts["hangul"] += 1
|
||
elif script == "CYRILLIC":
|
||
counts["cyrillic"] += 1
|
||
elif (
|
||
"\u3400" <= char <= "\u4dbf"
|
||
or "\u4e00" <= char <= "\u9fff"
|
||
or "\uf900" <= char <= "\ufaff"
|
||
):
|
||
counts["han"] += 1
|
||
|
||
# Han characters are ambiguous between Chinese and Japanese. Kana resolves
|
||
# that ambiguity; Kanji-only Japanese remains intentionally conservative.
|
||
if counts["kana"]:
|
||
return "ja"
|
||
if counts["hangul"] > max(counts["latin"], counts["han"], counts["cyrillic"]):
|
||
return "ko"
|
||
if counts["cyrillic"] > counts["latin"]:
|
||
return "ru"
|
||
if counts["han"] > max(counts["latin"], counts["hangul"], counts["cyrillic"]):
|
||
return "zh"
|
||
return None
|
||
|
||
|
||
def resolve_book_language(
|
||
*,
|
||
user_intent: str,
|
||
requested_language: str | None = "auto",
|
||
fallback_language: str | None = "en",
|
||
) -> str:
|
||
"""Resolve a concrete book language before any generation stage runs.
|
||
|
||
Explicit selections always win. ``auto`` uses an explicit request cue, then
|
||
a high-confidence script signal, then the caller's fallback (normally the
|
||
interface language).
|
||
"""
|
||
requested = normalize_language(requested_language)
|
||
fallback = normalize_language(fallback_language)
|
||
if requested not in {_AUTO_LANGUAGE, "automatic", "detect"}:
|
||
return requested
|
||
|
||
intent = user_intent or ""
|
||
return _explicit_language(intent) or _script_language(intent) or fallback
|
||
|
||
|
||
__all__ = ["resolve_book_language"]
|