File size: 1,644 Bytes
23590ba
 
 
 
 
 
 
 
981b713
 
 
 
 
 
 
 
 
 
 
de1cb80
23590ba
 
 
981b713
 
 
23590ba
981b713
 
 
 
23590ba
981b713
 
 
 
 
23590ba
981b713
 
 
 
 
23590ba
de1cb80
23590ba
981b713
23590ba
 
 
 
 
 
 
de1cb80
981b713
de1cb80
981b713
23590ba
 
981b713
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import wave
import json
import numpy as np
from flask import Flask, request, jsonify
from flask_cors import CORS
from vosk import Model, KaldiRecognizer

# Thư mục chứa model
MODEL_PATH = "model/vosk-model"

# Kiểm tra model đã tải chưa
if not os.path.exists(MODEL_PATH):
    raise Exception(f"❌ Model Vosk không tìm thấy tại {MODEL_PATH}! Kiểm tra lại.")

# Load model
print("✅ Đang tải model Vosk...")
model = Model(MODEL_PATH)

# Khởi tạo Flask app
app = Flask(__name__)
CORS(app)

@app.route("/")
def home():
    return "✅ Vosk STT API đang chạy!"

@app.route("/stt", methods=["POST"])
def stt():
    if "audio" not in request.files:
        return jsonify({"error": "Không tìm thấy file audio!"}), 400

    audio_file = request.files["audio"]
    file_path = "temp.wav"
    audio_file.save(file_path)

    # Mở file âm thanh
    wf = wave.open(file_path, "rb")

    # Kiểm tra file có đúng định dạng WAV mono không
    if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
        os.remove(file_path)
        return jsonify({"error": "File audio phải là WAV mono PCM!"}), 400

    rec = KaldiRecognizer(model, wf.getframerate())
    result_text = ""

    while True:
        data = wf.readframes(4000)
        if len(data) == 0:
            break
        if rec.AcceptWaveform(data):
            result_text += json.loads(rec.Result())["text"] + " "

    wf.close()
    os.remove(file_path)  # Xóa file tạm

    return jsonify({"text": result_text.strip()})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860, debug=True)