File size: 2,561 Bytes
0bc32ef
 
 
1b7a426
0bc32ef
 
 
 
1b7a426
0bc32ef
 
 
 
1b7a426
0bc32ef
 
 
 
1b7a426
0bc32ef
 
1b7a426
0bc32ef
 
 
 
 
 
 
 
 
 
 
 
 
6247532
 
 
 
 
 
 
 
 
 
 
 
0bc32ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6247532
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import random
from vocab import get_words_from_source
from sentences import get_sentence

# 生成單字選擇題
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']
        phonetic = word_data['phonetic']

        # 取得例句
        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,
            "phonetic": phonetic
        })

    # 將問題渲染為 HTML 以便 Gradio 顯示
    if not questions:
        return "<p style='color:red;'>❌ 無法生成試卷,可能單字缺少例句</p>"

    exam_html = ""
    for i, q in enumerate(questions):
        exam_html += f"<p><strong>第 {i + 1} 題:</strong> {q['sentence']}</p>"
        for option in q['options']:
            exam_html += f"<input type='radio' name='q{i}' value='{option}'> {option}  "
        exam_html += "<br>"

    return exam_html


# 自動對答案並計分
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>" \
                       f"<strong>你的答案:</strong> {res['user_answer']}<br>" \
                       f"<strong>正確答案:</strong> {res['correct_answer']}</p>"

    return result_html