jayliqinzhang commited on
Commit
111e2ad
·
verified ·
1 Parent(s): 9f88c5c

Upload script/process_audio.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. script/process_audio.py +66 -0
script/process_audio.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mutagen.flac import FLAC
2
+ from mutagen.mp3 import MP3
3
+
4
+ import io
5
+ import ast
6
+
7
+
8
+
9
+ def _get_audio_duration(bytes, file_type):
10
+ """
11
+ Get the flac file duration.
12
+ """
13
+
14
+ # Load the byte data into a BytesIO object
15
+ data = io.BytesIO(bytes)
16
+
17
+ if file_type == "flac":
18
+ # Load the bytes data
19
+ audio = FLAC(data)
20
+ if file_type == "mp3":
21
+ audio = MP3(data)
22
+
23
+ # Get the duration in seconds
24
+ duration = audio.info.length
25
+
26
+ return str(duration)
27
+ # ---
28
+ # Have to make two seperate functions to process audio string,
29
+ # in order to handle the dask partition properly.
30
+ def process_audio_string_path(audio_str):
31
+ audio_dict = ast.literal_eval(audio_str)
32
+ return audio_dict["path"]
33
+
34
+ def process_audio_string_duration(audio_str):
35
+ audio_dict = ast.literal_eval(audio_str)
36
+ path = audio_dict["path"]
37
+ a_type = path.split(".")[1]
38
+ try:
39
+ duration = _get_audio_duration(audio_dict["bytes"], a_type)
40
+ return duration
41
+ except Exception as e:
42
+ print(f"Get error {e}")
43
+ return "n/a"
44
+
45
+ def process_audio_partition(partition):
46
+ """
47
+ Process the audio column from the dataframe to get the path and duration.
48
+
49
+ """
50
+ # Perform operations on each partition as if it were a Pandas DataFrame
51
+ partition['path'] = partition['audio'].apply(process_audio_string_path)
52
+ partition['duration'] = partition['audio'].apply(process_audio_string_duration)
53
+ return partition
54
+
55
+
56
+ def process_audio_column(result_df):
57
+
58
+ # Extra steps to hanlde audio column.
59
+ meta = result_df.head(0) # Use the structure of the original DataFrame and add the new column
60
+ meta['path'] = 'string'
61
+ meta['duration'] = 'string'
62
+
63
+ result_df = result_df.map_partitions(process_audio_partition, meta=meta)
64
+ result_df = result_df.drop(columns=['audio'])
65
+
66
+ return result_df