Spaces:
Sleeping
Sleeping
(V1.5 專業 Excel 導出版)
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231242 unmodified linesimport google.generativeai as genaiimport timeimport os# --- 核心評分邏輯與嚴格準則 ---def get_grading_prompt(student_data_text):return f"""你是一位極其嚴格的初中數學老師。請根據轉錄文字對『二元一次方程組』解題進行評分。### 評分背景說明:1. 識別文字開頭的 [M:SS] 代表學生的解題總時長。2. 請自動判定題目類型:應用題 (軌道 A) 或 純解方程組 (軌道 B)。3. 嚴格對標 1-5 分標準(總分 20 分),不可隨意給高分。---### 評分準則 (1-5 分制):【軌道 A:應用題】- **建模設元**:1(無意識); 2(與背景無關); 3(設元模糊/方程錯); 4(正確但漏單位); 5(精準設元且有單位)- **運算精確**:1(無動作); 2(過程混亂); 3(符號錯導致解不符情境); 4(邏輯對僅末步筆誤); 5(運算零錯誤)- **術語規範**:1(純讀數); 2(術語誤用/斷裂); 3(口語過多); 4(基本正確但少答或設); 5(完整專業口述設/代/消/答)- **溝通流暢**:(參考[M:SS]) 1(碎詞); 2(重複/沈默長); 3(贅詞多/時長過長); 4(清晰少贅詞); 5(講解極流利且節奏精簡)【軌道 B:純解方程組】- **步驟規範**:1(無順序); 2(無說明直接跳答案); 3(跳步嚴重); 4(有概念但未標式號); 5(明確口述式號與變換過程)- **運算精確**:1(無法運算); 2(變換操作不熟); 3(移位變號錯/負號錯); 4(邏輯對僅代入求值筆誤); 5(係數正負完全正確)- **方法選取**:1(無方法概念); 2(名稱混淆); 3(方法不當/路徑極複雜); 4(正確執行但非最簡路徑); 5(能解釋理由且選用最優法)- **檢驗總結**:1(無結論); 2(計完即止無結尾); 3(殘缺僅求出一解); 4(有答案但無驗算); 5(主動口述驗算且給出標準格式解)---### 待評分學生數據:{student_data_text}---### 輸出要求 (必須使用 Markdown 表格):請輸出包含以下欄位的表格:| 學生姓名 | 判定軌道 | 時長 | 得分詳情 (維度:分數) | 總分 | 嚴格評語 (需指明具體扣分原因) |"""def process_grading(api_key, file):if not api_key: return None, "❌ 請輸入 API Key", Noneif file is None: return None, "❌ 請上傳 Excel 檔案", Nonetry:# 1. 配置 Gemini 2.5 Flashgenai.configure(api_key=api_key)model = genai.GenerativeModel("gemini-2.5-flash")# 2. 讀取 Exceldf = pd.read_excel(file.name)# 兼容性檢查:確保欄位名稱正確target_col = "[全片長度] 識別文字內容"if target_col not in df.columns:# 嘗試找包含「識別文字內容」的欄位found = [c for c in df.columns if "識別文字內容" in c]if found: target_col = found[0]else: return None, f"❌ 找不到欄位 '{target_col}',請檢查 Excel。", Nonetotal_students = len(df)batch_size = 10 # 每 10 人一組,確保 AI 專注度all_markdown_reports = []# 3. 批量處理邏輯 (支持 140 人)for i in range(0, total_students, batch_size):batch_df = df.iloc[i : i + batch_size]student_text_block = ""for _, row in batch_df.iterrows():student_text_block += f"學生 [{row['影片名稱']}]: {row[target_col]}\n\n"# 生成 Promptfinal_prompt = get_grading_prompt(student_text_block)# 調用 APIresponse = model.generate_content(final_prompt)all_markdown_reports.append(response.text)# 更新進度條current_progress = min(i + batch_size, total_students)yield None, f"⏳ 評分進度:{current_progress} / {total_students}...", None# 避開免費版 RPM 限制time.sleep(1.5)# 4. 合併報告complete_report = "\n\n---\n\n".join(all_markdown_reports)# 5. 生成下載檔案 (.md 格式最能完整保留表格)output_path = "final_grading_report.md"with open(output_path, "w", encoding="utf-8") as f:f.write("# 學生解題評分總報告\n\n")f.write(complete_report)yield complete_report, f"✅ 全班 {total_students} 位學生評分完成!", output_pathexcept Exception as e:yield None, f"❌ 運行出錯:{str(e)}", None# --- Gradio 介面 ---with gr.Blocks(theme=gr.themes.Soft(), title="MathGenius Grader") as demo:gr.Markdown("# 🤖 MathGenius AI 評分系統 (V1.2)")gr.Markdown("專為『二元一次方程組』設計。請上傳 Space 1 產出的 Excel 檔案。")with gr.Row():with gr.Column(scale=1):key_input = gr.Textbox(label="🔑 請輸入 Gemini API Key",type="password",placeholder="在此貼上您的 API Key...")file_input = gr.File(label="📤 上傳 Excel (.xlsx)", file_types=[".xlsx"])run_btn = gr.Button("🚀 開始批量評分", variant="primary")with gr.Column(scale=2):status_msg = gr.Markdown("等待操作...")report_display = gr.Markdown("### 評分報告預覽")download_btn = gr.File(label="📥 下載完整評分報告 (.md)")run_btn.click(fn=process_grading,inputs=[key_input, file_input],outputs=[report_display, status_msg, download_btn])if __name__ == "__main__":2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051062 unmodified linesimport google.generativeai as genaiimport timeimport osimport re# --- 核心指令:要求 AI 使用「|」作為格子的邊界 ---def get_grading_prompt(data_block):return f"""你是一位極其嚴格的初中數學老師。請對『二元一次方程組』解題影片轉錄稿進行評分。### 評分格式要求 (極重要):針對每位學生,你必須輸出一行且僅有一行的字串,各欄位之間用「|」分隔,嚴格遵守以下順序:總分|建模分|運算分|術語分|流暢分|優點1|優點2|優點3|缺點1|缺點2|缺點3|總教學意見### 內容規則:1. 軌道判定:自動識別為「應用題」或「純計算」。2. 得分(1-5分):建模、運算、術語、流暢(參考[M:SS])。3. 優/缺點:每個點限 1-2 句話,精準扼要。必須給滿 3 個優點與 3 個缺點。4. 總教學意見:對學生的整體建議,1 句話。待評數據:{data_block}"""def process_grading(api_key, file):if not api_key or file is None:return None, "❌ 缺少 API Key 或檔案", Nonetry:genai.configure(api_key=api_key)model = genai.GenerativeModel("gemini-2.5-flash")# 1. 讀取原始 Exceldf_original = pd.read_excel(file.name)target_col = df_original.columns[1] # 假設第二欄是文字內容all_scored_rows = []batch_size = 5 # 為了優缺點的精確度,縮小批次total = len(df_original)# 2. 批次處理for i in range(0, total, batch_size):batch_df = df_original.iloc[i : i + batch_size]prompt_input = ""for _, row in batch_df.iterrows():prompt_input += f"學生 [{row.iloc[0]}]: {row[target_col]}\n\n"response = model.generate_content(get_grading_prompt(prompt_input))raw_output = response.text.strip().split('\n')# 3. 解析 AI 回傳的每一行並拆分成格子for line in raw_output:if "|" in line:parts = [p.strip() for p in line.split("|")]# 確保長度符合 (補足或截斷)if len(parts) < 12:parts += ["-"] * (12 - len(parts))all_scored_rows.append(parts[:12])yield None, f"⏳ 已處理 {min(i+batch_size, total)} / {total} 位學生...", Nonetime.sleep(2) # 避開速率限制# 4. 建立評分結果表格new_columns = ["總分", "建模設元", "運算精確", "術語規範", "溝通流暢","優點1", "優點2", "優點3", "缺點1", "缺點2", "缺點3", "總教學意見"]df_scores = pd.DataFrame(all_scored_rows, columns=new_columns)# 5. 橫向合併 (按索引對齊)# 如果 AI 輸出的行數與原始不符,這裡會進行基本處理df_final = pd.concat([df_original.reset_index(drop=True), df_scores], axis=1)# 6. 導出 Exceloutput_path = "MathGenius_Full_Report.xlsx"df_final.to_excel(output_path, index=False)return df_final, "✅ 評分並合併完成!已生成追加欄位的 Excel 檔案。", output_pathexcept Exception as e:return None, f"❌ 運行出錯:{str(e)}", None# --- Gradio 介面佈局 ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🤖 MathGenius AI 評分系統 V1.5 (Excel 追加版)")gr.Markdown("上傳 Space 1 的檔案,系統將自動在右側追加 12 個評分與優缺點欄位。")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="結果預覽 (橫向拉動查看新欄位)")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__":
app.py+67-85