test_inference.py
11.4 KB
1
2
3
4
5
6
7
8
9
10
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""FunASR 推理测试脚本。
下载指定音频文件并执行完整推理流水线(VAD 分段 → ASR 识别 → 标点恢复 → 说话人分离),
结果打印到控制台。支持 debug 模式,方便断点调试和问题排查。
用法::
python test_inference.py # 使用内置默认 URL
python test_inference.py --url <音频URL> # 指定远程音频 URL
python test_inference.py --audio <本地音频路径> # 使用本地音频文件
python test_inference.py --debug # 启用 DEBUG 日志(详细打印各阶段信息)
python test_inference.py --no-download --audio <path> # 不下载,直接推理本地文件
python test_inference.py --hotword "阿里 达摩院" # 指定热词
Debug 调试建议::
1. 在 VS Code / PyCharm 中打开本文件,在关键位置设断点(如 model.recognize() 调用处)
2. 以 Debug 模式运行: python test_inference.py --debug
3. 首次运行会自动下载模型(约 1GB),后续从本地缓存加载
"""
import argparse
import json
import logging
import os
import sys
import tempfile
import time
from typing import Optional
from urllib.parse import urlparse
from asr_service.transform import fine_grained_transform_output
# 默认测试音频 URL(可在命令行覆盖)
DEFAULT_AUDIO_URL = (
"https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/17810656451981781063984653_807072C1.mp3"
)
logger = logging.getLogger("test_inference")
def setup_test_logging(debug: bool = False) -> None:
"""初始化测试脚本日志(仅控制台输出,不写文件)。"""
level = logging.DEBUG if debug else logging.INFO
fmt = logging.Formatter(
"[%(asctime)s] [%(levelname)s] %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
root = logging.getLogger()
root.setLevel(level)
root.handlers.clear()
sh = logging.StreamHandler(sys.stdout)
sh.setFormatter(fmt)
root.addHandler(sh)
# 降低第三方库冗余日志
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("modelscope").setLevel(logging.WARNING)
def download_audio(url: str) -> str:
"""下载音频 URL 到本地临时文件。
Returns:
本地临时文件路径(调用方负责删除)。
"""
import requests
logger.info("开始下载音频: %s", url)
# 从 URL 推断扩展名
path = urlparse(url).path
ext = os.path.splitext(path)[1].lower() or ".wav"
valid_exts = {".wav", ".mp3", ".pcm", ".flac", ".ogg", ".m4a", ".aac"}
if ext not in valid_exts:
ext = ".wav"
fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="asr_test_")
try:
with os.fdopen(fd, "wb") as f:
with requests.get(url, stream=True, timeout=120) as resp:
resp.raise_for_status()
total = 0
for chunk in resp.iter_content(chunk_size=64 * 1024):
if chunk:
total += len(chunk)
f.write(chunk)
size_mb = total / 1024 / 1024
logger.info("音频下载完成: %.2f MB -> %s", size_mb, tmp_path)
return tmp_path
except Exception:
if os.path.exists(tmp_path):
try:
os.remove(tmp_path)
except OSError:
pass
raise
def load_model(debug: bool = False):
"""加载 FunASR 模型。
Returns:
ASRModel 实例。
"""
from asr_service.models import ASRModel
logger.info("开始加载模型(首次运行会从 ModelScope 下载约 1GB,请耐心等待)...")
t0 = time.time()
model = ASRModel()
elapsed = time.time() - t0
logger.info("模型加载完成: %s(耗时 %.1fs)", model.model_info, elapsed)
return model
# ---------------------------------------------------------------------------
# 结果格式化输出
# ---------------------------------------------------------------------------
def print_divider(title: str = "", char: str = "=", width: int = 72,
out=None) -> None:
"""打印分隔线。out 默认 sys.stdout。"""
if out is None:
out = sys.stdout
if title:
padding = max(0, (width - len(title) - 2) // 2)
print(f"\n{char * padding} {title} {char * padding}", file=out)
else:
print(char * width, file=out)
def print_result(result: dict, out) -> None:
"""格式化识别结果写入文件 out。
包含:识别全文、说话人数量、音频时长、处理耗时、落库 JSON 格式、
分句明细(role/offset/duration/content)、逐字时间戳采样、原始模型输出。
"""
full_text = result.get("full_text", "")
speaker_count = result.get("speaker_count", 0)
audio_ms = result.get("audio_duration_ms", 0)
process_ms = result.get("process_time_ms", 0)
sentences = result.get("sentence_info", [])
timestamps = result.get("timestamp", [])
# ---- 摘要 ----
print_divider("识别结果摘要", out=out)
print(f" 音频时长 : {audio_ms / 1000:.2f}s ({audio_ms}ms)", file=out)
print(f" 处理耗时 : {process_ms / 1000:.2f}s ({process_ms}ms)", file=out)
print(f" 实时率 (RTF) : {process_ms / max(audio_ms, 1):.3f}", file=out)
print(f" 说话人数量 : {speaker_count}", file=out)
print(f" 分句数量 : {len(sentences)}", file=out)
print(f" 逐字时间戳数 : {len(timestamps)}", file=out)
# ---- 识别全文 ----
print_divider("识别全文", out=out)
print(f" {full_text}" if full_text else " (无识别结果)", file=out)
# ---- 落库 JSON 格式(与主程序/旧服务 fine_grained_transform_output 一致) ----
if sentences:
formatted_json = fine_grained_transform_output(sentences)
print_divider("落库 JSON 格式(与主程序/旧服务一致)", out=out)
print(f" {formatted_json}", file=out)
# ---- 分句明细(role / offset / duration / content) ----
formatted_list = json.loads(formatted_json)
print_divider(f"分句明细(共 {len(formatted_list)} 句)", out=out)
for i, item in enumerate(formatted_list):
offset_s = item["offset"] / 1000.0
dur_s = item["duration"] / 1000.0
print(f" [{i:3d}] 说话人{item['role']} | {offset_s:7.2f}s 起 时长{dur_s:6.2f}s | {item['content']}", file=out)
# ---- 逐字时间戳(采样前 20 条,调试用) ----
if timestamps:
sample_n = min(20, len(timestamps))
print_divider(f"逐字时间戳采样(前 {sample_n}/{len(timestamps)} 条)", out=out)
for i, ts in enumerate(timestamps[:sample_n]):
if isinstance(ts, (list, tuple)) and len(ts) >= 2:
print(f" [{i:4d}] {ts[0]:7d}ms ~ {ts[1]:7d}ms", file=out)
# ---- 原始模型输出(调试用) ----
print_divider("原始模型输出(完整)", out=out)
print(json.dumps(result, ensure_ascii=False, indent=2, default=str), file=out)
print_divider(out=out)
# ---------------------------------------------------------------------------
# 主逻辑
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="FunASR 推理测试脚本 - 下载音频并执行识别,结果写入 testoutput_{时间戳}.log 文件",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
python test_inference.py # 使用默认 URL
python test_inference.py --debug # 启用 DEBUG 日志
python test_inference.py --url https://example.com/a.mp3 # 指定远程 URL
python test_inference.py --audio ./test_audio.wav # 使用本地文件
python test_inference.py --hotword "你好 世界" # 指定热词
python test_inference.py --debug --audio ./test.wav # debug + 本地文件
""",
)
parser.add_argument(
"--url",
type=str,
default=None,
help="远程音频 URL(不传则使用内置默认 URL)",
)
parser.add_argument(
"--audio",
type=str,
default=None,
help="本地音频文件路径(与 --url 二选一,优先使用 --audio)",
)
parser.add_argument(
"--hotword",
type=str,
default="",
help="热词,空格分隔,如 '阿里 达摩院'",
)
parser.add_argument(
"--debug",
action="store_true",
default=False,
help="启用 DEBUG 日志级别,输出详细调试信息",
)
parser.add_argument(
"--no-download",
action="store_true",
default=False,
help="跳过 URL 下载,需配合 --audio 使用",
)
args = parser.parse_args()
# 初始化日志
setup_test_logging(debug=args.debug)
print_divider("FunASR 推理测试")
logger.info("Python: %s", sys.version)
logger.info("工作目录: %s", os.getcwd())
# 确定音频来源
audio_path: Optional[str] = args.audio
download_path: Optional[str] = None
if audio_path:
# 用户指定了本地文件
if not os.path.exists(audio_path):
logger.error("本地音频文件不存在: %s", audio_path)
sys.exit(1)
logger.info("使用本地音频文件: %s", audio_path)
elif args.no_download:
logger.error("--no-download 需要配合 --audio 指定本地文件")
sys.exit(1)
else:
# 下载音频
url = args.url or DEFAULT_AUDIO_URL
logger.info("音频 URL: %s", url)
try:
download_path = download_audio(url)
audio_path = download_path
except Exception as e:
logger.exception("音频下载失败: %s", e)
sys.exit(1)
# ---------- 断点调试建议在此处设置 ----------
# 如果要在 VS Code / PyCharm 中 debug:
# 1. 在下面 model.recognize(audio_path) 调用处设断点
# 2. 在返回的 result 处设断点查看数据结构
# 3. 以 Debug 模式运行: python test_inference.py --debug
try:
# 加载模型
model = load_model(debug=args.debug)
# 执行推理
hotword = args.hotword
if hotword:
logger.info("启用热词: %s", hotword)
logger.info("开始推理,音频路径: %s", audio_path)
t_infer = time.time()
result = model.recognize(audio_path, hotword=hotword)
infer_elapsed = time.time() - t_infer
logger.info("推理完成,耗时 %.2fs", infer_elapsed)
# 识别结果写入文件(不输出到控制台)
timestamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
output_file = os.path.join(os.getcwd(), f"testoutput_{timestamp}.log")
with open(output_file, "w", encoding="utf-8") as f:
print_result(result, f)
logger.info("识别结果已写入文件: %s", output_file)
except Exception as e:
logger.exception("推理过程发生异常: %s", e)
sys.exit(1)
finally:
# 清理临时下载的音频文件
if download_path and os.path.exists(download_path):
try:
os.remove(download_path)
logger.debug("已清理临时文件: %s", download_path)
except OSError as e:
logger.warning("清理临时文件失败: %s", e)
logger.info("测试完成。")
sys.exit(0)
if __name__ == "__main__":
main()