-
|
`` `` |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
输入的语音必须是单通道的吗 |
Beta Was this translation helpful? Give feedback.
-
|
可以。现在建议从旧的 ModelScope 下面是对 from functools import lru_cache
import numpy as np
import soundfile as sf
from scipy.signal import resample_poly
from funasr import AutoModel
TARGET_SR = 16000
BATCH_SIZE = 8 # 按显存和切片长度调整
def read_wav_scp(path):
recordings = {}
with open(path, encoding="utf-8") as f:
for line in f:
recording_id, audio_path = line.rstrip().split(maxsplit=1)
recordings[recording_id] = audio_path
return recordings
@lru_cache(maxsize=8)
def load_mono(audio_path):
# soundfile 的二维布局是 [samples, channels]
audio, sample_rate = sf.read(
audio_path, dtype="float32", always_2d=True
)
return audio.mean(axis=1, dtype=np.float32), sample_rate
def recognize_batch(model, batch, output):
segment_ids = [item[0] for item in batch]
waveforms = [item[1] for item in batch]
results = model.generate(
input=waveforms,
batch_size=len(waveforms),
fs=TARGET_SR,
)
if len(results) != len(batch):
raise RuntimeError(f"Expected {len(batch)} results, got {len(results)}")
for segment_id, result in zip(segment_ids, results):
output.write(f"{segment_id} {result['text']}\n")
recordings = read_wav_scp("wav.scp")
model = AutoModel(
model="paraformer-zh",
hub="hf", # 使用 ModelScope 时可删除本行
model_revision="main", # 使用 ModelScope 时可删除本行
device="cuda:0",
disable_update=True,
disable_pbar=True,
)
batch = []
with open("segments", encoding="utf-8") as segments, open(
"output.txt", "w", encoding="utf-8"
) as output:
for line_number, line in enumerate(segments, start=1):
segment_id, recording_id, begin_text, end_text = line.split()
audio, source_sr = load_mono(recordings[recording_id])
# segment 时间属于原始采样率,所以先切片,再重采样。
begin = max(0, round(float(begin_text) * source_sr))
end = min(len(audio), round(float(end_text) * source_sr))
if end <= begin:
raise ValueError(f"Invalid segment at line {line_number}: {line.rstrip()}")
clip = audio[begin:end]
if source_sr != TARGET_SR:
clip = resample_poly(clip, TARGET_SR, source_sr)
clip = np.ascontiguousarray(clip, dtype=np.float32)
batch.append((segment_id, clip))
if len(batch) == BATCH_SIZE:
recognize_batch(model, batch, output)
batch.clear()
if batch:
recognize_batch(model, batch, output)单双通道结论
我在当前主分支 如果 |
Beta Was this translation helpful? Give feedback.
可以。现在建议从旧的 ModelScope
pipeline迁移到 FunASRAutoModel:generate(input=...)可以直接接收list[np.ndarray],batch_size控制一次模型推理包含多少条切片。当前实现会按输入顺序返回结果,因此可以再与 segment ID 对齐。接口说明 批处理实现下面是对
wav.scp + segments的完整写法。它还避免了原代码在每个 segment 上重复读取同一录音: