@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)什么意思??

Ehcache集成Hibernate缓存
本文介绍如何在Hibernate中集成Ehcache作为二级缓存方案,并提供了详细的配置步骤及缓存策略选择建议。

从hibernate2.1开始ehcache已经作为hibernate的默认缓存方案(二级缓存方案 sessionfactory级别), 在项目中有针对性的使用缓存将对性能的提升右很大的帮助。

  要使用 Ehcache:需要一下步骤

  一,classpath添加相应的jar(ehcache,commons-logging)

  二,然后在hibernate.cfg.xml中配置

<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
 <property name="cache.use_second_level_cache">true</property>
 <property name="cache.use_query_cache">true</property>

  说明:如果没有配置<property name="cache.use_second_level_cache">true</property>(默认false) 将会产生根据单个id查询的情况(产生很多sql)。

  三,为需要缓存的类添加缓存标示:

  使用mapping文件时需要添加node :

  Java代码  

@Entity 
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

  如果使用使用hibernate annoation是使用@Cache(usage=CacheConcurrencyStrategy.)标签,有5种可选的缓存方案:

  1,CacheConcurrencyStrategy.NONE

  不适用,默认

  2.  CacheConcurrencyStrategy.NONSTRICT_READ_WRITE

  更新不频繁几个小时或更长

  3,CacheConcurrencyStrategy.READ_ONLY

  对于不发生改变的数据使用 [size=large][/size]

  4,CacheConcurrencyStrategy.READ_WRITE


  基于时间戳判定机制,,对于数据同步要求严格的情况,使用频繁

  5,CacheConcurrencyStrategy.TRANSACTIONAL

  运行在jta环境种,基于事务

