Sin2pi commited on
Commit
746db4a
1 Parent(s): 8acc296

Upload code_to_extract_audio_from_any_mp4_line_by_line_from_srt_file.ipynb

Browse files
code_to_extract_audio_from_any_mp4_line_by_line_from_srt_file.ipynb ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import pandas as pd\n",
10
+ "import os, io, re, sys, time, datetime, wave, contextlib, librosa\n",
11
+ "from glob import glob\n",
12
+ "import numpy as np\n",
13
+ "from moviepy.editor import *\n",
14
+ "import soundfile as sf\n",
15
+ "from pydub import AudioSegment\n",
16
+ "\n",
17
+ "def create_directories():\n",
18
+ " slice_path = './ready_for_slice'\n",
19
+ " if not os.path.exists(slice_path):\n",
20
+ " try:\n",
21
+ " os.mkdir(slice_path)\n",
22
+ " except OSError:\n",
23
+ " print('Creation of directory %s failed' %slice_path)\n",
24
+ " sliced_audio = './sliced_audio'\n",
25
+ " if not os.path.exists(sliced_audio):\n",
26
+ " try:\n",
27
+ " os.mkdir(sliced_audio)\n",
28
+ " except OSError:\n",
29
+ " print('Creation of directory %s failed' %sliced_audio)\n",
30
+ "\n",
31
+ " merged_csv_files = './merged_csv'\n",
32
+ " if not os.path.exists(merged_csv_files):\n",
33
+ " try:\n",
34
+ " os.mkdir(merged_csv_files)\n",
35
+ " except OSError:\n",
36
+ " print('Creation of directory %s failed' %merged_csv_files)\n",
37
+ "\n",
38
+ " final_csv_files = './final_csv'\n",
39
+ " if not os.path.exists(final_csv_files):\n",
40
+ " try:\n",
41
+ " os.mkdir(final_csv_files)\n",
42
+ " except OSError:\n",
43
+ " print('Creation of directory %s failed' %final_csv_files)\n",
44
+ " \n",
45
+ " audio = './audio'\n",
46
+ " if not os.path.exists(audio):\n",
47
+ " try:\n",
48
+ " os.mkdir(audio)\n",
49
+ " except OSError:\n",
50
+ " print('Creation of directory %s failed' %audio)\n",
51
+ " \n",
52
+ " srt_files = './srt_files'\n",
53
+ " if not os.path.exists(srt_files):\n",
54
+ " try:\n",
55
+ " os.mkdir(srt_files)\n",
56
+ " except OSError:\n",
57
+ " print('Creation of directory %s failed' %srt_files)\n",
58
+ "\n",
59
+ "def merge_csv(path):\n",
60
+ " print('Merging csv-files with transcriptions')\n",
61
+ " csv_combined = pd.DataFrame()\n",
62
+ " for entry in glob (path+'*.csv'):\n",
63
+ " df = pd.read_csv(entry)\n",
64
+ " csv_combined = csv_combined.append(df)\n",
65
+ "\n",
66
+ " csv_combined.to_csv('./merged_csv/Full_Transcript.csv', header=True, index=False, encoding='utf-8')\n",
67
+ " print('All csv-files merged')\n",
68
+ "\n",
69
+ "def change_encoding(srt):\n",
70
+ " with io.open(srt, 'r', encoding='utf-8') as f:\n",
71
+ " text = f.read()\n",
72
+ " # process Unicode text\n",
73
+ " with io.open(srt, 'w', encoding='utf-8') as f:\n",
74
+ " f.write(text)\n",
75
+ "\n",
76
+ "def convert_srt_to_csv(file):\n",
77
+ " with open(file, 'r', encoding='utf-8') as h:\n",
78
+ " sub = h.readlines() #returns list of all lines\n",
79
+ "\n",
80
+ " re_pattern = r'[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} --> [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}'\n",
81
+ " regex = re.compile(re_pattern)\n",
82
+ " # Get start times\n",
83
+ " times = list(filter(regex.search, sub))\n",
84
+ " end_times = [time.split('--> ')[1] for time in times] #returns a list\n",
85
+ " start_times = [time.split(' ')[0] for time in times] #returns a list\n",
86
+ "\n",
87
+ " # Get lines\n",
88
+ " lines = [[]]\n",
89
+ " for sentence in sub:\n",
90
+ " if re.match(re_pattern, sentence):\n",
91
+ " lines[-1].pop()\n",
92
+ " lines.append([])\n",
93
+ " else:\n",
94
+ " lines[-1].append(sentence)\n",
95
+ "\n",
96
+ " lines = lines[1:] #all text in lists\n",
97
+ "\n",
98
+ " column_names = ['id','start_times', 'end_times', 'sentence']\n",
99
+ " df_text = pd.DataFrame(columns=column_names)\n",
100
+ "\n",
101
+ " df_text['start_times'] = start_times\n",
102
+ " df_text['end_times'] = end_times\n",
103
+ " df_text['sentence'] = [\" \".join(i).replace('\\n', '') for i in lines]\n",
104
+ " df_text['end_times'] = df_text['end_times'].replace(r'\\n', '', regex=True)\n",
105
+ "\n",
106
+ " df_text['id'] = np.arange(len(df_text))\n",
107
+ " id_extension = os.path.basename(file).replace('.srt', '_')\n",
108
+ " id_extension = id_extension.replace(' ', '_')\n",
109
+ " id_extension = id_extension.replace('-', '_')\n",
110
+ " id_extension = id_extension.replace('.', '_')\n",
111
+ " id_extension = id_extension.replace('__', '_')\n",
112
+ " id_extension = id_extension.replace('___', '_')\n",
113
+ " df_text['id'] = id_extension + df_text['id'].map(str)\n",
114
+ " file_extension = id_extension[:-1]\n",
115
+ "\n",
116
+ " def convert_to_ms(time):\n",
117
+ " h_ms = int(time[:2])*3600000\n",
118
+ " m_ms = int(time[3:5])*60000\n",
119
+ " s_ms = int(time[6:8])*1000\n",
120
+ " ms = int(time[9:12])\n",
121
+ " ms_total = h_ms + m_ms + s_ms + ms\n",
122
+ " return(ms_total)\n",
123
+ "\n",
124
+ " def conv_int(start):\n",
125
+ " new_start = int(start)\n",
126
+ " return(new_start)\n",
127
+ "\n",
128
+ " df_text['start_times'] = df_text['start_times'].apply(convert_to_ms)\n",
129
+ " df_text['end_times'] = df_text['end_times'].apply(convert_to_ms)\n",
130
+ " df_text['start_times'] = df_text['start_times'].apply(conv_int)\n",
131
+ " df_text.to_csv('./ready_for_slice/' + file_extension + '.csv', index=False, header=True, encoding='utf-8-sig')\n",
132
+ "\n",
133
+ "def wmv_to_wav(entry):\n",
134
+ " video = VideoFileClip(entry)\n",
135
+ " audio = video.audio\n",
136
+ " filename = os.path.basename(entry)\n",
137
+ " filename = filename.replace(' ', '_')\n",
138
+ " filename = filename.replace('-', '_')\n",
139
+ " filename = filename.replace('.', '_')\n",
140
+ " filename = filename.replace('__', '_')\n",
141
+ " filename = filename.replace('___', '_')\n",
142
+ " filename = filename[:-4] + '.wav'\n",
143
+ " audio.write_audiofile('./audio/' +filename)\n",
144
+ "\n",
145
+ "def mp4_to_wav(entry):\n",
146
+ " video = VideoFileClip(entry)\n",
147
+ " #extract audio from video\n",
148
+ " audio = video.audio\n",
149
+ " filename = os.path.basename(entry)\n",
150
+ " filename = filename.replace(' ', '_')\n",
151
+ " filename = filename.replace('-', '_')\n",
152
+ " filename = filename.replace('.', '_')\n",
153
+ " filename = filename.replace('__', '_')\n",
154
+ " filename = filename.replace('___', '_')\n",
155
+ " filename = filename[:-4] + '.wav'\n",
156
+ " #filename = filename[:-4]+'.wav'\n",
157
+ " #filename = filename[:10] + '_' + filename[-9:]\n",
158
+ " audio.write_audiofile('./audio/' +filename)\n",
159
+ "\n",
160
+ "def pre_process_audio(audio_path):\n",
161
+ " path_audio_processed = './ready_for_slice/'\n",
162
+ " if not os.path.exists(path_audio_processed):\n",
163
+ " try:\n",
164
+ " os.mkdir(path_audio_processed)\n",
165
+ " except OSError:\n",
166
+ " print('Creation of directory %s failed' %path_audio_processed)\n",
167
+ " else:\n",
168
+ " print('Successfully created the directory %s' %path_audio_processed)\n",
169
+ " start_sub = time.time()\n",
170
+ " n = 0\n",
171
+ " print('Downsampling wav files...')\n",
172
+ " for file in os.listdir(audio_path):\n",
173
+ " if(file.endswith('.wav')):\n",
174
+ " try:\n",
175
+ " nameSolo_1 = file.rsplit('.', 1)[0]\n",
176
+ " y, s = librosa.load(audio_path + file, sr=16000) # Downsample 44.1kHz to 8kHz\n",
177
+ " sf.write(path_audio_processed + nameSolo_1 + '.wav', y, s)\n",
178
+ " n = n+1\n",
179
+ " print('File ', n , ' completed:', nameSolo_1)\n",
180
+ " except EOFError as error:\n",
181
+ " next\n",
182
+ "\n",
183
+ " s = 0\n",
184
+ " print('Changing bit pro sample...')\n",
185
+ " for file in os.listdir(path_audio_processed):\n",
186
+ " if(file.endswith('.wav')):\n",
187
+ " try:\n",
188
+ " nameSolo_2 = file.rsplit('.', 1)[0]\n",
189
+ " #nameSolo_2 = nameSolo_2.replace('')\n",
190
+ " data, samplerate = sf.read(path_audio_processed + file)\n",
191
+ " sf.write(path_audio_processed + nameSolo_2 + '.wav', data, samplerate, subtype='PCM_16')\n",
192
+ " s = s + 1\n",
193
+ " print('File ' , s , ' completed')\n",
194
+ " except EOFError as error:\n",
195
+ " next\n",
196
+ "\n",
197
+ " end_sub = time.time()\n",
198
+ " print('The script took ', end_sub-start_sub, ' seconds to run')\n",
199
+ " \n",
200
+ "def create_DS_csv (path):\n",
201
+ " print('Extracting filepath and -size for every .wav file in ./sliced_audio')\n",
202
+ " data = pd.DataFrame(columns=['file_name', 'duration'])\n",
203
+ " df = pd.DataFrame(columns=['file_name', 'duration'])\n",
204
+ "\n",
205
+ " for entry in glob(path +'*.wav'):\n",
206
+ " filename = os.path.basename(entry)\n",
207
+ " with contextlib.closing(wave.open(entry, 'rb')) as f:\n",
208
+ " frames = f.getnframes()\n",
209
+ " rate = f.getframerate()\n",
210
+ " duration = frames / float(rate)\n",
211
+ " df['file_name'] = [filename]\n",
212
+ " df['duration'] = [duration]\n",
213
+ " data = data.append(df)\n",
214
+ " data.to_csv('./merged_csv/Filepath_Filesize.csv', header=True, index=False, encoding='utf-8')\n",
215
+ "\n",
216
+ "def split_files(item, wav_item):\n",
217
+ " song = AudioSegment.from_wav(wav_item)\n",
218
+ " df = pd.read_csv(item)\n",
219
+ "\n",
220
+ " def audio_split(df):\n",
221
+ " split = song[df['start_times']:df['end_times']]\n",
222
+ " split.export('./sliced_audio/' + df['id'] + '.wav', format ='wav')\n",
223
+ "\n",
224
+ " df.apply(audio_split, axis=1)\n",
225
+ "\n",
226
+ "def merge_transcripts_and_wav_files(transcript_path, DS_csv):\n",
227
+ " df_final = pd.DataFrame()\n",
228
+ " df_transcripts = pd.read_csv(transcript_path)\n",
229
+ " df_files = pd.read_csv(DS_csv)\n",
230
+ " def remove_path(path):\n",
231
+ " path = path.split('/')[-1]\n",
232
+ " return path\n",
233
+ " df_files['id'] = df_files['file_name'].apply(remove_path)\n",
234
+ " #filter out duration of less than 10 seconds\n",
235
+ " def convert(duration):\n",
236
+ " time = float(duration)\n",
237
+ " return time\n",
238
+ " df_files['duration'] = df_files['duration'].apply(convert)\n",
239
+ " df_files = df_files[df_files['duration']<10.00]\n",
240
+ " #drop unnecessary columns\n",
241
+ " df_transcripts.drop(['start_times','end_times'], axis=1, inplace=True)\n",
242
+ " df_files.drop(['duration'], axis=1, inplace=True)\n",
243
+ " df_files['id'] = df_files['id'].replace('.wav', '', regex=True)\n",
244
+ " #merge on column id\n",
245
+ " df_final = pd.merge(df_transcripts, df_files, on='id')\n",
246
+ " df_final.drop(['id'], axis=1, inplace=True)\n",
247
+ " #rearrange columns\n",
248
+ " df_final = df_final[['file_name', 'sentence']]\n",
249
+ " df_final.to_csv('./final_csv/metadata.csv', header=True, index=False, encoding='utf-8')\n",
250
+ " \n",
251
+ " create_directories()\n",
252
+ " \n",
253
+ "print(\"Put your video or audio files into the audio folder and srt files into the srt_files folder when you're ready...\")"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "execution_count": null,
259
+ "metadata": {},
260
+ "outputs": [],
261
+ "source": [
262
+ "start_time = time.time()\n",
263
+ "srt_path = './srt_files'\n",
264
+ "audio_path = './audio/'\n",
265
+ "srt_counter = len(glob('./srt_files/' + '*.srt'))\n",
266
+ "\n",
267
+ "#Extracting information from srt-files to csv\n",
268
+ "print('Extracting information from srt_file(s) to csv_files')\n",
269
+ "for file in glob('./srt_files/*.srt'):\n",
270
+ " convert_srt_to_csv(file)\n",
271
+ "print('%s-file(s) converted and saved as csv-files to ./csv' %srt_counter)\n",
272
+ "print('---------------------------------------------------------------------')\n",
273
+ "\n",
274
+ "#extract audio (wav) from mp4\n",
275
+ "for entry in glob('./audio/*.mp4'):\n",
276
+ " mp4_to_wav(entry)\n",
277
+ "print('MP4 to WAV convert complete')\n",
278
+ "print('---------------------------------------------------------------------')\n",
279
+ "\n",
280
+ "\n",
281
+ "#Pre-process audio for folder in which wav files are stored\n",
282
+ "pre_process_audio(audio_path)\n",
283
+ "print('Pre-processing of audio files is complete.')\n",
284
+ "print('---------------------------------------------------------------------')\n",
285
+ "\n",
286
+ "print('Slicing audio according to start- and end_times of transcript_csvs...')\n",
287
+ "for item in glob('./ready_for_slice/*.csv'):\n",
288
+ " wav_item = item.replace('.csv','.wav')\n",
289
+ " if os.path.exists(wav_item):\n",
290
+ " split_files(item, wav_item)\n",
291
+ " else:\n",
292
+ " next\n",
293
+ "wav_counter = len(glob('./sliced_audio/' + '*.wav'))\n",
294
+ "print('Slicing complete. {} files in dir \"sliced_audio\"'.format(wav_counter))\n",
295
+ "print('---------------------------------------------------------------------')\n",
296
+ "\n",
297
+ "create_DS_csv('./sliced_audio/')\n",
298
+ "\n",
299
+ "#now join all seperate csv files\n",
300
+ "merge_csv('./ready_for_slice/')\n",
301
+ "print('Merged csv with all transcriptions created.')\n",
302
+ "print('---------------------------------------------------------------------')\n",
303
+ "transcript_path = './merged_csv/Full_Transcript.csv'\n",
304
+ "DS_path = './merged_csv/Filepath_Filesize.csv'\n",
305
+ "merge_transcripts_and_wav_files(transcript_path, DS_path)"
306
+ ]
307
+ }
308
+ ],
309
+ "metadata": {
310
+ "kernelspec": {
311
+ "display_name": "Python 3",
312
+ "language": "python",
313
+ "name": "python3"
314
+ },
315
+ "language_info": {
316
+ "codemirror_mode": {
317
+ "name": "ipython",
318
+ "version": 3
319
+ },
320
+ "file_extension": ".py",
321
+ "mimetype": "text/x-python",
322
+ "name": "python",
323
+ "nbconvert_exporter": "python",
324
+ "pygments_lexer": "ipython3",
325
+ "version": "3.10.0"
326
+ }
327
+ },
328
+ "nbformat": 4,
329
+ "nbformat_minor": 2
330
+ }