File size: 1,925 Bytes
f1cc9cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import torchaudio
from glob import glob
import os
import csv
from tqdm import tqdm
import pandas

sentence_bounds = {'!', '.', ';', '?', '…'}

files = list(sorted(glob("earnings22/media/*.mp3")))
metadata = []
for audio_file in tqdm(files):
    file_id = audio_file.split("/")[-1].split(".")[0]
    nlp_file = f"earnings22/aligned/{file_id}.nlp"

    speech, sr = torchaudio.load(audio_file)
    with open(nlp_file, "r") as nlp:
        start, end = None, None
        sentence = ""
        segment_id = 0
        csvreader = csv.DictReader(nlp, delimiter="|")
        for row in csvreader:
            punct = row["punctuation"].strip()
            sentence += row["token"]
            if punct:
                sentence += punct
            sentence += " "
            if start is None and row["ts"].strip():
                start = float(row["ts"]) - 0.1
            if row["endTs"].strip():
                end = float(row["endTs"]) + 0.1
            if punct in sentence_bounds and start is not None and end is not None:
                segment = speech[:, int(start*sr):int(end*sr)+1].contiguous()

                os.makedirs(f"earnings22/segmented/{file_id}", exist_ok=True)
                torchaudio.save(f"earnings22/segmented/{file_id}/{segment_id}.wav",
                                segment, sr, encoding="PCM_S", bits_per_sample=16)

                data_row = {
                    "source_id": f"{file_id}",
                    "segment_id": segment_id,
                    "file": f"{file_id}/{segment_id}.wav",
                    "start_ts": start,
                    "end_ts": end,
                    "sentence": sentence.strip()
                }
                metadata.append(data_row)

                start, end = None, None
                sentence = ""
                segment_id += 1
    pd.DataFrame(metadata).to_csv("earnings22/segmented/metadata.csv", index=False)