59 lines
2.3 KiB
Python
59 lines
2.3 KiB
Python
"""One request, local verified weights, CPU only, no runtime downloads."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
|
|
|
|
def text_chunks(text, maximum=60):
|
|
"""Bound Chinese phoneme length before Kokoro's 510-phoneme limit."""
|
|
remaining = text.strip()
|
|
while remaining:
|
|
prefix = remaining[:maximum]
|
|
endings = list(re.finditer(r'[。!?;!?;\n]', prefix))
|
|
end = endings[-1].end() if endings else len(prefix)
|
|
value = remaining[:end].strip()
|
|
remaining = remaining[end:].lstrip()
|
|
if value:
|
|
yield value
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--request', required=True, type=Path)
|
|
parser.add_argument('--output', required=True, type=Path)
|
|
parser.add_argument('--model-dir', required=True, type=Path)
|
|
args = parser.parse_args()
|
|
data = json.loads(args.request.read_text(encoding='utf-8'))
|
|
voice = data['voice']
|
|
if voice not in {'zf_xiaobei', 'zm_yunxi'}:
|
|
raise ValueError('Invalid voice')
|
|
os.environ['CUDA_VISIBLE_DEVICES'] = ''
|
|
import numpy as np
|
|
import soundfile as sf
|
|
import torch
|
|
from kokoro import KModel, KPipeline
|
|
torch.set_num_threads(4)
|
|
model = KModel(repo_id='hexgrad/Kokoro-82M',
|
|
config=str(args.model_dir / 'config.json'),
|
|
model=str(args.model_dir / 'kokoro-v1_0.pth')).to('cpu').eval()
|
|
pipeline = KPipeline(lang_code='z', repo_id='hexgrad/Kokoro-82M', model=model, device='cpu')
|
|
voice_tensor = torch.load(args.model_dir / 'voices' / (voice + '.pt'),
|
|
map_location='cpu', weights_only=True)
|
|
frames = []
|
|
for chunk in text_chunks(data['input']):
|
|
for result in pipeline(chunk, voice=voice_tensor, speed=float(data['speed']), split_pattern=None):
|
|
if result.audio is not None:
|
|
audio = result.audio.detach().cpu().numpy().astype(np.float32)
|
|
if not np.isfinite(audio).all():
|
|
raise ValueError('Invalid generated audio')
|
|
frames.append(audio)
|
|
if not frames:
|
|
raise ValueError('No speech was generated')
|
|
sf.write(str(args.output), np.concatenate(frames), 24000, subtype='PCM_16', format='WAV')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|