1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
| #!/usr/bin/env python3
"""Small adapter exposing one OpenAI-compatible ASR contract."""
import asyncio
import json
import os
import re
import tempfile
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, Response
from starlette.datastructures import UploadFile
UPSTREAM = "http://qwen3_asr:8000"
MAX_AUDIO_BYTES = 32 * 1024 * 1024
FFMPEG_TIMEOUT_SECONDS = 300
HOP_BY_HOP_HEADERS = {
"connection",
"content-encoding",
"content-length",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
}
ASR_METADATA_PATTERN = re.compile(
r"language\s+[^<\r\n]{1,80}\s*<asr_text>",
flags=re.IGNORECASE,
)
ASR_TEXT_TAG_PATTERN = re.compile(r"<asr_text>", flags=re.IGNORECASE)
def clean_asr_text(value: str) -> str:
# Qwen can emit a new language marker when the speaker switches language
# mid-utterance. Remove every metadata marker instead of only a leading one.
cleaned = ASR_METADATA_PATTERN.sub("", value)
return ASR_TEXT_TAG_PATTERN.sub("", cleaned).strip()
def clean_transcription_response(content: bytes, content_type: str) -> bytes:
if "application/json" in content_type:
try:
payload = json.loads(content)
except (json.JSONDecodeError, UnicodeDecodeError):
return content
if isinstance(payload, dict) and isinstance(payload.get("text"), str):
payload["text"] = clean_asr_text(payload["text"])
return json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
return content
if content_type.startswith("text/"):
try:
return clean_asr_text(content.decode()).encode()
except UnicodeDecodeError:
return content
return content
@asynccontextmanager
async def lifespan(app: FastAPI):
timeout = httpx.Timeout(connect=30, read=3600, write=3600, pool=30)
app.state.client = httpx.AsyncClient(timeout=timeout)
yield
await app.state.client.aclose()
app = FastAPI(
title="ASR Gateway",
docs_url=None,
redoc_url=None,
openapi_url=None,
lifespan=lifespan,
)
async def forward(request: Request, upstream_path: str, clean: bool = False) -> Response:
headers = {
key: value
for key, value in request.headers.items()
if key.lower() not in HOP_BY_HOP_HEADERS and key.lower() != "host"
}
async with app.state.client.stream(
request.method,
UPSTREAM + upstream_path,
params=request.query_params,
headers=headers,
content=request.stream(),
) as upstream:
content = await upstream.aread()
content_type = upstream.headers.get("content-type", "")
if clean and upstream.is_success:
content = clean_transcription_response(content, content_type)
response_headers = {
key: value
for key, value in upstream.headers.items()
if key.lower() not in HOP_BY_HOP_HEADERS
}
return Response(
content=content,
status_code=upstream.status_code,
headers=response_headers,
)
async def normalize_audio(upload: UploadFile, workdir: str) -> str:
"""Convert browser/vendor audio containers to deterministic PCM WAV."""
input_path = os.path.join(workdir, "input-audio")
output_path = os.path.join(workdir, "normalized.wav")
total = 0
with open(input_path, "wb") as destination:
while chunk := await upload.read(1024 * 1024):
total += len(chunk)
if total > MAX_AUDIO_BYTES:
raise HTTPException(status_code=413, detail="Audio file exceeds 32 MiB.")
destination.write(chunk)
if total == 0:
raise HTTPException(status_code=400, detail="Audio file is empty.")
process = await asyncio.create_subprocess_exec(
"ffmpeg",
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-i",
input_path,
"-vn",
"-ac",
"1",
"-ar",
"16000",
"-c:a",
"pcm_s16le",
output_path,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
try:
_, stderr = await asyncio.wait_for(
process.communicate(), timeout=FFMPEG_TIMEOUT_SECONDS
)
except TimeoutError as error:
process.kill()
await process.communicate()
raise HTTPException(status_code=504, detail="Audio conversion timed out.") from error
if process.returncode != 0 or not os.path.exists(output_path):
detail = stderr.decode(errors="replace").strip()[-500:]
raise HTTPException(
status_code=415,
detail="Unsupported or damaged audio file." + (" " + detail if detail else ""),
)
return output_path
async def forward_transcription(request: Request, parts: list[tuple]) -> Response:
headers = {
key: value
for key, value in request.headers.items()
if key.lower() not in HOP_BY_HOP_HEADERS
and key.lower() not in {"host", "content-type"}
}
upstream = await app.state.client.post(
UPSTREAM + "/v1/audio/transcriptions",
params=request.query_params,
headers=headers,
files=parts,
)
content_type = upstream.headers.get("content-type", "")
content = upstream.content
if upstream.is_success:
content = clean_transcription_response(content, content_type)
response_headers = {
key: value
for key, value in upstream.headers.items()
if key.lower() not in HOP_BY_HOP_HEADERS
}
return Response(
content=content,
status_code=upstream.status_code,
headers=response_headers,
)
@app.get("/")
async def service_info() -> JSONResponse:
return JSONResponse(
{
"service": "asr-gateway",
"contract": "openai-audio-transcriptions-v1",
"models": "/v1/models",
"transcriptions": "/v1/audio/transcriptions",
}
)
@app.get("/health")
async def health(request: Request) -> Response:
return await forward(request, "/health")
@app.get("/v1/models")
async def models(request: Request) -> Response:
return await forward(request, "/v1/models")
@app.post("/v1/audio/transcriptions")
async def transcriptions(request: Request) -> Response:
form = await request.form(max_files=4, max_fields=32, max_part_size=MAX_AUDIO_BYTES)
upload = form.get("file")
if not isinstance(upload, UploadFile):
raise HTTPException(status_code=400, detail="Multipart field 'file' is required.")
fields = [
(key, (None, str(value)))
for key, value in form.multi_items()
if key != "file" and not isinstance(value, UploadFile)
]
with tempfile.TemporaryDirectory(prefix="asr-gateway-") as workdir:
normalized_path = await normalize_audio(upload, workdir)
with open(normalized_path, "rb") as normalized:
parts = [("file", ("audio.wav", normalized, "audio/wav")), *fields]
return await forward_transcription(request, parts)
|