51 lines
3.7 KiB
Python
51 lines
3.7 KiB
Python
"""Audio-to-score jobs use Deck's music GPU lease and delete temporary input."""
|
|
import os,signal,subprocess,tempfile,threading,time
|
|
from pathlib import Path
|
|
from image_test import probe
|
|
class Remix:
|
|
def __init__(self,root,runtime,music,scheduler):
|
|
self.root=Path(root);self.runtime=runtime;self.music=music;self.scheduler=scheduler;self.lock=threading.Lock();self.process=None;self.active=False
|
|
def status(self):return dict(self.runtime.status(),active=self.active)
|
|
def transcribe(self,audio,melody_only=True):
|
|
if type(melody_only) is not bool:raise ValueError('melody_only muss boolesch sein.')
|
|
if not isinstance(audio,bytes) or not 44<=len(audio)<=256*1024**2:raise ValueError('Audiodatei fehlt oder ist größer als 256 MiB.')
|
|
if not self.runtime.status()['installed']:raise ValueError('YuE2 Audio Remix zuerst in Deck einrichten.')
|
|
if self.scheduler.gpu_mode!='music':raise ValueError('Bitte in Deck auf Musik umschalten.')
|
|
if not self.lock.acquire(blocking=False):raise ValueError('Audio-Remix-Analyse läuft bereits.')
|
|
release=None
|
|
try:
|
|
release=self.scheduler.image_reservation(kind='music');self.active=True
|
|
self.music.close() # Only after exclusive admission: analysis needs the same GPU.
|
|
gpu=next((g for g in probe() if 'RTX 5080' in g['name'] and not g['processes'] and g['free_mib']>6000),None)
|
|
if not gpu:raise ValueError('RTX 5080 nicht ausreichend frei. Fremde Prozesse bleiben unverändert.')
|
|
self.root.mkdir(parents=True,exist_ok=True)
|
|
with tempfile.TemporaryDirectory(prefix='analysis-',dir=self.root) as temp:
|
|
work=Path(temp);(work/'input').write_bytes(audio)
|
|
result=subprocess.run(['ffmpeg','-nostdin','-hide_banner','-loglevel','error','-y','-i',str(work/'input'),'-t','1201','-ac','1','-ar','24000','-c:a','pcm_s16le',str(work/'input.wav')],capture_output=True,timeout=180)
|
|
if result.returncode:raise ValueError('Audiodatei konnte nicht gelesen werden.')
|
|
import wave
|
|
with wave.open(str(work/'input.wav')) as wav:
|
|
if not 0<wav.getnframes()/wav.getframerate()<=1200:raise ValueError('Audio-Remix: maximal 20 Minuten pro Aufnahme.')
|
|
python,models=self.runtime.paths();started=time.monotonic()
|
|
with (work/'worker.log').open('wb') as log:
|
|
self.process=subprocess.Popen([str(python),str(Path(__file__).with_name('remix_worker.py')),str(models),str(work/'input.wav'),str(work/'output'),'true' if melody_only else 'false'],stdout=log,stderr=log,start_new_session=True,env=dict(os.environ,CUDA_VISIBLE_DEVICES=gpu['uuid'],HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1',OMP_NUM_THREADS='4'))
|
|
try:code=self.process.wait(timeout=3600)
|
|
except subprocess.TimeoutExpired:self.stop();raise ValueError('Audio-Remix-Analyse hat das Zeitlimit überschritten.') from None
|
|
if code:
|
|
error=(work/'worker.log').read_text(errors='replace')[-4000:]
|
|
raise ValueError('Remix-GPU-Speicher reicht nicht.' if 'out of memory' in error.lower() else 'SheetSage2-Analyse fehlgeschlagen ('+next((line.split(':',1)[0][:80] for line in reversed(error.splitlines()) if line and not line.startswith((' ','Traceback'))),'Worker-Fehler')+'). Laufzeit und Modellpaket prüfen.')
|
|
abc=(work/'output/score.abc').read_text()
|
|
if not 1<=len(abc)<=20000:raise ValueError('Musikplan zu umfangreich oder leer.')
|
|
return dict(abc=abc,melody_only=melody_only,seconds=round(time.monotonic()-started,1))
|
|
finally:
|
|
self.stop();self.active=False
|
|
if release:release()
|
|
self.lock.release()
|
|
def stop(self):
|
|
p=self.process
|
|
if p and p.poll() is None:
|
|
try:os.killpg(p.pid,signal.SIGTERM);p.wait(5)
|
|
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
|
|
except ProcessLookupError:pass
|
|
self.process=None
|