Create handler.py
Browse files- handler.py +41 -0
handler.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict
|
2 |
+
from transformers.pipelines.audio_utils import ffmpeg_read, WhisperProcessor, WhisperForConditionalGeneration
|
3 |
+
from datasets import load_dataset
|
4 |
+
|
5 |
+
import torch
|
6 |
+
|
7 |
+
SAMPLE_RATE = 16000
|
8 |
+
|
9 |
+
class EndpointHandler():
|
10 |
+
def __init__(self, path=""):
|
11 |
+
# load the model
|
12 |
+
#self.model = whisper.load_model("medium")
|
13 |
+
self.processor = WhisperProcessor.from_pretrained("openai/whisper-large-v2")
|
14 |
+
self.model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v2")
|
15 |
+
self.forced_decoder_ids = processor.get_decoder_prompt_ids(language="french", task="transcribe")
|
16 |
+
|
17 |
+
|
18 |
+
def __call__(self, data: Dict[str, bytes]) -> Dict[str, str]:
|
19 |
+
"""
|
20 |
+
Args:
|
21 |
+
data (:obj:):
|
22 |
+
includes the deserialized audio file as bytes
|
23 |
+
Return:
|
24 |
+
A :obj:`dict`:. base64 encoded image
|
25 |
+
"""
|
26 |
+
# process input
|
27 |
+
inputs = data.pop("inputs", data)
|
28 |
+
audio_nparray = ffmpeg_read(inputs, SAMPLE_RATE)
|
29 |
+
audio_tensor= torch.from_numpy(audio_nparray)
|
30 |
+
|
31 |
+
#ds = load_dataset("common_voice", "fr", split="test", streaming=True)
|
32 |
+
#ds = ds.cast_column("audio", Audio(sampling_rate=16_000))
|
33 |
+
#input_speech = next(iter(ds))["audio"]
|
34 |
+
#input_features = processor(input_speech["array"], sampling_rate=input_speech["sampling_rate"], return_tensors="pt").input_features
|
35 |
+
|
36 |
+
|
37 |
+
# run inference pipeline
|
38 |
+
result = self.model.transcribe(audio_nparray)
|
39 |
+
|
40 |
+
# postprocess the prediction
|
41 |
+
return {"text": result["text"]}
|