Update test3.py
Browse files
test3.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
import argparse
|
2 |
import os
|
|
|
3 |
from helpers import *
|
4 |
from faster_whisper import WhisperModel
|
5 |
import whisperx
|
@@ -9,206 +10,224 @@ from nemo.collections.asr.models.msdd_models import NeuralDiarizer
|
|
9 |
import logging
|
10 |
import shutil
|
11 |
import srt
|
|
|
|
|
12 |
|
13 |
mtypes = {"cpu": "int8", "cuda": "float16"}
|
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 |
-
help="Language spoken in the audio, specify None to perform language detection",
|
53 |
-
)
|
54 |
-
parser.add_argument(
|
55 |
-
"--device",
|
56 |
-
dest="device",
|
57 |
-
default="cuda" if torch.cuda.is_available() else "cpu",
|
58 |
-
help="if you have a GPU use 'cuda', otherwise 'cpu'",
|
59 |
-
)
|
60 |
-
args = parser.parse_args()
|
61 |
-
|
62 |
-
if args.stemming:
|
63 |
-
# Isolate vocals from the rest of the audio
|
64 |
-
return_code = os.system(
|
65 |
-
f'python3 -m demucs.separate -n htdemucs --two-stems=vocals "{args.audio}" -o "temp_outputs"'
|
66 |
-
)
|
67 |
-
if return_code != 0:
|
68 |
-
logging.warning(
|
69 |
-
"Source splitting failed, using original audio file. Use --no-stem argument to disable it."
|
70 |
)
|
71 |
-
vocal_target = args.audio
|
72 |
else:
|
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 |
-
mtypes[args.device],
|
101 |
-
args.suppress_numerals,
|
102 |
-
args.device,
|
103 |
)
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
108 |
)
|
109 |
-
|
110 |
-
|
|
|
|
|
|
|
111 |
)
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
|
|
|
|
116 |
)
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
), (
|
124 |
-
f"Unsupported language: {language}, use --batch_size to 0"
|
125 |
-
" to generate word timestamps using whisper directly and fix this error."
|
126 |
)
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
# Reading timestamps <> Speaker Labels mapping
|
147 |
-
speaker_ts = []
|
148 |
-
with open(os.path.join(temp_path, "pred_rttms", "mono_file.rttm"), "r") as f:
|
149 |
-
lines = f.readlines()
|
150 |
-
for line in lines:
|
151 |
-
line_list = line.split(" ")
|
152 |
-
s = int(float(line_list[5]) * 1000)
|
153 |
-
e = s + int(float(line_list[8]) * 1000)
|
154 |
-
speaker_ts.append([s, e, int(line_list[11].split("_")[-1])])
|
155 |
-
|
156 |
-
wsm = get_words_speaker_mapping(word_timestamps, speaker_ts, "start")
|
157 |
-
wsm = get_realigned_ws_mapping_with_punctuation(wsm)
|
158 |
-
ssm = get_sentences_speaker_mapping(wsm, speaker_ts)
|
159 |
-
|
160 |
-
# Create the autodiarization directory structure
|
161 |
-
autodiarization_dir = "autodiarization"
|
162 |
-
os.makedirs(autodiarization_dir, exist_ok=True)
|
163 |
-
|
164 |
-
# Get the base name of the audio file
|
165 |
-
base_name = os.path.splitext(os.path.basename(args.audio))[0]
|
166 |
-
|
167 |
-
# Create a subdirectory for the current audio file
|
168 |
-
audio_dir = os.path.join(autodiarization_dir, base_name)
|
169 |
-
os.makedirs(audio_dir, exist_ok=True)
|
170 |
-
|
171 |
-
# Create a dictionary to store speaker-specific metadata
|
172 |
-
speaker_metadata = {}
|
173 |
-
|
174 |
-
# Generate the SRT file
|
175 |
-
srt_file = f"{os.path.splitext(args.audio)[0]}.srt"
|
176 |
-
with open(srt_file, "w", encoding="utf-8") as f:
|
177 |
-
write_srt(ssm, f)
|
178 |
-
|
179 |
-
# Read the generated SRT file
|
180 |
-
with open(srt_file, "r", encoding="utf-8") as f:
|
181 |
-
srt_data = f.read()
|
182 |
-
|
183 |
-
# Parse the SRT data
|
184 |
-
srt_segments = list(srt.parse(srt_data))
|
185 |
-
|
186 |
-
# Process each segment in the SRT data
|
187 |
-
for segment in srt_segments:
|
188 |
-
start_time = segment.start.total_seconds() * 1000
|
189 |
-
end_time = segment.end.total_seconds() * 1000
|
190 |
-
speaker_name, transcript = segment.content.split(": ", 1)
|
191 |
-
|
192 |
-
# Extract the speaker ID from the speaker name
|
193 |
-
speaker_id = int(speaker_name.split(" ")[-1])
|
194 |
-
|
195 |
-
# Split the audio segment
|
196 |
-
segment_audio = sound[start_time:end_time]
|
197 |
-
segment_path = os.path.join(audio_dir, f"speaker_{speaker_id}", f"speaker_{speaker_id}_{segment.index:03d}.wav")
|
198 |
-
os.makedirs(os.path.dirname(segment_path), exist_ok=True)
|
199 |
-
segment_audio.export(segment_path, format="wav")
|
200 |
-
|
201 |
-
# Store the metadata for each speaker
|
202 |
-
if speaker_name not in speaker_metadata:
|
203 |
-
speaker_metadata[speaker_name] = []
|
204 |
-
speaker_metadata[speaker_name].append(f"speaker_{speaker_id}_{segment.index:03d}|{speaker_name}|{transcript}")
|
205 |
-
|
206 |
-
# Write the metadata.csv file for each speaker
|
207 |
-
for speaker_name, metadata in speaker_metadata.items():
|
208 |
-
speaker_id = int(speaker_name.split(" ")[-1])
|
209 |
-
speaker_dir = os.path.join(audio_dir, f"speaker_{speaker_id}")
|
210 |
-
with open(os.path.join(speaker_dir, "metadata.csv"), "w", encoding="utf-8") as f:
|
211 |
-
f.write("\n".join(metadata))
|
212 |
-
|
213 |
-
# Clean up temporary files
|
214 |
-
cleanup(temp_path)
|
|
|
1 |
import argparse
|
2 |
import os
|
3 |
+
import glob
|
4 |
from helpers import *
|
5 |
from faster_whisper import WhisperModel
|
6 |
import whisperx
|
|
|
10 |
import logging
|
11 |
import shutil
|
12 |
import srt
|
13 |
+
from tqdm import tqdm
|
14 |
+
import concurrent.futures
|
15 |
|
16 |
mtypes = {"cpu": "int8", "cuda": "float16"}
|
17 |
|
18 |
+
def setup_logging():
|
19 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
20 |
+
|
21 |
+
def process_audio_file(audio_file, args):
|
22 |
+
logging.info(f"Processing file: {audio_file}")
|
23 |
+
|
24 |
+
if args.stemming:
|
25 |
+
# Isolate vocals from the rest of the audio
|
26 |
+
logging.info("Performing source separation...")
|
27 |
+
return_code = os.system(
|
28 |
+
f'python3 -m demucs.separate -n htdemucs --two-stems=vocals "{audio_file}" -o "temp_outputs"'
|
29 |
+
)
|
30 |
+
if return_code != 0:
|
31 |
+
logging.warning("Source splitting failed, using original audio file.")
|
32 |
+
vocal_target = audio_file
|
33 |
+
else:
|
34 |
+
vocal_target = os.path.join(
|
35 |
+
"temp_outputs",
|
36 |
+
"htdemucs",
|
37 |
+
os.path.splitext(os.path.basename(audio_file))[0],
|
38 |
+
"vocals.wav",
|
39 |
+
)
|
40 |
+
else:
|
41 |
+
vocal_target = audio_file
|
42 |
+
|
43 |
+
# Transcribe the audio file
|
44 |
+
logging.info("Transcribing audio...")
|
45 |
+
if args.batch_size != 0:
|
46 |
+
from transcription_helpers import transcribe_batched
|
47 |
+
whisper_results, language = transcribe_batched(
|
48 |
+
vocal_target,
|
49 |
+
args.language,
|
50 |
+
args.batch_size,
|
51 |
+
args.model_name,
|
52 |
+
mtypes[args.device],
|
53 |
+
args.suppress_numerals,
|
54 |
+
args.device,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
)
|
|
|
56 |
else:
|
57 |
+
from transcription_helpers import transcribe
|
58 |
+
whisper_results, language = transcribe(
|
59 |
+
vocal_target,
|
60 |
+
args.language,
|
61 |
+
args.model_name,
|
62 |
+
mtypes[args.device],
|
63 |
+
args.suppress_numerals,
|
64 |
+
args.device,
|
65 |
+
)
|
66 |
+
|
67 |
+
logging.info("Aligning transcription...")
|
68 |
+
if language in wav2vec2_langs:
|
69 |
+
alignment_model, metadata = whisperx.load_align_model(
|
70 |
+
language_code=language, device=args.device
|
71 |
+
)
|
72 |
+
result_aligned = whisperx.align(
|
73 |
+
whisper_results, alignment_model, metadata, vocal_target, args.device
|
74 |
)
|
75 |
+
word_timestamps = filter_missing_timestamps(
|
76 |
+
result_aligned["word_segments"],
|
77 |
+
initial_timestamp=whisper_results[0].get("start"),
|
78 |
+
final_timestamp=whisper_results[-1].get("end"),
|
79 |
+
)
|
80 |
+
del alignment_model
|
81 |
+
torch.cuda.empty_cache()
|
82 |
+
else:
|
83 |
+
word_timestamps = []
|
84 |
+
for segment in whisper_results:
|
85 |
+
for word in segment["words"]:
|
86 |
+
word_timestamps.append({"word": word[2], "start": word[0], "end": word[1]})
|
87 |
+
|
88 |
+
# Convert audio to mono for NeMo compatibility
|
89 |
+
logging.info("Converting audio to mono...")
|
90 |
+
sound = AudioSegment.from_file(vocal_target).set_channels(1)
|
91 |
+
ROOT = os.getcwd()
|
92 |
+
temp_path = os.path.join(ROOT, "temp_outputs")
|
93 |
+
os.makedirs(temp_path, exist_ok=True)
|
94 |
+
sound.export(os.path.join(temp_path, "mono_file.wav"), format="wav")
|
95 |
+
|
96 |
+
# Initialize NeMo MSDD diarization model
|
97 |
+
logging.info("Performing diarization...")
|
98 |
+
msdd_model = NeuralDiarizer(cfg=create_config(temp_path)).to(args.device)
|
99 |
+
msdd_model.diarize()
|
100 |
+
del msdd_model
|
101 |
+
torch.cuda.empty_cache()
|
102 |
+
|
103 |
+
# Reading timestamps <> Speaker Labels mapping
|
104 |
+
speaker_ts = []
|
105 |
+
with open(os.path.join(temp_path, "pred_rttms", "mono_file.rttm"), "r") as f:
|
106 |
+
lines = f.readlines()
|
107 |
+
for line in lines:
|
108 |
+
line_list = line.split(" ")
|
109 |
+
s = int(float(line_list[5]) * 1000)
|
110 |
+
e = s + int(float(line_list[8]) * 1000)
|
111 |
+
speaker_ts.append([s, e, int(line_list[11].split("_")[-1])])
|
112 |
+
|
113 |
+
wsm = get_words_speaker_mapping(word_timestamps, speaker_ts, "start")
|
114 |
+
wsm = get_realigned_ws_mapping_with_punctuation(wsm)
|
115 |
+
ssm = get_sentences_speaker_mapping(wsm, speaker_ts)
|
116 |
+
|
117 |
+
# Create the autodiarization directory structure
|
118 |
+
autodiarization_dir = "autodiarization"
|
119 |
+
os.makedirs(autodiarization_dir, exist_ok=True)
|
120 |
+
|
121 |
+
# Get the base name of the audio file
|
122 |
+
base_name = os.path.splitext(os.path.basename(audio_file))[0]
|
123 |
+
|
124 |
+
# Create a subdirectory for the current audio file
|
125 |
+
audio_dir = os.path.join(autodiarization_dir, base_name)
|
126 |
+
os.makedirs(audio_dir, exist_ok=True)
|
127 |
+
|
128 |
+
# Create a dictionary to store speaker-specific metadata
|
129 |
+
speaker_metadata = {}
|
130 |
+
|
131 |
+
# Generate the SRT file
|
132 |
+
srt_file = f"{os.path.splitext(audio_file)[0]}.srt"
|
133 |
+
with open(srt_file, "w", encoding="utf-8") as f:
|
134 |
+
write_srt(ssm, f)
|
135 |
+
|
136 |
+
# Read the generated SRT file
|
137 |
+
with open(srt_file, "r", encoding="utf-8") as f:
|
138 |
+
srt_data = f.read()
|
139 |
+
|
140 |
+
# Parse the SRT data
|
141 |
+
srt_segments = list(srt.parse(srt_data))
|
142 |
+
|
143 |
+
# Process each segment in the SRT data
|
144 |
+
logging.info("Processing audio segments...")
|
145 |
+
for segment in tqdm(srt_segments, desc="Processing segments"):
|
146 |
+
start_time = segment.start.total_seconds() * 1000
|
147 |
+
end_time = segment.end.total_seconds() * 1000
|
148 |
+
speaker_name, transcript = segment.content.split(": ", 1)
|
149 |
+
|
150 |
+
# Extract the speaker ID from the speaker name
|
151 |
+
speaker_id = int(speaker_name.split(" ")[-1])
|
152 |
+
|
153 |
+
# Split the audio segment
|
154 |
+
segment_audio = sound[start_time:end_time]
|
155 |
+
segment_path = os.path.join(audio_dir, f"speaker_{speaker_id}", f"speaker_{speaker_id}_{segment.index:03d}.wav")
|
156 |
+
os.makedirs(os.path.dirname(segment_path), exist_ok=True)
|
157 |
+
segment_audio.export(segment_path, format="wav")
|
158 |
+
|
159 |
+
# Store the metadata for each speaker
|
160 |
+
if speaker_name not in speaker_metadata:
|
161 |
+
speaker_metadata[speaker_name] = []
|
162 |
+
speaker_metadata[speaker_name].append(f"speaker_{speaker_id}_{segment.index:03d}|{speaker_name}|{transcript}")
|
163 |
+
|
164 |
+
# Write the metadata.csv file for each speaker
|
165 |
+
for speaker_name, metadata in speaker_metadata.items():
|
166 |
+
speaker_id = int(speaker_name.split(" ")[-1])
|
167 |
+
speaker_dir = os.path.join(audio_dir, f"speaker_{speaker_id}")
|
168 |
+
with open(os.path.join(speaker_dir, "metadata.csv"), "w", encoding="utf-8") as f:
|
169 |
+
f.write("\n".join(metadata))
|
170 |
+
|
171 |
+
# Clean up temporary files
|
172 |
+
cleanup(temp_path)
|
173 |
+
logging.info(f"Finished processing {audio_file}")
|
174 |
+
|
175 |
+
def main():
|
176 |
+
setup_logging()
|
177 |
+
|
178 |
+
parser = argparse.ArgumentParser()
|
179 |
+
parser.add_argument(
|
180 |
+
"-a", "--audio", help="name of the target audio file or directory", required=True
|
181 |
)
|
182 |
+
parser.add_argument(
|
183 |
+
"--no-stem",
|
184 |
+
action="store_false",
|
185 |
+
dest="stemming",
|
186 |
+
default=True,
|
187 |
+
help="Disables source separation. This helps with long files that don't contain a lot of music.",
|
|
|
|
|
|
|
188 |
)
|
189 |
+
parser.add_argument(
|
190 |
+
"--suppress_numerals",
|
191 |
+
action="store_true",
|
192 |
+
dest="suppress_numerals",
|
193 |
+
default=False,
|
194 |
+
help="Suppresses Numerical Digits. This helps the diarization accuracy but converts all digits into written text.",
|
195 |
)
|
196 |
+
parser.add_argument(
|
197 |
+
"--whisper-model",
|
198 |
+
dest="model_name",
|
199 |
+
default="medium.en",
|
200 |
+
help="name of the Whisper model to use",
|
201 |
)
|
202 |
+
parser.add_argument(
|
203 |
+
"--batch-size",
|
204 |
+
type=int,
|
205 |
+
dest="batch_size",
|
206 |
+
default=8,
|
207 |
+
help="Batch size for batched inference, reduce if you run out of memory, set to 0 for non-batched inference",
|
208 |
)
|
209 |
+
parser.add_argument(
|
210 |
+
"--language",
|
211 |
+
type=str,
|
212 |
+
default=None,
|
213 |
+
choices=whisper_langs,
|
214 |
+
help="Language spoken in the audio, specify None to perform language detection",
|
|
|
|
|
|
|
215 |
)
|
216 |
+
parser.add_argument(
|
217 |
+
"--device",
|
218 |
+
dest="device",
|
219 |
+
default="cuda" if torch.cuda.is_available() else "cpu",
|
220 |
+
help="if you have a GPU use 'cuda', otherwise 'cpu'",
|
221 |
+
)
|
222 |
+
args = parser.parse_args()
|
223 |
+
|
224 |
+
if os.path.isdir(args.audio):
|
225 |
+
audio_files = glob.glob(os.path.join(args.audio, "*.wav")) + glob.glob(os.path.join(args.audio, "*.mp3"))
|
226 |
+
logging.info(f"Found {len(audio_files)} audio files in the directory.")
|
227 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
228 |
+
list(tqdm(executor.map(lambda f: process_audio_file(f, args), audio_files), total=len(audio_files), desc="Processing files"))
|
229 |
+
else:
|
230 |
+
process_audio_file(args.audio, args)
|
231 |
+
|
232 |
+
if __name__ == "__main__":
|
233 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|