不需要手动创建 audio 和 text 文件夹。代码中已经包含了自动创建这些文件夹的逻辑。具体来说,代码会在运行时检查这些文件夹是否存在,如果不存在则会自动创建它们。
以下是关键部分的代码,确保这些文件夹在运行时会被创建:
if __name__ == '__main__':
# 确保目录存在
os.makedirs(AUDIO_DIR, exist_ok=True)
os.makedirs(TEXT_DIR, exist_ok=True)
print(f"Ensured directories '{AUDIO_DIR}' and '{TEXT_DIR}' exist.")
os.makedirs 函数会创建指定的目录,如果目录已经存在,exist_ok=True 会确保不会抛出错误。
完整的修改后的代码
为了确保您的代码能够正确运行,以下是完整的修改后的代码:
import os
import torch
import warnings
import sys
from pydub import AudioSegment
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
from datasets import load_dataset
warnings.filterwarnings("ignore")
# 定义输出目录常量
AUDIO_DIR = "audio"
TEXT_DIR = "text"
def listfiles(root_dir):
arrfile = []
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
# 过滤掉 macOS 自动生成的隐藏文件
if filename.startswith('.'):
continue
file_path = os.path.join(dirpath, filename)
arrfile.append(file_path)
return arrfile
def extract_audio_pydub(input_video):
audio = AudioSegment.from_file(input_video, format="mp4")
base_name = os.path.splitext(os.path.basename(input_video))[0]
output_filename = f"{base_name}.mp3"
# 确保输出目录存在
if not os.path.exists(AUDIO_DIR):
os.makedirs(AUDIO_DIR)
print(f"Created directory: {AUDIO_DIR}")
# 使用 os.path.join 构建完整的输出路径
full_output_path = os.path.join(AUDIO_DIR, output_filename)
audio.export(full_output_path, format="mp3")
print(f"Extract {output_filename} done.\r\n")
def asr(audio_file_path):
device = "cuda:0" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_id = "/Users/liukairui/whisper-large-v3"
model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
)
model.to(device)
processor = AutoProcessor.from_pretrained(model_id)
pipe = pipeline(
"automatic-speech-recognition",
model=model,
tokenizer=processor.tokenizer,
feature_extractor=processor.feature_extractor,
torch_dtype=torch_dtype,
device=device,
return_timestamps=True
)
result = pipe(audio_file_path, batch_size=4)
base_name = os.path.splitext(os.path.basename(audio_file_path))[0]
txt_filename = f"{base_name}.txt"
# 确保输出目录存在
if not os.path.exists(TEXT_DIR):
os.makedirs(TEXT_DIR)
print(f"Created directory: {TEXT_DIR}")
# 使用 os.path.join 构建完整的文本输出路径
full_txt_path = os.path.join(TEXT_DIR, txt_filename)
with open(full_txt_path, 'w', encoding='utf-8') as file:
file.write(result["text"])
print(f"Transcribe {audio_file_path} and save to {txt_filename} done.\r\n")
def mergetxt():
arrfile = listfiles(TEXT_DIR)
with open("merged.txt", 'w', encoding='utf-8') as outfile:
for eachfile in arrfile:
with open(eachfile, 'r', encoding='utf-8') as infile:
outfile.write(f"\n=== {os.path.basename(eachfile)} ===\n")
outfile.write(infile.read())
print(f"Merged txt done!")
if __name__ == '__main__':
# 确保目录存在
os.makedirs(AUDIO_DIR, exist_ok=True)
os.makedirs(TEXT_DIR, exist_ok=True)
print(f"Ensured directories '{AUDIO_DIR}' and '{TEXT_DIR}' exist.")
# 处理视频文件
arrfile = listfiles(sys.argv[1])
for eachfile in arrfile:
extract_audio_pydub(eachfile)
# 处理音频文件
arrfile = listfiles(AUDIO_DIR)
for eachfile in arrfile:
asr(eachfile)
mergetxt()