Add application file
Browse files- .dockerignore +12 -0
- Dockerfile +26 -0
- README.md +37 -10
- app/__init__.py +0 -0
- app/__pycache__/__init__.cpython-312.pyc +0 -0
- app/__pycache__/main.cpython-312.pyc +0 -0
- app/__pycache__/space.cpython-312.pyc +0 -0
- app/main.py +136 -0
- app/space.py +3 -0
- requirements-hf.txt +9 -0
- requirements.txt +9 -0
.dockerignore
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/
|
Dockerfile
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
+
PYTHONUNBUFFERED=1 \
|
| 5 |
+
PORT=7860 \
|
| 6 |
+
MODEL_ID=hexgrad/Kokoro-82M-v1.1-zh \
|
| 7 |
+
DEFAULT_VOICE=zf_001
|
| 8 |
+
|
| 9 |
+
WORKDIR /app
|
| 10 |
+
|
| 11 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 12 |
+
build-essential \
|
| 13 |
+
libsndfile1 \
|
| 14 |
+
ffmpeg \
|
| 15 |
+
espeak-ng \
|
| 16 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 17 |
+
|
| 18 |
+
COPY requirements.txt ./requirements.txt
|
| 19 |
+
RUN pip install --no-cache-dir --upgrade pip \
|
| 20 |
+
&& pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu -r requirements.txt
|
| 21 |
+
|
| 22 |
+
COPY . .
|
| 23 |
+
|
| 24 |
+
EXPOSE 7860
|
| 25 |
+
|
| 26 |
+
CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-7860}"]
|
README.md
CHANGED
|
@@ -1,10 +1,37 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kokoro TTS FastAPI for Hugging Face Spaces
|
| 2 |
+
|
| 3 |
+
This project exposes the Hugging Face model `hexgrad/Kokoro-82M-v1.1-zh` through a lightweight FastAPI service designed for Docker-based Hugging Face Spaces.
|
| 4 |
+
|
| 5 |
+
## Run locally
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
python -m venv .venv
|
| 9 |
+
source .venv/bin/activate
|
| 10 |
+
pip install -r requirements.txt
|
| 11 |
+
uvicorn app.main:app --host 0.0.0.0 --port 7860
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
## Run with Docker
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
docker build -t kokoro-tts .
|
| 18 |
+
docker run -p 7860:7860 kokoro-tts
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Hugging Face Spaces
|
| 22 |
+
|
| 23 |
+
Use the Docker-based Space option with this repository.
|
| 24 |
+
|
| 25 |
+
### Notes
|
| 26 |
+
- The app listens on port `7860`, which is the default for Spaces.
|
| 27 |
+
- The first startup downloads the model weights, so the initial boot can take a while.
|
| 28 |
+
- The container uses CPU-only PyTorch and a slim image to keep disk usage lower for free-tier environments.
|
| 29 |
+
|
| 30 |
+
### Example request
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
curl -X POST http://127.0.0.1:7860/tts \
|
| 34 |
+
-H 'Content-Type: application/json' \
|
| 35 |
+
-d '{"text":"Hello world, this is an English voice sample.","speed":1.0}' \
|
| 36 |
+
--output speech.wav
|
| 37 |
+
```
|
app/__init__.py
ADDED
|
File without changes
|
app/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (112 Bytes). View file
|
|
|
app/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (6.4 kB). View file
|
|
|
app/__pycache__/space.cpython-312.pyc
ADDED
|
Binary file (148 Bytes). View file
|
|
|
app/main.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-v1.1-zh")
|
| 27 |
+
MAX_TEXT_CHARS = int(os.getenv("MAX_TEXT_CHARS", "500"))
|
| 28 |
+
DEFAULT_VOICE = os.getenv("DEFAULT_VOICE", "")
|
| 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 |
+
def load(self) -> Any | None:
|
| 44 |
+
if self.pipeline is not None or self.error is not None:
|
| 45 |
+
return self.pipeline
|
| 46 |
+
|
| 47 |
+
if KModel is None or KPipeline is None:
|
| 48 |
+
self.error = "The 'kokoro' package is not installed. Please install requirements first."
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 53 |
+
model = KModel(repo_id=MODEL_ID).to(device).eval()
|
| 54 |
+
self.pipeline = KPipeline(lang_code="a", repo_id=MODEL_ID, model=model)
|
| 55 |
+
return self.pipeline
|
| 56 |
+
except Exception as exc: # pragma: no cover - runtime dependent
|
| 57 |
+
self.error = f"Model could not be loaded: {exc}"
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
def synthesize(self, request: TTSRequest) -> bytes:
|
| 61 |
+
pipeline = self.load()
|
| 62 |
+
if pipeline is None:
|
| 63 |
+
raise RuntimeError(self.error or "The TTS model is unavailable")
|
| 64 |
+
|
| 65 |
+
kwargs: dict[str, Any] = {"speed": float(request.speed)}
|
| 66 |
+
if request.voice or DEFAULT_VOICE:
|
| 67 |
+
kwargs["voice"] = request.voice or DEFAULT_VOICE
|
| 68 |
+
|
| 69 |
+
generator = pipeline(request.text, **kwargs)
|
| 70 |
+
try:
|
| 71 |
+
result = next(generator)
|
| 72 |
+
except StopIteration as exc: # pragma: no cover - runtime dependent
|
| 73 |
+
raise RuntimeError("The model did not produce audio") from exc
|
| 74 |
+
|
| 75 |
+
audio = None
|
| 76 |
+
if isinstance(result, dict):
|
| 77 |
+
audio = result.get("audio")
|
| 78 |
+
else:
|
| 79 |
+
audio = getattr(result, "audio", None)
|
| 80 |
+
|
| 81 |
+
if audio is None:
|
| 82 |
+
raise RuntimeError("The model returned no audio data")
|
| 83 |
+
|
| 84 |
+
if not isinstance(audio, np.ndarray):
|
| 85 |
+
audio = np.array(audio, dtype=np.float32)
|
| 86 |
+
if audio.ndim == 2:
|
| 87 |
+
audio = audio[0]
|
| 88 |
+
|
| 89 |
+
buffer = io.BytesIO()
|
| 90 |
+
sf.write(buffer, audio.astype(np.float32), SAMPLE_RATE, format="WAV")
|
| 91 |
+
return buffer.getvalue()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
tts_service = TTSService()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@app.on_event("startup")
|
| 98 |
+
async def startup_event() -> None:
|
| 99 |
+
tts_service.load()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@app.get("/")
|
| 103 |
+
async def root() -> dict[str, Any]:
|
| 104 |
+
return {
|
| 105 |
+
"message": "Kokoro TTS API is running",
|
| 106 |
+
"model": MODEL_ID,
|
| 107 |
+
"health": "/health",
|
| 108 |
+
"tts": {"method": "POST", "path": "/tts"},
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@app.get("/health")
|
| 113 |
+
async def health() -> dict[str, Any]:
|
| 114 |
+
return {
|
| 115 |
+
"status": "ok",
|
| 116 |
+
"ready": tts_service.pipeline is not None,
|
| 117 |
+
"model": MODEL_ID,
|
| 118 |
+
"error": tts_service.error,
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@app.post("/tts")
|
| 123 |
+
async def tts(request: TTSRequest) -> Response:
|
| 124 |
+
if tts_service.error:
|
| 125 |
+
raise HTTPException(status_code=503, detail=tts_service.error)
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
audio_bytes = tts_service.synthesize(request)
|
| 129 |
+
except Exception as exc: # pragma: no cover - runtime dependent
|
| 130 |
+
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
| 131 |
+
|
| 132 |
+
return Response(
|
| 133 |
+
content=audio_bytes,
|
| 134 |
+
media_type="audio/wav",
|
| 135 |
+
headers={"X-Model": MODEL_ID, "X-Voice": request.voice or DEFAULT_VOICE or "default"},
|
| 136 |
+
)
|
app/space.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.main import app
|
| 2 |
+
|
| 3 |
+
# This module exists so Hugging Face Spaces can import the ASGI app directly.
|
requirements-hf.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.8.2
|
| 7 |
+
misaki[zh]>=0.8.2
|
| 8 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 9 |
+
torch==2.3.1
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.8.2
|
| 7 |
+
misaki[zh]>=0.8.2
|
| 8 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 9 |
+
torch==2.3.1
|