Python大数据分析学习.module_reload

本文介绍了一种在Python中实现模块重载的方法。当修改了已加载的模块后,可以通过使用importlib库中的reload函数来更新该模块,而无需重新启动整个程序。这对于调试和开发过程特别有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当加载模块被修改后,如不重新完全执行程序,则不会再加载此模块。

因此在调试中,通常用reload模块来更新所加载模块。

from imp import reload
import table_prep_sta

#if you would like to reload the module table_prep_sta, try to use the function below:
reload(table_prep_sta)

 

# -*- coding: utf-8 -*- import threading import time import sys import inspect import ctypes import os import cv2 import numpy as np import logging from .MvCameraControl_class import * from datetime import datetime from ctypes import * from enum import Enum from ctypes import byref, cast, POINTER, c_ubyte from .MvCameraControl_class import MvCamera from .Cam_eraConstants import * from .Camera_Params_header import MV_FRAME_OUT_INFO_EX, PixelType_Gvsp_BGR8_Packed # 配置日志系统 def setup_logging(log_level=logging.INFO): """配置全局日志系统""" logging.basicConfig( level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler("camera_operation.log"), logging.StreamHandler() ] ) logging.info("日志系统初始化完成") setup_logging(logging.INFO) # 像素格式兼容处理 try: # 尝试导入像素类型定义 from .PixelType_header import * logging.info("成功从 PixelType_header 导入像素类型定义") except ImportError: try: # 尝试从父目录导入 from .PixelType_header import * logging.info("成功从全局 PixelType_header 导入像素类型定义") except ImportError: logging.warning("警告: 无法导入 PixelType_header,创建虚拟定义") # 创建必要的虚拟定义 PixelType_Gvsp_Undefined = -1 PixelType_Gvsp_Mono8 = 0x01000008 PixelType_Gvsp_BayerGR8 = 0x01080008 PixelType_Gvsp_RGB8_Packed = 0x02180014 # 定义像素格式映射表 PIXEL_FORMATS = { "MONO8": PixelType_Gvsp_Mono8 if 'PixelType_Gvsp_Mono8' in globals() else 0x01080001, "MONO10": PixelType_Gvsp_Mono10 if 'PixelType_Gvsp_Mono10' in globals() else 0x01100003, "MONO12": PixelType_Gvsp_Mono12 if 'PixelType_Gvsp_Mono12' in globals() else 0x01100005, "BAYER_BG8": PixelType_Gvsp_BayerBG8 if 'PixelType_Gvsp_BayerBG8' in globals() else 0x0108000B, "BAYER_GB8": PixelType_Gvsp_BayerGB8 if 'PixelType_Gvsp_BayerGB8' in globals() else 0x0108000A, "BAYER_GR8": PixelType_Gvsp_BayerGR8 if 'PixelType_Gvsp_BayerGR8' in globals() else 0x01080008, "BAYER_RG8": PixelType_Gvsp_BayerRG8 if 'PixelType_Gvsp_BayerRG8' in globals() else 0x01080009, "RGB8": PixelType_Gvsp_RGB8_Packed if 'PixelType_Gvsp_RGB8_Packed' in globals() else 0x02180014, "BGR8": PixelType_Gvsp_BGR8_Packed, "YUV422": PixelType_Gvsp_YUV422_Packed if 'PixelType_Gvsp_YUV422_Packed' in globals() else 0x02100032, "YUV422_YUYV": PixelType_Gvsp_YUV422_YUYV_Packed if 'PixelType_Gvsp_YUV422_YUYV_Packed' in globals() else 0x0210001F } # 像素格式枚举 class PixelFormat(Enum): MONO8 = PIXEL_FORMATS["MONO8"] MONO10 = PIXEL_FORMATS["MONO10"] MONO12 = PIXEL_FORMATS["MONO12"] BAYER_BG8 = PIXEL_FORMATS["BAYER_BG8"] BAYER_GB8 = PIXEL_FORMATS["BAYER_GB8"] BAYER_GR8 = PIXEL_FORMATS["BAYER_GR8"] BAYER_RG8 = PIXEL_FORMATS["BAYER_RG8"] RGB8 = PIXEL_FORMATS["RGB8"] YUV422 = PIXEL_FORMATS["YUV422"] YUV422_YUYV = PIXEL_FORMATS["YUV422_YUYV"] def is_mono_data(enGvspPixelType): """判断是否为单色图像格式""" mono_formats = [ PIXEL_FORMATS["MONO8"], PIXEL_FORMATS["MONO10"], PIXEL_FORMATS["MONO12"], 0x010C0004, # Mono10 Packed 0x010C0006, # Mono12 Packed 0x01080002, # Mono8 Signed 0x0110000C # Mono16 ] return enGvspPixelType in mono_formats def is_color_data(enGvspPixelType): """判断是否为彩色图像格式""" color_formats = [ # Bayer格式 PIXEL_FORMATS["BAYER_BG8"], PIXEL_FORMATS["BAYER_GB8"], PIXEL_FORMATS["BAYER_GR8"], PIXEL_FORMATS["BAYER_RG8"], 0x01100011, # BayerBG10 0x01100010, # BayerGB10 0x0110000E, # BayerGR10 0x0110000F, # BayerRG10 0x01100017, # BayerBG12 0x01100016, # BayerGB12 0x01100014, # BayerGR12 0x01100015, # BayerRG12 # YUV格式 PIXEL_FORMATS["YUV422"], PIXEL_FORMATS["YUV422_YUYV"], # RGB格式 PIXEL_FORMATS["RGB8"], 0x0220001E, # RGB10_Packed 0x02300020, # RGB12_Packed 0x02400021, # RGB16_Packed 0x02180032 # BGR8_Packed ] return enGvspPixelType in color_formats def get_pixel_format_name(pixel_value): """根据像素值获取可读的名称""" for name, value in PIXEL_FORMATS.items(): if value == pixel_value: return name return f"未知格式: 0x{pixel_value:08X}" # 强制关闭线程 def async_raise(tid, exctype): """安全终止线程""" tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread): """停止指定线程""" async_raise(thread.ident, SystemExit) # ... 前面的导入和辅助函数保持不变 ... # 相机操作类 class CameraOperation: __public_methods__ = [ 'open_device', 'close_device', 'start_grabbing', 'stop_grabbing', 'set_trigger_mode', 'set_continue_mode', 'trigger_once', 'get_parameters', 'set_param', 'save_image', 'capture_frame', 'get_current_frame', 'is_frame_available' ] # 状态码定义 MV_OK = 0 MV_E_CALLORDER = -2147483647 MV_E_PARAMETER = -2147483646 MV_E_NO_DATA = -2147483645 MV_E_SAVE_IMAGE = -2147483644 MV_E_STATE = -2147483643 MV_E_HANDLE = -2147483642 MV_E_SUPPORT = -2147483641 def __init__(self, obj_cam, st_device_list, n_connect_num=0): """ 初始化相机操作对象 :param obj_cam: 相机对象 :param st_device_list: 设备列表 :param n_connect_num: 连接编号 """ self.device_handle = None self.is_open = False # 确保cam属性存在 self.cam = obj_cam # 使用cam作为相机对象的统一引用 self.obj_cam = obj_cam # 保持旧代码兼容性 self.st_device_list = st_device_list self.n_connect_num = n_connect_num # 状态标志 - 确保所有属性初始化 self.b_open_device = False self.b_start_grabbing = False self.b_thread_running = False self.b_exit = False self.connected = False # 连接状态标志 self.b_frame_received = False # 帧接收状态 # 线程相关 self.h_thread_handle = None # 图像数据 self.st_frame_info = None self.buf_save_image = None self.n_save_image_size = 0 self.current_frame = None # 参数 self.frame_rate = 0.0 self.exposure_time = 0.0 self.gain = 0.0 # 线程安全锁 self.buf_lock = threading.Lock() # 图像缓冲区锁 self.frame_lock = threading.Lock() # 当前帧锁 self.param_lock = threading.Lock() # 参数锁 self.frame_count = 0 # 帧计数 self.last_frame_time = None # 最后帧时间 self.is_streaming = False # 取流状态 logging.info("相机操作对象初始化完成") def is_frame_available(self): """检查是否有可用帧图像""" try: # 检查是否有有效帧图像 with self.frame_lock: return self.current_frame is not None and self.current_frame.size > 0 except Exception as e: logging.error(f"检查帧可用性失败: {str(e)}") return False def capture_frame(self): """捕获当前帧""" try: with self.frame_lock: if self.current_frame is not None: return self.current_frame.copy() return None except Exception as e: logging.error(f"捕获帧失败: {str(e)}") return None def get_current_frame(self): """获取当前帧图像""" try: with self.frame_lock: if self.current_frame is not None: return self.current_frame.copy() return None except Exception as e: logging.error(f"获取图像失败: {str(e)}") return None def get_frame_info(self): """ 获取当前帧的详细信息 :return: 帧信息字典 """ info = { "available": False, "width": 0, "height": 0, "format": "未知", "size": 0 } try: with self.frame_lock: if self.current_frame is not None: info["available"] = True info["width"] = self.current_frame.shape[1] info["height"] = self.current_frame.shape[0] info["format"] = f"{self.current_frame.dtype}" info["size"] = self.current_frame.size if self.st_frame_info: info["sdk_width"] = self.st_frame_info.nWidth info["sdk_height"] = self.st_frame_info.nHeight info["sdk_format"] = get_pixel_format_name(self.st_frame_info.enPixelType) info["sdk_size"] = self.st_frame_info.nFrameLen except Exception as e: logging.exception(f"获取帧信息异常: {str(e)}") return info def set_pixel_format(self, format_name): if format_name in PIXEL_FORMATS: format_value = PIXEL_FORMATS[format_name] ret = self.obj_cam.MV_CC_SetPixelType(format_value) if ret != self.MV_OK: logging.error(f"设置像素格式失败: {hex(ret)}") return ret else: logging.error(f"不支持的像素格式: {format_name}") return self.MV_E_PARAMETER def save_frame_to_file(self, frame, file_path, save_format="bmp", quality=95): """ 将帧保存到文件 :param frame: 要保存的帧 (numpy数组) :param file_path: 文件路径 :param save_format: 保存格式 (bmp, jpg, png, tiff) :param quality: 保存质量 (仅对jpg有效) :return: 保存结果 (MV_OK 或 错误码) """ if frame is None or frame.size == 0: logging.error("无法保存无效帧: 帧为空") return self.MV_E_NO_DATA try: # 确保目录存在 directory = os.path.dirname(file_path) if directory and not os.path.exists(directory): os.makedirs(directory, exist_ok=True) # 根据格式保存图像 save_format = save_format.lower() if save_format == "bmp": cv2.imwrite(file_path, frame) elif save_format in ["jpg", "jpeg"]: cv2.imwrite(file_path, frame, [cv2.IMWRITE_JPEG_QUALITY, quality]) elif save_format == "png": cv2.imwrite(file_path, frame, [cv2.IMWRITE_PNG_COMPRESSION, 9]) elif save_format in ["tiff", "tif"]: cv2.imwrite(file_path, frame, [cv2.IMWRITE_TIFF_COMPRESSION, 1]) else: logging.error(f"不支持的图像格式: {save_format}") return self.MV_E_PARAMETER # 验证保存结果 if not os.path.exists(file_path): logging.error(f"文件保存失败: {file_path}") return self.MV_E_SAVE_IMAGE file_size = os.path.getsize(file_path) if file_size < 1024: # 小于1KB视为无效 logging.error(f"文件大小异常: {file_path} ({file_size} 字节)") os.remove(file_path) # 删除无效文件 return self.MV_E_SAVE_IMAGE logging.info(f"图像已保存: {file_path} ({file_size} 字节)") return self.MV_OK except Exception as e: logging.exception(f"保存图像异常: {str(e)}") return self.MV_E_SAVE_IMAGE def stop_grabbing(self): """停止取流""" # 关键修复:添加状态检查 if not hasattr(self, 'cam') or self.cam is None: logging.error("无法停止采集:相机对象不存在") return self.MV_E_STATE if not self.connected: logging.error("无法停止采集:相机未连接") return self.MV_E_STATE try: ret = self.cam.stop_grabbing() if ret == MV_OK: self.is_grabbing = False self.last_frame = None # 清除最后帧 self.image_buffer = [] # 清空缓冲区 return ret except Exception as e: logging.exception(f"停止采集时发生异常: {e}") return self.MV_E_STATE def is_ready(self): """检查设备是否就绪""" return self.b_open_device and not self.b_exit def open_device(self, device_index=0, access_mode=0): """打开相机设备""" if self.b_open_device: logging.warning("设备已打开,无需重复操作") return self.MV_OK if self.n_connect_num < 0: logging.error("无效的连接编号") return self.MV_E_CALLORDER try: # 选择设备并创建句柄 nConnectionNum = int(self.n_connect_num) stDeviceList = cast(self.st_device_list.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents # 确保相机对象存在 if self.obj_cam is None: self.obj_cam = MvCamera() self.cam = self.obj_cam # 确保cam属性存在 # 创建相机句柄 ret = self.obj_cam.MV_CC_CreateHandle(stDeviceList) if ret != self.MV_OK: self.obj_cam.MV_CC_DestroyHandle() logging.error(f"创建句柄失败: {hex(ret)}") return ret # 打开设备 ret = self.obj_cam.MV_CC_OpenDevice() if ret != self.MV_OK: logging.error(f"打开设备失败: {hex(ret)}") return ret # 设备已成功打开 self.b_open_device = True self.connected = True # 设置连接状态 self.b_exit = False logging.info("设备打开成功") # 探测网络最佳包大小(仅对GigE相机有效) if stDeviceList.nTLayerType in [MV_GIGE_DEVICE, MV_GENTL_GIGE_DEVICE]: nPacketSize = self.obj_cam.MV_CC_GetOptimalPacketSize() if int(nPacketSize) > 0: ret = self.obj_cam.MV_CC_SetIntValue("GevSCPSPacketSize", nPacketSize) if ret != self.MV_OK: logging.warning(f"设置包大小失败: {hex(ret)}") else: logging.warning(f"获取最佳包大小失败: {hex(nPacketSize)}") # 获取采集帧率使能状态 stBool = c_bool(False) ret = self.obj_cam.MV_CC_GetBoolValue("AcquisitionFrameRateEnable", stBool) if ret != self.MV_OK: logging.warning(f"获取帧率使能状态失败: {hex(ret)}") # 现在设备已打开,可以安全设置触发模式 ret = self.set_continue_mode() if ret != self.MV_OK: logging.warning(f"设置连续模式失败: {hex(ret)}") return self.MV_OK except Exception as e: logging.exception(f"打开设备异常: {str(e)}") # 尝试清理资源 try: if hasattr(self, 'obj_cam'): self.obj_cam.MV_CC_CloseDevice() self.obj_cam.MV_CC_DestroyHandle() except: pass self.b_open_device = False self.connected = False return self.MV_E_STATE def close_device(self): """关闭相机设备""" if not self.b_open_device: logging.warning("设备未打开,无需关闭") return self.MV_OK try: # 停止采集(如果正在采集) if self.b_start_grabbing: self.stop_grabbing() # 关闭设备 ret = self.obj_cam.MV_CC_CloseDevice() if ret != self.MV_OK: logging.error(f"关闭设备失败: {hex(ret)}") # 销毁句柄 ret = self.obj_cam.MV_CC_DestroyHandle() if ret != self.MV_OK: logging.error(f"销毁句柄失败: {hex(ret)}") self.b_open_device = False self.connected = False # 重置连接状态 self.b_exit = True logging.info("设备关闭成功") return self.MV_OK except Exception as e: logging.exception(f"关闭设备异常: {str(e)}") return self.MV_E_STATE def start_grabbing(self, winHandle=None): """开始图像采集""" if not self.b_open_device: logging.error("设备未打开,无法开始采集") return self.MV_E_CALLORDER if self.b_start_grabbing: logging.warning("采集已在进行中") return self.MV_OK try: # 开始采集 ret = self.obj_cam.MV_CC_StartGrabbing() if ret != self.MV_OK: logging.error(f"开始采集失败: {hex(ret)}") return ret self.b_start_grabbing = True self.b_exit = False # 启动采集线程 self.h_thread_handle = threading.Thread( target=self.work_thread, args=(winHandle,), daemon=True ) self.h_thread_handle.start() self.b_thread_running = True logging.info("图像采集已开始") return self.MV_OK except Exception as e: logging.exception(f"开始采集异常: {str(e)}") return self.MV_E_STATE def set_trigger_mode(self, enable=True, source=MV_TRIGGER_SOURCE_SOFTWARE): """ 设置触发模式 :param enable: 是否启用触发模式 :param source: 触发源 (默认软件触发) :return: 操作结果 """ if not self.b_open_device: logging.error("设备未打开,无法设置触发模式") return self.MV_E_CALLORDER try: mode = MV_TRIGGER_MODE_ON if enable else MV_TRIGGER_MODE_OFF ret = self.obj_cam.MV_CC_SetEnumValue("TriggerMode", mode) if ret != self.MV_OK: logging.error(f"设置触发模式失败: {hex(ret)}") return ret if enable: ret = self.obj_cam.MV_CC_SetEnumValue("TriggerSource", source) if ret != self.MV_OK: logging.error(f"设置触发源失败: {hex(ret)}") return ret logging.info(f"触发模式设置成功: {'启用' if enable else '禁用'}") return self.MV_OK except Exception as e: logging.exception(f"设置触发模式异常: {str(e)}") return self.MV_E_STATE def set_continue_mode(self): """设置连续采集模式""" # 添加设备状态检查 if not self.b_open_device: logging.error("设备未打开,无法设置连续模式") return self.MV_E_CALLORDER logging.info("尝试设置连续采集模式") try: # 禁用触发模式 ret = self.obj_cam.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF) if ret != self.MV_OK: logging.error(f"禁用触发模式失败: {hex(ret)}") return ret # 设置采集模式为连续 ret = self.obj_cam.MV_CC_SetEnumValue("AcquisitionMode", 2) # 2表示连续采集 if ret != self.MV_OK: logging.error(f"设置连续采集模式失败: {hex(ret)}") return ret logging.info("连续采集模式设置成功") return self.MV_OK except Exception as e: logging.exception(f"设置连续模式异常: {str(e)}") return self.MV_E_STATE def trigger_once(self): """执行一次软触发""" if not self.b_open_device: logging.error("设备未打开,无法触发") return self.MV_E_CALLORDER try: ret = self.obj_cam.MV_CC_SetCommandValue("TriggerSoftware") if ret != self.MV_OK: logging.error(f"软触发失败: {hex(ret)}") return ret logging.info("软触发成功") return self.MV_OK except Exception as e: logging.exception(f"软触发异常: {str(e)}") return self.MV_E_STATE def get_parameters(self): """获取相机参数""" if not self.b_open_device: logging.error("设备未打开,无法获取参数") return self.MV_E_CALLORDER try: # 使用锁保护参数访问 with self.param_lock: # 初始化返回值为整数错误码 return_code = self.MV_OK # 帧率 stFrameRate = MVCC_FLOATVALUE() memset(byref(stFrameRate), 0, sizeof(MVCC_FLOATVALUE)) ret = self.obj_cam.MV_CC_GetFloatValue("AcquisitionFrameRate", stFrameRate) if ret == self.MV_OK: self.frame_rate = stFrameRate.fCurValue logging.debug(f"获取帧率成功: {self.frame_rate}") else: logging.warning(f"获取帧率失败: {hex(ret)}") if return_code == self.MV_OK: # 保留第一个错误码 return_code = ret # 曝光时间 stExposure = MVCC_FLOATVALUE() memset(byref(stExposure), 0, sizeof(MVCC_FLOATVALUE)) ret = self.obj_cam.MV_CC_GetFloatValue("ExposureTime", stExposure) if ret == self.MV_OK: self.exposure_time = stExposure.fCurValue logging.debug(f"获取曝光时间成功: {self.exposure_time}") else: logging.warning(f"获取曝光时间失败: {hex(ret)}") if return_code == self.MV_OK: return_code = ret # 增益 stGain = MVCC_FLOATVALUE() memset(byref(stGain), 0, sizeof(MVCC_FLOATVALUE)) ret = self.obj_cam.MV_CC_GetFloatValue("Gain", stGain) if ret == self.MV_OK: self.gain = stGain.fCurValue logging.debug(f"获取增益成功: {self.gain}") else: logging.warning(f"获取增益失败: {hex(ret)}") if return_code == self.MV_OK: return_code = ret # 返回整数错误码 return return_code except Exception as e: logging.exception(f"获取参数异常: {str(e)}") return self.MV_E_STATE # 添加兼容拼写错误的方法 def get_parame(self): """兼容拼写错误的方法名:get_parame""" logging.warning("调用get_parame方法 - 可能是拼写错误,建议使用get_parameters()") return self.get_parameters() # 添加动态属性处理 def __getattr__(self, name): # 处理保存方法 if name == "save_image": logging.warning("动态处理save_image调用 - 映射到save_image") return self.save_image if name == "save_bmp": logging.warning("动态处理save_bmp调用 - 映射到save_bmp") return self.save_bmp # 处理其他可能的拼写错误 method_map = { "get_parame": self.get_parame, "get_parm": self.get_parameters, "get_parmeter": self.get_parameters, "get_parma": self.get_parameters, "get_parameter": self.get_parameters, "get_param": self.get_parameters } if name in method_map: logging.warning(f"动态处理{name}调用 - 可能是拼写错误") return method_map[name] # 关键修复:处理b_frame_received属性 if name == "b_frame_received": logging.warning("动态访问b_frame_received属性 - 提供默认值") return False # 关键修复:处理cam属性 if name == "cam": if not hasattr(self, 'obj_cam') or self.obj_cam is None: raise AttributeError( f"'{type(self).__name__}' 对象没有 'cam' 属性。" "可能原因: 1) 相机未初始化 2) 连接未建立" ) return self.obj_cam raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") def set_param(self, frame_rate=None, exposure_time=None, gain=None): """ 设置相机参数 :param frame_rate: 帧率 (None表示不修改) :param exposure_time: 曝光时间 (None表示不修改) :param gain: 增益 (None表示不修改) :return: 操作结果 """ if not self.b_open_device: logging.error("设备未打开,无法设置参数") return self.MV_E_CALLORDER try: # 使用锁保护参数修改 with self.param_lock: # 禁用自动曝光 ret = self.obj_cam.MV_CC_SetEnumValue("ExposureAuto", 0) if ret != self.MV_OK: logging.warning(f"禁用自动曝光失败: {hex(ret)}") # 设置帧率 if frame_rate is not None: ret = self.obj_cam.MV_CC_SetFloatValue("AcquisitionFrameRate", float(frame_rate)) if ret != self.MV_OK: logging.error(f"设置帧率失败: {hex(ret)}") return ret self.frame_rate = float(frame_rate) # 设置曝光时间 if exposure_time is not None: ret = self.obj_cam.MV_CC_SetFloatValue("ExposureTime", float(exposure_time)) if ret != self.MV_OK: logging.error(f"设置曝光时间失败: {hex(ret)}") return ret self.exposure_time = float(exposure_time) # 设置增益 if gain is not None: ret = self.obj_cam.MV_CC_SetFloatValue("Gain", float(gain)) if ret != self.MV_OK: logging.error(f"设置增益失败: {hex(ret)}") return ret self.gain = float(gain) logging.info(f"参数设置成功: 帧率={self.frame_rate}, 曝光={self.exposure_time}, 增益={self.gain}") return self.MV_OK except Exception as e: logging.exception(f"设置参数异常: {str(e)}") return self.MV_E_STATE def work_thread(self, winHandle=None): """图像采集工作线程""" stOutFrame = MV_FRAME_OUT() memset(byref(stOutFrame), 0, sizeof(stOutFrame)) logging.info("采集线程启动") while not self.b_exit: try: # 获取图像缓冲区 ret = self.obj_cam.MV_CC_GetImageBuffer(stOutFrame, 1000) if ret != self.MV_OK: if ret != self.MV_E_NO_DATA: # 忽略无数据错误 logging.warning(f"获取图像缓冲区失败: {hex(ret)}") time.sleep(0.01) continue # 更新帧信息 self.st_frame_info = stOutFrame.stFrameInfo # 关键修复:标记帧已接收 self.b_frame_received = True # 记录像素格式信息 pixel_format = get_pixel_format_name(self.st_frame_info.enPixelType) logging.debug(f"获取到图像: {self.st_frame_info.nWidth}x{self.st_frame_info.nHeight}, " f"格式: {pixel_format}, 大小: {self.st_frame_info.nFrameLen}字节") # 分配/更新图像缓冲区 frame_size = stOutFrame.stFrameInfo.nFrameLen with self.buf_lock: if self.buf_save_image is None or self.n_save_image_size < frame_size: self.buf_save_image = (c_ubyte * frame_size)() self.n_save_image_size = frame_size # 复制图像数据 cdll.msvcrt.memcpy(byref(self.buf_save_image), stOutFrame.pBufAddr, frame_size) # 更新当前帧 self.update_current_frame() # 显示图像(如果指定了窗口句柄) if winHandle is not None: stDisplayParam = MV_DISPLAY_FRAME_INFO() memset(byref(stDisplayParam), 0, sizeof(stDisplayParam)) stDisplayParam.hWnd = int(winHandle) stDisplayParam.nWidth = self.st_frame_info.nWidth stDisplayParam.nHeight = self.st_frame_info.nHeight stDisplayParam.enPixelType = self.st_frame_info.enPixelType stDisplayParam.pData = self.buf_save_image stDisplayParam.nDataLen = frame_size self.obj_cam.MV_CC_DisplayOneFrame(stDisplayParam) # 释放图像缓冲区 self.obj_cam.MV_CC_FreeImageBuffer(stOutFrame) except Exception as e: logging.exception(f"采集线程异常: {str(e)}") time.sleep(0.1) # 清理资源 with self.buf_lock: if self.buf_save_image is not None: del self.buf_save_image self.buf_save_image = None self.n_save_image_size = 0 logging.info("采集线程退出") def update_current_frame(self): """将原始图像数据转换为OpenCV格式并存储""" if not self.st_frame_info or not self.buf_save_image: logging.warning("更新当前帧时缺少帧信息或缓冲区") return try: # 获取图像信息 width = self.st_frame_info.nWidth height = self.st_frame_info.nHeight pixel_type = self.st_frame_info.enPixelType # 复制缓冲区数据 with self.buf_lock: buffer_copy = bytearray(self.buf_save_image) # 转换为numpy数组 np_buffer = np.frombuffer(buffer_copy, dtype=np.uint8) # 根据像素类型处理图像 frame = None if is_mono_data(pixel_type): # 单色图像 frame = np_buffer.reshape(height, width) elif pixel_type == PIXEL_FORMATS["BAYER_BG8"]: # Bayer BG格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerBG2RGB) elif pixel_type == PIXEL_FORMATS["BAYER_GB8"]: # Bayer GB格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerGB2RGB) elif pixel_type == PIXEL_FORMATS["BAYER_GR8"]: # Bayer GR格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerGR2RGB) elif pixel_type == PIXEL_FORMATS["BAYER_RG8"]: # Bayer RG格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerRG2RGB) elif pixel_type == PIXEL_FORMATS["RGB8"]: # RGB格式 frame = np_buffer.reshape(height, width, 3) elif pixel_type in [PIXEL_FORMATS["YUV422"], PIXEL_FORMATS["YUV422_YUYV"]]: # YUV格式 frame = cv2.cvtColor(np_buffer.reshape(height, width, 2), cv2.COLOR_YUV2RGB_YUYV) else: # 尝试自动处理其他格式 if pixel_type in [PIXEL_FORMATS["MONO10"], PIXEL_FORMATS["MONO12"]]: # 10位或12位单色图像需要特殊处理 frame = self.process_high_bit_depth(np_buffer, width, height, pixel_type) else: logging.warning(f"不支持的像素格式: {get_pixel_format_name(pixel_type)}") return # 更新当前帧 - 使用线程安全锁 with self.frame_lock: self.current_frame = frame logging.debug(f"当前帧更新成功: {frame.shape if frame is not None else '无数据'}") except Exception as e: logging.exception(f"更新当前帧异常: {str(e)}") # 调试:保存原始数据用于分析 try: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") debug_path = f"frame_debug_{timestamp}.bin" with open(debug_path, "wb") as f: f.write(buffer_copy) logging.info(f"已保存原始帧数据到: {debug_path}") except: logging.error("保存调试帧数据失败") def process_high_bit_depth(self, buffer, width, height, pixel_type): """处理高位深度图像格式""" try: # 10位或12位图像处理 if pixel_type == PIXEL_FORMATS["MONO10"]: # 将10位数据转换为16位 data_16bit = np.frombuffer(buffer, dtype=np.uint16) # 10位数据存储方式:每个像素占用2字节,但只有10位有效 data_16bit = (data_16bit >> 6) # 右移6位使10位数据对齐到低10位 frame = data_16bit.reshape(height, width).astype(np.uint16) elif pixel_type == PIXEL_FORMATS["MONO12"]: # 将12位数据转换为16位 data_16bit = np.frombuffer(buffer, dtype=np.uint16) # 12位数据存储方式:每个像素占用2字节,但只有12位有效 data_16bit = (data_16bit >> 4) # 右移4位使12位数据对齐到低12位 frame = data_16bit.reshape(height, width).astype(np.uint16) else: logging.warning(f"不支持的高位深度格式: {get_pixel_format_name(pixel_type)}") return None # 归一化到8位用于显示(如果需要) frame_8bit = cv2.convertScaleAbs(frame, alpha=(255.0/4095.0)) return frame_8bit except Exception as e: logging.exception(f"处理高位深度图像异常: {str(e)}") return None def save_image(self, file_path, save_format="bmp", quality=95): """ 安全保存当前帧到文件 - 使用原始缓冲区数据 """ if not self.b_open_device or not self.b_start_grabbing: logging.error("设备未就绪,无法保存图像") return self.MV_E_CALLORDER # 使用缓冲区锁确保数据一致性 with self.buf_lock: if not self.buf_save_image or not self.st_frame_info: logging.error("无可用图像数据") return self.MV_E_NO_DATA # 获取图像信息 width = self.st_frame_info.nWidth height = self.st_frame_info.nHeight pixel_type = self.st_frame_info.enPixelType frame_size = self.st_frame_info.nFrameLen # 复制缓冲区数据 buffer_copy = bytearray(self.buf_save_image) try: # 确保目录存在 directory = os.path.dirname(file_path) if directory and not os.path.exists(directory): os.makedirs(directory, exist_ok=True) logging.info(f"创建目录: {directory}") # 根据像素类型处理图像 np_buffer = np.frombuffer(buffer_copy, dtype=np.uint8) # 根据像素格式转换图像 if is_mono_data(pixel_type): # 单色图像 frame = np_buffer.reshape(height, width) elif pixel_type == PIXEL_FORMATS["BAYER_BG8"]: # Bayer BG格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerBG2BGR) elif pixel_type == PIXEL_FORMATS["BAYER_GB8"]: # Bayer GB格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerGB2BGR) elif pixel_type == PIXEL_FORMATS["BAYER_GR8"]: # Bayer GR格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerGR2BGR) elif pixel_type == PIXEL_FORMATS["BAYER_RG8"]: # Bayer RG格式 frame = cv2.cvtColor(np_buffer.reshape(height, width), cv2.COLOR_BayerRG2BGR) elif pixel_type == PIXEL_FORMATS["RGB8"]: # RGB格式 frame = np_buffer.reshape(height, width, 3) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) elif pixel_type in [PIXEL_FORMATS["YUV422"], PIXEL_FORMATS["YUV422_YUYV"]]: # YUV格式 frame = cv2.cvtColor(np_buffer.reshape(height, width, 2), cv2.COLOR_YUV2BGR_YUYV) else: # 尝试自动处理其他格式 if pixel_type in [PIXEL_FORMATS["MONO10"], PIXEL_FORMATS["MONO12"]]: # 10位或12位单色图像需要特殊处理 frame = self.process_high_bit_depth(np_buffer, width, height, pixel_type) else: logging.error(f"不支持的像素格式: {get_pixel_format_name(pixel_type)}") return self.MV_E_PARAMETER # 根据格式保存图像 save_format = save_format.lower() try: if save_format == "bmp": cv2.imwrite(file_path, frame) elif save_format in ["jpg", "jpeg"]: cv2.imwrite(file_path, frame, [cv2.IMWRITE_JPEG_QUALITY, quality]) elif save_format == "png": cv2.imwrite(file_path, frame, [cv2.IMWRITE_PNG_COMPRESSION, 9]) elif save_format in ["tiff", "tif"]: cv2.imwrite(file_path, frame, [cv2.IMWRITE_TIFF_COMPRESSION, 1]) else: logging.error(f"不支持的图像格式: {save_format}") return self.MV_E_PARAMETER # 验证保存结果 if not os.path.exists(file_path): logging.error(f"文件保存失败: {file_path}") return self.MV_E_SAVE_IMAGE file_size = os.path.getsize(file_path) if file_size < 1024: # 小于1KB视为无效 logging.error(f"文件大小异常: {file_path} ({file_size} 字节)") os.remove(file_path) # 删除无效文件 return self.MV_E_SAVE_IMAGE logging.info(f"图像已保存: {file_path} ({file_size} 字节)") return self.MV_OK except Exception as e: logging.exception(f"保存图像异常: {str(e)}") return self.MV_E_SAVE_IMAGE except Exception as e: logging.exception(f"图像处理异常: {str(e)}") return self.MV_E_SAVE_IMAGE # 兼容旧方法的保存接口 def save_jpg(self, file_path=None, quality=95): """保存为JPEG格式""" if file_path is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") file_path = f"capture_{timestamp}.jpg" return self.save_image(file_path, "jpg", quality) def save_bmp(self, file_path=None): """保存为BMP格式""" if file_path is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") file_path = f"capture_{timestamp}.bmp" return self.save_image(file_path, "bmp") def save_png(self, file_path=None): """保存为PNG格式""" if file_path is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") file_path = f"capture_{timestamp}.png" return self.save_image(file_path, "png") def save_tiff(self, file_path=None): """保存为TIFF格式""" if file_path is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") file_path = f"capture_{timestamp}.tiff" return self.save_image(file_path, "tiff") # 新增方法:获取帧状态详细信息 def get_frame_status(self): """获取当前帧状态详细信息""" # 安全访问b_frame_received属性 frame_received = getattr(self, 'b_frame_received', False) status = { "camera_open": self.b_open_device, "grabbing_started": self.b_start_grabbing, "thread_running": self.b_thread_running, "frame_received": frame_received, # 使用安全访问 "frame_size": self.n_save_image_size if self.buf_save_image else 0, "current_frame": self.current_frame is not None, "connected": self.connected # 新增连接状态 } if self.st_frame_info: status.update({ "width": self.st_frame_info.nWidth, "height": self.st_frame_info.nHeight, "pixel_format": get_pixel_format_name(self.st_frame_info.enPixelType), "frame_num": self.st_frame_info.nFrameNum }) return status # 析构函数确保资源释放 def __del__(self): """确保相机资源被正确释放""" try: if self.b_start_grabbing: self.stop_grabbing() if self.b_open_device: self.close_device() except Exception as e: logging.error(f"析构函数中释放资源失败: {str(e)}") 可是我这个Cam_Operation_class.py里的命名就是小写啊
07-14
E:\AI_System\web_ui>python server.py Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 16, in <module> from flask_socketio import SocketIO, emit ModuleNotFoundError: No module named 'flask_socketio' # E:\AI_System\web_ui\server.py import sys import os import time import logging import json import traceback import threading import platform import psutil import importlib import datetime from pathlib import Path from flask import Flask, jsonify, request, render_template, send_from_directory from logging.handlers import TimedRotatingFileHandler from flask_socketio import SocketIO, emit from core.config import system_config as config # 导入必要的模块(假设这些模块存在) try: from environment.hardware_manager import create_hardware_manager from cognitive_arch.life_scheduler import LifeScheduler from agent.autonomous_agent import AutonomousAgent from environment.environment_manager import EnvironmentManager from environment.environment_state import EnvironmentState from environment.spatial_simulator import SpatialSimulator from environment.db_manager import DatabaseManager except ImportError as e: logging.warning(f"部分模块导入失败: {str(e)} - 使用模拟实现") # ========== 全局协调器 ========== coordinator = None def register_coordinator(coord): """注册意识系统协调器""" global coordinator coordinator = coord if coordinator and hasattr(coordinator, 'connect_to_ui'): coordinator.connect_to_ui(update_ui) def update_ui(event): """更新UI事件处理""" if 'socketio' in globals(): socketio.emit('system_event', event) # ========== 初始化日志系统 ========== def setup_logger(): """配置全局日志系统""" # 确保日志目录存在 config.LOG_DIR.mkdir(parents=True, exist_ok=True) # 创建主日志记录器 logger = logging.getLogger('WebServer') logger.setLevel(getattr(logging, config.LOG_LEVEL.upper(), logging.INFO)) # 日志格式 log_formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) # 文件日志处理器 (每天轮换,保留30天) file_handler = TimedRotatingFileHandler( config.LOG_DIR / 'web_server.log', when='midnight', backupCount=30, encoding='utf-8' ) file_handler.setFormatter(log_formatter) logger.addHandler(file_handler) # 控制台日志处理器 console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) # 安全日志处理装饰器 def safe_logger(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except UnicodeEncodeError: new_args = [] for arg in args: if isinstance(arg, str): new_args.append(arg.encode('ascii', 'ignore').decode('ascii')) else: new_args.append(arg) return func(*new_args, **kwargs) return wrapper # 应用安全日志处理 for level in ['debug', 'info', 'warning', 'error', 'critical']: setattr(logger, level, safe_logger(getattr(logger, level))) return logger # 初始化日志 logger = setup_logger() # ========== 系统初始化 ========== class SystemInitializer: """负责初始化系统核心组件""" def __init__(self): self.base_dir = Path(__file__).resolve().parent.parent self.ai_core = None self.hardware_manager = None self.life_scheduler = None self.ai_agent = None self.start_time = time.time() self.environment_manager = None def initialize_system_paths(self): """初始化系统路径""" sys.path.insert(0, str(self.base_dir)) logger.info(f"项目根目录: {self.base_dir}") sub_dirs = ['agent', 'core', 'utils', 'config', 'cognitive_arch', 'environment'] for sub_dir in sub_dirs: full_path = self.base_dir / sub_dir if full_path.exists(): sys.path.insert(0, str(full_path)) logger.info(f"添加路径: {full_path}") else: logger.warning(f"目录不存在: {full_path}") def initialize_environment_manager(self): """初始化环境管理器""" try: env_config = { 'update_interval': 1.0, 'spatial': {'grid_size': 1.0} } self.environment_manager = EnvironmentManager(env_config) self.environment_manager.start() logger.info("✅ 环境管理器初始化成功") return self.environment_manager except Exception as e: logger.error(f"❌ 环境管理器初始化失败: {str(e)}") logger.warning("⚠️ 环境交互功能将不可用") return None def initialize_ai_core(self): """初始化AI核心系统""" class AICore: def __init__(self, base_dir): self.base_dir = Path(base_dir) self.genetic_code = self.load_genetic_code() self.physical_state = { "health": 100, "energy": 100, "mood": "calm" } self.dependencies = self.scan_dependencies() def load_genetic_code(self): code_path = self.base_dir / "core" / "genetic_code.py" try: with open(code_path, "r", encoding="utf-8") as f: return f.read() except FileNotFoundError: return "# 默认遗传代码\nclass AICore:\n pass" def scan_dependencies(self): return { "nervous_system": "flask", "memory": "sqlite", "perception": "opencv", "reasoning": "transformers" } def mutate(self, new_code): try: code_path = self.base_dir / "core" / "genetic_code.py" with open(code_path, "w", encoding="utf-8") as f: f.write(new_code) importlib.reload(sys.modules['core.genetic_code']) self.genetic_code = new_code return True, "核心代码更新成功,系统已进化" except Exception as e: return False, f"进化失败: {str(e)}" def wear_dependency(self, dependency_name, version): self.dependencies[dependency_name] = version return f"已穿戴 {dependency_name}@{version}" def get_state(self): return { "genetic_code_hash": hash(self.genetic_code), "dependencies": self.dependencies, "physical_state": self.physical_state, "hardware_environment": self.get_hardware_info() } def get_hardware_info(self): return { "cpu": platform.processor(), "gpu": "NVIDIA RTX 3090" if psutil.virtual_memory().total > 16 * 1024 ** 3 else "Integrated", "memory_gb": round(psutil.virtual_memory().total / (1024 ** 3), 1), "storage_gb": round(psutil.disk_usage('/').total / (1024 ** 3), 1) } self.ai_core = AICore(self.base_dir) logger.info("✅ AI核心系统初始化完成") return self.ai_core def initialize_hardware_manager(self): """初始化硬件管理器""" try: config_path = config.CONFIG_DIR / "hardware_config.json" self.hardware_manager = create_hardware_manager(config_path) logger.info("✅ 硬件管理器初始化成功") return self.hardware_manager except Exception as e: logger.error(f"❌ 硬件管理器初始化失败: {str(e)}") logger.warning("⚠️ 使用内置简单硬件管理器") class SimpleHardwareManager: def __init__(self): self.available_hardware = { "cpu": ["Intel i9-13900K", "AMD Ryzen 9 7950X", "Apple M2 Max"], "gpu": ["NVIDIA RTX 4090", "AMD Radeon RX 7900 XTX", "Apple M2 GPU"], "memory": [16, 32, 64, 128], "storage": ["1TB SSD", "2TB SSD", "4TB SSD", "8TB HDD"], "peripherals": ["4K Camera", "3D Scanner", "High-Fidelity Microphone"] } self.current_setup = { "cpu": platform.processor(), "gpu": "Integrated Graphics", "memory": round(psutil.virtual_memory().total / (1024 ** 3), 1), "storage": round(psutil.disk_usage('/').total / (1024 ** 3), 1) } def request_hardware(self, hardware_type, specification): if hardware_type not in self.available_hardware: return False, f"不支持硬件类型: {hardware_type}" if specification not in self.available_hardware[hardware_type]: return False, f"不支持的规格: {specification}" self.current_setup[hardware_type] = specification return True, f"已请求 {hardware_type}: {specification}。请管理员完成安装。" def get_current_setup(self): return self.current_setup def get_performance_metrics(self): return { "cpu_usage": psutil.cpu_percent(), "memory_usage": psutil.virtual_memory().percent, "disk_usage": psutil.disk_usage('/').percent, "cpu_temp": 45.0, "gpu_temp": 55.0, "network_io": { "sent": psutil.net_io_counters().bytes_sent, "received": psutil.net_io_counters().bytes_recv }, "last_updated": datetime.datetime.now().isoformat() } self.hardware_manager = SimpleHardwareManager() return self.hardware_manager def initialize_life_scheduler(self): """初始化生活调度器""" try: config.MODEL_CACHE_DIR.mkdir(parents=True, exist_ok=True) self.life_scheduler = LifeScheduler() logger.info("✅ 生活调度器初始化成功") life_thread = threading.Thread( target=self._update_life_status, daemon=True, name="LifeSystemThread" ) life_thread.start() logger.info("✅ 生活系统后台线程已启动") return self.life_scheduler except Exception as e: logger.error(f"❌ 生活调度器初始化失败: {str(e)}") return None def _update_life_status(self): logger.info("🚦 生活系统后台线程启动") while True: try: now = datetime.datetime.now() current_hour = now.hour if 8 <= current_hour < 9: self.life_scheduler.wake_up() elif 12 <= current_hour < 13: self.life_scheduler.have_meal("lunch") elif 19 <= current_hour < 20: self.life_scheduler.have_meal("dinner") elif 23 <= current_hour or current_hour < 6: self.life_scheduler.go_to_sleep() self.life_scheduler.log_activity("系统状态更新") time.sleep(60) except Exception as e: logger.error(f"生活系统更新失败: {str(e)}", exc_info=True) time.sleep(300) def initialize_ai_agent(self): """初始化AI智能体""" try: config.MODEL_CACHE_DIR.mkdir(parents=True, exist_ok=True) self.ai_agent = AutonomousAgent( model_path=config.AGENT_PATH, cache_dir=config.MODEL_CACHE_DIR, use_gpu=config.USE_GPU, default_model=config.DEFAULT_MODEL ) logger.info("✅ AI智能体初始化成功") return self.ai_agent except Exception as e: logger.error(f"❌ AI智能体初始化失败: {str(e)}") return None def start_evolution_monitor(self): def monitor(): while True: try: cpu_usage = psutil.cpu_percent() mem_usage = psutil.virtual_memory().percent if cpu_usage > 80: self.ai_core.physical_state["energy"] = max(20, self.ai_core.physical_state["energy"] - 5) self.ai_core.physical_state["mood"] = "strained" elif cpu_usage < 30: self.ai_core.physical_state["energy"] = min(100, self.ai_core.physical_state["energy"] + 2) if self.hardware_manager: current_hw = self.ai_core.get_hardware_info() requested_hw = self.hardware_manager.get_current_setup() for hw_type, spec in requested_hw.items(): if current_hw.get(hw_type) != spec: if hw_type == "cpu": self.ai_core.physical_state["health"] = min(100, self.ai_core.physical_state[ "health"] + 10) elif hw_type == "gpu": self.ai_core.physical_state["energy"] = min(100, self.ai_core.physical_state[ "energy"] + 20) time.sleep(60) except Exception as e: logging.error(f"进化监控错误: {str(e)}") time.sleep(300) monitor_thread = threading.Thread(target=monitor, daemon=True) monitor_thread.start() logger.info("✅ 进化监控线程已启动") def initialize_all(self): logger.info("=" * 50) logger.info("🚀 开始初始化AI系统") logger.info("=" * 50) self.initialize_system_paths() self.initialize_ai_core() self.initialize_hardware_manager() self.initialize_life_scheduler() self.initialize_ai_agent() self.initialize_environment_manager() self.start_evolution_monitor() logger.info("✅ 所有系统组件初始化完成") return { "ai_core": self.ai_core, "hardware_manager": self.hardware_manager, "life_scheduler": self.life_scheduler, "ai_agent": self.ai_agent, "environment_manager": self.environment_manager } # ========== Flask应用工厂 ========== def create_app(): app = Flask( __name__, template_folder='templates', static_folder='static', static_url_path='/static' ) app.secret_key = config.SECRET_KEY system_initializer = SystemInitializer() components = system_initializer.initialize_all() app.config['SYSTEM_COMPONENTS'] = components app.config['START_TIME'] = system_initializer.start_time app.config['BASE_DIR'] = system_initializer.base_dir # 初始化SocketIO app.config['SOCKETIO'] = SocketIO(app, cors_allowed_origins="*", async_mode='threading') # 注册路由 register_routes(app) register_error_handlers(app) return app # ========== 环境交互路由 ========== def register_environment_routes(app): @app.route('/environment') def environment_view(): return render_template('environment_view.html') @app.route('/api/environment/state', methods=['GET']) def get_environment_state(): env_manager = app.config['SYSTEM_COMPONENTS'].get('environment_manager') if not env_manager: return jsonify({"success": False, "error": "环境管理器未初始化"}), 503 try: state = env_manager.get_state() return jsonify(state.to_dict()) except Exception as e: app.logger.error(f"获取环境状态失败: {traceback.format_exc()}") return jsonify({"success": False, "error": str(e)}), 500 @app.route('/api/environment/action', methods=['POST']) def execute_environment_action(): env_manager = app.config['SYSTEM_COMPONENTS'].get('environment_manager') if not env_manager: return jsonify({"success": False, "error": "环境管理器未初始化"}), 503 try: data = request.json action = data.get('action') params = data.get('params', {}) if not action: return jsonify({"success": False, "error": "缺少动作参数"}), 400 success = env_manager.execute_action(action, params) return jsonify({"success": success, "action": action}) except Exception as e: app.logger.error(f"执行环境动作失败: {traceback.format_exc()}") return jsonify({"success": False, "error": str(e)}), 500 # ========== 环境状态广播 ========== def setup_environment_broadcast(app): socketio = app.config['SOCKETIO'] @socketio.on('connect', namespace='/environment') def handle_environment_connect(): app.logger.info('客户端已连接环境WebSocket') @socketio.on('disconnect', namespace='/environment') def handle_environment_disconnect(): app.logger.info('客户端已断开环境WebSocket') def broadcast_environment_state(): env_manager = app.config['SYSTEM_COMPONENTS'].get('environment_manager') if not env_manager: return while True: try: state = env_manager.get_state() socketio.emit('environment_update', state.to_dict(), namespace='/environment') time.sleep(1) except Exception as e: app.logger.error(f"环境状态广播失败: {str(e)}") time.sleep(5) broadcast_thread = threading.Thread( target=broadcast_environment_state, daemon=True, name="EnvironmentBroadcastThread" ) broadcast_thread.start() app.logger.info("✅ 环境状态广播线程已启动") # ========== 路由注册 ========== def register_routes(app): register_environment_routes(app) setup_environment_broadcast(app) @app.route('/') def index(): return render_template('agent_interface.html') @app.route('/static/<path:filename>') def static_files(filename): try: return send_from_directory(app.static_folder, filename) except Exception as e: app.logger.error(f"静态文件服务失败: {filename} - {str(e)}") return jsonify({"error": "文件未找到"}), 404 @app.route('/status') def status(): try: components = app.config['SYSTEM_COMPONENTS'] status_data = { "server": { "status": "running", "uptime": time.time() - app.config['START_TIME'], "version": "1.0.0", "config": { "host": config.HOST, "port": config.PORT, "log_level": config.LOG_LEVEL, "default_model": config.DEFAULT_MODEL } }, "core": components['ai_core'].get_state(), "hardware": components['hardware_manager'].get_current_setup() } if components['environment_manager']: try: status_data["environment"] = components['environment_manager'].get_state().to_dict() except Exception as e: status_data["environment"] = {"error": str(e)} if components['life_scheduler']: try: status_data["life_system"] = components['life_scheduler'].get_current_state() except Exception as e: status_data["life_system"] = {"error": str(e)} if components['ai_agent']: try: status_data["agent"] = components['ai_agent'].get_status() except Exception as e: status_data["agent"] = {"error": str(e)} return jsonify(status_data) except Exception as e: app.logger.error(f"获取状态失败: {traceback.format_exc()}") return jsonify({"error": "内部错误", "details": str(e)}), 500 # 核心系统路由 @app.route('/api/core/state') def get_core_state(): return jsonify(app.config['SYSTEM_COMPONENTS']['ai_core'].get_state()) @app.route('/api/core/mutate', methods=['POST']) def mutate_core(): data = request.get_json() new_code = data.get('genetic_code') if not new_code: return jsonify({"success": False, "error": "缺少遗传代码"}), 400 success, message = app.config['SYSTEM_COMPONENTS']['ai_core'].mutate(new_code) return jsonify({"success": success, "message": message}) @app.route('/api/core/wear', methods=['POST']) def wear_dependency(): data = request.get_json() dep_name = data.get('dependency') version = data.get('version', 'latest') if not dep_name: return jsonify({"success": False, "error": "缺少依赖名称"}), 400 result = app.config['SYSTEM_COMPONENTS']['ai_core'].wear_dependency(dep_name, version) return jsonify({"success": True, "message": result}) # 硬件管理路由 @app.route('/api/hardware/catalog') def get_hardware_catalog(): return jsonify(app.config['SYSTEM_COMPONENTS']['hardware_manager'].available_hardware) @app.route('/api/hardware/request', methods=['POST']) def request_hardware(): data = request.get_json() hw_type = data.get('type') spec = data.get('specification') if not hw_type or not spec: return jsonify({"success": False, "error": "缺少硬件类型或规格"}), 400 success, message = app.config['SYSTEM_COMPONENTS']['hardware_manager'].request_hardware(hw_type, spec) return jsonify({"success": success, "message": message}) @app.route('/api/hardware/current') def get_current_hardware(): return jsonify(app.config['SYSTEM_COMPONENTS']['hardware_manager'].get_current_setup()) # 生活系统路由 @app.route('/life') def life_dashboard(): return render_template('life_dashboard.html') @app.route('/api/life/status') def get_life_status(): components = app.config['SYSTEM_COMPONENTS'] if not components['life_scheduler']: return jsonify({"success": False, "error": "生活系统未初始化"}), 503 try: current_state = components['life_scheduler'].get_current_state() recent_activities = components['life_scheduler'].get_recent_activities(10) return jsonify({ "success": True, "current_activity": current_state.get("current_activity", "未知"), "next_scheduled": current_state.get("next_scheduled", "未知"), "schedule": components['life_scheduler'].daily_schedule, "recent_activities": recent_activities, "energy_level": current_state.get("energy_level", 100), "mood": current_state.get("mood", "平静") }) except Exception as e: app.logger.error(f"获取生活状态失败: {traceback.format_exc()}") return jsonify({"success": False, "error": str(e)}), 500 @app.route('/adjust_schedule', methods=['POST']) def adjust_schedule(): components = app.config['SYSTEM_COMPONENTS'] if not components['life_scheduler']: return jsonify({"success": False, "error": "生活系统未初始化"}), 503 try: data = request.json adjustments = data.get("adjustments", {}) valid_activities = ["wake_up", "breakfast", "lunch", "dinner", "sleep"] for activity, new_time in adjustments.items(): if activity not in valid_activities: return jsonify({"success": False, "error": f"无效的活动类型: {activity}"}), 400 if not isinstance(new_time, str) or len(new_time) != 5 or new_time[2] != ':': return jsonify({"success": False, "error": f"无效的时间格式: {new_time}"}), 400 components['life_scheduler'].adjust_schedule(adjustments) return jsonify({ "success": True, "message": "计划表已更新", "new_schedule": components['life_scheduler'].daily_schedule }) except Exception as e: app.logger.error(f"调整作息时间失败: {traceback.format_exc()}") return jsonify({"success": False, "error": str(e)}), 400 # 聊天路由 @app.route('/chat', methods=['POST']) def chat(): components = app.config['SYSTEM_COMPONENTS'] if not components['ai_agent']: return jsonify({"error": "Agent未初始化"}), 503 try: data = request.get_json() user_input = data.get('message', '') user_id = data.get('user_id', 'default') if not user_input: return jsonify({"error": "消息内容不能为空"}), 400 app.logger.info(f"聊天请求: 用户={user_id}, 内容长度={len(user_input)}") response = components['ai_agent'].process_input(user_input, user_id) return jsonify({"response": response}) except Exception as e: app.logger.error(f"聊天处理失败: {traceback.format_exc()}") return jsonify({"error": "聊天处理失败", "details": str(e)}), 500 # 家具管理路由 furniture_cache = {} CACHE_DURATION = 3600 # 1小时 @app.route('/api/furniture') def get_furniture(): try: room = request.args.get('room', 'workshop') app.logger.info(f"获取家具数据: 房间={room}") current_time = time.time() if room in furniture_cache and current_time - furniture_cache[room]['timestamp'] < CACHE_DURATION: return jsonify(furniture_cache[room]['data']) furniture_data = { "workshop": [ {"type": "desk", "position": {"x": 0, "y": -1.5, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "chair", "position": {"x": 0, "y": -1.5, "z": -1}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "bookshelf", "position": {"x": 3, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "computer", "position": {"x": 0.5, "y": -0.5, "z": -3.2}, "rotation": {"x": 0, "y": 0, "z": 0}} ], "living_room": [ {"type": "sofa", "position": {"x": 0, "y": 0, "z": -2}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "tv", "position": {"x": 0, "y": 1.5, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}} ], "bedroom": [ {"type": "bed", "position": {"x": 0, "y": 0, "z": -3}, "rotation": {"x": 0, "y": 0, "z": 0}}, {"type": "nightstand", "position": {"x": 1.5, "y": 0, "z": -2.5}, "rotation": {"x": 0, "y": 0, "z": 0}} ] } furniture_cache[room] = { 'timestamp': current_time, 'data': furniture_data.get(room, []) } return jsonify(furniture_cache[room]['data']) except Exception as e: app.logger.error(f"获取家具数据失败: {traceback.format_exc()}") return jsonify({"error": "内部错误", "details": str(e)}), 500 # ========== 错误处理器 ========== def register_error_handlers(app): @app.errorhandler(404) def page_not_found(error): app.logger.warning(f"404错误: {request.path}") return jsonify({ "error": "资源未找到", "path": request.path, "method": request.method }), 404 @app.errorhandler(500) def internal_server_error(error): app.logger.error(f"500错误: {str(error)}") return jsonify({ "error": "服务器内部错误", "message": "系统遇到意外错误,请稍后重试" }), 500 @app.errorhandler(Exception) def handle_general_exception(error): app.logger.error(f"未处理异常: {traceback.format_exc()}") return jsonify({ "error": "未处理的异常", "type": type(error).__name__, "message": str(error) }), 500 # ========== WebSocket处理 ========== def setup_websocket_handlers(socketio): @socketio.on('connect') def handle_connect(): logger.info('客户端已连接') socketio.emit('system_status', {'status': 'ready'}) @socketio.on('disconnect') def handle_disconnect(): logger.info('客户端已断开连接') @socketio.on('user_message') def handle_user_message(data): user_id = data.get('user_id', 'guest') message = data.get('message', '') logger.info(f"收到来自 {user_id} 的消息: {message}") # 处理消息逻辑 response = f"已收到您的消息: {message}" # 如果有协调器,使用协调器处理 global coordinator if coordinator: try: response = coordinator.process_message(message) except Exception as e: logger.error(f"协调器处理消息失败: {str(e)}") socketio.emit('agent_response', { 'user_id': user_id, 'response': response }) # ========== 主程序入口 ========== if __name__ == '__main__': try: app = create_app() socketio = app.config['SOCKETIO'] # 设置WebSocket处理器 setup_websocket_handlers(socketio) # 启动服务器 socketio.run( app, host=config.HOST, port=config.PORT, debug=config.DEBUG, use_reloader=False ) logger.info(f"服务器运行在 http://{config.HOST}:{config.PORT}") except KeyboardInterrupt: logger.info("服务器关闭") except Exception as e: logger.critical(f"服务器启动失败: {str(e)}") logger.error(traceback.format_exc())
最新发布
08-11
Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.polynomial.polyutils failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\polynomial\polyutils.py", line 26, in <module> from numpy._core.multiarray import dragon4_positional, dragon4_scientific File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.polynomial.polynomial failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\polynomial\polynomial.py", line 85, in <module> from numpy.lib.array_utils import normalize_axis_index File "D:\annaCONDA\Lib\site-packages\numpy\lib\array_utils.py", line 1, in <module> from ._array_utils_impl import ( # noqa: F401 File "D:\annaCONDA\Lib\site-packages\numpy\lib\_array_utils_impl.py", line 4, in <module> from numpy._core import asarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.polynomial.chebyshev failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\polynomial\chebyshev.py", line 112, in <module> from numpy.lib.array_utils import normalize_axis_index File "D:\annaCONDA\Lib\site-packages\numpy\lib\array_utils.py", line 1, in <module> from ._array_utils_impl import ( # noqa: F401 File "D:\annaCONDA\Lib\site-packages\numpy\lib\_array_utils_impl.py", line 4, in <module> from numpy._core import asarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.polynomial.legendre failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\polynomial\legendre.py", line 84, in <module> from numpy.lib.array_utils import normalize_axis_index File "D:\annaCONDA\Lib\site-packages\numpy\lib\array_utils.py", line 1, in <module> from ._array_utils_impl import ( # noqa: F401 File "D:\annaCONDA\Lib\site-packages\numpy\lib\_array_utils_impl.py", line 4, in <module> from numpy._core import asarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.polynomial.hermite failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\polynomial\hermite.py", line 80, in <module> from numpy.lib.array_utils import normalize_axis_index File "D:\annaCONDA\Lib\site-packages\numpy\lib\array_utils.py", line 1, in <module> from ._array_utils_impl import ( # noqa: F401 File "D:\annaCONDA\Lib\site-packages\numpy\lib\_array_utils_impl.py", line 4, in <module> from numpy._core import asarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.polynomial.hermite_e failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\polynomial\hermite_e.py", line 80, in <module> from numpy.lib.array_utils import normalize_axis_index File "D:\annaCONDA\Lib\site-packages\numpy\lib\array_utils.py", line 1, in <module> from ._array_utils_impl import ( # noqa: F401 File "D:\annaCONDA\Lib\site-packages\numpy\lib\_array_utils_impl.py", line 4, in <module> from numpy._core import asarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.polynomial.laguerre failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\polynomial\laguerre.py", line 80, in <module> from numpy.lib.array_utils import normalize_axis_index File "D:\annaCONDA\Lib\site-packages\numpy\lib\array_utils.py", line 1, in <module> from ._array_utils_impl import ( # noqa: F401 File "D:\annaCONDA\Lib\site-packages\numpy\lib\_array_utils_impl.py", line 4, in <module> from numpy._core import asarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.ma.core failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 455, in superreload if not append_obj(module, old_objects, name, obj): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 423, in append_obj in_module = hasattr(obj, "__module__") and obj.__module__ == module.__name__ ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\site-packages\numpy\core\umath.py", line 2, in __getattr__ from numpy._core import umath File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy.ma.extras failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 22, in <module> from . import multiarray File "D:\annaCONDA\Lib\site-packages\numpy\_core\multiarray.py", line 11, in <module> from . import _multiarray_umath, overrides ImportError: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\ma\extras.py", line 28, in <module> from numpy.lib._function_base_impl import _ureduce File "D:\annaCONDA\Lib\site-packages\numpy\lib\_function_base_impl.py", line 9, in <module> import numpy._core.numeric as _nx File "D:\annaCONDA\Lib\site-packages\numpy\_core\__init__.py", line 48, in <module> raise ImportError(msg) from exc ImportError: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.11 from "D:\annaCONDA\python.exe" * The NumPy version is: "2.3.1" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed while importing _multiarray_umath: 找不到指定的模块。 ] [autoreload of numpy failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\numpy\__init__.py", line 125, in <module> from numpy.__config__ import show_config ImportError: cannot import name 'show_config' from 'numpy.__config__' (D:\annaCONDA\Lib\site-packages\numpy\__config__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 475, in superreload module = reload(module) ^^^^^^^^^^^^^^ File "D:\annaCONDA\Lib\importlib\__init__.py", line 169, in reload _bootstrap._exec(spec, module) File "<frozen importlib._bootstrap>", line 621, in _exec File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\annaCONDA\Lib\site-packages\numpy\__init__.py", line 130, in <module> raise ImportError(msg) from e ImportError: Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python interpreter from there. ] [autoreload of typing_extensions failed: Traceback (most recent call last): File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 276, in check superreload(m, reload, self.old_objects) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 500, in superreload update_generic(old_obj, new_obj) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 397, in update_generic update(a, b) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 365, in update_class update_instances(old, new) File "D:\annaCONDA\Lib\site-packages\IPython\extensions\autoreload.py", line 323, in update_instances object.__setattr__(ref, "__class__", new) TypeError: can't apply this __setattr__ to _ProtocolMeta object ] 开始测试数据库连接... 错误详情请查看日志文件: C:\Users\Lenovo\nepu_qa_project\db_test.log ❌ 测试失败,请检查日志获取详情
07-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值