‘dalvqw’ commited on
Commit
dcd5f79
1 Parent(s): 303e4dd

增加批量总结音视频的功能

Browse files
crazy_functional.py CHANGED
@@ -246,5 +246,15 @@ def get_crazy_functions():
246
  "Function": HotReload(图片生成)
247
  },
248
  })
 
 
 
 
 
 
 
 
 
 
249
  ###################### 第n组插件 ###########################
250
  return function_plugins
 
246
  "Function": HotReload(图片生成)
247
  },
248
  })
249
+ from crazy_functions.总结音视频 import 总结音视频
250
+ function_plugins.update({
251
+ "批量总结音视频(输入路径或上传压缩包)": {
252
+ "Color": "stop",
253
+ "AsButton": False,
254
+ "AdvancedArgs": True,
255
+ "ArgsReminder": "调用openai api 使用whisper-1模型, 目前支持的格式:mp4, m4a, wav, mpga, mpeg, mp3, 此处无需输入参数",
256
+ "Function": HotReload(总结音视频)
257
+ }
258
+ })
259
  ###################### 第n组插件 ###########################
260
  return function_plugins
crazy_functions/crazy_utils.py CHANGED
@@ -606,3 +606,40 @@ def get_files_from_everything(txt, type): # type='.md'
606
  success = False
607
 
608
  return success, file_manifest, project_folder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606
  success = False
607
 
608
  return success, file_manifest, project_folder
