FD900 commited on
Commit
a6908e4
·
verified ·
1 Parent(s): f0df228

Update tools/speech_recognition_tool.py

Browse files
Files changed (1) hide show
  1. tools/speech_recognition_tool.py +107 -0
tools/speech_recognition_tool.py CHANGED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import Tool
2
+ import torch
3
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline, logging
4
+ import warnings
5
+
6
+
7
+ class SpeechRecognitionTool(Tool):
8
+ name = 'speech_to_text'
9
+ description = 'Transcribes spoken audio to text with optional time markers.'
10
+
11
+ inputs = {
12
+ 'audio': {
13
+ 'type': 'string',
14
+ 'description': 'Local path to the audio file to transcribe.',
15
+ },
16
+ 'with_time_markers': {
17
+ 'type': 'boolean',
18
+ 'description': 'Include timestamps in output.',
19
+ 'nullable': True,
20
+ 'default': False,
21
+ },
22
+ }
23
+
24
+ output_type = 'string'
25
+
26
+ chunk_length_s = 30 # chunk length for inference
27
+
28
+ def __new__(cls, *args, **kwargs):
29
+ device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
30
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
31
+
32
+ model_id = 'openai/whisper-large-v3-turbo'
33
+
34
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
35
+ model_id,
36
+ torch_dtype=dtype,
37
+ low_cpu_mem_usage=True,
38
+ use_safetensors=True,
39
+ ).to(device)
40
+
41
+ processor = AutoProcessor.from_pretrained(model_id)
42
+
43
+ logging.set_verbosity_error()
44
+ warnings.filterwarnings("ignore", category=FutureWarning)
45
+
46
+ cls.pipe = pipeline(
47
+ task='automatic-speech-recognition',
48
+ model=model,
49
+ tokenizer=processor.tokenizer,
50
+ feature_extractor=processor.feature_extractor,
51
+ torch_dtype=dtype,
52
+ device=device,
53
+ chunk_length_s=cls.chunk_length_s,
54
+ return_timestamps=True,
55
+ )
56
+
57
+ return super().__new__(cls, *args, **kwargs)
58
+
59
+ def forward(self, audio: str, with_time_markers: bool = False) -> str:
60
+ """
61
+ Run speech recognition on the input audio file.
62
+
63
+ Args:
64
+ audio (str): Path to a local .wav or .mp3 file
65
+ with_time_markers (bool): Whether to return chunked timestamps
66
+
67
+ Returns:
68
+ str: Transcript or chunked transcript with [start]\n[text]\n[end]
69
+ """
70
+ result = self.pipe(audio)
71
+
72
+ if not with_time_markers:
73
+ return result['text'].strip()
74
+
75
+ chunks = self._normalize_chunks(result['chunks'])
76
+
77
+ lines = []
78
+ for ch in chunks:
79
+ lines.append(f"[{ch['start']:.2f}]\n{ch['text']}\n[{ch['end']:.2f}]")
80
+
81
+ return "\n".join(lines).strip()
82
+
83
+ def _normalize_chunks(self, chunks):
84
+ offset = 0.0
85
+ chunk_offset = 0.0
86
+ norm_chunks = []
87
+
88
+ for chunk in chunks:
89
+ ts_start, ts_end = chunk['timestamp']
90
+ if ts_start < chunk_offset:
91
+ offset += self.chunk_length_s
92
+ chunk_offset = ts_start
93
+
94
+ start = offset + ts_start
95
+ if ts_end < ts_start:
96
+ offset += self.chunk_length_s
97
+ end = offset + ts_end
98
+ chunk_offset = ts_end
99
+
100
+ if chunk['text'].strip():
101
+ norm_chunks.append({
102
+ 'start': start,
103
+ 'end': end,
104
+ 'text': chunk['text'].strip(),
105
+ })
106
+
107
+ return norm_chunks