Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,42 +9,37 @@ import gradio as gr
|
|
| 9 |
import coach_core
|
| 10 |
from coach_core import speech2text, llama_ask_question_and_record_student_answer
|
| 11 |
|
| 12 |
-
# ---
|
| 13 |
STORY_LIBRARY = [
|
| 14 |
("A monkey became friends with a crocodile who lived in a river. "
|
| 15 |
"The crocodile, at his wife's insistence, decided to trick the monkey into giving him his heart. "
|
| 16 |
"The clever monkey tricked the crocodile by saying he left his heart on a tree. "
|
| 17 |
"The crocodile returned to the tree, and the monkey escaped. "
|
| 18 |
"This shows that it is wise to think before you act."),
|
| 19 |
-
|
| 20 |
("A thirsty crow found a pitcher with very little water in it. "
|
| 21 |
"He could not reach the water with his beak. "
|
| 22 |
"He had a clever idea and started dropping pebbles into the pitcher one by one. "
|
| 23 |
"The water level rose up, and the crow drank the water and flew away happily. "
|
| 24 |
"This shows that where there is a will, there is a way."),
|
| 25 |
-
|
| 26 |
("A lion was sleeping when a mouse started playing on him. The lion woke up and caught the mouse. "
|
| 27 |
"The mouse begged for forgiveness and promised to help the lion someday. The lion laughed but let him go. "
|
| 28 |
"Later, hunters trapped the lion in a net. The mouse heard the roar, came back, and cut the net with his teeth. "
|
| 29 |
"This shows that even small friends can be great friends."),
|
| 30 |
-
|
| 31 |
("A hare made fun of a tortoise for being slow. The tortoise challenged the hare to a race. "
|
| 32 |
"The hare ran fast and then fell asleep, thinking he had plenty of time. "
|
| 33 |
"The tortoise kept moving slowly but steadily. "
|
| 34 |
"When the hare woke up, he saw the tortoise crossing the finish line. "
|
| 35 |
"This shows that slow and steady wins the race."),
|
| 36 |
-
|
| 37 |
("An ant fell into a stream and was drowning. A dove saw this and dropped a leaf into the water. "
|
| 38 |
"The ant climbed onto the leaf and was saved. "
|
| 39 |
"Later, a hunter aimed at the dove. The ant bit the hunter's foot, making him miss his shot. "
|
| 40 |
"The dove flew away safely. This shows that one good turn deserves another.")
|
| 41 |
]
|
| 42 |
|
| 43 |
-
# 2) Monkey-
|
| 44 |
_SPOKEN_CHUNKS = []
|
| 45 |
|
| 46 |
def _patched_play_to_student(text, wav_name='amy_said.wav', wav_file_only=False):
|
| 47 |
-
"""Collect text that would have been spoken."""
|
| 48 |
if not text or str(text).strip() == "":
|
| 49 |
return
|
| 50 |
t = re.sub(r"\*[^*]+\*", "", str(text))
|
|
@@ -60,8 +55,7 @@ def _patched_keep_playing():
|
|
| 60 |
coach_core.play_to_student = _patched_play_to_student
|
| 61 |
coach_core.keep_looking_for_audio_and_keep_playing = _patched_keep_playing
|
| 62 |
|
| 63 |
-
# --- Helpers
|
| 64 |
-
|
| 65 |
TARGET_SR = 16000
|
| 66 |
|
| 67 |
def _numpy_to_wav_bytesio(sr_in: int, audio_np: np.ndarray) -> io.BytesIO:
|
|
@@ -69,7 +63,6 @@ def _numpy_to_wav_bytesio(sr_in: int, audio_np: np.ndarray) -> io.BytesIO:
|
|
| 69 |
if x.ndim > 1:
|
| 70 |
x = x.mean(axis=1)
|
| 71 |
x = np.clip(x, -1.0, 1.0)
|
| 72 |
-
|
| 73 |
if sr_in != TARGET_SR:
|
| 74 |
ratio = TARGET_SR / float(sr_in)
|
| 75 |
new_len = int(round(len(x) * ratio))
|
|
@@ -77,9 +70,7 @@ def _numpy_to_wav_bytesio(sr_in: int, audio_np: np.ndarray) -> io.BytesIO:
|
|
| 77 |
t_old = np.linspace(0.0, 1.0, num=len(x), endpoint=False, dtype=np.float32)
|
| 78 |
t_new = np.linspace(0.0, 1.0, num=new_len, endpoint=False, dtype=np.float32)
|
| 79 |
x = np.interp(t_new, t_old, x).astype(np.float32)
|
| 80 |
-
|
| 81 |
pcm16 = (x * 32767.0).astype(np.int16)
|
| 82 |
-
|
| 83 |
buf = io.BytesIO()
|
| 84 |
with wave.open(buf, "wb") as wf:
|
| 85 |
wf.setnchannels(1)
|
|
@@ -90,7 +81,6 @@ def _numpy_to_wav_bytesio(sr_in: int, audio_np: np.ndarray) -> io.BytesIO:
|
|
| 90 |
return buf
|
| 91 |
|
| 92 |
def _get_random_story():
|
| 93 |
-
"""Returns a random string from the library."""
|
| 94 |
return random.choice(STORY_LIBRARY)
|
| 95 |
|
| 96 |
def _start_session(story_text, num_questions):
|
|
@@ -112,15 +102,11 @@ def _start_session(story_text, num_questions):
|
|
| 112 |
}
|
| 113 |
]
|
| 114 |
|
| 115 |
-
llama_input = coach_core.tokenizer.apply_chat_template(
|
| 116 |
-
messages, tokenize=False, add_generation_prompt=True
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
_SPOKEN_CHUNKS.clear()
|
| 120 |
coach_core.llama_ask_question_and_record_student_answer(llama_input, record=False)
|
| 121 |
bot_question = " ".join(_SPOKEN_CHUNKS).strip() or "(No output)"
|
| 122 |
_SPOKEN_CHUNKS.clear()
|
| 123 |
-
|
| 124 |
messages.append({"role": "assistant", "content": bot_question})
|
| 125 |
|
| 126 |
state = {
|
|
@@ -130,11 +116,10 @@ def _start_session(story_text, num_questions):
|
|
| 130 |
}
|
| 131 |
|
| 132 |
display_text = f"(Question 1/{target_q}): {bot_question}"
|
| 133 |
-
|
| 134 |
greeting_text = "Hello Student! I am about to read a short story. Ready? Let's start."
|
| 135 |
-
|
| 136 |
|
| 137 |
-
return display_text, json.dumps(state)
|
| 138 |
|
| 139 |
def _submit_answer(state_json, mic_tuple):
|
| 140 |
if not state_json:
|
|
@@ -158,7 +143,6 @@ def _submit_answer(state_json, mic_tuple):
|
|
| 158 |
max_q = state["num_q"]
|
| 159 |
|
| 160 |
appreciate_only = (current_q >= max_q)
|
| 161 |
-
|
| 162 |
if appreciate_only:
|
| 163 |
user_content = (
|
| 164 |
f"My answer is: {transcript}.\n\n"
|
|
@@ -170,16 +154,11 @@ def _submit_answer(state_json, mic_tuple):
|
|
| 170 |
user_content = transcript
|
| 171 |
|
| 172 |
messages.append({"role": "user", "content": user_content})
|
| 173 |
-
|
| 174 |
-
llama_input = coach_core.tokenizer.apply_chat_template(
|
| 175 |
-
messages, tokenize=False, add_generation_prompt=True
|
| 176 |
-
)
|
| 177 |
-
|
| 178 |
_SPOKEN_CHUNKS.clear()
|
| 179 |
coach_core.llama_ask_question_and_record_student_answer(llama_input, record=False)
|
| 180 |
reply_text = " ".join(_SPOKEN_CHUNKS).strip() or "(No output)"
|
| 181 |
_SPOKEN_CHUNKS.clear()
|
| 182 |
-
|
| 183 |
messages.append({"role": "assistant", "content": reply_text})
|
| 184 |
state["messages"] = messages
|
| 185 |
|
|
@@ -193,12 +172,13 @@ def _submit_answer(state_json, mic_tuple):
|
|
| 193 |
return display_text, reply_text, json.dumps(state), None
|
| 194 |
|
| 195 |
# ----- Browser auto-TTS -----
|
|
|
|
| 196 |
JS_TTS_AUTOSPEAK = r"""
|
| 197 |
function (text) {
|
| 198 |
try {
|
| 199 |
if (!text || !window.speechSynthesis) { return; }
|
| 200 |
const u = new SpeechSynthesisUtterance(text);
|
| 201 |
-
u.rate = 0.
|
| 202 |
u.pitch = 1.0;
|
| 203 |
u.lang = "en-US";
|
| 204 |
const voices = speechSynthesis.getVoices();
|
|
@@ -219,49 +199,42 @@ with gr.Blocks(title="English Coach") as demo:
|
|
| 219 |
gr.Markdown("## ๐ง English Story Coach")
|
| 220 |
|
| 221 |
with gr.Accordion("๐ Story & Settings", open=True):
|
| 222 |
-
|
| 223 |
-
# NEW: Random Story Button
|
| 224 |
rand_btn = gr.Button("๐ฒ Pick Random Story", size="sm")
|
| 225 |
-
|
| 226 |
with gr.Row():
|
| 227 |
-
story = gr.Textbox(
|
| 228 |
-
label="Story",
|
| 229 |
-
value=STORY_LIBRARY[0], # Default to the first story
|
| 230 |
-
lines=4
|
| 231 |
-
)
|
| 232 |
with gr.Row():
|
| 233 |
-
num_q = gr.Slider(
|
| 234 |
-
minimum=1,
|
| 235 |
-
maximum=10,
|
| 236 |
-
value=3,
|
| 237 |
-
step=1,
|
| 238 |
-
label="Number of Questions to Ask"
|
| 239 |
-
)
|
| 240 |
|
| 241 |
state = gr.State()
|
|
|
|
| 242 |
hidden_speech_trigger = gr.Textbox(visible=False)
|
| 243 |
|
| 244 |
start_btn = gr.Button("โถ๏ธ Start Session", variant="primary")
|
|
|
|
|
|
|
| 245 |
bot_display = gr.Textbox(label="Bot Question", interactive=False)
|
| 246 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
mic = gr.Audio(sources=["microphone"], type="numpy", label="Record your answer")
|
| 248 |
submit = gr.Button("Submit Answer")
|
| 249 |
|
| 250 |
# --- Wiring ---
|
| 251 |
-
|
| 252 |
-
# 1. Random Button: Click -> Updates 'story' textbox
|
| 253 |
rand_btn.click(fn=_get_random_story, inputs=None, outputs=story)
|
| 254 |
|
| 255 |
-
#
|
| 256 |
start_btn.click(
|
| 257 |
fn=_start_session,
|
| 258 |
inputs=[story, num_q],
|
| 259 |
-
outputs=[bot_display,
|
| 260 |
).then(
|
| 261 |
fn=None, inputs=hidden_speech_trigger, js=JS_TTS_AUTOSPEAK
|
| 262 |
)
|
| 263 |
|
| 264 |
-
#
|
| 265 |
submit.click(
|
| 266 |
fn=_submit_answer,
|
| 267 |
inputs=[state, mic],
|
|
@@ -269,6 +242,13 @@ with gr.Blocks(title="English Coach") as demo:
|
|
| 269 |
).then(
|
| 270 |
fn=None, inputs=hidden_speech_trigger, js=JS_TTS_AUTOSPEAK
|
| 271 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
if __name__ == "__main__":
|
| 274 |
demo.queue(max_size=32).launch(server_name="0.0.0.0", server_port=7860, share=True)
|
|
|
|
| 9 |
import coach_core
|
| 10 |
from coach_core import speech2text, llama_ask_question_and_record_student_answer
|
| 11 |
|
| 12 |
+
# --- STORY LIBRARY ---
|
| 13 |
STORY_LIBRARY = [
|
| 14 |
("A monkey became friends with a crocodile who lived in a river. "
|
| 15 |
"The crocodile, at his wife's insistence, decided to trick the monkey into giving him his heart. "
|
| 16 |
"The clever monkey tricked the crocodile by saying he left his heart on a tree. "
|
| 17 |
"The crocodile returned to the tree, and the monkey escaped. "
|
| 18 |
"This shows that it is wise to think before you act."),
|
|
|
|
| 19 |
("A thirsty crow found a pitcher with very little water in it. "
|
| 20 |
"He could not reach the water with his beak. "
|
| 21 |
"He had a clever idea and started dropping pebbles into the pitcher one by one. "
|
| 22 |
"The water level rose up, and the crow drank the water and flew away happily. "
|
| 23 |
"This shows that where there is a will, there is a way."),
|
|
|
|
| 24 |
("A lion was sleeping when a mouse started playing on him. The lion woke up and caught the mouse. "
|
| 25 |
"The mouse begged for forgiveness and promised to help the lion someday. The lion laughed but let him go. "
|
| 26 |
"Later, hunters trapped the lion in a net. The mouse heard the roar, came back, and cut the net with his teeth. "
|
| 27 |
"This shows that even small friends can be great friends."),
|
|
|
|
| 28 |
("A hare made fun of a tortoise for being slow. The tortoise challenged the hare to a race. "
|
| 29 |
"The hare ran fast and then fell asleep, thinking he had plenty of time. "
|
| 30 |
"The tortoise kept moving slowly but steadily. "
|
| 31 |
"When the hare woke up, he saw the tortoise crossing the finish line. "
|
| 32 |
"This shows that slow and steady wins the race."),
|
|
|
|
| 33 |
("An ant fell into a stream and was drowning. A dove saw this and dropped a leaf into the water. "
|
| 34 |
"The ant climbed onto the leaf and was saved. "
|
| 35 |
"Later, a hunter aimed at the dove. The ant bit the hunter's foot, making him miss his shot. "
|
| 36 |
"The dove flew away safely. This shows that one good turn deserves another.")
|
| 37 |
]
|
| 38 |
|
| 39 |
+
# 2) Monkey-patching
|
| 40 |
_SPOKEN_CHUNKS = []
|
| 41 |
|
| 42 |
def _patched_play_to_student(text, wav_name='amy_said.wav', wav_file_only=False):
|
|
|
|
| 43 |
if not text or str(text).strip() == "":
|
| 44 |
return
|
| 45 |
t = re.sub(r"\*[^*]+\*", "", str(text))
|
|
|
|
| 55 |
coach_core.play_to_student = _patched_play_to_student
|
| 56 |
coach_core.keep_looking_for_audio_and_keep_playing = _patched_keep_playing
|
| 57 |
|
| 58 |
+
# --- Helpers ---
|
|
|
|
| 59 |
TARGET_SR = 16000
|
| 60 |
|
| 61 |
def _numpy_to_wav_bytesio(sr_in: int, audio_np: np.ndarray) -> io.BytesIO:
|
|
|
|
| 63 |
if x.ndim > 1:
|
| 64 |
x = x.mean(axis=1)
|
| 65 |
x = np.clip(x, -1.0, 1.0)
|
|
|
|
| 66 |
if sr_in != TARGET_SR:
|
| 67 |
ratio = TARGET_SR / float(sr_in)
|
| 68 |
new_len = int(round(len(x) * ratio))
|
|
|
|
| 70 |
t_old = np.linspace(0.0, 1.0, num=len(x), endpoint=False, dtype=np.float32)
|
| 71 |
t_new = np.linspace(0.0, 1.0, num=new_len, endpoint=False, dtype=np.float32)
|
| 72 |
x = np.interp(t_new, t_old, x).astype(np.float32)
|
|
|
|
| 73 |
pcm16 = (x * 32767.0).astype(np.int16)
|
|
|
|
| 74 |
buf = io.BytesIO()
|
| 75 |
with wave.open(buf, "wb") as wf:
|
| 76 |
wf.setnchannels(1)
|
|
|
|
| 81 |
return buf
|
| 82 |
|
| 83 |
def _get_random_story():
|
|
|
|
| 84 |
return random.choice(STORY_LIBRARY)
|
| 85 |
|
| 86 |
def _start_session(story_text, num_questions):
|
|
|
|
| 102 |
}
|
| 103 |
]
|
| 104 |
|
| 105 |
+
llama_input = coach_core.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
|
|
|
|
|
|
|
|
| 106 |
_SPOKEN_CHUNKS.clear()
|
| 107 |
coach_core.llama_ask_question_and_record_student_answer(llama_input, record=False)
|
| 108 |
bot_question = " ".join(_SPOKEN_CHUNKS).strip() or "(No output)"
|
| 109 |
_SPOKEN_CHUNKS.clear()
|
|
|
|
| 110 |
messages.append({"role": "assistant", "content": bot_question})
|
| 111 |
|
| 112 |
state = {
|
|
|
|
| 116 |
}
|
| 117 |
|
| 118 |
display_text = f"(Question 1/{target_q}): {bot_question}"
|
|
|
|
| 119 |
greeting_text = "Hello Student! I am about to read a short story. Ready? Let's start."
|
| 120 |
+
full_speech_text = greeting_text + ". " + story_text + ". " + bot_question
|
| 121 |
|
| 122 |
+
return display_text, full_speech_text, json.dumps(state)
|
| 123 |
|
| 124 |
def _submit_answer(state_json, mic_tuple):
|
| 125 |
if not state_json:
|
|
|
|
| 143 |
max_q = state["num_q"]
|
| 144 |
|
| 145 |
appreciate_only = (current_q >= max_q)
|
|
|
|
| 146 |
if appreciate_only:
|
| 147 |
user_content = (
|
| 148 |
f"My answer is: {transcript}.\n\n"
|
|
|
|
| 154 |
user_content = transcript
|
| 155 |
|
| 156 |
messages.append({"role": "user", "content": user_content})
|
| 157 |
+
llama_input = coach_core.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
_SPOKEN_CHUNKS.clear()
|
| 159 |
coach_core.llama_ask_question_and_record_student_answer(llama_input, record=False)
|
| 160 |
reply_text = " ".join(_SPOKEN_CHUNKS).strip() or "(No output)"
|
| 161 |
_SPOKEN_CHUNKS.clear()
|
|
|
|
| 162 |
messages.append({"role": "assistant", "content": reply_text})
|
| 163 |
state["messages"] = messages
|
| 164 |
|
|
|
|
| 172 |
return display_text, reply_text, json.dumps(state), None
|
| 173 |
|
| 174 |
# ----- Browser auto-TTS -----
|
| 175 |
+
# UPDATED: Rate is set to 0.7 (Slow/Clear)
|
| 176 |
JS_TTS_AUTOSPEAK = r"""
|
| 177 |
function (text) {
|
| 178 |
try {
|
| 179 |
if (!text || !window.speechSynthesis) { return; }
|
| 180 |
const u = new SpeechSynthesisUtterance(text);
|
| 181 |
+
u.rate = 0.7;
|
| 182 |
u.pitch = 1.0;
|
| 183 |
u.lang = "en-US";
|
| 184 |
const voices = speechSynthesis.getVoices();
|
|
|
|
| 199 |
gr.Markdown("## ๐ง English Story Coach")
|
| 200 |
|
| 201 |
with gr.Accordion("๐ Story & Settings", open=True):
|
|
|
|
|
|
|
| 202 |
rand_btn = gr.Button("๐ฒ Pick Random Story", size="sm")
|
|
|
|
| 203 |
with gr.Row():
|
| 204 |
+
story = gr.Textbox(label="Story", value=STORY_LIBRARY[0], lines=4)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
with gr.Row():
|
| 206 |
+
num_q = gr.Slider(1, 10, value=3, step=1, label="Number of Questions")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
state = gr.State()
|
| 209 |
+
# This Hidden text box holds the clean text that the browser reads
|
| 210 |
hidden_speech_trigger = gr.Textbox(visible=False)
|
| 211 |
|
| 212 |
start_btn = gr.Button("โถ๏ธ Start Session", variant="primary")
|
| 213 |
+
|
| 214 |
+
# Visual Output
|
| 215 |
bot_display = gr.Textbox(label="Bot Question", interactive=False)
|
| 216 |
|
| 217 |
+
# REPLAY BUTTON
|
| 218 |
+
replay_btn = gr.Button("๐ Replay Teacher's Voice", size="sm")
|
| 219 |
+
|
| 220 |
+
# Input
|
| 221 |
mic = gr.Audio(sources=["microphone"], type="numpy", label="Record your answer")
|
| 222 |
submit = gr.Button("Submit Answer")
|
| 223 |
|
| 224 |
# --- Wiring ---
|
| 225 |
+
|
|
|
|
| 226 |
rand_btn.click(fn=_get_random_story, inputs=None, outputs=story)
|
| 227 |
|
| 228 |
+
# Start Session: Updates Text & Trigger Speech
|
| 229 |
start_btn.click(
|
| 230 |
fn=_start_session,
|
| 231 |
inputs=[story, num_q],
|
| 232 |
+
outputs=[bot_display, hidden_speech_trigger, state]
|
| 233 |
).then(
|
| 234 |
fn=None, inputs=hidden_speech_trigger, js=JS_TTS_AUTOSPEAK
|
| 235 |
)
|
| 236 |
|
| 237 |
+
# Submit Answer: Updates Text & Trigger Speech
|
| 238 |
submit.click(
|
| 239 |
fn=_submit_answer,
|
| 240 |
inputs=[state, mic],
|
|
|
|
| 242 |
).then(
|
| 243 |
fn=None, inputs=hidden_speech_trigger, js=JS_TTS_AUTOSPEAK
|
| 244 |
)
|
| 245 |
+
|
| 246 |
+
# Replay Button: Just re-triggers the JS on the *existing* hidden text
|
| 247 |
+
replay_btn.click(
|
| 248 |
+
fn=None,
|
| 249 |
+
inputs=hidden_speech_trigger,
|
| 250 |
+
js=JS_TTS_AUTOSPEAK
|
| 251 |
+
)
|
| 252 |
|
| 253 |
if __name__ == "__main__":
|
| 254 |
demo.queue(max_size=32).launch(server_name="0.0.0.0", server_port=7860, share=True)
|