Mahmous commited on
Commit
8d171d0
·
verified ·
1 Parent(s): 9ef5952

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +52 -0
api.py CHANGED
@@ -207,6 +207,58 @@ def ask():
207
  return jsonify(format_answers(question, f"⚠️ LLM call failed: {e}", results)), 200
208
 
209
  return jsonify(format_answers(question, answer, results))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
 
211
  # ---------- Run ----------
212
  if __name__ == "__main__":
 
207
  return jsonify(format_answers(question, f"⚠️ LLM call failed: {e}", results)), 200
208
 
209
  return jsonify(format_answers(question, answer, results))
210
+
211
+ from flask import send_file
212
+ import tempfile
213
+
214
+ @app.route("/voice", methods=["POST"])
215
+ def voice_chat():
216
+ try:
217
+ audio = request.files.get("audio")
218
+ if not audio:
219
+ return jsonify({"error": "No audio file uploaded"}), 400
220
+
221
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
222
+ audio.save(tmp.name)
223
+ audio_path = tmp.name
224
+
225
+ # Step 1️⃣: Transcribe using OpenAI Whisper or any STT
226
+ transcription = client.audio.transcriptions.create(
227
+ model="whisper-1",
228
+ file=open(audio_path, "rb")
229
+ )
230
+ text = transcription.text.strip()
231
+ print(f"🎤 Transcribed: {text}")
232
+
233
+ # Step 2️⃣: Get mentoring answer from your existing /ask logic
234
+ data = {"question": text}
235
+ with app.test_request_context(json=data):
236
+ response = ask()
237
+ response_json = response.get_json()
238
+
239
+ # Step 3️⃣: Optional TTS response
240
+ answer_text = response_json["answers"][0]["answer"]
241
+ speech_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
242
+ with client.audio.speech.with_streaming_response.create(
243
+ model="gpt-4o-mini-tts",
244
+ voice="alloy",
245
+ input=answer_text
246
+ ) as speech:
247
+ speech.stream_to_file(speech_file.name)
248
+
249
+ return jsonify({
250
+ "transcript": text,
251
+ "answer": answer_text,
252
+ "audio_url": f"/audio/{os.path.basename(speech_file.name)}"
253
+ })
254
+ except Exception as e:
255
+ traceback.print_exc()
256
+ return jsonify({"error": str(e)}), 500
257
+
258
+
259
+ @app.route("/audio/<filename>")
260
+ def serve_audio(filename):
261
+ return send_file(os.path.join(tempfile.gettempdir(), filename), mimetype="audio/mpeg")
262
 
263
  # ---------- Run ----------
264
  if __name__ == "__main__":