Spaces:
Paused
Paused
| import base64 | |
| import tempfile | |
| from flask import Flask, request, jsonify | |
| from transformers import pipeline | |
| app = Flask(__name__) | |
| # Whisperモデルを準備 | |
| model_name = "openai/whisper-small" | |
| transcriber = pipeline("automatic-speech-recognition", model=model_name) | |
| def decode_audio(data_url): | |
| """ | |
| dataURLをデコードして一時ファイルに保存し、そのファイルパスを返す | |
| """ | |
| # `dataURL`形式からヘッダーとデータ部分を分離 | |
| header, encoded = data_url.split(",", 1) | |
| audio_data = base64.b64decode(encoded) | |
| # 一時ファイルに保存 | |
| with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio_file: | |
| temp_audio_file.write(audio_data) | |
| return temp_audio_file.name | |
| def transcribe_audio(): | |
| """ | |
| POSTリクエストで送信されたdataURLを文字起こし | |
| """ | |
| try: | |
| # JSONからdataURLを取得 | |
| data = request.json | |
| data_url = data.get("dataURL") | |
| if not data_url: | |
| return jsonify({"error": "Missing 'dataURL' in request"}), 400 | |
| # 音声データをデコードして一時ファイルパスを取得 | |
| audio_file_path = decode_audio(data_url) | |
| # Whisperで文字起こし | |
| result = transcriber(audio_file_path) | |
| text = result["text"] | |
| # 一時ファイルを削除(必要なら実装) | |
| # os.remove(audio_file_path) | |
| return jsonify({"transcription": text}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(port=7860) | |