使用SWIG生成的coqui_stt_ctcdecoder中Scorer.fill_dictionary参数类型匹配失败求助
问题场景
更新基于coqui_stt_ctcdecoder(SWIG生成的Python绑定包)的旧项目时,Scorer::fill_dictionary方法参数类型变更:C++层要求接收const std::unordered_set<std::string>&类型参数。原代码传入bytes列表已失效,尝试传入str/bytes的列表、原生Python set均触发如下类型错误:
Traceback (most recent call last):
File "/mnt/d/shared/speech/dsalign/STT-align/align/align.py", line 693, in
main()
File "/mnt/d/shared/speech/dsalign/STT-align/align/align.py", line 451, in main
create_bundle(alphabet_path, scorer_path + '.' + 'lm.binary', scorer_path + '.' + 'vocab-500000.txt', scorer_path, False, 0.931289039105002, 1.1834137581510284)
File "/mnt/d/shared/speech/dsalign/STT-align/align/generate_package.py", line 75, in create_bundle
scorer.fill_dictionary(words)
File "/mnt/d/shared/speech/dsalign/STT-align/venv/lib/python3.10/site-packages/coqui_stt_ctcdecoder/swigwrapper.py", line 1269, in fill_dictionary
return _swigwrapper.Scorer_fill_dictionary(self, vocabulary)
TypeError: in method 'Scorer_fill_dictionary', argument 2 of type 'std::unordered_set< std::string > const &'
Windows和WSL的Python 3.8环境下问题一致。
解决方案
步骤1:确认SWIG生成的C++容器绑定类型
打开coqui_stt_ctcdecoder包下的swigwrapper.py文件,查找对应std::unordered_set<std::string>的绑定类,通常命名为unordered_set_string或unordered_set_std_string。
步骤2:显式构造符合要求的C++容器对象
将Python字符串集合转换为SWIG绑定的C++容器类型,再传入方法:
from coqui_stt_ctcdecoder.swigwrapper import unordered_set_string # 假设words是存储字符串的Python列表/集合 cpp_vocab_set = unordered_set_string() for word in words: # 确保word是str类型,不是bytes if isinstance(word, bytes): word = word.decode('utf-8') cpp_vocab_set.insert(word) # 调用fill_dictionary scorer.fill_dictionary(cpp_vocab_set)
关键说明
SWIG不会自动将Python原生的list/set隐式转换为C的std::unordered_set(尤其是const引用参数),必须使用其生成的对应容器类来传递参数,才能让底层C代码正确识别类型。旧版本可能存在自动转换逻辑,新版本移除后需要显式处理。
内容的提问来源于stack exchange,提问作者comodoro

