|
|
import os |
|
|
import json |
|
|
import numpy as np |
|
|
from vosk import Model, KaldiRecognizer |
|
|
from flask import Flask, request, jsonify |
|
|
from flask_restx import Api, Resource |
|
|
|
|
|
|
|
|
app = Flask(__name__) |
|
|
|
|
|
|
|
|
api = Api(app, version='1.0', title='Vosk STT API', description='API cho nhận diện giọng nói sử dụng Vosk') |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
@api.route('/stt') |
|
|
class SpeechToText(Resource): |
|
|
def post(self): |
|
|
""" |
|
|
Nhận dữ liệu âm thanh và trả về kết quả nhận diện giọng nói. |
|
|
""" |
|
|
|
|
|
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__": |
|
|
print("🚀 API Flask đang chạy tại http://localhost:5000") |
|
|
app.run(host="0.0.0.0", port=5000, debug=True) |
|
|
|