609
+
610
+
611
+ def split_audio_file(filename, split_duration=1000):
612
+ """
613
+ 根据给定的切割时长将音频文件切割成多个片段。
614
+
615
+ Args:
616
+ filename (str): 需要被切割的音频文件名。
617
+ split_duration (int, optional): 每个切割音频片段的时长(以秒为单位)。默认值为1000。
618
+
619
+ Returns:
620
+ filelist (list): 一个包含所有切割音频片段文件路径的列表。
621
+
622
+ """
623
+ from moviepy.editor import AudioFileClip
624
+ import os
625
+ os.makedirs('gpt_log/mp3/cut/', exist_ok=True) # 创建存储切割音频的文件夹
626
+
627
+ # 读取音频文件
628
+ audio = AudioFileClip(filename)
629
+
630
+ # 计算文件总时长和切割点
631
+ total_duration = audio.duration
632
+ split_points = list(range(0, int(total_duration), split_duration))
633
+ split_points.append(int(total_duration))
634
+ filelist = []
635
+
636
+ # 切割音频文件
637
+ for i in range(len(split_points) - 1):
638
+ start_time = split_points[i]
639
+ end_time = split_points[i + 1]
640
+ split_audio = audio.subclip(start_time, end_time)
641
+ split_audio.write_audiofile(f"gpt_log/mp3/cut/{filename[0]}_{i}.mp3")
642
+ filelist.append(f"gpt_log/mp3/cut/{filename[0]}_{i}.mp3")
643
+
644
+ audio.close()
645
+ return filelist
crazy_functions/总结音视频.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from toolbox import CatchException, report_execption, select_api_key, update_ui, write_results_to_file
2
+ from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive, split_audio_file
3
+
4
+
5
+ def AnalyAudio(file_manifest, llm_kwargs, chatbot, history):
6
+ import os, requests
7
+ from moviepy.editor import AudioFileClip
8
+ from request_llm.bridge_all import model_info
9
+
10
+ # 设置OpenAI密钥和模型
11
+ api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model'])
12
+ chat_endpoint = model_info[llm_kwargs['llm_model']]['endpoint']
13
+
14
+ whisper_endpoint = chat_endpoint.replace('chat/completions', 'audio/transcriptions')
15
+ url = whisper_endpoint
16
+ headers = {
17
+ 'Authorization': f"Bearer {api_key}"
18
+ }
19
+
20
+ os.makedirs('gpt_log/mp3/', exist_ok=True)
21
+ for index, fp in enumerate(file_manifest):
22
+ audio_history = []
23
+ # 提取文件扩展名
24
+ ext = os.path.splitext(fp)[1]
25
+ # 提取视频中的音频
26
+ if ext not in [".mp3", ".wav", ".m4a", ".mpga"]:
27
+ audio_clip = AudioFileClip(fp)
28
+ audio_clip.write_audiofile(f'gpt_log/mp3/output{index}.mp3')
29
+ fp = f'gpt_log/mp3/output{index}.mp3'
30
+ # 调用whisper模型音频转文字
31
+ voice = split_audio_file(fp)
32
+ for j, i in enumerate(voice):
33
+ with open(i, 'rb') as f:
34
+ file_content = f.read() # 读取文件内容到内存
35
+ files = {
36
+ 'file': (os.path.basename(i), file_content),
37
+ }
38
+ data = {
39
+ "model": "whisper-1",
40
+ 'response_format': "text"
41
+ }
42
+ response = requests.post(url, headers=headers, files=files, data=data).text
43
+
44
+ i_say = f'请对下面的文章片段做概述,文章内容是 ```{response}```'
45
+ i_say_show_user = f'第{index + 1}段音频的第{j + 1} / {len(voice)}片段。'
46
+ gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
47
+ inputs=i_say,
48
+ inputs_show_user=i_say_show_user,
49
+ llm_kwargs=llm_kwargs,
50
+ chatbot=chatbot,
51
+ history=[],
52
+ sys_prompt="总结文章。"
53
+ )
54
+
55
+ chatbot[-1] = (i_say_show_user, gpt_say)
56
+ history.extend([i_say_show_user, gpt_say])
57
+ audio_history.extend([i_say_show_user, gpt_say])
58
+
59
+ # 已经对该文章的所有片段总结完毕,如果文章被切分了,
60
+ result = "".join(audio_history)
61
+ if len(audio_history) > 1:
62
+ i_say = f"根据以上的对话,使用中文总结文章{result}的主要内容。"
63
+ i_say_show_user = f'第{index + 1}段音频的主要内容:'
64
+ gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
65
+ inputs=i_say,
66
+ inputs_show_user=i_say_show_user,
67
+ llm_kwargs=llm_kwargs,
68
+ chatbot=chatbot,
69
+ history=audio_history,
70
+ sys_prompt="总结文章。"
71
+ )
72
+
73
+ history.extend([i_say, gpt_say])
74
+ audio_history.extend([i_say, gpt_say])
75
+
76
+ res = write_results_to_file(history)
77
+ chatbot.append((f"第{index + 1}段音频完成了吗?", res))
78
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
79
+
80
+ # 删除中间文件夹
81
+ import shutil
82
+ shutil.rmtree('gpt_log/mp3')
83
+ res = write_results_to_file(history)
84
+ chatbot.append(("所有音频都总结完成了吗?", res))
85
+ yield from update_ui(chatbot=chatbot, history=history)
86
+
87
+
88
+ @CatchException
89
+ def 总结音视频(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, WEB_PORT):
90
+ import glob, os
91
+
92
+ # 基本信息:功能、贡献者
93
+ chatbot.append([
94
+ "函数插件功能?",
95
+ "总结音视频内容,函数插件贡献者: dalvqw"])
96
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
97
+
98
+ try:
99
+ from moviepy.editor import AudioFileClip
100
+ except:
101
+ report_execption(chatbot, history,
102
+ a=f"解析项目: {txt}",
103
+ b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade moviepy```。")
104
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
105
+ return
106
+
107
+ # 清空历史,以免输入溢出
108
+ history = []
109
+
110
+ # 检测输入参数,如没有给定输入参数,直接退出
111
+ if os.path.exists(txt):
112
+ project_folder = txt
113
+ else:
114
+ if txt == "": txt = '空空如也的输入栏'
115
+ report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到本地项目或无权访问: {txt}")
116
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
117
+ return
118
+
119
+ # 搜索需要处理的文件清单
120
+ extensions = ['.mp4', '.m4a', '.wav', '.mpga', '.mpeg', '.mp3', '.avi', '.mkv', '.flac', '.aac']
121
+
122
+ if txt.endswith(tuple(extensions)):
123
+ file_manifest = [txt]
124
+ else:
125
+ file_manifest = []
126
+ for extension in extensions:
127
+ file_manifest.extend(glob.glob(f'{project_folder}/**/*{extension}', recursive=True))
128
+
129
+ # 如果没找到任何文件
130
+ if len(file_manifest) == 0:
131
+ report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到任何音频或视频文件: {txt}")
132
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
133
+ return
134
+
135
+ # 开始正式执行任务
136
+ yield from AnalyAudio(file_manifest, llm_kwargs, chatbot, history)
137
+
138
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面