VIATEUR-AI commited on
Commit
528bf4b
·
verified ·
1 Parent(s): 5245a46

import gradio as gr import random import time from threading import Timer # ---------------- Dictionary y'ibibazo n'ibisubizo ---------------- ibisubizo_dict = { "Icyapa cya STOP gisobanura iki?": ("Ugomba guhagarara neza mbere yo gukomeza, urebe ko umuhanda utekanye.", "Icyapa cya STOP gituma umugenzi amenya guhagarara ngo hamenyekane umutekano w'umuhanda."), "Umuvuduko ntarengwa mu mujyi ni uwuhe?": ("Ni 40 km/h mu mijyi.", "Umuvuduko ntarengwa ugamije kugabanya impanuka mu mijyi."), "Icyapa cya Attention École gisobanura iki?": ("Kigaragaza ko hafi yaho hari ishuri, ugomba kugabanya umuvuduko no kwitonda.", "Iki cyapa cyerekana ahari ishuri cyangwa abana bari hafi y'umuhanda."), # Shyiramo ibindi bibazo byose... } # ---------------- Add more questions dynamically ---------------- for i in range(4, 21): question = f"Icyapa cyangwa amategeko y'umuhanda #{i}" answer = f"Igisubizo cy'ikibazo #{i} ku mategeko y'umuhanda." explanation = f"Impamvu y'ikibazo #{i} ku mategeko y'umuhanda." ibisubizo_dict[question] = (answer, explanation) ibibazo_bya_quiz = list(ibisubizo_dict.items()) # ---------------- Functions ---------------- def gutegura_quiz(batch_size=5): quiz = random.sample(ibibazo_bya_quiz, min(batch_size, len(ibibazo_bya_quiz))) quiz_questions = [] quiz_choices = [] for q, (ans, expl) in quiz: other_answers = list(set(a for a, _ in ibisubizo_dict.values()) - {ans}) choices = random.sample(other_answers, min(2, len(other_answers))) + [ans] random.shuffle(choices) quiz_questions.append(q) quiz_choices.append(choices) return quiz_questions, quiz_choices def check_answer(answer, question, scores_list): if not question: return "", scores_list, "0", "0/0" correct, expl = ibisubizo_dict.get(question, ("", "")) score = 4 if answer == correct else 0 scores_list.append(score) total_score = sum(scores_list) question_score_text = f"🏅 Amanota kuri iki kibazo: {score}/4\n💡 Explanation: {expl}" total_score_text = f"🏆 Amanota yose kugeza ubu: {total_score}/{len(scores_list)*4}" return question_score_text, scores_list, str(score), total_score_text def start_quiz(): questions, choices = gutegura_quiz() updates = [] for i, r in enumerate(radio_widgets): if i < len(questions): updates.append(gr.update(choices=choices[i], label=questions[i], visible=True, value=None)) else: updates.append(gr.update(visible=False)) for inst, t in zip(instant_outputs, timer_boxes): updates.append(gr.update(visible=False, value="")) updates.append(gr.update(visible=True, value="⏱️ 20s left")) return questions, choices, *updates, [], "0/0" def reset_quiz(): updates = [] for r, inst, t in zip(radio_widgets, instant_outputs, timer_boxes): updates.append(gr.update(visible=False, value=None)) updates.append(gr.update(value="")) updates.append(gr.update(value="⏱️ 20s left")) return [], [], [], "0/0", *updates # ---------------- Gradio Interface ---------------- with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="yellow")) as demo: gr.Markdown("# 🚗 AI y’Amategeko y’Umuhanda 🇷🇼\n### *Yakozwe na Viateur Irasubiza*") quiz_button = gr.Button("Tangira Quiz") reset_button = gr.Button("🔄 Reset Quiz") quiz_score = gr.Textbox(label="🏆 Amanota yose kugeza ubu", value="0/0", interactive=False) scores_list_state = gr.State([]) radio_widgets = [] instant_outputs = [] timer_boxes = [] for i in range(5): r = gr.Radio(choices=[], label=f"Ikibazo {i+1}", visible=False) radio_widgets.append(r) inst = gr.Markdown("", visible=False) instant_outputs.append(inst) timer_box = gr.Markdown("⏱️ 20s left", visible=False) timer_boxes.append(timer_box) quiz_questions_state = gr.State() quiz_choices_state = gr.State() # Buttons logic quiz_button.click(fn=start_quiz, inputs=[], outputs=[quiz_questions_state, quiz_choices_state] + [val for pair in zip(radio_widgets, instant_outputs) for val in pair] + timer_boxes + [scores_list_state, quiz_score]) reset_button.click(fn=reset_quiz, inputs=[], outputs=[quiz_questions_state, quiz_choices_state, scores_list_state, quiz_score] + [val for pair in zip(radio_widgets, instant_outputs) for val in pair] + timer_boxes) # Answer checking for r, inst, timer in zip(radio_widgets, instant_outputs, timer_boxes): r.change(fn=check_answer, inputs=[r, r.label, scores_list_state], outputs=[inst, scores_list_state, r, quiz_score]) # Footer gr.Markdown("© 2025 Viateur Irasubiza. Uburenganzira bwose burabitswe.\n\nAI yakozwe kugirango ifashe Abanyarwanda kwiga amategeko y'umuhanda.") demo.launch()

