File size: 8,258 Bytes
3428b9a
 
359246c
3428b9a
86823be
3428b9a
 
 
 
049c74d
3428b9a
 
 
049c74d
3428b9a
 
 
 
 
86823be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f23b28
5902d6b
 
 
 
2e8504f
 
 
 
 
f4a4410
 
 
 
 
2e8504f
 
 
 
 
 
 
 
 
 
 
 
9536d66
2e8504f
f0a336a
f4a4410
 
3f3b4f3
 
2e8504f
 
 
f4a4410
 
3f3b4f3
 
c748128
3f23b28
2e8504f
 
 
5902d6b
2e8504f
 
 
3428b9a
2e8504f
 
 
 
 
 
 
 
 
 
 
 
86823be
3428b9a
2e8504f
3428b9a
 
 
049c74d
 
 
 
 
 
3428b9a
 
 
 
 
 
f0a336a
3428b9a
 
 
049c74d
 
 
 
 
 
 
 
 
 
 
3428b9a
 
 
 
86823be
 
b22932f
86823be
2e8504f
5dec125
 
3428b9a
 
2e8504f
 
f4a4410
 
 
 
 
 
049c74d
 
f4a4410
049c74d
 
f4a4410
2e8504f
f0a336a
3f3b4f3
 
 
2e8504f
3f3b4f3
2e8504f
3428b9a
 
 
 
 
f4a4410
3767e24
9854ff1
3767e24
 
9854ff1
 
18e44df
 
f0a336a
3428b9a
5a3edbd
366694f
2e8504f
 
 
 
 
 
3428b9a
 
 
 
 
 
 
 
 
 
 
3f23b28
 
 
 
 
 
 
 
3428b9a
 
3f23b28
 
 
049c74d
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
import argparse
import csv
from datetime import datetime
import os
import re
import shutil
import tarfile
import tempfile
from tqdm import tqdm
import torchaudio
from pydub import AudioSegment
import requests
from pocketbase import PocketBase
from torchaudio.transforms import Resample

parser = argparse.ArgumentParser(description="Command description.")

pb = PocketBase('https://pocketbase.nenadb.dev/')

def contains_interruption(transcription: str, translation: str) -> bool:
    boundaries = r"[\s\-꞊ˈ…,\.?!]|$"
    languages = r"(A|Az|E|H|K|P|R)"

    # Check if transcription is just a string enclosed with parenthesis
    if re.fullmatch(r'\(.*\)', transcription):
        return True

    # Check if transcription contains any language abbreviation followed by a boundary
    pattern = f'{languages}(?={boundaries})'
    if re.search(pattern, transcription):
        return True

    # Check if translation contains square brackets
    if '[' in translation and ']' in translation:
        return True

    # If none of the above conditions are met, return False
    return False

