84 lines
6.1 KiB
Python
84 lines
6.1 KiB
Python
"""UI-only bridge: all GPU execution and profile selection remain in Athena Deck."""
|
|
import io,json,os,time,urllib.request,urllib.error,wave
|
|
from pathlib import Path
|
|
CONFIG=Path('/data/deck-connection.json')
|
|
BASE='http://127.0.0.1:8108'
|
|
def request(path,data=None,ctype='application/json'):
|
|
token=json.loads(CONFIG.read_text()).get('token','') if CONFIG.exists() else ''
|
|
if not token:raise ValueError('Deck-Verbindung zuerst einrichten.')
|
|
req=urllib.request.Request(BASE+path,data=data,headers={'Authorization':'Bearer '+token,'Content-Type':ctype})
|
|
try:
|
|
with urllib.request.urlopen(req,timeout=90) as r:return r.read()
|
|
except urllib.error.HTTPError as exc:
|
|
try:error=json.loads(exc.read()).get('error','Deck-Anfrage abgelehnt')
|
|
except Exception:error='Deck-Anfrage abgelehnt (HTTP '+str(exc.code)+')'
|
|
raise ValueError(error if isinstance(error,str) else error.get('message','Deck-Anfrage abgelehnt')) from None
|
|
|
|
def connect(token):
|
|
if not token:raise ValueError('API-Token eingeben.')
|
|
# Check before persisting; keep token out of output and logs.
|
|
req=urllib.request.Request(BASE+'/api/v1/voice/profiles',headers={'Authorization':'Bearer '+token})
|
|
with urllib.request.urlopen(req,timeout=10) as r:
|
|
if r.status!=200:raise ValueError('Deck-Verbindung nicht bestätigt.')
|
|
CONFIG.parent.mkdir(parents=True,exist_ok=True);tmp=CONFIG.with_suffix('.tmp');tmp.write_text(json.dumps({'token':token}));tmp.chmod(0o600);tmp.replace(CONFIG)
|
|
return 'Deck verbunden. In Deck das gewünschte Stimmprofil aktivieren und Stimmwerkzeuge starten.'
|
|
|
|
def generate(family,text,device='3060',reference=None,**options):
|
|
rows=json.loads(request('/api/v1/voice/profiles'))['profiles']
|
|
p=next((p for p in rows if p['repo']==family and p['enabled'] and p['runnable']),None)
|
|
if not p:raise ValueError('Dieses Stimmprofil zuerst in Deck aktivieren. Es darf nur ein Stimmprofil aktiv sein.')
|
|
data=dict(profile_id=p['id'],text=text,device=device,**options)
|
|
ctype='application/json'
|
|
if reference:
|
|
import soundfile as sf
|
|
arr,rate=sf.read(reference);buf=io.BytesIO();sf.write(buf,arr,rate,format='WAV',subtype='PCM_16');audio=buf.getvalue()
|
|
boundary='athena-voice-'+os.urandom(12).hex();parts=[]
|
|
for k,v in data.items():
|
|
value=str(v).lower() if isinstance(v,bool) else str(v)
|
|
parts.append(('--'+boundary+'\r\nContent-Disposition: form-data; name="'+k+'"\r\n\r\n'+value+'\r\n').encode())
|
|
parts.extend([('--'+boundary+'\r\nContent-Disposition: form-data; name="file"; filename="reference.wav"\r\nContent-Type: audio/wav\r\n\r\n').encode(),audio,('\r\n--'+boundary+'--\r\n').encode()]);body=b''.join(parts);ctype='multipart/form-data; boundary='+boundary
|
|
else:body=json.dumps(data).encode()
|
|
job=json.loads(request('/api/v1/voice/start',body,ctype));deadline=time.monotonic()+650
|
|
while time.monotonic()<deadline:
|
|
current=json.loads(request('/api/v1/voice'))['job']
|
|
if not current or current['id']!=job['id']:raise ValueError('Auftrag nicht mehr verfügbar.')
|
|
if current['state']=='complete':
|
|
import soundfile as sf
|
|
arr,rate=sf.read(io.BytesIO(request('/api/v1/voice/audio?id='+job['id'])),dtype='int16');return (rate,arr),'Fertig · '+current['gpu']
|
|
if current['state']!='running':raise ValueError(current['phase'])
|
|
time.sleep(.5)
|
|
raise ValueError('Deck-Auftrag dauert länger als erwartet. Status in Deck prüfen.')
|
|
|
|
def main():
|
|
import gradio as gr
|
|
family=os.environ['VOICE_FAMILY'];port=int(os.environ['VOICE_PORT'])
|
|
if family=='k2-fsa/OmniVoice':
|
|
# Reuse the exact OmniVoice demo shipped by the old router, replacing only
|
|
# generation with Deck requests. No weights or CUDA access in this container.
|
|
from omnivoice.cli.demo import build_demo
|
|
from types import SimpleNamespace
|
|
def gen(text,language,ref_audio,instruct,num_step,guidance_scale,denoise,speed,duration,preprocess_prompt,postprocess_output,mode,ref_text=None):
|
|
try:return generate(family,text,reference=ref_audio if mode=='clone' else None,reference_text=ref_text or '',language='' if language=='Auto' else language or '',instruct=instruct or '',steps=int(num_step or 32),cfg=float(guidance_scale if guidance_scale is not None else 2),seed=42,speed=float(speed or 1),duration=float(duration or 0),denoise=bool(denoise),preprocess_prompt=bool(preprocess_prompt),postprocess_output=bool(postprocess_output))
|
|
except Exception as exc:return None,str(exc) if isinstance(exc,ValueError) else 'Deck-Verbindung prüfen.'
|
|
demo=build_demo(SimpleNamespace(sampling_rate=24000),'Athena Deck · OmniVoice',generate_fn=gen)
|
|
with demo:
|
|
with gr.Accordion('Athena Deck-Verbindung',open=not CONFIG.exists()):
|
|
token=gr.Textbox(label='Deck API-Token',type='password');save=gr.Button('Verbinden');status=gr.Textbox(label='Verbindung',interactive=False);save.click(connect,token,status)
|
|
else:
|
|
with gr.Blocks(title='Athena VoxCPM2 Studio') as demo:
|
|
gr.Markdown('# VoxCPM2 Studio\nSprachausgabe, Voice Design und Stimmklonen. Verarbeitung über Athena Deck. Profil dort aktivieren; Stimmwerkzeuge starten.')
|
|
with gr.Accordion('Deck-Verbindung',open=not CONFIG.exists()):
|
|
token=gr.Textbox(label='Deck API-Token',type='password');save=gr.Button('Verbinden');status=gr.Textbox(interactive=False);save.click(connect,token,status)
|
|
text=gr.Textbox(label='Text (Voice Design: Beschreibung in Klammern voranstellen)',lines=5)
|
|
ref=gr.Audio(label='Referenzstimme (optional, WAV)',type='filepath')
|
|
device=gr.Dropdown(['3060','5080'],value='3060',label='GPU')
|
|
with gr.Row():
|
|
cfg=gr.Slider(.5,5,value=2,step=.1,label='Guidance');steps=gr.Slider(1,50,value=10,step=1,label='Schritte');seed=gr.Number(value=42,precision=0,label='Seed')
|
|
button=gr.Button('Stimme erzeugen',variant='primary');output=gr.Audio(label='Ergebnis');message=gr.Textbox(label='Status',interactive=False)
|
|
def gen(text,ref,device,cfg,steps,seed):
|
|
try:return generate(family,text,device,ref,cfg=float(cfg),steps=int(steps),seed=int(seed))
|
|
except Exception as exc:return None,str(exc) if isinstance(exc,ValueError) else 'Deck-Verbindung prüfen.'
|
|
button.click(gen,[text,ref,device,cfg,steps,seed],[output,message])
|
|
demo.queue(default_concurrency_limit=1).launch(server_name='127.0.0.1',server_port=port,show_error=False,allowed_paths=['/tmp'],max_file_size='8mb')
|
|
if __name__=='__main__':main()
|