Kr08 commited on
Commit
745e5b6
·
verified ·
1 Parent(s): 81e4ee2

Update audio_processing.py

Browse files
Files changed (1) hide show
  1. audio_processing.py +99 -106
audio_processing.py CHANGED
@@ -1,112 +1,105 @@
 
1
  import torch
2
- import whisper
3
- import torchaudio as ta
4
- import gradio as gr
5
- from model_utils import get_processor, get_model, get_whisper_model_small, get_device
6
- from config import SAMPLING_RATE, CHUNK_LENGTH_S
7
- import spaces
8
-
9
-
10
- @spaces.GPU
11
- def load_and_resample_audio(audio):
12
- if isinstance(audio, str): # If audio is a file path
13
- waveform, sample_rate = ta.load(audio)
14
- else: # If audio is already loaded (sample_rate, waveform)
15
- sample_rate, waveform = audio
16
- waveform = torch.tensor(waveform).float()
17
-
18
- if sample_rate != SAMPLING_RATE:
19
- waveform = ta.functional.resample(waveform, sample_rate, SAMPLING_RATE)
20
-
21
- # Ensure the audio is in the correct shape (mono)
22
- if waveform.dim() > 1 and waveform.shape[0] > 1:
23
- waveform = waveform.mean(dim=0, keepdim=True)
24
- elif waveform.dim() == 1:
25
- waveform = waveform.unsqueeze(0)
26
-
27
- return waveform, SAMPLING_RATE
28
-
29
-
30
- @spaces.GPU
31
- def detect_language(waveform):
32
- whisper_model = get_whisper_model_small()
33
-
34
- # Use Whisper's preprocessing
35
- audio_tensor = whisper.pad_or_trim(waveform.squeeze())
36
- mel = whisper.log_mel_spectrogram(audio_tensor).to(whisper_model.device)
37
-
38
- # Detect language
39
- _, probs = whisper_model.detect_language(mel)
40
- detected_lang = max(probs, key=probs.get)
41
-
42
- print(f"Audio shape: {audio_tensor.shape}")
43
- print(f"Mel spectrogram shape: {mel.shape}")
44
- print(f"Detected language: {detected_lang}")
45
- print("Language probabilities:", probs)
46
-
47
- return detected_lang
48
-
49
-
50
- @spaces.GPU
51
- def process_long_audio(waveform, sample_rate, task="transcribe", language=None):
52
- input_length = waveform.shape[1]
53
- chunk_length = int(CHUNK_LENGTH_S * sample_rate)
54
 
55
- chunks = [waveform[:, i:i + chunk_length] for i in range(0, input_length, chunk_length)]
 
 
56
 
57
- processor = get_processor()
58
- model = get_model()
59
- device = get_device()
 
60
 
61
- results = []
62
- for chunk in chunks:
63
- input_features = processor(chunk.squeeze(), sampling_rate=sample_rate, return_tensors="pt").input_features.to(
64
- device)
65
 
66
- with torch.no_grad():
67
- if task == "translate":
68
- forced_decoder_ids = processor.get_decoder_prompt_ids(language=language, task="translate")
69
- generated_ids = model.generate(input_features, forced_decoder_ids=forced_decoder_ids)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  else:
71
- generated_ids = model.generate(input_features)
72
-
73
- transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)
74
- results.extend(transcription)
75
-
76
- # Clear GPU cache
77
- torch.cuda.empty_cache()
78
-
79
- return " ".join(results)
80
-
81
-
82
- @spaces.GPU
83
- def process_audio(audio):
84
- if audio is None:
85
- return "No file uploaded", "", ""
86
-
87
- waveform, sample_rate = load_and_resample_audio(audio)
88
-
89
- detected_lang = detect_language(waveform)
90
- transcription = process_long_audio(waveform, sample_rate, task="transcribe")
91
- translation = process_long_audio(waveform, sample_rate, task="translate", language=detected_lang)
92
-
93
- return detected_lang, transcription, translation
94
-
95
-
96
- # Gradio interface
97
- iface = gr.Interface(
98
- fn=process_audio,
99
- inputs=gr.Audio(),
100
- outputs=[
101
- gr.Textbox(label="Detected Language"),
102
- gr.Textbox(label="Transcription", lines=5),
103
- gr.Textbox(label="Translation", lines=5)
104
- ],
105
- title="Audio Transcription and Translation",
106
- description="Upload an audio file to detect its language, transcribe, and translate it.",
107
- allow_flagging="never",
108
- css=".output-textbox { font-family: 'Noto Sans Devanagari', sans-serif; font-size: 18px; }"
109
- )
110
-
111
- if __name__ == "__main__":
112
- iface.launch()
 
