Spaces:
Running
Running
import random | |
from vocab import get_words_from_source | |
from sentences import get_sentence | |
import gradio as gr | |
# 生成單字選擇題資料 | |
def generate_fill_in_blank_exam(source, num): | |
words_data = get_words_from_source(source) | |
words = random.sample(words_data, num) | |
questions = [] | |
for word_data in words: | |
word = word_data['word'] | |
# 取得例句 | |
sentence_data = get_sentence(word) | |
if not sentence_data: | |
continue | |
sentence = sentence_data[2] | |
blank_sentence = sentence.replace(word, '______') | |
# 生成干擾選項 (亂數抽 3 個其他單字) | |
other_words = [w['word'] for w in words_data if w['word'] != word] | |
distractors = random.sample(other_words, 3) | |
options = [word] + distractors | |
random.shuffle(options) | |
questions.append({ | |
"sentence": blank_sentence, | |
"options": options, | |
"answer": word, | |
}) | |
return questions | |
# 自動對答案並計分 | |
def check_exam(user_answers, questions): | |
correct_count = 0 | |
results = [] | |
for i, user_answer in enumerate(user_answers): | |
correct_answer = questions[i]['answer'] | |
is_correct = (user_answer == correct_answer) | |
results.append({ | |
"question": questions[i]['sentence'], | |
"user_answer": user_answer, | |
"correct_answer": correct_answer, | |
"is_correct": is_correct, | |
}) | |
if is_correct: | |
correct_count += 1 | |
score = f"{correct_count}/{len(questions)} 分" | |
result_html = f"<p><strong>得分:</strong> {score}</p>" | |
for res in results: | |
color = "green" if res["is_correct"] else "red" | |
result_html += f"<p style='color:{color};'><strong>題目:</strong> {res['question']}<br>" | |
result_html += f"<strong>你的答案:</strong> {res['user_answer']}<br>" | |
result_html += f"<strong>正確答案:</strong> {res['correct_answer']}</p>" | |
return result_html | |
# 動態生成 Gradio Radio 元件 | |
def render_exam_interface(questions): | |
radios = [] | |
for i, q in enumerate(questions): | |
radios.append( | |
gr.Radio( | |
choices=q['options'], | |
label=f"第 {i + 1} 題:{q['sentence']}", | |
interactive=True | |
) | |
) | |
return radios | |