python PyPDF2.utils.PdfReadError: Illegal character in Name Object

在Python 3.7环境中使用PyPDF2模块处理PDF文件时遇到PdfReadError,原因是PDF文件包含多种编码。通过修改PyPDF2源码,包括在generic.py文件中添加处理多编码的代码,以及在utils.py文件中注释和替换特定代码段,可以解决这个问题。

python PyPDF2.utils.PdfReadError: Illegal character in Name Object

环境说明

PyCharm 2020.2.3 x64
Python 3.7
PyPDF2模块
报错场景

在使用PyPDF2模块将一个PDF文件分割成多个PDF文件时,出现报错

python PyPDF2.utils.PdfReadError: Illegal character in Name Object

报错原因

该错误是由于读取的PDF文件中包含多种编码导致

报错信息如下
Traceback (most recent call last):
  File "E:\Program_Practice\Python\pachong\venv\lib\site-packages\PyPDF2\generic.py", line 484, in readFromStream
    return NameObject(name.decode('utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcb in position 8: invalid continuation byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/Program_Practice/Python/pachong/test/Day_12/pdf_segmentation.py", line 19, in <module>
    pdf_writer.write(out)
  File "E:\Program_Practice\Python\pachong\venv\lib\site-packages\PyPDF2\pdf.py", line 482, in write
    self._sweepIndirectReferences(externalReferenceMap, self._root)
  File "E:\Program_Practice\Python\pachong\venv\lib\site-packages\PyPDF2\pdf.py", line 571, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "E:\Program_Practice\Python\pachong\venv\lib\site-packages\PyPDF2\pdf.py", line 547, in _sweepIndirectReferences
    value 
E:\AI_System\web_ui>python server.py ERROR:root:❌ 配置模块导入失败: No module named 'config.config_loader'; 'config' is not a package ERROR:root:请检查以下路径是否存在: ERROR:root:1. E:\AI_System\config/config_loader.py --- Logging error --- Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 90, in <module> from cognitive_arch.life_scheduler import LifeScheduler ModuleNotFoundError: No module named 'cognitive_arch' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 128, in <module> logger.error(f"❌ 生活系统模块导入失败: {str(e)}") Message: "❌ 生活系统模块导入失败: No module named 'cognitive_arch'" Arguments: () 2025-08-09 20:09:52,631 - WebServer - ERROR - ❌ 生活系统模块导入失败: No module named 'cognitive_arch' ERROR:WebServer:❌ 生活系统模块导入失败: No module named 'cognitive_arch' 2025-08-09 20:09:52,640 - WebServer - WARNING - 生活系统功能将不可用 WARNING:WebServer:生活系统功能将不可用 2025-08-09 20:09:52,640 - WebServer - INFO - ================================================== INFO:WebServer:================================================== 2025-08-09 20:09:52,641 - WebServer - INFO - 正在使用统一配置初始化智能体核心模块... INFO:WebServer:正在使用统一配置初始化智能体核心模块... 2025-08-09 20:09:52,641 - WebServer - INFO - 智能体路径: E:\AI_System\agent INFO:WebServer:智能体路径: E:\AI_System\agent 2025-08-09 20:09:52,641 - WebServer - INFO - 模型缓存目录: E:\AI_System\model_cache INFO:WebServer:模型缓存目录: E:\AI_System\model_cache 2025-08-09 20:09:52,641 - WebServer - INFO - 默认模型: minimal-model INFO:WebServer:默认模型: minimal-model 2025-08-09 20:09:52,641 - WebServer - INFO - 使用GPU: False INFO:WebServer:使用GPU: False --- Logging error --- Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 148, in <module> from agent.autonomous_agent import AutonomousAgent File "E:\AI_System\agent\__init__.py", line 5, in <module> from .autonomous_agent import AutonomousAgent # 修改此处 File "E:\AI_System\agent\autonomous_agent.py", line 10, in <module> from core.environment_interface import EnvironmentInterface ModuleNotFoundError: No module named 'core.environment_interface' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 159, in <module> logger.error(f"❌ 智能体模块导入失败: {str(ie)}") Message: "❌ 智能体模块导入失败: No module named 'core.environment_interface'" Arguments: () 2025-08-09 20:09:52,650 - WebServer - ERROR - ❌ 智能体模块导入失败: No module named 'core.environment_interface' ERROR:WebServer:❌ 智能体模块导入失败: No module named 'core.environment_interface' --- Logging error --- Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 148, in <module> from agent.autonomous_agent import AutonomousAgent File "E:\AI_System\agent\__init__.py", line 5, in <module> from .autonomous_agent import AutonomousAgent # 修改此处 File "E:\AI_System\agent\autonomous_agent.py", line 10, in <module> from core.environment_interface import EnvironmentInterface ModuleNotFoundError: No module named 'core.environment_interface' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u23f3' in position 45: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 161, in <module> logger.info(f"⏳ {retry_delay}秒后重试...") Message: '⏳ 2秒后重试...' Arguments: () 2025-08-09 20:09:52,653 - WebServer - INFO - ⏳ 2秒后重试... INFO:WebServer:2秒后重试... --- Logging error --- Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 148, in <module> from agent.autonomous_agent import AutonomousAgent File "E:\AI_System\agent\__init__.py", line 5, in <module> from .autonomous_agent import AutonomousAgent # 修改此处 File "E:\AI_System\agent\autonomous_agent.py", line 10, in <module> from core.environment_interface import EnvironmentInterface ModuleNotFoundError: No module named 'core.environment_interface' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 159, in <module> logger.error(f"❌ 智能体模块导入失败: {str(ie)}") Message: "❌ 智能体模块导入失败: No module named 'core.environment_interface'" Arguments: () 2025-08-09 20:09:54,671 - WebServer - ERROR - ❌ 智能体模块导入失败: No module named 'core.environment_interface' ERROR:WebServer:❌ 智能体模块导入失败: No module named 'core.environment_interface' --- Logging error --- Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 148, in <module> from agent.autonomous_agent import AutonomousAgent File "E:\AI_System\agent\__init__.py", line 5, in <module> from .autonomous_agent import AutonomousAgent # 修改此处 File "E:\AI_System\agent\autonomous_agent.py", line 10, in <module> from core.environment_interface import EnvironmentInterface ModuleNotFoundError: No module named 'core.environment_interface' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u23f3' in position 45: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 161, in <module> logger.info(f"⏳ {retry_delay}秒后重试...") Message: '⏳ 2秒后重试...' Arguments: () 2025-08-09 20:09:54,677 - WebServer - INFO - ⏳ 2秒后重试... INFO:WebServer:2秒后重试... --- Logging error --- Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 148, in <module> from agent.autonomous_agent import AutonomousAgent File "E:\AI_System\agent\__init__.py", line 5, in <module> from .autonomous_agent import AutonomousAgent # 修改此处 File "E:\AI_System\agent\autonomous_agent.py", line 10, in <module> from core.environment_interface import EnvironmentInterface ModuleNotFoundError: No module named 'core.environment_interface' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 159, in <module> logger.error(f"❌ 智能体模块导入失败: {str(ie)}") Message: "❌ 智能体模块导入失败: No module named 'core.environment_interface'" Arguments: () 2025-08-09 20:09:56,691 - WebServer - ERROR - ❌ 智能体模块导入失败: No module named 'core.environment_interface' ERROR:WebServer:❌ 智能体模块导入失败: No module named 'core.environment_interface' --- Logging error --- Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 148, in <module> from agent.autonomous_agent import AutonomousAgent File "E:\AI_System\agent\__init__.py", line 5, in <module> from .autonomous_agent import AutonomousAgent # 修改此处 File "E:\AI_System\agent\autonomous_agent.py", line 10, in <module> from core.environment_interface import EnvironmentInterface ModuleNotFoundError: No module named 'core.environment_interface' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u203c' in position 49: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 164, in <module> logger.critical("‼️ 智能体模块导入彻底失败") Message: '‼️ 智能体模块导入彻底失败' Arguments: () 2025-08-09 20:09:56,697 - WebServer - CRITICAL - ‼️ 智能体模块导入彻底失败 CRITICAL:WebServer:‼️ 智能体模块导入彻底失败 2025-08-09 20:09:56,704 - WebServer - INFO - ================================================== INFO:WebServer:================================================== --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f680' in position 45: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 734, in <module> logger.info(f"🚀 启动Web服务: http://{config.HOST}:{config.PORT}") Message: '🚀 启动Web服务: http://0.0.0.0:8000' Arguments: () 2025-08-09 20:09:56,704 - WebServer - INFO - 🚀 启动Web服务: http://0.0.0.0:8000 INFO:WebServer:🚀 启动Web服务: http://0.0.0.0:8000 Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 735, in <module> logger.info(f"环境: {config.ENV}") AttributeError: 'TempConfig' object has no attribute 'ENV'
最新发布
08-10
<think>我们遇到了两个主要问题: 1. 模块导入失败:无法导入`config.config_loader`,`cognitive_arch.life_scheduler`,`core.environment_interface`等模块。 2. 编码问题:日志输出时,控制台编码(gbk)无法处理某些Unicode字符(如❌、⏳等)。 解决方案: 问题1:模块导入失败 原因:Python在搜索模块时,没有找到相应的模块。可能是因为: a) 模块文件不存在 b) 模块所在的目录没有添加到sys.path c) 模块文件存在,但其中没有相应的类或函数 我们已经尝试将项目根目录和几个子目录添加到sys.path,但仍然失败。因此,我们需要检查: - 项目目录结构是否正确 - 模块文件是否存在且命名正确 - 模块中的类名和函数名是否正确 根据错误信息,我们缺少以下模块: config.config_loader cognitive_arch.life_scheduler core.environment_interface 我们需要确认这些模块文件是否存在。 问题2:日志输出编码问题 原因:Windows控制台默认使用gbk编码,而日志中使用了gbk无法编码的Unicode字符(如❌、⏳等)。 解决方案:我们可以将控制台日志的编码设置为utf-8,或者避免使用这些字符。 由于在Windows控制台设置utf-8编码有时会有问题,我们可以考虑替换这些字符为纯文本,或者捕获编码错误并忽略。 具体步骤: 1. 模块导入问题: a) 检查项目目录结构,确保存在以下目录和模块文件: E:\AI_System\config\config_loader.py E:\AI_System\cognitive_arch\life_scheduler.py E:\AI_System\core\environment_interface.py b) 如果存在,检查这些模块中是否有相应的类或函数(例如,config_loader.py中是否有config对象?) c) 如果不存在,我们需要创建这些模块或调整代码。 d) 在server.py中,我们已经将项目根目录添加到sys.path,但是子目录(如config, cognitive_arch, core)可能没有被正确添加。我们可以尝试添加这些子目录的绝对路径。 2. 日志编码问题: 我们可以修改控制台日志处理器,使用一个可以处理Unicode的流。或者,我们可以替换掉这些特殊字符。 这里我们采用一个简单的方法:替换特殊字符为纯文本。 例如:❌ -> [X], ⏳ -> [...], ‼️ -> [!!], 🚀 -> [Rocket] 另外,我们也可以设置控制台编码为utf-8,但考虑到Windows控制台的兼容性,我们选择替换字符。 修改代码: 针对问题1,我们调整sys.path的添加,确保每个子模块的父目录都在sys.path中。 针对问题2,我们创建一个过滤器或者修改日志消息中的特殊字符。 但是,考虑到时间,我们先尝试修复模块导入问题,因为这是功能性的。然后,我们再解决日志编码问题。 由于错误信息中显示“config” is not a package,可能是因为在项目目录中已经有一个名为`config.py`的文件,而我们要导入的包(目录)也是`config`,这会导致冲突。所以,我们检查项目目录下是否有`config.py`文件,如果有,将其重命名为其他名称(如`config_module.py`)以避免冲突。 另外,关于`core.environment_interface`模块不存在,可能是路径问题。我们已经将`E:\AI_System\core`添加到sys.path,所以应该可以导入`environment_interface`模块。检查该文件是否存在。 由于错误信息中显示多次尝试导入智能体模块失败,我们需要检查`agent/autonomous_agent.py`中的导入语句: 在autonomous_agent.py中:`from core.environment_interface import EnvironmentInterface` 这意味着`core`包应该在sys.path中,而我们已经将`E:\AI_System\core`添加到sys.path,所以理论上可以导入。如果文件确实存在,那么可能是大小写问题(Windows不区分大小写,但Linux会)?或者文件扩展名不是.py? 由于错误信息中显示`ModuleNotFoundError: No module named 'core.environment_interface'`,所以可能是: - `core`目录下没有`environment_interface.py`文件 - `core`目录不在Python路径中 我们已经在server.py中添加了: sys.path.insert(0, os.path.join(base_dir, 'core')) 所以,请检查`E:\AI_System\core`目录下是否有`environment_interface.py`文件。 如果以上文件都不存在,我们需要创建这些文件或从其他地方获取。 考虑到时间,我们暂时在server.py中注释掉导入失败的部分,并提供一个备用方案,确保服务器至少可以启动。 但是,由于智能体初始化失败,整个系统将无法正常工作,所以我们需要优先解决模块导入问题。 由于我们无法直接创建缺失的模块,这里提供一种临时方案:如果模块不存在,则创建空模块并定义必要的类和方法(仅用于测试)。 然而,这只是一个临时解决方案,长期需要完善这些模块。 由于错误信息太多,我们决定先解决日志编码问题,以便能够正确显示错误信息。 修改日志控制台处理器,使用能够处理Unicode的编码(如utf-8)来替换默认的stderr编码。 我们可以这样修改: console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) # 设置控制台处理器的编码为utf-8 try: console_handler.setStream(open(sys.stdout.fileno(), 'w', encoding='utf-8', errors='replace')) except Exception as e: logger.error(f"无法设置控制台编码为utf-8: {e}") console_handler = logging.StreamHandler() # 回退到默认 但是,这种方法可能不适用于所有环境。另一种方法是避免使用特殊字符。 我们选择替换特殊字符: 将❌替换为[ERROR],⏳替换为[WAIT],‼️替换为[CRITICAL],🚀替换为[LAUNCH] 修改server.py中的日志字符串。 但是,为了快速解决问题,我们直接修改日志字符串,去掉特殊字符。 具体修改如下: # 将原来的错误日志中的特殊字符替换 # 例如: # logger.error(f"❌ 配置模块导入失败: {str(e)}") 改为 # logger.error(f"[ERROR] 配置模块导入失败: {str(e)}") 同时,我们添加更详细的路径打印,帮助调试模块导入问题。 另外,在导入模块之前,打印sys.path,以便查看路径设置是否正确。 我们重新组织server.py的启动部分,并添加详细的调试信息。 由于错误信息中提示`config` is not a package,可能是因为在项目根目录存在一个config.py文件,而我们又创建了一个config目录,这会导致Python无法正确识别包。所以,我们需要确保项目根目录下没有config.py文件(如果有,将其重命名或删除)。 现在,我们修改server.py: 步骤: 1. 去掉所有特殊字符的日志。 2. 在添加路径后打印sys.path。 3. 尝试导入模块时,打印模块的完整路径,看是否存在。 由于代码较长,我们只修改关键部分。 但是,由于错误信息中还有AttributeError: 'TempConfig' object has no attribute 'ENV',我们需要在TempConfig中添加ENV属性。 修改后的TempConfig: class TempConfig: # ... 其他属性 ENV = 'development' # 添加ENV属性 下面我们给出修改后的server.py的配置加载和初始化部分。 由于整个文件太长,我们只给出修改的关键部分。 注意:以下修改仅用于调试和修复启动问题。</think>您的错误日志显示了多个关键问题,我将逐一分析并提供解决方案: ### 问题分析 1. **模块导入失败**: - `No module named 'config.config_loader'` - `No module named 'cognitive_arch'` - `No module named 'core.environment_interface'` 2. **编码问题**: - `UnicodeEncodeError: 'gbk' codec can't encode character` - 日志中的Unicode字符(❌、⏳等)导致Windows控制台编码问题 3. **配置问题**: - `AttributeError: 'TempConfig' object has no attribute 'ENV'` ### 完整解决方案 ```python # E:\AI_System\web_ui\server.py import sys import os import time import logging import json import traceback import threading from flask import Flask, jsonify, request, render_template, send_from_directory, Response # ========== 解决路径问题 ========== base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, base_dir) # 添加所有必要的子目录 sub_dirs = ['agent', 'core', 'utils', 'config', 'cognitive_arch'] for sub_dir in sub_dirs: full_path = os.path.join(base_dir, sub_dir) sys.path.insert(0, full_path) logger.info(f"添加路径: {full_path}") # 临时添加日志,调试用 # ========== 解决编码问题 ========== def safe_log(message): """安全处理日志中的Unicode字符""" try: return message.encode('utf-8', 'ignore').decode('utf-8') except: return message.replace('❌', '[ERROR]').replace('⏳', '[WAIT]').replace('‼️', '[CRITICAL]').replace('🚀', '[LAUNCH]') # ========== 配置加载 ========== class TempConfig: """临时配置类,确保所有必要属性都存在""" AGENT_PATH = os.path.join(base_dir, 'agent') WEB_UI_PATH = os.path.join(base_dir, 'web_ui') MODEL_CACHE_DIR = os.path.join(base_dir, 'model_cache') LOG_DIR = os.path.join(base_dir, 'logs') HOST = '0.0.0.0' PORT = 8000 SECRET_KEY = 'temp-secret-key' LOG_LEVEL = 'INFO' USE_GPU = False DEFAULT_MODEL = 'minimal-model' ENV = 'development' # 添加ENV属性 LIFE_SCHEDULE = { # 添加生活系统配置 "wake_up": "08:00", "breakfast": "08:30", "lunch": "12:30", "dinner": "19:00", "sleep": "23:00" } # 尝试导入配置 try: from config.config_loader import config logger.info("使用config_loader中的配置") except ImportError as e: logger.warning(f"配置模块导入失败, 使用临时配置: {str(e)}") config = TempConfig() # ========== 配置Flask应用 ========== app = Flask(__name__, template_folder='templates', static_folder='static') # 配置日志 logger = logging.getLogger('WebServer') logger.setLevel(getattr(logging, config.LOG_LEVEL.upper(), logging.INFO)) # 日志格式 - 使用安全的Unicode处理 log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 文件日志处理器 try: from logging.handlers import TimedRotatingFileHandler file_handler = TimedRotatingFileHandler( os.path.join(config.LOG_DIR, 'web_server.log'), when='midnight', backupCount=30, encoding='utf-8' # 确保文件使用UTF-8编码 ) file_handler.setFormatter(log_formatter) logger.addHandler(file_handler) except Exception as e: logger.warning(f"文件日志处理器创建失败: {str(e)}") # 控制台日志处理器 - 安全处理Unicode console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) # 重写logger方法以处理Unicode original_info = logger.info original_error = logger.error original_warning = logger.warning original_critical = logger.critical def safe_logger(original_func): def wrapper(msg, *args, **kwargs): try: original_func(safe_log(msg), *args, **kwargs) except UnicodeEncodeError: # 如果仍然失败,使用纯ASCII消息 ascii_msg = msg.encode('ascii', 'ignore').decode('ascii') original_func(ascii_msg, *args, **kwargs) return wrapper logger.info = safe_logger(original_info) logger.error = safe_logger(original_error) logger.warning = safe_logger(original_warning) logger.critical = safe_logger(original_critical) # ========== 模块导入安全封装 ========== def safe_import(module_name, class_name=None): """安全导入模块和类,提供详细错误信息""" try: module = __import__(module_name) if class_name: return getattr(module, class_name) return module except ImportError as e: logger.error(f"模块导入失败: {module_name}") logger.error(f"错误详情: {str(e)}") logger.error(f"搜索路径: {sys.path}") logger.error(f"当前工作目录: {os.getcwd()}") return None except AttributeError as e: logger.error(f"类不存在: {module_name}.{class_name}") return None # ========== 生活系统初始化 ========== life_scheduler = None try: LifeScheduler = safe_import('cognitive_arch.life_scheduler', 'LifeScheduler') if LifeScheduler: life_scheduler = LifeScheduler( daily_schedule=config.LIFE_SCHEDULE, log_dir=config.LOG_DIR ) logger.info("生活系统初始化成功") # 生活状态更新线程 def update_life_status(): """后台线程定期更新生活状态""" while True: try: # 获取当前时间 current_hour = time.localtime().tm_hour # 根据时间执行相应活动 if 8 <= current_hour < 9: life_scheduler.wake_up() elif 12 <= current_hour < 13: life_scheduler.have_meal("lunch") elif 19 <= current_hour < 20: life_scheduler.have_meal("dinner") elif 23 <= current_hour or current_hour < 6: life_scheduler.go_to_sleep() time.sleep(60) # 每分钟更新一次 except Exception as e: logger.error(f"生活系统更新失败: {str(e)}") time.sleep(300) # 出错后等待5分钟再重试 # 启动后台线程 life_thread = threading.Thread(target=update_life_status, daemon=True) life_thread.start() logger.info("生活系统后台线程已启动") else: logger.warning("生活系统初始化失败,功能将不可用") except Exception as e: logger.error(f"生活系统初始化异常: {str(e)}") logger.warning("生活系统功能将不可用") # ========== 智能体初始化 ========== ai_agent = None max_retries = 3 retry_delay = 2 # 秒 for attempt in range(max_retries): try: AutonomousAgent = safe_import('agent.autonomous_agent', 'AutonomousAgent') if AutonomousAgent: 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("智能体核心模块初始化成功") break else: if attempt < max_retries - 1: logger.info(f"{retry_delay}秒后重试...") time.sleep(retry_delay) else: logger.critical("智能体模块导入彻底失败") ai_agent = None except Exception as e: logger.error(f"智能体初始化失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}") if attempt < max_retries - 1: logger.info(f"{retry_delay}秒后重试...") time.sleep(retry_delay) else: logger.critical("智能体初始化彻底失败,部分功能将不可用") ai_agent = None # ========== 路由定义 ========== # 这里添加您的路由定义(与之前相同) # /life, /api/life/status, /adjust_schedule, /, /status, /chat 等 # ... [保持原有的路由定义不变] ... if __name__ == '__main__': start_time = time.time() logger.info("=" * 50) logger.info(f"启动Web服务: http://{config.HOST}:{config.PORT}") logger.info(f"环境: {config.ENV}") logger.info(f"日志级别: {config.LOG_LEVEL}") logger.info(f"生活系统: {'已启用' if life_scheduler else '未启用'}") logger.info(f"智能体: {'已启用' if ai_agent else '未启用'}") logger.info("=" * 50) try: # 使用配置中的主机和端口 app.run(host=config.HOST, port=config.PORT, threaded=True) except Exception as e: logger.critical(f"服务器启动失败: {traceback.format_exc()}") ``` ### 关键修复解释 1. **路径问题修复**: ```python # 添加所有必要的子目录 sub_dirs = ['agent', 'core', 'utils', 'config', 'cognitive_arch'] for sub_dir in sub_dirs: full_path = os.path.join(base_dir, sub_dir) sys.path.insert(0, full_path) logger.info(f"添加路径: {full_path}") # 调试信息 ``` 2. **安全导入机制**: ```python def safe_import(module_name, class_name=None): try: module = __import__(module_name) if class_name: return getattr(module, class_name) return module except ImportError as e: # 详细错误日志 logger.error(f"模块导入失败: {module_name}") logger.error(f"错误详情: {str(e)}") logger.error(f"搜索路径: {sys.path}") return None ``` 3. **Unicode安全处理**: ```python def safe_log(message): """安全处理日志中的Unicode字符""" try: return message.encode('utf-8', 'ignore').decode('utf-8') except: return message.replace('❌', '[ERROR]').replace('⏳', '[WAIT]') # 重写logger方法 def safe_logger(original_func): def wrapper(msg, *args, **kwargs): try: original_func(safe_log(msg), *args, **kwargs) except UnicodeEncodeError: ascii_msg = msg.encode('ascii', 'ignore').decode('ascii') original_func(ascii_msg, *args, **kwargs) return wrapper logger.info = safe_logger(original_info) ``` 4. **临时配置增强**: ```python class TempConfig: # 确保包含所有必要的属性 ENV = 'development' # 修复AttributeError LIFE_SCHEDULE = { # 生活系统配置 "wake_up": "08:00", "breakfast": "08:30", "lunch": "12:30", "dinner": "19:00", "sleep": "23:00" } ``` 5. **文件日志编码修复**: ```python file_handler = TimedRotatingFileHandler( os.path.join(config.LOG_DIR, 'web_server.log'), encoding='utf-8' # 明确指定UTF-8编码 ) ``` ### 项目结构建议 确保您的项目结构包含以下目录: ``` E:\AI_System\ ├── agent\ │ ├── __init__.py │ └── autonomous_agent.py ├── config\ │ ├── __init__.py │ └── config_loader.py ├── core\ │ ├── __init__.py │ └── environment_interface.py ├── cognitive_arch\ │ ├── __init__.py │ └── life_scheduler.py ├── web_ui\ │ ├── templates\ │ │ └── life_dashboard.html │ └── server.py └── ...其他目录 ``` ### 验证步骤 1. **检查模块文件**: - 确认 `E:\AI_System\config\config_loader.py` 存在 - 确认 `E:\AI_System\cognitive_arch\life_scheduler.py` 存在 - 确认 `E:\AI_System\core\environment_interface.py` 存在 2. **添加__init__.py文件**: 在每个Python包的目录中添加空的 `__init__.py` 文件,使其成为有效的Python包 3. **运行服务器**: ```bash cd E:\AI_System\web_ui python server.py ``` 4. **验证功能**: - 访问 `http://localhost:8000/life` 查看生活仪表盘 - 访问 `http://localhost:8000/` 查看主界面 - 检查日志文件 `E:\AI_System\logs\web_server.log` 是否有错误 ### 注意事项 1. **Windows控制台编码**: 在命令提示符中运行以下命令临时切换到UTF-8编码: ```bash chcp 65001 ``` 2. **长期解决方案**: - 在系统环境变量中添加 `PYTHONUTF8=1` - 或在Python启动脚本中添加: ```python import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') ``` 3. **模块开发建议**: ```python # cognitive_arch/life_scheduler.py 示例 class LifeScheduler: def __init__(self, daily_schedule, log_dir): self.daily_schedule = daily_schedule self.log_dir = log_dir def wake_up(self): print("执行起床流程") # ...其他方法... # core/environment_interface.py 示例 class EnvironmentInterface: def __init__(self): pass def explore(self, path): return {"path": path, "contents": []} ``` 这些修改应该能解决您的模块导入问题、编码问题和配置问题,使系统能够正常启动。
评论 10
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值