Browse files
Files changed (1) hide show
  1. app.py +69 -111
app.py CHANGED
@@ -1,42 +1,31 @@
1
  import gradio as gr
2
  import random
3
  import time
4
- import threading
5
 
6
  # ---------------- Dictionary y'ibibazo n'ibisubizo ----------------
7
  ibisubizo_dict = {
8
- "Icyapa cya STOP gisobanura iki?": (
9
- "Ugomba guhagarara neza mbere yo gukomeza, urebe ko umuhanda utekanye.",
10
- "Icyapa cya STOP gituma umugenzi amenya guhagarara ngo hamenyekane umutekano w'umuhanda."
11
- ),
12
- "Umuvuduko ntarengwa mu mujyi ni uwuhe?": (
13
- "Ni 40 km/h mu mijyi.",
14
- "Umuvuduko ntarengwa ugamije kugabanya impanuka mu mijyi, cyane cyane hafi y'ahantu hateraniye abantu."
15
- ),
16
- "Icyapa cya Attention École gisobanura iki?": (
17
- "Kigaragaza ko hafi yaho hari ishuri, ugomba kugabanya umuvuduko no kwitonda.",
18
- "Iki cyapa cyerekana ahari ishuri cyangwa abana bari hafi y'umuhanda."
19
- ),
20
- "Iyo umwana ari ku muhanda, ukora iki?": (
21
- "Ugabanya umuvuduko kandi ube maso cyane.",
22
- "Umwana ashobora guhita yinjira mu muhanda nta kwitegereza, ugomba kwitonda cyane."
23
- ),
24
- "Iyo ugiye guca ku bandi, ukora iki?": (
25
- "Ureba neza niba umuhanda ubibemerera kandi nta modoka iza imbere.",
26
- "Kureba mbere yo guca ku bandi birinda impanuka."
27
- ),
28
  }
29
 
30
- # ---------------- Functions ----------------
31
- def gusubiza(ikibazo):
32
- ans, expl = ibisubizo_dict.get(ikibazo, ("Nta bisubizo bihari kuri icyo kibazo.", "Nta explanation."))
33
- return ans + "\n\n💡 Explanation: " + expl
 
 
 
 
34
 
 
35
  def gutegura_quiz(batch_size=5):
36
- quiz = random.sample(list(ibisubizo_dict.items()), min(batch_size, len(ibisubizo_dict)))
37
  quiz_questions = []
38
  quiz_choices = []
39
- for q, (ans, _) in quiz:
40
  other_answers = list(set(a for a, _ in ibisubizo_dict.values()) - {ans})
