sitecustomize.start_error.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """
  2. PaddleX 适配器自动加载钩子
  3. 放置在 Python 搜索路径中,会在任何 Python 进程启动时自动执行
  4. """
  5. import os
  6. import sys
  7. def load_paddlex_adapters():
  8. """自动加载 PaddleX 适配器"""
  9. # 只有设置了环境变量才激活
  10. if os.getenv("PADDLEX_ENABLE_TABLE_ADAPTER", "").lower() not in ("true", "1", "yes"):
  11. return
  12. try:
  13. # 确保适配器路径在 sys.path
  14. adapter_base = os.path.dirname(os.path.abspath(__file__))
  15. adapters_path = os.path.join(adapter_base, 'adapters')
  16. if adapters_path not in sys.path:
  17. sys.path.insert(0, adapters_path)
  18. # 延迟导入,只有在实际使用时才加载
  19. def activate_adapter():
  20. try:
  21. from adapters.table_recognition_adapter import apply_table_recognition_adapter, restore_original_function
  22. if apply_table_recognition_adapter():
  23. print("✅ [sitecustomize] Table recognition adapter activated")
  24. except Exception as e:
  25. print(f"⚠️ [sitecustomize] Failed to activate adapter: {e}")
  26. # 监听 PaddleX 导入事件
  27. import importlib.abc
  28. import importlib.machinery
  29. class AdapterLoader(importlib.abc.MetaPathFinder):
  30. def find_module(self, fullname, path=None):
  31. if fullname == "paddlex.inference.pipelines.table_recognition.pipeline_v2":
  32. # 在目标模块导入后激活适配器
  33. activate_adapter()
  34. return None
  35. sys.meta_path.insert(0, AdapterLoader())
  36. except Exception as e:
  37. print(f"⚠️ [sitecustomize] Error setting up adapter hook: {e}")
  38. # 自动执行
  39. load_paddlex_adapters()