File size: 4,685 Bytes
522c053
bf756e1
af1a473
 
a83e487
a6ad9ca
a83e487
 
a6ad9ca
a83e487
af1a473
112a3e2
 
15bf7ba
af1a473
a83e487
 
 
 
 
 
 
 
 
 
 
 
af1a473
 
a83e487
a6ad9ca
 
a83e487
 
 
 
 
 
 
a6ad9ca
 
 
a83e487
 
a6ad9ca
a83e487
af1a473
 
 
a6ad9ca
a83e487
 
a6ad9ca
a83e487
a6ad9ca
 
 
 
af1a473
a6ad9ca
af1a473
a83e487
 
 
 
 
a6ad9ca
a83e487
af1a473
371ca9c
a6ad9ca
371ca9c
a6ad9ca
371ca9c
a6ad9ca
371ca9c
a6ad9ca
 
 
371ca9c
a6ad9ca
 
 
371ca9c
a6ad9ca
522c053
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
import gradio as gr
import openai
import speech_recognition as sr
import logging
import traceback

# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# Set OpenAI API key
openai.api_key = os.environ.get("OPENAI_API_KEY")

def generate_text():
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "Generate exactly two simple sentences for English pronunciation practice. Do not include any instructions, comments, or additional text."},
                {"role": "user", "content": "Create two simple sentences for pronunciation practice."}
            ]
        )
        return response.choices[0].message['content'].strip()
    except Exception as e:
        logger.error(f"Error in generate_text: {str(e)}")
        return "Error generating text. Please try again."

def get_pronunciation_feedback(original_text, transcription):
    try:
        logger.debug(f"Original text: {original_text}")
        logger.debug(f"Transcription: {transcription}")
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful pronunciation assistant. Compare the generated text with the user's transcription and provide feedback on how the user can improve their pronunciation. Single out specific words they pronounced incorrectly and give tips on how to improve, like for example 'schedule' can be pronounced as 'sked-jool'."},
                {"role": "user", "content": f"Original text: '{original_text}'\nTranscription: '{transcription}'\nProvide pronunciation feedback."}
            ]
        )
        feedback = response.choices[0].message['content']
        logger.debug(f"Generated feedback: {feedback}")
        return feedback
    except Exception as e:
        logger.error(f"Error in get_pronunciation_feedback: {str(e)}")
        logger.error(traceback.format_exc())
        return "Error generating feedback. Please try again."

def transcribe_audio_realtime(audio):
    try:
        logger.debug(f"Received audio file: {audio}")
        recognizer = sr.Recognizer()
        with sr.AudioFile(audio) as source:
            logger.debug("Reading audio file")
            audio_data = recognizer.record(source)
        logger.debug("Transcribing audio")
        transcription = recognizer.recognize_google(audio_data)
        logger.debug(f"Transcription result: {transcription}")
        return transcription
    except sr.UnknownValueError:
        logger.warning("Could not understand audio")
        return "Could not understand audio"
    except sr.RequestError as e:
        logger.error(f"Could not request results from the speech recognition service; {str(e)}")
        return "Error in speech recognition service"
    except Exception as e:
        logger.error(f"Error in transcribe_audio_realtime: {str(e)}")
        logger.error(traceback.format_exc())
        return "Error transcribing audio. Please try again."

def practice_pronunciation(audio, text_to_read):
    logger.info("Starting practice_pronunciation function")
    if not text_to_read:
        logger.info("Generating new text to read")
        text_to_read = generate_text()
    logger.info(f"Text to read: {text_to_read}")
    
    logger.info("Starting transcription")
    transcription = transcribe_audio_realtime(audio)
    logger.info(f"Transcription result: {transcription}")
    
    logger.info("Getting pronunciation feedback")
    feedback = get_pronunciation_feedback(text_to_read, transcription)
    logger.info(f"Feedback generated: {feedback}")
    
    return text_to_read, transcription, feedback

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("# Pronunciation Practice Tool")
    gr.Markdown("Generate a text to read, then record yourself reading it. The system will provide pronunciation feedback.")
    
    with gr.Row():
        text_to_read = gr.Textbox(label="Text to Read")
        generate_button = gr.Button("Generate New Text")
    
    audio_input = gr.Audio(type="filepath", label="Record your voice")
    
    with gr.Row():
        transcription_output = gr.Textbox(label="Your Transcription")
        feedback_output = gr.Textbox(label="Pronunciation Feedback")
    
    submit_button = gr.Button("Submit")
    
    generate_button.click(generate_text, outputs=text_to_read)
    submit_button.click(practice_pronunciation, inputs=[audio_input, text_to_read], outputs=[text_to_read, transcription_output, feedback_output])

# Launch the app
if __name__ == "__main__":
    demo.launch()