Spaces:
Running on Zero

File size: 6,269 Bytes
8fdcf1e
e7352e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fdcf1e
 
 
 
 
e7352e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fdcf1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7352e3
 
8fdcf1e
e7352e3
 
 
 
 
974346c
 
 
 
 
 
 
 
 
e7352e3
 
 
 
 
 
 
 
 
 
8fdcf1e
e7352e3
 
 
 
 
 
 
974346c
 
e7352e3
 
974346c
e7352e3
8fdcf1e
e7352e3
974346c
e7352e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""Ohùn voice API. Runs on a free Hugging Face Space (Gradio SDK; inference on CPU), mounted at /api.

POST /v1/tts      {"text": "...", "voice": "yo-female-1", "speed": 1.0}  -> audio/wav
GET  /v1/voices   list of voices and whether each is live
GET  /health

Auth: header `Authorization: Bearer <key>`; keys in env OHUN_API_KEYS (comma separated).
Requests without a key are allowed for the public demo, capped at DEMO_MAX_CHARS characters.
"""
from __future__ import annotations

import os
import threading
import time
from collections import defaultdict, deque

from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import Response
from pydantic import BaseModel, Field

from engines import KokoroVoice, PiperPhonemeVoice, to_wav_bytes

DEMO_MAX_CHARS = int(os.getenv("DEMO_MAX_CHARS", "300"))
PAID_MAX_CHARS = int(os.getenv("PAID_MAX_CHARS", "5000"))
DEMO_PER_MIN = int(os.getenv("DEMO_PER_MIN", "6"))
API_KEYS = {k.strip() for k in os.getenv("OHUN_API_KEYS", "").split(",") if k.strip()}
YO_REPO = os.getenv("OHUN_YO_REPO", "")  # e.g. aladewealth/ohun-yoruba on Hugging Face

VOICES = {
    "yo-female-1": {"lang": "yo", "label": "Yoruba · Adùnní (female)", "engine": "yo", "speaker": 0},
    "yo-male-1":   {"lang": "yo", "label": "Yoruba · Tọ́lá (male)", "engine": "yo", "speaker": None},
    "es-female-1": {"lang": "es", "label": "Spanish · Dora (female)", "engine": "es", "kokoro": "ef_dora"},
    "es-male-1":   {"lang": "es", "label": "Spanish · Alex (male)", "engine": "es", "kokoro": "em_alex"},
    "fr-female-1": {"lang": "fr", "label": "French · Siwis (female)", "engine": "fr", "kokoro": "ff_siwis"},
    "en-female-1": {"lang": "en", "label": "English · Heart (female)", "engine": "en", "kokoro": "af_heart"},
}

_engines: dict = {}
_lock = threading.Lock()


def _engine(name: str):
    with _lock:
        if name in _engines:
            return _engines[name]
        if name == "yo":
            onnx, cfg = "models/ohun_yo.onnx", "models/ohun_yo.onnx.json"
            if not os.path.exists(onnx) and YO_REPO:
                from huggingface_hub import hf_hub_download
                try:
                    onnx = hf_hub_download(YO_REPO, "ohun_yo.onnx")
                    cfg = hf_hub_download(YO_REPO, "ohun_yo.onnx.json")
                except Exception:  # weights not published yet
                    return None
            if not os.path.exists(onnx):
                return None
            eng = PiperPhonemeVoice(onnx, cfg)
            # pick the first male speaker id for the male voice
            males = [i for s, i in sorted(eng.speakers.items(), key=lambda x: x[1]) if s.startswith("m")]
            females = [i for s, i in sorted(eng.speakers.items(), key=lambda x: x[1]) if s.startswith("f")]
            VOICES["yo-female-1"]["speaker"] = int(os.getenv("YO_FEMALE_SID", females[0] if females else 0))
            VOICES["yo-male-1"]["speaker"] = int(os.getenv("YO_MALE_SID", males[0] if males else 0))
        else:
            eng = KokoroVoice(name)
        _engines[name] = eng
        return eng


app = FastAPI(title="Ohùn Voice API", version="0.1.0")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
_hits: dict[str, deque] = defaultdict(deque)


class TTSRequest(BaseModel):
    text: str = Field(..., min_length=1)
    voice: str = "yo-female-1"
    speed: float = Field(1.0, ge=0.5, le=2.0)


@app.get("/health")
def health():
    return {"ok": True}


_yo_check = {"t": 0.0, "live": False}


def _yo_live() -> bool:
    """True once Yoruba weights exist locally or in the model repo (checked at most every 10 min)."""
    if os.path.exists("models/ohun_yo.onnx"):
        return True
    if not YO_REPO:
        return False
    if time.time() - _yo_check["t"] > 600:
        try:
            from huggingface_hub import file_exists
            _yo_check["live"] = file_exists(YO_REPO, "ohun_yo.onnx")
        except Exception:
            _yo_check["live"] = False
        _yo_check["t"] = time.time()
    return _yo_check["live"]


@app.get("/v1/voices")
def voices():
    yo_live = _yo_live()
    return [{"id": k, "language": v["lang"], "label": v["label"],
             "live": yo_live if v["engine"] == "yo" else True} for k, v in VOICES.items()]


@app.post("/v1/tts")
async def tts(request: Request):
    """Body is JSON. Content-Type text/plain is accepted too, so browsers can call it without a CORS preflight."""
    import json as _json
    from pydantic import ValidationError
    try:
        req = TTSRequest(**_json.loads(await request.body() or b"{}"))
    except (ValueError, ValidationError) as e:
        raise HTTPException(422, str(e)[:300])
    authorization = request.headers.get("authorization")
    key = (authorization or "").removeprefix("Bearer ").strip()
    paid = key in API_KEYS
    if key and not paid:
        raise HTTPException(401, "invalid API key")
    if not paid:
        ip = request.headers.get("x-forwarded-for", request.client.host if request.client else "?").split(",")[0]
        q, now = _hits[ip], time.time()
        while q and now - q[0] > 60:
            q.popleft()
        if len(q) >= DEMO_PER_MIN:
            raise HTTPException(429, "demo limit reached (6 requests a minute without an API key)")
        q.append(now)
    limit = PAID_MAX_CHARS if paid else DEMO_MAX_CHARS
    if len(req.text) > limit:
        raise HTTPException(413, f"text over {limit} characters" + ("" if paid else " (demo limit)"))
    v = VOICES.get(req.voice)
    if not v:
        raise HTTPException(404, "unknown voice")
    from starlette.concurrency import run_in_threadpool as _rt
    eng = await _rt(_engine, v["engine"])
    if eng is None:
        raise HTTPException(503, "this voice is still training")
    from starlette.concurrency import run_in_threadpool
    if v["engine"] == "yo":
        sr, audio = await run_in_threadpool(eng.synthesize, req.text, speaker=v["speaker"] if v["speaker"] is not None else 0, speed=req.speed)
    else:
        sr, audio = await run_in_threadpool(eng.synthesize, req.text, voice=v["kokoro"], speed=req.speed)
    return Response(to_wav_bytes(sr, audio), media_type="audio/wav")