|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import uuid |
| 4 | +from functools import wraps |
| 5 | + |
| 6 | +if not os.path.exists(os.environ["GOOGLE_APPLICATION_CREDENTIALS"]): |
| 7 | + with open(os.environ["GOOGLE_APPLICATION_CREDENTIALS"], "w") as f: |
| 8 | + f.write(os.environ["GOOGLE_APPLICATION_CREDENTIALS_FILE"]) |
| 9 | + |
| 10 | +from flask import Flask, request |
| 11 | +from werkzeug.utils import secure_filename |
| 12 | + |
| 13 | +sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) |
| 14 | +from scripts.asr.deepspeech import deepspeech_transcribe_from_file |
| 15 | +from scripts.asr.google_speech import google_transcribe_from_file |
| 16 | + |
| 17 | +app = Flask(__name__) |
| 18 | + |
| 19 | + |
| 20 | +def api_key_required(f): |
| 21 | + @wraps(f) |
| 22 | + def decorated_function(*args, **kwargs): |
| 23 | + api_key = str(request.headers.get("Authorization")).split(" ")[-1] |
| 24 | + if not api_key: |
| 25 | + return "API Key is missing", 401 |
| 26 | + if api_key != os.environ.get("API_KEY", "secret"): |
| 27 | + return "Invalid API Key", 403 |
| 28 | + return f(*args, **kwargs) |
| 29 | + |
| 30 | + return decorated_function |
| 31 | + |
| 32 | + |
| 33 | +@app.route("/api/v1/asr/<model>", methods=["POST"]) |
| 34 | +@api_key_required |
| 35 | +def run_asr(model: str): |
| 36 | + MODELS = { |
| 37 | + "deepspeech": deepspeech_transcribe_from_file, |
| 38 | + "google": lambda f: google_transcribe_from_file(f) |
| 39 | + .results[0] |
| 40 | + .alternatives[0] |
| 41 | + .transcript, |
| 42 | + } |
| 43 | + |
| 44 | + if model not in MODELS: |
| 45 | + return f"Invalid model '{model}', must choose one from {MODELS.keys()}", 400 |
| 46 | + |
| 47 | + if "audio_file" not in request.files or not request.files["audio_file"].filename: |
| 48 | + return "No audio file part in the request", 400 |
| 49 | + |
| 50 | + file = request.files["audio_file"] |
| 51 | + filename = secure_filename(file.filename) # type: ignore |
| 52 | + filepath = os.path.join( |
| 53 | + os.path.dirname(__file__), str(uuid.uuid4()) + "_" + filename |
| 54 | + ) |
| 55 | + file.save(filepath) |
| 56 | + |
| 57 | + try: |
| 58 | + return MODELS[model](filepath), 200 |
| 59 | + except Exception as e: |
| 60 | + return f"Transcription failed: {e}", 500 |
| 61 | + finally: |
| 62 | + os.remove(filepath) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + from dotenv import load_dotenv |
| 67 | + |
| 68 | + load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) |
| 69 | + |
| 70 | + # run dev server with: python browser_tests/run_models/main.py |
| 71 | + # test with: curl -X POST -F "audio_file=@data/ExamplesWithComments/TIMIT_sample_0.wav" http://127.0.0.1:5000/api/v1/asr/deepspeech -H "Authorization: Bearer secret" |
| 72 | + app.run(debug=True) |
0 commit comments