繁体   English   中英

Python使用Speech_recognition或PocketSphinx库避免文件IO

[英]Python avoid file IO with speech_recognition or PocketSphinx libraries

在处理具有需要文件路径作为参数的方法的Python库时,我经常遇到问题。 当我的内存中有一些要与库函数一起使用的数据时,这是一个问题。 在这些情况下,我最终要做的是:

  1. 写入包含数据的临时文件。
  2. 将临时文件路径传递给库函数。
  3. 函数返回后删除文件。

这足够好用,但是,对于时间敏感的应用程序,与写入和读取临时文件有关的文件IO会破坏交易。

有没有人对这个问题有解决方案? 我认为这里没有一个适合所有解决方案的规模,但我不想做任何假设。 但是,让我描述一下我当前的用例,并希望有人能够为我提供具体的帮助。

我正在使用speech_recognition库将大量音频文件转换为文本。 我有二进制格式的音频文件数据。 这是我的代码:

from os import path, remove

from scipy.io.wavfile import write

import speech_recognition as sr

audio_list = ... # get the audio

text_list = []

for item in audio_list:

        temp_name = 'temp.wav'
        # create temporary file, writing it as a wave for speech_recognition to read
        write(temp_name, rate, item)

        audio_file = path.join(path.dirname(path.realpath('__file__')), temp_name) 

        recognizer = sr.Recognizer()

        # this is where I need to have the path to the file
        with sr.AudioFile(audio_file) as source:
            audio = recognizer.record(source)

        text = recognizer.recognize_sphinx(audio)
        text_list.append(text)

        remove(temp_name) 

speech_recognition库使用PocketSphinx作为后端。 PocketSphinx有其自己的Python API,但我也无法获得任何运气。

谁能帮我减少这个文件的IO?

sr.AudioFile构造函数还接受一个“文件状对象”,并且SciPy应该能够写入一个文件。 在您的情况下,听起来像io.BytesIO会很合适。 它是围绕内存缓冲区构建的类似文件的对象。

制作一个,然后像使用任何其他类似文件的对象一样使用它:

import io

...

buffer = io.BytesIO()

...

write(buffer, rate, item)

...

with sr.AudioFile(buffer) as source:
    audio = recognizer.record(source)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM