File size: 13,385 Bytes
9fda066
b7fa1b5
5bcf187
b7fa1b5
 
5bcf187
c2fb837
 
3cf670e
5bcf187
b7fa1b5
 
 
6fccdc4
3cf670e
 
f8893d8
 
5bcf187
c2fb837
 
 
 
 
5bcf187
95d83f6
c2fb837
8cdbd94
 
 
 
 
 
 
 
95d83f6
c2fb837
 
 
 
 
 
95d83f6
 
c2fb837
 
 
 
 
 
 
 
 
0053d2c
5bcf187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7fa1b5
5bcf187
 
b7fa1b5
5bcf187
 
0053d2c
8cdbd94
c2fb837
 
 
 
5669eef
c2fb837
 
 
5bcf187
c2fb837
95d83f6
c2fb837
 
 
 
 
 
 
 
 
 
 
8cdbd94
c2fb837
 
6fccdc4
 
 
bd4cc90
6fccdc4
c2fb837
 
6fccdc4
c2fb837
 
6fccdc4
 
1354064
122eea4
870de60
 
122eea4
 
870de60
122eea4
 
870de60
 
 
 
 
1354064
 
a5e2883
870de60
c2fb837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95d83f6
d262e76
 
 
 
 
 
a5e2883
d262e76
 
a5e2883
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d262e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cf670e
 
6fccdc4
 
 
3cf670e
94ecbf5
3cf670e
 
 
 
 
c2fb837
3cf670e
 
c2fb837
3cf670e
 
c2fb837
3cf670e
 
5669eef
3cf670e
 
 
 
 
5bcf187
3cf670e
 
 
 
 
 
 
 
 
 
6fccdc4
99577ba
 
 
 
6fccdc4
 
3cf670e
 
 
95d83f6
 
 
 
c2fb837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5669eef
95d83f6
 
24a2822
790d7cc
 
c2fb837
6fccdc4
 
c2fb837
 
 
 
 
6fccdc4
 
d262e76
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import spaces
from pydub import AudioSegment
import os
import torchaudio
import torch
import re
import whisper_timestamped as whisper_ts
from typing import Dict
from faster_whisper import WhisperModel

device = 0 if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float32

DEBUG_MODE = True
MODEL_PATH_V2 = "langtech-veu/whisper-timestamped-cs"
MODEL_PATH_V2_FAST = "langtech-veu/faster-whisper-timestamped-cs"
#DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
#print("[INFO] CUDA available:", torch.cuda.is_available())

def clean_text(input_text):
    remove_chars = ['.', ',', ';', ':', '¿', '?', '«', '»', '-', '¡', '!', '@',
                    '*', '{', '}', '[', ']', '=', '/', '\\', '&', '#', '…']
    output_text = ''.join(char if char not in remove_chars else ' ' for char in input_text)
    return ' '.join(output_text.split()).lower()


def split_stereo_channels(audio_path):
    ext = os.path.splitext(audio_path)[1].lower()

    if ext == ".wav":
        audio = AudioSegment.from_wav(audio_path)
    elif ext == ".mp3":
        audio = AudioSegment.from_file(audio_path, format="mp3")
    else:
        raise ValueError(f"Unsupported file format: {audio_path}")

    channels = audio.split_to_mono()
    if len(channels) != 2:
        raise ValueError(f"Audio {audio_path} does not have 2 channels.")

    channels[0].export(f"temp_mono_speaker1.wav", format="wav")  # Right
    channels[1].export(f"temp_mono_speaker2.wav", format="wav")  # Left


def format_audio(audio_path):
    input_audio, sample_rate = torchaudio.load(audio_path)
    if input_audio.shape[0] == 2:
        input_audio = torch.mean(input_audio, dim=0, keepdim=True)
    resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)
    input_audio = resampler(input_audio)
    return input_audio.squeeze(), 16000
    
def post_process_transcription(transcription, max_repeats=2): 
    tokens = re.findall(r'\b\w+\'?\w*\b[.,!?]?', transcription)

    cleaned_tokens = []
    repetition_count = 0
    previous_token = None

    for token in tokens:
        reduced_token = re.sub(r"(\w{1,3})(\1{2,})", "", token)

        if reduced_token == previous_token:
            repetition_count += 1
            if repetition_count <= max_repeats:
                cleaned_tokens.append(reduced_token)
        else:
            repetition_count = 1
            cleaned_tokens.append(reduced_token)

        previous_token = reduced_token

    cleaned_transcription = " ".join(cleaned_tokens)
    cleaned_transcription = re.sub(r'\s+', ' ', cleaned_transcription).strip()

    return cleaned_transcription


