-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
160 lines (128 loc) · 5.49 KB
/
Copy pathapp.py
File metadata and controls
160 lines (128 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import os
from flask import Flask, render_template, request, jsonify
from openai import OpenAI
from ibm_watson import SpeechToTextV1, TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
# OpenAI Client
openai_api_key = os.getenv("OPENAI_API_KEY")
openai_client = OpenAI(api_key=openai_api_key) if openai_api_key else None
# IBM Watson Credentials
ibm_stt_api_key = os.getenv("IBM_STT_API_KEY")
ibm_stt_url = os.getenv("IBM_STT_URL")
ibm_tts_api_key = os.getenv("IBM_TTS_API_KEY")
ibm_tts_url = os.getenv("IBM_TTS_URL")
# Initialize IBM Watson Speech to Text
stt = None
if ibm_stt_api_key and ibm_stt_url:
stt_authenticator = IAMAuthenticator(ibm_stt_api_key)
stt = SpeechToTextV1(authenticator=stt_authenticator)
stt.set_service_url(ibm_stt_url)
# Initialize IBM Watson Text to Speech
tts = None
if ibm_tts_api_key and ibm_tts_url:
tts_authenticator = IAMAuthenticator(ibm_tts_api_key)
tts = TextToSpeechV1(authenticator=tts_authenticator)
tts.set_service_url(ibm_tts_url)
@app.errorhandler(400)
def bad_request_error(error):
return jsonify({'error': 'Bad Request', 'message': str(error)}), 400
@app.errorhandler(404)
def not_found_error(error):
if request.path.startswith('/'):
return jsonify({'error': 'Not Found', 'message': 'The requested endpoint does not exist.'}), 404
return render_template('index.html'), 404
@app.errorhandler(500)
def internal_error(error):
app.logger.error(f'Server Error: {error}')
return jsonify({'error': 'Internal Server Error', 'message': 'An unexpected error occurred.'}), 500
@app.route('/')
def index():
return render_template('index.html')
@app.route('/transcribe', methods=['POST'])
def transcribe():
req_ibm_stt_api_key = request.headers.get('X-IBM-STT-API-KEY') or ibm_stt_api_key
req_ibm_stt_url = request.headers.get('X-IBM-STT-URL') or ibm_stt_url
if not req_ibm_stt_api_key or not req_ibm_stt_url:
return jsonify({'error': 'IBM Speech to Text is not configured'}), 400
local_stt = stt
if request.headers.get('X-IBM-STT-API-KEY'):
try:
local_authenticator = IAMAuthenticator(req_ibm_stt_api_key)
local_stt = SpeechToTextV1(authenticator=local_authenticator)
local_stt.set_service_url(req_ibm_stt_url)
except Exception as e:
return jsonify({'error': f'Failed to initialize STT: {str(e)}'}), 500
if 'audio' not in request.files:
return jsonify({'error': 'No audio file provided'}), 400
audio_file = request.files['audio']
try:
stt_result = local_stt.recognize(
audio=audio_file,
content_type=audio_file.content_type,
model='en-US_BroadbandModel'
).get_result()
transcript = ""
if stt_result['results']:
transcript = stt_result['results'][0]['alternatives'][0]['transcript']
return jsonify({'transcript': transcript})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/ask', methods=['POST'])
def ask():
data = request.json
prompt = data.get('prompt')
req_openai_api_key = request.headers.get('X-OPENAI-API-KEY') or openai_api_key
if not req_openai_api_key:
return jsonify({'error': 'OpenAI is not configured'}), 400
local_openai_client = openai_client
if request.headers.get('X-OPENAI-API-KEY'):
local_openai_client = OpenAI(api_key=req_openai_api_key)
if not prompt:
return jsonify({'error': 'No prompt provided'}), 400
try:
response = local_openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful voice assistant."},
{"role": "user", "content": prompt}
]
)
answer = response.choices[0].message.content
return jsonify({'answer': answer})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/synthesize', methods=['POST'])
def synthesize():
data = request.json
text = data.get('text')
req_ibm_tts_api_key = request.headers.get('X-IBM-TTS-API-KEY') or ibm_tts_api_key
req_ibm_tts_url = request.headers.get('X-IBM-TTS-URL') or ibm_tts_url
if not req_ibm_tts_api_key or not req_ibm_tts_url:
return jsonify({'error': 'IBM Text to Speech is not configured'}), 400
local_tts = tts
if request.headers.get('X-IBM-TTS-API-KEY'):
try:
local_authenticator = IAMAuthenticator(req_ibm_tts_api_key)
local_tts = TextToSpeechV1(authenticator=local_authenticator)
local_tts.set_service_url(req_ibm_tts_url)
except Exception as e:
return jsonify({'error': f'Failed to initialize TTS: {str(e)}'}), 500
if not text:
return jsonify({'error': 'No text provided'}), 400
try:
tts_result = local_tts.synthesize(
text,
voice='en-US_AllisonV3Voice',
accept='audio/wav'
).get_result()
# In a real app, you might save this to a file or stream it.
# For simplicity, returning the audio directly would require setting up proper binary response.
from flask import Response
return Response(tts_result.content, mimetype='audio/wav')
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, port=5000)