首页 > 解决方案 > 谷歌云功能的临时文件夹不起作用

问题描述

大家好,我正在尝试从电报下载音频文件并解析到谷歌云函数临时文件夹中进行处理。我正在尝试从音频文件中进行一些转录。

但是,它不断在行中抛出一个错误,ft.transcode(voice.download('/tmp/file.ogg'), 'wav')指出该文件不存在。GCF 有 tmp 文件夹吗?

我的代码如下

import os
import telegram
import speech_recognition as sr
import ftransc.core as ft
from googletrans import Translator
from google.cloud import speech_v1


bot = telegram.Bot(token=os.environ["TELEGRAM_TOKEN"])
translator = Translator()

def webhook(request):
    if request.method == "POST":
        update = telegram.Update.de_json(request.get_json(force=True), bot)
        chat_id = update.message.chat.id
        # Reply with the same message
        # getting the audio  file 
        audio_data = update.message.voice
        chat_data = update.message.text

        if audio_data  :

            voice = bot.getFile(audio_data.file_id)    
            print ("hello")
            print(voice)
            voice.download('/tmp/file.ogg')
            os.listdir('/tmp')
            ft.transcode(voice.download('/tmp/file.ogg'), 'wav')
            r = sr.Recognizer()
            with sr.WavFile('/tmp/file.wav') as source:
                audio = r.record(source)
                txt = r.recognize_google(audio)
                print(txt) 

        else :
            print(chat_data)
            try:

                translated = translator.translate(chat_data, dest='bn')
                transldated_data = translated.text
            except :
                transldated_data = "please try again"
            print(transldated_data)
            bot.sendMessage(chat_id=chat_id, text=transldated_data)
    return "ok"

标签: pythongoogle-cloud-functions

解决方案


确实有一个 tmp 文件夹,'/tmp'[1]。

使用 /tmp 存储文件时要小心,尤其是当您尝试将它用作您需要经常访问的文件的相对永久存储时。正如另一位 Googler[2] 所提到的,每个函数都在其自己的容器中执行,并具有自己的 /tmp 目录。甚至对同一函数的多次调用也可以在不同的容器中执行,因此具有不同的 /tmp 挂载。

如果需要更永久的存储,建议使用 Cloud Storage[3] 来存储音频文件以供以后使用。然后,您可以在需要时相应地下载音频文件。

这也可以通过为您的函数实现 Cloud Storage 触发器来实现 [4]。

[1] https://cloud.google.com/functions/docs/concepts/exec#file_system

[2]从 Google Cloud Function 写入临时文件

[3] https://cloud.google.com/storage

[4] https://cloud.google.com/functions/docs/tutorials/storage


推荐阅读