mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 20:11:38 +08:00
Merge pull request #1052 from evan188199-tech/codex/fix/book-language-options
This commit is contained in:
@@ -59,6 +59,7 @@ class CreateBookRequest(BaseModel):
|
||||
question_categories: list[int] = Field(default_factory=list)
|
||||
question_entries: list[int] = Field(default_factory=list)
|
||||
language: str = Field(default="en")
|
||||
fallback_language: str = Field(default="en")
|
||||
depth: str = Field(default="standard")
|
||||
|
||||
|
||||
@@ -682,6 +683,7 @@ async def create_book(req: CreateBookRequest) -> dict[str, Any]:
|
||||
question_categories=req.question_categories,
|
||||
question_entries=req.question_entries,
|
||||
language=req.language,
|
||||
fallback_language=req.fallback_language,
|
||||
depth=req.depth,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
@@ -1330,6 +1332,7 @@ async def book_websocket(ws: WebSocket) -> None:
|
||||
],
|
||||
question_entries=[int(e) for e in (data.get("question_entries") or [])],
|
||||
language=str(data.get("language") or "en"),
|
||||
fallback_language=str(data.get("fallback_language") or "en"),
|
||||
depth=str(data.get("depth") or "standard"),
|
||||
stream=creation_bus,
|
||||
)
|
||||
|
||||
@@ -56,6 +56,7 @@ from .agents.spine_synthesizer import SpineSynthesizer
|
||||
from .compiler import BookCompiler, CompilerOptions, systemic_failure_reason
|
||||
from .event_hub import close_book_bus, get_book_bus
|
||||
from .inputs import IdeationContext, build_book_inputs
|
||||
from .language import resolve_book_language
|
||||
from .models import (
|
||||
Block,
|
||||
BlockStatus,
|
||||
@@ -422,12 +423,18 @@ class BookEngine:
|
||||
question_categories: list[int] | None = None,
|
||||
question_entries: list[int] | None = None,
|
||||
language: str = "en",
|
||||
fallback_language: str = "en",
|
||||
depth: str = BookDepth.STANDARD.value,
|
||||
stream: StreamBus | None = None,
|
||||
) -> tuple[Book, BookProposal]:
|
||||
"""Capture inputs, run IdeationAgent, persist DRAFT book + proposal."""
|
||||
bus = stream or StreamBus()
|
||||
bstream = BookStream(bus)
|
||||
language = resolve_book_language(
|
||||
user_intent=user_intent,
|
||||
requested_language=language,
|
||||
fallback_language=fallback_language,
|
||||
)
|
||||
|
||||
async with bstream.stage(STAGE_IDEATION):
|
||||
await bstream.progress("Capturing inputs…", stage=STAGE_IDEATION)
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""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.
|
||||
_LANGUAGE_CUES: tuple[tuple[str, str], ...] = (
|
||||
("zh-tw", r"(?:繁體中文|正體中文|traditional\s+chinese)"),
|
||||
("zh", r"(?:用(?:简体中文|中文|汉语)|以(?:中文|汉语)|in\s+chinese|in\s+mandarin)"),
|
||||
("ja", r"(?:日本語で|用(?:日语|日文)|in\s+japanese)"),
|
||||
("ko", r"(?:한국어로|用(?:韩语|韓語)|in\s+korean)"),
|
||||
("ru", r"(?:по-русски|на\s+русском|in\s+russian)"),
|
||||
("es", r"(?:en\s+español|en\s+espanol|in\s+spanish|castellano|用(?:西班牙语|西班牙文))"),
|
||||
("fr", r"(?:en\s+français|en\s+francais|in\s+french|用(?:法语|法文))"),
|
||||
("de", r"(?:auf\s+deutsch|in\s+german|用(?:德语|德文))"),
|
||||
("pt", r"(?:em\s+português|em\s+portugues|in\s+portuguese|用(?:葡萄牙语|葡萄牙文))"),
|
||||
("it", r"(?:in\s+italiano|in\s+italian|用(?:意大利语|意大利文))"),
|
||||
("en", r"(?:in\s+english|英語で|用(?:英语|英文)|en\s+anglais|en\s+inglés)"),
|
||||
)
|
||||
|
||||
_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"]
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Language fields must survive both book creation transports."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import FastAPI
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
from deeptutor.api.routers import book as book_router
|
||||
from deeptutor.book.models import Book, BookProposal
|
||||
|
||||
|
||||
class _RecordingEngine:
|
||||
def __init__(self) -> None:
|
||||
self.kwargs: dict | None = None
|
||||
|
||||
async def create_book(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
return Book(id="bk_language", title="Language Test"), BookProposal(title="Language Test")
|
||||
|
||||
|
||||
def _install(monkeypatch, engine: _RecordingEngine) -> FastAPI:
|
||||
monkeypatch.setattr(book_router, "get_book_engine", lambda: engine)
|
||||
monkeypatch.setattr(book_router, "can_create_book", lambda: True)
|
||||
app = FastAPI()
|
||||
app.include_router(book_router.router, prefix="/api/v1/book")
|
||||
return app
|
||||
|
||||
|
||||
def test_rest_create_passes_requested_and_fallback_language(monkeypatch) -> None:
|
||||
engine = _RecordingEngine()
|
||||
app = _install(monkeypatch, engine)
|
||||
|
||||
response = TestClient(app).post(
|
||||
"/api/v1/book/books",
|
||||
json={
|
||||
"user_intent": "Create a book",
|
||||
"language": "auto",
|
||||
"fallback_language": "zh",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert engine.kwargs is not None
|
||||
assert engine.kwargs["language"] == "auto"
|
||||
assert engine.kwargs["fallback_language"] == "zh"
|
||||
|
||||
|
||||
def test_websocket_create_passes_fallback_language(monkeypatch) -> None:
|
||||
engine = _RecordingEngine()
|
||||
app = _install(monkeypatch, engine)
|
||||
|
||||
with TestClient(app).websocket_connect("/api/v1/book/ws") as ws:
|
||||
ws.send_json(
|
||||
{
|
||||
"type": "create",
|
||||
"user_intent": "Create a book",
|
||||
"language": "auto",
|
||||
"fallback_language": "zh",
|
||||
}
|
||||
)
|
||||
result = ws.receive_json()
|
||||
|
||||
assert result["type"] == "create_result"
|
||||
assert engine.kwargs is not None
|
||||
assert engine.kwargs["language"] == "auto"
|
||||
assert engine.kwargs["fallback_language"] == "zh"
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Book creation must persist one concrete language for every later stage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from deeptutor.book.engine import BookEngine
|
||||
from deeptutor.book.models import BookInputs, BookProposal
|
||||
|
||||
|
||||
class _RecordingStorage:
|
||||
def __init__(self) -> None:
|
||||
self.books: list = []
|
||||
self.inputs: list[BookInputs] = []
|
||||
|
||||
def save_book(self, book) -> None:
|
||||
self.books.append(book)
|
||||
|
||||
def save_inputs(self, book_id: str, inputs: BookInputs) -> None:
|
||||
self.inputs.append(inputs)
|
||||
|
||||
def save_progress(self, progress) -> None:
|
||||
self.progress = progress
|
||||
|
||||
def append_log(self, *args, **kwargs) -> None:
|
||||
self.log_calls = (args, kwargs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_book_resolves_auto_before_inputs_are_persisted(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
engine = object.__new__(BookEngine)
|
||||
engine.storage = _RecordingStorage()
|
||||
|
||||
async def fake_ideation(self, ctx, language: str) -> BookProposal:
|
||||
return BookProposal(title="Language Test", estimated_chapters=1)
|
||||
|
||||
monkeypatch.setattr(BookEngine, "_run_ideation", fake_ideation)
|
||||
|
||||
book, _proposal = await engine.create_book(
|
||||
user_intent="Please make a Fourier book in Japanese",
|
||||
language="auto",
|
||||
fallback_language="zh",
|
||||
)
|
||||
|
||||
assert book.language == "ja"
|
||||
assert engine.storage.inputs[0].language == "ja"
|
||||
@@ -0,0 +1,64 @@
|
||||
"""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"),
|
||||
("Please create a book about Japanese history", "en"),
|
||||
],
|
||||
)
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
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"
|
||||
)
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
type SourceTab = "knowledge" | "notebooks" | "questions" | "chats";
|
||||
|
||||
/**
|
||||
* Languages a book can be written in.
|
||||
* Languages a book can be written in, plus the request-driven default.
|
||||
*
|
||||
* Mirrors `_LANGUAGE_LABELS` in `deeptutor/services/prompt/language.py`, which
|
||||
* has always handled all of these — the picker offered only English and
|
||||
@@ -50,6 +50,7 @@ type SourceTab = "knowledge" | "notebooks" | "questions" | "chats";
|
||||
* scans for the word they'd write it in.
|
||||
*/
|
||||
const BOOK_LANGUAGES: Array<{ code: string; label: string }> = [
|
||||
{ code: "auto", label: "Auto" },
|
||||
{ code: "en", label: "English" },
|
||||
{ code: "zh", label: "简体中文" },
|
||||
{ code: "zh-tw", label: "繁體中文" },
|
||||
@@ -103,6 +104,7 @@ export interface BookCreatorProps {
|
||||
question_categories: number[];
|
||||
question_entries: number[];
|
||||
language: string;
|
||||
fallback_language: string;
|
||||
depth: BookDepth;
|
||||
}) => void | Promise<void>;
|
||||
loading?: boolean;
|
||||
@@ -124,8 +126,7 @@ export default function BookCreator({
|
||||
const { t } = useTranslation();
|
||||
const { language: appLanguage } = useAppShell();
|
||||
const [intent, setIntent] = useState("");
|
||||
const [language, setLanguage] = useState<string>(appLanguage);
|
||||
const languageTouchedRef = useRef(false);
|
||||
const [language, setLanguage] = useState<string>("auto");
|
||||
const [depth, setDepth] = useState<BookDepth>("standard");
|
||||
const [tab, setTab] = useState<SourceTab>("knowledge");
|
||||
|
||||
@@ -246,10 +247,6 @@ export default function BookCreator({
|
||||
void refreshSessions();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!languageTouchedRef.current) setLanguage(appLanguage);
|
||||
}, [appLanguage]);
|
||||
|
||||
// ── selection counts ─────────────────────────────────────────────
|
||||
const countSelection = <P extends string | number, C extends string | number>(
|
||||
map: ParentMap<P, C>,
|
||||
@@ -387,6 +384,7 @@ export default function BookCreator({
|
||||
question_categories,
|
||||
question_entries,
|
||||
language,
|
||||
fallback_language: appLanguage,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -770,7 +768,6 @@ export default function BookCreator({
|
||||
<select
|
||||
value={language}
|
||||
onChange={(e) => {
|
||||
languageTouchedRef.current = true;
|
||||
setLanguage(e.target.value);
|
||||
}}
|
||||
className="ml-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-xs text-[var(--foreground)]"
|
||||
|
||||
@@ -520,6 +520,7 @@ function BookPageInner() {
|
||||
question_categories: number[];
|
||||
question_entries: number[];
|
||||
language: string;
|
||||
fallback_language: string;
|
||||
depth: BookDepth;
|
||||
}) => {
|
||||
setCreating(true);
|
||||
|
||||
@@ -98,6 +98,7 @@ export interface CreateBookPayload {
|
||||
question_categories?: number[];
|
||||
question_entries?: number[];
|
||||
language?: string;
|
||||
fallback_language?: string;
|
||||
depth?: BookDepth;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user