KIFF commited on
Commit
ddc46b4
·
verified ·
1 Parent(s): de733c0

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +23 -17
handler.py CHANGED
@@ -3,48 +3,54 @@ from pyannote.audio import Pipeline
3
  import torch
4
  import base64
5
  import numpy as np
6
- import os
7
 
8
  SAMPLE_RATE = 16000
9
 
10
  class EndpointHandler():
11
  def __init__(self, path=""):
12
- self.pipeline = Pipeline.from_pretrained(
13
- "pyannote/[email protected]",
14
- use_auth_token=os.environ.get("HF_API_TOKEN")
15
- )
16
- self.pipeline.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
17
 
18
  def __call__(self, data: Dict) -> Dict:
19
  """
20
  Args:
21
  data (Dict):
22
  'inputs': Base64-encoded audio bytes
23
- 'parameters': Additional diarization parameters (currently unused)
24
  Return:
25
  Dict: Speaker diarization results
26
  """
27
  inputs = data.get("inputs")
28
- parameters = data.get("parameters", {}) # We are not using them now
29
 
30
  # Decode the base64 audio data
31
  audio_data = base64.b64decode(inputs)
32
  audio_nparray = np.frombuffer(audio_data, dtype=np.int16)
33
 
34
- # Handle multi-channel audio (convert to mono)
35
- if audio_nparray.ndim > 1:
36
- audio_nparray = audio_nparray.mean(axis=0) # Average channels to create mono
37
-
38
  # Convert to PyTorch tensor
39
  audio_tensor = torch.from_numpy(audio_nparray).float().unsqueeze(0)
40
- if audio_tensor.dim() == 1:
41
- audio_tensor = audio_tensor.unsqueeze(0)
42
-
43
  pyannote_input = {"waveform": audio_tensor, "sample_rate": SAMPLE_RATE}
44
 
45
- # Run diarization pipeline (without num_speakers)
 
 
 
46
  try:
47
- diarization = self.pipeline(pyannote_input) # No num_speakers parameter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  except Exception as e:
49
  print(f"An unexpected error occurred: {e}")
50
  return {"error": "Diarization failed unexpectedly"}
 
3
  import torch
4
  import base64
5
  import numpy as np
 
6
 
7
  SAMPLE_RATE = 16000
8
 
9
  class EndpointHandler():
10
  def __init__(self, path=""):
11
+ self.pipeline = Pipeline.from_pretrained("KIFF/pyannote-speaker-diarization-endpoint")
 
 
 
 
12
 
13
  def __call__(self, data: Dict) -> Dict:
14
  """
15
  Args:
16
  data (Dict):
17
  'inputs': Base64-encoded audio bytes
18
+ 'parameters': Additional diarization parameters, including 'num_speakers' (optional)
19
  Return:
20
  Dict: Speaker diarization results
21
  """
22
  inputs = data.get("inputs")
23
+ parameters = data.get("parameters", {}) # Default to empty dict if not provided
24
 
25
  # Decode the base64 audio data
26
  audio_data = base64.b64decode(inputs)
27
  audio_nparray = np.frombuffer(audio_data, dtype=np.int16)
28
 
 
 
 
 
29
  # Convert to PyTorch tensor
30
  audio_tensor = torch.from_numpy(audio_nparray).float().unsqueeze(0)
 
 
 
31
  pyannote_input = {"waveform": audio_tensor, "sample_rate": SAMPLE_RATE}
32
 
33
+ # Extract num_speakers from parameters, if present
34
+ num_speakers = parameters.pop("num_speakers", None)
35
+
36
+ # Run diarization pipeline
37
  try:
38
+ if num_speakers is not None:
39
+ diarization = self.pipeline(pyannote_input, num_speakers=num_speakers, **parameters)
40
+ else:
41
+ diarization = self.pipeline(pyannote_input, **parameters)
42
+ except TypeError as e:
43
+ print(f"Error: TypeError: {e}")
44
+ if "num_speakers" in str(e):
45
+ print("The 'num_speakers' parameter might not be supported by this version of the pipeline.")
46
+ print("Trying without num_speakers...")
47
+ try:
48
+ diarization = self.pipeline(pyannote_input, **parameters)
49
+ except Exception as e:
50
+ print(f"An error occurred even without 'num_speakers': {e}")
51
+ return {"error": "Diarization failed"}
52
+ else:
53
+ return {"error": "Diarization failed with an unexpected TypeError. Check the server logs for details."}
54
  except Exception as e:
55
  print(f"An unexpected error occurred: {e}")
56
  return {"error": "Diarization failed unexpectedly"}