def post_merge_consecutive_segments_from_text(transcription_text: str) -> str:
    segments = re.split(r'(\[SPEAKER_\d{2}\])', transcription_text)
    merged_transcription = ''
    current_speaker = None
    current_segment = []

    for i in range(1, len(segments) - 1, 2):
        speaker_tag = segments[i]
        text = segments[i + 1].strip()

        speaker = re.search(r'\d{2}', speaker_tag).group()

        if speaker == current_speaker:
            current_segment.append(text)
        else:
            if current_speaker is not None:
                merged_transcription += f'[SPEAKER_{current_speaker}] {" ".join(current_segment)}\n'
            current_speaker = speaker
            current_segment = [text]

    if current_speaker is not None:
        merged_transcription += f'[SPEAKER_{current_speaker}] {" ".join(current_segment)}\n'

    return merged_transcription.strip()

def cleanup_temp_files(*file_paths):

    if DEBUG_MODE: print(f"Entered cleanup_temp_files function...")

    if DEBUG_MODE: print(f"file_paths: {file_paths}")
        
    for path in file_paths:
        if path and os.path.exists(path):
            if DEBUG_MODE: print(f"Removing path: {path}")
            os.remove(path)

    if DEBUG_MODE: print(f"Exited cleanup_temp_files function.")

'''
try:
    faster_model = WhisperModel(
        MODEL_PATH_V2_FAST,
        device="cuda" if torch.cuda.is_available() else "cpu",
        compute_type="float16" if torch.cuda.is_available() else "int8"
    )
except RuntimeError as e:
    print(f"[WARNING] Failed to load model on GPU: {e}")
    faster_model = WhisperModel(
        MODEL_PATH_V2_FAST,
        device="cpu",
        compute_type="int8"
    )
'''

#faster_model = WhisperModel(MODEL_PATH_V2_FAST, device=DEVICE, compute_type="int8")

def load_whisper_model(model_path: str):
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model = whisper_ts.load_model(model_path, device=device)
    return model

def transcribe_audio(model, audio_path: str) -> Dict:
    try:
        result = whisper_ts.transcribe(
            model,
            audio_path,
            beam_size=5,
            best_of=5,
            temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
            vad=False,  
            detect_disfluencies=True,
        )
        
        words = []
        for segment in result.get('segments', []):
            for word in segment.get('words', []):
                word_text = word.get('word', '').strip()
                if word_text.startswith(' '):
                    word_text = word_text[1:]
                
                words.append({
                    'word': word_text,
                    'start': word.get('start', 0),
                    'end': word.get('end', 0),
                    'confidence': word.get('confidence', 0)
                })
        
        return {
            'audio_path': audio_path,
            'text': result['text'].strip(),
            'segments': result.get('segments', []),
            'words': words,
            'duration': result.get('duration', 0),
            'success': True
        }
        
    except Exception as e:
        return {
            'audio_path': audio_path,
            'error': str(e),
            'success': False
        }



def generate(audio_path, use_v2_fast):
    if DEBUG_MODE: print(f"Entering generate function...")
    if DEBUG_MODE: print(f"use_v2_fast: {use_v2_fast}")

    faster_model = None

    if use_v2_fast:
        if torch.cuda.is_available():
            try:
                if DEBUG_MODE: print("[INFO] GPU detected. Loading model on GPU with float16...")
                faster_model = WhisperModel(
                    MODEL_PATH_V2_FAST,
                    device="cuda",
                    compute_type="float16"
                )
            except RuntimeError as e:
                print(f"[WARNING] Failed to load model on GPU: {e}")
                if DEBUG_MODE: print("[INFO] Falling back to CPU with int8...")
                faster_model = WhisperModel(
                    MODEL_PATH_V2_FAST,
                    device="cpu",
                    compute_type="int8"
                )
        else:
            if DEBUG_MODE: print("[INFO] No GPU detected. Loading model on CPU with int8...")
            faster_model = WhisperModel(
                MODEL_PATH_V2_FAST,
                device="cpu",
                compute_type="int8"
            )
        split_stereo_channels(audio_path)
        left_channel_path = "temp_mono_speaker2.wav"
        right_channel_path = "temp_mono_speaker1.wav"

        left_waveform, _ = format_audio(left_channel_path)
        right_waveform, _ = format_audio(right_channel_path)

        left_waveform = left_waveform.numpy().astype("float32")
        right_waveform = right_waveform.numpy().astype("float32")

        left_result, _ = faster_model.transcribe(left_waveform, beam_size=5, task="transcribe")
        right_result, _ = faster_model.transcribe(right_waveform, beam_size=5, task="transcribe")

        left_result = list(left_result)
        right_result = list(right_result)

        def get_faster_segments(segments, speaker_label):
            return [
                (seg.start, seg.end, speaker_label, post_process_transcription(seg.text.strip()))
                for seg in segments if seg.text
            ]

        left_segs = get_faster_segments(left_result, "Speaker 1")
        right_segs = get_faster_segments(right_result, "Speaker 2")

        merged_transcript = sorted(
            left_segs + right_segs,
            key=lambda x: float(x[0]) if x[0] is not None else float("inf")
        )

        clean_output = ""
        for start, end, speaker, text in merged_transcript:
            clean_output += f"[{speaker}]: {text}\n"

        if DEBUG_MODE: print(f"clean_output: {clean_output}")

    else:
        model = load_whisper_model(MODEL_PATH_V2)
        split_stereo_channels(audio_path)
        left_channel_path = "temp_mono_speaker2.wav"
        right_channel_path = "temp_mono_speaker1.wav"

        left_waveform, _ = format_audio(left_channel_path)
        right_waveform, _ = format_audio(right_channel_path)

        left_result = transcribe_audio(model, left_waveform)
        right_result = transcribe_audio(model, right_waveform)

        def get_segments(result, speaker_label):
            segments = result.get("segments", [])
            if not segments:
                return []
            return [
                (seg.get("start", 0.0), seg.get("end", 0.0), speaker_label,
                 post_process_transcription(seg.get("text", "").strip()))
                for seg in segments if seg.get("text")
            ]

        left_segs = get_segments(left_result, "Speaker 1")
        right_segs = get_segments(right_result, "Speaker 2")

        merged_transcript = sorted(
            left_segs + right_segs,
            key=lambda x: float(x[0]) if x[0] is not None else float("inf")
        )

        clean_output = ""
        for start, end, speaker, text in merged_transcript:
            clean_output += f"[{speaker}]: {text}\n"

    cleanup_temp_files("temp_mono_speaker1.wav", "temp_mono_speaker2.wav")

    if DEBUG_MODE: print(f"Exiting generate function...")
    return clean_output.strip()

    
