SoundHarvest / generate_dataset.py
0x22almostEvil's picture
Upload 5 files
7beabae
import subprocess
import os
import glob
import shutil
from concurrent.futures import ThreadPoolExecutor
def move_to_unmatched(base_path, lang, audio_exists, subtitle_exists):
unmatched_path = os.path.join(base_path, "unmatched", lang)
os.makedirs(unmatched_path, exist_ok=True)
if audio_exists:
audio_file = glob.glob(f"{base_path}/{lang}.wav")[0]
shutil.move(audio_file, unmatched_path)
if subtitle_exists:
subtitle_file = glob.glob(f"{base_path}/{lang}.vtt")[0]
shutil.move(subtitle_file, unmatched_path)
def download_and_convert_audio(video_url, languages):
video_id = video_url.split('=')[-1]
base_path = f"dataset/{video_id}"
os.makedirs(base_path, exist_ok=True)
for lang in languages:
command_download = [
'yt-dlp',
'--extract-audio',
'--audio-format', 'm4a',
'--write-sub',
'--sub-langs', lang,
'--sub-format', 'vtt',
'--output', f"{base_path}/%(title)s.{lang}.%(ext)s",
'--format', f'bestaudio[ext=m4a][acodec=mp4a.40.2][language={lang}]',
video_url
]
subprocess.run(command_download)
m4a_files = glob.glob(f"{base_path}/*.{lang}.m4a")
if m4a_files:
m4a_file = m4a_files[0]
wav_file = f"{base_path}/{lang}.wav"
command_convert = ['ffmpeg', '-i', m4a_file, '-acodec', 'pcm_s16le', '-ar', '44100', wav_file]
subprocess.run(command_convert)
os.remove(m4a_file)
vtt_files = glob.glob(f"{base_path}/*.{lang}.vtt")
if vtt_files:
vtt_file = vtt_files[0]
new_vtt_file = f"{base_path}/{lang}.vtt"
os.rename(vtt_file, new_vtt_file)
audio_exists = bool(glob.glob(f"{base_path}/{lang}.wav"))
subtitle_exists = bool(glob.glob(f"{base_path}/{lang}.vtt"))
if not (audio_exists and subtitle_exists):
move_to_unmatched(base_path, lang, audio_exists, subtitle_exists)
def process_video(url, languages):
try:
download_and_convert_audio(url, languages)
except Exception as e:
print(f"Error processing {url}: {e}")
if __name__ == "__main__":
video_urls = []
with open('urls.txt', 'r') as file:
video_urls = [line.strip() for line in file if line.strip()]
languages = ["ar", "es", "fr", "hi", "id", "ja", "ko", "pt", "ru", "th", "tr", "vi", "en"]
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(process_video, url, languages) for url in video_urls]
for future in futures:
future.result()