File size: 1,855 Bytes
111e2ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from mutagen.flac import FLAC
from mutagen.mp3 import MP3

import io
import ast



def _get_audio_duration(bytes, file_type):
    """
    Get the flac file duration. 
    """

    # Load the byte data into a BytesIO object
    data = io.BytesIO(bytes)

    if file_type == "flac":
        # Load the bytes data
        audio = FLAC(data)
    if file_type == "mp3":
        audio = MP3(data)
    
    # Get the duration in seconds
    duration = audio.info.length

    return str(duration)
# ---
# Have to make two seperate functions to process audio string, 
# in order to handle the dask partition properly. 
def process_audio_string_path(audio_str):
    audio_dict = ast.literal_eval(audio_str)
    return audio_dict["path"]

def process_audio_string_duration(audio_str):
    audio_dict = ast.literal_eval(audio_str)
    path = audio_dict["path"]
    a_type = path.split(".")[1]
    try:
        duration = _get_audio_duration(audio_dict["bytes"], a_type)
        return duration
    except Exception as e:
        print(f"Get error {e}")
        return "n/a"

def process_audio_partition(partition):
    """
    Process the audio column from the dataframe to get the path and duration.
    
    """
    # Perform operations on each partition as if it were a Pandas DataFrame
    partition['path'] = partition['audio'].apply(process_audio_string_path)
    partition['duration'] = partition['audio'].apply(process_audio_string_duration)
    return partition


def process_audio_column(result_df):

    # Extra steps to hanlde audio column.
    meta = result_df.head(0)  # Use the structure of the original DataFrame and add the new column
    meta['path'] = 'string'  
    meta['duration'] = 'string'
    
    result_df = result_df.map_partitions(process_audio_partition, meta=meta)
    result_df = result_df.drop(columns=['audio'])

    return result_df