Spaces:
Sleeping
Sleeping
Download app.py from trindqb/learning_with_kiwi: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/trindqb/learning_with_kiwi/resolve/main/app.py
- Command line
-
hf download hf://spaces/trindqb/learning_with_kiwi/app.py
-
curl -L -o app.py https://huggingface.co/spaces/trindqb/learning_with_kiwi/resolve/main/app.py
11.4 kB
| import gradio as gr | |
| import json | |
| import os | |
| import random | |
| # --- 1. Setup & Data Loading --- | |
| JSON_FILE = 'stories.json' | |
| def load_stories(): | |
| if not os.path.exists(JSON_FILE): | |
| print(f"β Error: {JSON_FILE} not found.") | |
| return [] | |
| with open(JSON_FILE, 'r', encoding='utf-8') as f: | |
| data = json.load(f) | |
| return data.get("stories", []) | |
| stories = load_stories() | |
| if not stories: | |
| story_titles = ["No stories found"] | |
| else: | |
| story_titles = [s['title'] for s in stories] | |
| # --- 2. Styling Templates (HTML/CSS) --- | |
| STORY_CARD_TEMPLATE = """ | |
| <div style=' | |
| background-color: #ffffff; | |
| padding: 30px; | |
| border-radius: 25px; | |
| border: 3px solid #bae6fd; | |
| box-shadow: 0 4px 6px rgba(0,0,0,0.05); | |
| font-family: "Comic Sans MS", cursive, sans-serif; | |
| font-size: 22px; | |
| line-height: 1.6; | |
| color: #334155; | |
| text-align: left; | |
| '> | |
| {content} | |
| </div> | |
| """ | |
| VOCAB_BADGE_STYLE = """ | |
| <span style=' | |
| background-color: #e0f2fe; | |
| color: #0284c7; | |
| padding: 6px 12px; | |
| margin: 4px; | |
| border-radius: 15px; | |
| font-weight: bold; | |
| font-size: 16px; | |
| display: inline-block; | |
| border: 2px solid #7dd3fc; | |
| '> | |
| {word} | |
| </span> | |
| """ | |
| SCRAMBLE_WORD_STYLE = """ | |
| <span style=' | |
| background-color: #fef3c7; | |
| color: #d97706; | |
| padding: 8px 12px; | |
| margin: 4px; | |
| border-radius: 10px; | |
| font-weight: bold; | |
| font-size: 18px; | |
| display: inline-block; | |
| border: 2px dashed #f59e0b; | |
| '> | |
| {word} | |
| </span> | |
| """ | |
| # --- 3. Logic Functions --- | |
| def get_scramble_options(correct_sentence): | |
| """Generates 3 options for the scramble game: 1 correct, 2 shuffled incorrect.""" | |
| if not correct_sentence: | |
| return [] | |
| words = correct_sentence.split() | |
| options = [correct_sentence] | |
| # Generate 2 incorrect variations | |
| for _ in range(2): | |
| shuffled = words[:] | |
| random.shuffle(shuffled) | |
| # Ensure it's not accidentally correct | |
| count = 0 | |
| while shuffled == words and count < 5: | |
| random.shuffle(shuffled) | |
| count += 1 | |
| options.append(" ".join(shuffled)) | |
| # Shuffle the position of the correct answer | |
| random.shuffle(options) | |
| return options | |
| def parse_story_data(story): | |
| """Extracts MCQs and Scramble data regardless of JSON format (Old 'quiz' dict vs New 'questions' list).""" | |
| mcqs = [] | |
| scramble = None | |
| # Case A: New Format (List of questions) | |
| if 'questions' in story: | |
| for q in story['questions']: | |
| if q.get('type') == 'mcq': | |
| mcqs.append(q) | |
| elif q.get('type') == 'scramble': | |
| scramble = q | |
| # Case B: Old Format (Single 'quiz' dict) | |
| elif 'quiz' in story: | |
| if 'mcq' in story['quiz']: | |
| mcqs.append(story['quiz']['mcq']) | |
| if 'scramble' in story['quiz']: | |
| scramble = story['quiz']['scramble'] | |
| return mcqs, scramble | |
| def update_story_content(selected_title): | |
| if not stories: | |
| # Return empty states for everything | |
| return ( | |
| "No Data", None, "", | |
| *[gr.update(visible=False)]*12, # Hide all MCQs | |
| gr.update(visible=False), "", "", [], "" # Hide Scramble | |
| ) | |
| # Find the story object | |
| story = next((s for s in stories if s['title'] == selected_title), stories[0]) | |
| # 1. Story Content | |
| styled_content = STORY_CARD_TEMPLATE.format(content=story['content']) | |
| # 2. Audio | |
| audio_path = f"audio/story_{story['id']}.mp3" | |
| if not os.path.exists(audio_path): | |
| audio_path = None | |
| # 3. Vocabulary | |
| vocab_html = '<div style="text-align: center; margin-top: 5px;">' | |
| for word in story.get('vocabulary', []): | |
| vocab_html += VOCAB_BADGE_STYLE.format(word=word) | |
| vocab_html += '</div>' | |
| # 4. Parse Quiz Data | |
| mcqs, scramble_data = parse_story_data(story) | |
| # --- Prepare MCQ Outputs (Max 3 slots) --- | |
| mcq_outputs = [] | |
| # We have 3 slots in UI. Fill them with data or hide them. | |
| for i in range(3): | |
| if i < len(mcqs): | |
| q_data = mcqs[i] | |
| # Question Text | |
| mcq_outputs.append(gr.update(visible=True, value=f"**Q{i+1}:** {q_data['question']}")) | |
| # Radio Options | |
| mcq_outputs.append(gr.update(visible=True, choices=q_data['options'], value=None)) | |
| # Feedback text (reset) | |
| mcq_outputs.append(gr.update(visible=True, value="")) | |
| # Correct Answer (Stored in State) | |
| mcq_outputs.append(q_data['correct_answer']) | |
| else: | |
| # Hide unused slots | |
| mcq_outputs.append(gr.update(visible=False)) # Markdown | |
| mcq_outputs.append(gr.update(visible=False)) # Radio | |
| mcq_outputs.append(gr.update(visible=False)) # Feedback | |
| mcq_outputs.append(None) # State | |
| # --- Prepare Scramble Outputs --- | |
| if scramble_data: | |
| correct_sentence = scramble_data.get('original_sentence', "") | |
| shuffled_words = scramble_data.get('shuffled_words', []) | |
| # HTML Badges | |
| scramble_html = '<div style="text-align: center; margin: 10px;">' | |
| for w in shuffled_words: | |
| scramble_html += SCRAMBLE_WORD_STYLE.format(word=w) | |
| scramble_html += '</div>' | |
| scramble_opts = get_scramble_options(correct_sentence) | |
| scramble_outputs = [ | |
| gr.update(visible=True, value=scramble_html), # Display | |
| correct_sentence, # State | |
| gr.update(choices=scramble_opts, value=None), # Radio | |
| "" # Feedback | |
| ] | |
| else: | |
| scramble_outputs = [ | |
| gr.update(visible=False), None, gr.update(choices=[], value=None), "" | |
| ] | |
| # Return everything flattened | |
| return (styled_content, audio_path, vocab_html, *mcq_outputs, *scramble_outputs) | |
| # --- Check Functions --- | |
| def check_answer(user_choice, correct_answer): | |
| if not user_choice: | |
| return "β οΈ Choose an answer first!" | |
| if user_choice == correct_answer: | |
| return "β Correct! Good job! π" | |
| else: | |
| return "β Oops! Try again. πͺ" | |
| def next_story(current_title): | |
| try: | |
| curr_idx = story_titles.index(current_title) | |
| next_idx = (curr_idx + 1) % len(story_titles) | |
| return story_titles[next_idx] | |
| except: | |
| return story_titles[0] | |
| def prev_story(current_title): | |
| try: | |
| curr_idx = story_titles.index(current_title) | |
| prev_idx = (curr_idx - 1) % len(story_titles) | |
| return story_titles[prev_idx] | |
| except: | |
| return story_titles[0] | |
| # --- 4. Build UI --- | |
| kid_theme = gr.themes.Soft(primary_hue="sky", secondary_hue="teal").set( | |
| body_background_fill="#f0f9ff" | |
| ) | |
| with gr.Blocks(theme=kid_theme, title="Learning English With Kiwi π") as demo: | |
| gr.Markdown("# π π§ Learning English With Kiwi", elem_classes=["text-center"]) | |
| with gr.Row(): | |
| # --- Left Column: Navigation & Quiz --- | |
| with gr.Column(scale=1): | |
| # Navigation | |
| dropdown = gr.Dropdown(choices=story_titles, value=story_titles[0] if story_titles else None, label="Choose a Story", interactive=True) | |
| with gr.Row(): | |
| btn_prev = gr.Button("β¬ οΈ Prev", variant="secondary") | |
| btn_next = gr.Button("Next β‘οΈ", variant="primary") | |
| gr.Markdown("### π§© Quiz Corner") | |
| with gr.Tabs(): | |
| # --- Tab 1: Multiple Choice (Supports up to 3 questions) --- | |
| with gr.TabItem("β Questions"): | |
| # Question 1 Block | |
| with gr.Group(): | |
| q1_text = gr.Markdown(visible=False) | |
| q1_opts = gr.Radio(choices=[], label="Select Answer", visible=False) | |
| q1_ans = gr.State() # Store correct answer | |
| q1_feed = gr.Markdown(visible=False) | |
| q1_btn = gr.Button("Check Q1", size="sm", visible=True) | |
| q1_btn.click(fn=check_answer, inputs=[q1_opts, q1_ans], outputs=[q1_feed]) | |
| gr.HTML("<hr style='margin: 10px 0; opacity: 0.3;'>") | |
| # Question 2 Block | |
| with gr.Group(): | |
| q2_text = gr.Markdown(visible=False) | |
| q2_opts = gr.Radio(choices=[], show_label=False, visible=False) | |
| q2_ans = gr.State() | |
| q2_feed = gr.Markdown(visible=False) | |
| q2_btn = gr.Button("Check Q2", size="sm", visible=True) | |
| q2_btn.click(fn=check_answer, inputs=[q2_opts, q2_ans], outputs=[q2_feed]) | |
| gr.HTML("<hr style='margin: 10px 0; opacity: 0.3;'>") | |
| # Question 3 Block | |
| with gr.Group(): | |
| q3_text = gr.Markdown(visible=False) | |
| q3_opts = gr.Radio(choices=[], show_label=False, visible=False) | |
| q3_ans = gr.State() | |
| q3_feed = gr.Markdown(visible=False) | |
| q3_btn = gr.Button("Check Q3", size="sm", visible=True) | |
| q3_btn.click(fn=check_answer, inputs=[q3_opts, q3_ans], outputs=[q3_feed]) | |
| # --- Tab 2: Scramble --- | |
| with gr.TabItem("π€ Unscramble"): | |
| gr.Markdown("Put the words in the correct order:") | |
| scramble_display = gr.HTML(visible=False) | |
| scramble_ans = gr.State() # Store correct sentence | |
| scramble_opts = gr.Radio(label="Which sentence is correct?", choices=[]) | |
| scramble_feed = gr.Markdown("") | |
| btn_check_scramble = gr.Button("Check Sentence", variant="primary") | |
| btn_check_scramble.click(fn=check_answer, inputs=[scramble_opts, scramble_ans], outputs=[scramble_feed]) | |
| # --- Right Column: Story Content --- | |
| with gr.Column(scale=2): | |
| audio_player = gr.Audio(label="Listen along!", autoplay=True, type="filepath") | |
| story_display = gr.HTML() | |
| gr.Markdown("### π Key Words", elem_classes=["text-center"]) | |
| vocab_display = gr.HTML() | |
| # --- Interaction Logic --- | |
| # Group all outputs to keep the change function clean | |
| # Output Order: | |
| # [Story, Audio, Vocab] | |
| # [Q1_Txt, Q1_Opt, Q1_Feed, Q1_State] | |
| # [Q2_Txt, Q2_Opt, Q2_Feed, Q2_State] | |
| # [Q3_Txt, Q3_Opt, Q3_Feed, Q3_State] | |
| # [Scramble_Disp, Scramble_State, Scramble_Opt, Scramble_Feed] | |
| all_outputs = [ | |
| story_display, audio_player, vocab_display, | |
| q1_text, q1_opts, q1_feed, q1_ans, | |
| q2_text, q2_opts, q2_feed, q2_ans, | |
| q3_text, q3_opts, q3_feed, q3_ans, | |
| scramble_display, scramble_ans, scramble_opts, scramble_feed | |
| ] | |
| dropdown.change(fn=update_story_content, inputs=[dropdown], outputs=all_outputs) | |
| btn_prev.click(fn=prev_story, inputs=[dropdown], outputs=[dropdown]) | |
| btn_next.click(fn=next_story, inputs=[dropdown], outputs=[dropdown]) | |
| # Initialize | |
| demo.load(fn=update_story_content, inputs=[dropdown], outputs=all_outputs) | |
| if __name__ == "__main__": | |
| demo.launch() |