Files
Athena-Deck/seedvc.py
T

98 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Serial GPU voice-conversion jobs with scheduler leases and private input cleanup."""
import io,json,os,signal,subprocess,threading,time,uuid,wave
from pathlib import Path
from humaneness import Humaneness,pitch_options
from seedvc_runtime import supported
from image_test import probe,cgroup_headroom
def wav_input(audio,max_seconds=120):
if not isinstance(audio,bytes) or not 44<=len(audio)<=16*1024**2 or audio[:4]!=b'RIFF' or audio[8:12]!=b'WAVE':raise ValueError('PCM-WAV bis16MiB erforderlich.')
try:
with wave.open(io.BytesIO(audio)) as w:
seconds=w.getnframes()/w.getframerate();size=w.getnframes()*w.getnchannels()*2
if w.getsampwidth()!=2 or w.getnchannels() not in (1,2) or w.getframerate() not in (16000,22050,24000,44100,48000) or not 1<=seconds<=max_seconds or len(w.readframes(w.getnframes()))!=size:raise ValueError('PCM16-WAV mit1–'+str(max_seconds)+' Sekunden erforderlich.')
except (wave.Error,EOFError,ZeroDivisionError):raise ValueError('Ungültige WAV-Datei.') from None
return audio
class SeedVC(Humaneness):
def __init__(self,*args):
super().__init__(*args)
import re,shutil
latest=None
if self.root.exists():
for folder in self.root.iterdir():
if folder.is_symlink() or not folder.is_dir() or not re.fullmatch('[a-f0-9]{32}',folder.name):continue
try:j=json.loads((folder/'job.json').read_text())
except (OSError,ValueError):j=dict(id=folder.name,state='cancelled',phase='Durch Neustart unterbrochen.',finished_at=time.time())
for n in ('source.wav','reference.wav'):(folder/n).unlink(missing_ok=True)
shutil.rmtree(folder/'output',ignore_errors=True)
if j.get('state')!='complete':
(folder/'result.wav').unlink(missing_ok=True);j.update(state='cancelled',phase='Durch Neustart unterbrochen.')
(folder/'job.json').write_text(json.dumps(j))
if latest is None or j.get('finished_at',0)>latest.get('finished_at',0):latest=j
self.job=latest
def blockers(self,p):return [] if self.runtime.status()['installed'] else ['Seed-VC-GPU-Laufzeit und Gewichte fehlen.']
def default_reference(self):
# Use the saved default voice; bounded normalization also handles streaming WAV headers.
path=self.voice_path('default')
r=subprocess.run(['ffmpeg','-nostdin','-v','error','-protocol_whitelist','file,pipe','-i',str(path),'-t','8','-ac','1','-ar','24000','-f','s16le','pipe:1'],capture_output=True,timeout=30)
if r.returncode or len(r.stdout)<48000:raise ValueError('Gespeicherte Referenzstimme konnte nicht gelesen werden.')
out=io.BytesIO()
with wave.open(out,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(24000);w.writeframes(r.stdout)
return out.getvalue()
def start(self,profile_id,source,reference=None,wait=False,pitch_auto=True,pitch_semitones=0):
options=pitch_options(pitch_auto,pitch_semitones)
if not options['pitch_semitones'].is_integer():raise ValueError('Seed-VC verwendet ganze Halbtöne.')
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id and supported(p.get('model'))),None)
if not p or not p['runnable']:raise ValueError('Seed-VC-Profil nicht ausführbar.')
source=wav_input(source);reference=wav_input(reference,30) if reference is not None else self.default_reference()
if not self.gate.acquire(False):raise ValueError('Seed-VC-Konvertierung läuft bereits.')
lease=None
try:
lease=self.scheduler.lease(('seedvc',),timeout=600 if wait else 0,modes=('llm','voice'));lease.__enter__()
gpu=next((g for g in probe() if 'RTX 3060' in g['name'] and not g['processes'] and g['free_mib']>=8500),None)
if not gpu:raise ValueError('Seed-VC benötigt eine freie RTX3060 mit mindestens8,5GiB VRAM. Kein CPU-Fallback.')
headroom=cgroup_headroom()
if headroom is not None and headroom<6*1024**3:raise ValueError('Mindestens6GiB freier Deck-RAM erforderlich.')
ident=uuid.uuid4().hex;directory=self.root/ident;directory.mkdir(parents=True,mode=0o700)
(directory/'source.wav').write_bytes(source);(directory/'reference.wav').write_bytes(reference);(directory/'options.json').write_text(json.dumps(options))
with wave.open(io.BytesIO(source)) as w:duration=w.getnframes()/w.getframerate()
with self.lock:self.cancel.clear();self.job=dict(id=ident,profile_id=profile_id,state='running',phase='Seed-VC: Stimme wird auf RTX3060 umgewandelt',started_at=time.time(),gpu=gpu['name'],source_duration=duration,**options)
threading.Thread(target=self._run,args=(ident,gpu,lease),daemon=True).start();return dict(self.job)
except Exception:
if 'directory' in locals():
for n in ('source.wav','reference.wav'):(directory/n).unlink(missing_ok=True)
if lease:lease.__exit__(None,None,None)
self.gate.release();raise
def _run(self,ident,gpu,lease):
folder=self.root/ident;state='failed';phase='Seed-VC-Konvertierung fehlgeschlagen.';process=None
try:
py,_=self.runtime.paths();env={k:v for k,v in os.environ.items() if not k.startswith(('HF_','DECK_','OPENAI_','LLAMA_'))};env.update(CUDA_VISIBLE_DEVICES=gpu['uuid'],PYTHONDONTWRITEBYTECODE='1')
with (folder/'worker.stderr').open('wb') as log:process=subprocess.Popen([str(py),str(Path(__file__).with_name('seedvc_worker.py')),str(self.runtime.root),str(folder)],env=env,stdout=log,stderr=log,start_new_session=True)
with self.lock:self.process=process
deadline=time.monotonic()+1800
while process.poll() is None:
if self.cancel.wait(.2):raise InterruptedError()
if time.monotonic()>deadline:raise ValueError('Seed-VC-Zeitlimit erreicht.')
if self.cancel.is_set():raise InterruptedError()
if process.returncode:raise ValueError('Seed-VC-Worker beendet, Exitcode '+str(process.returncode)+'.')
with wave.open(str(folder/'result.wav')) as w:duration=w.getnframes()/w.getframerate()
if not 0<duration<=125:raise ValueError('Ungültige Seed-VC-Ausgabedauer.')
metrics=json.loads((folder/'metrics.json').read_text())
with self.lock:self.job.update(duration=duration,metrics=metrics)
state='complete';phase='Stimme mit Seed-VC umgewandelt'
except InterruptedError:state='cancelled';phase='Seed-VC-Umwandlung abgebrochen.'
except Exception as e:phase=str(e)
finally:
if process and process.poll() is None:
try:os.killpg(process.pid,signal.SIGTERM);process.wait(10)
except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait()
except ProcessLookupError:pass
for n in ('source.wav','reference.wav'):(folder/n).unlink(missing_ok=True)
if state!='complete':
(folder/'result.wav').unlink(missing_ok=True)
import shutil
shutil.rmtree(folder/'output',ignore_errors=True)
with self.lock:self.process=None;self.job.update(state=state,phase=phase,finished_at=time.time());(folder/'job.json').write_text(json.dumps(self.job))
lease.__exit__(None,None,None);self.gate.release()