stage4 / videos_gen_audios.py
Wangpeng An
Upload folder using huggingface_hub
b619216 verified
import os
import random
import concurrent.futures
from moviepy.editor import *
def process_video(file_path):
try:
# 加载视频文件
clip = VideoFileClip(file_path)
# 检查视频是否包含音频
if clip.audio is not None:
# 提取音频
audio = clip.audio
# 保存为随机选择的格式,文件名和原视频文件相同,保存在相同的路径下
audio_format = random.choice(["mp3", "wav"])
audio_file_path = os.path.splitext(file_path)[0] + f'.{audio_format}'
audio_file_wav = os.path.splitext(file_path)[0] + '.wav'
audio_file_mp3 = os.path.splitext(file_path)[0] + '.mp3'
if not os.path.exists(audio_file_wav) and not os.path.exists(audio_file_mp3):
audio.write_audiofile(audio_file_path)
else:
print(f"file {audio_file_path} exit.")
# 关闭音频和剪辑对象
audio.close()
clip.close()
except Exception as e:
if "Resource temporarily unavailable" in str(e):
print(f"An error occurred while processing the file {file_path}: {e}")
time.sleep(20)
else:
print(f"An error occurred while processing the file {file_path}: {e}")
def process_folder(folder_path):
video_files = []
for foldername, subfolders, filenames in os.walk(folder_path):
for filename in filenames:
if filename.endswith('.mp4') or filename.endswith('.mkv'):
video_files.append(os.path.join(foldername, filename))
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
executor.map(process_video, video_files)
if __name__ == "__main__":
folder_path = "videochatgpt_tune"
process_folder(folder_path)