Mrlongpro's picture
Update app.py
ae77bb0 verified
raw
history blame
2.67 kB
import gradio as gr
import speech_recognition as sr
import difflib
import pyaudio
# Hàm chuyển giọng nói thành văn bản
def transcribe_speech():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
# Điều chỉnh tiếng ồn nền và ghi âm
recognizer.adjust_for_ambient_noise(source, duration=1)
audio = recognizer.listen(source)
try:
# Chuyển giọng nói thành văn bản
text = recognizer.recognize_google(audio, language="vi-VN")
return text
except sr.UnknownValueError:
return "Không thể nhận diện giọng nói"
except sr.RequestError as e:
return f"Lỗi kết nối dịch vụ Google: {e}"
# Hàm so sánh văn bản chuyển đổi với văn bản mẫu
def compare_transcription(transcribed_text, reference_text):
transcribed_words = transcribed_text.split()
reference_words = reference_text.split()
incorrect_words = []
for i, word in enumerate(transcribed_words):
if i >= len(reference_words) or word.lower() != reference_words[i].lower():
incorrect_words.append(word)
matches = difflib.SequenceMatcher(None, transcribed_words, reference_words)
accuracy = matches.ratio() * 100
return accuracy, incorrect_words
# Hàm tích hợp để dùng trên Gradio
def process_speech(reference_text):
transcribed_text = transcribe_speech()
if "Lỗi" in transcribed_text or "Không thể nhận diện" in transcribed_text:
return transcribed_text, None, None
accuracy, incorrect_words = compare_transcription(transcribed_text, reference_text)
return transcribed_text, f"{accuracy:.2f}%", ", ".join(incorrect_words) if incorrect_words else "Không có từ sai"
# Tạo giao diện với Gradio
def build_interface():
with gr.Blocks() as demo:
# Input cho văn bản mẫu
reference_text = gr.Textbox(label="Văn bản mẫu", value="Xin chào, tôi là ChatGPT", lines=2)
# Button để ghi âm
record_button = gr.Button("Ghi âm và kiểm tra")
# Output hiển thị kết quả
transcribed_text = gr.Textbox(label="Văn bản bạn nói")
accuracy = gr.Textbox(label="Độ chính xác (%)")
incorrect_words = gr.Textbox(label="Những từ nói sai")
# Nút ghi âm được kết nối với chức năng xử lý
record_button.click(fn=process_speech, inputs=[reference_text], outputs=[transcribed_text, accuracy, incorrect_words])
return demo
# Chạy giao diện
demo = build_interface()
demo.launch()