File size: 1,513 Bytes
77a13ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pandas as pd

# Read CSV
df = pd.read_csv('metadata.csv', sep=',')

# if directory audio does not exist, create it
if not os.path.exists('audio'):
    os.makedirs('audio')


def youtube_timer_in_seconds(time_str):
    """Converts a youtube timestamp (M:S or H:M:S) to seconds."""
    parts = str(time_str).split(':')
    seconds = 0
    try:
        if len(parts) == 2:  # M:S
            seconds = int(parts[0]) * 60 + int(parts[1])
        elif len(parts) == 3:  # H:M:S
            seconds = int(parts[0]) * 3600 + int(parts[1]) * 60 + int(parts[2])
        else:
            raise ValueError("Unsupported time format")
    except ValueError:
        raise ValueError(
            f"Invalid time format for '{time_str}'. Expected M:S or H:M:S."
        )
    return seconds


# Download audio from YouTube using yt-dlp library
for index, row in df.iterrows():

    yt_url = row["url"]
    start_time = youtube_timer_in_seconds(row["start_time"])
    end_time = youtube_timer_in_seconds(row["end_time"])

    output_template = os.path.join(
        'audio', "tmp_" + str(row["identifier"]) + ".wav"
    )

    output_final_template = str(row["file_name"])

    cmd_ytb = f'yt-dlp "{yt_url}" --extract-audio --audio-format wav --output "{output_template}"'
    print(cmd_ytb)
    cmd_ffmpeg = f"ffmpeg -y -i {output_template} -ss {start_time} -to {end_time} -c copy {output_final_template}"
    print(cmd_ffmpeg)
    cmd_rm_tmp = f"rm {output_template}"
    print(cmd_rm_tmp)

    print("-"*25)