将SpeechRecognitionResult返回为JSON或编码为JSON

时间:2019-07-19 21:22:31

标签: json google-cloud-speech

speech_v1.SpeechClient返回一个不可序列化的<class 'google.cloud.speech_v1.types.RecognizeResponse'>

我尝试对json.dumps RecognizeResponse对象进行转储,但它不可序列化。有没有一种方法可以将响应编码为JSON或向后请求JSON响应?

import json
from google.cloud import speech_v1
from google.cloud.speech_v1 import types
from google.cloud.speech_v1 import enums
from google.oauth2 import service_account

service_account_info = json.load(open('path/to/google_creds.json'))
credentials = service_account.Credentials.from_service_account_info(service_account_info)
client = speech_v1.SpeechClient(credentials=credentials)

audio = types.RecognitionAudio(content='gs://bucket_name/sample-audio.flac')
config = types.RecognitionConfig(
    encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
    audio_channel_count=2,
    enable_separate_recognition_per_channel=True,
    sample_rate_hertz=44100,
    language_code='en-US',
    model="phone_call",
    use_enhanced=True
)

response = client.recognize(config, audio)

print(type(response))
# <class 'google.cloud.speech_v1.types.RecognizeResponse'>

print(response)
"""
results {
  alternatives {
    transcript: "..."
    confidence: 0.742891252040863
  }
  channel_tag: 2
}
results {
  alternatives {
    transcript: "..."
    confidence: 0.8125505447387695
  }
  channel_tag: 2
}
"""

所需的结果是我可以写入文件或使用的JSON。

1 个答案:

答案 0 :(得分:0)

在底部添加以下行。将其转换为字符串,然后将其写入文件。

x = str(response)
text_file = open("response.json", "w")
text_file.write(x)
text_file.close()