Team Ai
Apppublic

MathTeacherUser/Ranking-Text

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
app.py112 linesDownload Raw Back to root
1import gradio as gr2import pandas as pd3import google.generativeai as genai4import time, os5 6# --- 核心指令:嚴格要求 AI 輸出「|」分隔符 ---7def get_grading_prompt(data_block):8    return f"""你是一位極其嚴格的初中數學老師。請對『二元一次方程組』解題影片轉錄稿進行評分。9 10### 格式要求 (極重要):11針對每位學生,你必須輸出一行且僅有一行的字串,各欄位之間用「|」分隔。12不要輸出 Markdown 表格標頭 (如 |---|),直接輸出數據。13順序如下:14總分|建模分|運算分|術語分|流暢分|優點1|優點2|優點3|缺點1|缺點2|缺點3|總教學意見15 16### 內容規則:171. 優/缺點:每個點限 1-2 句話。必須給滿 3 個優點與 3 個缺點。182. 總分:為四項得分之和。193. 參考文字開頭的 [M:SS] 評定流暢度。20 21待評數據:22{data_block}23"""24 25def process_grading(api_key, file):26    if not api_key or file is None:27        return None, "❌ 缺少 API Key 或檔案", None28 29    try:30        # 1. 配置 Gemini 2.5 Flash31        genai.configure(api_key=api_key)32        model = genai.GenerativeModel("gemini-2.5-flash")33        34        # 2. 讀取 Excel35        df_orig = pd.read_excel(file.name)36        # 取得文字內容欄位 (假設是第二欄)37        target_col = df_orig.columns[1] 38        39        all_scored_rows = []40        batch_size = 5 # 每 5 人一組確保穩定41        total = len(df_orig)42 43        for i in range(0, total, batch_size):44            batch_df = df_orig.iloc[i : i + batch_size]45            prompt_input = ""46            for _, row in batch_df.iterrows():47                prompt_input += f"學生 [{row.iloc[0]}]: {row[target_col]}\n\n"48            49            # 調用 API50            response = model.generate_content(get_grading_prompt(prompt_input))51            raw_lines = response.text.strip().split('\n')52            53            # 3. 解析與清理 (過濾 Markdown 雜質)54            for line in raw_lines:55                # 移除 Markdown 表格裝飾線與前後空格56                clean_line = line.replace('---', '').strip('| ')57                if "|" in clean_line:58                    parts = [p.strip() for p in clean_line.split("|")]59                    # 確保是有效的數據行 (至少有 5 個欄位)60                    if len(parts) >= 5:61                        if len(parts) < 12:62                            parts += ["-"] * (12 - len(parts))63                        all_scored_rows.append(parts[:12])64            65            yield None, f"⏳ 正在處理數據:{len(all_scored_rows)} / {total} 位學生...", None66            time.sleep(2)67 68        # 4. 建立新表格並合併69        new_cols = [70            "總分", "建模設元", "運算精確", "術語規範", "溝通流暢",71            "優點1", "優點2", "優點3", "缺點1", "缺點2", "缺點3", "總教學意見"72        ]73        74        # 建立評分結果的 DataFrame75        df_scores = pd.DataFrame(all_scored_rows, columns=new_cols)76        77        # 5. 強制對齊合併 (使用索引對齊)78        df_final = pd.concat([df_orig.reset_index(drop=True), df_scores], axis=1)79 80        # 6. 導出 Excel81        output_path = "MathGenius_Final_Report.xlsx"82        df_final.to_excel(output_path, index=False)83 84        # 最終回傳:表格內容、成功訊息、下載路徑85        yield df_final, f"✅ 評分完成!共處理 {len(all_scored_rows)} 位學生。", output_path86 87    except Exception as e:88        yield None, f"❌ 運行出錯:{str(e)}", None89 90# --- Gradio 介面 ---91with gr.Blocks(theme=gr.themes.Soft()) as demo:92    gr.Markdown("# 🤖 MathGenius AI 評分系統 V1.5.1 (穩定版)")93    94    with gr.Row():95        with gr.Column(scale=1):96            key_input = gr.Textbox(label="🔑 Gemini API Key", type="password")97            file_input = gr.File(label="📤 上傳原始 Excel", file_types=[".xlsx"])98            run_btn = gr.Button("🚀 執行全自動追加評分", variant="primary")99            100        with gr.Column(scale=2):101            status_msg = gr.Markdown("等待中...")102            data_view = gr.Dataframe(label="結果預覽 (橫向拉動可看 12 個新欄位)")103            download_file = gr.File(label="📥 下載最終成績總表 (.xlsx)")104 105    run_btn.click(106        fn=process_grading,107        inputs=[key_input, file_input],108        outputs=[data_view, status_msg, download_file]109    )110 111if __name__ == "__main__":112    demo.launch()