実現したいこと
azureのspeech to textとrest apiをつかってwavファイルをおくってテキスト化したものを受け取りたい。
前提
azureとの連携の部分はchatgptに型を用意してもらった。
認証トークンは受け取れているため、REST API自体は連携できているみたいだが、
音声ファイルをおくるところでこけているのか、テキスト変換のレスポンスが返ってこない(response_finalのところ)
発生している問題・エラーメッセージ
アクセストークンがおかしいといわれるがazure側から送られてきたので問題はないはず
エラー: { "statusCode": 401, "message": "Unauthorized. Access token is missing, invalid, audience is incorrect (urn:ms.scopedToken or urn:ms.faceSessionToken), or have expired." } 127.0.0.1 - - [07/Oct/2023 17:57:10] "POST /upload HTTP/1.1" 200 -
該当のソースコード
# -*- coding: utf-8 -*- from flask import Flask, render_template, request, jsonify #requestは、Flaskのリクエストオブジェクトで、HTTPリクエストに関する情報を提供 import requests #PythonのHTTPライブラリで、HTTPリクエストを送信するための機能を提供 import os #ファイルのパスを取得するためのライブラリ app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/hello') def hello(): return render_template('hello.html') @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = file.filename file.save(os.path.join('uploads', filename)) AzureSpeechToTextAPI(file) return 'アップロード完了' #SpeechToTextにREST APIで連携する処理 def AzureSpeechToTextAPI(file): # Speech ServicesのAPIキーとエンドポイントを設定する subscription_key = 'xxxxxxxxxxxxxxxx' endpoint = 'https://japaneast.api.cognitive.microsoft.com/sts/v1.0/issuetoken' # REST APIのヘッダーを設定する headers = { 'Ocp-Apim-Subscription-Key': subscription_key } # REST APIを呼び出して、認証トークンを取得する response = requests.post(endpoint, headers=headers) if response.status_code == 200: access_token = response.text print('認証トークンを取得しました。') # アクセストークンの有効期限を確認する try: expires_in = response.json()['expires_in'] print('アクセストークンの有効期限は{}秒です。'.format(expires_in)) except ValueError as e: print('JSONデータが無効です。') print('エラーメッセージ: {}'.format(str(e))) else: print('認証トークンの取得に失敗しました。') # スピーチ認識のリクエストデータ(例: WAVファイルの音声データ) audio_data = open("uploads/01.male.wav", "rb").read() # スピーチ認識のREST APIリクエスト headers = { "Authorization": "Bearer " + access_token, "Content-Type": "audio/wav", } params = { "api-version": "3.1", "language": "ja-JP", # 言語設定 } response_final = requests.post(endpoint, headers=headers, params=params, data=audio_data) # 結果の表示 if response_final.status_code == 200: print("認識結果: {}".format(response_final.json())) else: print("エラー: {}".format(response_final.text)) if __name__ == '__main__': app.run()
試したこと
ここに問題に対して試したことを記載してください。
補足情報(FW/ツールのバージョンなど)
Python 3.11.5
Flask 3.0.0

回答1件
あなたの回答
tips
プレビュー