SpeechRecognition/app/asr/routes.py

70 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import request, jsonify
from app.utils import make_response
from pathlib import Path
import uuid
import threading
import signal
import os
import json
# 全局状态(模块内部)
task_running = {}
GLOBAL_ASR_SERVICE = None
GLOBAL_DIAR_SERVICE = None
ASR_MODEL_LOADED = False
DIAR_MODEL_LOADED = False
ASR_MODEL_LOCK = threading.Lock()
DIAR_MODEL_LOCK = threading.Lock()
def register_asr_routes(app):
"""【模块唯一入口】只注册路由不创建app"""
@app.route('/api/recognize', methods=['GET'])
def recognize():
task_id = str(uuid.uuid4())
task_running[task_id] = True
try:
path = request.args.get('path', '')
if not path:
return jsonify(make_response(status="error", message="缺少path参数")), 400
server_dir = Path(__file__).parent.parent.parent.absolute()
os.chdir(server_dir)
def timeout_handler(signum, frame):
task_running[task_id] = False
raise TimeoutError(f"超时 {app.config['TASK_TIMEOUT']}s")
use_alarm = False
try:
signal.signal(signal.SIGALRM, timeout_handler) # pyright: ignore
signal.alarm(app.config['TASK_TIMEOUT']) # pyright: ignore
use_alarm = True
except:
pass
try:
from app.asr.core import main
main(path)
finally:
if use_alarm:
signal.alarm(0) # pyright: ignore
task_running[task_id] = False
return jsonify(make_response(message="推理完成", data={"task_id": task_id, "path": path}))
except Exception as e:
task_running[task_id] = False
return jsonify(make_response(status="error", message=str(e))), 500
@app.route('/api/result', methods=['GET'])
def result():
path = request.args.get('path', '')
if not path:
return jsonify(make_response(status="error", message="缺少path")), 400
result_file = Path(app.config['OUTPUT_DIR']) / "SpeechRecognition" / f"{Path(path).stem}_result.json"
if not result_file.exists():
return jsonify(make_response(status="error", message="结果不存在")), 404
with open(result_file, 'r', encoding='utf-8') as f:
data = json.load(f)
return jsonify(make_response(data=data))