|
from flask import Flask, request, jsonify, abort |
|
import whisper |
|
import os |
|
|
|
from flask_cors import CORS |
|
from tempfile import NamedTemporaryFile |
|
|
|
|
|
print("\nLoading Whisper\n", flush=True) |
|
model = whisper.load_model("small") |
|
|
|
|
|
app = Flask(__name__) |
|
CORS(app) |
|
print("\nHello, welcome to SemaBox\n", flush=True) |
|
|
|
|
|
def transcribe(audio): |
|
|
|
|
|
|
|
audio = whisper.load_audio(audio) |
|
audio = whisper.pad_or_trim(audio) |
|
|
|
|
|
mel = whisper.log_mel_spectrogram(audio).to(model.device) |
|
|
|
|
|
_, probs = model.detect_language(mel) |
|
print(f"Detected language: {max(probs, key=probs.get)}") |
|
|
|
|
|
options = whisper.DecodingOptions(fp16 = False) |
|
result = whisper.decode(model, mel, options) |
|
return result.text |
|
|
|
@app.route("/") |
|
def hello(): |
|
return "Semabox, listens to you!" |
|
|
|
@app.route('/whisper', methods=['POST']) |
|
def transcribe_audio(): |
|
if 'audio' not in request.files: |
|
|
|
abort(400, description="No audio file provided") |
|
|
|
audio_file = request.files['audio'] |
|
|
|
|
|
with NamedTemporaryFile(suffix=".wav", delete=True) as temp: |
|
audio_file.save(temp.name) |
|
|
|
|
|
result = model.transcribe(temp.name) |
|
|
|
|
|
return jsonify({ |
|
'filename': audio_file.filename, |
|
'transcript': result['text'], |
|
}) |
|
|
|
|
|
|
|
@app.route('/transcribe', methods=['POST']) |
|
def transcribe_audio(): |
|
|
|
if 'audio' not in request.files: |
|
return jsonify({"error": "No audio file provided"}), 400 |
|
|
|
audio_file = request.files['audio'] |
|
|
|
|
|
audio_path = os.path.join("temp_audio", audio_file.filename) |
|
audio_file.save(audio_path) |
|
|
|
|
|
transcription, language = transcribe(audio_path) |
|
|
|
|
|
os.remove(audio_path) |
|
|
|
|
|
return jsonify({"transcription": transcription, "language": language}), 200 |
|
|
|
|
|
@app.route('/healthcheck', methods=['GET']) |
|
def healthcheck(): |
|
return jsonify({"status": "API is running"}), 200 |
|
|
|
|
|
if __name__ == '__main__': |
|
app.run(host="0.0.0.0", port=5000) |
|
|