PedroDKE commited on
Commit
9cd3692
1 Parent(s): 5de7e1c

Additional example files

Browse files
align_text_and_audio.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import aeneas.globalconstants as gc
3
+ import pandas as pd
4
+ import os
5
+ import argparse
6
+
7
+ from aeneas.executetask import ExecuteTask
8
+ from aeneas.language import Language
9
+ from aeneas.syncmap import SyncMapFormat
10
+ from aeneas.task import Task
11
+ from aeneas.task import TaskConfiguration
12
+ from aeneas.textfile import TextFileFormat
13
+ from pydub import AudioSegment
14
+
15
+
16
+ parser = argparse.ArgumentParser(description='A program to download all the chapters in a given librivox URL.')
17
+ parser.add_argument("--text_dir",
18
+ help='Directory containing the txt files to allign the audio to',
19
+ required=True,
20
+ type=str)
21
+ parser.add_argument("--audio_path",
22
+ help="path to the chapter which are to be aligned.",
23
+ required=True,
24
+ type=str)
25
+ parser.add_argument("--aeneas_path",
26
+ help="path to save the allignments from aeneas",
27
+ required=True,
28
+ type=str)
29
+ parser.add_argument("--en_audio_export_path",
30
+ help="path to save the english audio fragments",
31
+ required=True,
32
+ type=str)
33
+ parser.add_argument("--total_alignment_path",
34
+ help="path to save the english audio fragments",
35
+ required=True,
36
+ type=str)
37
+ parser.add_argument("--librivoxdeen_alignment",
38
+ help="path to TSV file provided by LibriVoxDeEn for this particular book",
39
+ required=True,
40
+ type=str)
41
+ parser.add_argument("--aeneas_head_max",
42
+ help="max value (s) of the head for the aeneas alignment, depending on the book to be alligned this has to be tuned",
43
+ default = 0,
44
+ required=False,
45
+ type=int)
46
+ parser.add_argument("--aeneas_tail_min",
47
+ help="min value (s) of the tail for the aeneas alignment, depending on the book to be alligned this has to be tuned",
48
+ default = 0,
49
+ required=False,
50
+ type=int)
51
+ args = parser.parse_args()
52
+
53
+ #variables
54
+ number_files = len(os.listdir(args.text_dir))
55
+ txt_files = os.listdir(args.text_dir)
56
+ txt_files.sort()
57
+
58
+ audio_files = os.listdir(args.audio_path)
59
+ audio_files.sort()
60
+
61
+ EN_AUDIO_EXPORT_NAME = '000{}-{}.wav' # path where to store the english fragments
62
+ EN_ALIGNED_CSV = '000{}-undine_map.csv' #name to store the aeneas mapping
63
+ TOTAL_ALIGNMENT_NAME = '000{}-undine_map_DeEn.csv' #path to store the english and german mapping
64
+
65
+ GE_AUDIO_NAME_TEMPLATE = '000{}-undine_{}.flac' #name of german audio file
66
+ #aeneas arguments
67
+ tsv_audio_template = "000{}" #template of audio files in tsv file
68
+
69
+ #count the number of total missing files unaligned
70
+ total_missing = 0
71
+ total = 0
72
+
73
+
74
+ if not os.path.exists(args.aeneas_path):
75
+ os.makedirs(args.aeneas_path)
76
+ print('made new directory at:',args.aeneas_path)
77
+ if not os.path.exists(args.en_audio_export_path):
78
+ os.makedirs(args.en_audio_export_path)
79
+ print('made new directory at:',args.en_audio_export_path)
80
+ if not os.path.exists(args.total_alignment_path):
81
+ os.makedirs(args.total_alignment_path)
82
+ print('made new directory at:',args.total_alignment_path)
83
+
84
+
85
+
86
+ for chap in range(1 ,number_files+1):
87
+
88
+ abs_path = args.text_dir+txt_files[chap-1]
89
+ str_chap = str(chap)
90
+ str_chap = str(chap).zfill(2)
91
+
92
+ print('start alignent for chap: {}'.format(chap))
93
+
94
+ # create Task object
95
+ config = TaskConfiguration()
96
+ config[gc.PPN_TASK_LANGUAGE] = Language.ENG
97
+ config[gc.PPN_TASK_IS_TEXT_FILE_FORMAT] = TextFileFormat.PLAIN
98
+ config[gc.PPN_TASK_OS_FILE_FORMAT] = SyncMapFormat.CSV
99
+ config[gc.PPN_TASK_OS_FILE_NAME] = EN_ALIGNED_CSV.format(str_chap)
100
+ config[gc.PPN_TASK_IS_AUDIO_FILE_DETECT_HEAD_MAX] = args.aeneas_head_max
101
+ config[gc.PPN_TASK_IS_AUDIO_FILE_DETECT_TAIL_MIN] = args.aeneas_tail_min
102
+ config[gc.PPN_TASK_OS_FILE_HEAD_TAIL_FORMAT] = 'hidden'
103
+
104
+ task = Task()
105
+ task.configuration = config
106
+ task.text_file_path_absolute = abs_path
107
+ task.audio_file_path_absolute = args.audio_path+'/'+audio_files[chap-1]
108
+ task.sync_map_file_path = EN_ALIGNED_CSV.format(str_chap)
109
+
110
+ # process Task
111
+ ExecuteTask(task).execute()
112
+
113
+ task.output_sync_map_file(os.getcwd()+args.aeneas_path[1:])
114
+
115
+ # print(task.sync_map)
116
+ print('alignent done for chap: {}'.format(chap))
117
+
118
+ # -------- read csv and cut audio -----------
119
+ print('cutting audio for chap: {}'.format(chap))
120
+
121
+ en_alignment = pd.read_csv(args.aeneas_path+EN_ALIGNED_CSV.format(str_chap), header = None)
122
+
123
+ original = AudioSegment.from_file(args.audio_path+'/'+audio_files[chap-1])
124
+ for Name, Start, End, Text in zip(en_alignment.iloc[:,0], en_alignment.iloc[:,1], en_alignment.iloc[:,2], en_alignment.iloc[:,3]):
125
+ extract = original[Start*1000:End*1000]
126
+ extract.export(args.en_audio_export_path+EN_AUDIO_EXPORT_NAME.format(str_chap,Name), format="wav")
127
+
128
+ print('done cutting audio for chap: {}'.format(chap))
129
+ # ------- create CSV file with concatenated data ------
130
+ print('create CSV for chap: {}'.format(chap))
131
+
132
+ new = pd.DataFrame(columns=['book', 'DE_audio', 'EN_audio', 'score', 'DE_transcript', 'EN_transcript'])
133
+
134
+ # open German TSV
135
+ ge_alignment = pd.read_table(args.librivoxdeen_alignment)
136
+
137
+ # all german audio names
138
+ # restrict german to only the current chapter
139
+ ge_alignment = ge_alignment[ge_alignment['audio'].str.contains(tsv_audio_template.format(str_chap))==True]
140
+ ge_audio_names = []
141
+
142
+ for i in range(ge_alignment.shape[0]+1):
143
+ ge_audio_names.append(GE_AUDIO_NAME_TEMPLATE.format(str_chap,i))
144
+
145
+ for name in ge_audio_names:
146
+ ge_index = ge_alignment[ge_alignment['audio']==name].index
147
+ if len(ge_index) > 0:
148
+ en_translation = ge_alignment['en_sentence'][ge_index[0]].replace('<MERGE> ', '').strip()
149
+ en_index = en_alignment[en_alignment.iloc[:, 3] == en_translation.replace('~', '')].index
150
+ if len(en_index) > 0:
151
+ ind = ge_index[0]
152
+ new = new.append({'book': ge_alignment['book'][ind],
153
+ 'DE_audio': ge_alignment['audio'][ind],
154
+ 'EN_audio':'000{}-'.format(str_chap)+en_alignment.iloc[en_index[0],0]+'.wav',
155
+ 'score':ge_alignment['score'][ind],
156
+ 'DE_transcript':ge_alignment['de_sentence'][ind],
157
+ 'EN_transcript': ge_alignment['en_sentence'][ind]},
158
+ ignore_index=True)
159
+ new.to_csv(args.total_alignment_path+'/'+TOTAL_ALIGNMENT_NAME.format(str_chap),index=False)
160
+
161
+ print('files in the DeEn csv: ' + str(new.shape))
162
+ print('files in the EN alignment'+str(en_alignment.shape))
163
+ print('files in the original DE csv: ' + str(ge_alignment.shape))
164
+ missing = ge_alignment.shape[0]-new.shape[0]
165
+ total_missing += missing
166
+ print('number of unaligned audio files: '+str(missing))
167
+ print('done creating CSV for chap: {}'.format(chap))
168
+ total += ge_alignment.shape[0]
169
+ print('missing: '+str(total_missing)+' out of '+str(total)+' GE files')
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ aeneas=1.7.3.0
2
+ pandas>=1.1.4
3
+ pydub=0.24.1
4
+ beautifulsoup4=4.9.3
5
+ requests=2.25.1
scrape_audio_from_librivox.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import argparse
4
+ import requests
5
+ from bs4 import BeautifulSoup
6
+
7
+ parser = argparse.ArgumentParser(description='A program to download all the chapters in a given librivox URL.')
8
+ parser.add_argument("--save_dir",
9
+ default="./chapters",
10
+ help='directory to save the downloaded chapters. If the directory does not exist it will be made.',
11
+ required=False,
12
+ type=str)
13
+
14
+ parser.add_argument("--url",
15
+ help='URL to audiobook.',
16
+ required=True,
17
+ type=str)
18
+
19
+ args = parser.parse_args()
20
+
21
+ page = requests.get(args.url)
22
+ soup = BeautifulSoup(page.content, 'html.parser')
23
+ results = soup.find_all(class_='chapter-name')
24
+ hrefs = []
25
+ for c in results:
26
+ hrefs.append(c['href'])
27
+ print('found {} chapters to download'.format(len(hrefs)))
28
+
29
+ if not os.path.exists(args.save_dir):
30
+ os.makedirs(args.save_dir)
31
+ print('made new directory at:',args.save_dir)
32
+
33
+ for audio in hrefs:
34
+ audio_path = args.save_dir+'/'+audio.split('/')[-1][:-3]+'wav'
35
+ print('writing {} to:'.format(audio),audio_path)
36
+ file = requests.get(audio)
37
+ with open(audio_path, 'wb') as f:
38
+ f.write(file.content)