DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(reading): add safe read-aloud extension (#1103)
XZH1fb291045d8d
diff --git a/deeptutor/reading/read_aloud.py b/deeptutor/reading/read_aloud.pynew file mode 100644index 000000000..23a54a7e1--- /dev/null+++ b/deeptutor/reading/read_aloud.py@@ -0,0 +1,33 @@+"""Built-in browser speech extension for Immersive Reading."""++from __future__ import annotations++from deeptutor.reading.extensions import (+ ReadingAction,+ ReadingContext,+ ReadingExtensionManifest,+ ReadingExtensionResult,+)+++class ReadAloudExtension:+ """Return server-verified unit text for the browser's speech API."""++ manifest = ReadingExtensionManifest(+ id="read_aloud",+ version="1.0.0",+ name="Read aloud",+ actions=[ReadingAction(id="read", label="Read aloud")],+ result_types=["browser_speech"],+ )++ def run_action(self, action: str, context: ReadingContext) -> ReadingExtensionResult:+ if action != "read":+ raise ValueError(f"Unsupported read-aloud action: {action}")+ return ReadingExtensionResult(+ type="browser_speech",+ payload={"text": context.visible_text, "locale": context.locale},+ )+++__all__ = ["ReadAloudExtension"]diff --git a/pyproject.toml b/pyproject.tomlindex 99953ad77..f97f32935 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -83,6 +83,9 @@ dependencies = [[project.scripts]deeptutor = "deeptutor_cli.main:main"+[project.entry-points."deeptutor.reading_extensions"]+read_aloud = "deeptutor.reading.read_aloud:ReadAloudExtension"+[project.optional-dependencies]# Compatibility extra for source installs and older docs. These packages are# already included in the public `deeptutor` wheel; the local CLI-only projectdiff --git a/tests/reading/test_extensions.py b/tests/reading/test_extensions.pyindex 0e041d6ed..bb7597f3c 100644--- a/tests/reading/test_extensions.py+++ b/tests/reading/test_extensions.py@@ -26,7 +26,7 @@ def _extension(identifier: str = "sample"):)-def test_core_has_no_builtin_reading_extensions(monkeypatch):+def test_registry_is_empty_when_no_entry_points_are_installed(monkeypatch):monkeypatch.setattr("deeptutor.reading.extensions.load_entry_point_group",lambda *_args, **_kwargs: [],diff --git a/tests/reading/test_read_aloud.py b/tests/reading/test_read_aloud.pynew file mode 100644index 000000000..af10ec6d8--- /dev/null+++ b/tests/reading/test_read_aloud.py@@ -0,0 +1,78 @@+from __future__ import annotations++from pathlib import Path+import tomllib++from fastapi import FastAPI+from fastapi.testclient import TestClient++from deeptutor.api.routers import reading_extensions+from deeptutor.reading import ReadingStore+from deeptutor.reading.extensions import ReadingContext, ReadingExtensionRegistry+from deeptutor.reading.read_aloud import ReadAloudExtension+from deeptutor.services.path_service import PathService+++def test_read_aloud_returns_verified_visible_text_only():+ context = ReadingContext(+ material_id="material",+ locator=2,+ locale="zh-CN",+ visible_text="Visible passage",+ )++ result = ReadAloudExtension().run_action("read", context)++ assert result.type == "browser_speech"+ assert result.payload == {"text": "Visible passage", "locale": "zh-CN"}+++def test_read_aloud_is_registered_as_a_packaged_extension():+ project = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))+ group = project["project"]["entry-points"]["deeptutor.reading_extensions"]++ assert group == {"read_aloud": "deeptutor.reading.read_aloud:ReadAloudExtension"}+++def test_read_aloud_crosses_the_authenticated_api_boundary_with_stored_text(monkeypatch, tmp_path):+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ source = tmp_path / "source.txt"+ source.write_text("Stored unit text only.", encoding="utf-8")+ material = ReadingStore().ingest(source)+ registry = ReadingExtensionRegistry([ReadAloudExtension()])+ monkeypatch.setattr(+ reading_extensions,+ "get_reading_extension_registry",+ lambda: registry,+ )+ app = FastAPI()+ app.include_router(reading_extensions.router, prefix="/api/v1/reading")+ client = TestClient(app)++ try:+ response = client.post(+ f"/api/v1/reading/materials/{material.material_id}/extensions/read_aloud/actions/read",+ json={"locator": 1, "visible_text": "Forged text", "locale": "zh-CN"},+ )+ finally:+ PathService.reset_instance()++ assert response.status_code == 200, response.text+ assert response.json() == {+ "type": "browser_speech",+ "title": "",+ "message": "",+ "payload": {"text": "Stored unit text only.", "locale": "zh-CN"},+ }+++def test_read_aloud_rejects_undeclared_actions():+ context = ReadingContext(material_id="material", locator=1, visible_text="Text")++ try:+ ReadAloudExtension().run_action("summarize", context)+ except ValueError as exc:+ assert "Unsupported read-aloud action" in str(exc)+ else:+ raise AssertionError("undeclared action must fail")diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsxindex f681eba4b..5d89974c2 100644--- a/web/components/reading/ReadingExtensionBar.tsx+++ b/web/components/reading/ReadingExtensionBar.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useMemo, useState } from "react";-import { Loader2, Sparkles, X } from "lucide-react";+import { Loader2, Sparkles, Square, Volume2, X } from "lucide-react";import { useTranslation } from "react-i18next";import {listReadingExtensions,@@ -25,6 +25,12 @@ export function ReadingExtensionBar({const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([]);const [busy, setBusy] = useState("");const [result, setResult] = useState<ReadingExtensionResult | null>(null);+ const [speaking, setSpeaking] = useState(false);++ function stopSpeaking() {+ window.speechSynthesis?.cancel();+ setSpeaking(false);+ }useEffect(() => {let active = true;@@ -38,11 +44,16 @@ export function ReadingExtensionBar({});return () => {active = false;- window.speechSynthesis?.cancel();};- }, [materialId, onError]);+ }, [onError]);- useEffect(() => setResult(null), [locator, materialId]);+ useEffect(() => {+ setResult(null);+ return () => {+ window.speechSynthesis?.cancel();+ setSpeaking(false);+ };+ }, [locator, materialId]);const actions = useMemo(() =>@@ -79,7 +90,10 @@ export function ReadingExtensionBar({window.speechSynthesis.cancel();const utterance = new SpeechSynthesisUtterance(text);utterance.lang = String(next.payload.locale || i18n.language);+ utterance.onend = () => setSpeaking(false);+ utterance.onerror = () => setSpeaking(false);window.speechSynthesis.speak(utterance);+ setSpeaking(true);}} catch (error) {onError(error instanceof Error ? error.message : String(error));@@ -97,6 +111,10 @@ export function ReadingExtensionBar({const disabled =Boolean(busy) ||(action.requires.includes("selection") && !selection?.trim());+ const label =+ extension.id === "read_aloud" && action.id === "read"+ ? t("Read aloud")+ : action.label;return (<buttonkey={key}@@ -110,11 +128,29 @@ export function ReadingExtensionBar({) : (<Sparkles size={14} />)}- <span className="truncate">{action.label}</span>+ <span className="truncate">{label}</span></button>);})}</div>+ {speaking ? (+ <div+ role="status"+ className="flex shrink-0 items-center gap-2 border-b border-[var(--border)] bg-[var(--card)] px-3 py-2 text-xs text-[var(--muted-foreground)]"+ >+ <Volume2 size={14} />+ <span>{t("Reading aloud")}</span>+ <button+ type="button"+ aria-label={t("Stop reading aloud")}+ title={t("Stop reading aloud")}+ onClick={stopSpeaking}+ className="ml-auto inline-flex h-7 w-7 items-center justify-center rounded-md text-[var(--foreground)] transition hover:bg-[var(--muted)]"+ >+ <Square size={12} fill="currentColor" />+ </button>+ </div>+ ) : null}{result && result.type !== "browser_speech" ? (<ExtensionResultresult={result}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 300b8d93c..bde80ba3b 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3840,6 +3840,9 @@"What DeepTutor has noticed": "What DeepTutor has noticed","Mastery path": "Mastery path","Reading": "Reading",+ "Read aloud": "Read aloud",+ "Reading aloud": "Reading aloud",+ "Stop reading aloud": "Stop reading aloud","Partner group": "Partner group","Everything this course studies with. Conversations here start with these already in hand.": "Everything this course studies with. Conversations here start with these already in hand.","Nothing attached yet. Add a textbook or knowledge base and this course starts knowing what it is about.": "Nothing attached yet. Add a textbook or knowledge base and this course starts knowing what it is about.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 85b1d8031..e89472980 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3840,6 +3840,9 @@"What DeepTutor has noticed": "DeepTutor 注意到的","Mastery path": "精通之路","Reading": "阅读",+ "Read aloud": "朗读",+ "Reading aloud": "正在朗读",+ "Stop reading aloud": "停止朗读","Partner group": "伙伴群组","Everything this course studies with. Conversations here start with these already in hand.": "这门课用到的一切。课内对话开口就带着它们。","Nothing attached yet. Add a textbook or knowledge base and this course starts knowing what it is about.": "还没挂任何资料。挂上教材或知识库,这门课就知道自己在讲什么了。",diff --git a/web/tests/reading-extensions.test.ts b/web/tests/reading-extensions.test.tsindex a42619f7b..dad380501 100644--- a/web/tests/reading-extensions.test.ts+++ b/web/tests/reading-extensions.test.ts@@ -15,6 +15,8 @@ const api = readFileSync(path.resolve(process.cwd(), "lib/reading-api.ts"),"utf8",);+const english = readFileSync(path.resolve(process.cwd(), "locales/en/app.json"), "utf8");+const chinese = readFileSync(path.resolve(process.cwd(), "locales/zh/app.json"), "utf8");test("the Reader toolbar is empty when no extension is installed", () => {assert.match(component, /if \(actions\.length === 0\) return null/);@@ -38,3 +40,24 @@ test("a malformed extension catalog cannot crash the whole reader", () => {/Array\.isArray\(\(row as ReadingExtensionManifest\)\.actions\)/,);});++test("browser speech is stoppable and cannot continue after navigation", () => {+ assert.match(component, /const \[speaking, setSpeaking\] = useState\(false\)/);+ assert.match(component, /function stopSpeaking\(\)/);+ assert.match(component, /window\.speechSynthesis\?\.cancel\(\)/);+ assert.match(component, /utterance\.onend = \(\) => setSpeaking\(false\)/);+ assert.match(component, /utterance\.onerror = \(\) => setSpeaking\(false\)/);+ assert.match(component, /\}, \[locator, materialId\]\);/);+ assert.match(component, /aria-label=\{t\("Stop reading aloud"\)\}/);+});++test("the built-in read-aloud action is localized", () => {+ assert.match(component, /extension\.id === "read_aloud" && action\.id === "read"/);+ assert.match(component, /t\("Read aloud"\)/);+ assert.match(english, /"Read aloud": "Read aloud"/);+ assert.match(chinese, /"Read aloud": "朗读"/);+ assert.match(english, /"Reading aloud": "Reading aloud"/);+ assert.match(chinese, /"Reading aloud": "正在朗读"/);+ assert.match(english, /"Stop reading aloud": "Stop reading aloud"/);+ assert.match(chinese, /"Stop reading aloud": "停止朗读"/);+});