Files
Athena-Deck/omnivoice_worker.py
T

68 lines
4.0 KiB
Python

"""Offline OmniVoice worker; persistent weights, per-request reference state."""
import contextlib,json,sys
from pathlib import Path
def write_result(root,name,result):
temporary=root/(name+'.tmp');temporary.write_text(json.dumps(result));temporary.replace(root/name)
def load(root):
import torch
from omnivoice import OmniVoice
return OmniVoice.from_pretrained(str(root/'model'),device_map='cuda:0',dtype=torch.float16,local_files_only=True,load_asr=False)
def generate(model,request,root):
import torch,soundfile as sf
from omnivoice import OmniVoiceGenerationConfig
torch.manual_seed(request['seed'])
kwargs=dict(text=request['text'],language=request.get('language') or None,instruct=request.get('instruct') or None,speed=request.get('speed',1.0),generation_config=OmniVoiceGenerationConfig(num_step=request['steps'],guidance_scale=request['cfg'],denoise=request.get('denoise',True),preprocess_prompt=request.get('preprocess_prompt',True),postprocess_output=request.get('postprocess_output',True)))
if request.get('duration'):kwargs['duration']=request['duration']
if (root/'reference.wav').exists():kwargs.update(ref_audio=str(root/'reference.wav'),ref_text=request['reference_text'])
wave=model.generate(**kwargs)[0];rate=model.sampling_rate
sf.write(root/'result.wav',wave,rate,subtype='PCM_16')
return dict(ok=True,sample_rate=rate,duration=len(wave)/rate)
def failure(exc,phase):
oom='outofmemory' in type(exc).__name__.lower() or 'out of memory' in str(exc).lower()
return dict(ok=False,error='GPU-Speicher reicht nicht aus. Andere Deck-Modelle entladen oder andere GPU wählen.' if oom else 'OmniVoice: '+phase+' fehlgeschlagen ('+type(exc).__name__+'). Laufzeit und Komponenten prüfen.')
def prepare_reference(root,rate=24000):
# Use the installed OmniVoice preprocessing, before Deck's external CPU ASR.
# Supplying ASR text to generate() otherwise disables OmniVoice's own trimming.
import numpy as np
import soundfile as sf
from omnivoice.utils.audio import trim_long_audio,remove_silence,load_audio
audio=load_audio(str(root/'reference.wav'),rate);original=audio.shape[-1]/rate
rms=float(np.sqrt(np.mean(audio**2)))
if 0<rms<.1:audio=audio*.1/rms
audio=trim_long_audio(audio,rate,trim_threshold=20.0)
audio=remove_silence(audio,rate,mid_sil=200,lead_sil=100,trail_sil=200)
if audio.shape[-1]==0:raise ValueError('Referenz enthält nach der Aufbereitung keine Sprache. Vorverarbeitung ausschalten oder andere Aufnahme verwenden.')
sf.write(root/'reference.wav',audio[0],rate,subtype='PCM_16')
return dict(ok=True,original_duration=original,duration=audio.shape[-1]/rate)
def main():
root=Path(sys.argv[1]);resident='--resident' in sys.argv[2:]
with open('/dev/null','w') as sink,contextlib.redirect_stdout(sink),contextlib.redirect_stderr(sink):
if '--prepare-reference' in sys.argv[2:]:
try:
config=json.loads(Path(sys.argv[2]).read_text());rate=config['sampling_rate']
if type(rate)!=int or not 11025<=rate<=96000:raise ValueError('Ungültige OmniVoice-Abtastrate in der Modellkomponente.')
result=prepare_reference(root,rate)
except Exception as exc:result=dict(ok=False,error=str(exc) if isinstance(exc,ValueError) else 'OmniVoice: Referenzaufbereitung fehlgeschlagen ('+type(exc).__name__+').')
write_result(root,'reference-info.json',result);return 0 if result['ok'] else 1
try:model=load(root)
except Exception as exc:
write_result(root,'ready.json' if resident else 'result.json',failure(exc,'Modell laden'));return 1
if resident:write_result(root,'ready.json',dict(ok=True))
lines=sys.stdin if resident else [sys.stdin.read()]
for line in lines:
request=json.loads(line);output=Path(request['output']) if resident else root
try:
(output/'phase').write_text('OmniVoice: Stimme wird erzeugt')
result=generate(model,request,output)
except Exception as exc:result=failure(exc,'Stimme erzeugen')
write_result(output,'result.json',result)
if not resident:return 0 if result['ok'] else 1
return 0
if __name__=='__main__':sys.exit(main())