Accept streamed browser audio uploads at transcription endpoint

This commit is contained in:
Mikei386 committed 2026-10-05 23:32:10 +02:00
1 parent cbf5f19c97
commit 2933f3aa1e
3 files changed
+61 -6

No files matched your search

+3 -1
View File
@@ -325,7 +325,9 @@ class APIHandler(BaseHTTPRequestHandler):
def transcription(self,ep):
if not ep.stt:raise APIError('STT-Laufzeit nicht eingerichtet.',501,'not_implemented')
try:
fields,audio=read_upload(self)
from stt import normalize_transcription_audio
fields,audio=read_upload(self,validate=False,allow_chunked=True)
audio=normalize_transcription_audio(audio)
if 'profile_id' in fields:raise ValueError('API-Profilname als model erforderlich.')
profile=ep.find_profile(fields.get('model'),'stt')
job=ep.stt.start(profile['id'],audio,fields.get('language','de'))
+37 -5
View File
@@ -22,15 +22,47 @@ def validate_wav(audio):
if len(w.readframes(w.getnframes()))!=w.getnframes()*2:raise ValueError('WAV-Datei ist unvollständig.')
except (wave.Error,EOFError):raise ValueError('Ungültige WAV-Datei.') from None
def read_upload(handler,validate=True,max_audio=MAX_AUDIO,allowed_fields=None,max_field=256):
def read_chunked_upload(handler,limit):
if handler.headers.get('Content-Length') is not None or handler.headers.get('Transfer-Encoding','').lower().strip()!='chunked':raise ValueError('Ungültige Chunked-Upload-Header.')
raw=bytearray()
while True:
line=handler.rfile.readline(1025)
if not line.endswith(b'\r\n') or len(line)>1024:raise ValueError('Ungültige Chunk-Länge.')
size_text=line[:-2].split(b';',1)[0]
if not size_text or any(c not in b'0123456789abcdefABCDEF' for c in size_text):raise ValueError('Ungültige Chunk-Länge.')
size=int(size_text,16)
if size==0:
if handler.rfile.readline(3)!=b'\r\n':raise ValueError('Upload-Trailer werden nicht unterstützt.')
return bytes(raw)
if len(raw)+size>limit:raise ValueError('Audio-Upload zu groß.')
chunk=handler.rfile.read(size)
if len(chunk)!=size or handler.rfile.read(2)!=b'\r\n':raise ValueError('Chunked Upload unvollständig.')
raw.extend(chunk)
def normalize_transcription_audio(audio):
try:validate_wav(audio);return audio
except ValueError:pass
if not isinstance(audio,bytes) or not 1<=len(audio)<=MAX_AUDIO:raise ValueError('Audiodatei bis 8 MiB erforderlich.')
try:
converted=subprocess.run(['ffmpeg','-nostdin','-v','error','-protocol_whitelist','pipe','-i','pipe:0','-t','121','-vn','-ac','1','-ar','16000','-f','s16le','pipe:1'],input=audio,capture_output=True,timeout=30)
except FileNotFoundError:raise ValueError('Audio-Konvertierung nicht verfügbar: ffmpeg fehlt.') from None
except subprocess.TimeoutExpired:raise ValueError('Audio-Konvertierung hat das Zeitlimit überschritten.') from None
if converted.returncode or not converted.stdout:raise ValueError('Audioformat konnte nicht gelesen werden. WAV, WebM, MP3, Ogg oder M4A verwenden.')
if len(converted.stdout)>120*16000*2:raise ValueError('Sprachaufnahme darf höchstens 120 Sekunden lang sein.')
out=io.BytesIO()
with wave.open(out,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(converted.stdout)
result=out.getvalue();validate_wav(result);return result
def read_upload(handler,validate=True,max_audio=MAX_AUDIO,allowed_fields=None,max_field=256,allow_chunked=False):
handler.connection.settimeout(30)
if handler.headers.get('Transfer-Encoding'):raise ValueError('Chunked Upload wird nicht unterstützt.')
chunked=bool(handler.headers.get('Transfer-Encoding'))
if chunked and not allow_chunked:raise ValueError('Chunked Upload wird nicht unterstützt.')
try:length=int(handler.headers.get('Content-Length','0'))
except ValueError:raise ValueError('Ungültige Upload-Länge.') from None
content_type=handler.headers.get('Content-Type','')
if not 0<length<=max_audio+65536 or not content_type.lower().startswith('multipart/form-data;'):raise ValueError(f'Multipart-Upload bis {max_audio//1024**2} MiB erforderlich.')
raw=handler.rfile.read(length)
if len(raw)!=length:raise ValueError('Upload unvollständig.')
if (not chunked and not 0<length<=max_audio+65536) or not content_type.lower().startswith('multipart/form-data;'):raise ValueError(f'Multipart-Upload bis {max_audio//1024**2} MiB erforderlich.')
raw=read_chunked_upload(handler,max_audio+65536) if chunked else handler.rfile.read(length)
if not chunked and len(raw)!=length:raise ValueError('Upload unvollständig.')
message=BytesParser(policy=policy.default).parsebytes(b'Content-Type: '+content_type.encode()+b'\r\nMIME-Version: 1.0\r\n\r\n'+raw)
if not message.is_multipart() or message.defects:raise ValueError('Ungültiger Multipart-Upload.')
fields={};audio=None
+21
View File
@@ -24,6 +24,27 @@ class STTTests(unittest.TestCase):
s=STT(None,None,SimpleNamespace(status=lambda:{'active':None}))
with self.assertRaises(ValueError):s.build()
class BrowserUploadTests(unittest.TestCase):
def handler(self,body,headers=None):
return SimpleNamespace(headers=headers or {'Transfer-Encoding':'chunked'},rfile=io.BytesIO(body))
def test_chunked_upload(self):
from stt import read_chunked_upload
self.assertEqual(read_chunked_upload(self.handler(b'3\r\nabc\r\n2;ext=yes\r\nde\r\n0\r\n\r\n'),5),b'abcde')
def test_invalid_chunked_uploads(self):
from stt import read_chunked_upload
for body in (b'6\r\nabcdef\r\n0\r\n\r\n',b'zz\r\n',b'3\r\nab',b'0\r\nx: y\r\n\r\n'):
with self.assertRaises(ValueError):read_chunked_upload(self.handler(body),5)
with self.assertRaises(ValueError):read_chunked_upload(self.handler(b'0\r\n\r\n',{'Transfer-Encoding':'chunked','Content-Length':'0'}),5)
def test_normalizes_non_16khz_wav(self):
from stt import normalize_transcription_audio
out=io.BytesIO()
with wave.open(out,'wb') as w:w.setnchannels(2);w.setsampwidth(2);w.setframerate(48000);w.writeframes(bytes(4800*4))
converted=normalize_transcription_audio(out.getvalue());validate_wav(converted)
with wave.open(io.BytesIO(converted)) as w:self.assertAlmostEqual(w.getnframes()/w.getframerate(),.1,places=2)
def test_rejects_invalid_audio(self):
from stt import normalize_transcription_audio
with self.assertRaisesRegex(ValueError,'Audioformat'):normalize_transcription_audio(b'not an audio file')
class ReferenceTranscriptionTests(unittest.TestCase):
def test_reference_normalized_and_transcribed_without_download(self):
import threading