File size: 4,502 Bytes
82286e5
 
 
1f9e8c9
82286e5
1f9e8c9
ae5987e
 
ee44313
1f9e8c9
 
 
 
ae5987e
ee44313
ae5987e
1f9e8c9
 
 
ee44313
ae5987e
 
ee44313
 
 
ae5987e
 
82286e5
 
1f9e8c9
82286e5
ee44313
82286e5
1f9e8c9
 
 
 
ee44313
ae5987e
1f9e8c9
 
ae5987e
 
1f9e8c9
ae5987e
ee44313
ae5987e
82286e5
1f9e8c9
ae5987e
1f9e8c9
ee44313
1f9e8c9
 
 
 
 
 
 
 
 
 
 
ee44313
1f9e8c9
 
ae5987e
1f9e8c9
 
ae5987e
 
 
82286e5
1f9e8c9
 
 
 
 
ae5987e
 
1f9e8c9
ae5987e
ee44313
1f9e8c9
 
ee44313
82286e5
1f9e8c9
82286e5
1f9e8c9
ae5987e
1f9e8c9
 
82286e5
 
ae5987e
 
 
ee44313
82286e5
ae5987e
1f9e8c9
ae5987e
82286e5
ee44313
 
 
ae5987e
82286e5
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import gradio as gr
import pandas as pd
import google.generativeai as genai
import time, os

# --- 核心指令:嚴格要求 AI 輸出「|」分隔符 ---
def get_grading_prompt(data_block):
    return f"""你是一位極其嚴格的初中數學老師。請對『二元一次方程組』解題影片轉錄稿進行評分。

### 格式要求 (極重要):
針對每位學生,你必須輸出一行且僅有一行的字串,各欄位之間用「|」分隔。
不要輸出 Markdown 表格標頭 (如 |---|),直接輸出數據。
順序如下:
總分|建模分|運算分|術語分|流暢分|優點1|優點2|優點3|缺點1|缺點2|缺點3|總教學意見

### 內容規則:
1. 優/缺點:每個點限 1-2 句話。必須給滿 3 個優點與 3 個缺點。
2. 總分:為四項得分之和。
3. 參考文字開頭的 [M:SS] 評定流暢度。

待評數據:
{data_block}
"""

def process_grading(api_key, file):
    if not api_key or file is None:
        return None, "❌ 缺少 API Key 或檔案", None

    try:
        # 1. 配置 Gemini 2.5 Flash
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel("gemini-2.5-flash")
        
        # 2. 讀取 Excel
        df_orig = pd.read_excel(file.name)
        # 取得文字內容欄位 (假設是第二欄)
        target_col = df_orig.columns[1] 
        
        all_scored_rows = []
        batch_size = 5 # 每 5 人一組確保穩定
        total = len(df_orig)

        for i in range(0, total, batch_size):
            batch_df = df_orig.iloc[i : i + batch_size]
            prompt_input = ""
            for _, row in batch_df.iterrows():
                prompt_input += f"學生 [{row.iloc[0]}]: {row[target_col]}\n\n"
            
            # 調用 API
            response = model.generate_content(get_grading_prompt(prompt_input))
            raw_lines = response.text.strip().split('\n')
            
            # 3. 解析與清理 (過濾 Markdown 雜質)
            for line in raw_lines:
                # 移除 Markdown 表格裝飾線與前後空格
                clean_line = line.replace('---', '').strip('| ')
                if "|" in clean_line:
                    parts = [p.strip() for p in clean_line.split("|")]
                    # 確保是有效的數據行 (至少有 5 個欄位)
                    if len(parts) >= 5:
                        if len(parts) < 12:
                            parts += ["-"] * (12 - len(parts))
                        all_scored_rows.append(parts[:12])
            
            yield None, f"⏳ 正在處理數據:{len(all_scored_rows)} / {total} 位學生...", None
            time.sleep(2)

        # 4. 建立新表格並合併
        new_cols = [
            "總分", "建模設元", "運算精確", "術語規範", "溝通流暢",
            "優點1", "優點2", "優點3", "缺點1", "缺點2", "缺點3", "總教學意見"
        ]
        
        # 建立評分結果的 DataFrame
        df_scores = pd.DataFrame(all_scored_rows, columns=new_cols)
        
        # 5. 強制對齊合併 (使用索引對齊)
        df_final = pd.concat([df_orig.reset_index(drop=True), df_scores], axis=1)

        # 6. 導出 Excel
        output_path = "MathGenius_Final_Report.xlsx"
        df_final.to_excel(output_path, index=False)

        # 最終回傳:表格內容、成功訊息、下載路徑
        yield df_final, f"✅ 評分完成!共處理 {len(all_scored_rows)} 位學生。", output_path

    except Exception as e:
        yield None, f"❌ 運行出錯:{str(e)}", None

# --- Gradio 介面 ---
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# 🤖 MathGenius AI 評分系統 V1.5.1 (穩定版)")
    
    with gr.Row():
        with gr.Column(scale=1):
            key_input = gr.Textbox(label="🔑 Gemini API Key", type="password")
            file_input = gr.File(label="📤 上傳原始 Excel", file_types=[".xlsx"])
            run_btn = gr.Button("🚀 執行全自動追加評分", variant="primary")
            
        with gr.Column(scale=2):
            status_msg = gr.Markdown("等待中...")
            data_view = gr.Dataframe(label="結果預覽 (橫向拉動可看 12 個新欄位)")
            download_file = gr.File(label="📥 下載最終成績總表 (.xlsx)")

    run_btn.click(
        fn=process_grading,
        inputs=[key_input, file_input],
        outputs=[data_view, status_msg, download_file]
    )

if __name__ == "__main__":
    demo.launch()