-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwhisper_fastapi.py
527 lines (448 loc) · 16.2 KB
/
whisper_fastapi.py
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
import asyncio
from functools import partial
from contextlib import asynccontextmanager
import aiohttp
import os
import sys
import dataclasses
import faster_whisper
import json
from fastapi.responses import PlainTextResponse, StreamingResponse
import wave
import pydub
import io
import hashlib
import argparse
import uvicorn
from typing import Annotated, Any, BinaryIO, Literal, Generator, Tuple, Iterable, Union
from fastapi import (
File,
HTTPException,
Query,
UploadFile,
Form,
FastAPI,
Request,
WebSocket,
)
from fastapi.middleware.cors import CORSMiddleware
from src.whisper_ctranslate2.writers import format_timestamp
from faster_whisper.transcribe import Segment, TranscriptionInfo
from faster_whisper.tokenizer import _LANGUAGE_CODES
import opencc
from prometheus_fastapi_instrumentator import Instrumentator
from wyoming.server import AsyncEventHandler, AsyncServer, partial
from wyoming.event import Event
from wyoming.audio import AudioChunk, AudioStop
from wyoming.asr import Transcribe, Transcript
from wyoming.info import Describe, Info
from wyoming.info import AsrModel, AsrProgram, Attribution, Info
# redirect print to stderr
_print = print
def print(*args, **kwargs):
_print(*args, file=sys.stderr, **kwargs)
parser = argparse.ArgumentParser()
parser.add_argument("--host", default="0.0.0.0", type=str)
parser.add_argument("--wyoming-uri", default="tcp://0.0.0.0:3001", type=str)
parser.add_argument("--port", default=5000, type=int)
parser.add_argument("--model", default="large-v3", type=str)
parser.add_argument("--device", default="auto", type=str)
parser.add_argument("--cache_dir", default=None, type=str)
parser.add_argument("--local_files_only", default=False, type=bool)
parser.add_argument("--threads", default=4, type=int)
args = parser.parse_args()
# for home assistant wyoming server
@asynccontextmanager
async def lifespan(_: FastAPI):
server = AsyncServer.from_uri(args.wyoming_uri)
print(f"Running wyoming server at {args.wyoming_uri}")
asyncio.create_task(server.run(partial(Handler)))
yield
app = FastAPI(lifespan=lifespan)
# Instrument your app with default metrics and expose the metrics
Instrumentator().instrument(app).expose(app, endpoint="/konele/metrics")
ccc = opencc.OpenCC("t2s.json")
print(f"Loading model to device {args.device}...")
model = faster_whisper.WhisperModel(
model_size_or_path=args.model,
device=args.device,
cpu_threads=args.threads,
local_files_only=args.local_files_only,
)
print(f"Model loaded to device {model.model.device}")
# allow all cors
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
async def gpt_refine_text(
ge: Generator[Segment, None, None], info: TranscriptionInfo, context: str
) -> str:
text = build_json_result(ge, info).text.strip()
model = os.environ.get("OPENAI_LLM_MODEL", "gpt-4o-mini")
if not text:
return ""
body: dict = {
"model": model,
"temperature": 0.1,
"stream": False,
"messages": [
{
"role": "system",
"content": f"""
You are a audio transcription text refiner. You may refer to the context to correct the transcription text.
Your task is to correct the transcribed text by removing redundant and repetitive words, resolving any contradictions, and fixing punctuation errors.
Keep my spoken language as it is, and do not change my speaking style. Only fix the text.
Response directly with the text.
""".strip(),
},
{
"role": "user",
"content": f"""
context: {context}
---
transcription: {text}
""".strip(),
},
],
}
print(f"Refining text length: {len(text)} with {model}")
print(body)
async with aiohttp.ClientSession() as session:
async with session.post(
os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1")
+ "/chat/completions",
json=body,
headers={
"Authorization": f'Bearer {os.environ["OPENAI_API_KEY"]}',
},
) as response:
return (await response.json())["choices"][0]["message"]["content"]
def stream_writer(generator: Generator[Segment, Any, None]):
for segment in generator:
yield "data: " + json.dumps(segment, ensure_ascii=False) + "\n\n"
yield "data: [DONE]\n\n"
def text_writer(generator: Generator[Segment, Any, None]):
for segment in generator:
yield segment.text.strip() + "\n"
def tsv_writer(generator: Generator[Segment, Any, None]):
yield "start\tend\ttext\n"
for i, segment in enumerate(generator):
start_time = str(round(1000 * segment.start))
end_time = str(round(1000 * segment.end))
text = segment.text.strip()
yield f"{start_time}\t{end_time}\t{text}\n"
def srt_writer(generator: Generator[Segment, Any, None]):
for i, segment in enumerate(generator):
start_time = format_timestamp(
segment.start, decimal_marker=",", always_include_hours=True
)
end_time = format_timestamp(
segment.end, decimal_marker=",", always_include_hours=True
)
text = segment.text.strip()
yield f"{i}\n{start_time} --> {end_time}\n{text}\n\n"
def vtt_writer(generator: Generator[Segment, Any, None]):
yield "WEBVTT\n\n"
for _, segment in enumerate(generator):
start_time = format_timestamp(segment.start)
end_time = format_timestamp(segment.end)
text = segment.text.strip()
yield f"{start_time} --> {end_time}\n{text}\n\n"
@dataclasses.dataclass
class JsonResult(TranscriptionInfo):
segments: list[Segment]
text: str
def build_json_result(
generator: Iterable[Segment],
info: TranscriptionInfo,
) -> JsonResult:
segments = [i for i in generator]
return JsonResult(
text="\n".join(i.text for i in segments),
segments=segments,
**dataclasses.asdict(info),
)
def stream_builder(
audio: BinaryIO,
task: str,
vad_filter: bool,
language: str | None,
initial_prompt: str = "",
repetition_penalty: float = 1.0,
) -> Tuple[Generator[Segment, None, None], TranscriptionInfo]:
segments, info = model.transcribe(
audio=audio,
language=language,
task=task,
vad_filter=vad_filter,
initial_prompt=initial_prompt if initial_prompt else None,
word_timestamps=True,
repetition_penalty=repetition_penalty,
)
print(
"Detected language '%s' with probability %f"
% (info.language, info.language_probability)
)
def wrap():
for segment in segments:
if info.language == "zh":
segment.text = ccc.convert(segment.text)
yield segment
return wrap(), info
@app.websocket("/k6nele/status")
@app.websocket("/konele/status")
@app.websocket("/v1/k6nele/status")
@app.websocket("/v1/konele/status")
async def konele_status(
websocket: WebSocket,
):
await websocket.accept()
await websocket.send_json(dict(num_workers_available=1))
await websocket.close()
@app.websocket("/k6nele/ws")
@app.websocket("/konele/ws")
@app.websocket("/konele/ws/gpt_refine")
@app.websocket("/k6nele/ws/gpt_refine")
@app.websocket("/v1/k6nele/ws")
@app.websocket("/v1/konele/ws")
@app.websocket("/v1/konele/ws/gpt_refine")
@app.websocket("/v1/k6nele/ws/gpt_refine")
async def konele_ws(
websocket: WebSocket,
task: Literal["transcribe", "translate"] = "transcribe",
lang: str = "und",
initial_prompt: str = "",
vad_filter: bool = False,
content_type: Annotated[str, Query(alias="content-type")] = "audio/x-raw",
):
await websocket.accept()
# convert lang code format (eg. en-US to en)
lang = lang.split("-")[0]
data = b""
while True:
try:
data += await websocket.receive_bytes()
if data[-3:] == b"EOS":
break
except:
break
md5 = hashlib.md5(data).hexdigest()
# create fake file for wave.open
file_obj = io.BytesIO()
if content_type.startswith("audio/x-flac"):
pydub.AudioSegment.from_file(io.BytesIO(data), format="flac").export(
file_obj, format="wav"
)
else:
buffer = wave.open(file_obj, "wb")
buffer.setnchannels(1)
buffer.setsampwidth(2)
buffer.setframerate(16000)
buffer.writeframes(data)
file_obj.seek(0)
generator, info = stream_builder(
audio=file_obj,
task=task,
vad_filter=vad_filter,
language=None if lang == "und" else lang,
initial_prompt=initial_prompt,
)
if websocket.url.path.endswith("gpt_refine"):
result = await gpt_refine_text(generator, info, initial_prompt)
else:
result = build_json_result(generator, info).text
await websocket.send_json(
{
"status": 0,
"segment": 0,
"result": {"hypotheses": [{"transcript": result}], "final": True},
"id": md5,
}
)
await websocket.close()
@app.post("/k6nele/post")
@app.post("/konele/post")
@app.post("/k6nele/post/gpt_refine")
@app.post("/konele/post/gpt_refine")
@app.post("/v1/k6nele/post")
@app.post("/v1/konele/post")
@app.post("/v1/k6nele/post/gpt_refine")
@app.post("/v1/konele/post/gpt_refine")
async def translateapi(
request: Request,
task: Literal["transcribe", "translate"] = "transcribe",
lang: str = "und",
initial_prompt: str = "",
vad_filter: bool = False,
):
content_type = request.headers.get("Content-Type", "")
# convert lang code format (eg. en-US to en)
lang = lang.split("-")[0]
splited = [i.strip() for i in content_type.split(",") if "=" in i]
info = {k: v for k, v in (i.split("=") for i in splited)}
channels = int(info.get("channels", "1"))
rate = int(info.get("rate", "16000"))
body = await request.body()
md5 = hashlib.md5(body).hexdigest()
# create fake file for wave.open
file_obj = io.BytesIO()
if content_type.startswith("audio/x-flac"):
pydub.AudioSegment.from_file(io.BytesIO(body), format="flac").export(
file_obj, format="wav"
)
else:
buffer = wave.open(file_obj, "wb")
buffer.setnchannels(channels)
buffer.setsampwidth(2)
buffer.setframerate(rate)
buffer.writeframes(body)
file_obj.seek(0)
generator, info = stream_builder(
audio=file_obj,
task=task,
vad_filter=vad_filter,
language=None if lang == "und" else lang,
initial_prompt=initial_prompt,
)
if request.url.path.endswith("gpt_refine"):
result = await gpt_refine_text(generator, info, initial_prompt)
else:
result = build_json_result(generator, info).text
return {
"status": 0,
"hypotheses": [{"utterance": result}],
"id": md5,
}
@app.post("/v1/audio/transcriptions", response_model=Union[JsonResult, str])
@app.post("/v1/audio/translations", response_model=Union[JsonResult, str])
async def transcription(
request: Request,
file: UploadFile = File(...),
prompt: str = Form(""),
response_format: str = Form("json"),
task: str = Form(""),
language: str = Form("und"),
vad_filter: bool = Form(False),
repetition_penalty: float = Form(1.0),
gpt_refine: bool = Form(False),
):
"""Transcription endpoint
User upload audio file in multipart/form-data format and receive transcription in response
"""
if not task:
if request.url.path == "/v1/audio/transcriptions":
task = "transcribe"
elif request.url.path == "/v1/audio/translations":
task = "translate"
else:
raise HTTPException(400, "task parameter is required")
# timestamp as filename, keep original extension
generator, info = stream_builder(
audio=io.BytesIO(file.file.read()),
task=task,
vad_filter=vad_filter,
initial_prompt=prompt,
language=None if language == "und" else language,
repetition_penalty=repetition_penalty,
)
# special function for streaming response (OpenAI API does not have this)
if response_format == "stream":
return StreamingResponse(
stream_writer(generator),
media_type="text/event-stream",
)
elif response_format == "json":
return build_json_result(generator, info)
elif response_format == "text":
if gpt_refine:
return PlainTextResponse(await gpt_refine_text(generator, info, prompt))
return StreamingResponse(text_writer(generator), media_type="text/plain")
elif response_format == "tsv":
return StreamingResponse(tsv_writer(generator), media_type="text/plain")
elif response_format == "srt":
return StreamingResponse(srt_writer(generator), media_type="text/plain")
elif response_format == "vtt":
return StreamingResponse(vtt_writer(generator), media_type="text/plain")
raise HTTPException(400, "Invailed response_format")
# for home assitant
# code from https://github.com/rhasspy/wyoming-faster-whisper
class Handler(AsyncEventHandler):
file_obj: io.BytesIO | None = None
wav_file: wave.Wave_write | None = None
lang: str | None = None
async def handle_event(self, event: Event) -> bool:
if AudioChunk.is_type(event.type):
chunk = AudioChunk.from_event(event)
if self.wav_file is None:
print("AudioChunk begin")
self.file_obj = io.BytesIO()
self.wav_file = wave.open(self.file_obj, "wb")
self.wav_file.setframerate(chunk.rate)
self.wav_file.setsampwidth(chunk.width)
self.wav_file.setnchannels(chunk.channels)
self.wav_file.writeframes(chunk.audio)
return True
if AudioStop.is_type(event.type):
print("AudioStop")
assert self.wav_file is not None
assert self.file_obj is not None
self.wav_file.close()
self.wav_file = None
self.file_obj.seek(0)
generator, info = stream_builder(
audio=self.file_obj,
task="transcribe",
vad_filter=False,
language=self.lang,
)
text = build_json_result(generator, info).text
print(text)
await self.write_event(Transcript(text=text).event())
self.lang = None
return False
if Transcribe.is_type(event.type):
print("Transcribe")
transcribe = Transcribe.from_event(event)
if transcribe.language:
self.lang = transcribe.language
return True
if Describe.is_type(event.type):
print("Describe")
await self.write_event(
Info(
asr=[
AsrProgram(
name="whisper-forward",
description="Whisper forward to OpenAI API endpoint",
attribution=Attribution(
name="heimoshuiyu",
url="https://github.com/heimoshuiyu/whisper-fastapi",
),
installed=True,
version="0.1",
models=[
AsrModel(
name="whisper-1",
description="whisper-1",
attribution=Attribution(
name="Systran",
url="https://huggingface.co/Systran",
),
installed=True,
languages=list(
_LANGUAGE_CODES
), # pylint: disable=protected-access
version="0.1",
)
],
)
],
).event()
)
return True
return True
uvicorn.run(app, host=args.host, port=args.port)