Mahmous commited on
Commit
f6fc55b
·
verified ·
1 Parent(s): 08040e3

Update app.py

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