File size: 2,561 Bytes
740de37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222ae43
740de37
222ae43
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import subprocess
from yt_dlp import YoutubeDL
import pandas as pd
import os
import platform
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip

#sheet_id = "1yMeqGmhDEwLvz956L-AL6rOhREo9WNvmO00-sacGkEg"
#gid = "469944202"
#df = pd.read_csv(f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?gid={gid}&format=csv")

df = pd.read_csv('./links.csv')

def ensure_hhmmss_format(t):
    parts = t.split(':')
    if len(parts) == 2: 
        return f"00:{t}"
    return t

def create_dir(string):
    try:
        os.makedirs(string)
    except Exception as e:
        ...
        
def trim_audio(input_file, start_time, end_time, output_file):
    try:
        ffmpeg_extract_subclip(input_file, float(start_time), float(end_time), targetname=output_file)
    except Exception as e:
        print(f"moviepy error: {e}")
        print("Falling back to direct ffmpeg call")

        # Detect the OS
        current_platform = platform.system()

        # Adjust command if on Windows (use 'ffmpeg.exe' if needed)
        ffmpeg_cmd = 'ffmpeg'
        if current_platform == 'Windows':
            ffmpeg_cmd = 'ffmpeg.exe'

        command = [
            ffmpeg_cmd,
            '-y',
            '-i', input_file,
            '-ss', str(start_time),  
            '-to', str(end_time),
            '-c', 'copy',
            output_file
        ]
        subprocess.run(command, check=True)

def download_audio(youtube_url, output_file):
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'outtmpl': output_file,
    }

    with YoutubeDL(ydl_opts) as ydl:
        ydl.download([youtube_url])
        
for k,v in df.T.to_dict().items():
    lst = v['timestamps'].replace("(",'').replace(')','').split(',')
    start,end = lst
    start = ensure_hhmmss_format(start)
    end = ensure_hhmmss_format(end)
    
    unique_name = k
    uid = v['id']
    category = v['category']
    
    create_dir(f"{category}/{uid}")
    
    
    download_audio(v['url'],f"{category}/{uid}/{unique_name}")

    trim_audio(f"{category}/{uid}/{unique_name}.mp3", start, end, f"{category}/{uid}/{unique_name}_{v['name'.replace(' ','_')]}_voices.mp3")

    
# clean raw voices
for root, dirs, files in os.walk(os.getcwd()):
    for file in files:
        file_path = os.path.join(root, file)
        if "voices.mp3" not in file_path and file_path.endswith(".mp3"):
            os.remove(file_path)