Spaces:
Running
Running
Download scripts/export_voice_bins.py from walydevelopers/pocket-tts-web: direct link, hf CLI and curl.
- Browser
- Download file 2.17 kB
-
https://huggingface.co/spaces/walydevelopers/pocket-tts-web/resolve/main/scripts/export_voice_bins.py
- Command line
-
hf download hf://spaces/walydevelopers/pocket-tts-web/scripts/export_voice_bins.py
-
curl -L -o export_voice_bins.py https://huggingface.co/spaces/walydevelopers/pocket-tts-web/resolve/main/scripts/export_voice_bins.py
2.17 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import struct | |
| from pathlib import Path | |
| from huggingface_hub import hf_hub_download | |
| from safetensors import safe_open | |
| HF_REPO_ID = "kyutai/pocket-tts" | |
| DTYPE_CODES = { | |
| "float32": 0, | |
| "int64": 1, | |
| "bool": 2, | |
| } | |
| def encode_tensor(handle, key: str) -> bytes: | |
| tensor = handle.get_tensor(key) | |
| tensor_bytes = tensor.tobytes(order="C") | |
| key_bytes = key.encode("utf-8") | |
| payload = bytearray() | |
| payload += struct.pack("<H", len(key_bytes)) | |
| payload += key_bytes | |
| payload += struct.pack("<B", DTYPE_CODES[str(tensor.dtype)]) | |
| payload += struct.pack("<B", len(tensor.shape)) | |
| for dim in tensor.shape: | |
| payload += struct.pack("<I", dim) | |
| payload += struct.pack("<I", len(tensor_bytes)) | |
| payload += tensor_bytes | |
| return bytes(payload) | |
| def encode_voice(language: str, voice: str) -> bytes: | |
| source = hf_hub_download( | |
| repo_id=HF_REPO_ID, | |
| filename=f"languages/{language}/embeddings/{voice}.safetensors", | |
| token=True, | |
| ) | |
| with safe_open(source, framework="np") as handle: | |
| keys = sorted(handle.keys()) | |
| voice_bytes = bytearray() | |
| voice_name = voice.encode("utf-8") | |
| voice_bytes += struct.pack("<H", len(voice_name)) | |
| voice_bytes += voice_name | |
| voice_bytes += struct.pack("<H", len(keys)) | |
| for key in keys: | |
| voice_bytes += encode_tensor(handle, key) | |
| return bytes(voice_bytes) | |
| def write_language_bundle(bundle_dir: Path) -> None: | |
| metadata = json.loads((bundle_dir / "bundle.json").read_text()) | |
| voices = metadata["predefined_voices"] | |
| output = bytearray() | |
| output += b"PTVB1" | |
| output += struct.pack("<I", len(voices)) | |
| for voice in voices: | |
| output += encode_voice(bundle_dir.name, voice) | |
| (bundle_dir / "voices.bin").write_bytes(output) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("bundle_dirs", nargs="+", type=Path) | |
| args = parser.parse_args() | |
| for bundle_dir in args.bundle_dirs: | |
| write_language_bundle(bundle_dir) | |
| if __name__ == "__main__": | |
| main() | |