File size: 7,654 Bytes
3428b9a
 
 
86823be
3428b9a
 
 
 
 
 
 
 
 
 
 
 
 
86823be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4a4410
5902d6b
 
 
 
2e8504f
 
 
 
 
f4a4410
 
 
 
 
2e8504f
 
 
 
 
 
 
 
 
 
 
 
9536d66
2e8504f
f0a336a
2e8504f
f4a4410
 
 
 
2e8504f
 
 
f4a4410
 
 
 
2e8504f
 
 
 
 
5902d6b
2e8504f
 
 
3428b9a
2e8504f
 
 
 
 
 
 
 
 
 
 
 
86823be
3428b9a
2e8504f
3428b9a
 
 
 
 
 
 
 
 
 
f0a336a
3428b9a
 
 
 
 
 
 
 
 
 
 
 
 
2e8504f
3428b9a
 
 
86823be
 
b22932f
86823be
f4a4410
2e8504f
3428b9a
 
2e8504f
 
f4a4410
 
 
 
 
 
 
 
 
 
 
 
2e8504f
f0a336a
2e8504f
 
 
 
 
 
3428b9a
 
 
 
 
f4a4410
3767e24
9854ff1
3767e24
 
9854ff1
 
18e44df
 
f0a336a
3428b9a
2e8504f
 
 
 
 
 
 
 
3428b9a
 
 
 
 
 
 
 
 
 
 
 
 
f4a4410
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
import argparse
import csv
import os
import re
import shutil
import tarfile
import tempfile
from tqdm import tqdm

from pydub import AudioSegment
import requests
from pocketbase import PocketBase

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(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(),
                "size": 0,
                "totalExamples": 0,
                "examplesTranslated": 0,
                "durationLabelled": 0,
                "durationUnlabelled": 0,
            }
            for dialect in dialects.keys()
        },
        "totalExamples": 0,
        "examplesTranslated": 0,
        "durationLabelled": 0,
        "durationUnlabelled": 0,
        "version": "1.0.0",
        "date": "2023-10-7",
        "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)
                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_url = pb.get_file_url(example, example.speech, {})
                    response = requests.get(audio_url)
                    with tempfile.NamedTemporaryFile() as f:
                        f.write(response.content)
                        f.flush()
                        audio = AudioSegment.from_file(f.name)
                    audio = audio.set_frame_rate(48000)
                    audio_file_name = f"nena_speech_{example.id}.mp3"
                    audio_file_path = os.path.join(audio_dir_path, audio_file_name)
                    audio.export(audio_file_path, format="mp3")
                    
                    transcripts.append({
                        'client_id': example.speaker,
                        'transcription': example.transcription,
                        'translation': example.translation,
                        'path': audio_file_name,
                        'locale': example.locale,
                        'proficiency': example.proficiency,
                        'age': example.age,
                        'crowdsourced': example.crowdsourced,
                        'unlabelled': not example.transcription,
                        'interrupted': contains_interruption(example.transcription, example.translation),
                    })

                    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["durationLabelled"] += len(audio) / 1000
                        dialect_stats["durationLabelled"] += len(audio) / 1000
                    else:
                        stats["durationUnlabelled"] += len(audio) / 1000
                        dialect_stats["durationUnlabelled"] += len(audio) / 1000

                    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 / len(examples)
                    dialect_stats["splits"]["age"][example.age] = dialect_stats["splits"]["age"].get(example.age, 0) + 1 / len(examples)
                    dialect_stats["splits"]["locale"][example.locale] = dialect_stats["splits"]["locale"].get(example.locale, 0) + 1 / len(examples)
                    if example.crowdsourced:
                        dialect_stats["splits"]["crowdsourced"] += 1 / len(examples)

                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('dialect.py', 'w') as f:
        python_code = f'DIALECT = {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",
    )

    args = parser.parse_args()

    build_dataset()