|
import gradio as gr |
|
from huggingface_hub import InferenceClient |
|
import difflib |
|
|
|
|
|
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta") |
|
|
|
|
|
s2t = gr.Interface.load('huggingface/facebook/s2t-medium-librispeech-asr') |
|
|
|
|
|
def generate_text_with_huggingface(system_message, max_tokens, temperature, top_p): |
|
""" |
|
Function to generate text using Hugging Face Inference API |
|
based on the system message, max tokens, temperature, and top-p. |
|
""" |
|
messages = [{"role": "system", "content": system_message}] |
|
message = "" |
|
|
|
response = "" |
|
|
|
for message in client.chat_completion( |
|
messages, |
|
max_tokens=max_tokens, |
|
stream=True, |
|
temperature=temperature, |
|
top_p=top_p, |
|
): |
|
token = message.choices[0].delta.content |
|
response += token |
|
|
|
return response.strip() |
|
|
|
|
|
def pronunciation_feedback(transcription, reference_text): |
|
""" |
|
Function to provide feedback on pronunciation based on differences |
|
between the transcription and the reference (expected) text. |
|
""" |
|
diff = difflib.ndiff(reference_text.split(), transcription.split()) |
|
|
|
errors = [word for word in diff if word.startswith('- ')] |
|
|
|
if errors: |
|
feedback = "Mispronounced words: " + ', '.join([error[2:] for error in errors]) |
|
else: |
|
feedback = "Great job! Your pronunciation is spot on." |
|
|
|
return feedback |
|
|
|
|
|
def transcribe_and_feedback(audio, system_message, max_tokens, temperature, top_p): |
|
""" |
|
Transcribe the audio and provide pronunciation feedback using the generated text. |
|
""" |
|
|
|
reference_text = generate_text_with_huggingface(system_message, max_tokens, temperature, top_p) |
|
|
|
|
|
transcription = s2t(audio) |
|
|
|
|
|
feedback = pronunciation_feedback(transcription, reference_text) |
|
|
|
return transcription, feedback, reference_text |
|
|
|
|
|
|
|
demo = gr.Interface( |
|
fn=transcribe_and_feedback, |
|
inputs=[ |
|
gr.Audio(type="filepath", label="Record Audio"), |
|
gr.Textbox(value="Please read a simple sentence.", label="System message"), |
|
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), |
|
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), |
|
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)") |
|
], |
|
outputs=[ |
|
gr.Textbox(label="Transcription"), |
|
gr.Textbox(label="Pronunciation Feedback"), |
|
gr.Textbox(label="Generated Text (What You Were Supposed to Read)") |
|
], |
|
title="Speech-to-Text with Pronunciation Feedback", |
|
description="Record an audio sample and the system will transcribe it, " |
|
"compare your transcription to the generated text, and give pronunciation feedback.", |
|
live=True |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.launch(queue=True, show_error=True) |
|
|