Download runtime/common.py from florianvoss/kokoro-sima: direct link, hf CLI and curl.
- Browser
- Download file 5.99 kB
-
https://huggingface.co/florianvoss/kokoro-sima/resolve/main/runtime/common.py
- Command line
-
hf download hf://florianvoss/kokoro-sima/runtime/common.py
-
curl -L -o common.py https://huggingface.co/florianvoss/kokoro-sima/resolve/main/runtime/common.py
5.99 kB
| """Validated web requests, sentence boundaries and bundled voice metadata.""" | |
| from __future__ import annotations | |
| import math | |
| from pathlib import Path | |
| import re | |
| ROOT = Path(__file__).resolve().parents[1] | |
| MODELS = ROOT / "models" | |
| LANGUAGES = { | |
| "a": "English · American", "b": "English · British", "e": "Spanish", | |
| "f": "French", "h": "Hindi", "i": "Italian", "j": "Japanese", | |
| "p": "Portuguese · Brazilian", "z": "Chinese · Mandarin", | |
| } | |
| SAMPLES = { | |
| "a": "The morning sunlight spilled across the kitchen table. Can you hear how naturally this voice flows? Let's try another sentence!", | |
| "b": "Good morning! The sunlight is coming through the window. Shall we try another voice?", | |
| "e": "¡Hola! Esta es una demostración de voz. ¿Cómo estás hoy?", | |
| "f": "Bonjour ! Voici une démonstration de synthèse vocale. Comment allez-vous ?", | |
| "h": "नमस्ते! यह आवाज़ का एक उदाहरण है. आप कैसे हैं?", | |
| "i": "Ciao! Questa è una dimostrazione della voce. Come stai oggi?", | |
| "j": "こんにちは!これは音声合成のデモです。今日はいい天気ですね。", | |
| "p": "Olá! Esta é uma demonstração de voz. Como você está hoje?", | |
| "z": "你好!这是语音合成演示。今天的天气怎么样?", | |
| } | |
| def options(): | |
| voices = [] | |
| for path in sorted((MODELS / "voices").glob("*.npy")): | |
| name = path.stem | |
| if len(name) < 4 or name[0] not in LANGUAGES: | |
| continue | |
| voices.append({"id": name, "language": name[0], | |
| "name": name[3:].replace("_", " ").title(), | |
| "gender": "Female" if name[1] == "f" else "Male"}) | |
| return {"languages": [{"id": k, "name": v, "sample": SAMPLES[k]} for k, v in LANGUAGES.items()], | |
| "voices": voices, "sample_rate": 24000, "max_characters": 5000, | |
| "defaults": {"language": "a", "voice": "af_heart", "speed": 1.0, "seed": 1234}} | |
| def split_sentences(text): | |
| """Split punctuation runs, preserving decimal points and common initials.""" | |
| sentences, start, i = [], 0, 0 | |
| closing = '\"\'”’»)]}' | |
| abbreviations = {"mr", "mrs", "ms", "dr", "prof", "sr", "jr", "st", "vs", "e.g", "i.e"} | |
| while i < len(text): | |
| mark = text[i] | |
| if mark not in ".?!。?!": | |
| i += 1 | |
| continue | |
| if mark == ".": | |
| if i and i + 1 < len(text) and text[i - 1].isdigit() and text[i + 1].isdigit(): | |
| i += 1 | |
| continue | |
| word = re.search(r"([A-Za-z.]+)$", text[start:i]) | |
| value = word.group(1).lower() if word else "" | |
| following = text[i + 1:].lstrip() | |
| if following and (value in abbreviations or (len(value) == 1 and value.isalpha()) | |
| or (i + 2 < len(text) and text[i + 1].isalpha() and text[i + 2] == ".")): | |
| i += 1 | |
| continue | |
| end = i + 1 | |
| while end < len(text) and text[end] in ".?!。?!" + closing: | |
| end += 1 | |
| sentence = text[start:end].strip() | |
| if sentence and any(c.isalnum() for c in sentence): | |
| sentences.append(sentence) | |
| start, i = end, end | |
| tail = text[start:].strip() | |
| if tail and any(c.isalnum() for c in tail): | |
| sentences.append(tail) | |
| return sentences | |
| def validate_request(data): | |
| if not isinstance(data, dict): | |
| raise ValueError("Expected a JSON object") | |
| text = data.get("text", "") | |
| if not isinstance(text, str) or not text.strip(): | |
| raise ValueError("Enter some text to generate speech.") | |
| if len(text) > 5000: | |
| raise ValueError("Use at most 5,000 characters per request.") | |
| language, voice = data.get("language", "a"), data.get("voice", "af_heart") | |
| if not isinstance(language, str) or language not in LANGUAGES: | |
| raise ValueError("Select a supported language.") | |
| if not isinstance(voice, str) or voice not in {v["id"] for v in options()["voices"]} or voice[0] != language: | |
| raise ValueError("Select a voice for the chosen language.") | |
| speed, seed = data.get("speed", 1.0), data.get("seed", 1234) | |
| if isinstance(speed, bool) or not isinstance(speed, (int, float)) or not math.isfinite(speed) or not 0.5 <= speed <= 2.0: | |
| raise ValueError("Speed must be between 0.5 and 2.0.") | |
| if isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed <= 2**32 - 1: | |
| raise ValueError("Seed must be an integer from 0 to 4294967295.") | |
| chunks = split_sentences(text.strip()) | |
| if not chunks: | |
| raise ValueError("Enter text containing words or numbers.") | |
| return {"text": text.strip(), "language": language, "voice": voice, | |
| "speed": float(speed), "seed": seed, "sentences": chunks} | |
| def validate_speech_request(data): | |
| """Supported OpenAI speech request fields; raw PCM is signed 16-bit LE.""" | |
| if not isinstance(data, dict): | |
| raise ValueError("Expected a JSON object") | |
| allowed = {"model", "input", "voice", "response_format", "speed", "language", "seed", "stream_format"} | |
| unknown = set(data) - allowed | |
| if unknown: | |
| raise ValueError("Unsupported fields: " + ", ".join(sorted(unknown))) | |
| if data.get("model") not in ("kokoro", "kokoro-sima"): | |
| raise ValueError("model must be 'kokoro' or 'kokoro-sima'") | |
| output = data.get("response_format", "wav") | |
| if output not in ("wav", "pcm"): | |
| raise ValueError("response_format must be 'wav' or 'pcm'") | |
| if data.get("stream_format", "audio") != "audio": | |
| raise ValueError("Only stream_format='audio' is supported") | |
| voice = data.get("voice", "af_heart") | |
| language = data.get("language", voice[:1] if isinstance(voice, str) else "a") | |
| request = validate_request({"text": data.get("input"), "voice": voice, "language": language, | |
| "speed": data.get("speed", 1.0), "seed": data.get("seed", 1234)}) | |
| return request, output | |