"""Audio-to-audio conversion using the unchanged upstream Humaneness CLI.""" import io,json,math,os,re,signal,subprocess,threading,time,uuid,wave from email.parser import BytesParser from email.policy import default from pathlib import Path from humaneness_runtime import supported from image_test import probe,cgroup_headroom def wav_input(audio): 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() if w.getsampwidth()!=2 or w.getnchannels()!=1 or w.getframerate() not in (16000,24000,48000) or not 1<=seconds<=30 or len(w.readframes(w.getnframes()))!=w.getnframes()*2:raise ValueError('WAV: mono PCM16, 16/24/48kHz, 1–30Sekunden erforderlich.') except (wave.Error,EOFError,ZeroDivisionError):raise ValueError('Ungültige WAV-Datei.') from None return audio def read_upload(handler,field='profile_id'): if handler.headers.get('Transfer-Encoding'):raise ValueError('Chunked Upload wird nicht unterstützt.') try:length=int(handler.headers.get('Content-Length','0')) except ValueError:raise ValueError('Ungültige Upload-Länge.') from None content=handler.headers.get('Content-Type','') if not 05 or len(manual)>16 or auto not in ('true','false'):raise ValueError() options=pitch_options(auto=='true',float(manual)) except (UnicodeError,ValueError):raise ValueError('Tonhöhe: pitch_auto=true/false und pitch_semitones zwischen -12 und12 erforderlich.') from None return name,wav_input(parts['source']),wav_input(parts['reference']),options def pitch_options(pitch_auto=False,pitch_semitones=0): if not isinstance(pitch_auto,bool) or isinstance(pitch_semitones,bool) or not isinstance(pitch_semitones,(int,float)) or not math.isfinite(pitch_semitones) or not -12<=pitch_semitones<=12:raise ValueError('Ungültige Tonhöhenkorrektur.') return dict(pitch_auto=pitch_auto,pitch_semitones=float(pitch_semitones)) class Humaneness: def __init__(self,root,runtime,profiles,scheduler): self.root=Path(root);self.runtime=runtime;self.profiles=profiles;self.scheduler=scheduler;self.lock=threading.RLock();self.gate=threading.Lock();self.job=None;self.process=None;self.cancel=threading.Event() def blockers(self,p):return [] if self.runtime.status()['installed'] else ['Humaneness-Laufzeit und Gewichte fehlen.'] def status(self): with self.lock:return dict(runtime=self.runtime.status(),job=dict(self.job) if self.job else None) def start(self,profile_id,source,reference,wait=False,pitch_auto=False,pitch_semitones=0): options=pitch_options(pitch_auto,pitch_semitones) 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('Humaneness-Profil nicht ausführbar.') source=wav_input(source);reference=wav_input(reference) if not self.gate.acquire(False):raise ValueError('Voice Conversion läuft bereits.') lease=None try: lease=self.scheduler.lease(('conversion',),timeout=600 if wait else 0,modes=('llm','voice'));lease.__enter__() gpu=next((g for g in probe() if '3060' in g['name'] and not g['processes'] and g['free_mib']>=8500),None) if not gpu:raise ValueError('RTX3060 benötigt mindestens8,5GiB freien VRAM ohne fremden GPU-Prozess.') 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) with wave.open(io.BytesIO(source)) as w:source_duration=w.getnframes()/w.getframerate() with self.lock:self.cancel.clear();self.job=dict(id=ident,profile_id=profile_id,state='running',phase='Humaneness: Stimme wird umgewandelt',started_at=time.time(),gpu=gpu['name'],source_duration=source_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 name in ('source.wav','reference.wav'):(directory/name).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='Humaneness-Konvertierung fehlgeschlagen.';process=None try: python,model=self.runtime.paths();env={k:v for k,v in os.environ.items() if not k.startswith(('DECK_','HF_'))};env.update(CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HOME=str(self.runtime.root/'hf-cache'),HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1',OMP_NUM_THREADS='4',PYTHONDONTWRITEBYTECODE='1') with (folder/'worker.stderr').open('wb') as log: process=subprocess.Popen([str(python),str(model/'infer.py'),'--model-dir',str(model),'--source',str(folder/'source.wav'),'--target',str(folder/'reference.wav'),'--output',str(folder/'result.wav'),'--candidates','1','--precision','bf16'],env=env,stdout=subprocess.DEVNULL,stderr=log,start_new_session=True) with self.lock:self.process=process deadline=time.monotonic()+600 while process.poll() is None: if self.cancel.wait(.2):raise InterruptedError() if time.monotonic()>deadline:raise ValueError('Zeitlimit der Konvertierung erreicht.') if self.cancel.is_set():raise InterruptedError() if process.returncode:raise ValueError('Humaneness-Worker beendet, Exitcode '+str(process.returncode)+'.') if self.job.get('pitch_auto') or self.job.get('pitch_semitones'): with self.lock:self.job['phase']='Tonhöhe wird an die Referenz angepasst' args=[str(python),str(Path(__file__).with_name('humaneness_pitch.py')),'--folder',str(folder),'--semitones',str(self.job['pitch_semitones'])] if self.job['pitch_auto']:args.append('--automatic') # CPU subprocess with the same controlled cancellation and timeout as inference. env['CUDA_VISIBLE_DEVICES']='';env['NUMBA_NUM_THREADS']='2';env['NUMBA_CACHE_DIR']=str(self.runtime.root/'numba-cache') with (folder/'worker.stderr').open('ab') as log:process=subprocess.Popen(args,env=env,stdout=subprocess.DEVNULL,stderr=log,start_new_session=True) with self.lock:self.process=process deadline=time.monotonic()+180 while process.poll() is None: if self.cancel.wait(.2):raise InterruptedError() if time.monotonic()>deadline:raise ValueError('Zeitlimit der Tonhöhenkorrektur erreicht.') if self.cancel.is_set():raise InterruptedError() if process.returncode:raise ValueError('Tonhöhenkorrektur fehlgeschlagen, Exitcode '+str(process.returncode)+'.') with self.lock:self.job['pitch']=json.loads((folder/'pitch.json').read_text()) with wave.open(str(folder/'result.wav')) as w:duration=w.getnframes()/w.getframerate() if not 0