spellingdragon commited on
Commit
694416b
1 Parent(s): 90adbf4

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +51 -0
handler.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers.pipelines.audio_utils import ffmpeg_read
3
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
4
+ from datasets import load_dataset
5
+
6
+ class EndpointHandler():
7
+ def __init__(self, path=""):
8
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
9
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
10
+ model_id = "openai/whisper-large-v3"
11
+ self.model = AutoModelForSpeechSeq2Seq.from_pretrained(
12
+ model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
13
+ )
14
+ model.to(device)
15
+
16
+ processor = AutoProcessor.from_pretrained(model_id)
17
+
18
+ self.pipeline = pipeline(
19
+ "automatic-speech-recognition",
20
+ model=model,
21
+ tokenizer=processor.tokenizer,
22
+ feature_extractor=processor.feature_extractor,
23
+ max_new_tokens=128,
24
+ chunk_length_s=30,
25
+ batch_size=16,
26
+ return_timestamps=True,
27
+ torch_dtype=torch_dtype,
28
+ device=device,
29
+ )
30
+
31
+
32
+ def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
33
+ """
34
+ Args:
35
+ data (:obj:):
36
+ includes the input data and the parameters for the inference.
37
+ Return:
38
+ A :obj:`list`:. The object returned should be a list of one list like [[{"label": 0.9939950108528137}]] containing :
39
+ - "label": A string representing what the label/class is. There can be multiple labels.
40
+ - "score": A score between 0 and 1 describing how confident the model is for this label/class.
41
+ """
42
+ inputs = data.pop("inputs", data)
43
+ parameters = data.pop("parameters", None)
44
+
45
+ # pass inputs with all kwargs in data
46
+ if parameters is not None:
47
+ result = self.pipeline(inputs, return_timestamps=True, **parameters)
48
+ else:
49
+ result = self.pipeline(inputs, return_timestamps=True, generate_kwargs={"task": "translate"})
50
+ # postprocess the prediction
51
+ return {"chunks": result["chunks"]}