auto-tts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # auto-tts
2
+
3
+ 基于 [edge-tts](https://github.com/rany2/edge-tts) 的无限量文本转语音工具。输入文本,挑一个音色和语气,队列会把它们合成成 mp3,可在线试听和下载。
4
+
5
+ 不需要 API Key,不按字数收费,长文本和批量任务都能排队处理。
6
+
7
+ ## 快速开始
8
+
9
+ 一条命令,不需要 clone 仓库,也不需要手动装 Python 依赖:
10
+
11
+ ```bash
12
+ npx auto-tts web
13
+ ```
14
+
15
+ 首次运行会在 `~/.local/share/auto-tts/venv` 建一个独立的 Python 环境并安装后端依赖(只需一次),随后启动服务并自动打开浏览器。
16
+
17
+ ### 环境要求
18
+
19
+ | 依赖 | 版本 | 说明 |
20
+ | --- | --- | --- |
21
+ | Node.js | 18 或更高 | 用来运行 `npx` 命令 |
22
+ | Python | 3.9 或更高 | 后端运行时 |
23
+
24
+ Debian / Ubuntu 上如果提示无法创建虚拟环境,需要先装 `python3-venv`:
25
+
26
+ ```bash
27
+ sudo apt install python3-venv
28
+ ```
29
+
30
+ ### 常用参数
31
+
32
+ ```bash
33
+ npx auto-tts web --port 9000 # 换一个端口(默认 8000)
34
+ npx auto-tts web --host 0.0.0.0 # 允许局域网内其它设备访问
35
+ npx auto-tts web --no-open # 不自动打开浏览器
36
+ npx auto-tts web --reset # 重建 Python 环境后启动
37
+ npx auto-tts --help # 查看全部用法
38
+ ```
39
+
40
+ ## 功能
41
+
42
+ - **音色**:322 个 edge-tts 音色,可按语言区域或名称筛选
43
+ - **语气**:自然、温柔、愉悦、兴奋、严肃、悲伤、新闻播报、低语,另有自定义
44
+ - **长文本**:自动分块合成,长度不限
45
+ - **批量队列**:用空行分隔多段文本,每段成为一个独立任务
46
+ - **任务面板**:实时进度、失败原因、试听、下载 mp3
47
+
48
+ ### 关于语气
49
+
50
+ edge-tts 本身**不支持**真正的情感风格(微软服务端会拒绝 `<mstts:express-as>` 一类的请求),所以这里的语气是用**语速、音调、音量**三个参数组合近似出来的预设。选中预设会自动填写这三个滑块,手动拖动任一滑块则切回「自定义」。所有预设定义在 [`backend/app/tts.py`](backend/app/tts.py) 的 `TONE_PRESETS`。
51
+
52
+ ## 数据存放位置
53
+
54
+ 生成内容和运行环境都放在用户目录,不会写进 node_modules:
55
+
56
+ ```
57
+ ~/.local/share/auto-tts/
58
+ ├── venv/ # Python 虚拟环境
59
+ ├── data/audio/ # 生成的 mp3
60
+ └── requirements.sha256 # 依赖指纹,用于判断是否需要重装
61
+ ```
62
+
63
+ `requirements.txt` 改动后,下次启动会自动识别并重装依赖。
64
+
65
+ ## 从源码运行
66
+
67
+ 如果你想改代码,把仓库克隆下来:
68
+
69
+ ```bash
70
+ git clone https://github.com/kms413/auto-tts.git
71
+ cd auto-tts
72
+ ./start.sh # 建 venv、装依赖、构建前端、单端口启动
73
+ ./start.sh --dev # 开发模式:后端热重载 + Vite 开发服务器
74
+ ./start.sh --rebuild
75
+ ```
76
+
77
+ `./start.sh` 与 `npx auto-tts web` 效果一致,区别是使用仓库内的 `.venv` 和源码构建产物。
78
+
79
+ ## HTTP 接口
80
+
81
+ 服务同时托管页面和 API,全部挂在同一个端口下:
82
+
83
+ | 方法 | 路径 | 说明 |
84
+ | --- | --- | --- |
85
+ | GET | `/api/health` | 健康检查 |
86
+ | GET | `/api/voices` | 全部可用音色 |
87
+ | GET | `/api/tones` | 语气预设及其对应的语速/音调/音量 |
88
+ | POST | `/api/jobs` | 创建任务,`text` 单条或 `texts` 批量 |
89
+ | GET | `/api/jobs` | 任务列表 |
90
+ | GET | `/api/jobs/{id}` | 单个任务 |
91
+ | DELETE | `/api/jobs/{id}` | 删除任务 |
92
+ | GET | `/api/audio/{filename}` | 获取音频文件 |
93
+
94
+ ## 技术栈
95
+
96
+ - 后端:FastAPI + edge-tts,任务队列为进程内异步队列
97
+ - 前端:React + TypeScript + Vite
98
+
99
+ ## 许可
100
+
101
+ GNU Affero General Public License v3.0 或更新版本(AGPL-3.0-or-later),完整条款见 [LICENSE](LICENSE)。
102
+
103
+ Copyright (C) 2026 kms413
104
+
105
+ AGPL 第 13 条要求以网络方式提供服务的程序向用户提供获取源代码的途径,因此页面底部保留了「获取源代码」链接,请勿移除。
@@ -0,0 +1 @@
1
+ """auto-tts backend package."""
@@ -0,0 +1,36 @@
1
+ """Runtime configuration resolved from environment variables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ BASE_DIR = Path(__file__).resolve().parent.parent
9
+ PROJECT_DIR = BASE_DIR.parent
10
+ DATA_DIR = Path(os.getenv("AUTO_TTS_DATA_DIR", BASE_DIR / "data"))
11
+ AUDIO_DIR = DATA_DIR / "audio"
12
+
13
+ # Built frontend served by the backend in single-port mode. When the directory
14
+ # is missing the API still runs and the Vite dev server proxies to it instead.
15
+ FRONTEND_DIST = Path(os.getenv("AUTO_TTS_FRONTEND_DIST", PROJECT_DIR / "frontend" / "dist"))
16
+
17
+ # Number of synthesis jobs that may run in parallel.
18
+ MAX_CONCURRENCY = int(os.getenv("AUTO_TTS_MAX_CONCURRENCY", "2"))
19
+
20
+ # Long texts are split into chunks of at most this many characters before
21
+ # being sent to edge-tts, then concatenated back into a single audio file.
22
+ CHUNK_SIZE = int(os.getenv("AUTO_TTS_CHUNK_SIZE", "800"))
23
+
24
+ CORS_ORIGINS = [
25
+ origin.strip()
26
+ for origin in os.getenv(
27
+ "AUTO_TTS_CORS_ORIGINS",
28
+ "http://localhost:5173,http://127.0.0.1:5173",
29
+ ).split(",")
30
+ if origin.strip()
31
+ ]
32
+
33
+
34
+ def ensure_dirs() -> None:
35
+ """Create the directories required at runtime."""
36
+ AUDIO_DIR.mkdir(parents=True, exist_ok=True)
@@ -0,0 +1,145 @@
1
+ """In-memory job queue that drives edge-tts synthesis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ import uuid
8
+ from dataclasses import dataclass, field
9
+
10
+ from . import config, tts
11
+
12
+
13
+ @dataclass
14
+ class Job:
15
+ """A single text-to-speech task."""
16
+
17
+ id: str
18
+ text: str
19
+ voice: str
20
+ tone: str
21
+ rate: int
22
+ volume: int
23
+ pitch: int
24
+ status: str = "pending"
25
+ progress: float = 0.0
26
+ error: str | None = None
27
+ created_at: float = field(default_factory=time.time)
28
+ finished_at: float | None = None
29
+ size_bytes: int = 0
30
+
31
+ @property
32
+ def filename(self) -> str:
33
+ return f"{self.id}.mp3"
34
+
35
+ def to_dict(self) -> dict:
36
+ return {
37
+ "id": self.id,
38
+ "text": self.text,
39
+ "voice": self.voice,
40
+ "tone": self.tone,
41
+ "tone_label": tts.tone_label(self.tone),
42
+ "rate": self.rate,
43
+ "volume": self.volume,
44
+ "pitch": self.pitch,
45
+ "status": self.status,
46
+ "progress": round(self.progress, 3),
47
+ "error": self.error,
48
+ "created_at": self.created_at,
49
+ "finished_at": self.finished_at,
50
+ "size_bytes": self.size_bytes,
51
+ "chars": len(self.text),
52
+ "audio_url": f"/api/audio/{self.filename}" if self.status == "completed" else None,
53
+ }
54
+
55
+
56
+ class JobManager:
57
+ """Queue and worker pool that turns jobs into audio files."""
58
+
59
+ def __init__(self, concurrency: int) -> None:
60
+ self._concurrency = max(1, concurrency)
61
+ self._jobs: dict[str, Job] = {}
62
+ self._queue: asyncio.Queue[str] = asyncio.Queue()
63
+ self._workers: list[asyncio.Task] = []
64
+ self._lock = asyncio.Lock()
65
+
66
+ async def start(self) -> None:
67
+ self._workers = [asyncio.create_task(self._worker()) for _ in range(self._concurrency)]
68
+
69
+ async def stop(self) -> None:
70
+ for worker in self._workers:
71
+ worker.cancel()
72
+ if self._workers:
73
+ await asyncio.gather(*self._workers, return_exceptions=True)
74
+ self._workers = []
75
+
76
+ async def submit(self, text: str, voice: str, tone: str, rate: int, volume: int, pitch: int) -> Job:
77
+ job = Job(
78
+ id=uuid.uuid4().hex,
79
+ text=text,
80
+ voice=voice,
81
+ tone=tone,
82
+ rate=rate,
83
+ volume=volume,
84
+ pitch=pitch,
85
+ )
86
+ async with self._lock:
87
+ self._jobs[job.id] = job
88
+ await self._queue.put(job.id)
89
+ return job
90
+
91
+ async def list(self) -> list[Job]:
92
+ async with self._lock:
93
+ return sorted(self._jobs.values(), key=lambda job: job.created_at, reverse=True)
94
+
95
+ async def get(self, job_id: str) -> Job | None:
96
+ async with self._lock:
97
+ return self._jobs.get(job_id)
98
+
99
+ async def delete(self, job_id: str) -> bool:
100
+ async with self._lock:
101
+ job = self._jobs.pop(job_id, None)
102
+ if job is None:
103
+ return False
104
+ (config.AUDIO_DIR / job.filename).unlink(missing_ok=True)
105
+ return True
106
+
107
+ async def _worker(self) -> None:
108
+ while True:
109
+ job_id = await self._queue.get()
110
+ try:
111
+ job = await self.get(job_id)
112
+ if job is None:
113
+ continue
114
+ await self._run(job)
115
+ finally:
116
+ self._queue.task_done()
117
+
118
+ async def _run(self, job: Job) -> None:
119
+ job.status = "processing"
120
+
121
+ async def on_progress(value: float) -> None:
122
+ job.progress = value
123
+
124
+ try:
125
+ size = await tts.synthesize(
126
+ job.text,
127
+ job.voice,
128
+ tts.format_rate(job.rate),
129
+ tts.format_volume(job.volume),
130
+ tts.format_pitch(job.pitch),
131
+ config.AUDIO_DIR / job.filename,
132
+ on_progress,
133
+ )
134
+ job.size_bytes = size
135
+ job.progress = 1.0
136
+ job.status = "completed"
137
+ except asyncio.CancelledError:
138
+ job.status = "failed"
139
+ job.error = "cancelled"
140
+ raise
141
+ except Exception as exc: # noqa: BLE001 - surfaced to the client via job.error
142
+ job.status = "failed"
143
+ job.error = str(exc) or exc.__class__.__name__
144
+ finally:
145
+ job.finished_at = time.time()
@@ -0,0 +1,119 @@
1
+ """FastAPI application exposing the auto-tts HTTP API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import asynccontextmanager
6
+ from pathlib import Path
7
+
8
+ from fastapi import FastAPI, HTTPException
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import FileResponse
11
+ from fastapi.staticfiles import StaticFiles
12
+
13
+ from . import config, tts
14
+ from .jobs import JobManager
15
+ from .schemas import JobView, SynthesisRequest
16
+
17
+ manager = JobManager(config.MAX_CONCURRENCY)
18
+
19
+
20
+ @asynccontextmanager
21
+ async def lifespan(_: FastAPI):
22
+ config.ensure_dirs()
23
+ await manager.start()
24
+ yield
25
+ await manager.stop()
26
+
27
+
28
+ app = FastAPI(title="auto-tts", version="0.1.0", lifespan=lifespan)
29
+ app.add_middleware(
30
+ CORSMiddleware,
31
+ allow_origins=config.CORS_ORIGINS,
32
+ allow_methods=["*"],
33
+ allow_headers=["*"],
34
+ )
35
+
36
+
37
+ @app.get("/api/health")
38
+ async def health() -> dict:
39
+ return {"status": "ok"}
40
+
41
+
42
+ @app.get("/api/voices")
43
+ async def voices() -> list[dict]:
44
+ """Return the available voices, normalised for the frontend."""
45
+ result = [
46
+ {
47
+ "name": voice["ShortName"],
48
+ "locale": voice["Locale"],
49
+ "gender": voice["Gender"],
50
+ "friendly_name": voice.get("FriendlyName", voice["ShortName"]),
51
+ }
52
+ for voice in await tts.list_voices()
53
+ ]
54
+ result.sort(key=lambda item: (item["locale"], item["name"]))
55
+ return result
56
+
57
+
58
+ @app.get("/api/tones")
59
+ async def tones() -> list[dict]:
60
+ """Return the speaking-tone presets the frontend maps onto prosody."""
61
+ return tts.list_tones()
62
+
63
+
64
+ @app.post("/api/jobs", response_model=list[JobView])
65
+ async def create_jobs(payload: SynthesisRequest) -> list[dict]:
66
+ """Create one job per text (batch mode) or a single job for `text`."""
67
+ texts = payload.texts if payload.texts else [payload.text]
68
+ texts = [text for text in texts if text and text.strip()]
69
+ if not texts:
70
+ raise HTTPException(status_code=400, detail="No text provided")
71
+
72
+ jobs = [
73
+ await manager.submit(
74
+ text,
75
+ payload.voice,
76
+ payload.tone,
77
+ payload.rate,
78
+ payload.volume,
79
+ payload.pitch,
80
+ )
81
+ for text in texts
82
+ ]
83
+ return [job.to_dict() for job in jobs]
84
+
85
+
86
+ @app.get("/api/jobs", response_model=list[JobView])
87
+ async def list_jobs() -> list[dict]:
88
+ return [job.to_dict() for job in await manager.list()]
89
+
90
+
91
+ @app.get("/api/jobs/{job_id}", response_model=JobView)
92
+ async def get_job(job_id: str) -> dict:
93
+ job = await manager.get(job_id)
94
+ if job is None:
95
+ raise HTTPException(status_code=404, detail="Job not found")
96
+ return job.to_dict()
97
+
98
+
99
+ @app.delete("/api/jobs/{job_id}")
100
+ async def delete_job(job_id: str) -> dict:
101
+ if not await manager.delete(job_id):
102
+ raise HTTPException(status_code=404, detail="Job not found")
103
+ return {"deleted": job_id}
104
+
105
+
106
+ @app.get("/api/audio/{filename}")
107
+ async def get_audio(filename: str) -> FileResponse:
108
+ if Path(filename).name != filename:
109
+ raise HTTPException(status_code=404, detail="Audio not found")
110
+ path = config.AUDIO_DIR / filename
111
+ if not path.is_file():
112
+ raise HTTPException(status_code=404, detail="Audio not found")
113
+ return FileResponse(path, media_type="audio/mpeg", filename=filename)
114
+
115
+
116
+ # Serve the built frontend from the same origin so a single command can run the
117
+ # whole app on one port. Mounted last, so every /api route above takes priority.
118
+ if config.FRONTEND_DIST.is_dir():
119
+ app.mount("/", StaticFiles(directory=config.FRONTEND_DIST, html=True), name="frontend")
@@ -0,0 +1,41 @@
1
+ """Pydantic schemas shared by the auto-tts HTTP API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ class SynthesisRequest(BaseModel):
9
+ """Payload used to create one or more synthesis jobs."""
10
+
11
+ text: str = Field(default="", description="Single text to synthesise.")
12
+ texts: list[str] | None = Field(
13
+ default=None,
14
+ description="Batch of texts; when present it takes precedence over `text`.",
15
+ )
16
+ voice: str = Field(..., description="edge-tts voice short name.")
17
+ tone: str = Field(default="natural", description="Speaking-tone preset key.")
18
+ rate: int = Field(default=0, ge=-100, le=200, description="Speaking rate delta, percent.")
19
+ volume: int = Field(default=0, ge=-100, le=100, description="Volume delta, percent.")
20
+ pitch: int = Field(default=0, ge=-100, le=100, description="Pitch delta, Hz.")
21
+
22
+
23
+ class JobView(BaseModel):
24
+ """Serialised view of a synthesis job."""
25
+
26
+ id: str
27
+ text: str
28
+ voice: str
29
+ tone: str
30
+ tone_label: str
31
+ rate: int
32
+ volume: int
33
+ pitch: int
34
+ status: str
35
+ progress: float
36
+ error: str | None = None
37
+ created_at: float
38
+ finished_at: float | None = None
39
+ size_bytes: int
40
+ chars: int
41
+ audio_url: str | None = None
@@ -0,0 +1,141 @@
1
+ """edge-tts integration: voice discovery and speech synthesis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import re
7
+ from collections.abc import Awaitable, Callable
8
+ from pathlib import Path
9
+
10
+ import edge_tts
11
+
12
+ from . import config
13
+
14
+ ProgressCallback = Callable[[float], Awaitable[None]]
15
+
16
+ _voices_cache: list[dict] | None = None
17
+ _voices_lock = asyncio.Lock()
18
+
19
+ # Split on sentence terminators while keeping the terminator with the sentence.
20
+ _SENTENCE_BOUNDARY = re.compile(r"(?<=[。!?;!?;.\n])")
21
+
22
+
23
+ def format_rate(value: int) -> str:
24
+ """Convert a percent delta into the edge-tts rate string."""
25
+ return f"{value:+d}%"
26
+
27
+
28
+ def format_volume(value: int) -> str:
29
+ """Convert a percent delta into the edge-tts volume string."""
30
+ return f"{value:+d}%"
31
+
32
+
33
+ def format_pitch(value: int) -> str:
34
+ """Convert a hertz delta into the edge-tts pitch string."""
35
+ return f"{value:+d}Hz"
36
+
37
+
38
+ # Speaking-tone presets. edge-tts does not expose emotion styles, so every tone
39
+ # is approximated with a rate/volume/pitch delta triple that the frontend can
40
+ # apply to the prosody controls.
41
+ TONE_PRESETS: tuple[dict, ...] = (
42
+ {"key": "natural", "label": "自然", "hint": "默认语速与音高", "rate": 0, "volume": 0, "pitch": 0},
43
+ {"key": "gentle", "label": "温柔", "hint": "放慢、压低,像在耳边说话", "rate": -10, "volume": -6, "pitch": 4},
44
+ {"key": "cheerful", "label": "愉悦", "hint": "略快、上扬,带一点笑意", "rate": 8, "volume": 4, "pitch": 8},
45
+ {"key": "excited", "label": "兴奋", "hint": "更快、更亮,情绪外放", "rate": 16, "volume": 8, "pitch": 14},
46
+ {"key": "serious", "label": "严肃", "hint": "沉稳、低音,适合声明", "rate": -6, "volume": 2, "pitch": -8},
47
+ {"key": "sad", "label": "悲伤", "hint": "缓慢、低沉,语气下沉", "rate": -14, "volume": -8, "pitch": -6},
48
+ {"key": "newscast", "label": "新闻播报", "hint": "清晰、稳定,字正腔圆", "rate": 6, "volume": 6, "pitch": -2},
49
+ {"key": "whisper", "label": "低语", "hint": "轻声细语,音量很轻", "rate": -8, "volume": -40, "pitch": 2},
50
+ {"key": "custom", "label": "自定义", "hint": "自己微调语速、音调与音量", "rate": 0, "volume": 0, "pitch": 0},
51
+ )
52
+
53
+ TONE_INDEX: dict[str, dict] = {preset["key"]: preset for preset in TONE_PRESETS}
54
+
55
+ DEFAULT_TONE = "natural"
56
+
57
+
58
+ def list_tones() -> list[dict]:
59
+ """Return the speaking-tone presets understood by the API."""
60
+ return [dict(preset) for preset in TONE_PRESETS]
61
+
62
+
63
+ def tone_label(key: str) -> str:
64
+ """Resolve a tone key to its display label, falling back to the raw key."""
65
+ preset = TONE_INDEX.get(key)
66
+ return preset["label"] if preset else key
67
+
68
+
69
+ async def list_voices() -> list[dict]:
70
+ """Return the edge-tts voice catalogue, cached for the process lifetime."""
71
+ global _voices_cache
72
+ async with _voices_lock:
73
+ if _voices_cache is None:
74
+ _voices_cache = await edge_tts.list_voices()
75
+ return _voices_cache
76
+
77
+
78
+ def split_text(text: str, limit: int) -> list[str]:
79
+ """Split *text* into chunks of at most *limit* characters on sentence boundaries."""
80
+ text = text.strip()
81
+ if not text:
82
+ return []
83
+ if len(text) <= limit:
84
+ return [text]
85
+
86
+ chunks: list[str] = []
87
+ current = ""
88
+ for sentence in _SENTENCE_BOUNDARY.split(text):
89
+ if not sentence:
90
+ continue
91
+ if len(sentence) > limit:
92
+ # A single sentence longer than the limit is hard-split.
93
+ if current:
94
+ chunks.append(current)
95
+ current = ""
96
+ for start in range(0, len(sentence), limit):
97
+ chunks.append(sentence[start : start + limit])
98
+ continue
99
+ if len(current) + len(sentence) <= limit:
100
+ current += sentence
101
+ else:
102
+ chunks.append(current)
103
+ current = sentence
104
+ if current:
105
+ chunks.append(current)
106
+ return chunks
107
+
108
+
109
+ async def synthesize(
110
+ text: str,
111
+ voice: str,
112
+ rate: str,
113
+ volume: str,
114
+ pitch: str,
115
+ out_path: Path,
116
+ on_progress: ProgressCallback | None = None,
117
+ ) -> int:
118
+ """Synthesise *text* into an mp3 file and return the number of audio bytes written."""
119
+ chunks = split_text(text, config.CHUNK_SIZE)
120
+ if not chunks:
121
+ raise ValueError("Text must not be empty")
122
+
123
+ out_path.parent.mkdir(parents=True, exist_ok=True)
124
+ tmp_path = out_path.with_name(f"{out_path.name}.part")
125
+ total = len(chunks)
126
+ written = 0
127
+ try:
128
+ with tmp_path.open("wb") as handle:
129
+ for index, chunk in enumerate(chunks):
130
+ communicate = edge_tts.Communicate(chunk, voice, rate=rate, volume=volume, pitch=pitch)
131
+ async for message in communicate.stream():
132
+ if message["type"] == "audio":
133
+ handle.write(message["data"])
134
+ written += len(message["data"])
135
+ if on_progress is not None:
136
+ await on_progress((index + 1) / total)
137
+ tmp_path.replace(out_path)
138
+ except BaseException:
139
+ tmp_path.unlink(missing_ok=True)
140
+ raise
141
+ return written
@@ -0,0 +1,3 @@
1
+ edge-tts>=7.2.0
2
+ fastapi>=0.115.0
3
+ uvicorn[standard]>=0.30.0