sergeipetrov commited on
Commit
c7d2a58
1 Parent(s): ea6360f

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +109 -0
handler.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import torch
3
+ import os
4
+
5
+ from pyannote.audio import Pipeline
6
+ from transformers import pipeline, AutoModelForCausalLM
7
+ from diarization_utils import diarize
8
+ from huggingface_hub import HfApi
9
+ from transformers.pipelines.audio_utils import ffmpeg_read
10
+ from pydantic import Json, BaseModel, ValidationError
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class InferenceConfig(BaseModel):
17
+ task: Literal["transcribe", "translate"] = "transcribe"
18
+ batch_size: int = 24
19
+ assisted: bool = False
20
+ chunk_length_s: int = 30
21
+ sampling_rate: int = 16000
22
+ language: Optional[str] = None
23
+ num_speakers: Optional[int] = None
24
+ min_speakers: Optional[int] = None
25
+ max_speakers: Optional[int] = None
26
+
27
+
28
+ class EndpointHandler():
29
+ def __init__(self):
30
+
31
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
32
+ logger.info(f"Using device: {device.type}")
33
+ torch_dtype = torch.float32 if device.type == "cpu" else torch.float16
34
+
35
+ self.assistant_model = AutoModelForCausalLM.from_pretrained(
36
+ os.getenv("ASSISTANT_MODEL"),
37
+ torch_dtype=torch_dtype,
38
+ low_cpu_mem_usage=True,
39
+ use_safetensors=True
40
+ ) if os.getenv("ASSISTANT_MODEL") else None
41
+
42
+ if self.assistant_model:
43
+ self.assistant_model.to(device)
44
+
45
+ self.asr_pipeline = pipeline(
46
+ "automatic-speech-recognition",
47
+ model=os.getenv("ASR_MODEL"),
48
+ torch_dtype=torch_dtype,
49
+ device=device
50
+ )
51
+
52
+ if os.getenv("DIARIZATION_MODEL"):
53
+ # diarization pipeline doesn't raise if there is no token
54
+ HfApi().whoami(model_settings.hf_token)
55
+ self.diarization_pipeline = Pipeline.from_pretrained(
56
+ checkpoint_path=os.getenv("DIARIZATION_MODEL"),
57
+ use_auth_token=os.getenv("HF_TOKEN"),
58
+ )
59
+ self.diarization_pipeline.to(device)
60
+ else:
61
+ self.diarization_pipeline = None
62
+
63
+ async def __call__(self, file, parameters):
64
+ try:
65
+ parameters = InferenceConfig(**parameters)
66
+ except ValidationError as e:
67
+ logger.error(f"Error validating parameters: {e}")
68
+ raise ValidationError(f"Error validating parameters: {e}")
69
+
70
+ logger.info(f"inference parameters: {parameters}")
71
+
72
+ generate_kwargs = {
73
+ "task": parameters.task,
74
+ "language": parameters.language,
75
+ "assistant_model": self.assistant_model if parameters.assisted else None
76
+ }
77
+
78
+ try:
79
+ asr_outputs = self.asr_pipeline(
80
+ file,
81
+ chunk_length_s=parameters.chunk_length_s,
82
+ batch_size=parameters.batch_size,
83
+ generate_kwargs=generate_kwargs,
84
+ return_timestamps=True,
85
+ )
86
+ except RuntimeError as e:
87
+ logger.error(f"ASR inference error: {str(e)}")
88
+ raise HTTPException(status_code=400, detail=f"ASR inference error: {str(e)}")
89
+ except Exception as e:
90
+ logger.error(f"Unknown error diring ASR inference: {str(e)}")
91
+ raise HTTPException(status_code=500, detail=f"Unknown error diring ASR inference: {str(e)}")
92
+
93
+ if self.diarization_pipeline:
94
+ try:
95
+ transcript = diarize(self.diarization_pipeline, file, parameters, asr_outputs)
96
+ except RuntimeError as e:
97
+ logger.error(f"Diarization inference error: {str(e)}")
98
+ raise HTTPException(status_code=400, detail=f"Diarization inference error: {str(e)}")
99
+ except Exception as e:
100
+ logger.error(f"Unknown error during diarization: {str(e)}")
101
+ raise HTTPException(status_code=500, detail=f"Unknown error during diarization: {str(e)}")
102
+ else:
103
+ transcript = []
104
+
105
+ return {
106
+ "speakers": transcript,
107
+ "chunks": asr_outputs["chunks"],
108
+ "text": asr_outputs["text"],
109
+ }