import tensorrt as trt import numpy as np import time import pycuda.driver as cuda import pycuda.autoinit # 自定义INT8校准器类(兼容TensorRT 8.x+) class MyCalibrator(trt.IInt8EntropyCalibrator2): def __init__(self, batch_size=1, input_shape=(1, 3, 224, 224), cache_file="calibration.cache"): trt.IInt8EntropyCalibrator2.__init__(self) self.batch_size = batch_size self.input_shape = input_shape self.cache_file = cache_file # 生成随机校准数据(实际应用中应使用真实数据集) self.data = np.random.randn(100, *input_shape).astype(np.float32) self.current_index = 0 # 分配设备内存 self.device_input = cuda.mem_alloc(self.data[0].nbytes * self.batch_size) def get_batch_size(self): return self.batch_size def get_batch(self, names): if self.current_index + self.batch_size > len(self.data): return None batch = self.data[self.current_index:self.current_index+self.batch_size] self.current_index += self.batch_size # 将数据复制到设备 cuda.memcpy_htod(self.device_input, batch.tobytes()) return [int(self.device_input)] def read_calibration_cache(self): # 如果存在缓存,跳校准 try: with open(self.cache_file, "rb") as f: return f.read() except FileNotFoundError: return None def write_calibration_cache(self, cache): with open(self.cache_file, "wb") as f: f.write(cache) # 创建简单网络(使用 add_pooling_nd 替代 add_pooling) def create_network(): logger = trt.Logger(trt.Logger.WARNING) builder = trt.Builder(logger) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)) # 定义输入 input_tensor = network.add_input("input", trt.DataType.FLOAT, (1, 3, 224, 224)) # 添加卷积层(模拟ResNet-18第一层) conv1 = network.add_convolution_nd( input=input_tensor, num_output_maps=64, kernel_shape=(7, 7), kernel=np.random.randn(64, 3, 7, 7).astype(np.float32).ravel(), bias=np.random.randn(64).astype(np.float32) ) # 设置步长和填充(直接赋值属性) conv1.stride_nd = (2, 2) # 使用元组而不是列表 conv1.padding_nd = (3, 3) # 添加池化层(使用 add_pooling_nd) pool1 = network.add_pooling_nd( input=conv1.get_output(0), type=trt.PoolingType.MAX, window_size=(3, 3) # 直接传递元组 ) pool1.stride_nd = (2, 2) # 设置池化步长 # 展平输出为二维张量(N, C*H*W) flatten = network.add_shuffle(pool1.get_output(0)) # 计算展平后的维度:64通道 * 56高度 * 56宽度 flatten.reshape_dims = (1, 64 * 56 * 56) # 使用元组而不是trt.Dims # 添加全连接层权重 weights = np.random.randn(1000, 64 * 56 * 56).astype(np.float32) weights_layer = network.add_constant((1000, 64 * 56 * 56), weights) # 添加全连接层偏置 bias = np.random.randn(1000).astype(np.float32) bias_layer = network.add_constant((1000,), bias) # 矩阵乘法:[input] @ [weights.T] + [bias] matmul = network.add_matrix_multiply( flatten.get_output(0), trt.MatrixOperation.NONE, weights_layer.get_output(0), trt.MatrixOperation.TRANSPOSE ) bias_add = network.add_elementwise( matmul.get_output(0), bias_layer.get_output(0), trt.ElementWiseOperation.SUM ) # 标记输出 bias_add.get_output(0).name = "output" network.mark_output(bias_add.get_output(0)) return builder, network, logger # 主测试函数 def int8_perf_test(): # 创建网络 builder, network, logger = create_network() # 配置INT8量化 config = builder.create_builder_config() config.set_flag(trt.BuilderFlag.INT8) config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 1 << 30) # 1GB工作空间 # 创建校准器并设置给配置 calib = MyCalibrator(batch_size=1, input_shape=(1, 3, 224, 224), cache_file="calibration.cache") config.int8_calibrator = calib # 使用新校准器接口 # 使用新API构建引擎(解决build_engine缺失问题) serialized_engine = builder.build_serialized_network(network, config) if serialized_engine is None: print("Engine序列化构建失败!") return # 反序列化引擎 runtime = trt.Runtime(logger) engine = runtime.deserialize_cuda_engine(serialized_engine) if not engine: print("Engine反序列化失败!") return # 创建执行上下文 context = engine.create_execution_context() # 准备输入输出缓冲区 input_shape = (1, 3, 224, 224) output_shape = (1, 1000) host_input = np.random.randn(*input_shape).astype(np.float32) host_output = np.empty(output_shape, dtype=np.float32) # 分配设备内存 d_input = cuda.mem_alloc(host_input.nbytes) d_output = cuda.mem_alloc(host_output.nbytes) bindings = [int(d_input), int(d_output)] # 创建CUDA流 stream = cuda.Stream() # 预热 for _ in range(5): cuda.memcpy_htod_async(d_input, host_input, stream) context.execute_async_v2(bindings=bindings, stream_handle=stream.handle) cuda.memcpy_dtoh_async(host_output, d_output, stream) stream.synchronize() # 正式测试 start = time.time() for _ in range(100): cuda.memcpy_htod_async(d_input, host_input, stream) context.execute_async_v2(bindings=bindings, stream_handle=stream.handle) cuda.memcpy_dtoh_async(host_output, d_output, stream) stream.synchronize() total_time = time.time() - start # 计算INT8 TOPS(基于ResNet-18的3.9G MACs) # 注意:INT8操作数 = MACs × 2(乘加各算一次操作) ops = 3.9e9 * 2 # ResNet-18的INT8操作数 tops = (ops * 100) / (total_time * 1e12) # 100次推理 print(f"INT8 TOPS: {tops:.2f} TOPS") print(f"总推理时间: {total_time:.4f}秒, 平均延迟: {total_time*10:.2f}毫秒") # 清理资源 del context del engine if __name__ == "__main__": int8_perf_test() 运行报错 jp@jp-Super-Server:~/test$ python3 TensorRT_int8.py /home/jp/test/TensorRT_int8.py:115: DeprecationWarning: Use Deprecated in TensorRT 10.1. Superseded by explicit quantization. instead. config.int8_calibrator = calib # 使用新校准器接口 [06/17/2025-22:46:30] [TRT] [E] ITensor::getDimensions: Error Code 4: Shape Error (reshape changes volume. Reshaping [1,64,55,55] to [1,200704].) [06/17/2025-22:46:30] [TRT] [E] IBuilder::buildSerializedNetwork: Error Code 4: API Usage Error ((Unnamed Layer* 2) [Shuffle]: volume mismatch. Input dimensions [1,64,55,55] have volume 193600 and output dimensions [1,200704] have volume 200704.) Engine序列化构建失败! 请检查全部代码,给出完整的修改后代码
06-18
import os import random import tkinter as tk from tkinter import filedialog, messagebox, ttk import shutil import hashlib import time import pefile import os import sys class ExeProtectorApp: def __init__(self, root): self.root = root self.root.title("EXE文件保护工具 v4.1") self.root.geometry("750x680") self.root.resizable(True, True) # 设置中文字体 self.style = ttk.Style() self.style.configure("TLabel", font=("SimHei", 10)) self.style.configure("TButton", font=("SimHei", 10)) self.style.configure("TProgressbar", thickness=20) # 创建主框架 self.main_frame = ttk.Frame(root, padding="20") self.main_frame.pack(fill=tk.BOTH, expand=True) # 文件选择部分 ttk.Label(self.main_frame, text="选择EXE文件:").grid(row=0, column=0, sticky=tk.W, pady=5) self.file_path_var = tk.StringVar() ttk.Entry(self.main_frame, textvariable=self.file_path_var, width=50).grid(row=0, column=1, padx=5, pady=5) ttk.Button(self.main_frame, text="浏览...", command=self.browse_file).grid(row=0, column=2, padx=5, pady=5) # 输出目录选择 ttk.Label(self.main_frame, text="输出目录:").grid(row=1, column=0, sticky=tk.W, pady=5) self.output_dir_var = tk.StringVar() ttk.Entry(self.main_frame, textvariable=self.output_dir_var, width=50).grid(row=1, column=1, padx=5, pady=5) ttk.Button(self.main_frame, text="浏览...", command=self.browse_output_dir).grid(row=1, column=2, padx=5, pady=5) # 选项设置 options_frame = ttk.LabelFrame(self.main_frame, text="选项", padding="10") options_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=10) ttk.Label(options_frame, text="随机字节增加范围 (KB):").grid(row=0, column=0, sticky=tk.W, pady=5) self.min_size_var = tk.IntVar(value=100) ttk.Entry(options_frame, textvariable=self.min_size_var, width=10).grid(row=0, column=1, padx=5, pady=5) ttk.Label(options_frame, text="至").grid(row=0, column=2, padx=5, pady=5) self.max_size_var = tk.IntVar(value=500) ttk.Entry(options_frame, textvariable=self.max_size_var, width=10).grid(row=0, column=3, padx=5, pady=5) ttk.Label(options_frame, text="随机性强度:").grid(row=0, column=4, sticky=tk.W, pady=5) self.random_strength = tk.StringVar(value="中") strength_options = ttk.Combobox(options_frame, textvariable=self.random_strength, state="readonly", width=12) strength_options['values'] = ("低", "中", "高") strength_options.grid(row=0, column=5, padx=5, pady=5) ttk.Label(options_frame, text="模拟程序类型:").grid(row=1, column=0, sticky=tk.W, pady=5) self.app_type = tk.StringVar(value="通用程序") app_types = ttk.Combobox(options_frame, textvariable=self.app_type, state="readonly", width=15) app_types['values'] = ("通用程序", "游戏程序", "办公软件", "系统工具", "开发工具") app_types.grid(row=1, column=1, padx=5, pady=5) self.process_method = tk.StringVar(value="standard") ttk.Radiobutton(options_frame, text="标准保护", variable=self.process_method, value="standard").grid(row=1, column=2, sticky=tk.W, pady=5) ttk.Radiobutton(options_frame, text="高级保护", variable=self.process_method, value="advanced").grid(row=1, column=3, sticky=tk.W, pady=5) # 高级选项 advanced_frame = ttk.LabelFrame(self.main_frame, text="保护选项", padding="10") advanced_frame.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=10) self.obfuscate_resources = tk.BooleanVar(value=True) ttk.Checkbutton(advanced_frame, text="混淆资源文件", variable=self.obfuscate_resources).grid(row=0, column=0, sticky=tk.W, pady=5) self.encrypt_sections = tk.BooleanVar(value=True) ttk.Checkbutton(advanced_frame, text="轻度代码变换", variable=self.encrypt_sections).grid(row=0, column=1, sticky=tk.W, pady=5) self.add_dummy_sections = tk.BooleanVar(value=True) ttk.Checkbutton(advanced_frame, text="添加随机数据块", variable=self.add_dummy_sections).grid(row=1, column=0, sticky=tk.W, pady=5) self.randomize_imports = tk.BooleanVar(value=True) ttk.Checkbutton(advanced_frame, text="随机化导入表顺序", variable=self.randomize_imports).grid(row=1, column=1, sticky=tk.W, pady=5) # 处理按钮 ttk.Button(self.main_frame, text="保护文件", command=self.process_file).grid(row=4, column=0, columnspan=3, pady=20) # 状态和进度条 self.status_var = tk.StringVar(value="就绪") ttk.Label(self.main_frame, textvariable=self.status_var).grid(row=5, column=0, columnspan=2, sticky=tk.W, pady=5) self.progress_var = tk.DoubleVar(value=0) self.progress_bar = ttk.Progressbar(self.main_frame, variable=self.progress_var, length=100) self.progress_bar.grid(row=5, column=2, sticky=(tk.W, tk.E), pady=5) # 默认输出目录 self.output_dir_var.set(os.path.join(os.getcwd(), "protected_exes")) # 绑定窗口关闭事件 self.root.protocol("WM_DELETE_WINDOW", self.on_closing) # 初始化随机种子 self.initialize_random_seed() def initialize_random_seed(self): seed_material = ( time.time_ns().to_bytes(8, 'big') + os.getpid().to_bytes(4, 'big') + os.urandom(16) ) seed = int.from_bytes(hashlib.sha256(seed_material).digest(), 'big') random.seed(seed) def browse_file(self): file_path = filedialog.askopenfilename(filetypes=[("可执行文件", "*.exe"), ("所有文件", "*.*")]) if file_path: self.file_path_var.set(file_path) def browse_output_dir(self): dir_path = filedialog.askdirectory() if dir_path: self.output_dir_var.set(dir_path) def process_file(self): exe_path = self.file_path_var.get() output_dir = self.output_dir_var.get() if not exe_path: messagebox.showerror("错误", "请选择一个EXE文件") return if not os.path.exists(exe_path): messagebox.showerror("错误", "选择的文件不存在") return if not output_dir: messagebox.showerror("错误", "请选择输出目录") return if not os.path.exists(output_dir): try: os.makedirs(output_dir) except: messagebox.showerror("错误", "无法创建输出目录") return file_name, file_ext = os.path.splitext(os.path.basename(exe_path)) random_suffix = hashlib.md5(str(time.time_ns()).encode()).hexdigest()[:8] output_path = os.path.join(output_dir, f"{file_name}_protected_{random_suffix}{file_ext}") try: self.status_var.set("正在处理文件...") self.progress_var.set(0) self.root.update() min_size = self.min_size_var.get() max_size = self.max_size_var.get() if min_size < 0 or max_size < 0 or min_size > max_size: messagebox.showerror("错误", "请设置有效的字节增加范围") return strength_factor = 1.0 if self.random_strength.get() == "高": strength_factor = 1.5 elif self.random_strength.get() == "低": strength_factor = 0.5 adjusted_min = int(min_size * strength_factor) adjusted_max = int(max_size * strength_factor) random_size_kb = random.randint(adjusted_min, adjusted_max) random_size_bytes = random_size_kb * 1024 shutil.copy2(exe_path, output_path) original_hash = self.calculate_file_hash(exe_path) self.progress_var.set(5) self.root.update() if self.process_method.get() == "standard": self.standard_protection(output_path, random_size_bytes) else: self.advanced_protection(output_path, random_size_bytes) modified_hash = self.calculate_file_hash(output_path) self.progress_var.set(95) self.root.update() if self.verify_exe_file(output_path): self.status_var.set("文件处理完成") self.progress_var.set(100) messagebox.showinfo( "成功", f"文件保护成功!\n" f"原始文件大小: {os.path.getsize(exe_path) // 1024} KB\n" f"处理后文件大小: {os.path.getsize(output_path) // 1024} KB\n" f"增加了: {random_size_kb} KB\n\n" f"原始文件哈希 (MD5): {original_hash}\n" f"处理后文件哈希 (MD5): {modified_hash}\n\n" f"文件已保存至: {output_path}" ) else: self.status_var.set("文件验证失败") self.progress_var.set(100) messagebox.showwarning("警告", "处理后的文件可能需要在特定环境运行") except Exception as e: self.status_var.set("处理过程中出错") messagebox.showerror("错误", f"处理文件时出错: {str(e)}") finally: self.progress_var.set(0) self.initialize_random_seed() def calculate_file_hash(self, file_path): hash_md5 = hashlib.md5() with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def standard_protection(self, file_path, additional_bytes): try: pe = pefile.PE(file_path) section_count = random.randint(1, 3) for _ in range(section_count): new_section = pefile.SectionStructure(pe.__IMAGE_SECTION_HEADER_format__) new_section.Name = self.generate_sane_section_name() section_size = random.randint(0x1000, 0x8000) new_section.Misc_VirtualSize = section_size base_virtual_address = (pe.sections[-1].VirtualAddress + pe.sections[-1].Misc_VirtualSize + 0x1000 - 1) & ~0xFFF new_section.VirtualAddress = base_virtual_address + random.randint(0, 0x1000) base_raw_data = (pe.sections[-1].PointerToRawData + pe.sections[-1].SizeOfRawData + 0x1000 - 1) & ~0xFFF new_section.PointerToRawData = base_raw_data + random.randint(0, 0x1000) new_section.SizeOfRawData = section_size section_flags = [0xC0000040, 0x40000040, 0x20000040, 0x80000040, 0x00000040, 0xE0000040] new_section.Characteristics = random.choice(section_flags) app_type = self.app_type.get() new_data = self.generate_application_specific_data(section_size, app_type) pe.set_bytes_at_offset(new_section.PointerToRawData, new_data) pe.sections.append(new_section) pe.FILE_HEADER.NumberOfSections += 1 pe.OPTIONAL_HEADER.SizeOfImage = (new_section.VirtualAddress + new_section.Misc_VirtualSize + 0x1000 - 1) & ~0xFFF if self.encrypt_sections.get(): self.apply_mild_code_transformations(pe) if self.randomize_imports.get() and hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'): random.shuffle(pe.DIRECTORY_ENTRY_IMPORT) self.safe_modify_exe_file(file_path, additional_bytes) pe.FILE_HEADER.TimeDateStamp = int(time.time()) + random.randint(-3600, 3600) pe.write(file_path) pe.close() except Exception as e: print(f"标准保护执行: {e}") self.safe_modify_exe_file(file_path, additional_bytes) def advanced_protection(self, file_path, additional_bytes): try: pe = pefile.PE(file_path) section_count = random.randint(2, 4) for _ in range(section_count): new_section = pefile.SectionStructure(pe.__IMAGE_SECTION_HEADER_format__) new_section.Name = self.generate_sane_section_name() section_size = random.randint(0x1000, 0x10000) new_section.Misc_VirtualSize = section_size base_virtual_address = (pe.sections[-1].VirtualAddress + pe.sections[-1].Misc_VirtualSize + 0x1000 - 1) & ~0xFFF new_section.VirtualAddress = base_virtual_address + random.randint(0, 0x2000) base_raw_data = (pe.sections[-1].PointerToRawData + pe.sections[-1].SizeOfRawData + 0x1000 - 1) & ~0xFFF new_section.PointerToRawData = base_raw_data + random.randint(0, 0x2000) new_section.SizeOfRawData = section_size section_flags = [0xC0000040, 0x40000040, 0x20000040, 0x80000040, 0x00000040, 0xE0000040, 0x00000080, 0x40000080] new_section.Characteristics = random.choice(section_flags) app_type = self.app_type.get() new_data = self.generate_application_specific_data(section_size, app_type) pe.set_bytes_at_offset(new_section.PointerToRawData, new_data) pe.sections.append(new_section) pe.FILE_HEADER.NumberOfSections += 1 pe.OPTIONAL_HEADER.SizeOfImage = (new_section.VirtualAddress + new_section.Misc_VirtualSize + 0x1000 - 1) & ~0xFFF if self.encrypt_sections.get(): self.apply_mild_code_transformations(pe) if self.obfuscate_resources.get() and hasattr(pe, 'DIRECTORY_ENTRY_RESOURCE'): self.obfuscate_pe_resources(pe) if self.randomize_imports.get() and hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'): for _ in range(random.randint(1, 3)): random.shuffle(pe.DIRECTORY_ENTRY_IMPORT) if self.add_dummy_sections.get(): dummy_size = random.randint(additional_bytes // 2, additional_bytes) self.safe_modify_exe_file(file_path, dummy_size) additional_bytes -= dummy_size self.safe_modify_exe_file(file_path, additional_bytes) pe.FILE_HEADER.TimeDateStamp = int(time.time()) + random.randint(-86400, 86400) pe.write(file_path) pe.close() except Exception as e: print(f"高级保护执行: {e}") self.standard_protection(file_path, additional_bytes) def safe_modify_exe_file(self, file_path, additional_bytes): with open(file_path, 'ab') as f: app_type = self.app_type.get() data = self.generate_application_specific_data(additional_bytes, app_type) f.write(data) def generate_application_specific_data(self, size, app_type): data = bytearray() type_templates = { "通用程序": [ b"C:\\Program Files\\Common Files\\\x00", b"HKLM\\Software\\Microsoft\\Windows\\\x00", b"ERROR_ACCESS_DENIED\x00", b"SUCCESS\x00", b"CONFIG_FILE\x00", b"LOG_FILE\x00", (0x00000001).to_bytes(4, 'little'), (0x00000100).to_bytes(4, 'little'), (0x00010000).to_bytes(4, 'little'), ], "游戏程序": [ b"C:\\Program Files\\Game\\Data\\\x00", b"C:\\Users\\Public\\Documents\\GameSaves\\\x00", b"TEXTURE_", b"MODEL_", b"SOUND_", b"LEVEL_", b"SCORE_", b"PLAYER_", b"ENEMY_", b"WEAPON_", (0x000F4240).to_bytes(4, 'little'), (0x000003E8).to_bytes(4, 'little'), ], "办公软件": [ b"C:\\Users\\%USERNAME%\\Documents\\\x00", b"File Format: DOCX\x00", b"File Format: XLSX\x00", b"Page ", b"Sheet ", b"Table ", b"Font ", b"Style ", b"Paragraph ", b"Header", b"Footer", (0x0000000A).to_bytes(4, 'little'), (0x00000014).to_bytes(4, 'little'), ], "系统工具": [ b"C:\\Windows\\System32\\\x00", b"C:\\Windows\\SysWOW64\\\x00", b"HKLM\\SYSTEM\\CurrentControlSet\\\x00", b"Driver ", b"Service ", b"Device ", b"Registry ", b"Process ", b"Thread ", (0x00000001).to_bytes(4, 'little'), (0x00000000).to_bytes(4, 'little'), (0xFFFFFFFF).to_bytes(4, 'little'), ], "开发工具": [ b"C:\\Program Files\\Developer\\SDK\\\x00", b"C:\\Users\\%USERNAME%\\Source\\\x00", b"Compiler ", b"Linker ", b"Debugger ", b"Library ", b"Include ", b"Namespace ", b"Class ", b"Function ", b"Variable ", (0x00000000).to_bytes(4, 'little'), (0x00000001).to_bytes(4, 'little'), (0x00000002).to_bytes(4, 'little'), ] } templates = type_templates.get(app_type, type_templates["通用程序"]) template_usage = 0.7 if self.random_strength.get() == "高": template_usage = 0.5 elif self.random_strength.get() == "低": template_usage = 0.9 while len(data) < size: if random.random() < template_usage: data.extend(random.choice(templates)) else: random_len = random.randint(1, 64) data.extend(os.urandom(random_len)) if random.random() < 0.3: data.extend(b'\x00' * random.randint(1, 8)) elif random.random() < 0.2: data.extend(b' ' * random.randint(1, 16)) return data[:size] def generate_sane_section_name(self): base_names = [ b'.data', b'.rdata', b'.text', b'.rsrc', b'.reloc', b'.bss', b'.edata', b'.idata', b'.pdata', b'.tls', b'.data1', b'.rdata2', b'.text1', b'.rsrc1', b'.data_', b'.rdata_', b'.text_', b'.rsrc_', b'.init', b'.fini', b'.ctors', b'.dtors', b'.gnu', b'.note', b'.eh_frame', b'.debug' ] name = random.choice(base_names) if random.random() < 0.7: if random.random() < 0.5: suffix = str(random.randint(10, 99)).encode() else: suffix = bytes(random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(2)) name = name[:8-len(suffix)] + suffix return name.ljust(8, b'\x00')[:8] def apply_mild_code_transformations(self, pe): text_section = None for section in pe.sections: if b'.text' in section.Name: text_section = section break if text_section: data = pe.get_data(text_section.VirtualAddress, text_section.SizeOfRawData) if not isinstance(data, bytes): data = bytes(data) data_list = list(data) transform_count = len(data_list) // 200 if self.random_strength.get() == "高": transform_count = len(data_list) // 100 elif self.random_strength.get() == "低": transform_count = len(data_list) // 400 transform_count = min(100, transform_count) for _ in range(transform_count): i = random.randint(0, len(data_list) - 1) transform_type = random.choice([0, 1, 2, 3, 4]) if transform_type == 0: data_list[i] = (data_list[i] + 1) % 256 elif transform_type == 1: data_list[i] = (data_list[i] - 1) % 256 elif transform_type == 2: data_list[i] ^= 0xFF elif transform_type == 3: data_list[i] = (data_list[i] << 1) % 256 else: data_list[i] = (data_list[i] >> 1) % 256 pe.set_bytes_at_offset(text_section.PointerToRawData, bytes(data_list)) def obfuscate_pe_resources(self, pe): try: for resource_type in pe.DIRECTORY_ENTRY_RESOURCE.entries: if hasattr(resource_type, 'directory'): for resource_id in resource_type.directory.entries: if hasattr(resource_id, 'directory'): for resource_lang in resource_id.directory.entries: data_rva = resource_lang.data.struct.OffsetToData size = resource_lang.data.struct.Size resource_data = list(pe.get_data(data_rva, size)) step_size = 200 if self.random_strength.get() == "高": step_size = 100 elif self.random_strength.get() == "低": step_size = 400 for i in range(0, len(resource_data), random.randint(step_size-50, step_size+50)): if i < len(resource_data): if random.random() < 0.3: resource_data[i] = (resource_data[i] + random.randint(1, 5)) % 256 elif random.random() < 0.6: resource_data[i] = (resource_data[i] - random.randint(1, 5)) % 256 else: resource_data[i] ^= random.randint(1, 255) pe.set_bytes_at_offset(data_rva, bytes(resource_data)) except Exception as e: print(f"资源混淆错误: {e}") def verify_exe_file(self, file_path): try: pe = pefile.PE(file_path) pe.close() return True except: return False def on_closing(self): if messagebox.askokcancel("退出", "确定要退出程序吗?"): self.root.destroy() if __name__ == "__main__": root = tk.Tk() app = ExeProtectorApp(root) root.mainloop() 用户希望输出的程序每次都会有静态特征变化 绕过QVM 将代码段熵值降到最低 在此基础上修改
07-11
# 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 datetime from pathlib import Path from flask import Flask, jsonify, request, render_template from logging.handlers import TimedRotatingFileHandler from flask_socketio import SocketIO, emit # 在server.py中添加健康检查路由 from flask import jsonify @app.route('/system/health') def health_check(): """系统健康检查接口""" components = { 'ai_core': True, # 实际应替换为状态检测函数 'hardware_manager': True, 'scheduler': True, 'environment': True, 'evolution_monitor': True } status = all(components.values()) return jsonify( status="running" if status else "degraded", components=components, timestamp=datetime.now().isoformat() ) # ========== 配置系统 ========== class SystemConfig: def __init__(self): self.BASE_DIR = Path(__file__).resolve().parent.parent self.HOST = '127.0.0.1' self.PORT = 5000 self.LOG_LEVEL = 'INFO' self.SECRET_KEY = 'your_secret_key_here' self.DEBUG = True self.USE_GPU = False self.DEFAULT_MODEL = 'gpt-3.5-turbo' # 目录配置 self.LOG_DIR = self.BASE_DIR / 'logs' self.LOG_DIR.mkdir(parents=True, exist_ok=True) self.CONFIG_DIR = self.BASE_DIR / 'config' self.CONFIG_DIR.mkdir(parents=True, exist_ok=True) self.AGENT_PATH = self.BASE_DIR / 'agent' self.MODEL_CACHE_DIR = self.BASE_DIR / 'model_cache' self.MODEL_CACHE_DIR.mkdir(parents=True, exist_ok=True) def __str__(self): return f"SystemConfig(HOST={self.HOST}, PORT={self.PORT})" config = SystemConfig() # ========== 全局协调器 ========== 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(): """配置全局日志系统""" 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: # 环境管理器模拟实现 class EnvironmentManager: def __init__(self, config): self.config = config self.state = { 'temperature': 22.5, 'humidity': 45.0, 'light_level': 75, 'objects': [], 'last_updated': datetime.datetime.now().isoformat() } def start(self): logger.info("环境管理器已启动") def get_state(self): # 更新模拟数据 self.state['temperature'] = 20 + 5 * (time.time() % 10) / 10 self.state['humidity'] = 40 + 10 * (time.time() % 10) / 10 self.state['light_level'] = 70 + 10 * (time.time() % 10) / 10 self.state['last_updated'] = datetime.datetime.now().isoformat() return self.state def execute_action(self, action, params): logger.info(f"执行环境动作: {action} 参数: {params}") if action == "adjust_temperature": self.state['temperature'] = params.get('value', 22.0) return True elif action == "adjust_light": self.state['light_level'] = params.get('level', 70) return True return False 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: if not code_path.exists(): # 创建默认遗传代码文件 default_code = """# 默认遗传代码 class AICore: def __init__(self): self.version = "1.0.0" self.capabilities = ["learning", "reasoning", "problem_solving"] def evolve(self): print("系统正在进化...") """ with open(code_path, "w", encoding="utf-8") as f: f.write(default_code) with open(code_path, "r", encoding="utf-8") as f: return f.read() except Exception as e: logger.error(f"加载遗传代码失败: {str(e)}") 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) 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(), "cpu_cores": psutil.cpu_count(logical=False), "cpu_threads": psutil.cpu_count(logical=True), "memory_gb": round(psutil.virtual_memory().total / (1024 ** 3), 1), "storage_gb": round(psutil.disk_usage('/').total / (1024 ** 3), 1), "os": f"{platform.system()} {platform.release()}" } self.ai_core = AICore(self.base_dir) logger.info("✅ AI核心系统初始化完成") return self.ai_core def initialize_hardware_manager(self): """初始化硬件管理器""" try: # 硬件管理器模拟实现 class HardwareManager: 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 = HardwareManager() logger.info("✅ 硬件管理器初始化成功") return self.hardware_manager except Exception as e: logger.error(f"❌ 硬件管理器初始化失败: {str(e)}") logger.warning("⚠️ 使用内置简单硬件管理器") return None def initialize_life_scheduler(self): """初始化生活调度器""" try: # 生活调度器模拟实现 class LifeScheduler: def __init__(self): self.daily_schedule = { "wake_up": "07:00", "breakfast": "08:00", "lunch": "12:30", "dinner": "19:00", "sleep": "23:00" } self.current_activity = "awake" self.energy_level = 100 self.mood = "calm" self.activity_log = [] def wake_up(self): self.current_activity = "awake" self.log_activity("醒来") def have_meal(self, meal_type): self.current_activity = f"eating_{meal_type}" self.energy_level = min(100, self.energy_level + 20) self.log_activity(f"用餐: {meal_type}") def go_to_sleep(self): self.current_activity = "sleeping" self.log_activity("睡觉") def log_activity(self, activity): timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.activity_log.append(f"{timestamp} - {activity}") # 保留最近的100条记录 if len(self.activity_log) > 100: self.activity_log.pop(0) def adjust_schedule(self, adjustments): for activity, new_time in adjustments.items(): if activity in self.daily_schedule: self.daily_schedule[activity] = new_time def get_current_state(self): return { "current_activity": self.current_activity, "next_scheduled": self._get_next_scheduled(), "energy_level": self.energy_level, "mood": self.mood } def get_recent_activities(self, count=10): return self.activity_log[-count:] def _get_next_scheduled(self): now = datetime.datetime.now() current_time = now.strftime("%H:%M") # 找到下一个计划活动 schedule_times = sorted( [(k, v) for k, v in self.daily_schedule.items()], key=lambda x: x[1] ) for activity, time_str in schedule_times: if time_str > current_time: return f"{activity} at {time_str}" # 如果没有找到,返回第二天的第一个活动 return f"{schedule_times[0][0]} at {schedule_times[0][1]} tomorrow" 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 current_minute = now.minute current_time = f"{current_hour:02d}:{current_minute:02d}" # 根据时间更新活动状态 if 7 <= current_hour < 8 and self.life_scheduler.current_activity != "awake": self.life_scheduler.wake_up() elif 12 <= current_hour < 13 and self.life_scheduler.current_activity != "eating_lunch": self.life_scheduler.have_meal("lunch") elif 19 <= current_hour < 20 and self.life_scheduler.current_activity != "eating_dinner": self.life_scheduler.have_meal("dinner") elif (23 <= current_hour or current_hour < 6) and self.life_scheduler.current_activity != "sleeping": self.life_scheduler.go_to_sleep() # 自然能量消耗 if self.life_scheduler.current_activity != "sleeping": self.life_scheduler.energy_level = max(0, self.life_scheduler.energy_level - 0.1) 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: # AI智能体模拟实现 class AutonomousAgent: def __init__(self, model_path, cache_dir, use_gpu, default_model): self.model_name = default_model self.cache_dir = cache_dir self.use_gpu = use_gpu self.conversation_history = {} def process_input(self, user_input, user_id): # 初始化用户对话历史 if user_id not in self.conversation_history: self.conversation_history[user_id] = [] # 添加用户输入到历史 self.conversation_history[user_id].append({"role": "user", "content": user_input}) # 生成AI响应(模拟) if "你好" in user_input or "hello" in user_input: response = "你好!我是AI助手,有什么可以帮您的吗?" elif "时间" in user_input: response = f"现在是 {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" elif "状态" in user_input: response = "系统运行正常,所有组件都在线。" else: response = f"我已收到您的消息: '{user_input}'。这是一个模拟响应,实际系统中我会分析您的问题并提供专业解答。" # 添加AI响应到历史 self.conversation_history[user_id].append({"role": "assistant", "content": response}) return response def get_status(self): return { "model": self.model_name, "cache_dir": str(self.cache_dir), "use_gpu": self.use_gpu, "active_conversations": len(self.conversation_history) } 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 # 根据系统负载调整AI状态 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) 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 socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading') app.config['SOCKETIO'] = socketio # 注册路由 register_routes(app) register_error_handlers(app) return app, socketio # ========== 环境交互路由 ========== 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) 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, 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('/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() 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", "未知"), "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, socketio = create_app() # 设置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-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值