48 lines
1.6 KiB
Python
48 lines
1.6 KiB
Python
"""HTTP adapters for short voice input; no audio is stored or added to history."""
|
|
|
|
from io import BytesIO
|
|
|
|
from flask import Blueprint, Request, request
|
|
from werkzeug.exceptions import RequestEntityTooLarge
|
|
|
|
from .. import speech_service
|
|
|
|
|
|
bp = Blueprint('speech', __name__)
|
|
|
|
|
|
class MemoryAudioRequest(Request):
|
|
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None):
|
|
if self.path == '/api/speech/transcribe':
|
|
return BytesIO()
|
|
return super()._get_file_stream(total_content_length, content_type, filename, content_length)
|
|
|
|
|
|
@bp.after_request
|
|
def no_cache(response):
|
|
response.headers['Cache-Control'] = 'no-store'
|
|
return response
|
|
|
|
|
|
@bp.get('/api/speech/config')
|
|
def speech_config():
|
|
return {'enabled': speech_service.speech_enabled(), 'max_seconds': speech_service.MAX_DURATION_SECONDS,
|
|
'max_bytes': speech_service.MAX_AUDIO_BYTES}, {'Cache-Control': 'no-store'}
|
|
|
|
|
|
@bp.post('/api/speech/transcribe')
|
|
def speech_transcribe():
|
|
request.max_content_length = speech_service.MAX_AUDIO_BYTES + 64 * 1024
|
|
if not speech_service.speech_enabled():
|
|
return {'ok': False, 'error': speech_service.UNAVAILABLE}, 503
|
|
try:
|
|
files = request.files
|
|
try:
|
|
return speech_service.transcribe_recording(files.get('audio'), request.form.get('duration'),
|
|
request.form.get('language'))
|
|
finally:
|
|
for _, upload in files.items(multi=True):
|
|
upload.close()
|
|
except RequestEntityTooLarge:
|
|
return {'ok': False, 'error': '录音文件过大,请缩短后重试。'}, 413
|