Update app.py
Browse files
app.py
CHANGED
@@ -3,160 +3,177 @@ import spaces
|
|
3 |
import gradio as gr
|
4 |
import os
|
5 |
from pyannote.audio import Pipeline
|
|
|
6 |
from pydub import AudioSegment
|
7 |
|
8 |
# 获取 Hugging Face 认证令牌
|
9 |
HF_TOKEN = os.environ.get("HUGGINGFACE_READ_TOKEN")
|
10 |
-
pipeline = None
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
"
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
#
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
target_audio_segment = AudioSegment.from_wav(target_audio)
|
35 |
-
except Exception as e:
|
36 |
-
return f"加载目标音频时出错: {e}"
|
37 |
-
|
38 |
-
# 加载混合音频
|
39 |
-
try:
|
40 |
-
mixed_audio_segment = AudioSegment.from_wav(mixed_audio)
|
41 |
-
except Exception as e:
|
42 |
-
return f"加载混合音频时出错: {e}"
|
43 |
-
|
44 |
-
# 记录目标说话人音频的时间点(精确到0.01秒)
|
45 |
-
target_start_time = len(mixed_audio_segment) / 1000 # 秒为单位,精确到 0.01 秒
|
46 |
-
|
47 |
-
# 目标音频的结束时间(拼接后的音频长度)
|
48 |
-
target_end_time = target_start_time + len(target_audio_segment) / 1000 # 秒为单位
|
49 |
-
|
50 |
-
# 将目标说话人的音频片段添加到混合音频的最后
|
51 |
-
final_audio = mixed_audio_segment + target_audio_segment
|
52 |
-
final_audio.export("final_output.wav", format="wav")
|
53 |
-
|
54 |
-
# 返回目标音频的起始时间和结束时间
|
55 |
-
return {"start_time": target_start_time, "end_time": target_end_time}
|
56 |
-
|
57 |
-
# 使用 pyannote/speaker-diarization 对拼接后的音频进行说话人分离
|
58 |
-
@spaces.GPU(duration=60 * 2) # 使用 GPU 加速,限制执行时间为 120 秒
|
59 |
-
def diarize_audio(temp_file):
|
60 |
-
if pipeline is None:
|
61 |
-
return "错误: 模型未初始化"
|
62 |
-
|
63 |
-
try:
|
64 |
-
diarization = pipeline(temp_file)
|
65 |
-
except Exception as e:
|
66 |
-
return f"处理音频时出错: {e}"
|
67 |
-
|
68 |
-
print(type(diarization))
|
69 |
-
# 返回 diarization 输出
|
70 |
-
return str(diarization)
|
71 |
-
|
72 |
-
# 将时间戳转换为秒
|
73 |
-
def timestamp_to_seconds(timestamp):
|
74 |
-
try:
|
75 |
-
h, m, s = map(float, timestamp.split(':'))
|
76 |
-
return 3600 * h + 60 * m + s
|
77 |
-
except ValueError as e:
|
78 |
-
print(f"转换时间戳时出错: '{timestamp}'. 错误: {e}")
|
79 |
-
return None
|
80 |
-
|
81 |
-
# 计算时间段的重叠部分(单位:秒)
|
82 |
-
def calculate_overlap(start1, end1, start2, end2):
|
83 |
-
overlap_start = max(start1, start2)
|
84 |
-
overlap_end = min(end1, end2)
|
85 |
-
overlap_duration = max(0, overlap_end - overlap_start)
|
86 |
-
return overlap_duration
|
87 |
-
|
88 |
-
# 获取目标时间段和说话人时间段的重叠比例
|
89 |
-
def get_best_match(target_time, diarization_output):
|
90 |
-
target_start_time = target_time['start_time']
|
91 |
-
target_end_time = target_time['end_time']
|
92 |
-
|
93 |
-
# 假设 diarization_output 是一个列表,包含说话人时间段和标签
|
94 |
-
speaker_segments = []
|
95 |
-
for line in diarization_output.strip().split('\n'):
|
96 |
try:
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
-
|
103 |
-
|
104 |
|
105 |
-
|
106 |
-
|
107 |
-
overlap_ratio = overlap / (end_seconds - start_seconds)
|
108 |
|
109 |
-
|
110 |
-
|
|
|
111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
except Exception as e:
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
# Gradio 接口
|
142 |
with gr.Blocks() as demo:
|
143 |
gr.Markdown("""
|
144 |
# 🗣️ 音频拼接与说话人分类 🗣️
|
145 |
-
|
146 |
""")
|
147 |
-
|
148 |
mixed_audio_input = gr.Audio(type="filepath", label="上传混合音频")
|
149 |
target_audio_input = gr.Audio(type="filepath", label="上传目标说话人音频")
|
150 |
-
|
151 |
process_button = gr.Button("处理音频")
|
152 |
-
|
153 |
# 输出结果
|
154 |
diarization_output = gr.Textbox(label="最佳匹配说话人")
|
155 |
time_range_output = gr.Textbox(label="最佳匹配时间段")
|
156 |
|
157 |
# 点击按钮时触发处理音频
|
158 |
process_button.click(
|
159 |
-
fn=process_audio,
|
160 |
inputs=[target_audio_input, mixed_audio_input],
|
161 |
outputs=[diarization_output, time_range_output]
|
162 |
)
|
|
|
3 |
import gradio as gr
|
4 |
import os
|
5 |
from pyannote.audio import Pipeline
|
6 |
+
from pyannote.core import Annotation, Segment
|
7 |
from pydub import AudioSegment
|
8 |
|
9 |
# 获取 Hugging Face 认证令牌
|
10 |
HF_TOKEN = os.environ.get("HUGGINGFACE_READ_TOKEN")
|
|
|
11 |
|
12 |
+
class AudioProcessor:
|
13 |
+
def __init__(self):
|
14 |
+
self.pipeline = None
|
15 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
16 |
+
|
17 |
+
# 尝试加载 pyannote 模型
|
18 |
+
try:
|
19 |
+
self.pipeline = Pipeline.from_pretrained(
|
20 |
+
"pyannote/speaker-diarization-3.1", use_auth_token=HF_TOKEN
|
21 |
+
)
|
22 |
+
self.pipeline.to(self.device)
|
23 |
+
print("pyannote model loaded successfully.")
|
24 |
+
except Exception as e:
|
25 |
+
print(f"Error initializing pipeline: {e}")
|
26 |
+
self.pipeline = None
|
27 |
+
|
28 |
+
# 音频拼接函数:拼接目标音频和混合音频,返回目标音频的起始时间和结束时间作为字典
|
29 |
+
def combine_audio_with_time(self, target_audio, mixed_audio):
|
30 |
+
if self.pipeline is None:
|
31 |
+
return "错误: 模型未初始化"
|
32 |
+
|
33 |
+
# 加载目标说话人的样本音频
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
try:
|
35 |
+
target_audio_segment = AudioSegment.from_wav(target_audio)
|
36 |
+
except Exception as e:
|
37 |
+
return f"加载目标音频时出错: {e}"
|
38 |
+
|
39 |
+
# 加载混合音频
|
40 |
+
try:
|
41 |
+
mixed_audio_segment = AudioSegment.from_wav(mixed_audio)
|
42 |
+
except Exception as e:
|
43 |
+
return f"加载混合音频时出错: {e}"
|
44 |
|
45 |
+
# 记录目标说话人音频的时间点(精确到0.01秒)
|
46 |
+
target_start_time = len(mixed_audio_segment) / 1000 # 秒为单位,精确到 0.01 秒
|
47 |
|
48 |
+
# 目标音频的结束时间(拼接后的音频长度)
|
49 |
+
target_end_time = target_start_time + len(target_audio_segment) / 1000 # 秒为单位
|
|
|
50 |
|
51 |
+
# 将目标说话人的音频片段添加到混合音频的最后
|
52 |
+
final_audio = mixed_audio_segment + target_audio_segment
|
53 |
+
final_audio.export("final_output.wav", format="wav")
|
54 |
|
55 |
+
# 返回目标音频的起始时间和结束时间
|
56 |
+
return {"start_time": target_start_time, "end_time": target_end_time}
|
57 |
+
|
58 |
+
# 使用 pyannote/speaker-diarization 对拼接后的音频进行说话人分离
|
59 |
+
@spaces.GPU(duration=60 * 2) # 使用 GPU 加速,限制执行时间为 120 秒
|
60 |
+
def diarize_audio(self, temp_file):
|
61 |
+
if self.pipeline is None:
|
62 |
+
return "错误: 模型未初始化"
|
63 |
+
|
64 |
+
try:
|
65 |
+
diarization = self.pipeline(temp_file) # 返回 Annotation 对象
|
66 |
except Exception as e:
|
67 |
+
return f"处理音频时出错: {e}"
|
68 |
+
|
69 |
+
return diarization # 直接返回 Annotation 对象
|
70 |
+
|
71 |
+
# 将时间戳转换为秒
|
72 |
+
def timestamp_to_seconds(self, timestamp):
|
73 |
+
try:
|
74 |
+
h, m, s = map(float, timestamp.split(':'))
|
75 |
+
return 3600 * h + 60 * m + s
|
76 |
+
except ValueError as e:
|
77 |
+
print(f"转换时间戳时出错: '{timestamp}'. 错误: {e}")
|
78 |
+
return None
|
79 |
+
|
80 |
+
# 计算时间段的重叠部分(单位:秒)
|
81 |
+
def calculate_overlap(self, start1, end1, start2, end2):
|
82 |
+
overlap_start = max(start1, start2)
|
83 |
+
overlap_end = min(end1, end2)
|
84 |
+
overlap_duration = max(0, overlap_end - overlap_start)
|
85 |
+
return overlap_duration
|
86 |
+
|
87 |
+
# 获取目标时间段和说话人时间段的重叠比例
|
88 |
+
def get_best_match(self, target_time, diarization_output):
|
89 |
+
target_start_time = target_time['start_time']
|
90 |
+
target_end_time = target_time['end_time']
|
91 |
+
|
92 |
+
# 用于存储每个说话人时间段的重叠比例
|
93 |
+
speaker_segments = []
|
94 |
+
for segment, label in diarization_output.itertracks(yield_label=True):
|
95 |
+
try:
|
96 |
+
start_seconds = segment.start
|
97 |
+
end_seconds = segment.end
|
98 |
+
|
99 |
+
# 计算目标音频时间段和说话人时间段的重叠时间
|
100 |
+
overlap = self.calculate_overlap(target_start_time, target_end_time, start_seconds, end_seconds)
|
101 |
+
overlap_ratio = overlap / (end_seconds - start_seconds)
|
102 |
+
|
103 |
+
# 记录说话人标签和重叠比例
|
104 |
+
speaker_segments.append((label, overlap_ratio, start_seconds, end_seconds))
|
105 |
+
|
106 |
+
except Exception as e:
|
107 |
+
print(f"处理行时出错: '{segment}'. 错误: {e}")
|
108 |
+
|
109 |
+
# 按照重叠比例排序,返回重叠比例最大的一段
|
110 |
+
best_match = max(speaker_segments, key=lambda x: x[1], default=None)
|
111 |
+
return best_match
|
112 |
+
|
113 |
+
# 获取该说话人除了目标语音时间段外的所有时间段
|
114 |
+
def get_speaker_time_segments(self, diarization_output, target_time, speaker_label):
|
115 |
+
remaining_segments = []
|
116 |
+
|
117 |
+
# 遍历 diarization 输出,查找该说话人的所有时间段
|
118 |
+
for segment, label in diarization_output.itertracks(yield_label=True):
|
119 |
+
if label == speaker_label:
|
120 |
+
start_seconds = segment.start
|
121 |
+
end_seconds = segment.end
|
122 |
+
|
123 |
+
# 计算与目标音频的重叠部分
|
124 |
+
overlap_start = max(start_seconds, target_time['start_time'])
|
125 |
+
overlap_end = min(end_seconds, target_time['end_time'])
|
126 |
+
|
127 |
+
# 如果有重叠部分,排除重叠部分
|
128 |
+
if overlap_start < overlap_end:
|
129 |
+
if start_seconds < overlap_start:
|
130 |
+
remaining_segments.append((start_seconds, overlap_start))
|
131 |
+
if overlap_end < end_seconds:
|
132 |
+
remaining_segments.append((overlap_end, end_seconds))
|
133 |
+
else:
|
134 |
+
remaining_segments.append((start_seconds, end_seconds))
|
135 |
+
|
136 |
+
return remaining_segments
|
137 |
+
|
138 |
+
# 处理音频文件并返回输出
|
139 |
+
def process_audio(self, target_audio, mixed_audio):
|
140 |
+
# 进行音频拼接并返回目标音频的起始和结束时间(作为字典)
|
141 |
+
time_dict = self.combine_audio_with_time(target_audio, mixed_audio)
|
142 |
+
|
143 |
+
# 执行说话人分离
|
144 |
+
diarization_result = self.diarize_audio("final_output.wav")
|
145 |
+
|
146 |
+
if isinstance(diarization_result, str) and diarization_result.startswith("错误"):
|
147 |
+
return diarization_result, None # 出错时返回错误信息
|
148 |
+
else:
|
149 |
+
# 获取最佳匹配的说话人标签和时间段
|
150 |
+
best_match = self.get_best_match(time_dict, diarization_result)
|
151 |
+
|
152 |
+
if best_match:
|
153 |
+
speaker_label = best_match[0] # 取出最佳匹配说话人的标签
|
154 |
+
# 获取该说话人除了目标语音时间段外的所有时间段
|
155 |
+
remaining_segments = self.get_speaker_time_segments(diarization_result, time_dict, speaker_label)
|
156 |
+
return speaker_label, remaining_segments
|
157 |
|
158 |
# Gradio 接口
|
159 |
with gr.Blocks() as demo:
|
160 |
gr.Markdown("""
|
161 |
# 🗣️ 音频拼接与说话人分类 🗣️
|
162 |
+
上传目标音频和混合音频,拼接并进行说话人分类。结果包括最佳匹配说话人的时间段(排除目标音频时间段)。
|
163 |
""")
|
164 |
+
|
165 |
mixed_audio_input = gr.Audio(type="filepath", label="上传混合音频")
|
166 |
target_audio_input = gr.Audio(type="filepath", label="上传目标说话人音频")
|
167 |
+
|
168 |
process_button = gr.Button("处理音频")
|
169 |
+
|
170 |
# 输出结果
|
171 |
diarization_output = gr.Textbox(label="最佳匹配说话人")
|
172 |
time_range_output = gr.Textbox(label="最佳匹配时间段")
|
173 |
|
174 |
# 点击按钮时触发处理音频
|
175 |
process_button.click(
|
176 |
+
fn=AudioProcessor().process_audio,
|
177 |
inputs=[target_audio_input, mixed_audio_input],
|
178 |
outputs=[diarization_output, time_range_output]
|
179 |
)
|