问题描述
我正在尝试使用 watson 语音将文件转录为文本 api。今天我使用
从 anaconda 提示 Windows 操作系统升级pip install --upgrade "ibm-watson>=5.1.0"
但是,这样做之后,我无法再访问 api 并且收到以下错误
import os
import json
import time
# import threading
from pathlib import Path
import concurrent.futures
# from os.path import join,dirname
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback,AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import pandas as pd
# Replace with your api key.
my_api_key = "N_OUpGsgBvL-xx"
#my_api_key = "x"
# my_api_key = "xx-UtZsw2Q0WCwVw"
# You can add a directory path to Path() if you want to run
# the project from a different folder at some point.
directory = Path().absolute()
authenticator = IAMAuthenticator(my_api_key)
service = SpeechToTextV1(authenticator=authenticator)
service.set_service_url('https://api.us-east.speech-to-text.watson.cloud.ibm.com')
# I used this URL.
# service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api')
models = service.list_models().get_result()
#print(json.dumps(models,indent=2))
model = service.get_model('en-US_broadbandModel').get_result()
#print(json.dumps(model,indent=2))
# get data to a csv
########################RUN THIS PART SECOND#####################################
def process_data(json_data,output_path):
print(f"Processing: {output_path.stem}")
cols = ["transcript","confidence"]
dfdata = [[t[cols[0]],t.get(cols[1],None)] for r in json_data.get('results') for t in r.get("alternatives")]
df0 = pd.DataFrame(data = dfdata,columns = cols)
df1 = pd.DataFrame(json_data.get("speaker_labels")).drop(["final","confidence"],axis=1)
# test3 = pd.concat([df0,df1],axis=1)
test3 = pd.merge(df0,df1,left_index = True,right_index = True)
# sentiment
print(f"Getting sentiment for: {output_path.stem}")
transcript = test3["transcript"]
transcript.dropna(inplace=True)
analyzer = SentimentIntensityAnalyzer()
text = transcript
scores = [analyzer.polarity_scores(txt) for txt in text]
# data = pd.DataFrame(text,columns = ["Text"])
data = transcript.to_frame(name="Text")
data2 = pd.DataFrame(scores)
# final_dataset= pd.concat([data,data2],axis=1)
final_dataset = pd.merge(data,data2,right_index = True)
# test4 = pd.concat([test3,final_dataset],axis=1)
test4 = pd.merge(test3,final_dataset,right_index = True)
test4.drop("Text",axis=1,inplace=True)
test4.rename(columns = {
"neg": "Negative","pos": "Positive","neu": "Neutral",},inplace=True)
# This is the name of the output csv file
test4.to_csv(output_path,index = False)
def process_audio_file(filename,output_type = "csv"):
audio_file_path = directory.joinpath(filename)
# Update output path to consider `output_type` parameter.
out_path = directory.joinpath(f"{audio_file_path.stem}.{output_type}")
print(f"Current file: '{filename}'")
with open(audio_file_path,"rb") as audio_file:
data = service.recognize(
audio = audio_file,speaker_labels = True,content_type = "audio/wav",inactivity_timeout = -1,smart_formatting = True,model = "en-US_NarrowbandModel",continuous = True,).get_result()
print(f"Speech-to-text complete for: '{filename}'")
# Return data and output path as collection.
return [data,out_path]
def main():
print("Running main()...")
# Default num. workers == min(32,os.cpu_count() + 4)
n_workers = os.cpu_count() + 2
# Create generator for all .wav files in folder (and subfolders).
file_gen = directory.glob("**/*.wav")
with concurrent.futures.ThreadPoolExecutor(max_workers = n_workers) as executor:
futures = {executor.submit(process_audio_file,f) for f in file_gen}
for future in concurrent.futures.as_completed(futures):
pkg = future.result()
process_data(*pkg)
if __name__ == "__main__":
print(f"Program to process audio files has started.")
t_start = time.perf_counter()
main()
t_stop = time.perf_counter()
print(f"Done! Processing completed in {t_stop - t_start} seconds.")
TypeError:init() 缺少 7 个必需的仅限关键字的参数:“url”、“client_id”、“client_secret”、“disable_ssl_verification”、“headers”、“proxies”和“scope” '
我该如何解决这个问题?我需要添加这些新参数吗?如果是这样,在我代码的哪一部分?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)