Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import gradio as grimport pandas as pdimport google.generativeai as genaiimport os
# --- 核心邏輯:驗證 API Key 並執行評分 ---def check_key_and_process(api_key, file): # 1. 基本檢查 if not api_key or len(api_key) < 10: return None, "❌ 請先輸入正確的 Gemini API Key。" if file is None: return None, "❌ 請上傳從 Space 1 下載的 Excel 檔案。"
try: # 2. 嘗試配置 Gemini genai.configure(api_key=api_key) model = genai.GenerativeModel("gemini-1.5-flash") # 先用 1.5 測試連通性 # 嘗試一個極簡的測試調用 response = model.generate_content("Hi", generation_config={"max_output_tokens": 5}) if not response.text: raise Exception("API 回傳異常") except Exception as e: return None, f"❌ API Key 無效或網路錯誤:{str(e)}\n請檢查 Key 是否正確或是否有 RPD 限制。"
# 3. 讀取 Excel 數據 try: df = pd.read_excel(file.name) # 檢查欄位是否符合 Space 1 的輸出 if "影片名稱" not in df.columns or "[全片長度] 識別文字內容" not in df.columns: return df, "⚠️ 檔案格式似乎不符,請確保這是從 Space 1 匯出的 Excel。" return df, f"✅ API 連接成功!已讀取 {len(df)} 位學生的數據。準備好進行下一步批量評分嗎?" except Exception as e: return None, f"❌ 檔案讀取失敗:{str(e)}"
# --- Gradio 介面佈局 ---with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# 🤖 MathGenius AI 評分系統 (Space 2)") gr.Markdown("這裏負責處理 Space 1 的文字結果,並進行**二元一次方程組**雙軌制評分。")
with gr.Row(): # 左側控制區 with gr.Column(scale=1): user_key = gr.Textbox( label="🔑 請輸入 Gemini API Key", placeholder="在此貼上你的 API Key...", type="password" # 隱藏輸入內容 ) upload_file = gr.File( label="📤 上傳辨識結果 (.xlsx)", file_types=[".xlsx"] ) start_btn = gr.Button("🚀 驗證並預覽數據", variant="primary")
# 右側顯示區 with gr.Column(scale=2): status_msg = gr.Markdown("等待操作...") data_preview = gr.Dataframe( label="學生文字預覽 (140人清單)", wrap=True, interactive=False )
# 按鈕交互 start_btn.click( fn=check_key_and_process, inputs=[user_key, upload_file], outputs=[data_preview, status_msg] )
if __name__ == "__main__": demo.launch()app.pyAdded+75