Update app.py
Browse files46 unmodified lines47484950515253545548 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512612712812913013171 unmodified lines20320420520620720814 unmodified lines2232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363375 unmodified lines3433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803815 unmodified lines38738838939039139239343 unmodified lines43743843944044144244332 unmodified lines47647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759869 unmodified lines66866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871946 unmodified lines"status": "N/A","update_time": "Waiting for data...","image_url": "N/A","auto_capture_requested": False,"last_capture_job": "None","last_capture_time": "None"}bambu_client = None48 unmodified linespayload = msg.payload.decode("utf-8")logger.info(f"Received message from RPI: {payload}")try:data = json.loads(payload)# 处理状态更新if "status" in data:latest_data["status"] = data["status"]latest_data["update_time"] = data.get("update_time", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))if "nozzle_temperature" in data:latest_data["nozzle_temperature"] = data["nozzle_temperature"]if "bed_temperature" in data:latest_data["bed_temperature"] = data["bed_temperature"]if "error" in data:logger.error(f"Error from RPI: {data['error']}")# 添加对自动拍照命令的处理if "command" in data and data["command"] == "capture_image" and data.get("auto_triggered", False):logger.info("收到自动拍照命令")# 异步处理拍照请求,避免阻塞MQTT回调threading.Thread(target=handle_auto_capture, args=(data,), daemon=True).start()except json.JSONDecodeError:logger.error(f"Invalid JSON in message: {payload}")71 unmodified lineslogger.error(f"Error sending parameters: {e}")return f"Error sending parameters: {e}"def get_image_base64(image):if image is None:14 unmodified linesreturn Nonedef get_test_image(image_name=None):test_dir = os.path.join(os.path.dirname(__file__), "test_images")if not os.path.exists(test_dir):logger.error(f"Test images directory not found: {test_dir}")return Noneimage_files = [ffor f in os.listdir(test_dir)if f.lower().endswith((".png", ".jpg", ".jpeg", ".bmp"))]if not image_files:logger.error("No test images found")return Noneif image_name and image_name in image_files:image_path = os.path.join(test_dir, image_name)else:image_path = os.path.join(test_dir, random.choice(image_files))logger.info(f"Using test image: {image_path}")try:return Image.open(image_path)except Exception as e:logger.error(f"Failed to open test image: {e}")return Nonedef capture_image():"""捕获图像"""try:logger.info("Capturing image...")# 尝试使用摄像头捕获图像try:cap = cv2.VideoCapture(0) # 使用默认摄像头ret, frame = cap.read()cap.release()if ret:# 转换为RGB(OpenCV使用BGR)frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)logger.info(f"Image captured successfully: {frame_rgb.shape}")return frame_rgbelse:logger.error("Failed to capture image from camera")except Exception as e:logger.error(f"Error accessing camera: {e}")# 如果摄像头捕获失败,使用测试图像test_image = get_test_image()if test_image is not None:logger.info("Using test image instead")return np.array(test_image)# 如果测试图像也不可用,创建一个错误图像error_img = np.zeros((480, 640, 3), dtype=np.uint8)cv2.putText(error_img, "Camera Error", (50, 240), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)return error_imgexcept Exception as e:logger.error(f"Error in capture_image: {e}")# 返回错误图像error_img = np.zeros((480, 640, 3), dtype=np.uint8)cv2.putText(error_img, f"Error: {str(e)}", (50, 240), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)return error_imgdef handle_auto_capture(message):"""处理自动拍照请求"""try:logger.info(f"收到自动拍照请求: {message}")# 提取信息print_job = message.get("print_job", "unknown_job")timestamp = message.get("timestamp", time.strftime("%Y-%m-%d %H:%M:%S"))# 记录到最新数据中latest_data["auto_capture_requested"] = Truelatest_data["last_capture_job"] = print_joblatest_data["last_capture_time"] = timestamp# 执行拍照操作image = capture_image()# 保存图像try:save_dir = os.path.join(os.path.dirname(__file__), "captured_images")os.makedirs(save_dir, exist_ok=True)filename = f"{print_job}_{timestamp.replace(' ', '_').replace(':', '-')}.jpg"filepath = os.path.join(save_dir, filename)if isinstance(image, np.ndarray):cv2.imwrite(filepath, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))else:image.save(filepath)logger.info(f"Saved captured image to {filepath}")except Exception as e:logger.error(f"Error saving captured image: {e}")return imageexcept Exception as e:logger.error(f"处理自动拍照请求时出错: {e}")return Nonedef health_check():5 unmodified lines"latest_update": latest_data["update_time"],}logger.info(f"Health check: {status}")# 修改返回值,确保返回6个值return (status.get("app", "unknown"),"N/A", # 作为nozzle_temperature"N/A", # 作为bed_temperaturestatus.get("time", "unknown"),0, # 作为progressf"MQTT: Bambu={status.get('bambu_mqtt_connected')}, RPI={status.get('rpi_mqtt_connected')}" # 作为message)def update_print_status():"""更新打印状态显示"""global latest_datareturn (latest_data["status"],latest_data["nozzle_temperature"],latest_data["bed_temperature"],latest_data["update_time"],latest_data.get("progress", 0),latest_data.get("message", ""),)demo = gr.Blocks(title="Bambu A1 Mini Print Control")with demo:gr.Markdown("# Bambu A1 Mini Print Control")with gr.Row():refresh_btn = gr.Button("Refresh Status")with gr.Row():current_status = gr.Textbox(label="Printer Status", value="N/A", interactive=False5 unmodified lineslabel="Current Nozzle Temperature", value="N/A", interactive=False)last_update = gr.Textbox(label="Last Update", value="N/A", interactive=False)with gr.Row():# Left column for image and capture buttonwith gr.Column(scale=2):43 unmodified linesfn=get_data,outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update],)capture_btn.click(fn=lambda: gr.update(interactive=False), outputs=capture_btn).then(fn=capture_image, outputs=[captured_image]).then(32 unmodified lineslogger.error(f"Error in capture_frame: {e}")return {"success": False, "error": str(e)}def api_lambda(img_data=None,param_1=200,param_2=60,param_3=60,param_4=100,use_test_image=False,test_image_name=None,):logger.info(f"API call: lambda with params: {param_1}, {param_2}, {param_3}, {param_4}, use_test_image: {use_test_image}, test_image_name: {test_image_name}")try:img = Noneif use_test_image:logger.info(f"Lambda using test image: {test_image_name}")img = get_test_image(test_image_name)elif (img_dataand isinstance(img_data, str)and (img_data.startswith("http://") or img_data.startswith("https://"))):logger.info(f"Lambda received image URL: {img_data}")img = capture_image(img_data)elif img_data and isinstance(img_data, str):try:logger.info("Lambda received base64 image data")img_bytes = base64.b64decode(img_data)img = Image.open(io.BytesIO(img_bytes))except Exception as e:logger.error(f"Failed to decode base64 image: {e}")if img is None:logger.info("No valid image data received, using default test image")img = get_test_image()if img:img_array = np.array(img)quality_level = "low"if 190 <= param_1 <= 210 and param_3 <= 50 and param_4 >= 80:quality_level = "high"elif 185 <= param_1 <= 215 and param_3 <= 70 and param_4 >= 60:quality_level = "medium"if quality_level == "high":missing_rate = 0.02excess_rate = 0.01stringing_rate = 0.01elif quality_level == "medium":missing_rate = 0.05excess_rate = 0.03stringing_rate = 0.02else: # lowmissing_rate = 0.10excess_rate = 0.07stringing_rate = 0.05uniformity_score = 1.0 - (missing_rate + excess_rate + stringing_rate)print_quality_score = 1.0 - (missing_rate * 2.0 + excess_rate * 1.5 + stringing_rate * 1.0)print_quality_score = max(0, min(1, print_quality_score))print_speed_score = param_3 / 150.0print_speed_score = max(0, min(1, print_speed_score))material_efficiency_score = 1.0 - excess_rate * 3.0material_efficiency_score = max(0, min(1, material_efficiency_score))total_performance_score = (0.5 * print_quality_score+ 0.3 * print_speed_score+ 0.2 * material_efficiency_score)img_draw = img.copy()draw = ImageDraw.Draw(img_draw)draw.text((10, 10), f"Quality: {quality_level.upper()}", fill=(255, 0, 0))draw.text((10, 30), f"Missing: {missing_rate:.2f}", fill=(255, 0, 0))draw.text((10, 50), f"Excess: {excess_rate:.2f}", fill=(255, 0, 0))draw.text((10, 70), f"Stringing: {stringing_rate:.2f}", fill=(255, 0, 0))result = {"success": True,"missing_rate": missing_rate,"excess_rate": excess_rate,"stringing_rate": stringing_rate,"uniformity_score": uniformity_score,"print_quality_score": print_quality_score,"print_speed_score": print_speed_score,"material_efficiency_score": material_efficiency_score,"total_performance_score": total_performance_score,}if img_draw.mode == "RGBA":img_draw = img_draw.convert("RGB")buffered = io.BytesIO()img_draw.save(buffered, format="JPEG")img_str = base64.b64encode(buffered.getvalue()).decode()result["image"] = img_strreturn resultelse:return {"success": False, "error": "Failed to get image"}except Exception as e:logger.error(f"Error in lambda: {e}")return {"error": str(e)}def api_send_print_parameters(nozzle_temp=200, bed_temp=60, print_speed=60, fan_speed=10069 unmodified linesapi_name="health_check",)# 在Camera Control标签页中添加自动拍照状态显示with gr.Tab("Camera Control"):# 添加自动拍照状态显示with gr.Row():auto_capture_status = gr.Textbox(label="Auto Capture Status", value="Waiting")refresh_status_btn = gr.Button("Refresh Status")# 添加手动拍照按钮和显示区域with gr.Row():capture_btn = gr.Button("Capture Image")with gr.Row():captured_image = gr.Image(label="Captured Image", type="numpy")# 定义更新状态函数def update_capture_status():auto_status = "Triggered" if latest_data.get("auto_capture_requested", False) else "Waiting"last_time = latest_data.get("last_capture_time", "None")last_job = latest_data.get("last_capture_job", "None")return f"{auto_status} (Last: {last_job} at {last_time})"# 连接刷新按钮refresh_status_btn.click(fn=update_capture_status,inputs=[],outputs=[auto_capture_status])# 连接拍照按钮capture_btn.click(fn=capture_image,inputs=[],outputs=[captured_image])# 使用JavaScript实现自动刷新auto_refresh_js = """function autoRefresh() {document.querySelector('#refresh-status-btn').click();setTimeout(autoRefresh, 5000); // 每5秒刷新一次}setTimeout(autoRefresh, 5000); // 启动自动刷新"""gr.HTML(f"<script>{auto_refresh_js}</script>")if __name__ == "__main__":logger.info("Starting Bambu A1 Mini Print Control application")46 unmodified lines474849505152535448 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214371 unmodified lines21521621721821922022122222322422522614 unmodified lines2412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243255 unmodified lines3313323333343353363373383393403413423433443453463475 unmodified lines35335435535635735835943 unmodified lines40340440540640740840932 unmodified lines44244344444544644769 unmodified lines51751851952052152246 unmodified lines"status": "N/A","update_time": "Waiting for data...","image_url": "N/A","progress": 0,"message": "",}bambu_client = None48 unmodified linespayload = msg.payload.decode("utf-8")logger.info(f"Received message from RPI: {payload}")data = json.loads(payload)status = data.get("status", "Unknown")latest_data["status"] = statuslatest_data["update_time"] = data.get("update_time", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))if "nozzle_temperature" in data:latest_data["nozzle_temperature"] = data["nozzle_temperature"]if "bed_temperature" in data:latest_data["bed_temperature"] = data["bed_temperature"]if "error" in data:logger.error(f"Error from RPI: {data['error']}")if status == "Ready":latest_data["progress"] = 0latest_data["message"] = "Printer ready"elif status == "Processing":latest_data["progress"] = 25latest_data["message"] = "Processing G-code..."except Exception as e:logger.error(f"Error processing message from RPI: {e}")try:result = json.loads(payload)if "status" in result:status = result["status"]latest_data["status"] = statusif "command" in result and result["command"] == "capture_image" and result.get("auto_triggered", False):logger.info("receive capture command")threading.Thread(target=handle_auto_capture, args=(result,), daemon=True).start()except json.JSONDecodeError:logger.error(f"Invalid JSON in message: {payload}")71 unmodified lineslogger.error(f"Error sending parameters: {e}")return f"Error sending parameters: {e}"latest_data["status"] = "Sending"latest_data["progress"] = 10latest_data["message"] = "Sending parameters to printer..."def get_image_base64(image):if image is None:14 unmodified linesreturn Nonedef handle_auto_capture(message):try:logger.info(f"receive capture command: {message}")print_job = message.get("print_job", "unknown_job")timestamp = message.get("timestamp", time.strftime("%Y-%m-%d %H:%M:%S"))latest_data["auto_capture_requested"] = Truelatest_data["last_capture_job"] = print_joblatest_data["last_capture_time"] = timestampreturn capture_image()except Exception as e:logger.error(f"error: {e}")return None, f"capture failed: {str(e)}"def capture_image(url=None, use_test_image=False, test_image_name=None):global rpi_client, latest_dataif rpi_client is None:create_client("rpi")serial = DEFAULT_SERIALrequest_topic = f"bambu_a1_mini/request/{serial}"response_topic = f"bambu_a1_mini/response/{serial}"logger.info(f"Subscribing to {response_topic}")rpi_client.subscribe(response_topic)rpi_client.publish(request_topic,json.dumps({"command": "capture_image",}),)latest_data["image_url"] = "N/A"timeout = 45while latest_data["image_url"] == "N/A" and timeout > 0:# print("timeout", timeout)time.sleep(1)timeout -= 1url = latest_data["image_url"]if use_test_image:logger.info("Using test image instead of URL")test_img = get_test_image(test_image_name)if test_img:return test_imgelse:logger.warning("Failed to get specified test image, trying URL")if url != "N/A":try:logger.info(f"Capturing image from URL: {url}")response = requests.get(url, timeout=10)if response.status_code == 200:return Image.open(io.BytesIO(response.content))else:logger.error(f"Failed to get image from URL: {response.status_code}")except Exception as e:logger.error(f"Error capturing image from URL: {e}")else:raise Exception("url is 'N/A'")def update_print_status():global latest_datareturn (latest_data["status"],latest_data["nozzle_temperature"],latest_data["bed_temperature"],latest_data["update_time"],latest_data.get("progress", 0),latest_data.get("message", ""),)def health_check():5 unmodified lines"latest_update": latest_data["update_time"],}logger.info(f"Health check: {status}")return statusdemo = gr.Blocks(title="Bambu A1 Mini Print Control")with demo:gr.Markdown("# Bambu A1 Mini Print Control")with gr.Row():refresh_btn = gr.Button("Refresh Status")with gr.Row():current_status = gr.Textbox(label="Printer Status", value="N/A", interactive=False5 unmodified lineslabel="Current Nozzle Temperature", value="N/A", interactive=False)last_update = gr.Textbox(label="Last Update", value="N/A", interactive=False)with gr.Row():# Left column for image and capture buttonwith gr.Column(scale=2):43 unmodified linesfn=get_data,outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update],)capture_btn.click(fn=lambda: gr.update(interactive=False), outputs=capture_btn).then(fn=capture_image, outputs=[captured_image]).then(32 unmodified lineslogger.error(f"Error in capture_frame: {e}")return {"success": False, "error": str(e)}def api_send_print_parameters(nozzle_temp=200, bed_temp=60, print_speed=60, fan_speed=10069 unmodified linesapi_name="health_check",)if __name__ == "__main__":logger.info("Starting Bambu A1 Mini Print Control application")
app.py+112-309