import requests import json import gradio as gr def calculate(course_input, course_profile, course_hour): url = "https://rd-ai-knowledge-navigator.onrender.com/process" headers = { "Content-Type": "application/json" } data = { "title": course_input, "content": course_profile, "hour": course_hour } try: response = requests.post(url, json=data, headers=headers, timeout=50) if response.status_code == 200: try: response_json = response.json() success = response_json.get("success", False) title = response_json.get("title", "未知課程") top_competencies = response_json.get("top_competencies", []) competencies = response_json.get("competencies", []) if success: competencies_list = [f"{item['item']} ({item['score']})" for item in competencies] return (f"課程 '{title}' 職能匹配成功!", top_competencies, "\n".join(competencies_list)) else: return "匹配失敗,請稍後再試", "無職能項目", "無職能項目" except json.JSONDecodeError: return "錯誤: 伺服器回應非 JSON 格式", "無職能項目", "無職能項目" else: return f"錯誤: 伺服器返回 HTTP {response.status_code}", "無職能項目", "無職能項目" except requests.exceptions.Timeout: return "錯誤: 伺服器回應超時", "無職能項目", "無職能項目" except requests.exceptions.RequestException as e: return f"請求失敗: {str(e)}", "無職能項目", "無職能項目" # 驗證輸入欄位是否為空 def validate_input(course_input, course_profile, course_hour): errors = [] if not course_input.strip(): errors.append("課程名稱為必填項目") if not course_profile.strip(): errors.append("課程簡介為必填項目") if not course_hour.strip(): errors.append("課程時數為必填項目") if errors: return "\n".join(errors), "", "" # 直接回傳錯誤訊息,阻止請求 return None # 表示輸入有效,允許繼續執行 def setup_gradio_interface(): with gr.Blocks() as demo: with gr.Row(): course_input = gr.Textbox(label="課程名稱", placeholder="請輸入課程名稱") course_hour = gr.Textbox(label="課程時數", placeholder="請輸入課程時數") with gr.Row(): course_profile = gr.Textbox(label="課程簡介", placeholder="請輸入課程簡介") with gr.Row(): submit_button = gr.Button("計算職能項目") with gr.Row(): txt_response = gr.Textbox(label="計算狀態", placeholder="計算結果", interactive=False) course_competencies = gr.Textbox(label="職能項目", placeholder="職能項目", interactive=False) with gr.Row(): json_competencies = gr.Textbox(label="JSON內容", placeholder="職能項目", interactive=False) # 先驗證輸入,再進行計算 def validate_and_calculate(course_input, course_profile, course_hour): validation_result = validate_input(course_input, course_profile, course_hour) if validation_result: return validation_result # 若輸入無效,回傳錯誤訊息 return calculate(course_input, course_profile, course_hour) # 若有效則繼續計算 submit_button.click( validate_and_calculate, inputs=[course_input, course_profile, course_hour], outputs=[txt_response, course_competencies, json_competencies] ) return demo # 運行 Gradio 介面 if __name__ == "__main__": demo = setup_gradio_interface() demo.launch()