'''
def generate(audio_path, use_v2_fast):

    if DEBUG_MODE: print(f"Entering generate function...")
    if DEBUG_MODE: print(f"use_v2_fast: {use_v2_fast}")

    if use_v2_fast:
        split_stereo_channels(audio_path)
        left_channel_path = "temp_mono_speaker2.wav"
        right_channel_path = "temp_mono_speaker1.wav"
        
        left_waveform, left_sr = format_audio(left_channel_path)
        right_waveform, right_sr = format_audio(right_channel_path)

        left_waveform = left_waveform.numpy().astype("float32")
        right_waveform = right_waveform.numpy().astype("float32")

        left_result, info = faster_model.transcribe(left_waveform, beam_size=5, task="transcribe")
        right_result, info = faster_model.transcribe(right_waveform, beam_size=5, task="transcribe")

        left_result = list(left_result)
        right_result = list(right_result)

        def get_faster_segments(segments, speaker_label):
            return [
                (seg.start, seg.end, speaker_label, post_process_transcription(seg.text.strip()))
                for seg in segments if seg.text
            ]

        left_segs = get_faster_segments(left_result, "Speaker 1")
        right_segs = get_faster_segments(right_result, "Speaker 2")
                
        merged_transcript = sorted(
            left_segs + right_segs,
            key=lambda x: float(x[0]) if x[0] is not None else float("inf")
        )
        
        clean_output = ""
        for start, end, speaker, text in merged_transcript:
            clean_output += f"[{speaker}]: {text}\n"     

        # FIX Seems that post_merge_consecutive_segments_from_text returns an empty string
        #clean_output = post_merge_consecutive_segments_from_text(clean_output) 
        #print('clean_output',clean_output)      

        if DEBUG_MODE: print(f"clean_output: {clean_output}")
        
    else: 
        model = load_whisper_model(MODEL_PATH_V2)
        split_stereo_channels(audio_path)

        left_channel_path = "temp_mono_speaker2.wav"
        right_channel_path = "temp_mono_speaker1.wav"
        
        left_waveform, left_sr = format_audio(left_channel_path)
        right_waveform, right_sr = format_audio(right_channel_path)
        left_result = transcribe_audio(model, left_waveform)
        right_result = transcribe_audio(model, right_waveform)

        def get_segments(result, speaker_label):
            segments = result.get("segments", [])
            if not segments:
                return []
            return [
                (seg.get("start", 0.0), seg.get("end", 0.0), speaker_label, post_process_transcription(seg.get("text", "").strip()))
                for seg in segments if seg.get("text")
            ]

        left_segs = get_segments(left_result, "Speaker 1")
        right_segs = get_segments(right_result, "Speaker 2")

        merged_transcript = sorted(
            left_segs + right_segs,
            key=lambda x: float(x[0]) if x[0] is not None else float("inf")
        )     
        
        output = ""
        for start, end, speaker, text in merged_transcript:
            output += f"[{speaker}]: {text}\n"        
       
        clean_output = output.strip()

    if DEBUG_MODE: print(f"Clean output generated.")

    cleanup_temp_files(
        "temp_mono_speaker1.wav",
        "temp_mono_speaker2.wav"
    )

    if DEBUG_MODE: print(f"Exiting generate function...")
        
    return clean_output
'''