phdkhanh2507 commited on
Commit
23942ce
·
verified ·
1 Parent(s): f3a27ac

Upload transcribed-vietnamese-audio.py

Browse files
Files changed (1) hide show
  1. transcribed-vietnamese-audio.py +167 -0
transcribed-vietnamese-audio.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import datasets
3
+ from huggingface_hub import HfFileSystem
4
+ from typing import List, Tuple
5
+
6
+
7
+ logger = datasets.logging.get_logger(__name__)
8
+ fs = HfFileSystem()
9
+
10
+
11
+ _CITATION = """
12
+
13
+ """
14
+ _DESCRIPTION = """
15
+ This dataset contains transcripts from audio of Vietnamese speakers.
16
+ """
17
+ _HOMEPAGE = "https://github.com/duytran1332002/vlr"
18
+ _MAIN_REPO_PATH = "datasets/phdkhanh2507/transcribed-vietnamese-audio"
19
+ _VISUAL_REPO_PATH = "datasets/phdkhanh2507/vietnamese-speaker-clip"
20
+ _REPO_URL = "https://huggingface.co/{}/resolve/main"
21
+ _URLS = {
22
+ "meta": f"{_REPO_URL}/metadata/".format(_MAIN_REPO_PATH) + "{channel}.parquet",
23
+ "visual": f"{_REPO_URL}/visual/".format(_VISUAL_REPO_PATH) + "{channel}.zip",
24
+ "audio": f"{_REPO_URL}/audio/".format(_MAIN_REPO_PATH) + "{channel}.zip",
25
+ "transcript": f"{_REPO_URL}/transcript/".format(_MAIN_REPO_PATH) + "{channel}.zip",
26
+ }
27
+ _CONFIGS = ["all"]
28
+ if fs.exists(_MAIN_REPO_PATH + "/metadata"):
29
+ _CONFIGS.extend([
30
+ os.path.basename(file_name)[:-8]
31
+ for file_name in fs.listdir(_MAIN_REPO_PATH + "/metadata", detail=False)
32
+ if file_name.endswith(".parquet")
33
+ ])
34
+
35
+
36
+ class TranscribedVietnameseAudioConfig(datasets.BuilderConfig):
37
+ """Transcribed Vietnamese Audio configuration."""
38
+
39
+ def __init__(self, name, **kwargs):
40
+ """
41
+ :param name: Name of subset.
42
+ :param kwargs: Arguments.
43
+ """
44
+ super().__init__(
45
+ name=name,
46
+ version=datasets.Version("1.0.0"),
47
+ description=_DESCRIPTION,
48
+ **kwargs,
49
+ )
50
+
51
+
52
+ class TranscribedVietnameseAudio(datasets.GeneratorBasedBuilder):
53
+ """Transcribed Vietnamese Audio dataset."""
54
+
55
+ BUILDER_CONFIGS = [TranscribedVietnameseAudioConfig(name) for name in _CONFIGS]
56
+ DEFAULT_CONFIG_NAME = "all"
57
+
58
+ def _info(self) -> datasets.DatasetInfo:
59
+ features = datasets.Features({
60
+ "id": datasets.Value("string"),
61
+ "channel": datasets.Value("string"),
62
+ "duration": datasets.Value("float64"),
63
+ "fps": datasets.Value("int8"),
64
+ "audio": datasets.Value("binary"),
65
+ "sampling_rate": datasets.Value("int64"),
66
+ "transcript": datasets.Value("string"),
67
+ })
68
+
69
+ return datasets.DatasetInfo(
70
+ description=_DESCRIPTION,
71
+ features=features,
72
+ homepage=_HOMEPAGE,
73
+ citation=_CITATION,
74
+ )
75
+
76
+ def _split_generators(
77
+ self, dl_manager: datasets.DownloadManager
78
+ ) -> List[datasets.SplitGenerator]:
79
+ """
80
+ Get splits.
81
+ :param dl_manager: Download manager.
82
+ :return: Splits.
83
+ """
84
+ config_names = _CONFIGS[1:] if self.config.name == "all" else [self.config.name]
85
+
86
+ metadata_paths = dl_manager.download(
87
+ [_URLS["meta"].format(channel=channel) for channel in config_names]
88
+ )
89
+ audio_dirs = dl_manager.download_and_extract(
90
+ [_URLS["audio"].format(channel=channel) for channel in config_names]
91
+ )
92
+ transcript_dirs = dl_manager.download_and_extract(
93
+ [_URLS["transcript"].format(channel=channel) for channel in config_names]
94
+ )
95
+
96
+ audio_dict = {
97
+ channel: audio_dir for channel, audio_dir in zip(config_names, audio_dirs)
98
+ }
99
+ transcript_dict = {
100
+ channel: transcript_dir
101
+ for channel, transcript_dir in zip(config_names, transcript_dirs)
102
+ }
103
+
104
+ return [
105
+ datasets.SplitGenerator(
106
+ name=datasets.Split.TRAIN,
107
+ gen_kwargs={
108
+ "metadata_paths": metadata_paths,
109
+ "audio_dict": audio_dict,
110
+ "transcript_dict": transcript_dict,
111
+ },
112
+ ),
113
+ ]
114
+
115
+ def _generate_examples(
116
+ self, metadata_paths: List[str],
117
+ audio_dict: dict,
118
+ transcript_dict: dict,
119
+ ) -> Tuple[int, dict]:
120
+ """
121
+ Generate examples from metadata.
122
+ :param metadata_paths: Paths to metadata.
123
+ :param audio_dict: Paths to directory containing audios.
124
+ :param transcript_dict: Paths to directory containing transcripts.
125
+ :yield: Example.
126
+ """
127
+ dataset = datasets.load_dataset(
128
+ "parquet",
129
+ data_files=metadata_paths,
130
+ split="train",
131
+ )
132
+ for i, sample in enumerate(dataset):
133
+ channel = sample["channel"]
134
+ audio_path = os.path.join(
135
+ audio_dict[channel], channel, sample["id"] + ".wav"
136
+ )
137
+ transcript_path = os.path.join(
138
+ transcript_dict[channel], channel, sample["id"] + ".txt"
139
+ )
140
+
141
+ yield i, {
142
+ "id": sample["id"],
143
+ "channel": channel,
144
+ "duration": sample["duration"],
145
+ "fps": sample["fps"],
146
+ "audio": self.__get_binary_data(audio_path),
147
+ "sampling_rate": sample["sampling_rate"],
148
+ "transcript": self.__get_text_data(transcript_path),
149
+ }
150
+
151
+ def __get_binary_data(self, path: str) -> bytes:
152
+ """
153
+ Get binary data from path.
154
+ :param path: Path to file.
155
+ :return: Binary data.
156
+ """
157
+ with open(path, "rb") as f:
158
+ return f.read()
159
+
160
+ def __get_text_data(self, path: str) -> str:
161
+ """
162
+ Get transcript from path.
163
+ :param path: Path to transcript.
164
+ :return: Transcript.
165
+ """
166
+ with open(path, "r", encoding="utf-8") as f:
167
+ return f.read().strip()