|
import gradio as gr |
|
import matplotlib.pyplot as plt |
|
import numpy as np |
|
|
|
|
|
motor_text = """ |
|
## How an Electric Motor Runs |
|
|
|
An electric motor converts electrical energy into mechanical energy using **electromagnetism**. |
|
|
|
**Key parts:** |
|
- **Rotor** β The rotating part. |
|
- **Stator** β The stationary part with magnets or coils. |
|
- **Commutator & Brushes** β Switch current direction to keep the rotor spinning. |
|
|
|
**Basic principle:** |
|
When current flows through a coil in a magnetic field, a force (Lorentz force) acts on it, making it rotate. Changing current direction at the right time keeps it spinning. |
|
""" |
|
|
|
|
|
def draw_motor(angle): |
|
fig, ax = plt.subplots(figsize=(4,4)) |
|
ax.set_xlim(-1.5, 1.5) |
|
ax.set_ylim(-1.5, 1.5) |
|
ax.set_aspect('equal') |
|
ax.axis('off') |
|
|
|
|
|
for y in np.linspace(-1, 1, 5): |
|
ax.arrow(-1.4, y, 2.8, 0, head_width=0.05, color='blue') |
|
|
|
|
|
coil_x = [0.5*np.cos(angle), -0.5*np.cos(angle)] |
|
coil_y = [0.5*np.sin(angle), -0.5*np.sin(angle)] |
|
ax.plot(coil_x, coil_y, color='red', linewidth=3) |
|
|
|
|
|
circle = plt.Circle((0,0), 0.6, fill=False, color='black', linewidth=1.5) |
|
ax.add_artist(circle) |
|
|
|
|
|
ax.arrow(coil_x[0], coil_y[0], 0.2*np.sin(angle), -0.2*np.cos(angle), color='green', width=0.01) |
|
ax.arrow(coil_x[1], coil_y[1], -0.2*np.sin(angle), 0.2*np.cos(angle), color='green', width=0.01) |
|
|
|
plt.close(fig) |
|
return fig |
|
|
|
|
|
quiz_questions = [ |
|
("What part of a motor rotates?", ["Stator", "Rotor", "Magnet", "Brushes"], "Rotor"), |
|
("What converts electrical to mechanical energy?", ["Generator", "Motor", "Battery", "Switch"], "Motor"), |
|
("What keeps the motor spinning in the same direction?", ["Magnets", "Switch", "Commutator", "Resistor"], "Commutator") |
|
] |
|
|
|
def quiz(q_idx, answer): |
|
question, options, correct = quiz_questions[q_idx] |
|
if answer == correct: |
|
return "β
Correct!" |
|
else: |
|
return f"β Incorrect. Correct answer: {correct}" |
|
|
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown("# Spin It! β How an Electric Motor Runs") |
|
|
|
with gr.Tab("Learn"): |
|
gr.Markdown(motor_text) |
|
angle_slider = gr.Slider(0, 2*np.pi, value=0, step=0.1, label="Rotor Angle") |
|
image_output = gr.Plot() |
|
angle_slider.change(lambda a: draw_motor(a), inputs=angle_slider, outputs=image_output) |
|
draw_motor(0) |
|
|
|
with gr.Tab("Test Yourself"): |
|
q_idx = gr.Number(value=0, label="Question Number (0-2)", precision=0) |
|
answer_choice = gr.Radio(["Stator", "Rotor", "Magnet", "Brushes"], label="Select your answer") |
|
quiz_btn = gr.Button("Submit Answer") |
|
quiz_output = gr.Textbox(label="Result") |
|
quiz_btn.click(quiz, inputs=[q_idx, answer_choice], outputs=quiz_output) |
|
|
|
demo.launch() |
|
|