-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto_rename_video_all
51 lines (40 loc) · 1.81 KB
/
auto_rename_video_all
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 subprocess
import openai
# 设置 API 密钥
openai.api_key = "你的密钥"
# 设置音频持续时间
audio_duration = 10
# 获取当前目录及其子文件夹下的所有 MP4 文件
video_files = []
for root, dirs, files in os.walk(os.getcwd()):
for file in files:
if (file.endswith(".MP4") or file.endswith(".mp4")) and not file.startswith("._"):
video_files.append(os.path.join(root, file))
# 定义处理视频文件的函数
def process_video_file(video_file_path):
temp_audio_path = os.path.join(os.getcwd(), "temp_audio.wav")
# 使用 ffmpeg 从视频中提取前 audio_duration 秒的音频
subprocess.run([
"ffmpeg", "-y", "-i", video_file_path,
"-ss", "0", "-t", str(audio_duration), "-vn", "-acodec", "pcm_s16le", "-f", "wav",
temp_audio_path
], check=True, text=True)
# 使用 OpenAI API 识别音频文件
with open(temp_audio_path, "rb") as audio_file:
transcript = openai.Audio.transcribe("whisper-1", audio_file)
recognized_text = transcript['text']
print(f"识别到的文本: {recognized_text}")
# 修复文件名中的非法字符
fixed_text = "".join([c if c.isalnum() or c.isspace() else "-" for c in recognized_text])
# 重命名视频文件
original_file_name, original_file_ext = os.path.splitext(os.path.basename(video_file_path))
new_video_path = os.path.join(os.path.dirname(video_file_path), f"{original_file_name}_{fixed_text}{original_file_ext}")
os.rename(video_file_path, new_video_path)
print(f"视频已重命名为:{new_video_path}")
# 删除临时音频文件
os.remove(temp_audio_path)
# 对目录及其子文件夹中的每个视频文件执行处理
for video_file in video_files:
print(f"处理文件:{video_file}")
process_video_file(video_file)