Files
Athena-Deck/humaneness.py

131 lines
9.6 KiB
Python
Raw Permalink 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.
"""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',validator=wav_input,reference_required=True,auto_default=False):
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 0<length<=32*1024**2+8192 or not content.startswith('multipart/form-data;'):raise ValueError('Multipart mit source und reference erforderlich, zusammen höchstens32MiB.')
handler.connection.settimeout(30);raw=handler.rfile.read(length)
if len(raw)!=length:raise ValueError('Unvollständiger Upload.')
message=BytesParser(policy=default).parsebytes(('Content-Type: '+content+'\r\nMIME-Version: 1.0\r\n\r\n').encode()+raw);parts={}
if not message.is_multipart():raise ValueError('Ungültiges Multipart.')
for part in message.iter_parts():
name=part.get_param('name',header='content-disposition');data=part.get_payload(decode=True)
if name not in (field,'source','reference','pitch_auto','pitch_semitones') or name in parts or part.is_multipart() or not isinstance(data,bytes):raise ValueError('Unbekanntes oder doppeltes Feld.')
parts[name]=data
if not ({field,'source','reference'} if reference_required else {field,'source'})<=set(parts) or not 1<=len(parts[field])<=128:raise ValueError('Profil, Quellaufnahme und Referenz erforderlich.')
try:name=parts[field].decode('utf-8')
except UnicodeError:raise ValueError('Ungültiger Profilname.') from None
try:
auto=parts.get('pitch_auto',b'true' if auto_default else b'false').decode('ascii');manual=parts.get('pitch_semitones',b'0').decode('ascii')
if len(auto)>5 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,validator(parts['source']),validator(parts['reference']) if 'reference' in parts else None,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<duration<=40:raise ValueError('Ungültige Ausgabedauer.')
with self.lock:self.job['duration']=duration
state='complete';phase='Stimme umgewandelt'
except InterruptedError:state='cancelled';phase='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 name in ('source.wav','reference.wav','pitch-result.wav'):(folder/name).unlink(missing_ok=True)
if state!='complete':(folder/'result.wav').unlink(missing_ok=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()
def stop(self):
self.cancel.set()
process=self.process
if process and process.poll() is None:
try:process.wait(12)
except subprocess.TimeoutExpired:
os.killpg(process.pid,signal.SIGKILL);process.wait()
def audio(self,ident):
if not isinstance(ident,str) or not re.fullmatch('[0-9a-f]{32}',ident):raise ValueError('Ungültiger Auftrag.')
folder=self.root/ident
try:done=json.loads((folder/'job.json').read_text())['state']=='complete'
except (OSError,ValueError,KeyError):done=False
if not done:raise ValueError('Ausgabe noch nicht fertig.')
return (folder/'result.wav').read_bytes()