41
  choices = random.sample(other_answers, min(2, len(other_answers))) + [ans]
42
  random.shuffle(choices)
@@ -44,105 +33,74 @@ def gutegura_quiz(batch_size=5):
44
  quiz_choices.append(choices)
45
  return quiz_questions, quiz_choices
46
 
47
- # ---------------- Timer Function ----------------
48
- def start_timer(timer_box, duration=20):
49
- def countdown():
50
- for i in range(duration, -1, -1):
51
- timer_box.update(value=f"⏱️ {i} seconds left", visible=True)
52
- time.sleep(1)
53
- thread = threading.Thread(target=countdown, daemon=True)
54
- thread.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  # ---------------- Gradio Interface ----------------
57
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="yellow")) as demo:
58
-
59
  gr.Markdown("# 🚗 AI y’Amategeko y’Umuhanda 🇷🇼\n### *Yakozwe na Viateur Irasubiza*")
60
-
61
- # --- Igice cyo gusaba igisubizo ---
62
- with gr.Row():
63
- with gr.Column(scale=1):
64
- ikibazo = gr.Dropdown(choices=list(ibisubizo_dict.keys()), label="➡️ Hitamo ikibazo", value=list(ibisubizo_dict.keys())[0])
65
- kanda = gr.Button("🔍 Saba igisubizo")
66
- with gr.Column(scale=1):
67
- igisubizo = gr.Textbox(label="🧠 Igisubizo", lines=6)
68
- kanda.click(fn=gusubiza, inputs=ikibazo, outputs=igisubizo)
69
-
70
- # --- Quiz Section ---
71
- gr.Markdown("## 📝 Quiz: Amanota ako kanya ku kibazo kimwe ku gihe")
72
  quiz_button = gr.Button("Tangira Quiz")
73
  reset_button = gr.Button("🔄 Reset Quiz")
74
- quiz_score = gr.Textbox(label="🏆 Amanota yose", value="0/20", interactive=False)
75
- current_score = gr.State(0)
76
- quiz_questions_state = gr.State()
77
- quiz_choices_state = gr.State()
78
- current_question_state = gr.State("")
79
-
80
  radio_widgets = []
81
  instant_outputs = []
82
  timer_boxes = []
83
-
84
  for i in range(5):
85
  r = gr.Radio(choices=[], label=f"Ikibazo {i+1}", visible=False)
86
  radio_widgets.append(r)
87
  inst = gr.Markdown("", visible=False)
88
  instant_outputs.append(inst)
89
- timer_box = gr.Markdown("", visible=False)
90
  timer_boxes.append(timer_box)
