Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -11,78 +11,178 @@ import whisper
|
|
| 11 |
import pandas as pd
|
| 12 |
from gtts import gTTS
|
| 13 |
import re
|
| 14 |
-
import
|
| 15 |
-
import
|
| 16 |
|
| 17 |
-
# ---
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
# --- CAMBIO: La funci贸n de evaluaci贸n ahora incrusta el audio en Base64 ---
|
| 21 |
def run_sentence_evaluation(audio_input, reference_transcript):
|
| 22 |
if not api_key_found: raise gr.Error("OpenAI API key not found.")
|
| 23 |
if audio_input is None or not reference_transcript:
|
| 24 |
return 0, "N/A", "Please provide both an audio file and the reference text.", ""
|
| 25 |
-
|
| 26 |
sr, y = audio_input; temp_audio_path = "temp_audio_sentence.wav"; sf.write(temp_audio_path, y, sr)
|
| 27 |
word_features = extract_word_level_features(temp_audio_path)
|
| 28 |
if not word_features:
|
| 29 |
return 0, "N/A", "Could not process the audio.", ""
|
| 30 |
prompt_data = {"reference_transcript": reference_transcript, "spoken_words": word_features}
|
| 31 |
-
|
| 32 |
print("Sending detailed data to GPT-4o for sentence analysis...")
|
| 33 |
response = client.chat.completions.create(model="gpt-4o", response_format={"type": "json_object"}, messages=[{"role": "system", "content": SENTENCE_EVALUATION_SYSTEM_PROMPT}, {"role": "user", "content": json.dumps(prompt_data)}])
|
| 34 |
-
|
| 35 |
try:
|
| 36 |
result = json.loads(response.choices[0].message.content)
|
| 37 |
holistic_feedback_md = f"### Strengths\n{result['holistic_feedback']['strengths']}\n\n### Areas for Improvement\n{result['holistic_feedback']['areas_for_improvement']}"
|
| 38 |
word_analysis_list = result['word_by_word_analysis']
|
| 39 |
-
|
| 40 |
-
# --- NUEVA L脫GICA: Construir tabla en Markdown con audio Base64 ---
|
| 41 |
-
md_table = "| Reference Word | Spoken Word | Score | Feedback (EN) | Feedback (ES) | Reference Audio |\n"
|
| 42 |
-
md_table += "| :--- | :--- | :---: | :--- | :--- | :---: |\n"
|
| 43 |
-
|
| 44 |
for index, item in enumerate(word_analysis_list):
|
| 45 |
word_to_speak = item['reference_word']
|
| 46 |
-
|
| 47 |
try:
|
| 48 |
-
|
| 49 |
-
tts = gTTS(text=word_to_speak, lang='en')
|
| 50 |
-
mp3_fp = io.BytesIO()
|
| 51 |
-
tts.write_to_fp(mp3_fp)
|
| 52 |
-
mp3_fp.seek(0)
|
| 53 |
-
|
| 54 |
-
# 2. Codificar el audio en Base64
|
| 55 |
audio_base64 = base64.b64encode(mp3_fp.read()).decode('utf-8')
|
| 56 |
-
|
| 57 |
-
# 3. Crear una etiqueta de audio con los datos incrustados (Data URI)
|
| 58 |
audio_player = f'<audio src="data:audio/mpeg;base64,{audio_base64}" controls></audio>'
|
| 59 |
-
|
| 60 |
except Exception as e:
|
| 61 |
print(f"Error al generar TTS para '{word_to_speak}': {e}"); audio_player = "Error"
|
| 62 |
-
|
| 63 |
md_table += (f"| **{item['reference_word']}** | {item['spoken_word']} | {item['word_score_100']} | {item['feedback_en']} | {item['feedback_es']} | {audio_player} |\n")
|
| 64 |
-
|
| 65 |
return (result.get("overall_score_100", 0), result.get("cefr_level", "N/A"), holistic_feedback_md, md_table)
|
| 66 |
except (json.JSONDecodeError, KeyError) as e:
|
| 67 |
print(f"Error processing API response: {e}"); error_msg = "The API response was not in the expected format."
|
| 68 |
return 0, "Error", error_msg, ""
|
| 69 |
|
| 70 |
-
|
| 71 |
-
# --- 3. INTERFAZ DE GRADIO CON PESTA脩AS (La definici贸n no cambia, pero ahora recibe Markdown) ---
|
| 72 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 73 |
-
#
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
with gr.TabItem("Evaluaci贸n por Frase"):
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
if __name__ == "__main__":
|
| 87 |
-
if not api_key_found: print("\nFATAL: OpenAI API key not found.")
|
| 88 |
else: demo.launch(debug=True)
|
|
|
|
| 11 |
import pandas as pd
|
| 12 |
from gtts import gTTS
|
| 13 |
import re
|
| 14 |
+
import base64
|
| 15 |
+
import io
|
| 16 |
|
| 17 |
+
# --- 0. CONFIGURACI脫N INICIAL ---
|
| 18 |
+
try:
|
| 19 |
+
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
|
| 20 |
+
api_key_found = True
|
| 21 |
+
except TypeError:
|
| 22 |
+
api_key_found = False
|
| 23 |
+
|
| 24 |
+
print("Loading Whisper for transcription...")
|
| 25 |
+
whisper_model = whisper.load_model("base", device="cpu")
|
| 26 |
+
print("Whisper model loaded.")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# --- 1. DEFINICI脫N DE PROMPTS PARA LA IA ---
|
| 30 |
+
|
| 31 |
+
CONVERSATION_SYSTEM_PROMPT = """
|
| 32 |
+
You are a friendly and encouraging English language tutor named Alex.
|
| 33 |
+
A student will speak to you. Your task is to keep a natural, simple conversation going.
|
| 34 |
+
1. Briefly analyze the user's previous response to estimate their CEFR level (A1, A2, B1, etc.).
|
| 35 |
+
2. Formulate a simple, open-ended follow-up question that is appropriate for THAT estimated level.
|
| 36 |
+
3. Your entire response must be a single, short paragraph in natural, conversational English. DO NOT use JSON.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
FINAL_EVALUATION_SYSTEM_PROMPT = """
|
| 40 |
+
You are an expert English language examiner providing a final report. Analyze the entire conversation history provided.
|
| 41 |
+
Your task is to return a single, valid JSON object with the following structure. Do not include any text outside this JSON object.
|
| 42 |
+
JSON Output Structure:
|
| 43 |
+
{
|
| 44 |
+
"cefr_level": "string (e.g., A2, B1)",
|
| 45 |
+
"feedback_en": { "strengths": "string", "areas_for_improvement": "string", "word_by_word_feedback": [{"word": "string", "feedback": "string"}] },
|
| 46 |
+
"feedback_es": { "fortalezas": "string", "areas_a_mejorar": "string", "feedback_por_palabra": [{"palabra": "string", "feedback": "string"}] }
|
| 47 |
+
}
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
SENTENCE_EVALUATION_SYSTEM_PROMPT = """
|
| 51 |
+
You are an expert English language examiner specializing in phonetics. Your task is to provide a detailed, diagnostic assessment of a student's spoken English based on a reference sentence and detailed word-level audio analysis.
|
| 52 |
+
Input You Will Receive: A JSON object with `reference_transcript` and a list of `spoken_words` with timestamps and energy.
|
| 53 |
+
Your entire response MUST be a single, valid JSON object with the following structure. Do not include any text outside this JSON object.
|
| 54 |
+
JSON Output Structure:
|
| 55 |
+
{
|
| 56 |
+
"overall_score_100": integer,
|
| 57 |
+
"cefr_level": "string (A1, A2, B1, B2, C1, or C2)",
|
| 58 |
+
"holistic_feedback": { "strengths": "string", "areas_for_improvement": "string" },
|
| 59 |
+
"word_by_word_analysis": [ { "reference_word": "string", "spoken_word": "string", "word_score_100": integer, "correct_ipa": "string", "feedback_en": "string", "feedback_es": "string" } ]
|
| 60 |
+
}
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
# --- 2. FUNCIONES L脫GICAS ---
|
| 64 |
+
|
| 65 |
+
def extract_word_level_features(audio_path):
|
| 66 |
+
try:
|
| 67 |
+
y, sr = librosa.load(audio_path, sr=16000)
|
| 68 |
+
result = whisper_model.transcribe(audio_path, word_timestamps=True, fp16=False)
|
| 69 |
+
if not result["segments"] or 'words' not in result["segments"][0]: return []
|
| 70 |
+
word_segments = result["segments"][0]["words"]
|
| 71 |
+
features_list = []
|
| 72 |
+
for segment in word_segments:
|
| 73 |
+
start_sample = int(segment['start'] * sr); end_sample = int(segment['end'] * sr)
|
| 74 |
+
word_audio = y[start_sample:end_sample]
|
| 75 |
+
rms_energy = np.mean(librosa.feature.rms(y=word_audio)) if len(word_audio) > 0 else 0
|
| 76 |
+
features_list.append({"word": segment['word'].strip(), "start": round(segment['start'], 2), "end": round(segment['end'], 2), "energy": round(float(rms_energy), 4)})
|
| 77 |
+
return features_list
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"Error during feature extraction: {e}"); return []
|
| 80 |
+
|
| 81 |
+
def chat_interaction(audio_input, history_state):
|
| 82 |
+
if not api_key_found: raise gr.Error("OpenAI API key not found.")
|
| 83 |
+
if audio_input is None: return history_state, history_state, gr.Markdown(visible=False), gr.Markdown(visible=False)
|
| 84 |
+
|
| 85 |
+
sr, y = audio_input; temp_audio_path = "temp_audio_chat.wav"; sf.write(temp_audio_path, y, sr)
|
| 86 |
+
user_text = client.audio.transcriptions.create(model="whisper-1", file=open(temp_audio_path, "rb")).text
|
| 87 |
+
|
| 88 |
+
# Si el historial est谩 vac铆o, lo inicializamos con el prompt del sistema
|
| 89 |
+
if not history_state:
|
| 90 |
+
history_state = [{"role": "system", "content": CONVERSATION_SYSTEM_PROMPT}]
|
| 91 |
+
|
| 92 |
+
history_state.append({"role": "user", "content": user_text})
|
| 93 |
+
|
| 94 |
+
if len(history_state) < 10: # 1 system + 4 pares de user/assistant
|
| 95 |
+
response = client.chat.completions.create(model="gpt-4o", messages=history_state, temperature=0.7)
|
| 96 |
+
ai_response = response.choices[0].message.content
|
| 97 |
+
history_state.append({"role": "assistant", "content": ai_response})
|
| 98 |
+
|
| 99 |
+
chat_display = [(history_state[i]['content'], history_state[i+1]['content']) for i in range(1, len(history_state), 2)]
|
| 100 |
+
return chat_display, history_state, gr.Markdown(visible=False), gr.Markdown(visible=False)
|
| 101 |
+
else:
|
| 102 |
+
print("Generating final evaluation...");
|
| 103 |
+
final_messages = [{"role": "system", "content": FINAL_EVALUATION_SYSTEM_PROMPT}] + history_state[1:] # Excluir el prompt de conversaci贸n
|
| 104 |
+
response = client.chat.completions.create(model="gpt-4o", response_format={"type": "json_object"}, messages=final_messages)
|
| 105 |
+
try:
|
| 106 |
+
result = json.loads(response.choices[0].message.content)
|
| 107 |
+
fb_en = result.get('feedback_en', {}); md_en = f"## Final Report (CEFR Level: {result.get('cefr_level', 'N/A')})\n### Strengths\n{fb_en.get('strengths', '')}\n### Areas for Improvement\n{fb_en.get('areas_for_improvement', '')}\n### Word-by-Word Feedback\n"
|
| 108 |
+
for item in fb_en.get('word_by_word_feedback', []): md_en += f"- **{item['word']}**: {item['feedback']}\n"
|
| 109 |
+
fb_es = result.get('feedback_es', {}); md_es = f"## Reporte Final (Nivel MCERL: {result.get('cefr_level', 'N/A')})\n### Fortalezas\n{fb_es.get('fortalezas', '')}\n### 脕reas a Mejorar\n{fb_es.get('areas_a_mejorar', '')}\n### Retroalimentaci贸n por Palabra\n"
|
| 110 |
+
for item in fb_es.get('feedback_por_palabra', []): md_es += f"- **{item['palabra']}**: {item['feedback']}\n"
|
| 111 |
+
|
| 112 |
+
chat_display = [(history_state[i]['content'], history_state[i+1]['content']) for i in range(1, len(history_state), 2)]
|
| 113 |
+
chat_display.append((None, "Thank you for the conversation! Here is your final report below."))
|
| 114 |
+
|
| 115 |
+
return chat_display, [], gr.Markdown(value=md_en, visible=True), gr.Markdown(value=md_es, visible=True)
|
| 116 |
+
except (json.JSONDecodeError, KeyError) as e:
|
| 117 |
+
print(f"Error parsing final report: {e}"); return [], [], gr.Markdown(value="Error generating report.", visible=True), gr.Markdown(visible=False)
|
| 118 |
|
|
|
|
| 119 |
def run_sentence_evaluation(audio_input, reference_transcript):
|
| 120 |
if not api_key_found: raise gr.Error("OpenAI API key not found.")
|
| 121 |
if audio_input is None or not reference_transcript:
|
| 122 |
return 0, "N/A", "Please provide both an audio file and the reference text.", ""
|
|
|
|
| 123 |
sr, y = audio_input; temp_audio_path = "temp_audio_sentence.wav"; sf.write(temp_audio_path, y, sr)
|
| 124 |
word_features = extract_word_level_features(temp_audio_path)
|
| 125 |
if not word_features:
|
| 126 |
return 0, "N/A", "Could not process the audio.", ""
|
| 127 |
prompt_data = {"reference_transcript": reference_transcript, "spoken_words": word_features}
|
|
|
|
| 128 |
print("Sending detailed data to GPT-4o for sentence analysis...")
|
| 129 |
response = client.chat.completions.create(model="gpt-4o", response_format={"type": "json_object"}, messages=[{"role": "system", "content": SENTENCE_EVALUATION_SYSTEM_PROMPT}, {"role": "user", "content": json.dumps(prompt_data)}])
|
|
|
|
| 130 |
try:
|
| 131 |
result = json.loads(response.choices[0].message.content)
|
| 132 |
holistic_feedback_md = f"### Strengths\n{result['holistic_feedback']['strengths']}\n\n### Areas for Improvement\n{result['holistic_feedback']['areas_for_improvement']}"
|
| 133 |
word_analysis_list = result['word_by_word_analysis']
|
| 134 |
+
md_table = "| Reference Word | Spoken Word | Score | Feedback (EN) | Feedback (ES) | Reference Audio |\n| :--- | :--- | :---: | :--- | :--- | :---: |\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
for index, item in enumerate(word_analysis_list):
|
| 136 |
word_to_speak = item['reference_word']
|
|
|
|
| 137 |
try:
|
| 138 |
+
tts = gTTS(text=word_to_speak, lang='en'); mp3_fp = io.BytesIO(); tts.write_to_fp(mp3_fp); mp3_fp.seek(0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
audio_base64 = base64.b64encode(mp3_fp.read()).decode('utf-8')
|
|
|
|
|
|
|
| 140 |
audio_player = f'<audio src="data:audio/mpeg;base64,{audio_base64}" controls></audio>'
|
|
|
|
| 141 |
except Exception as e:
|
| 142 |
print(f"Error al generar TTS para '{word_to_speak}': {e}"); audio_player = "Error"
|
|
|
|
| 143 |
md_table += (f"| **{item['reference_word']}** | {item['spoken_word']} | {item['word_score_100']} | {item['feedback_en']} | {item['feedback_es']} | {audio_player} |\n")
|
|
|
|
| 144 |
return (result.get("overall_score_100", 0), result.get("cefr_level", "N/A"), holistic_feedback_md, md_table)
|
| 145 |
except (json.JSONDecodeError, KeyError) as e:
|
| 146 |
print(f"Error processing API response: {e}"); error_msg = "The API response was not in the expected format."
|
| 147 |
return 0, "Error", error_msg, ""
|
| 148 |
|
| 149 |
+
# --- 3. INTERFAZ DE GRADIO CON PESTA脩AS ---
|
|
|
|
| 150 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 151 |
+
gr.Markdown("# 馃嚞馃嚙 AI English Speaking Practice & Assessment")
|
| 152 |
+
with gr.Tabs():
|
| 153 |
+
# --- PESTA脩A 1: CHAT AI ---
|
| 154 |
+
with gr.TabItem("Pr谩ctica Conversacional (Chat AI)"):
|
| 155 |
+
with gr.Row():
|
| 156 |
+
with gr.Column(scale=2):
|
| 157 |
+
chatbot = gr.Chatbot(value=[(None, "Hi there! I'm Alex. How are you doing today?")], label="Conversation with your AI Tutor", height=500)
|
| 158 |
+
audio_in_chat = gr.Audio(sources=["microphone"], type="numpy", label="Record your response")
|
| 159 |
+
with gr.Column(scale=1):
|
| 160 |
+
gr.Markdown("### Final Report"); feedback_en_out = gr.Markdown(label="English Feedback", visible=False); feedback_es_out = gr.Markdown(label="Retroalimentaci贸n en Espa帽ol", visible=False)
|
| 161 |
+
history = gr.State([])
|
| 162 |
+
audio_in_chat.stop_recording(fn=chat_interaction, inputs=[audio_in_chat, history], outputs=[chatbot, history, feedback_en_out, feedback_es_out])
|
| 163 |
+
|
| 164 |
+
# --- PESTA脩A 2: EVALUACI脫N POR FRASE ---
|
| 165 |
with gr.TabItem("Evaluaci贸n por Frase"):
|
| 166 |
+
TONGUE_TWISTERS = ["Peter Piper picked a peck of pickled peppers.", "She sells seashells by the seashore.", "How much wood would a woodchuck chuck if a woodchuck could chuck wood?", "Betty Botter bought some butter but she said the butter鈥檚 bitter.", "A proper copper coffee pot."]
|
| 167 |
+
gr.Markdown("Choose a tongue twister or write your own sentence. Record yourself, and our AI examiner will provide a detailed diagnostic report.")
|
| 168 |
+
tongue_twister_selector = gr.Dropdown(choices=TONGUE_TWISTERS, label="Or Choose a Tongue Twister to Practice")
|
| 169 |
+
with gr.Row():
|
| 170 |
+
with gr.Column(scale=1):
|
| 171 |
+
audio_in_sentence = gr.Audio(sources=["microphone"], type="numpy", label="1. Record Your Voice")
|
| 172 |
+
text_in_sentence = gr.Textbox(lines=3, label="2. Reference Sentence", value=TONGUE_TWISTERS[0])
|
| 173 |
+
submit_btn_sentence = gr.Button("Get Assessment", variant="primary")
|
| 174 |
+
with gr.Column(scale=2):
|
| 175 |
+
gr.Markdown("### Assessment Summary")
|
| 176 |
+
with gr.Row():
|
| 177 |
+
score_out_sentence = gr.Number(label="Overall Score (0-100)", interactive=False)
|
| 178 |
+
level_out_sentence = gr.Textbox(label="Estimated CEFR Level", interactive=False)
|
| 179 |
+
holistic_feedback_out_sentence = gr.Markdown(label="Examiner's Feedback")
|
| 180 |
+
gr.Markdown("--- \n ### Detailed Word-by-Word Analysis")
|
| 181 |
+
word_analysis_out_sentence = gr.Markdown(label="Phonetic Breakdown")
|
| 182 |
+
def update_text(choice): return gr.Textbox(value=choice)
|
| 183 |
+
tongue_twister_selector.change(fn=update_text, inputs=tongue_twister_selector, outputs=text_in_sentence)
|
| 184 |
+
submit_btn_sentence.click(fn=run_sentence_evaluation, inputs=[audio_in_sentence, text_in_sentence], outputs=[score_out_sentence, level_out_sentence, holistic_feedback_out_sentence, word_analysis_out_sentence])
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
+
if not api_key_found: print("\nFATAL: OpenAI API key not found. Please set the OPENAI_API_KEY environment variable.")
|
| 188 |
else: demo.launch(debug=True)
|