DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(voice): add Microsoft Edge read-aloud as a free TTS provider
SeleiXi6e047d905496
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex 8f04e735b..421b02419 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -391,6 +391,15 @@ TTS_PROVIDERS: dict[str, VoiceProviderSpec] = {default_api_base="",default_model="",),+ # Edge's free read-aloud voices via the edge-tts package; no key, no endpoint.+ "edge": VoiceProviderSpec(+ label="Microsoft Edge (free)",+ default_api_base="",+ adapter="edge",+ default_model="edge-tts",+ default_voice="zh-CN-XiaoxiaoNeural",+ is_local=True,+ ),}STT_PROVIDERS: dict[str, VoiceProviderSpec] = {diff --git a/deeptutor/services/voice/adapters/__init__.py b/deeptutor/services/voice/adapters/__init__.pyindex 312cdaf4b..af2d1bd5f 100644--- a/deeptutor/services/voice/adapters/__init__.py+++ b/deeptutor/services/voice/adapters/__init__.py@@ -12,6 +12,7 @@ from deeptutor.services.voice.adapters.dashscope import (DashScopeSTTAdapter,DashScopeTTSAdapter,)+from deeptutor.services.voice.adapters.edge import EdgeTTSAdapterfrom deeptutor.services.voice.adapters.gemini import GeminiTTSAdapterfrom deeptutor.services.voice.adapters.mimo import MiMoTTSAdapterfrom deeptutor.services.voice.adapters.minimax import MiniMaxTTSAdapter@@ -31,6 +32,7 @@ TTS_ADAPTERS: dict[str, BaseTTSAdapter] = {"openrouter_tts": OpenRouterTTSAdapter(),"dashscope": DashScopeTTSAdapter(),"gemini": GeminiTTSAdapter(),+ "edge": EdgeTTSAdapter(),}STT_ADAPTERS: dict[str, BaseSTTAdapter] = {diff --git a/deeptutor/services/voice/adapters/edge.py b/deeptutor/services/voice/adapters/edge.pynew file mode 100644index 000000000..4a3f92196--- /dev/null+++ b/deeptutor/services/voice/adapters/edge.py@@ -0,0 +1,67 @@+"""Microsoft Edge read-aloud voices through the ``edge-tts`` package.++Edge's online voices need no account or API key, which makes them a usable+default when no paid speech provider is configured. The service is not an+official API, so it can be rate limited or change without notice.+Package: https://github.com/rany2/edge-tts+"""++from __future__ import annotations++import math++from deeptutor.services.voice.base import BaseTTSAdapter, VoiceProviderError+from deeptutor.services.voice.config import TTSConfig++EDGE_DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural"+++def edge_rate(speed: float | None) -> str:+ """Map a 0.5–2 speed multiplier onto edge-tts's signed percentage."""+ if speed is None:+ return "+0%"+ if not math.isfinite(speed) or not 0.5 <= speed <= 2:+ raise VoiceProviderError("Edge speech speed must be between 0.5 and 2.")+ return f"{round((speed - 1) * 100):+d}%"+++class EdgeTTSAdapter(BaseTTSAdapter):+ """Stream mp3 audio from Edge's read-aloud service."""++ async def synthesize(self, text: str, config: TTSConfig) -> tuple[bytes, str]:+ try:+ import edge_tts+ except ImportError as exc:+ raise VoiceProviderError(+ "Edge speech needs the edge-tts package: pip install 'deeptutor[edge-tts]'."+ ) from exc+ if (config.response_format or "mp3") != "mp3":+ raise VoiceProviderError("Edge TTS only produces mp3 audio.")+ communicate = edge_tts.Communicate(+ text, config.voice or EDGE_DEFAULT_VOICE, rate=edge_rate(config.speed)+ )+ audio = bytearray()+ try:+ async for chunk in communicate.stream():+ if chunk["type"] == "audio":+ audio += chunk["data"]+ except Exception as exc: # edge-tts raises its own and aiohttp errors+ raise VoiceProviderError(f"Edge TTS request failed: {type(exc).__name__}.") from exc+ if not audio:+ raise VoiceProviderError("Edge TTS returned no audio.")+ return bytes(audio), "audio/mpeg"+++async def list_edge_voices() -> list[dict]:+ """Every public Edge voice, as voice-discovery rows."""+ import edge_tts++ return [+ {+ "id": row["ShortName"],+ "label": f"{row['ShortName']} ({row.get('Gender', '')})".replace(" ()", ""),+ "languages": [row["Locale"]],+ }+ for row in await edge_tts.list_voices()+ if row.get("ShortName") and row.get("Locale")+ ]diff --git a/deeptutor/services/voice/discovery.py b/deeptutor/services/voice/discovery.pyindex 8e2cb3c2a..b06074b76 100644--- a/deeptutor/services/voice/discovery.py+++ b/deeptutor/services/voice/discovery.py@@ -62,6 +62,19 @@ def discovery_url(base: str, provider: str) -> str:async def discover_voices(catalog: dict, profile_id: str, model_id: str) -> dict:config = resolve_tts_runtime_config(selected_catalog(catalog, "tts", profile_id, model_id))provider = config.provider_name+ if provider == "edge":+ from deeptutor.services.voice.adapters.edge import list_edge_voices++ try:+ async with asyncio.timeout(25):+ edge_voices = await list_edge_voices()+ except ImportError as exc:+ raise VoiceDiscoveryError("Install edge-tts before fetching voices.") from exc+ except Exception as exc:+ raise VoiceDiscoveryError(+ "Could not fetch voices. Check the connection and try again."+ ) from exc+ return {"status": "ready", "scope": "public", "voices": edge_voices}# A vendor's speech API key is not permission to call its separately signed# control plane. Never fabricate a generic /voices API for compatible hosts.if provider not in {"minimax", "dashscope"}:diff --git a/deeptutor/services/voice/options.py b/deeptutor/services/voice/options.pyindex 38c848947..04d21fab6 100644--- a/deeptutor/services/voice/options.py+++ b/deeptutor/services/voice/options.py@@ -168,6 +168,18 @@ def _tts_models(provider: str) -> tuple[list[dict], str]:language_note="Saudi Arabic; enter a voice ID from the provider documentation.",),], "https://console.groq.com/docs/text-to-speech"+ if provider == "edge":+ return [+ preset(+ "edge-tts",+ formats=["mp3"],+ speed={"min": 0.5, "max": 2, "step": 0.05},+ configuration_note=(+ "Free Microsoft Edge read-aloud voices; no API key. Not an official API, "+ "so it may be rate limited. Voices look like zh-CN-XiaoxiaoNeural."+ ),+ )+ ], "https://github.com/rany2/edge-tts"if provider == "siliconflow":siliconflow_model = "FunAudioLLM/CosyVoice2-0.5B"return [@@ -201,6 +213,8 @@ def voice_options(provider: str, service: str) -> dict:fallback = preset("", formats=["wav", "pcm16"], instructions=True)elif provider == "gemini":fallback = preset("", formats=["wav", "pcm"], instructions=True)+ elif provider == "edge":+ fallback = {**deepcopy(models[0]), "id": ""}else:ids = {"openai": ["gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1"],diff --git a/pyproject.toml b/pyproject.tomlindex 3b68bbca5..865b704ab 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -165,6 +165,9 @@ codebuddy = ["codebuddy-agent-sdk>=0.3,<0.4"]# adapter enables transcript-grounded learning when public captions exist.video-learning = ["youtube-transcript-api>=1.0.0,<2.0.0"]+# Microsoft Edge read-aloud voices as a free, keyless TTS provider.+edge-tts = ["edge-tts>=7.0,<8.0"]+# Compatibility extra for source installs and older docs. These packages are# already included in the public `deeptutor` wheel.server = [@@ -310,6 +313,7 @@ all = ["deeptutor[math-animator]","deeptutor[dev]","deeptutor[video-learning]",+ "deeptutor[edge-tts]",][tool.setuptools]diff --git a/requirements/edge-tts.txt b/requirements/edge-tts.txtnew file mode 100644index 000000000..eda0e15e8--- /dev/null+++ b/requirements/edge-tts.txt@@ -0,0 +1,2 @@+# Optional free TTS provider: Microsoft Edge read-aloud voices, no API key.+edge-tts>=7.0,<8.0diff --git a/tests/services/test_edge_voice.py b/tests/services/test_edge_voice.pynew file mode 100644index 000000000..8363288dc--- /dev/null+++ b/tests/services/test_edge_voice.py@@ -0,0 +1,78 @@+"""Edge read-aloud speech: keyless catalog resolution and the edge-tts call, offline."""++import sys+import types++import pytest++from deeptutor.services.config.provider_runtime import TTS_PROVIDERS, resolve_tts_runtime_config+from deeptutor.services.voice import synthesize_speech+from deeptutor.services.voice.adapters.edge import edge_rate+from deeptutor.services.voice.base import VoiceProviderError+++def catalog(**model):+ """The connection Settings stores for Edge: no API key."""+ return {+ "version": 1,+ "connections": [{"id": "speech", "provider": "edge"}],+ "services": {+ "tts": {+ "active_profile_id": "p",+ "active_model_id": "m",+ "profiles": [+ {+ "id": "p",+ "provider_ref": {"connection_id": "speech", "binding": "edge"},+ "models": [{"id": "m", "model": "edge-tts", **model}],+ }+ ],+ }+ },+ }+++def fake_edge(monkeypatch):+ calls = []++ class Communicate:+ def __init__(self, text, voice, *, rate="+0%"):+ calls.append({"text": text, "voice": voice, "rate": rate})++ async def stream(self):+ yield {"type": "SentenceBoundary", "offset": 0, "duration": 1, "text": "hi"}+ yield {"type": "audio", "data": b"ID3"}+ yield {"type": "audio", "data": b"abc"}++ monkeypatch.setitem(sys.modules, "edge_tts", types.SimpleNamespace(Communicate=Communicate))+ return calls+++def test_edge_resolves_without_an_api_key() -> None:+ resolved = resolve_tts_runtime_config(catalog())+ assert resolved.provider_name == resolved.adapter == "edge"+ assert resolved.model == TTS_PROVIDERS["edge"].default_model+ assert resolved.response_format == "mp3"+++async def test_edge_speaks_with_the_configured_voice_and_speed(fake_edge) -> None:+ audio = await synthesize_speech(+ "Hello", catalog=catalog(voice="en-US-AvaNeural", speed=1.25), math_speak=False+ )+ assert audio == (b"ID3abc", "audio/mpeg")+ assert fake_edge == [{"text": "Hello", "voice": "en-US-AvaNeural", "rate": "+25%"}]+++async def test_edge_defaults_to_a_chinese_voice(fake_edge) -> None:+ await synthesize_speech("你好", catalog=catalog(), math_speak=False)+ assert fake_edge[0]["voice"] == "zh-CN-XiaoxiaoNeural"+++def test_edge_rate_bounds() -> None:+ assert edge_rate(None) == "+0%"+ assert edge_rate(0.8) == "-20%"+ with pytest.raises(VoiceProviderError):+ edge_rate(3)