python编写环境过程中print('\r{}'.format(interaction), end='')出错

本文详细解析了如何在优快云上发布一篇高质量的技术博客,包括标题、标签和内容的优化策略,旨在帮助作者提高文章的可见性和吸引力。

https://blog.youkuaiyun.com/vmxhc1314/article/details/81216900

整个代码顺一下逻辑,并修正错误 #!/usr/bin/env python3 import subprocess import os import time import traceback import gzip import shutil from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import sys import platform class ChangeHandler(PatternMatchingEventHandler): # 只监控.tex文件的变化 patterns = ["*.tex"] last_processed_file = None # 用于防止重复处理 def process(self, event): """处理文件变化事件""" if event.is_directory: return modified_file = event.src_path # 简单防抖,避免在短时间内重复编译 if self.last_processed_file == modified_file and (time.time() - os.path.getmtime(modified_file)) < 1: return self.last_processed_file = modified_file try: latex_project_filename = 'latex_project.config' compiled_path_relative_to_project_path = "compiled" # 查找项目目录 modified_dir = os.path.dirname(modified_file) project_directory = self.get_project_directory(modified_dir, latex_project_filename) if project_directory is None: print('Python script: 未找到项目文件,跳过编译。') return # 获取源文件 src_files = self.get_source_files(project_directory, latex_project_filename) if not src_files: print('Python script: 未找到源文件,请检查 latex_project.config。') return for src_file in src_files: print(f'\n--- Python script: 开始处理文件 \'{os.path.basename(src_file)}\' ---') src_file_relative = os.path.relpath(src_file, project_directory) filename = os.path.splitext(os.path.basename(src_file))[0] compiled_dir = os.path.join(project_directory, compiled_path_relative_to_project_path) # 创建编译目录 os.makedirs(compiled_dir, exist_ok=True) # 构建latexmk命令 latexmk_cmd = [ "latexmk", "-pdf", "-recorder-", f"-outdir={compiled_path_relative_to_project_path}", f"-aux-directory={compiled_path_relative_to_project_path}", "-pdflatex=pdflatex -synctex=1 -interaction=nonstopmode -file-line-error", src_file_relative ] # 执行命令并捕获输出 print(f"执行命令: {' '.join(latexmk_cmd)}") try: # 执行latexmk命令 result = subprocess.run( latexmk_cmd, cwd=project_directory, capture_output=True, text=True, encoding='utf-8' ) # 检查是否有错误 if result.returncode != 0: print(f"编译出现错误,返回代码: {result.returncode}") else: print("编译成功") # 从输出目录查找并解析日志文件 find_and_parse_log(compiled_dir, filename) except FileNotFoundError: print("错误: 找不到 latexmk 命令。请确保它已安装并配置在系统 PATH 中。") except Exception as e: print(f"命令执行异常: {str(e)}") traceback.print_exc() # 修正synctex路径 self.fix_synctex(project_directory, compiled_path_relative_to_project_path, filename) print('--- Python script: latexmk处理完成 ---') except Exception: traceback.print_exc() def find_and_parse_log(compiled_dir, filename): """在编译输出目录中查找日志文件并解析""" log_file_path = os.path.join(compiled_dir, f"{filename}.log") # 兼容文件名不完全匹配的情况,找到最新的.log文件 if not os.path.exists(log_file_path): print(f"未找到 {filename}.log,正在搜索编译目录中的其他日志文件...") log_files = [os.path.join(compiled_dir, f) for f in os.listdir(compiled_dir) if f.endswith('.log')] if not log_files: print("在编译目录中未找到任何日志文件") return # 选择最新的日志文件 log_files.sort(key=os.path.getmtime, reverse=True) log_file_path = log_files[0] print(f"使用最新的日志文件: {log_file_path}") # 解析找到的日志文件 parse_log_with_texlogfilter(log_file_path) def parse_log_with_texlogfilter(log_file_path): try: # 执行texlogfilter命令,默认显示错误和警告 result = subprocess.run(['texlogfilter', log_file_path], capture_output=True, text=True, encoding='utf-8') if result.returncode == 0: # 解析成功,输出结果 filtered_log = result.stdout # 将结果保存到文件 output_file = log_file_path.rsplit('.', 1)[0] + '_filtered.txt' with open(output_file, 'w', encoding='utf-8') as f: f.write(filtered_log) print(f"已过滤的日志文件保存至: {output_file}") else: print(f"命令执行失败,返回代码: {result.returncode}") print(f"错误信息: {result.stderr}") except FileNotFoundError: print("未找到texlogfilter命令。请确保TeX Live已安装并添加到系统PATH。") def print_raw_errors(log_file_path, include_warnings=True): """打印原始错误信息,可选择包含警告""" print("\n===== 原始日志信息 =====") try: # 使用更健壮的编码方式 with open(log_file_path, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() error_markers = ['error', '!', 'undefined', 'missing'] if include_warnings: error_markers.append('warning') found_errors = False lines = content.split('\n') for i, line in enumerate(lines): if any(marker in line.lower() for marker in error_markers): start = max(0, i-2) end = min(len(lines), i+3) for j in range(start, end): print(f"第{j+1}行: {lines[j]}") found_errors = True print("---") if not found_errors: print("未发现明显的错误或警告") except Exception as e: print(f"读取日志文件失败: {str(e)}") def on_modified(self, event): self.process(event) def on_created(self, event): self.process(event) def on_moved(self, event): self.process(event) def get_project_directory(self, startDir, projectFilename): """查找包含项目文件的目录""" current_dir = os.path.abspath(startDir) while True: if os.path.isfile(os.path.join(current_dir, projectFilename)): return current_dir parent_dir = os.path.dirname(current_dir) if parent_dir == current_dir: break current_dir = parent_dir return None def get_source_files(self, projectDirectory, projectFilename): """从项目文件获取源文件列表""" files_to_compile = [] project_file_path = os.path.join(projectDirectory, projectFilename) if not os.path.exists(project_file_path): print(f"项目配置文件不存在: {project_file_path}") return [] with open(project_file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line and not line.startswith('#'): files_to_compile.append(line) src_files = [] for f in files_to_compile: full_path = os.path.join(projectDirectory, f) if os.path.isfile(full_path): src_files.append(full_path) else: print(f'Python script: 无效文件 ({full_path})') return src_files def fix_synctex(self, project_directory, compiled_path_relative_to_project_path, filename): """修正synctex文件中的路径,兼容gz和普通文件""" synctex_base_path = os.path.join(project_directory, compiled_path_relative_to_project_path, filename) synctex_path = f"{synctex_base_path}.synctex" synctex_gz_path = f"{synctex_base_path}.synctex.gz" if os.path.isfile(synctex_path): input_file = synctex_path is_compressed = False elif os.path.isfile(synctex_gz_path): input_file = synctex_gz_path is_compressed = True else: return # 没有synctex文件,跳过 try: temp_file = f"{synctex_base_path}.synctex.tmp" # 读取文件内容 if is_compressed: with gzip.open(input_file, 'rt', encoding='utf-8') as f: content = f.read() else: with open(input_file, 'r', encoding='utf-8') as f: content = f.read() # 修正路径 project_abs = os.path.abspath(project_directory) compiled_abs = os.path.abspath(os.path.join(project_directory, compiled_path_relative_to_project_path)) project_rel = os.path.relpath(project_abs, compiled_abs) modified_content = content.replace(project_abs, project_rel) # 将修正后的内容写入新文件 if is_compressed: with gzip.open(temp_file, 'wt', encoding='utf-8') as f: f.write(modified_content) os.replace(temp_file, synctex_gz_path) else: with open(temp_file, 'w', encoding='utf-8') as f: f.write(modified_content) os.replace(temp_file, synctex_path) print(f"修正 synctex 文件成功: {os.path.basename(input_file)}") except Exception as e: print(f"修正synctex时出错: {e}") traceback.print_exc() if __name__ == '__main__': # 检查依赖 try: import watchdog except ImportError: print("请安装必要的依赖:") print("pip install watchdog") sys.exit(1) handler = ChangeHandler() directory = './' if len(sys.argv) > 1: directory = sys.argv[1] if not os.path.exists(directory): os.makedirs(directory) print(f"创建监控目录: {os.path.abspath(directory)}") observer = Observer() observer.schedule(handler, directory, recursive=True) observer.start() print(f"开始监控目录: {os.path.abspath(directory)}") print("按Ctrl+C停止监控") try: while True: time.sleep(1) except KeyboardInterrupt: print("\n正在停止监控...") observer.stop() observer.join() print('监控已停止')
09-27
# agent/autonomous_agent.py from concurrent.futures import ThreadPoolExecutor from core.config import get_config from core.subsystem_registry import SubsystemRegistry from core.circuit_breaker import CircuitBreakerRegistry # 获取配置 system_config = get_config() class AutonomousAgent: def __init__(self): # 使用配置系统获取 MAX_WORKERS max_workers = system_config.get("MAX_WORKERS", max(1, os.cpu_count() * 2)) self.executor = ThreadPoolExecutor(max_workers=max_workers) # 获取子系统注册表 self.registry = SubsystemRegistry() # 初始化熔断器 self.circuit_breaker = CircuitBreakerRegistry.get_breaker( "autonomous_agent", failure_threshold=system_config.get("AGENT_FAILURE_THRESHOLD", 5), recovery_timeout=system_config.get("AGENT_RECOVERY_TIMEOUT", 60) ) def initialize(self): """初始化智能体""" # 确保所有子系统已初始化 if not self.registry.initialized: self.registry.initialize_all() # 获取关键子系统 self.hardware = self.registry.get("hardware_manager") self.scheduler = self.registry.get("life_scheduler") self.memory = self.registry.get("memory_manager") # 初始化完成 print("AutonomousAgent 初始化完成") def run(self): """运行智能体主循环""" try: while True: # 使用熔断器保护关键操作 self.circuit_breaker.call(self._run_cycle) except KeyboardInterrupt: print("智能体运行终止") except Exception as e: print(f"智能体运行错误: {str(e)}") # 错误处理逻辑... def _run_cycle(self): """执行单个运行周期""" # 获取下一个任务 task = self.scheduler.get_next_task() # 在线程池中执行任务 future = self.executor.submit(self.hardware.execute, task) future.add_done_callback(self._task_completed) def _task_completed(self, future): """任务完成回调""" try: result = future.result() # 处理任务结果... except Exception as e: print(f"任务执行失败: {str(e)}") # 错误处理逻辑... # 子系统注册 @SubsystemRegistry.subsystem("autonomous_agent", dependencies=["hardware_manager", "life_scheduler"]) class RegisteredAutonomousAgent(AutonomousAgent): """注册为子系统的智能体""" import os import sys import time import json import logging import traceback import threading import platform import psutil from pathlib import Path from typing import Any, Dict, Optional, Callable from concurrent.futures import ThreadPoolExecutor, Future # 确保项目根目录在 sys.path 中 BASE_DIR = Path(__file__).resolve().parent.parent.parent # 指向 E:\AI_System if str(BASE_DIR) not in sys.path: sys.path.insert(0, str(BASE_DIR)) # 导入核心模块 from core.config import system_config from core.exceptions import DependencyError, SubsystemFailure, ConfigurationError from core.metrics import MetricsCollector from core.circuit_breaker import CircuitBreaker from core.subsystem_registry import SubsystemRegistry # 全局线程池 executor = ThreadPoolExecutor(max_workers=system_config.MAX_WORKERS) class AutonomousAgent: def __init__(self): """重构后的自主智能体核心类,负责协调所有子系统""" self.logger = self._setup_logger() self.logger.info("🚀 初始化自主智能体核心模块...") self._running = False self._background_thread = None # 初始化状态跟踪 self.initialization_steps = [] self._last_env_check = 0 self._initialization_time = time.time() self.metrics = MetricsCollector() # 熔断器管理器 self.circuit_breakers = {} # 子系统注册表 self.subsystem_registry = SubsystemRegistry() # 环境管理器(外部设置) self.environment = None # 确保必要目录存在 self._ensure_directories_exist() try: # 初始化步骤 self._record_step("验证配置") self._validate_configuration() self._record_step("加载环境变量") self._load_environment() self._record_step("验证环境") self.verify_environment() self._record_step("初始化核心组件") self._initialize_core_components() self._record_step("初始化子系统") self._initialize_subsystems() self.logger.info(f"✅ 自主智能体初始化完成 (耗时: {time.time() - self._initialization_time:.2f}秒)") self.logger.info(f"初始化步骤: {', '.join(self.initialization_steps)}") except Exception as e: self.logger.exception(f"❌ 智能体初始化失败: {str(e)}") self.logger.error(f"堆栈跟踪:\n{traceback.format_exc()}") raise RuntimeError(f"智能体初始化失败: {str(e)}") from e def _setup_logger(self) -> logging.Logger: """配置日志记录器""" logger = logging.getLogger('AutonomousAgent') logger.setLevel(system_config.LOG_LEVEL) # 创建控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(system_config.LOG_LEVEL) # 创建文件处理器 log_file = Path(system_config.LOG_DIR) / 'autonomous_agent.log' log_file.parent.mkdir(parents=True, exist_ok=True) file_handler = logging.FileHandler(log_file, encoding='utf-8') file_handler.setLevel(system_config.LOG_LEVEL) # 创建格式化器 formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(name)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) console_handler.setFormatter(formatter) file_handler.setFormatter(formatter) # 添加处理器 logger.addHandler(console_handler) logger.addHandler(file_handler) logger.propagate = False return logger def _ensure_directories_exist(self): """确保所需目录存在""" required_dirs = [ system_config.LOG_DIR, system_config.CONFIG_DIR, system_config.MODEL_CACHE_DIR ] for dir_path in required_dirs: try: if not isinstance(dir_path, Path): dir_path = Path(dir_path) if not dir_path.exists(): dir_path.mkdir(parents=True, exist_ok=True) self.logger.info(f"创建目录: {dir_path}") except Exception as e: self.logger.error(f"创建目录失败 {dir_path}: {str(e)}") def _validate_configuration(self): """验证关键配置项""" required_configs = [ 'LOG_DIR', 'CONFIG_DIR', 'MODEL_CACHE_DIR', 'MAX_WORKERS', 'AGENT_RESPONSE_TIMEOUT' ] missing = [] for config_key in required_configs: if not hasattr(system_config, config_key): missing.append(config_key) if missing: raise ConfigurationError(f"缺失关键配置项: {', '.join(missing)}") # 检查配置值有效性 if system_config.MAX_WORKERS <= 0: raise ConfigurationError(f"无效的MAX_WORKERS值: {system_config.MAX_WORKERS}") def _record_step(self, step_name: str): """记录初始化步骤""" self.initialization_steps.append(step_name) self.logger.info(f"⏳ 步骤 {len(self.initialization_steps)}: {step_name}") def _load_environment(self): """加载环境变量""" env_path = system_config.CONFIG_DIR / ".env" if not env_path.exists(): self.logger.warning(f"⚠️ 环境变量文件不存在: {env_path}") return try: from dotenv import load_dotenv load_dotenv(env_path) self.logger.info(f"✅ 已加载环境变量文件: {env_path}") except ImportError: self.logger.warning("dotenv包未安装,跳过环境变量加载。请安装: pip install python-dotenv") except Exception as e: self.logger.error(f"加载环境变量失败: {str(e)}") def set_environment(self, env_manager): """设置环境管理器引用""" self.environment = env_manager self.logger.info("✅ 已连接环境管理器") # 注册环境监控任务 if self.environment: self.subsystem_registry.register_task( "环境监控", self._monitor_environment, interval=system_config.get('ENVIRONMENT_MONITOR_INTERVAL', 5.0) ) def start(self): """启动智能体后台任务""" if not self._running: self._start_background_tasks() self.logger.info("🏁 智能体后台任务已启动") else: self.logger.warning("智能体已在运行中") def _start_background_tasks(self): """启动后台任务线程""" if self._running: return self._running = True self._background_thread = threading.Thread( target=self._background_task_loop, daemon=True, name="AutonomousAgentBackgroundTasks" ) self._background_thread.start() self.logger.info("✅ 后台任务线程已启动") def _background_task_loop(self): """后台任务循环""" self.logger.info("🔄 后台任务循环启动") while self._running: try: start_time = time.time() # 执行注册的周期性任务 self.subsystem_registry.run_periodic_tasks() # 动态调整睡眠时间 task_time = time.time() - start_time sleep_time = max(0.1, system_config.AGENT_TASK_INTERVAL - task_time) time.sleep(sleep_time) except Exception as e: self.logger.error(f"后台任务错误: {str(e)}") self.metrics.record_error('background_task') time.sleep(30) # 错误后等待更长时间 def verify_environment(self): """验证运行环境是否满足要求""" # 检查必需模块 required_modules = [ 'os', 'sys', 'logging', 'flask', 'werkzeug', 'numpy', 'transformers', 'torch', 'psutil' ] # 检查必需包 required_packages = [ ('dotenv', 'python-dotenv'), ('flask_socketio', 'flask-socketio') ] missing_modules = [] for mod in required_modules: try: __import__(mod) except ImportError: missing_modules.append(mod) missing_packages = [] for import_name, pkg_name in required_packages: try: __import__(import_name) except ImportError: missing_packages.append(pkg_name) # 处理缺失项 errors = [] if missing_modules: errors.append(f"缺失Python模块: {', '.join(missing_modules)}") if missing_packages: errors.append(f"缺失Python包: {', '.join(missing_packages)}") if errors: error_msg = "环境验证失败:\n" + "\n".join(errors) self.logger.error(error_msg) raise DependencyError(error_msg) self.logger.info("✅ 环境验证通过") def _log_environment_status(self): """记录环境状态信息""" try: # 获取系统信息 sys_info = { "os": platform.system(), "os_version": platform.version(), "cpu": platform.processor(), "cpu_cores": psutil.cpu_count(logical=False), "memory_total": round(psutil.virtual_memory().total / (1024 ** 3), 1), "memory_used": round(psutil.virtual_memory().used / (1024 ** 3), 1), "disk_total": round(psutil.disk_usage('/').total / (1024 ** 3), 1), "disk_used": round(psutil.disk_usage('/').used / (1024 ** 3), 1), } self.logger.info( f"📊 系统状态: OS={sys_info['os']} {sys_info['os_version']}, " f"CPU={sys_info['cpu']} ({sys_info['cpu_cores']}核), " f"内存={sys_info['memory_used']}/{sys_info['memory_total']}GB, " f"磁盘={sys_info['disk_used']}/{sys_info['disk_total']}GB" ) except Exception as e: self.logger.error(f"环境状态获取失败: {str(e)}") self.metrics.record_error('environment_status') def _initialize_core_components(self): """初始化不依赖其他组件的核心组件""" self._log_environment_status() # 初始化熔断器 self._initialize_circuit_breakers() # 注册核心任务 self.subsystem_registry.register_task( "子系统心跳检查", self._check_subsystem_heartbeats, interval=system_config.get('HEARTBEAT_INTERVAL', 60.0) ) self.subsystem_registry.register_task( "子系统恢复", self._recover_failed_subsystems, interval=system_config.get('RECOVERY_INTERVAL', 300.0) ) def _initialize_circuit_breakers(self): """为所有子系统初始化熔断器""" subsystems = [ '健康系统', '模型管理器', '记忆系统', '情感系统', '认知架构', '通信系统' ] for subsystem in subsystems: breaker = CircuitBreaker( failure_threshold=system_config.get('CIRCUIT_BREAKER_THRESHOLD', 5), recovery_timeout=system_config.get('CIRCUIT_BREAKER_TIMEOUT', 300) ) self.circuit_breakers[subsystem] = breaker self.logger.info(f"⚡ 为 {subsystem} 初始化熔断器") def _initialize_subsystems(self): """初始化所有子系统""" # 定义子系统初始化顺序 subsystems = [ ('健康系统', self._create_health_system, {}), ('模型管理器', self._create_model_manager, {}), ('记忆系统', self._create_memory_system, {}), ('情感系统', self._create_affective_system, {}), ('认知架构', self._create_cognitive_architecture, {}), ('通信系统', self._create_communication_system, {}) ] # 注册子系统依赖关系 dependencies = { '通信系统': ['认知架构'], '情感系统': ['健康系统', '记忆系统'], '认知架构': ['记忆系统'] } for name, creator_func, kwargs in subsystems: try: # 检查依赖是否满足 if name in dependencies: missing_deps = [dep for dep in dependencies[name] if not self.subsystem_registry.get_subsystem(dep)] if missing_deps: self.logger.warning(f"⚠️ 子系统 {name} 缺少依赖: {', '.join(missing_deps)}") # 尝试自动初始化缺失依赖 for dep in missing_deps: self._initialize_dependency(dep) # 创建实例 instance = creator_func(**kwargs) self.subsystem_registry.register_subsystem(name, instance) # 注册子系统任务 if hasattr(instance, 'periodic_task'): self.subsystem_registry.register_task( f"{name}更新", instance.periodic_task, interval=system_config.get(f'{name}_INTERVAL', 60.0) ) self.logger.info(f"✅ {name}初始化完成") except Exception as e: self.logger.error(f"❌ {name}初始化失败: {str(e)}") self.metrics.record_error(f'subsystem_init_{name.lower()}') def _initialize_dependency(self, subsystem_name: str): """初始化依赖子系统""" creators = { '健康系统': self._create_health_system, '模型管理器': self._create_model_manager, '记忆系统': self._create_memory_system, '情感系统': self._create_affective_system, '认知架构': self._create_cognitive_architecture, '通信系统': self._create_communication_system } if subsystem_name in creators: try: instance = creators[subsystem_name]() self.subsystem_registry.register_subsystem(subsystem_name, instance) self.logger.info(f"✅ 依赖子系统 {subsystem_name} 初始化完成") except Exception as e: self.logger.error(f"❌ 依赖子系统 {subsystem_name} 初始化失败: {str(e)}") raise # 各子系统实现(增强功能) def _create_health_system(self): class HealthSystem: def __init__(self): self.status = "healthy" self.metrics = {} self.logger = logging.getLogger('HealthSystem') def periodic_task(self): """更新健康状态""" try: # 获取系统状态 cpu_usage = psutil.cpu_percent() mem_usage = psutil.virtual_memory().percent disk_usage = psutil.disk_usage('/').percent # 更新状态 self.status = "healthy" if cpu_usage < 90 and mem_usage < 90 else "warning" self.metrics = { "cpu_usage": cpu_usage, "mem_usage": mem_usage, "disk_usage": disk_usage, "timestamp": time.time() } self.logger.debug(f"健康状态更新: {self.status}") except Exception as e: self.logger.error(f"健康系统更新失败: {str(e)}") def record_environment_status(self, env_data): """记录环境状态""" self.metrics['environment'] = env_data def get_status(self): return { "status": self.status, "metrics": self.metrics } return HealthSystem() def _create_model_manager(self): class ModelManager: def __init__(self): self.loaded_models = {} self.logger = logging.getLogger('ModelManager') def load_model(self, model_name): """加载模型""" if model_name not in self.loaded_models: # 模拟模型加载 self.logger.info(f"加载模型: {model_name}") self.loaded_models[model_name] = { "status": "loaded", "load_time": time.time() } return True return False def periodic_task(self): """模型管理器周期性任务""" # 检查模型状态 for model_name, model_info in list(self.loaded_models.items()): # 模拟模型验证 if time.time() - model_info['load_time'] > 86400: # 24小时 self.logger.info(f"重新加载模型: {model_name}") model_info['load_time'] = time.time() def get_status(self): return { "loaded_models": list(self.loaded_models.keys()), "count": len(self.loaded_models) } return ModelManager() def _create_memory_system(self): class MemorySystem: def __极忆__init__(self): self.memories = [] self.last_consolidation = time.time() self.logger = logging.getLogger('MemorySystem') def periodic_task(self): """巩固记忆""" try: # 保留最近100条记忆 if len(self.memories) > 100: self.memories = self.memories[-100:] self.last_consolidation = time.time() self.logger.debug(f"记忆巩固完成,当前记忆数: {极忆len(self.memories)}") except Exception as e: self.logger.error(f"记忆巩固失败: {str(e)}") def add_memory(self, memory): """添加记忆""" self.memories.append({ "content": memory, "timestamp": time.time() }) def get_status(self): return { "memory_count": len(self.memories), "last_consolidation": self.last_consolidation } return MemorySystem() def _create_affective_system(self): class AffectiveSystem: def __init__(self): self.mood = "neutral" self.energy = 100 self.logger = logging.getLogger('AffectiveSystem') def periodic_task(self): """情感成长""" try: # 根据时间恢复能量 self.energy = min(100, self.energy + 1) self.logger.debug(f"情感更新: 能量={self.energy}, 情绪={self.mood}") except Exception as e: self.logger.error(f"情感系统更新失败: {str(e)}") def update_mood(self, interaction): """根据交互更新情绪""" if "positive" in interaction: self.mood = "happy" elif "negative" in interaction: self.mood = "sad" def get_status(self): return { "mood": self.mood, "energy": self.energy } return AffectiveSystem() def _create_cognitive_architecture(self): class CognitiveArchitecture: def __init__(self): self.current_task = None self.task_history = [] self.logger = logging.getLogger('CognitiveArchitecture') def start_task(self, task): """开始新任务""" self.logger.info(f"开始任务: {task}") self.current_task = task self.task_history.append({ "task": task, "start_time": time.time(), "status": "in_progress" }) def complete_task(self, result): """完成任务""" if self.current_task: for task in reversed(self.task_history): if task["task"] == self.current_task and task["status"] == "in_progress": task["status"] = "completed" task["result"] = result task["end_time"] = time.time() self.log极忆.info(f"完成任务: {task['task']}") break self.current_task = None def periodic_task(self): """认知架构周期性任务""" # 清理过时任务 now = time.time() self.task_history = [t for t in self.task_history if t['status'] == 'completed' or (now - t['start_time']) < 3600] # 保留1小时内进行中的任务 def get_status(self): return { "current_task": self.current_task, "task_count": len(self.task_history), "completed_tasks": sum(1 for t in self.task_history if t["status"] == "completed") } return CognitiveArchitecture() def _create_communication_system(self): class CommunicationSystem: def __init__(self): self.message_queue = [] self.processed_count = 0 self.logger = logging.getLogger('CommunicationSystem') def process_input(self, user_input: str, user_id: str = "default") -> str: """处理用户输入""" try: # 模拟处理逻辑 response = f"已处理您的消息: '{user_input}' (用户: {user_id})" # 记录处理 self.processed_count += 1 self.logger.info(f"处理消息: '{user_input[:30]}...' (用户: {user_id})") return response except Exception as e: self.logger.error(f"消息处理失败: {str(e)}") return "处理消息时出错" def periodic_task(self): """通信系统周期性任务""" # 清理消息队列 if len(self.message_queue) > 100: self.message_queue = self.message_queue[-100:] self.logger.debug("清理消息队列") def check_heartbeat(self): """心跳检查""" return True def get_status(self): return { "queue_size": len(self.message_queue), "processed_count": self.processed_count } return CommunicationSystem() def process_input(self, user_input: str, user_id: str = "default") -> Dict[str, Any]: """处理用户输入(通过通信系统)""" # 获取通信系统 comm_system = self.subsystem_registry.get_subsystem('通信系统') if not comm_system: self.logger.error("通信系统未初始化,使用回退处理") self.metrics.record_error('communication_system_inactive') return {"response": "系统正在维护中,请稍后再试"} # 检查熔断器状态 breaker = self.circuit_breakers.get('通信系统') if breaker and breaker.is_open(): self.logger.warning("通信系统熔断器已打开") self.metrics.record_error('communication_circuit_open') return {"response": "系统繁忙,请稍后再试"} try: # 使用熔断器包装调用 def process_wrapper(): return comm_system.process_input(user_input, user_id) if breaker: response = breaker.call(process_wrapper) else: response = process_wrapper() # 使用线程池异步处理 future = executor.submit(lambda: response) result = future.result(timeout=system_config.AGENT_RESPONSE_TIMEOUT) # 记录成功 self.metrics.record_success('process_input') return {"response": result} except TimeoutError: self.logger.warning("处理输入超时") self.metrics.record_timeout('process_input') if breaker: breaker.record_failure() return {"error": "处理超时,请重试"} except Exception as e: self.logger.error(f"处理输入失败: {str(e)}") self.metrics.record_error('process_input') if breaker: breaker.record极忆failure() return {"error": "处理失败,请稍后再试"} def _monitor_environment(self): """监控环境状态""" try: if self.environment and hasattr(self.environment, 'get_state'): # 使用真实环境管理器获取状态 env_state = self.environment.get_state() self.logger.info( f"🌡️ 环境监控: 温度={env_state.get('temperature', '未知')}℃, " f"湿度={env_state.get('humidity', '未知')}%, " f"光照={env_state.get('light_level', '未知')}%" ) # 记录到健康系统(如果可用) health_system = self.subsystem_registry.get_subsystem('健康系统') if health_system and hasattr(health_system, 'record_environment_status'): health_system.record_environment_status(env_state) else: # 使用内置监控 cpu_usage = psutil.cpu_percent() mem_usage = psutil.virtual_memory().percent disk_usage = psutil.disk_usage('/').percent self.logger.info( f"📊 系统监控: CPU={cpu_usage}%, " f"内存={mem_usage}%, " f"磁盘={disk_usage}%" ) # 记录到健康系统 health_system = self.subsystem_registry.get_subsystem('健康系统') if health_system and hasattr(health_system, 'record_environment_status'): health_system.record_environment_status({ "cpu_usage": cpu_usage, "mem_usage": mem_usage, "disk_usage": disk_usage }) except Exception as e: self.logger.error(f"环境监控失败: {str(e)}") self.metrics.record_error('environment_monitoring') def _check_subsystem_heartbeats(self): """检查子系统心跳""" for name, subsystem in self.subsystem_registry.subsystems.items(): if hasattr(subsystem, 'check_heartbeat'): try: if not subsystem.check_heartbeat(): self.logger.warning(f"⚠️ 子系统 {name} 心跳检测失败") self._handle_subsystem_error(name) else: self.logger.debug(f"✅ 子系统 {name} 心跳正常") except Exception as e: self.logger.error(f"子系统 {name} 心跳检查异常: {str(e)}") self._handle_subsystem_error(name) self.metrics.record_error(f'heartbeat_{name.lower()}') def _handle_subsystem_error(self, name: str): """处理子系统错误""" breaker = self.circuit_breakers.get(name) if breaker: breaker.record_failure() if breaker.is_open(): self.logger.critical(f"🚨 子系统 {name} 因连续错误被熔断!") self.metrics.record_event('circuit_breaker', name) def _recover_failed_subsystems(self): """尝试恢复失败的子系统""" for name, breaker in self.circuit_breakers.items(): if breaker.is_open() and breaker.should_try_recovery(): self.logger.info(f"🔄 尝试恢复子系统: {name}") try: # 尝试重新初始化子系统 self._reinitialize_subsystem(name) breaker.record_success() self.logger.info(f"✅ 子系统 {name} 恢复成功") self.metrics.record_event('subsystem_recovered', name) except Exception as e: self.logger.error(f"子系统 {name} 恢复失败: {str(e)}") breaker.record_failure() self.metrics.record_error(f'recovery_{name.lower()}') def _reinitialize_subsystem(self, name: str): """重新初始化子系统""" creators = { '健康系统': self._create_health_system, '模型管理器': self._create_model_manager, '记忆系统': self._create_memory_system, '情感系统': self._create_affective_system, '认知架构': self._create_cognitive_architecture, '通信系统': self._create_communication_system } if name in creators: instance = creators[name]() self.subsystem_registry.register_subsystem(name, instance) else: raise SubsystemFailure(f"未知子系统: {name}") def get_status(self) -> Dict[str, Any]: """获取智能体状态报告""" status_data = { "uptime": time.time() - self._initialization_time, "running": self._running, "metrics": self.metrics.get_metrics(), "subsystems": {} } # 添加子系统状态 for name, subsystem in self.subsystem_registry.subsystems.items(): if hasattr(subsystem, 'get_status'): status_data['subsystems'][name] = subsystem.get_status() # 添加熔断器状态 status_data['circuit_breakers'] = {} for name, breaker in self.circuit_breakers.items(): status_data['circuit_breakers'][name] = breaker.get_status() return status_data def shutdown(self): """关闭智能体""" self.logger.info("🛑 正在关闭智能体...") self._running = False # 停止线程池 executor.shutdown(wait=False) # 等待后台线程 if self._background_thread and self._background_thread.is_alive(): self._background_thread.join(timeout=5.0) if self._background_thread.is_alive(): self.logger.warning("后台线程未正常退出") self.logger.info("✅ 智能体已关闭")
08-13
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from datetime import datetime import re # 解析表格数据 data = [] rows = [line for line in """ | A | B | C | D | E | F | G | H | I | J | K | L | |:----|:-----|:-----|:----------|:---|:-----|:-----|:-----|:----|:----|:----|:-----| | 关键词 | 博主名称 | 笔记类型 | 视频链接/首图链接 | 标题 | 正文内容 | 发布时间 | 发布地址 | 点赞数 | 收藏数 | 评论数 | 笔记链接 | | 饿了么 | 天天巨省钱 | 图文 | http://sns-webpic-qc.xhscdn.com/202505281033/6b87661da21eb78006f3e63eb2f9efa3/notes_pre_post/1040g3k031i0pbqgh6s0g5o9a0650bnh68jtoghg!nd_dft_wlteh_webp_3 | 简直了…饿了么牛啊!!! | 简直了…饿了么牛啊!!!<br>为什么不给我18-18?为什么不给我18-18?为什么不给我18-18?@饿了么福利社 @饿了么 @饿了么大蓝 @淘宝 @万能的淘宝 卸载你卸载你[生气R][生气R] @淘宝攻略[微笑R][微笑R]<br> <br>elm对用户数据有点过度了吧<br>开始蕞新大水18-18攻略教程⬇️<br>记住!一定要在逃饱的e了么([九R][六R][六R][八R][八R])<br>#不要太离谱 #还有人不知道 #饿了么 #家人们谁懂啊 #真让我大开眼界了 #想告诉全世界 #商战 #饿了么外卖 #省钱小妙招 #外卖 | 2025-05-28 09:10:26 | 北京 | 0 | 0 | 2 | https://www.xiaohongshu.com/search_result/68366281000000002300da99?xsec_token=ABlLblC0_WVPQdbtDz3EuvP8lnYYegM-Kt8NS7gF-GqIw=&xsec_source= | ...(完整数据)... """.split('\n') if line.strip()] # 提取列名 headers = [col.strip() for col in rows[1].split('|')[1:-1]] # 解析数据行 for row in rows[3:]: if not row.startswith('|'): continue cols = [re.sub(r'<br>|\s+', ' ', col.strip()) for col in row.split('|')[1:-1]] if len(cols) == len(headers): data.append(cols) # 创建DataFrame df = pd.DataFrame(data, columns=headers) # 转换数据类型 df['发布时间'] = pd.to_datetime(df['发布时间']) df['点赞数'] = pd.to_numeric(df['点赞数']) df['收藏数'] = pd.to_numeric(df['收藏数']) df['评论数'] = pd.to_numeric(df['评论数']) # 筛选日期范围 start_date = '2025-04-30' end_date = '2025-05-13' filtered_df = df[(df['发布时间'] >= start_date) & (df['发布时间'] <= end_date)] print(f"筛选后数据量: {len(filtered_df)}条") # 数据分析与可视化 plt.figure(figsize=(15, 12)) plt.suptitle(f'饿了么笔记数据分析 ({start_date}至{end_date})', fontsize=16) # 1. 笔记类型分布 plt.subplot(221) note_type = filtered_df['笔记类型'].value_counts() note_type.plot.pie(autopct='%1.1f%%', startangle=90) plt.title('笔记类型分布') plt.ylabel('') # 2. 热门发布地区TOP10 plt.subplot(222) top_locations = filtered_df['发布地址'].value_counts().head(10) sns.barplot(x=top_locations.values, y=top_locations.index, palette='viridis') plt.title('发布地区TOP10') plt.xlabel('数量') # 3. 每日发布趋势 plt.subplot(223) daily_count = filtered_df.set_index('发布时间').resample('D').size() daily_count.plot(marker='o') plt.title('每日发布数量趋势') plt.xlabel('日期') plt.ylabel('发布量') plt.grid(True) # 4. 互动量分析 plt.subplot(224) interaction = filtered_df[['点赞数', '收藏数', '评论数']].mean() sns.barplot(x=interaction.values, y=interaction.index, palette='Set2') plt.title('平均互动量对比') plt.xlabel('数量') plt.tight_layout(rect=[0, 0, 1, 0.96]) plt.savefig('eleme_data_analysis.png', dpi=300) plt.show() # 生成分析报告 report = f""" 数据分析报告 ({start_date}至{end_date}) ==================================== 1. 数据概况: - 总笔记数量: {len(filtered_df)}条 - 时间范围: {filtered_df['发布时间'].min().strftime('%Y-%m-%d')} 至 {filtered_df['发布时间'].max().strftime('%Y-%m-%d')} 2. 内容特征: - 笔记类型分布: 图文: {note_type.get('图文', 0)}条 ({note_type.get('图文', 0)/len(filtered_df):.1%}) 视频: {note_type.get('视频', 0)}条 ({note_type.get('视频', 0)/len(filtered_df):.1%}) - 热门地区: {top_locations.idxmax()} ({top_locations.max()}条) 3. 互动分析: - 平均点赞: {interaction['点赞数']:.1f} - 平均收藏: {interaction['收藏数']:.1f} - 平均评论: {interaction['评论数']:.1f} 4. 时间趋势: - 发布高峰日: {daily_count.idxmax().strftime('%Y-%m-%d')} ({daily_count.max()}条) """ print(report) 将这段代码中的# 解析表格数据 data = [] rows = [line for line in """ | A | B | C | D | E | F | G | H | I | J | K | L | |:----|:-----|:-----|:----------|:---|:-----|:-----|:-----|:----|:----|:----|:-----| | 关键词 | 博主名称 | 笔记类型 | 视频链接/首图链接 | 标题 | 正文内容 | 发布时间 | 发布地址 | 点赞数 | 收藏数 | 评论数 | 笔记链接 | | 饿了么 | 天天巨省钱 | 图文 | http://sns-webpic-qc.xhscdn.com/202505281033/6b87661da21eb78006f3e63eb2f9efa3/notes_pre_post/1040g3k031i0pbqgh6s0g5o9a0650bnh68jtoghg!nd_dft_wlteh_webp_3 | 简直了…饿了么牛啊!!! | 简直了…饿了么牛啊!!!<br>为什么不给我18-18?为什么不给我18-18?为什么不给我18-18?@饿了么福利社 @饿了么 @饿了么大蓝 @淘宝 @万能的淘宝 卸载你卸载你[生气R][生气R] @淘宝攻略[微笑R][微笑R]<br> <br>elm对用户数据有点过度了吧<br>开始蕞新大水18-18攻略教程⬇️<br>记住!一定要在逃饱的e了么([九R][六R][六R][八R][八R])<br>#不要太离谱 #还有人不知道 #饿了么 #家人们谁懂啊 #真让我大开眼界了 #想告诉全世界 #商战 #饿了么外卖 #省钱小妙招 #外卖 | 2025-05-28 09:10:26 | 北京 | 0 | 0 | 2 | https://www.xiaohongshu.com/search_result/68366281000000002300da99?xsec_token=ABlLblC0_WVPQdbtDz3EuvP8lnYYegM-Kt8NS7gF-GqIw=&xsec_source= | ...(完整数据)... """.split('\n') if line.strip()] 将这段内容改为# 直接从Excel文件读取数据 df = pd.read_excel('results(京东).xlsx', sheet_name='Sheet1') 并 增加数据清洗:检查缺失值,处理异常值。
05-30
总结一下我的代码,我现在希望录音策略改用用户未讲话时持续等待,说话时长时等待10~20s,停顿时短时等待5s """ 【语音识别模块】Speech Recognition (Offline) 使用麦克风进行实时语音识别,基于 Vosk 离线模型 支持单次识别 & 持续监听模式 音量可视化、模型路径检查、资源安全释放 """ import random import threading import time import logging import json import os from vosk import Model, KaldiRecognizer import pyaudio from database import config from Progress.utils.logger_utils import log_time, log_step, log_var, log_call from Progress.utils.logger_config import setup_logger # --- 配置参数 --- VOICE_TIMEOUT = config.timeout # 最大等待语音输入时间(秒) VOICE_PHRASE_TIMEOUT = config.phrase_timeout # 单句话最长录音时间 VOSK_MODEL_PATH = "./vosk-model-small-cn-0.22" # --- 初始化日志器 --- logger = logging.getLogger("ai_assistant") # 定义最小有效音量阈值 MIN_VOLUME_THRESHOLD = 600 # 可调(根据环境测试) class SpeechRecognizer: def __init__(self): self.model = None self.recognizer = None self.audio = None self.is_listening = False self.callback = None # 用户注册的回调函数:callback(text) self._last_text = "" self._listen_thread = None self.sample_rate = 16000 # Vosk 要求采样率 16kHz self.chunk_size = 1600 # 推荐帧大小(对应 ~100ms) # 🔒 TTS 播放状态标志(由外部控制) self._is_tts_playing = False self._tts_lock = threading.Lock() self._load_model() self._init_audio_system() @property def is_tts_playing(self) -> bool: with self._tts_lock: return self._is_tts_playing def set_tts_playing(self, status: bool): """供 TTS 模块调用:通知当前是否正在播放""" with self._tts_lock: self._is_tts_playing = status if not status: logger.debug("🟢 TTS 播放结束,语音识别恢复") @log_step("加载 Vosk 离线模型") @log_time def _load_model(self): """加载本地 Vosk 模型""" if not os.path.exists(VOSK_MODEL_PATH): raise FileNotFoundError(f"❌ Vosk 模型路径不存在: {VOSK_MODEL_PATH}\n","请从 https://alphacephei.com/vosk/models 下载中文小模型并解压至此路径") try: logger.info(f"📦 正在加载模型: {VOSK_MODEL_PATH}") self.model = Model(VOSK_MODEL_PATH) log_call("✅ 模型加载成功") except Exception as e: logger.critical(f"🔴 加载 Vosk 模型失败: {e}") raise RuntimeError("Failed to load Vosk model") from e @log_step("初始化音频系统") @log_time def _init_audio_system(self): """初始化 PyAudio 并创建全局 recognizer""" try: self.audio = pyaudio.PyAudio() # 创建默认识别器(可在每次识别前 Reset) self.recognizer = KaldiRecognizer(self.model, self.sample_rate) logger.debug("✅ 音频系统初始化完成") except Exception as e: logger.exception("❌ 初始化音频系统失败") raise @property def last_text(self) -> str: return self._last_text def is_available(self) -> bool: """检查麦克风是否可用""" if not self.audio: return False try: stream = self.audio.open( format=pyaudio.paInt16, channels=1, rate=self.sample_rate, input=True, frames_per_buffer=self.chunk_size ) stream.close() return True except Exception as e: logger.error(f"🔴 麦克风不可用或无权限: {e}") return False @log_step("执行单次语音识别") @log_time def listen_and_recognize(self, timeout=None) -> str: timeout = timeout or VOICE_TIMEOUT start_time = time.time() in_speech = False result_text = "" logger.debug(f"🎙️ 开始单次语音识别 (timeout={timeout:.1f}s)...") # 🔴 如果正在播放 TTS,直接返回空 if self.is_tts_playing: logger.info("🔇 TTS 正在播放,跳过本次识别") return "" logger.info("🔊 请说话...") stream = None try: recognizer = KaldiRecognizer(self.model, self.sample_rate) stream = self.audio.open( format=pyaudio.paInt16, channels=1, rate=self.sample_rate, input=True, frames_per_buffer=self.chunk_size ) while (time.time() - start_time) < timeout: # 再次检查播放状态(可能中途开始) if self.is_tts_playing: logger.info("🔇 TTS 开始播放,中断识别") break data = stream.read(self.chunk_size, exception_on_overflow=False) if recognizer.AcceptWaveform(data): final_result = json.loads(recognizer.Result()) text = final_result.get("text", "").strip() if text: result_text = text break else: partial = json.loads(recognizer.PartialResult()) if partial.get("partial", "").strip(): in_speech = True if not in_speech and (time.time() - start_time) >= timeout: logger.info("💤 超时未检测到语音输入") break if result_text: self._last_text = result_text logger.info(f"🎯 识别结果: '{result_text}'") return result_text else: logger.info("❓ 未识别到有效内容") self._last_text = "" return "" except Exception as e: logger.exception("🔴 执行单次语音识别时发生异常") self._last_text = "" return "" finally: if stream: try: stream.stop_stream() stream.close() except Exception as e: logger.warning(f"⚠️ 关闭音频流失败: {e}") @log_step("启动持续语音监听") def start_listening(self, callback=None, language=None): """ 启动后台线程持续监听语音输入 :param callback: 回调函数,接受一个字符串参数 text :param language: 语言代码(忽略,由模型决定) """ if self.is_listening: logger.warning("⚠️ 已在监听中,忽略重复启动") return if not callable(callback): logger.error("🔴 回调函数无效,请传入可调用对象") return self.callback = callback self.is_listening = True self._listen_thread = threading.Thread(target=self._background_listen, args=(language,), daemon=True) self._listen_thread.start() logger.info("🟢 已启动后台语音监听") @log_step("停止语音监听") def stop_listening(self): """安全停止后台监听""" if not self.is_listening: return self.is_listening = False logger.info("🛑 正在停止语音监听...") if self._listen_thread and self._listen_thread != threading.current_thread(): self._listen_thread.join(timeout=3) if self._listen_thread.is_alive(): logger.warning("🟡 监听线程未能及时退出(可能阻塞)") elif self._listen_thread == threading.current_thread(): logger.error("❌ 无法在当前线程中 join 自己!请检查调用栈") else: logger.debug("No thread to join") logger.info("✅ 语音监听已停止") def _background_listen(self, language=None): """后台循环监听线程""" logger.debug("🎧 后台监听线程已启动") stream = None try: stream = self.audio.open( format=pyaudio.paInt16, channels=1, rate=self.sample_rate, input=True, frames_per_buffer=self.chunk_size ) except Exception as e: logger.error(f"🔴 无法打开音频流: {e}") return try: while self.is_listening: # 🔴 检查是否正处于 TTS 播放中 → 跳过本次读取 if self.is_tts_playing: time.sleep(0.1) # 减少 CPU 占用 continue try: data = stream.read(self.chunk_size, exception_on_overflow=False) if self.recognizer.AcceptWaveform(data): result_json = self.recognizer.Result() result_dict = json.loads(result_json) text = result_dict.get("text", "").strip() if text and self.callback: logger.info(f"🔔 回调触发: '{text}'") self.callback(text) self.recognizer.Reset() else: partial = json.loads(self.recognizer.PartialResult()) partial_text = partial.get("partial", "") if partial_text.strip(): logger.debug(f"🗣️ 当前语音片段: '{partial_text}'") except Exception as e: logger.exception("Background listening error") time.sleep(0.05) finally: if stream: stream.stop_stream() stream.close() logger.debug("🔚 后台监听线程退出") recognizer = SpeechRecognizer() """ 【AI语音助手】主程序入口 集成语音识别、Qwen 意图理解、TTS 与动作执行 ✅ 已修复:不再访问 _last_text 私有字段 ✅ 增强:异常防护、类型提示、唤醒词预留接口 """ import sys import time import logging # --- 导入日志工具 --- from Progress.utils.logger_config import setup_logger from Progress.utils.logger_utils import log_time, log_step, log_var, log_call # --- 显式导入各模块核心类 --- from Progress.app.voice_recognizer import recognizer from Progress.app.qwen_assistant import assistant from Progress.app.text_to_speech import tts_engine from Progress.app.system_controller import executor from database import config # --- 初始化全局日志器 --- logger = logging.getLogger("ai_assistant") @log_step("处理一次语音交互") @log_time def handle_single_interaction(): """ 单次完整交互:听 -> 识别 -> AI 决策 -> 执行 -> 回复 """ # 1. 听 # 使用动态超时进行语音识别 text = recognizer.listen_and_recognize(recognizer.current_timeout) if not text: logger.info(f"🔇 未检测到有效语音(超时:{recognizer.current_timeout}秒)") return logger.info(f"🗣️ 用户说: '{text}'") # 2. AI决策 decition = assistant.process_voice_command(text) # 3. 构造回复语句 result = executor.execute_task_plan(decition) if result["success"]: ai_reply = str(result["message"]) logger.info(f"✅ 操作成功: {result['operation']} -> {ai_reply}") else: error_msg = result["message"] ai_reply = f"抱歉,{error_msg if '抱歉' not in error_msg else error_msg[3:]}" logger.warning(f"❌ 执行失败: {error_msg}") # 4. 说 logger.info(f"🤖 回复: {ai_reply}") tts_engine.speak(ai_reply) @log_step("启动 AI 语音助手") @log_time def main(): logger.info("🚀 正在启动 AI 语音助手系统...") try: tts_engine.start() log_call("✅ 所有模块初始化完成,进入监听循环") log_call("\n" + "—" * 50) log_call("🎙️ 语音助手已就绪") log_call("💡 说出你的命令,例如:'打开浏览器'、'写一篇春天的文章'") log_call("🛑 说出‘退出’、‘关闭’、‘停止’或‘拜拜’来结束程序") log_call("—" * 50 + "\n") while True: try: handle_single_interaction() # 🚩 检查上一次执行的结果是否有退出请求 last_result = executor.last_result # 假设 TaskOrchestrator 记录了 last_result if last_result and last_result.get("should_exit"): logger.info("🎯 接收到退出指令,即将终止程序...") break # 跳出循环,进入清理流程 except KeyboardInterrupt: logger.info("🛑 用户主动中断 (Ctrl+C),准备退出...") raise # 让 main 捕获并退出 except Exception as e: logger.exception("⚠️ 单次交互过程中发生异常,已降级处理") error_msg = "抱歉,我在处理刚才的操作时遇到了一点问题。" logger.info(f"🗣️ 回复: {error_msg}") tts_engine.speak(error_msg) last_text = recognizer.last_text.lower() exit_keywords = ['退出', '关闭', '停止', '拜拜', '再见'] if any(word in last_text for word in exit_keywords): logger.info("🎯 用户请求退出,程序即将终止") break time.sleep(0.5) tts_engine.stop() logger.info("👋 语音助手已安全退出") except KeyboardInterrupt: logger.info("🛑 用户通过 Ctrl+C 中断程序") print("\n👋 再见!") except Exception as e: logger.exception("❌ 主程序运行时发生未预期异常") print(f"\n🚨 程序异常终止:{e}") sys.exit(1) if __name__ == "__main__": if not logging.getLogger().handlers: setup_logger(name="ai_assistant", log_dir="logs", level=logging.INFO) main()
最新发布
10-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值