Files

267 lines
13 KiB
Python

"""Athena's existing separation API, exposed through the native Hermes plugin API.
Each call waits at most 15 seconds for processing. Repeat with the returned job_id
until complete; no detached daemon, long-running tool timeout or duplicate starts.
"""
import hashlib
import http.client
import json
import fcntl
from pathlib import Path
import re
import subprocess
import tempfile
import time
from urllib.parse import urlencode, urlsplit
import uuid
import wave
MAX_BYTES = 256 * 1024**2
MAX_OUTPUT = 512 * 1024**2
EXTENSIONS = {'.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.opus', '.aiff', '.aif', '.webm'}
MODEL = 'model_bs_roformer_ep_317_sdr_12.9755.ckpt'
SCHEMA = {
'name': 'athena_separate_audio',
'description': (
'Trenne eine hochgeladene MP3/Audiodatei in Gesang (Vocals.wav) und Instrumental.wav. '
'Use the real gateway-local path from the user attachment, never a path on the phone/Mac. '
'Start with file_path; while state=running repeat with ONLY the returned job_id until complete. '
'Processing may wait for Athena GPU availability; never unload models yourself. '
'On success include BOTH returned MEDIA: lines verbatim on separate lines in your final reply '
'so the chat offers both WAV files as attachments. Do not claim success before state=complete. '
'Maximum 20 minutes / 256 MiB; no ZIP.'),
'parameters': {'type': 'object', 'properties': {
'file_path': {'type': 'string', 'description': 'Uploaded audio path; only for starting a new separation.'},
'job_id': {'type': 'string', 'description': 'Returned local job ID; poll this instead of starting again.'}},
'additionalProperties': False},
}
class AudioError(Exception):
pass
class Client:
def __init__(self, base_url, api_key):
self.url = urlsplit(base_url.rstrip('/'))
if self.url.scheme not in ('http', 'https') or not self.url.hostname or self.url.username or self.url.password or self.url.query or self.url.fragment:
raise AudioError('Ungültige Athena-Adresse in den Plugin-Einstellungen.')
if not api_key:
raise AudioError('Athena-Dienstschlüssel fehlt in den Plugin-Einstellungen.')
self.headers = {'Authorization': 'Bearer ' + api_key}
def connection(self):
cls = http.client.HTTPSConnection if self.url.scheme == 'https' else http.client.HTTPConnection
return cls(self.url.hostname, self.url.port, timeout=120)
def request(self, path, *, upload=None):
conn = self.connection()
try:
full_path = self.url.path.rstrip('/') + path
if upload is None:
conn.request('GET', full_path, headers=self.headers)
else:
boundary = 'athena-' + uuid.uuid4().hex
prefix = (f'--{boundary}\r\nContent-Disposition: form-data; name="model"\r\n\r\n{MODEL}\r\n'
f'--{boundary}\r\nContent-Disposition: form-data; name="target"\r\n\r\nvocals\r\n'
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="input.wav"\r\n'
'Content-Type: audio/wav\r\n\r\n').encode()
suffix = f'\r\n--{boundary}--\r\n'.encode()
conn.putrequest('POST', full_path)
for key, val in self.headers.items():
conn.putheader(key, val)
conn.putheader('Content-Type', 'multipart/form-data; boundary=' + boundary)
conn.putheader('Content-Length', str(len(prefix) + upload.stat().st_size + len(suffix)))
conn.endheaders()
conn.send(prefix)
with upload.open('rb') as source:
while block := source.read(1024**2):
conn.send(block)
conn.send(suffix)
response = conn.getresponse()
if response.status != 200:
# Never reflect arbitrary remote bodies, request headers or credentials.
raise AudioError(f'Athena meldet HTTP {response.status}. Endpunktfreigabe und Trennprofil prüfen.')
payload = response.read(2 * 1024**2 + 1)
if len(payload) > 2 * 1024**2:
raise AudioError('Athena-Statusantwort ist zu groß.')
return json.loads(payload)
finally:
conn.close()
def download(self, remote_id, index, destination):
conn = self.connection()
partial = destination.with_suffix('.part')
try:
conn.request('GET', self.url.path.rstrip('/') + '/api/v1/separator-tests/audio?' +
urlencode({'id': remote_id, 'index': index}), headers=self.headers)
response = conn.getresponse()
if response.status != 200:
raise AudioError(f'WAV-Download fehlgeschlagen (HTTP {response.status}).')
size = 0
with partial.open('wb') as output:
while block := response.read(1024**2):
size += len(block)
if size > MAX_OUTPUT:
raise AudioError('Ergebnisspur überschreitet 512 MiB.')
output.write(block)
with wave.open(str(partial)) as audio:
if not audio.getnframes():
raise AudioError('Athena lieferte eine leere WAV-Datei.')
partial.replace(destination)
finally:
partial.unlink(missing_ok=True)
conn.close()
def home():
from hermes_constants import get_hermes_home
return Path(get_hermes_home()).resolve()
def cwd():
from agent.runtime_cwd import resolve_agent_cwd
return Path(resolve_agent_cwd()).resolve()
def scope(kwargs):
# Separate records for sessions even when they share a workspace.
session = kwargs.get('session_id') or kwargs.get('task_id')
if not session:
from gateway.session_context import get_session_env
session = get_session_env('HERMES_SESSION_ID')
if not session:
raise AudioError('Hermes-Sitzung fehlt; Werkzeug aus einem Chat aufrufen.')
return hashlib.sha256(str(session).encode()).hexdigest()[:24]
def source_path(raw):
path = Path(raw).expanduser()
path = (cwd() / path).resolve() if not path.is_absolute() else path.resolve()
allowed = [cwd(), home() / 'attachments']
if not any(path.is_relative_to(root.resolve()) for root in allowed):
raise AudioError('Audiodatei muss aus dem Workspace oder den Hermes-Chat-Anhängen stammen.')
if path.suffix.lower() not in EXTENSIONS or not path.is_file() or not 0 < path.stat().st_size <= MAX_BYTES:
raise AudioError('Audiodatei fehlt, ist leer, hat ein unbekanntes Format oder überschreitet 256 MiB.')
return path
def decode(source, destination):
# Probe BEFORE decoding: reject long/compressed inputs without expanding hours of PCM.
result = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'json', str(source)], capture_output=True, timeout=30)
try:
duration = float(json.loads(result.stdout)['format']['duration'])
except (ValueError, KeyError, TypeError):
raise AudioError('Audiodauer konnte nicht bestimmt werden.') from None
if result.returncode or not 0 < duration <= 1200:
raise AudioError('Audiodatei muss zwischen 0 und 20 Minuten lang sein.')
result = subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(source),
'-vn', '-ac', '2', '-ar', '44100', '-c:a', 'pcm_s16le', str(destination)],
capture_output=True, timeout=180)
if result.returncode or not destination.is_file() or destination.stat().st_size > MAX_BYTES:
raise AudioError('Audio konnte nicht in Stereo-WAV umgewandelt werden.')
def save(record_path, record):
temp = record_path.with_suffix('.tmp')
temp.write_text(json.dumps(record))
temp.chmod(0o600)
temp.replace(record_path)
def separate(args, *, base_url, api_key, **kwargs):
"""Serialize requests per chat so parallel calls cannot launch the same input twice."""
try:
root = home() / 'audio-separation' / scope(kwargs)
root.mkdir(parents=True, exist_ok=True, mode=0o700)
with (root / '.lock').open('a') as lock:
try:
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return json.dumps({'state': 'busy', 'next': 'Another separation call in this chat is still running. Wait for it; do not start another job.'})
return _separate(args, base_url=base_url, api_key=api_key, **kwargs)
except AudioError as exc:
return json.dumps({'state': 'error', 'error': str(exc)}, ensure_ascii=False)
except Exception:
return json.dumps({'state': 'error', 'error': 'Sitzungsablage nicht verfügbar.'})
def _separate(args, *, base_url, api_key, **kwargs):
try:
owner = scope(kwargs)
root = home() / 'audio-separation' / owner
root.mkdir(parents=True, exist_ok=True, mode=0o700)
client = Client(base_url, api_key)
job_id = args.get('job_id', '')
if job_id and args.get('file_path'):
raise AudioError('Entweder file_path zum Starten oder job_id zum Abfragen angeben.')
if job_id:
if not re.fullmatch(r'[a-f0-9]{32}', job_id):
raise AudioError('Ungültige Auftrags-ID.')
folder = root / job_id
record_path = folder / 'job.json'
if not record_path.is_file():
raise AudioError('Auftrag gehört nicht zu dieser Sitzung oder wurde nicht gefunden.')
record = json.loads(record_path.read_text())
if record.get('result'):
return json.dumps(record['result'], ensure_ascii=False)
else:
if not args.get('file_path'):
raise AudioError('Bitte den Pfad der hochgeladenen MP3/Audiodatei angeben.')
source = source_path(args['file_path'])
# Resume same session/input after retries instead of launching duplicate GPU work.
stamp = source.stat()
fingerprint = hashlib.sha256(f'{source}:{stamp.st_size}:{stamp.st_mtime_ns}'.encode()).hexdigest()
for existing in root.glob('*/job.json'):
previous = json.loads(existing.read_text())
if previous.get('fingerprint') == fingerprint:
return _separate({'job_id': existing.parent.name}, base_url=base_url, api_key=api_key, **kwargs)
job_id = uuid.uuid4().hex
folder = root / job_id
folder.mkdir(mode=0o700)
record_path = folder / 'job.json'
record = {'fingerprint': fingerprint, 'remote_id': None, 'state': 'submitting'}
save(record_path, record)
with tempfile.TemporaryDirectory(prefix='athena-audio-') as temp:
converted = Path(temp) / 'input.wav'
decode(source, converted)
job = client.request('/api/v1/separator-chat/start', upload=converted)
record.update(remote_id=job['id'], state=job['state'])
save(record_path, record)
if not record.get('remote_id'):
raise AudioError('Ein früherer Start ist unbestätigt. Athena prüfen, bevor erneut gestartet wird.')
deadline = time.monotonic() + 15
while True:
job = client.request('/api/v1/separator-tests').get('job')
if not job or job.get('id') != record['remote_id']:
raise AudioError('Athena-Auftrag wurde ersetzt oder ist nicht mehr verfügbar. Keine fremden Ergebnisse werden übernommen.')
if job['state'] != 'running' or time.monotonic() >= deadline:
break
time.sleep(2)
if job['state'] == 'running':
return json.dumps({'state': 'running', 'job_id': job_id,
'next': 'Call athena_separate_audio again with this job_id; do not restart.'})
if job['state'] != 'complete':
raise AudioError('Athena konnte die Audiotrennung nicht abschließen. Trennprofil und GPU-Verfügbarkeit prüfen.')
files = job.get('files', [])
if len(files) != 2 or sum(f.get('name') == 'rest.wav' for f in files) != 1:
raise AudioError('Athena lieferte nicht die erwarteten zwei Spuren.')
outputs = []
for item in files:
destination = folder / ('Instrumental.wav' if item['name'] == 'rest.wav' else 'Vocals.wav')
client.download(record['remote_id'], item['index'], destination)
outputs.append({'name': destination.name, 'path': str(destination)})
result = {'state': 'complete', 'job_id': job_id, 'files': outputs,
'delivery': '\n'.join('MEDIA:' + f['path'] for f in outputs),
'instruction': 'Include both MEDIA: lines verbatim, each on its own line, in the final chat answer.'}
record.update(state='complete', result=result)
save(record_path, record)
return json.dumps(result, ensure_ascii=False)
except AudioError as exc:
return json.dumps({'state': 'error', 'error': str(exc)}, ensure_ascii=False)
except subprocess.TimeoutExpired:
return json.dumps({'state': 'error', 'error': 'Audio-Vorbereitung hat das Zeitlimit überschritten.'})
except Exception:
return json.dumps({'state': 'error', 'error': 'Dateizugriff oder Verbindung fehlgeschlagen; Athena und den Upload prüfen. Ein unbestätigter Start wird nicht automatisch wiederholt.'})