jianchang512 / stt

Voice Recognition to Text Tool / 一个离线运行的本地语音识别转文字服务,输出json、srt字幕带时间戳、纯文字格式
https://pyvideotrans.com
GNU General Public License v3.0
1.81k stars 204 forks source link

使用同名文件调用api(内容变化),却总是输出第一次的内容 #58

Closed flying-forever closed 1 week ago

flying-forever commented 4 weeks ago

这个问题折磨了我许久。

我多次录音上传识别,然而结果一直显示'招子白地参运见。'(朝辞白帝彩云间)(终端片段如下),然而我听我保存的本地录音文件(我命名为recording.mp3,是变化了的。重启flask服务并没有效果。

{'code': 0, 'data': '招子白地参运见。', 'msg': 'ok'}
127.0.0.1 - - [27/Jun/2024 21:34:41] "POST /upload HTTP/1.1" 200 -
127.0.0.1 - - [27/Jun/2024 21:37:16] "GET /?speechInput= HTTP/1.1" 200 -

{'code': 0, 'data': '招子白地参运见。', 'msg': 'ok'}
127.0.0.1 - - [27/Jun/2024 21:37:26] "POST /upload HTTP/1.1" 200 -

后来我发现了...\stt\static\tmp目录下,保存有我的recording.wavrecording.mp3文件,听录音,确实还是我第一遍录的“朝辞白帝彩云间“。我尝试阅读代码段:

@app.route('/api',methods=['GET','POST'])
def api():
    ...

但一时没有找到问题所在。不过我发现只需要删除相应的.wav文件(不用管.mp3),将得到新的识别结果。我只好编写一个函数在每次识别前删除所有的.wav文件,临时处理了这个问题。

def init_delete_wav_files(func):
    '''装饰器,先删除TMP_DIR所有的.wav文件'''

    def delete_wav_files(*args, directory=cfg.TMP_DIR, **kargs):
        """
        Delete all .wav files in the specified directory.
        """
        try:
            print(f'[delete] .wav in {directory}...')
            for filename in os.listdir(directory):
                if filename.endswith(".wav"):
                    file_path = os.path.join(directory, filename)
                    os.remove(file_path)
                    print(f"Deleted: {file_path}")
            print("[complete]All .wav files have been deleted.")
        except Exception as e:
            print(f"An error occurred: {e}")

        return func(*args, **kargs)
    return delete_wav_files
@app.route('/api',methods=['GET','POST'])
@init_delete_wav_files
def api():
    ...

终于可以得到新的识别结果。

{'code': 0, 'data': '编议员里。', 'msg': 'ok'}
jianchang512 commented 4 weeks ago

会使用上次的缓存结果 可改名后再处理