import gradio as gr from nlp_transform import extract_conditions from area_calculator import calculate_area, get_missing_keys def chat(user_input, history): try: result = extract_conditions(user_input) print("🧠 NLP 萃取結果:", result) response_lines = [] # 檢查缺失欄位 missing = get_missing_keys(result) # 顯示已抓到欄位 if "site_area" in result: response_lines.append(f"📏 基地面積:{result['site_area']} m²") if "BCR" in result: response_lines.append(f"🏗️ 建蔽率:{result['BCR']}%") if "FAR" in result: response_lines.append(f"🏙️ 容積率:{result['FAR']}%") if "bonus_far" in result: response_lines.append(f"🎁 容積獎勵:{result['bonus_far']}%") # 如果資料齊全 → 計算面積 if not missing: area_result = calculate_area(result) response_lines.append(area_result["summary"]) else: response_lines.append("⚠️ 缺少以下資料:" + "、".join(missing)) final_response = "\n".join(response_lines) if response_lines else "⚠️ 無法辨識有用資訊,請重新描述~" # 更新歷史 new_history = history + [ {"role": "user", "content": user_input}, {"role": "assistant", "content": final_response}, ] return new_history, new_history, "" except Exception as e: print("❌ 錯誤訊息:", e) error_msg = f"❌ 發生錯誤:{str(e)}" new_history = history + [ {"role": "user", "content": user_input}, {"role": "assistant", "content": error_msg}, ] return new_history, new_history, "" # ✅ Gradio 介面區塊 with gr.Blocks() as demo: gr.Markdown("## 🏗️ 建築條件助理") chatbot = gr.Chatbot(label="條件分析助手", type="messages") msg = gr.Textbox(label="請輸入建築條件", placeholder="例:基地面積2000平方公尺,容積率200%,建蔽率50%", lines=2) send_btn = gr.Button("📨 傳送") state = gr.State([]) def handle_input(user_input, history): return chat(user_input, history) msg.submit(handle_input, [msg, state], [chatbot, state, msg]) send_btn.click(handle_input, [msg, state], [chatbot, state, msg]) # ✅ 執行 Gradio 介面 demo.launch(share=True)