Match voice conversion pitch to reference with optional CPU correction
This commit is contained in:
1 parent
04cd46e3e6
commit
369cb2ffe5
16 files changed
+408
-19
No files matched your search
+32
-7
@@ -1,5 +1,5 @@
|
||||
"""Audio-to-audio conversion using the unchanged upstream Humaneness CLI."""
|
||||
import io,json,os,re,signal,subprocess,threading,time,uuid,wave
|
||||
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
|
||||
@@ -27,12 +27,21 @@ def read_upload(handler,field='profile_id'):
|
||||
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') or name in parts or part.is_multipart() or not isinstance(data,bytes):raise ValueError('Unbekanntes oder doppeltes Feld.')
|
||||
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 set(parts)!={field,'source','reference'} or not 1<=len(parts[field])<=128:raise ValueError('Profil, Quellaufnahme und Referenz erforderlich.')
|
||||
if not {field,'source','reference'}<=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
|
||||
return name,wav_input(parts['source']),wav_input(parts['reference'])
|
||||
try:
|
||||
auto=parts.get('pitch_auto',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,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):
|
||||
@@ -40,7 +49,8 @@ class Humaneness:
|
||||
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):
|
||||
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)
|
||||
@@ -54,7 +64,7 @@ class Humaneness:
|
||||
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)
|
||||
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():
|
||||
@@ -74,6 +84,21 @@ class Humaneness:
|
||||
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
|
||||
@@ -85,7 +110,7 @@ class Humaneness:
|
||||
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'):(folder/name).unlink(missing_ok=True)
|
||||
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()
|
||||
|
||||
Reference in new issue
Block a user