91
-
92
- # --- Start Quiz ---
93
- def start_quiz():
94
- questions, choices = gutegura_quiz()
95
- updates = []
96
- for i, r in enumerate(radio_widgets):
97
- if i < len(questions):
98
- updates.append(gr.update(choices=choices[i], label=questions[i], visible=True, value=None))
99
- else:
100
- updates.append(gr.update(visible=False))
101
- for inst in instant_outputs:
102
- updates.append(gr.update(value="", visible=False))
103
- for timer_box in timer_boxes:
104
- updates.append(gr.update(value="", visible=False))
105
- # Start timer for first question
106
- start_timer(timer_boxes[0])
107
- return questions, choices, *updates, 0, "0/20", questions[0]
108
-
109
- quiz_button.click(
110
- fn=start_quiz,
111
- inputs=[],
112
- outputs=[quiz_questions_state, quiz_choices_state] + radio_widgets + instant_outputs + timer_boxes + [current_score, quiz_score, current_question_state]
113
- )
114
-
115
- # --- Check Answer ---
116
- def check_answer(answer, question, score):
117
- if not question:
118
- return "", score, f"{score}/20"
119
- correct, expl = ibisubizo_dict.get(question, ("", ""))
120
- if answer == correct:
121
- score += 4
122
- status = f"✅ Igisubizo cyawe ni cyo\n💡 Explanation: {expl}"
123
- else:
124
- status = f"❌ Igisubizo nyacyo: {correct}\n💡 Explanation: {expl}\nTip: Subira usome neza icyapa!"
125
- return status, score, f"{score}/20"
126
-
127
- for r, inst in zip(radio_widgets, instant_outputs):
128
- r.change(fn=check_answer, inputs=[r, current_question_state, current_score], outputs=[inst, current_score, quiz_score])
129
-
130
- # --- Reset Quiz ---
131
- def reset_quiz():
132
- updates = []
133
- for r, inst, timer_box in zip(radio_widgets, instant_outputs, timer_boxes):
134
- updates.append(gr.update(visible=False, value=None))
135
- updates.append(gr.update(value=""))
136
- updates.append(gr.update(value="", visible=False))
137
- return 0, "0/20", *updates
138
-
139
- reset_button.click(
140
- fn=reset_quiz,
141
- inputs=[],
142
- outputs=[current_score, quiz_score] + radio_widgets + instant_outputs + timer_boxes
143
- )
144
-
145
- # --- Footer / Copyright ---
146
  gr.Markdown("© 2025 Viateur Irasubiza. Uburenganzira bwose burabitswe.\n\nAI yakozwe kugirango ifashe Abanyarwanda kwiga amategeko y'umuhanda.")
147
 
148
  demo.launch()
 
1
  import gradio as gr
2
  import random
3
  import time
4
+ from threading import Timer
5
 
6
  # ---------------- Dictionary y'ibibazo n'ibisubizo ----------------
7
  ibisubizo_dict = {
8
+ "Icyapa cya STOP gisobanura iki?": ("Ugomba guhagarara neza mbere yo gukomeza, urebe ko umuhanda utekanye.", "Icyapa cya STOP gituma umugenzi amenya guhagarara ngo hamenyekane umutekano w'umuhanda."),
9
+ "Umuvuduko ntarengwa mu mujyi ni uwuhe?": ("Ni 40 km/h mu mijyi.", "Umuvuduko ntarengwa ugamije kugabanya impanuka mu mijyi."),
10
+ "Icyapa cya Attention École gisobanura iki?": ("Kigaragaza ko hafi yaho hari ishuri, ugomba kugabanya umuvuduko no kwitonda.", "Iki cyapa cyerekana ahari ishuri cyangwa abana bari hafi y'umuhanda."),
11
+ # Shyiramo ibindi bibazo byose...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  }
13
 
14
+ # ---------------- Add more questions dynamically ----------------
15
+ for i in range(4, 21):
16
+ question = f"Icyapa cyangwa amategeko y'umuhanda #{i}"
17
+ answer = f"Igisubizo cy'ikibazo #{i} ku mategeko y'umuhanda."
18
+ explanation = f"Impamvu y'ikibazo #{i} ku mategeko y'umuhanda."
19
+ ibisubizo_dict[question] = (answer, explanation)
20
+
21
+ ibibazo_bya_quiz = list(ibisubizo_dict.items())
22
 
23
+ # ---------------- Functions ----------------
24
  def gutegura_quiz(batch_size=5):
25
+ quiz = random.sample(ibibazo_bya_quiz, min(batch_size, len(ibibazo_bya_quiz)))
26
  quiz_questions = []
27
  quiz_choices = []
28
+ for q, (ans, expl) in quiz:
29
  other_answers = list(set(a for a, _ in ibisubizo_dict.values()) - {ans})
30
  choices = random.sample(other_answers, min(2, len(other_answers))) + [ans]
31
  random.shuffle(choices)
 
33
  quiz_choices.append(choices)
34
  return quiz_questions, quiz_choices
35
 
36
+ def check_answer(answer, question, scores_list):
37
+ if not question:
38
+ return "", scores_list, "0", "0/0"
39
+
40
+ correct, expl = ibisubizo_dict.get(question, ("", ""))
41
+ score = 4 if answer == correct else 0
42
+
43
+ scores_list.append(score)
44
+ total_score = sum(scores_list)
45
+ question_score_text = f"🏅 Amanota kuri iki kibazo: {score}/4\n💡 Explanation: {expl}"
46
+ total_score_text = f"🏆 Amanota yose kugeza ubu: {total_score}/{len(scores_list)*4}"
47
+
48
+ return question_score_text, scores_list, str(score), total_score_text
49
+
50
+ def start_quiz():
51
+ questions, choices = gutegura_quiz()
52
+ updates = []
53
+ for i, r in enumerate(radio_widgets):
54
+ if i < len(questions):
55
+ updates.append(gr.update(choices=choices[i], label=questions[i], visible=True, value=None))
56
+ else:
57
+ updates.append(gr.update(visible=False))
58
+ for inst, t in zip(instant_outputs, timer_boxes):
59
+ updates.append(gr.update(visible=False, value=""))
60
+ updates.append(gr.update(visible=True, value="⏱️ 20s left"))
61
+ return questions, choices, *updates, [], "0/0"
62
+
63
+ def reset_quiz():
64
+ updates = []
65
+ for r, inst, t in zip(radio_widgets, instant_outputs, timer_boxes):
66
+ updates.append(gr.update(visible=False, value=None))
67
+ updates.append(gr.update(value=""))
68
+ updates.append(gr.update(value="⏱️ 20s left"))
69
+ return [], [], [], "0/0", *updates
70
 
71
  # ---------------- Gradio Interface ----------------
72
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="yellow")) as demo:
 