1
+ import whisperx
2
  import torch
3
+ import numpy as np
4
+ from scipy.signal import resample
5
+ import numpy as np
6
+ import whisperx
7
+ from pyannote.audio import Pipeline
8
+ import os
9
+ from dotenv import load_dotenv
10
+
11
+ load_dotenv()
12
+
13
+ hf_token = os.getenv("HF_TOKEN")
14
+ import whisperx
15
+ import torch
16
+ import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ import whisperx
19
+ import torch
20
+ import numpy as np
21
 
22
+ import whisperx
23
+ import torch
24
+ import numpy as np
25
+ CHUNK_LENGTH= 30
26
 
 
 
 
 
27
 
28
+ import whisperx
29
+ import torch
30
+ import numpy as np
31
+
32
+ def preprocess_audio(audio, chunk_size=CHUNK_LENGTH*16000): # 30 seconds at 16kHz
33
+ chunks = []
34
+ for i in range(0, len(audio), chunk_size):
35
+ chunk = audio[i:i+chunk_size]
36
+ if len(chunk) < chunk_size:
37
+ chunk = np.pad(chunk, (0, chunk_size - len(chunk)))
38
+ chunks.append(chunk)
39
+ return chunks
40
+
41
+ def process_audio(audio_file):
42
+ device = "cuda" if torch.cuda.is_available() else "cpu"
43
+ compute_type = "float32"
44
+ audio = whisperx.load_audio(audio_file)
45
+ model = whisperx.load_model("small", device, compute_type=compute_type)
46
+
47
+ # Initialize speaker diarization pipeline
48
+ diarization_pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token=hf_token)
49
+ diarization_pipeline = diarization_pipeline.to(torch.device(device))
50
+
51
+ # Perform diarization on the entire audio
52
+ diarization_result = diarization_pipeline({"waveform": torch.from_numpy(audio).unsqueeze(0), "sample_rate": 16000})
53
+
54
+
55
+ # Preprocess audio into consistent chunks
56
+ chunks = preprocess_audio(audio)
57
+
58
+ language_segments = []
59
+ final_segments = []
60
+
61
+ for i, chunk in enumerate(chunks):
62
+ # Detect language for this chunk
63
+ lang = model.detect_language(chunk)
64
+
65
+ # Transcribe this chunk
66
+ result = model.transcribe(chunk, language=lang)
67
+
68
+ chunk_start_time = i * 5 # Each chunk is 30 seconds
69
+
70
+ # Adjust timestamps and add language information
71
+ for segment in result["segments"]:
72
+ segment_start = chunk_start_time + segment["start"]
73
+ segment_end = chunk_start_time + segment["end"]
74
+ segment["start"] = segment_start
75
+ segment["end"] = segment_end
76
+ segment["language"] = lang
77
+
78
+ speakers = []
79
+ for turn, track, speaker in diarization_result.itertracks(yield_label=True):
80
+ if turn.start <= segment_end and turn.end >= segment_start:
81
+ speakers.append(speaker)
82
+ if speakers:
83
+ segment["speaker"] = max(set(speakers), key=speakers.count)
84
  else:
85
+ segment["speaker"] = "Unknown"
86
+
87
+ final_segments.append(segment)
88
+ # Add language segment
89
+ language_segments.append({
90
+ "language": lang,
91
+ "start": chunk_start_time,
92
+ "end": chunk_start_time + 5
93
+ })
94
+
95
+ return language_segments, final_segments
96
+
97
+ def print_results(language, language_probs, segments):
98
+ print(f"Detected Language: {language}")
99
+ print("Language Probabilities:")
100
+ for lang, prob in language_probs.items():
101
+ print(f" {lang}: {prob:.4f}")
102
+
103
+ print("\nTranscription:")
104
+ for segment in segments:
105
+ print(f"[{segment['start']:.2f}s - {segment['end']:.2f}s] Speaker {segment['speaker']}: {segment['text']}")