|
|
import os |
|
|
import json |
|
|
import numpy as np |
|
|
from vosk import Model, KaldiRecognizer |
|
|
from flask import Flask, request, jsonify |
|
|
|
|
|
|
|
|
app = Flask(__name__) |
|
|
|
|
|
|
|
|
MODEL_PATH = "model/vosk-model" |
|
|
if not os.path.exists(MODEL_PATH): |
|
|
raise Exception("❌ Model Vosk không tìm thấy!") |
|
|
print("✅ Đang tải model Vosk...") |
|
|
model = Model(MODEL_PATH) |
|
|
|
|
|
|
|
|
rec = KaldiRecognizer(model, 16000) |
|
|
|
|
|
|
|
|
@app.route('/stt', methods=['POST']) |
|
|
def handle_audio(): |
|
|
|
|
|
if 'file' not in request.files: |
|
|
return jsonify({"error": "Không có tệp âm thanh trong yêu cầu."}), 400 |
|
|
|
|
|
audio_file = request.files['file'] |
|
|
|
|
|
|
|
|
audio_data = audio_file.read() |
|
|
print(f"📩 Nhận dữ liệu âm thanh: {len(audio_data)} bytes") |
|
|
|
|
|
|
|
|
audio_np = np.frombuffer(audio_data, dtype=np.int16) |
|
|
|
|
|
|
|
|
if rec.AcceptWaveform(audio_np.tobytes()): |
|
|
result = json.loads(rec.Result()) |
|
|
text = result.get("text", "") |
|
|
print(f"📤 Kết quả nhận diện: {text}") |
|
|
return jsonify({"text": text}) |
|
|
else: |
|
|
|
|
|
return jsonify({"text": ""}) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
app.run(host="0.0.0.0", port=5000, debug=True) |
|
|
|