Update app.py
Browse files
app.py
CHANGED
@@ -3,180 +3,162 @@ import spaces
|
|
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 |
-
|
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 |
try:
|
41 |
-
|
42 |
-
|
43 |
-
|
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 |
-
|
53 |
-
final_audio.export("final_output.wav", format="wav")
|
54 |
|
55 |
-
|
56 |
-
|
|
|
57 |
|
58 |
-
|
59 |
-
|
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 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
return
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
speaker_segments = []
|
95 |
-
for segment, label in diarization_output.itertracks(yield_label=True):
|
96 |
-
try:
|
97 |
-
start_seconds = segment.start
|
98 |
-
end_seconds = segment.end
|
99 |
-
|
100 |
-
# 计算目标音频时间段和说话人时间段的重叠时间
|
101 |
-
overlap = self.calculate_overlap(target_start_time, target_end_time, start_seconds, end_seconds)
|
102 |
-
overlap_ratio = overlap / (end_seconds - start_seconds)
|
103 |
-
|
104 |
-
# 记录说话人标签和重叠比例
|
105 |
-
speaker_segments.append((label, overlap_ratio, start_seconds, end_seconds))
|
106 |
-
|
107 |
-
except Exception as e:
|
108 |
-
print(f"处理行时出错: '{segment}'. 错误: {e}")
|
109 |
-
|
110 |
-
# 按照重叠比例排序,返回重叠比例最大的一段
|
111 |
-
best_match = max(speaker_segments, key=lambda x: x[1], default=None)
|
112 |
-
return best_match
|
113 |
-
|
114 |
-
# 获取该说话人除了目标语音时间段外的所有时间段
|
115 |
-
def get_speaker_time_segments(self, diarization_output, target_time, speaker_label):
|
116 |
-
remaining_segments = []
|
117 |
-
|
118 |
-
# 遍历 diarization 输出,查找该说话人的所有时间段
|
119 |
-
for segment, label in diarization_output.itertracks(yield_label=True):
|
120 |
-
if label == speaker_label:
|
121 |
-
start_seconds = segment.start
|
122 |
-
end_seconds = segment.end
|
123 |
-
|
124 |
-
# 计算与目标音频的重叠部分
|
125 |
-
overlap_start = max(start_seconds, target_time['start_time'])
|
126 |
-
overlap_end = min(end_seconds, target_time['end_time'])
|
127 |
-
|
128 |
-
# 如果有重叠部分,排除重叠部分
|
129 |
-
if overlap_start < overlap_end:
|
130 |
-
if start_seconds < overlap_start:
|
131 |
-
remaining_segments.append((start_seconds, overlap_start))
|
132 |
-
if overlap_end < end_seconds:
|
133 |
-
remaining_segments.append((overlap_end, end_seconds))
|
134 |
-
else:
|
135 |
-
remaining_segments.append((start_seconds, end_seconds))
|
136 |
-
|
137 |
-
return remaining_segments
|
138 |
-
|
139 |
-
# 处理音频文件并返回输出
|
140 |
-
def process_audio(self, target_audio, mixed_audio):
|
141 |
-
# 进行音频拼接并返回目标音频的起始和结束时间(作为字典)
|
142 |
-
time_dict = self.combine_audio_with_time(target_audio, mixed_audio)
|
143 |
-
|
144 |
-
# 执行���话人分离
|
145 |
-
diarization_result = self.diarize_audio("final_output.wav")
|
146 |
-
|
147 |
-
if isinstance(diarization_result, str) and diarization_result.startswith("错误"):
|
148 |
-
return diarization_result, None # 出错时返回错误信息
|
149 |
-
else:
|
150 |
-
# 获取最佳匹配的说话人标签和时间段
|
151 |
-
best_match = self.get_best_match(time_dict, diarization_result)
|
152 |
-
|
153 |
-
if best_match:
|
154 |
-
speaker_label = best_match[0] # 取出最佳匹配说话人的标签
|
155 |
-
# 获取该说话人除了目标语音时间段外的所有时间段
|
156 |
-
remaining_segments = self.get_speaker_time_segments(diarization_result, time_dict, speaker_label)
|
157 |
-
return speaker_label, remaining_segments
|
158 |
|
159 |
# Gradio 接口
|
160 |
with gr.Blocks() as demo:
|
161 |
gr.Markdown("""
|
162 |
# 🗣️ 音频拼接与说话人分类 🗣️
|
163 |
-
|
164 |
""")
|
165 |
-
|
166 |
mixed_audio_input = gr.Audio(type="filepath", label="上传混合音频")
|
167 |
target_audio_input = gr.Audio(type="filepath", label="上传目标说话人音频")
|
168 |
-
|
169 |
process_button = gr.Button("处理音频")
|
170 |
-
|
171 |
# 输出结果
|
172 |
diarization_output = gr.Textbox(label="最佳匹配说话人")
|
173 |
time_range_output = gr.Textbox(label="最佳匹配时间段")
|
174 |
|
175 |
# 点击按钮时触发处理音频
|
176 |
process_button.click(
|
177 |
-
fn=
|
178 |
inputs=[target_audio_input, mixed_audio_input],
|
179 |
outputs=[diarization_output, time_range_output]
|
180 |
)
|
181 |
|
182 |
-
demo.launch(share=True)
|
|
|
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 |
+
# 尝试加载 pyannote 模型
|
13 |
+
try:
|
14 |
+
pipeline = Pipeline.from_pretrained(
|
15 |
+
"pyannote/speaker-diarization-3.1", use_auth_token=HF_TOKEN
|
16 |
+
)
|
17 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
18 |
+
pipeline.to(device)
|
19 |
+
except Exception as e:
|
20 |
+
print(f"Error initializing pipeline: {e}")
|
21 |
+
pipeline = None
|
22 |
+
|
23 |
+
# 音频拼接函数:拼接目标音频和混合音频,返回目标音频的起始时间和结束时间作为字典
|
24 |
+
def combine_audio_with_time(target_audio, mixed_audio):
|
25 |
+
if pipeline is None:
|
26 |
+
return "错误: 模型未初始化"
|
27 |
+
|
28 |
+
# 打印文件路径,确保文件正确传递
|
29 |
+
print(f"目标音频文件路径: {target_audio}")
|
30 |
+
print(f"混合音频文件路径: {mixed_audio}")
|
31 |
+
|
32 |
+
# 加载目标说话人的样本音频
|
33 |
+
try:
|
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 |
+
print(diarization)
|
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 |
+
parts = line.strip()[1:-1].split(' --> ')
|
98 |
+
start_time = parts[0].strip()
|
99 |
+
end_time = parts[1].split(']')[0].strip()
|
100 |
+
label = line.split()[-1].strip()
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
+
start_seconds = timestamp_to_seconds(start_time)
|
103 |
+
end_seconds = timestamp_to_seconds(end_time)
|
|
|
104 |
|
105 |
+
# 计算目标音频时间段和说话人时间段的重叠时间
|
106 |
+
overlap = calculate_overlap(target_start_time, target_end_time, start_seconds, end_seconds)
|
107 |
+
overlap_ratio = overlap / (end_seconds - start_seconds)
|
108 |
|
109 |
+
# 记录说话人标签和重叠比例
|
110 |
+
speaker_segments.append((label, overlap_ratio, start_seconds, end_seconds))
|
|
|
|
|
|
|
111 |
|
|
|
|
|
112 |
except Exception as e:
|
113 |
+
print(f"处理行时出错: '{line.strip()}'. 错误: {e}")
|
114 |
+
|
115 |
+
# 按照重叠比例排序,返回重叠比例最大的一段
|
116 |
+
best_match = max(speaker_segments, key=lambda x: x[1], default=None)
|
117 |
+
|
118 |
+
return best_match
|
119 |
+
|
120 |
+
# 处理音频文件并返回输出
|
121 |
+
def process_audio(target_audio, mixed_audio):
|
122 |
+
# 打印文件路径,确保传入的文件有效
|
123 |
+
print(f"处理音频:目标音频: {target_audio}, 混合音频: {mixed_audio}")
|
124 |
+
|
125 |
+
# 进行音频拼接并返回目标音频的起始和结束时间(作为字典)
|
126 |
+
time_dict = combine_audio_with_time(target_audio, mixed_audio)
|
127 |
+
|
128 |
+
# 执行说话人分离
|
129 |
+
diarization_result = diarize_audio("final_output.wav")
|
130 |
+
|
131 |
+
if diarization_result.startswith("错误"):
|
132 |
+
return diarization_result, None # 出错时返回错误信息
|
133 |
+
else:
|
134 |
+
# 获取最佳匹配的说话人标签和时间段
|
135 |
+
best_match = get_best_match(time_dict, diarization_result)
|
136 |
+
|
137 |
+
if best_match:
|
138 |
+
# 返回最佳匹配说话人的标签和时间段
|
139 |
+
return best_match[0], best_match[2], best_match[3]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
)
|
163 |
|
164 |
+
demo.launch(share=True)
|