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