Files

88 lines
4.9 KiB
Python

"""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['SOULX_SINGER_ASSETS'])
OUTPUT=Path(os.environ['SOULX_SINGER_OUTPUT'])
def load_engine():
from cli.inference_svc import build_model
from soulxsinger.utils.file_utils import load_config
from preprocess.tools.f0_extraction import F0Extractor
config=load_config(ASSETS/'soulx/config.yaml')
model=build_model(str(ASSETS/'soulx/model-svc.pt'),config,device='cuda',use_fp16=True)
f0=F0Extractor(str(ASSETS/'preprocess/rmvpe/rmvpe.pt'),device='cuda',verbose=False)
return model,config,f0
def convert(source,reference,steps=32,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['SOULX_SINGER_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; SoulX erneut öffnen.')
progress(0,desc='Gesangsmodell laden')
if ENGINE is None:ENGINE=load_engine()
model,config,f0=ENGINE;started=time.monotonic()
from soulxsinger.utils.audio_utils import load_wav
import torch
progress(None,desc='Tonhöhen erkennen und Gesang umwandeln')
pt_f0=torch.from_numpy(f0.process(reference,verbose=False)).unsqueeze(0).cuda()
gt_f0=torch.from_numpy(f0.process(source,verbose=False)).unsqueeze(0).cuda()
pt=load_wav(reference,config.audio.sample_rate).cuda();gt=load_wav(source,config.audio.sample_rate).cuda()
with torch.inference_mode():
audio,_=model.infer(pt_wav=pt,gt_wav=gt,pt_f0=pt_f0,gt_f0=gt_f0,auto_shift=False,pitch_shift=int(pitch),n_steps=int(steps),cfg=3.0,use_fp16=True)
audio=audio.squeeze().float().cpu().numpy()
if not audio.size or not np.isfinite(audio).all():raise gr.Error('Ungültige SoulX-Audioausgabe.')
path=OUTPUT/('Gesang-'+uuid.uuid4().hex[:12]+'.wav');sf.write(path,audio,config.audio.sample_rate,subtype='PCM_16')
return str(path),str(path),f'Fertig · 24 kHz WAV · {time.monotonic()-started:.1f} s Verarbeitung'
finally:connection.close()
with gr.Blocks(title='SoulX-Singer · 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('Verwende möglichst eine saubere Gesangsreferenz und reinen Quellgesang ohne Begleitmusik. Ausgabe: 24 kHz. Der Quellgesang wird nach dem offiziellen SoulX-Verfahren verarbeitet.')
run=gr.Button('Gesang umwandeln',variant='primary')
with gr.Accordion('Einstellungen',open=False):
steps=gr.Slider(1,200,value=32,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['SOULX_SINGER_BRIDGE_KEY_FILE']).read_text().strip()
if not secrets.compare_digest(request.headers.get('X-SoulX-Singer-Bridge',''),key):return JSONResponse({'detail':'Deck-Brücke erforderlich.'},status_code=403)
return await call_next(request)
@app.post('/load')
def preload():
global ENGINE
with LOCK:
connection=socket.socket(socket.AF_UNIX)
try:
connection.connect(os.environ['SOULX_SINGER_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'):return JSONResponse(reply,status_code=409)
if reply['gpu']!=os.environ['CUDA_VISIBLE_DEVICES']:return JSONResponse({'error':'GPU geändert'},status_code=409)
if ENGINE is None:ENGINE=load_engine()
return {'status':'ready','model_loaded':True}
finally:connection.close()
@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=os.environ.get('SOULX_SINGER_BIND','127.0.0.1'),port=8139,access_log=False)