"""Small singing UI: pinned upstream SVC, lazy GPU load under Deck's voice lease.""" import json,os,secrets,socket,threading,time,uuid from pathlib import Path from types import SimpleNamespace import gradio as gr import numpy as np import soundfile as sf from fastapi import FastAPI,Request from fastapi.responses import JSONResponse import uvicorn LOCK=threading.RLock() ENGINE=None ASSETS=Path(os.environ['SEED_VC_ASSETS']) OUTPUT=Path(os.environ['SEED_VC_OUTPUT']) def load_engine(device='cuda'): import app_svc as engine import torch,yaml engine.device=torch.device(device) original_load=engine.load_checkpoint def verified_load(model,optimizer,path,**kwargs): weights=torch.load(path,map_location='cpu',weights_only=True)['net'] for key,module in model.items(): saved={name.removeprefix('module.'):value for name,value in weights[key].items()} invalid=[name for name,param in module.named_parameters() if name not in saved or saved[name].shape!=param.shape] if invalid:raise RuntimeError('Seed-VC-Gewicht passt nicht zur Inferenzarchitektur: '+', '.join(invalid[:5])) del weights return original_load(model,optimizer,path,**kwargs) engine.load_checkpoint=verified_load # All model reads use the locally verified asset set, including auxiliary models. def local_model(repo,model_filename='pytorch_model.bin',config_filename=None): base=ASSETS/repo.replace('/','--') return (str(base/model_filename),str(base/config_filename)) if config_filename else str(base/model_filename) engine.load_custom_model_from_hf=local_model main=ASSETS/'Plachta--Seed-VC' config=yaml.safe_load((main/'config_dit_mel_seed_uvit_whisper_base_f0_44k.yml').read_text()) config['model_params']['vocoder']['name']=str(ASSETS/'nvidia--bigvgan_v2_44khz_128band_512x') config['model_params']['speech_tokenizer']['name']=str(ASSETS/'openai--whisper-small') config_path=OUTPUT/'local-config.yml';config_path.write_text(yaml.safe_dump(config)) args=SimpleNamespace(fp16=device.startswith('cuda'),checkpoint=str(main/'DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth'),config=str(config_path)) (engine.model_f0,engine.semantic_fn,engine.vocoder_fn,engine.campplus_model, engine.to_mel_f0,engine.mel_fn_args,engine.f0_fn)=engine.load_models(args) engine.max_context_window=engine.sr//engine.hop_length*30 engine.overlap_wave_len=engine.overlap_frame_len*engine.hop_length return engine def convert(source,reference,steps=40,pitch=0,progress=gr.Progress()): global ENGINE if not source or not reference:raise gr.Error('Gesangsdatei und Referenzstimme hochladen.') with LOCK: connection=socket.socket(socket.AF_UNIX) try: connection.connect(os.environ['SEED_VC_LEASE_SOCKET']);connection.sendall(b'{"action":"reserve"}\n') with connection.makefile('rb') as stream:reply=json.loads(stream.readline(8193)) if not reply.get('ok'):raise gr.Error(reply.get('error','Deck-Ressourcen nicht verfügbar.')) if reply['gpu']!=os.environ['CUDA_VISIBLE_DEVICES']:raise gr.Error('GPU-Auswahl geändert; Seed-VC erneut öffnen.') progress(0,desc='Gesangsmodell laden') if ENGINE is None:ENGINE=load_engine() started=time.monotonic();result=None progress(None,desc='Gesang umwandeln') for _,wave in ENGINE.voice_conversion(source,reference,int(steps),1.0,0.7,False,int(pitch)): if wave is not None:result=wave if result is None:raise gr.Error('Seed-VC lieferte keine vollständige Audiodatei.') sr,audio=result if sr!=44100 or not np.isfinite(audio).all():raise gr.Error('Ungültige Seed-VC-Audioausgabe.') path=OUTPUT/('Gesang-'+uuid.uuid4().hex[:12]+'.wav');sf.write(path,audio,sr,subtype='PCM_16') return str(path),str(path),f'Fertig · 44,1 kHz WAV · {time.monotonic()-started:.1f} s Verarbeitung' finally:connection.close() with gr.Blocks(title='Seed-VC · Gesang') as demo: gr.Markdown('# Gesang mit deiner Referenzstimme\nGesangsdatei und Zielstimme hochladen. Melodie und Timing bleiben erhalten; kein Stimmtraining nötig. Die Qualität hängt von beiden Aufnahmen ab.') with gr.Row(): source=gr.Audio(label='Reiner Gesang',type='filepath',sources=['upload']) reference=gr.Audio(label='Referenzstimme',type='filepath',sources=['upload','microphone']) gr.Markdown('Die Referenz wird wie im Original auf die ersten 25 Sekunden begrenzt. Der vollständige Quellgesang wird in Abschnitten verarbeitet. Verwende eine klare Einzelstimme ohne Begleitmusik.') run=gr.Button('Gesang umwandeln',variant='primary') with gr.Accordion('Einstellungen',open=False): steps=gr.Slider(1,200,value=40,step=1,label='Qualität / Diffusionsschritte') pitch=gr.Slider(-24,24,value=0,step=1,label='Tonhöhe verschieben (Halbtöne)') output=gr.Audio(label='Ergebnis',type='filepath');download=gr.File(label='WAV herunterladen');report=gr.Markdown() run.click(convert,[source,reference,steps,pitch],[output,download,report],api_name='convert') app=FastAPI() @app.middleware('http') async def protect(request:Request,call_next): key=Path(os.environ['SEED_VC_BRIDGE_KEY_FILE']).read_text().strip() if not secrets.compare_digest(request.headers.get('X-Seed-VC-Bridge',''),key):return JSONResponse({'detail':'Deck-Brücke erforderlich.'},status_code=403) return await call_next(request) @app.get('/health') def health():return {'status':'ready','model_loaded':ENGINE is not None} app=gr.mount_gradio_app(app,demo.queue(default_concurrency_limit=1),path='/',allowed_paths=[str(OUTPUT)]) if __name__=='__main__':uvicorn.run(app,host='0.0.0.0',port=8137,access_log=False)