david
commited on
Commit
·
27321a0
1
Parent(s):
0c38083
update strategy
Browse files- main.py +1 -1
- transcribe/strategy.py +76 -51
- transcribe/whisper_llm_serve.py +67 -37
main.py
CHANGED
|
@@ -65,7 +65,7 @@ async def translate(websocket: WebSocket):
|
|
| 65 |
)
|
| 66 |
|
| 67 |
if from_lang and to_lang:
|
| 68 |
-
client.
|
| 69 |
logger.info(f"Source lange: {from_lang} -> Dst lange: {to_lang}")
|
| 70 |
await websocket.accept()
|
| 71 |
try:
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
if from_lang and to_lang:
|
| 68 |
+
client.set_language(from_lang, to_lang)
|
| 69 |
logger.info(f"Source lange: {from_lang} -> Dst lange: {to_lang}")
|
| 70 |
await websocket.accept()
|
| 71 |
try:
|
transcribe/strategy.py
CHANGED
|
@@ -18,6 +18,9 @@ class TranscriptSegment:
|
|
| 18 |
t0: float # 开始时间(百分之一秒)
|
| 19 |
t1: float # 结束时间(百分之一秒)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
class TextStabilityBuffer:
|
| 23 |
"""
|
|
@@ -77,12 +80,26 @@ class TranscriptionManager:
|
|
| 77 |
self._committed_segments: List[str] = [] # 确认的完整段落
|
| 78 |
self._committed_sentences: List[str] = [] # 确认的短句
|
| 79 |
self._temp_string: str = "" # 临时字符串缓冲
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
@property
|
| 82 |
def current_sentence(self) -> str:
|
| 83 |
"""当前已确认的短句组合"""
|
| 84 |
return "".join(self._committed_sentences)
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
@property
|
| 87 |
def latest_segment(self) -> str:
|
| 88 |
"""最新确认的完整段落"""
|
|
@@ -153,8 +170,8 @@ class TranscriptionSplitter:
|
|
| 153 |
@staticmethod
|
| 154 |
def split_by_punctuation(
|
| 155 |
segments: List[TranscriptSegment],
|
| 156 |
-
|
| 157 |
-
|
| 158 |
) -> Tuple[int, List[TranscriptSegment], List[TranscriptSegment], bool]:
|
| 159 |
"""
|
| 160 |
根据标点符号将片段分为左侧(已确认)和右侧(待确认)
|
|
@@ -167,24 +184,26 @@ class TranscriptionSplitter:
|
|
| 167 |
split_index = 0
|
| 168 |
is_sentence_end = False
|
| 169 |
|
| 170 |
-
# 短音频使用所有标点符号作为分割依据
|
| 171 |
-
buffer_duration = len(audio_buffer) / sample_rate
|
| 172 |
-
markers = ALL_MARKERS if buffer_duration < 12 else SENTENCE_END_MARKERS
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
| 175 |
left_segments.append(seg)
|
| 176 |
if seg.text and seg.text[-1] in markers:
|
| 177 |
split_index = int(seg.t1 / 100 * sample_rate)
|
| 178 |
is_sentence_end = bool(SENTENCE_END_PATTERN.search(seg.text))
|
| 179 |
-
right_segments =
|
| 180 |
break
|
| 181 |
-
|
| 182 |
return split_index, left_segments, right_segments, is_sentence_end
|
| 183 |
|
| 184 |
@staticmethod
|
| 185 |
def split_by_sequences(
|
| 186 |
segments: List[TranscriptSegment],
|
| 187 |
-
audio_buffer: np.ndarray,
|
| 188 |
sample_rate: int = 16000
|
| 189 |
) -> Tuple[int, Iterator[TranscriptSegment], Iterator[TranscriptSegment], bool]:
|
| 190 |
"""
|
|
@@ -210,14 +229,32 @@ class TranscriptionSplitter:
|
|
| 210 |
return 0, iter([]), iter(segments), False
|
| 211 |
|
| 212 |
|
| 213 |
-
class TranscriptionStabilizer:
|
| 214 |
"""
|
| 215 |
转录结果稳定器,负责确认和管理转录片段
|
| 216 |
"""
|
| 217 |
def __init__(self, sample_rate: int = 16000):
|
| 218 |
-
self.
|
| 219 |
-
self.stability_buffer = TextStabilityBuffer(max_history=2)
|
| 220 |
self.sample_rate = sample_rate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
def process_segments(self, segments: List[TranscriptSegment]) -> Tuple[Optional[int], bool]:
|
| 223 |
"""
|
|
@@ -232,49 +269,37 @@ class TranscriptionStabilizer:
|
|
| 232 |
# 查找第一个包含标点的片段作为分割点
|
| 233 |
split_index = None
|
| 234 |
stable_segments = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
if REGEX_MARKERS.search(seg.text):
|
| 239 |
-
split_index = int(seg.t1 / 100 * self.sample_rate)
|
| 240 |
-
stable_idx = min(idx + 1, len(segments))
|
| 241 |
-
break
|
| 242 |
|
| 243 |
-
if split_index: # 找到标点,确认标点前的内容
|
| 244 |
-
stable_text =
|
| 245 |
-
self.
|
| 246 |
|
| 247 |
# 更新剩余文本
|
| 248 |
-
remaining_text =
|
| 249 |
-
self.
|
| 250 |
else:
|
| 251 |
-
#
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
# 检查是否达到换行标准
|
| 255 |
-
should_linebreak = self.
|
| 256 |
-
|
| 257 |
-
return split_index, should_linebreak
|
| 258 |
-
|
| 259 |
-
def check_stability(self, text: str, index: int) -> Optional[int]:
|
| 260 |
-
"""
|
| 261 |
-
检查文本是否稳定
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
index: 当前索引
|
| 266 |
-
|
| 267 |
-
Returns:
|
| 268 |
-
如果文本稳定,返回稳定的索引;否则返回None
|
| 269 |
-
"""
|
| 270 |
-
self.stability_buffer.add_entry(text, index)
|
| 271 |
-
return self.stability_buffer.get_stable_index()
|
| 272 |
-
|
| 273 |
-
def commit_segment(self, is_end_of_sentence: bool) -> None:
|
| 274 |
-
"""提交转录片段"""
|
| 275 |
-
self.manager.commit_segment(is_end_of_sentence)
|
| 276 |
-
|
| 277 |
-
@staticmethod
|
| 278 |
-
def _join_segment_text(segments: List[TranscriptSegment], separator: str = "") -> str:
|
| 279 |
-
"""连接多个片段的文本"""
|
| 280 |
-
return separator.join(seg.text for seg in segments)
|
|
|
|
| 18 |
t0: float # 开始时间(百分之一秒)
|
| 19 |
t1: float # 结束时间(百分之一秒)
|
| 20 |
|
| 21 |
+
def join_segment_text(segments: List[TranscriptSegment], separator: str = "") -> str:
|
| 22 |
+
"""连接多个片段的文本"""
|
| 23 |
+
return separator.join(seg.text for seg in segments)
|
| 24 |
|
| 25 |
class TextStabilityBuffer:
|
| 26 |
"""
|
|
|
|
| 80 |
self._committed_segments: List[str] = [] # 确认的完整段落
|
| 81 |
self._committed_sentences: List[str] = [] # 确认的短句
|
| 82 |
self._temp_string: str = "" # 临时字符串缓冲
|
| 83 |
+
|
| 84 |
+
def check_line_break(self, min_length: int = 20) -> bool:
|
| 85 |
+
"""检查当前短句长度是否达到换行标准"""
|
| 86 |
+
return self.sentence_length >= min_length
|
| 87 |
+
|
| 88 |
+
def force_line_break(self) -> None:
|
| 89 |
+
"""强制换行,保留当前内容但创建新段落"""
|
| 90 |
+
if self.current_sentence:
|
| 91 |
+
self._committed_segments.append(self.current_sentence)
|
| 92 |
+
self._committed_sentences = []
|
| 93 |
|
| 94 |
@property
|
| 95 |
def current_sentence(self) -> str:
|
| 96 |
"""当前已确认的短句组合"""
|
| 97 |
return "".join(self._committed_sentences)
|
| 98 |
|
| 99 |
+
@property
|
| 100 |
+
def remaining_text(self) -> str:
|
| 101 |
+
return self._temp_string
|
| 102 |
+
|
| 103 |
@property
|
| 104 |
def latest_segment(self) -> str:
|
| 105 |
"""最新确认的完整段落"""
|
|
|
|
| 170 |
@staticmethod
|
| 171 |
def split_by_punctuation(
|
| 172 |
segments: List[TranscriptSegment],
|
| 173 |
+
sample_rate: int = 16000,
|
| 174 |
+
segment_skip_index= 0
|
| 175 |
) -> Tuple[int, List[TranscriptSegment], List[TranscriptSegment], bool]:
|
| 176 |
"""
|
| 177 |
根据标点符号将片段分为左侧(已确认)和右侧(待确认)
|
|
|
|
| 184 |
split_index = 0
|
| 185 |
is_sentence_end = False
|
| 186 |
|
| 187 |
+
# # 短音频使用所有标点符号作为分割依据
|
| 188 |
+
# buffer_duration = len(audio_buffer) / sample_rate
|
| 189 |
+
# markers = ALL_MARKERS if buffer_duration < 12 else SENTENCE_END_MARKERS
|
| 190 |
+
skip_segments = segments[:segment_skip_index+1]
|
| 191 |
+
skipped_segments = segments[segment_skip_index:]
|
| 192 |
+
|
| 193 |
+
markers = ALL_MARKERS
|
| 194 |
+
for idx, seg in enumerate(skipped_segments):
|
| 195 |
left_segments.append(seg)
|
| 196 |
if seg.text and seg.text[-1] in markers:
|
| 197 |
split_index = int(seg.t1 / 100 * sample_rate)
|
| 198 |
is_sentence_end = bool(SENTENCE_END_PATTERN.search(seg.text))
|
| 199 |
+
right_segments = skipped_segments[min(idx+1, len(skipped_segments)):]
|
| 200 |
break
|
| 201 |
+
left_segments = skip_segments+ left_segments
|
| 202 |
return split_index, left_segments, right_segments, is_sentence_end
|
| 203 |
|
| 204 |
@staticmethod
|
| 205 |
def split_by_sequences(
|
| 206 |
segments: List[TranscriptSegment],
|
|
|
|
| 207 |
sample_rate: int = 16000
|
| 208 |
) -> Tuple[int, Iterator[TranscriptSegment], Iterator[TranscriptSegment], bool]:
|
| 209 |
"""
|
|
|
|
| 229 |
return 0, iter([]), iter(segments), False
|
| 230 |
|
| 231 |
|
| 232 |
+
class TranscriptionStabilizer(TranscriptionSplitter):
|
| 233 |
"""
|
| 234 |
转录结果稳定器,负责确认和管理转录片段
|
| 235 |
"""
|
| 236 |
def __init__(self, sample_rate: int = 16000):
|
| 237 |
+
self.text_manager = TranscriptionManager()
|
|
|
|
| 238 |
self.sample_rate = sample_rate
|
| 239 |
+
|
| 240 |
+
@property
|
| 241 |
+
def latest_segment(self):
|
| 242 |
+
return self.text_manager.latest_segment
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@property
|
| 246 |
+
def segment_count(self):
|
| 247 |
+
return self.text_manager.segment_count
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
def remaining_text(self):
|
| 252 |
+
return self.text_manager.remaining_text
|
| 253 |
+
|
| 254 |
+
@property
|
| 255 |
+
def stable_string(self):
|
| 256 |
+
return self.text_manager.current_sentence
|
| 257 |
+
|
| 258 |
|
| 259 |
def process_segments(self, segments: List[TranscriptSegment]) -> Tuple[Optional[int], bool]:
|
| 260 |
"""
|
|
|
|
| 269 |
# 查找第一个包含标点的片段作为分割点
|
| 270 |
split_index = None
|
| 271 |
stable_segments = []
|
| 272 |
+
force_split = False
|
| 273 |
+
if len(segments) < 20:
|
| 274 |
+
remaining_text = join_segment_text(segments)
|
| 275 |
+
self.text_manager.update_temp(remaining_text)
|
| 276 |
+
return split_index, False, join_segment_text(segments), self.text_manager.remaining_text
|
| 277 |
|
| 278 |
+
# 查找20个长度后的标点符号
|
| 279 |
+
split_index, left_segments, right_segments, is_sentence_end = self.split_by_punctuation(segments[20:],sample_rate=self.sample_rate)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
+
if split_index is not None: # 找到标点,确认标点前的内容
|
| 282 |
+
stable_text = join_segment_text(left_segments)
|
| 283 |
+
self.text_manager.update_temp(stable_text).commit_sentence()
|
| 284 |
|
| 285 |
# 更新剩余文本
|
| 286 |
+
remaining_text = join_segment_text(right_segments)
|
| 287 |
+
self.text_manager.update_temp(remaining_text)
|
| 288 |
else:
|
| 289 |
+
# 如果没有标点 但是累计超过22个字符 直接从20个字符的位置切掉
|
| 290 |
+
if len(segments) > 22 and not REGEX_MARKERS.search(join_segment_text(segments)):
|
| 291 |
+
split_index = int(segments[20].t1 / 100 * self.sample_rate)
|
| 292 |
+
stable_idx = 21 # 直接使用22个字符的索引
|
| 293 |
+
force_split = True
|
| 294 |
+
stable_text = join_segment_text(segments[:stable_idx])
|
| 295 |
+
self.text_manager.update_temp(stable_text).commit_sentence()
|
| 296 |
+
self.text_manager.update_temp(join_segment_text(segments[stable_idx:]))
|
| 297 |
+
else:
|
| 298 |
+
# 没有找到标点,全部作为临时文本
|
| 299 |
+
self.text_manager.update_temp(join_segment_text(segments))
|
| 300 |
|
| 301 |
# 检查是否达到换行标准
|
| 302 |
+
should_linebreak = self.text_manager.sentence_length >= 20 or force_split
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
return split_index, should_linebreak, join_segment_text(stable_segments), self.text_manager.remaining_text
|
| 305 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
transcribe/whisper_llm_serve.py
CHANGED
|
@@ -12,7 +12,13 @@ from api_model import TransResult, Message
|
|
| 12 |
from .server import ServeClientBase
|
| 13 |
from .utils import log_block, save_to_wave
|
| 14 |
from .translatepipes import TranslatePipes
|
| 15 |
-
from .strategy import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
logger = getLogger("TranscriptionService")
|
| 18 |
|
|
@@ -50,6 +56,8 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 50 |
self.translate_thread = self._start_thread(self._transcription_processing_loop)
|
| 51 |
self.frame_processing_thread = self._start_thread(self._frame_processing_loop)
|
| 52 |
|
|
|
|
|
|
|
| 53 |
def _start_thread(self, target_function) -> threading.Thread:
|
| 54 |
"""启动守护线程执行指定函数"""
|
| 55 |
thread = threading.Thread(target=target_function)
|
|
@@ -154,11 +162,26 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 154 |
result = self._translate_pipe.translate(text, self.source_language, self.target_language)
|
| 155 |
translated_text = result.translate_content
|
| 156 |
|
| 157 |
-
log_block("Translation time", f"{(time.perf_counter() - start_time):.3f}", "s")
|
| 158 |
log_block("Translation output", f"{translated_text}")
|
| 159 |
|
| 160 |
return translated_text
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
def _analyze_segments(self, segments: List[TranscriptSegment], audio_buffer: np.ndarray) -> Tuple[Optional[int], str, str, bool]:
|
| 163 |
"""
|
| 164 |
分析转录片段,确定稳定部分和需要继续观察的部分
|
|
@@ -171,24 +194,35 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 171 |
segments, audio_buffer, self.sample_rate
|
| 172 |
)
|
| 173 |
|
| 174 |
-
left_text = self.text_separator
|
| 175 |
-
right_text = self.text_separator
|
| 176 |
|
| 177 |
# 如果找到分割点,检查左侧文本稳定性
|
| 178 |
if left_idx != 0:
|
| 179 |
self._text_stability_buffer.add_entry(left_text, left_idx)
|
| 180 |
stable_idx = self._text_stability_buffer.get_stable_index()
|
| 181 |
if stable_idx:
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
# 如果基于标点的方法未找到稳定点,尝试基于句子序列的方法
|
| 185 |
left_idx, left_segments, right_segments, is_end = TranscriptionSplitter.split_by_sequences(
|
| 186 |
-
segments,
|
| 187 |
)
|
| 188 |
|
| 189 |
if left_idx != 0:
|
| 190 |
-
left_text = self.text_separator
|
| 191 |
-
right_text = self.text_separator
|
| 192 |
return left_idx, left_text, right_text, is_end
|
| 193 |
|
| 194 |
# 如果都没有找到分割点
|
|
@@ -196,6 +230,7 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 196 |
|
| 197 |
def _transcription_processing_loop(self) -> None:
|
| 198 |
"""主转录处理循环"""
|
|
|
|
| 199 |
while not self._translate_thread_stop.is_set():
|
| 200 |
if self.exit:
|
| 201 |
logger.info("Exiting transcription thread")
|
|
@@ -203,26 +238,28 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 203 |
|
| 204 |
# 等待音频数据
|
| 205 |
if self.frames_np is None:
|
| 206 |
-
time.sleep(0.
|
| 207 |
logger.info("Waiting for audio data...")
|
| 208 |
continue
|
| 209 |
|
| 210 |
# 获取音频块进行处理
|
| 211 |
audio_buffer = self._get_audio_for_processing()
|
| 212 |
if audio_buffer is None:
|
| 213 |
-
time.sleep(0.
|
| 214 |
continue
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
| 223 |
|
| 224 |
-
except Exception as e:
|
| 225 |
-
|
| 226 |
|
| 227 |
def _process_transcription_results(self, segments: List[TranscriptSegment], audio_buffer: np.ndarray) -> Iterator[TransResult]:
|
| 228 |
"""
|
|
@@ -236,12 +273,7 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 236 |
if not full_text:
|
| 237 |
return
|
| 238 |
|
| 239 |
-
|
| 240 |
-
self._transcription_manager.update_temp(full_text)
|
| 241 |
-
|
| 242 |
-
# 分析片段,确定稳定部分和需要继续观察的部分
|
| 243 |
-
cut_index, stable_text, remaining_text, is_sentence_end = self._analyze_segments(segments, audio_buffer)
|
| 244 |
-
|
| 245 |
# 如果找到稳定的分割点
|
| 246 |
if cut_index:
|
| 247 |
# 更新音频缓冲区,移除已处理部分
|
|
@@ -249,13 +281,11 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 249 |
|
| 250 |
# 提交稳定的文本
|
| 251 |
log_block("Stable transcription", f"{stable_text}")
|
| 252 |
-
|
| 253 |
-
self._transcription_manager.update_temp(remaining_text)
|
| 254 |
-
|
| 255 |
# 如果是句子结束,发送完整句子的翻译结果
|
| 256 |
if is_sentence_end:
|
| 257 |
-
segment_text = self.
|
| 258 |
-
segment_id = self.
|
| 259 |
|
| 260 |
# 生成已确认句子的翻译结果
|
| 261 |
yield TransResult(
|
|
@@ -268,19 +298,19 @@ class WhisperTranscriptionService(ServeClientBase):
|
|
| 268 |
)
|
| 269 |
|
| 270 |
# 如果还有剩余部分,生成临时翻译结果
|
| 271 |
-
if self.
|
| 272 |
yield TransResult(
|
| 273 |
seg_id=segment_id + 1,
|
| 274 |
-
context=self.
|
| 275 |
from_=self.source_language,
|
| 276 |
to=self.target_language,
|
| 277 |
-
tran_content=self._translate_text(self.
|
| 278 |
partial=True
|
| 279 |
)
|
| 280 |
else:
|
| 281 |
# 没有找到稳定点,发送当前所有内容的临时翻译结果
|
| 282 |
-
segment_id = self.
|
| 283 |
-
current_text = self.
|
| 284 |
|
| 285 |
yield TransResult(
|
| 286 |
seg_id=segment_id,
|
|
|
|
| 12 |
from .server import ServeClientBase
|
| 13 |
from .utils import log_block, save_to_wave
|
| 14 |
from .translatepipes import TranslatePipes
|
| 15 |
+
from .strategy import (
|
| 16 |
+
TextStabilityBuffer,
|
| 17 |
+
TranscriptionManager,
|
| 18 |
+
TranscriptionSplitter,
|
| 19 |
+
TranscriptSegment,
|
| 20 |
+
TranscriptionStabilizer,
|
| 21 |
+
join_segment_text)
|
| 22 |
|
| 23 |
logger = getLogger("TranscriptionService")
|
| 24 |
|
|
|
|
| 56 |
self.translate_thread = self._start_thread(self._transcription_processing_loop)
|
| 57 |
self.frame_processing_thread = self._start_thread(self._frame_processing_loop)
|
| 58 |
|
| 59 |
+
self.text_stablizer = TranscriptionStabilizer()
|
| 60 |
+
|
| 61 |
def _start_thread(self, target_function) -> threading.Thread:
|
| 62 |
"""启动守护线程执行指定函数"""
|
| 63 |
thread = threading.Thread(target=target_function)
|
|
|
|
| 162 |
result = self._translate_pipe.translate(text, self.source_language, self.target_language)
|
| 163 |
translated_text = result.translate_content
|
| 164 |
|
| 165 |
+
log_block("Translation time ", f"{(time.perf_counter() - start_time):.3f}", "s")
|
| 166 |
log_block("Translation output", f"{translated_text}")
|
| 167 |
|
| 168 |
return translated_text
|
| 169 |
|
| 170 |
+
def _find_best_split_position(self, segments: list, target_length: int = 20) -> int:
|
| 171 |
+
"""找到最适合分割的位置,尽量靠近目标长度且在词/字的边界"""
|
| 172 |
+
if len(segments) <= target_length:
|
| 173 |
+
return 0
|
| 174 |
+
|
| 175 |
+
# 从目标长度位置向前搜索适合的分割点
|
| 176 |
+
for i in range(target_length, min(target_length + 10, len(segments))):
|
| 177 |
+
# 对于中文,每个字符都可以作为分割点
|
| 178 |
+
# 对于英文,在空格处分割
|
| 179 |
+
if self.source_language == "zh" or segments[i] == " ":
|
| 180 |
+
return i
|
| 181 |
+
|
| 182 |
+
# 如果找不到理想分割点,就在目标长度处分割
|
| 183 |
+
return target_length
|
| 184 |
+
|
| 185 |
def _analyze_segments(self, segments: List[TranscriptSegment], audio_buffer: np.ndarray) -> Tuple[Optional[int], str, str, bool]:
|
| 186 |
"""
|
| 187 |
分析转录片段,确定稳定部分和需要继续观察的部分
|
|
|
|
| 194 |
segments, audio_buffer, self.sample_rate
|
| 195 |
)
|
| 196 |
|
| 197 |
+
left_text = join_segment_text(left_segments, self.text_separator)
|
| 198 |
+
right_text = join_segment_text(right_segments, self.text_separator)
|
| 199 |
|
| 200 |
# 如果找到分割点,检查左侧文本稳定性
|
| 201 |
if left_idx != 0:
|
| 202 |
self._text_stability_buffer.add_entry(left_text, left_idx)
|
| 203 |
stable_idx = self._text_stability_buffer.get_stable_index()
|
| 204 |
if stable_idx:
|
| 205 |
+
should_break = True if (self._transcription_manager.sentence_length>= 20) else False
|
| 206 |
+
return stable_idx, left_text, right_text, should_break
|
| 207 |
+
|
| 208 |
+
# 如果基于标点的方法没有找到稳定点,尝试检查句子的长度
|
| 209 |
+
if len(segments) >= 20: # 设置更长的阈值,确保有足够内容进行分割
|
| 210 |
+
# 尝试在约20字符处找一个词的边界进行分割
|
| 211 |
+
split_pos = self._find_best_split_position(segments)
|
| 212 |
+
if split_pos > 0:
|
| 213 |
+
left_text = join_segment_text(segments[:split_pos], self.text_separator)
|
| 214 |
+
right_text = join_segment_text(segments[split_pos:], self.text_separator)
|
| 215 |
+
audio_pos = int(segments[split_pos].t1 / 100 * self.sample_rate)
|
| 216 |
+
return audio_pos, left_text, right_text, True
|
| 217 |
+
|
| 218 |
# 如果基于标点的方法未找到稳定点,尝试基于句子序列的方法
|
| 219 |
left_idx, left_segments, right_segments, is_end = TranscriptionSplitter.split_by_sequences(
|
| 220 |
+
segments, self.sample_rate
|
| 221 |
)
|
| 222 |
|
| 223 |
if left_idx != 0:
|
| 224 |
+
left_text = join_segment_text(left_segments, self.text_separator)
|
| 225 |
+
right_text = join_segment_text(right_segments, self.text_separator)
|
| 226 |
return left_idx, left_text, right_text, is_end
|
| 227 |
|
| 228 |
# 如果都没有找到分割点
|
|
|
|
| 230 |
|
| 231 |
def _transcription_processing_loop(self) -> None:
|
| 232 |
"""主转录处理循环"""
|
| 233 |
+
c = 0
|
| 234 |
while not self._translate_thread_stop.is_set():
|
| 235 |
if self.exit:
|
| 236 |
logger.info("Exiting transcription thread")
|
|
|
|
| 238 |
|
| 239 |
# 等待音频数据
|
| 240 |
if self.frames_np is None:
|
| 241 |
+
time.sleep(0.2)
|
| 242 |
logger.info("Waiting for audio data...")
|
| 243 |
continue
|
| 244 |
|
| 245 |
# 获取音频块进行处理
|
| 246 |
audio_buffer = self._get_audio_for_processing()
|
| 247 |
if audio_buffer is None:
|
| 248 |
+
time.sleep(0.2)
|
| 249 |
continue
|
| 250 |
+
|
| 251 |
+
c+= 1
|
| 252 |
+
save_to_wave(f"dev-{c}.wav", audio_buffer)
|
| 253 |
+
|
| 254 |
+
# try:
|
| 255 |
+
segments = self._transcribe_audio(audio_buffer)
|
| 256 |
+
|
| 257 |
+
# 处理转录结果并发送到客户端
|
| 258 |
+
for result in self._process_transcription_results(segments, audio_buffer):
|
| 259 |
+
self._send_result_to_client(result)
|
| 260 |
|
| 261 |
+
# except Exception as e:
|
| 262 |
+
# logger.error(f"Error processing audio: {e}")
|
| 263 |
|
| 264 |
def _process_transcription_results(self, segments: List[TranscriptSegment], audio_buffer: np.ndarray) -> Iterator[TransResult]:
|
| 265 |
"""
|
|
|
|
| 273 |
if not full_text:
|
| 274 |
return
|
| 275 |
|
| 276 |
+
cut_index, is_sentence_end, stable_text, remaining_text = self.text_stablizer.process_segments(segments)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
# 如果找到稳定的分割点
|
| 278 |
if cut_index:
|
| 279 |
# 更新音频缓冲区,移除已处理部分
|
|
|
|
| 281 |
|
| 282 |
# 提交稳定的文本
|
| 283 |
log_block("Stable transcription", f"{stable_text}")
|
| 284 |
+
|
|
|
|
|
|
|
| 285 |
# 如果是句子结束,发送完整句子的翻译结果
|
| 286 |
if is_sentence_end:
|
| 287 |
+
segment_text = self.text_stablizer.latest_segment
|
| 288 |
+
segment_id = self.text_stablizer.segment_count - 1
|
| 289 |
|
| 290 |
# 生成已确认句子的翻译结果
|
| 291 |
yield TransResult(
|
|
|
|
| 298 |
)
|
| 299 |
|
| 300 |
# 如果还有剩余部分,生成临时翻译结果
|
| 301 |
+
if self.text_stablizer.remaining_text.strip():
|
| 302 |
yield TransResult(
|
| 303 |
seg_id=segment_id + 1,
|
| 304 |
+
context=self.text_stablizer.remaining_text,
|
| 305 |
from_=self.source_language,
|
| 306 |
to=self.target_language,
|
| 307 |
+
tran_content=self._translate_text(self.text_stablizer.remaining_text.strip()),
|
| 308 |
partial=True
|
| 309 |
)
|
| 310 |
else:
|
| 311 |
# 没有找到稳定点,发送当前所有内容的临时翻译结果
|
| 312 |
+
segment_id = self.text_stablizer.segment_count
|
| 313 |
+
current_text = self.text_stablizer.stable_string + self.text_stablizer.remaining_text
|
| 314 |
|
| 315 |
yield TransResult(
|
| 316 |
seg_id=segment_id,
|