Files
Athena-Deck/integrations/openwebui/athena_audio.py
T

202 lines
11 KiB
Python

"""
title: Athena Audio-Trennung
author: Athena Deck
description: Trennt hochgeladene Audiodateien auf Athena und liefert einzelne WAV-Spuren mit Vorschau und Download.
version: 1.0.0
"""
import asyncio
import tempfile
import time
import wave
from pathlib import Path
from typing import Literal
import aiohttp
from pydantic import BaseModel, Field
TARGETS = {
'vocals': ('model_bs_roformer_ep_317_sdr_12.9755.ckpt', 'Vocals', 'Instrumental'),
'drums': ('htdemucs_ft.yaml', 'Drums', 'Rest'),
'bass': ('htdemucs_ft.yaml', 'Bass', 'Rest'),
'guitar': ('htdemucs_6s.yaml', 'Guitar', 'Rest'),
'piano': ('htdemucs_6s.yaml', 'Piano', 'Rest'),
'other': ('htdemucs_6s.yaml', 'Other', 'Rest'),
'speech': ('MossFormer2_SE_48K', 'Speech', 'Background'),
}
AUDIO_EXTENSIONS = {'.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.opus', '.aiff', '.aif', '.webm'}
MAX_BYTES = 256 * 1024 ** 2
class Tools:
class Valves(BaseModel):
DECK_URL: str = Field(default='http://192.168.1.212:8108', description='Athena Deck Verwaltungsadresse')
DECK_API_TOKEN: str = Field(default='', description='Bestehender Deck-API-Token; nur in den Administrator-Valves hinterlegen')
def __init__(self):
self.valves = self.Valves()
@staticmethod
def _attachment(files, filename):
candidates = {}
for item in files or []:
nested = item.get('file') or {}
name = item.get('name') or nested.get('filename') or nested.get('meta', {}).get('name', '')
ident = nested.get('id') or item.get('id')
if ident and Path(name).suffix.lower() in AUDIO_EXTENSIONS:
candidates[ident] = name
if filename:
candidates = {i: n for i, n in candidates.items() if filename in (i, n)}
if not candidates:
raise ValueError('Keine passende Audiodatei angehängt. Audio als Datei hochladen und erneut anfragen.')
if len(candidates) != 1:
raise ValueError('Mehrere Audiodateien angehängt. Bitte den Dateinamen der zu trennenden Datei nennen.')
return next(iter(candidates.items()))
@staticmethod
async def _decode(source, destination):
# Only a trusted storage path is passed; no shell, arbitrary URL or model-provided path.
process = await asyncio.create_subprocess_exec(
'ffmpeg', '-nostdin', '-v', 'error', '-i', str(source), '-map', '0:a:0',
'-vn', '-t', '1201', '-ac', '2', '-ar', '44100', '-c:a', 'pcm_s16le',
'-y', str(destination), stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
)
try:
await asyncio.wait_for(process.wait(), timeout=180)
finally:
if process.returncode is None:
process.kill()
await process.wait()
if process.returncode:
raise ValueError('Audiodatei konnte nicht gelesen werden. Format und Datei prüfen.')
if destination.stat().st_size > MAX_BYTES:
raise ValueError('Die aufbereitete Audiodatei überschreitet 256 MiB.')
with wave.open(str(destination)) as audio:
if not 0 < audio.getnframes() / audio.getframerate() <= 1200:
raise ValueError('Audio-Trennung unterstützt Dateien bis 20 Minuten; bitte kürzen.')
@staticmethod
async def _json(response):
payload = await response.json(content_type=None)
if response.status >= 400:
raise ValueError(payload.get('error') or 'Athena hat den Trennauftrag abgelehnt.')
return payload
async def separate_audio(
self,
target: Literal['vocals', 'drums', 'bass', 'guitar', 'piano', 'other', 'speech'] = 'vocals',
output: Literal['both', 'isolated', 'rest'] = 'both',
filename: str = '',
__files__: list = None,
__user__: dict = None,
__request__=None,
__event_emitter__=None,
) -> str:
"""Separate an uploaded song/audio into individual downloadable and playable WAV files.
Use vocals for Gesang/Stimme from music; speech for spoken-voice noise removal;
drums=Schlagzeug, bass=Bass, guitar=Gitarre, piano=Piano/Klavier, other=remaining instruments.
'Trenne Gesang' returns both vocals and instrumental by default (output=both).
'Gib mir nur den Gesang' uses isolated; 'Entferne Gesang'/karaoke uses rest.
Guitar/piano isolation is experimental and can contain bleed. Never invent a result.
filename is needed only if multiple audio attachments exist; choose an attached filename.
No ZIP needed: separate WAV files appear in this chat, with audio preview when opened.
"""
async def status(text, done=False):
if __event_emitter__:
await __event_emitter__({'type': 'status', 'data': {'description': text, 'done': done}})
try:
if target not in TARGETS or output not in ('both', 'isolated', 'rest'):
raise ValueError('Unbekannte Zielspur oder Ausgabeart.')
if not self.valves.DECK_API_TOKEN:
raise ValueError('Athena-API-Token fehlt in den Werkzeug-Einstellungen.')
if not __request__ or not __user__ or not __user__.get('id'):
raise ValueError('Benutzer oder OpenWebUI-Dateizugriff fehlt.')
from open_webui.models.users import Users
from open_webui.routers.files import get_file_by_id, upload_file_handler
from open_webui.storage.provider import Storage
from starlette.datastructures import UploadFile, Headers
ident, original_name = self._attachment(__files__, filename)
user = await Users.get_user_by_id(__user__['id'])
if user is None:
raise ValueError('Benutzer nicht gefunden.')
# The router verifies ownership/grants; attachment metadata is never trusted as a path.
record = await get_file_by_id(ident, user=user, db=None)
source = Path(await asyncio.to_thread(Storage.get_file, record.path))
if not source.is_file() or source.stat().st_size > MAX_BYTES:
raise ValueError('Audiodatei fehlt oder überschreitet 256 MiB.')
await status('Audiodatei vorbereiten')
base = self.valves.DECK_URL.rstrip('/')
headers = {'Authorization': 'Bearer ' + self.valves.DECK_API_TOKEN}
timeout = aiohttp.ClientTimeout(total=240)
async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session:
with tempfile.TemporaryDirectory(prefix='athena-audio-') as temporary:
converted = Path(temporary) / 'input.wav'
await self._decode(source, converted)
model, isolated_name, rest_name = TARGETS[target]
form = aiohttp.FormData()
form.add_field('model', model)
form.add_field('target', target)
with converted.open('rb') as stream:
form.add_field('file', stream, filename='input.wav', content_type='audio/wav')
async with session.post(base + '/api/v1/separator-chat/start', data=form) as response:
job = await self._json(response)
job_id = job['id']
deadline = time.monotonic() + 8000
last_phase = None
while job['state'] == 'running':
if time.monotonic() >= deadline:
raise ValueError('Trennung dauert zu lange. Den Auftrag in Athena prüfen.')
if job.get('phase') != last_phase:
last_phase = job.get('phase')
await status(last_phase or 'Audio trennen')
await asyncio.sleep(2)
async with session.get(base + '/api/v1/separator-tests') as response:
current = (await self._json(response)).get('job')
if not current or current.get('id') != job_id:
raise ValueError('Auftrag wurde durch einen anderen ersetzt. Ergebnisse in Athena prüfen.')
job = current
if job['state'] != 'complete':
raise ValueError(job.get('phase') or 'Audio-Trennung fehlgeschlagen.')
await status('WAV-Spuren im Chat bereitstellen')
attachments = []
links = []
for item in job['files']:
is_rest = item['name'] == 'rest.wav'
if output == 'isolated' and is_rest or output == 'rest' and not is_rest:
continue
name = (rest_name if is_rest else isolated_name) + '.wav'
async with session.get(base + '/api/v1/separator-tests/audio', params={'id': job_id, 'index': item['index']}) as response:
if response.status != 200:
raise ValueError('Ergebnisspur konnte nicht geladen werden.')
with tempfile.TemporaryFile() as stream:
size = 0
async for chunk in response.content.iter_chunked(1024 * 1024):
size += len(chunk)
if size > 512 * 1024 ** 2:
raise ValueError('Ergebnisspur überschreitet 512 MiB.')
stream.write(chunk)
stream.seek(0)
upload = UploadFile(file=stream, filename=name, headers=Headers({'content-type': 'audio/wav'}))
saved = await upload_file_handler(__request__, upload, metadata={}, process=False, user=user)
data = saved.model_dump() if hasattr(saved, 'model_dump') else saved
file_id = data['id']
url = '/api/v1/files/' + file_id + '/content'
attachments.append({'id': file_id, 'type': 'file', 'name': name, 'url': url,
'size': size, 'content_type': 'audio/wav', 'file': data})
links.append('[' + name + '](' + url + '?attachment=true)')
if not attachments:
raise ValueError('Keine passende Ergebnisspur vorhanden.')
if __event_emitter__:
await __event_emitter__({'type': 'chat:message:files', 'data': {'files': attachments}})
await status('Audio-Trennung fertig', done=True)
return 'Fertig: ' + ' · '.join(links) + '. Die WAV-Dateien sind im Chat angehängt. Zum Anhören einen Dateieintrag öffnen. Keine ZIP erforderlich.'
except asyncio.CancelledError:
# Deck owns the job independently. Do not cancel a potentially shared/finished GPU job.
raise
except Exception as exc:
# Never include HTTP headers, API credentials or arbitrary exception bodies in model context.
message = str(exc) if isinstance(exc, ValueError) else 'Dateizugriff oder Verbindung fehlgeschlagen. Athena und den Upload prüfen.'
await status(message, done=True)
return 'Audio-Trennung fehlgeschlagen: ' + message