Nechba commited on
Commit
8ec66b1
·
verified ·
1 Parent(s): 43ca604

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -23
app.py CHANGED
@@ -1,43 +1,30 @@
1
  from flask import Flask, request, jsonify
2
-
3
  import whisper
4
- import os
5
- import tempfile
6
  import io
7
- import torchaudio
8
 
9
  app = Flask(__name__)
10
 
11
- # Initialize Whisper model
12
- whisper_model = whisper.load_model("small") # Renamed variable
13
-
14
-
15
-
16
 
17
  @app.route('/transcribe', methods=['POST'])
18
  def transcribe():
19
  try:
20
- # Read raw bytes from the request
21
  audio_bytes = request.data
22
  if not audio_bytes:
23
  return jsonify({"error": "No audio data provided"}), 400
24
 
25
- # Convert bytes to a file-like object
26
- audio_file = io.BytesIO(audio_bytes)
 
 
27
 
28
- # Load audio as a waveform using torchaudio
29
- waveform, sample_rate = torchaudio.load(audio_file)
30
-
31
- # Whisper expects a NumPy array, so we convert it
32
- audio_numpy = waveform.squeeze().numpy()
33
-
34
- # Transcribe the audio
35
- result = model.transcribe(audio_numpy)
36
 
37
  return jsonify({"text": result["text"]})
38
 
39
  except Exception as e:
40
  print("Error:", str(e)) # Log error for debugging
41
- return jsonify({"error": "Internal Server Error", "details": str(e)}), 500
42
-
43
-
 
1
  from flask import Flask, request, jsonify
 
2
  import whisper
 
 
3
  import io
 
4
 
5
  app = Flask(__name__)
6
 
7
+ # Load Whisper model once for efficiency
8
+ model = whisper.load_model("small")
 
 
 
9
 
10
  @app.route('/transcribe', methods=['POST'])
11
  def transcribe():
12
  try:
13
+ # Read raw bytes from request
14
  audio_bytes = request.data
15
  if not audio_bytes:
16
  return jsonify({"error": "No audio data provided"}), 400
17
 
18
+ # Save bytes to a temporary file (required for Whisper)
19
+ temp_audio_path = "temp_audio.wav"
20
+ with open(temp_audio_path, "wb") as f:
21
+ f.write(audio_bytes)
22
 
23
+ # Transcribe using Whisper
24
+ result = model.transcribe(temp_audio_path)
 
 
 
 
 
 
25
 
26
  return jsonify({"text": result["text"]})
27
 
28
  except Exception as e:
29
  print("Error:", str(e)) # Log error for debugging
30
+ return jsonify({"error": "Internal Server Error", "details": str(e)}), 500