def build_dataset(version, test_split=0.10, dev_split=0.10):
    dialects = pb.collection("dialects").get_full_list(query_params={
        "sort": "name",
    })

    dialects = {
        dialect.name.lower(): dialect.name
        for dialect in dialects
    }

    examples = pb.collection("examples").get_full_list(query_params={
        "expand": "dialect",
        "filter": "validated=true",
    })

    stats = {
        "dialects": {
            dialect : {
                "buckets": {
                    "dev": 0,
                    "test": 0,
                    "train": 0,
                },
                "splits": {
                    "proficiency": {},
                    "age": {},
                    "locale": {},
                    "crowdsourced": 0,
                },
                "speakers": set(),
                "totalExamples": 0,
                "examplesTranslated": 0,
                "durationLabeled": 0,
                "durationUnlabeled": 0,
            }
            for dialect in dialects.keys()
        },
        "totalExamples": 0,
        "examplesTranslated": 0,
        "durationLabeled": 0,
        "durationUnlabeled": 0,
        "version": version,
        "date": datetime.now().strftime("%Y-%m-%d"),
        "name": "NENA Speech Dataset",
        "multilingual": True,
    }

    def split_examples(examples):
        test_end = int(test_split * len(examples))
        dev_end = int((dev_split + test_split) * len(examples))
        
        return {
            'test': examples[:test_end],
            'dev': examples[test_end:dev_end],
            'train': examples[dev_end:],
        }

    subsets = {
        dialect: split_examples([
            example for example in examples
            if example.expand['dialect'].name.lower() == dialect
        ])
        for dialect in dialects.keys()
    }

    with tqdm(total=len(examples)) as pbar:
        for dialect, subset in subsets.items():
            for split, examples in subset.items():
                audio_dir_path = os.path.join("audio", dialect, split)
                audio_tar_path = f"{audio_dir_path}.tar"
                if os.path.exists(audio_tar_path):
                    with tarfile.open(audio_tar_path, "r") as tar:
                        tar.extractall(path=os.path.join("audio", dialect))
                else:
                    os.makedirs(audio_dir_path, exist_ok=True)

                transcripts = []
                transcript_dir_path = os.path.join("transcript", dialect)
                os.makedirs(transcript_dir_path, exist_ok=True)
                
                for example in examples:
                    pbar.set_description(f"Downloading audios ({dialect}/{split})")
                    pbar.update(1)
                    audio_file_name = f"nena_speech_{example.id}.mp3"
                    audio_file_path = os.path.join(audio_dir_path, audio_file_name)

                    if not os.path.exists(audio_file_path):
                        audio_url = pb.get_file_url(example, example.speech, {})
                        response = requests.get(audio_url)
                        with tempfile.NamedTemporaryFile() as f:
                            f.write(response.content)
                            f.flush()
                            waveform, sample_rate = torchaudio.load(f.name)
                        resampler = Resample(orig_freq=sample_rate, new_freq=48000)
                        resampled_waveform = resampler(waveform)
                        torchaudio.save(audio_file_path, resampled_waveform, 48000, format="mp3")
                    
                    transcripts.append({
                        'transcription': example.transcription,
                        'translation': example.translation,
                        'locale': example.locale,
                        'proficiency': example.proficiency,
                        'age': example.age,
                        'crowdsourced': example.crowdsourced,
                        'interrupted': contains_interruption(example.transcription, example.translation),
                        'client_id': example.speaker,
                        'path': audio_file_name,
                    })

                    dialect_stats = stats["dialects"][dialect]

                    stats["totalExamples"] += 1
                    dialect_stats["totalExamples"] += 1
                    if example.translation:
                        stats["examplesTranslated"] += 1
                        dialect_stats["examplesTranslated"] += 1
                    if example.transcription:
                        stats["durationLabeled"] += 0
                        dialect_stats["durationLabeled"] += 0
                    else:
                        stats["durationUnlabeled"] += 0
                        dialect_stats["durationUnlabeled"] += 0

                    dialect_stats["buckets"][split] += 1
                    dialect_stats["speakers"].add(example.speaker)
                    dialect_stats["splits"]["proficiency"][example.proficiency] = dialect_stats["splits"]["proficiency"].get(example.proficiency, 0) + 1
                    dialect_stats["splits"]["age"][example.age] = dialect_stats["splits"]["age"].get(example.age, 0) + 1
                    dialect_stats["splits"]["locale"][example.locale] = dialect_stats["splits"]["locale"].get(example.locale, 0) + 1
                    if example.crowdsourced:
                        dialect_stats["splits"]["crowdsourced"] += 1

                pbar.set_description(f"Saving audios ({dialect}/{split})")
                audio_tar_path = f"{audio_dir_path}.tar"
                with tarfile.open(audio_tar_path, 'w') as tar:
                    tar.add(audio_dir_path, arcname=os.path.basename(audio_dir_path))

                pbar.set_description(f"Saving transcripts ({dialect}/{split})")

                with open(os.path.join(transcript_dir_path, f"{split}.tsv"), 'w', newline='') as f:
                    fieldnames = [] if len(transcripts) == 0 else transcripts[0].keys()
                    writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter='\t')
                    writer.writeheader()
                    writer.writerows(transcripts)

                shutil.rmtree(audio_dir_path) 
            stats["dialects"][dialect]["speakers"] = len(stats["dialects"][dialect]["speakers"])

    with open('dialects.py', 'w') as f:
        python_code = f'DIALECTS = {repr(dialects)}\n'
        f.write(python_code)

    with open('release_stats.py', 'w') as f:
        python_code = f'STATS = {repr(stats)}\n'
        f.write(python_code)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Generate text from prompt")

    parser.add_argument(
        "-b",
        "--build",
        action="store_true",
        help="Download text prompts from GCS bucket",
    )

    parser.add_argument(
        "-v",
        "--version",
        type=str,
        default="1.0.0",
        help="Download text prompts from GCS bucket",
    )

    args = parser.parse_args()

    if args.build:
        build_dataset(version=args.version)