73
  gr.Markdown("# 🚗 AI y’Amategeko y’Umuhanda 🇷🇼\n### *Yakozwe na Viateur Irasubiza*")
74
+
 
 
 
 
 
 
 
 
 
 
 
75
  quiz_button = gr.Button("Tangira Quiz")
76
  reset_button = gr.Button("🔄 Reset Quiz")
77
+
78
+ quiz_score = gr.Textbox(label="🏆 Amanota yose kugeza ubu", value="0/0", interactive=False)
79
+ scores_list_state = gr.State([])
80
+
 
 
81
  radio_widgets = []
82
  instant_outputs = []
83
  timer_boxes = []
 
84
  for i in range(5):
85
  r = gr.Radio(choices=[], label=f"Ikibazo {i+1}", visible=False)
86
  radio_widgets.append(r)
87
  inst = gr.Markdown("", visible=False)
88
  instant_outputs.append(inst)
89
+ timer_box = gr.Markdown("⏱️ 20s left", visible=False)
90
  timer_boxes.append(timer_box)
91
+
92
+ quiz_questions_state = gr.State()
93
+ quiz_choices_state = gr.State()
94
+
95
+ # Buttons logic
96
+ quiz_button.click(fn=start_quiz, inputs=[], outputs=[quiz_questions_state, quiz_choices_state] + [val for pair in zip(radio_widgets, instant_outputs) for val in pair] + timer_boxes + [scores_list_state, quiz_score])
97
+ reset_button.click(fn=reset_quiz, inputs=[], outputs=[quiz_questions_state, quiz_choices_state, scores_list_state, quiz_score] + [val for pair in zip(radio_widgets, instant_outputs) for val in pair] + timer_boxes)
98
+
99
+ # Answer checking
100
+ for r, inst, timer in zip(radio_widgets, instant_outputs, timer_boxes):
101
+ r.change(fn=check_answer, inputs=[r, r.label, scores_list_state], outputs=[inst, scores_list_state, r, quiz_score])
102
+
103
+ # Footer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  gr.Markdown("© 2025 Viateur Irasubiza. Uburenganzira bwose burabitswe.\n\nAI yakozwe kugirango ifashe Abanyarwanda kwiga amategeko y'umuhanda.")
105
 
106
  demo.launch()