kjbytes commited on
Commit
a2d2bc0
·
1 Parent(s): a069204
.dockerignore DELETED
@@ -1,12 +0,0 @@
1
- __pycache__/
2
- *.py[cod]
3
- *.pyo
4
- *.pyd
5
- *.log
6
- .git/
7
- .gitignore
8
- .venv/
9
- venv/
10
- .env
11
- .cache/
12
- .pytest_cache/
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitattributes DELETED
@@ -1,35 +0,0 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile CHANGED
@@ -1,44 +1,18 @@
1
- FROM python:3.10-slim
2
 
3
- ENV PYTHONDONTWRITEBYTECODE=1 \
4
- PYTHONUNBUFFERED=1 \
5
- PORT=7860 \
6
- MODEL_ID=hexgrad/Kokoro-82M \
7
- DEFAULT_VOICE=af_heart \
8
- HF_HOME=/app/.cache/huggingface \
9
- TRANSFORMERS_CACHE=/app/.cache/huggingface
10
-
11
- WORKDIR /app
12
-
13
- RUN apt-get update && apt-get install -y --no-install-recommends \
14
- build-essential \
15
- libsndfile1 \
16
- ffmpeg \
17
- espeak-ng \
18
  && rm -rf /var/lib/apt/lists/*
19
 
20
- COPY requirements.txt ./requirements.txt
21
- RUN pip install --no-cache-dir --upgrade pip \
22
- && pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu -r requirements.txt
 
 
23
 
24
- COPY . .
 
25
 
26
- RUN mkdir -p /app/.cache/huggingface \
27
- && python - <<'PY'
28
- import os
29
- from huggingface_hub import snapshot_download
30
- repo = os.environ['MODEL_ID']
31
- cache_dir = '/app/.cache/huggingface'
32
- path = snapshot_download(
33
- repo_id=repo,
34
- repo_type='model',
35
- cache_dir=cache_dir,
36
- allow_patterns=['*.json', '*.txt', '*.pt', '*.bin', '*.safetensors', 'tokenizer*', 'voices/*'],
37
- local_dir_use_symlinks=False,
38
- )
39
- print(path)
40
- PY
41
 
42
  EXPOSE 7860
43
-
44
- CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-7860}"]
 
1
+ FROM python:3.11-slim
2
 
3
+ RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg git \
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  && rm -rf /var/lib/apt/lists/*
5
 
6
+ # HF Spaces runs as uid 1000; HF_HOME must be writable for model downloads.
7
+ RUN useradd -m -u 1000 user
8
+ ENV HOME=/home/user HF_HOME=/home/user/.cache/huggingface OUT_DIR=/home/user/audio
9
+ USER user
10
+ WORKDIR /home/user/app
11
 
12
+ COPY --chown=user requirements.txt .
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
 
15
+ COPY --chown=user app.py .
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  EXPOSE 7860
18
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
README.md CHANGED
@@ -1,48 +1,36 @@
1
  ---
2
- title: Kokoro TTS FastAPI
3
- emoji: 🔊
4
- colorFrom: blue
5
  colorTo: purple
6
  sdk: docker
7
- sdk_version: "1.0"
8
- app_file: app/main.py
9
  pinned: false
10
  ---
11
 
12
- # Kokoro TTS FastAPI for Hugging Face Spaces
13
 
14
- This project exposes the Hugging Face model `hexgrad/Kokoro-82M` through a lightweight FastAPI service designed for Docker-based Hugging Face Spaces.
15
 
16
- ## Run locally
17
 
18
- ```bash
19
- python -m venv .venv
20
- source .venv/bin/activate
21
- pip install -r requirements.txt
22
- uvicorn app.main:app --host 0.0.0.0 --port 7860
23
- ```
24
 
25
- ## Run with Docker
26
 
27
  ```bash
28
- docker build -t kokoro-tts .
29
- docker run -p 7860:7860 kokoro-tts
 
 
30
  ```
31
 
32
- ## Hugging Face Spaces
33
-
34
- Use the Docker-based Space option with this repository.
35
 
36
- ### Notes
37
- - The app listens on port `7860`, which is the default for Spaces.
38
- - The first startup downloads the model weights, so the initial boot can take a while.
39
- - The container uses CPU-only PyTorch and a slim image to keep disk usage lower for free-tier environments.
40
 
41
- ### Example request
42
 
43
- ```bash
44
- curl -X POST http://127.0.0.1:7860/tts \
45
- -H 'Content-Type: application/json' \
46
- -d '{"text":"Hello world, this is an English voice sample.","speed":1.0}' \
47
- --output speech.wav
48
- ```
 
1
  ---
2
+ title: Chatterbox TTS API
3
+ emoji: 🗣️
4
+ colorFrom: indigo
5
  colorTo: purple
6
  sdk: docker
7
+ app_port: 7860
 
8
  pinned: false
9
  ---
10
 
11
+ # Chatterbox TTS API
12
 
13
+ CPU-only FastAPI wrapper around [ResembleAI/chatterbox](https://huggingface.co/ResembleAI/chatterbox) multilingual TTS.
14
 
15
+ ## Setup
16
 
17
+ Space → Settings → Variables and secrets → add secret `API_KEY`.
 
 
 
 
 
18
 
19
+ ## Usage
20
 
21
  ```bash
22
+ curl -X POST https://<user>-<space>.hf.space/tts \
23
+ -H "x-api-key: $API_KEY" -H "content-type: application/json" \
24
+ -d '{"text": "Hello there", "lang": "en"}'
25
+ # {"url": "https://<user>-<space>.hf.space/audio/<uuid>.wav", "lang": "en"}
26
  ```
27
 
28
+ Then `curl -O <url>` — the download endpoint is public (unguessable uuid).
 
 
29
 
30
+ Params: `text` (required, ≤1000 chars), `lang` (default `en`), `exaggeration` (0–2), `cfg_weight` (0–1).
31
+ Supported langs: ar, da, de, el, en, es, fi, fr, he, hi, it, ja, ko, ms, nl, no, pl, pt, ru, sv, sw, tr, zh.
 
 
32
 
33
+ ## Notes
34
 
35
+ - First request downloads the model (~1–2 min); CPU synthesis takes roughly 10–40s per sentence. Free Spaces sleep when idle, so the first call after a wake is slow.
36
+ - Audio lives on the ephemeral container disk — links die on restart. Add S3/Blob upload if you need durable URLs.
 
 
 
 
__pycache__/app.cpython-312.pyc ADDED
Binary file (4.06 kB). View file
 
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+
4
+ from fastapi import Depends, FastAPI, HTTPException, Header, Request
5
+ from fastapi.responses import FileResponse
6
+ from pydantic import BaseModel, Field
7
+
8
+ API_KEY = os.environ["API_KEY"]
9
+ OUT_DIR = os.environ.get("OUT_DIR", "/tmp/audio")
10
+ os.makedirs(OUT_DIR, exist_ok=True)
11
+
12
+ app = FastAPI(title="Chatterbox TTS")
13
+ _model = None
14
+
15
+
16
+ def auth(x_api_key: str = Header(None)):
17
+ if x_api_key != API_KEY:
18
+ raise HTTPException(401, "bad api key")
19
+
20
+
21
+ def model():
22
+ # ponytail: lazy singleton so the Space boots fast and healthchecks pass.
23
+ # Single uvicorn worker, so no lock needed; add one if we ever scale up.
24
+ global _model
25
+ if _model is None:
26
+ from chatterbox.mtl_tts import ChatterboxMultilingualTTS
27
+
28
+ _model = ChatterboxMultilingualTTS.from_pretrained(device="cpu")
29
+ return _model
30
+
31
+
32
+ class TTSRequest(BaseModel):
33
+ text: str = Field(min_length=1, max_length=1000)
34
+ lang: str = Field("en", min_length=2, max_length=5)
35
+ exaggeration: float = Field(0.5, ge=0.0, le=2.0)
36
+ cfg_weight: float = Field(0.5, ge=0.0, le=1.0)
37
+
38
+
39
+ @app.post("/tts", dependencies=[Depends(auth)])
40
+ def tts(req: TTSRequest, request: Request):
41
+ import torchaudio # ponytail: lazy so the module imports without torch installed
42
+
43
+ m = model()
44
+ lang = req.lang.lower()
45
+ if lang not in m.get_supported_languages():
46
+ raise HTTPException(400, f"unsupported lang: {lang}")
47
+
48
+ wav = m.generate(
49
+ req.text,
50
+ language_id=lang,
51
+ exaggeration=req.exaggeration,
52
+ cfg_weight=req.cfg_weight,
53
+ )
54
+ name = f"{uuid.uuid4().hex}.wav"
55
+ torchaudio.save(os.path.join(OUT_DIR, name), wav, m.sr)
56
+ return {"url": str(request.base_url) + f"audio/{name}", "lang": lang}
57
+
58
+
59
+ @app.get("/audio/{name}")
60
+ def download(name: str):
61
+ # ponytail: uuid names only; reject anything else instead of path-joining it.
62
+ if len(name) != 36 or not name.endswith(".wav") or not name[:32].isalnum():
63
+ raise HTTPException(400, "bad name")
64
+ path = os.path.join(OUT_DIR, name)
65
+ if not os.path.isfile(path):
66
+ raise HTTPException(404, "unknown file")
67
+ return FileResponse(path, media_type="audio/wav", filename=name)
68
+
69
+
70
+ @app.get("/")
71
+ def health():
72
+ return {"ok": True, "loaded": _model is not None}
app/__init__.py DELETED
File without changes
app/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (112 Bytes)
 
app/__pycache__/main.cpython-312.pyc DELETED
Binary file (6.92 kB)
 
app/__pycache__/space.cpython-312.pyc DELETED
Binary file (148 Bytes)
 
app/main.py DELETED
@@ -1,146 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import io
4
- import os
5
- from typing import Any
6
-
7
- import numpy as np
8
- import soundfile as sf
9
- import torch
10
- from fastapi import FastAPI, HTTPException
11
- from fastapi.responses import Response
12
- from pydantic import BaseModel, Field
13
-
14
- try:
15
- from kokoro import KModel, KPipeline
16
- except ImportError: # pragma: no cover - dependency may be absent at import time
17
- KModel = None
18
- KPipeline = None
19
-
20
- app = FastAPI(
21
- title="Kokoro TTS API",
22
- description="A small FastAPI service for the Hugging Face Kokoro text-to-speech model.",
23
- version="0.1.0",
24
- )
25
-
26
- MODEL_ID = os.getenv("MODEL_ID", "hexgrad/Kokoro-82M")
27
- MAX_TEXT_CHARS = int(os.getenv("MAX_TEXT_CHARS", "500"))
28
- DEFAULT_VOICE = os.getenv("DEFAULT_VOICE", "af_heart")
29
- SAMPLE_RATE = 24000
30
-
31
-
32
- class TTSRequest(BaseModel):
33
- text: str = Field(..., min_length=1, max_length=MAX_TEXT_CHARS)
34
- voice: str | None = None
35
- speed: float = 1.0
36
-
37
-
38
- class TTSService:
39
- def __init__(self) -> None:
40
- self.pipeline: Any | None = None
41
- self.error: str | None = None
42
-
43
- @staticmethod
44
- def normalize_voice(voice: str | None) -> str | None:
45
- candidate = (voice or "").strip()
46
- if not candidate or candidate.lower() == "string":
47
- candidate = (DEFAULT_VOICE or "af_heart").strip()
48
- if not candidate or candidate.lower() == "string":
49
- return "af_heart"
50
- return candidate
51
-
52
- def load(self) -> Any | None:
53
- if self.pipeline is not None or self.error is not None:
54
- return self.pipeline
55
-
56
- if KModel is None or KPipeline is None:
57
- self.error = "The 'kokoro' package is not installed. Please install requirements first."
58
- return None
59
-
60
- try:
61
- device = "cuda" if torch.cuda.is_available() else "cpu"
62
- model = KModel(repo_id=MODEL_ID).to(device).eval()
63
- self.pipeline = KPipeline(lang_code="a", repo_id=MODEL_ID, model=model)
64
- return self.pipeline
65
- except Exception as exc: # pragma: no cover - runtime dependent
66
- self.error = f"Model could not be loaded: {exc}"
67
- return None
68
-
69
- def synthesize(self, request: TTSRequest) -> bytes:
70
- pipeline = self.load()
71
- if pipeline is None:
72
- raise RuntimeError(self.error or "The TTS model is unavailable")
73
-
74
- kwargs: dict[str, Any] = {"speed": float(request.speed)}
75
- voice = self.normalize_voice(request.voice)
76
- if voice:
77
- kwargs["voice"] = voice
78
-
79
- generator = pipeline(request.text, **kwargs)
80
- try:
81
- result = next(generator)
82
- except StopIteration as exc: # pragma: no cover - runtime dependent
83
- raise RuntimeError("The model did not produce audio") from exc
84
-
85
- audio = None
86
- if isinstance(result, dict):
87
- audio = result.get("audio")
88
- else:
89
- audio = getattr(result, "audio", None)
90
-
91
- if audio is None:
92
- raise RuntimeError("The model returned no audio data")
93
-
94
- if not isinstance(audio, np.ndarray):
95
- audio = np.array(audio, dtype=np.float32)
96
- if audio.ndim == 2:
97
- audio = audio[0]
98
-
99
- buffer = io.BytesIO()
100
- sf.write(buffer, audio.astype(np.float32), SAMPLE_RATE, format="WAV")
101
- return buffer.getvalue()
102
-
103
-
104
- tts_service = TTSService()
105
-
106
-
107
- @app.on_event("startup")
108
- async def startup_event() -> None:
109
- tts_service.load()
110
-
111
-
112
- @app.get("/")
113
- async def root() -> dict[str, Any]:
114
- return {
115
- "message": "Kokoro TTS API is running",
116
- "model": MODEL_ID,
117
- "health": "/health",
118
- "tts": {"method": "POST", "path": "/tts"},
119
- }
120
-
121
-
122
- @app.get("/health")
123
- async def health() -> dict[str, Any]:
124
- return {
125
- "status": "ok",
126
- "ready": tts_service.pipeline is not None,
127
- "model": MODEL_ID,
128
- "error": tts_service.error,
129
- }
130
-
131
-
132
- @app.post("/tts")
133
- async def tts(request: TTSRequest) -> Response:
134
- if tts_service.error:
135
- raise HTTPException(status_code=503, detail=tts_service.error)
136
-
137
- try:
138
- audio_bytes = tts_service.synthesize(request)
139
- except Exception as exc: # pragma: no cover - runtime dependent
140
- raise HTTPException(status_code=500, detail=str(exc)) from exc
141
-
142
- return Response(
143
- content=audio_bytes,
144
- media_type="audio/wav",
145
- headers={"X-Model": MODEL_ID, "X-Voice": request.voice or DEFAULT_VOICE or "default"},
146
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/space.py DELETED
@@ -1,3 +0,0 @@
1
- from app.main import app
2
-
3
- # This module exists so Hugging Face Spaces can import the ASGI app directly.
 
 
 
 
requirements-hf.txt DELETED
@@ -1,9 +0,0 @@
1
- fastapi==0.115.0
2
- uvicorn[standard]==0.30.6
3
- numpy>=1.26.0
4
- soundfile>=0.12.0
5
- pydantic>=2.7.0
6
- kokoro==0.9.4
7
- misaki[zh]==0.9.4
8
- --extra-index-url https://download.pytorch.org/whl/cpu
9
- torch==2.4.1+cpu
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,9 +1,6 @@
1
- fastapi==0.115.0
2
- uvicorn[standard]==0.30.6
3
- numpy>=1.26.0
4
- soundfile>=0.12.0
5
- pydantic>=2.7.0
6
- kokoro==0.9.4
7
- misaki[zh]==0.9.4
8
  --extra-index-url https://download.pytorch.org/whl/cpu
9
- torch==2.4.1+cpu
 
 
 
 
 
 
 
 
 
 
 
 
1
  --extra-index-url https://download.pytorch.org/whl/cpu
2
+ torch==2.6.0+cpu
3
+ torchaudio==2.6.0+cpu
4
+ fastapi==0.115.6
5
+ uvicorn[standard]==0.34.0
6
+ chatterbox-tts==0.1.4
test_download_name.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runnable check for the /audio/{name} path-traversal guard: python test_download_name.py"""
2
+ import os
3
+ import uuid
4
+
5
+ os.environ.setdefault("API_KEY", "test")
6
+ os.environ.setdefault("OUT_DIR", "/tmp/audio-test")
7
+
8
+ from fastapi import HTTPException
9
+
10
+ from app import download
11
+
12
+
13
+ def rejected(name):
14
+ try:
15
+ download(name)
16
+ except HTTPException as e:
17
+ return e.status_code == 400
18
+ return False
19
+
20
+
21
+ # a real uuid name passes validation (it 404s for a missing file, not 400)
22
+ good = f"{uuid.uuid4().hex}.wav"
23
+ assert not rejected(good), good
24
+
25
+ for bad in [
26
+ "../../etc/passwd",
27
+ "../" * 4 + "x.wav",
28
+ "/etc/passwd",
29
+ "short.wav",
30
+ f"{uuid.uuid4().hex}.mp3",
31
+ f"{'../a' * 8}.wav", # 36 chars, but not alnum
32
+ ]:
33
+ assert rejected(bad), bad
34
+
35
+ print("ok")