Files
DeepTutor/tests/book/test_language.py
Mohammad Hijjawi 7bd5b99f9a fix(book): match language cues as whole words (#2477)
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.
2026-12-01 14:57:45 +08:00

92 lines
2.8 KiB
Python

"""Language resolution for automatic book creation."""
from __future__ import annotations
import pytest
from deeptutor.book.language import resolve_book_language
@pytest.mark.parametrize(
("intent", "expected"),
[
("Please create a Fourier book in Japanese", "ja"),
("Write about Japanese history in Spanish", "es"),
("请用日语整理机器学习入门内容", "ja"),
("日本語で書いてください", "ja"),
("한국어로 정리해 주세요", "ko"),
("Сделай книгу по алгоритмам", "ru"),
("帮我整理机器学习入门内容", "zh"),
("Hãy tạo một cuốn sách về giải thuật bằng tiếng Việt", "vi"),
("Please write the book in Vietnamese", "vi"),
("Please create a book about Japanese history", "en"),
("Please write the book in Traditional Chinese", "zh-tw"),
("Write the book in Mandarin, please", "zh"),
("Hazlo en español", "es"),
("Írd meg a könyvet magyarul", "hu"),
("Please write the book in Hungarian", "hu"),
],
)
def test_auto_uses_high_confidence_language_signals(intent: str, expected: str) -> None:
assert (
resolve_book_language(
user_intent=intent,
requested_language="auto",
fallback_language="en",
)
== expected
)
@pytest.mark.parametrize(
"intent",
[
"Create a book about renewable energy policy in Germany",
"Explain the dialects of Berlin German",
"Write a book about Traditional Chinese Medicine",
"A guide to the main English Premier League clubs",
],
)
def test_a_cue_inside_another_word_or_a_topic_is_not_a_language_request(intent: str) -> None:
assert (
resolve_book_language(
user_intent=intent,
requested_language="auto",
fallback_language="zh",
)
== "zh"
)
def test_auto_falls_back_to_the_interface_language() -> None:
assert (
resolve_book_language(
user_intent="Create a book about distributed systems",
requested_language="auto",
fallback_language="zh",
)
== "zh"
)
def test_explicit_language_selection_wins_over_intent_signals() -> None:
assert (
resolve_book_language(
user_intent="请用日语整理内容",
requested_language="zh",
fallback_language="en",
)
== "zh"
)
def test_traditional_chinese_requests_resolve_to_the_regional_code() -> None:
assert (
resolve_book_language(
user_intent="請用繁體中文寫一本演算法書",
requested_language="auto",
fallback_language="en",
)
== "zh-tw"
)