Files
Athena-Deck/integrations/openwebui/test_audio.py

86 lines
4.4 KiB
Python

"""Run inside OpenWebUI; synthetic audio only, no existing chats or user files read.
Usage: python test_audio.py CONNECTION_JSON
"""
import asyncio
from datetime import timedelta
import io
import json
import math
from pathlib import Path
import struct
import sys
import tempfile
import wave
import aiohttp
from starlette.requests import Request
from starlette.datastructures import UploadFile, Headers
from open_webui.models.users import Users
from open_webui.routers.files import upload_file_handler
from open_webui.utils.auth import create_token
from open_webui.utils.middleware import process_tool_result
from athena_audio import Tools
async def main():
tool = Tools()
for files in ([], [{'id': 'a', 'name': 'a.wav'}, {'id': 'b', 'name': 'b.mp3'}]):
try:
tool._attachment(files, '')
except ValueError:
pass
else:
raise AssertionError('Missing/ambiguous attachment accepted')
assert tool._attachment([{'id': 'outer', 'file': {'id': 'stored', 'filename': 'song.wav'}}], '') == ('stored', 'song.wav')
user = next(u for u in (await Users.get_users())['users'] if u.role == 'admin')
token = create_token({'id': user.id}, timedelta(minutes=10))
request = Request({'type': 'http', 'method': 'POST', 'path': '/', 'headers': []})
data = io.BytesIO()
with wave.open(data, 'wb') as audio:
audio.setnchannels(2);audio.setsampwidth(2);audio.setframerate(44100)
audio.writeframes(b''.join(struct.pack('<hh', *(int(3000 * math.sin(i * 2 * math.pi * 440 / 44100)),) * 2) for i in range(44100 * 3)))
data.seek(0)
uploaded = await upload_file_handler(request, UploadFile(file=data, filename='athena-synthetic-test.wav', headers=Headers({'content-type': 'audio/wav'})), metadata={}, process=False, user=user)
connection = json.loads(Path(sys.argv[1]).read_text())
tool.valves.DECK_API_TOKEN = connection['token']
tool.valves.DECK_URL = 'http://192.168.1.212:8108'
events = []
async def emitter(event):
events.append(event)
file_ids = [uploaded.id]
try:
result = await tool.separate_audio(__files__=[{'id': uploaded.id, 'name': uploaded.filename}], __request__=request, __user__={'id': user.id}, __event_emitter__=emitter)
assert isinstance(result, tuple), result
context, _, embeds = await process_tool_result(request, 'separate_audio', result, 'tool', user=user)
assert len(embeds) == 1 and 'Audio-Trennung fertig' in context
files = [f for e in events if e['type'] == 'chat:message:files' for f in e['data']['files']]
file_ids.extend(f['id'] for f in files)
assert sorted(f['name'] for f in files) == ['Instrumental.wav', 'Vocals.wav'], result
for file in files:
assert file['name'] + ' herunterladen' in embeds[0]
assert file['url'] + '?attachment=true' in embeds[0]
async with aiohttp.ClientSession(headers={'Authorization': 'Bearer ' + token}) as session:
for file in files:
async with session.get('http://127.0.0.1:8080' + file['url']) as response:
assert response.status == 200
payload = await response.read()
assert payload[:4] == b'RIFF'
# Native FileItem audio preview authenticates with the existing login cookie.
async with session.get('http://127.0.0.1:8080' + files[0]['url'] + '?attachment=true', headers={'Authorization': ''}, cookies={'token': token}) as response:
assert response.status == 200
assert response.headers.get('Content-Disposition', '').startswith('attachment;')
async with aiohttp.ClientSession() as session:
async with session.get('http://127.0.0.1:8080' + files[0]['url']) as response:
assert response.status == 401
assert events[-1]['type'] == 'status' and events[-1]['data']['done']
print(json.dumps({'synthetic_separation': 'passed', 'files': [f['name'] for f in files], 'authenticated_download': 'passed', 'cookie_audio_preview': 'passed', 'anonymous_access': 'blocked', 'attachment_validation': 'passed'}, ensure_ascii=False))
finally:
async with aiohttp.ClientSession(headers={'Authorization': 'Bearer ' + token}) as session:
for ident in file_ids:
async with session.delete('http://127.0.0.1:8080/api/v1/files/' + ident):
pass
if __name__ == '__main__':
asyncio.run(main())