loading.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import pkgutil
  2. import sys
  3. from importlib import import_module
  4. from pathlib import Path
  5. from types import ModuleType
  6. from typing import List
  7. def get_path(module: ModuleType) -> str:
  8. if getattr(sys, "frozen", False):
  9. # frozen
  10. if getattr(sys, "_MEIPASS", False):
  11. # PyInstaller
  12. lib_dir = Path(getattr(sys, "_MEIPASS"))
  13. else:
  14. # others
  15. lib_dir = Path(sys.executable).parent / "lib"
  16. path = lib_dir.joinpath(*module.__package__.split(".")) # type: ignore
  17. else:
  18. # unfrozen
  19. path = Path(module.__file__).parent
  20. return str(path)
  21. def list_module(module: ModuleType) -> List[str]:
  22. path = get_path(module)
  23. if getattr(sys, "_MEIPASS", False):
  24. # PyInstaller
  25. return [file.parent.name for file in Path(path).glob("*/__init__.py")]
  26. else:
  27. return [name for _, name, is_pkg in pkgutil.iter_modules([str(path)]) if is_pkg]
  28. def find_available_locales(providers: List[str]) -> List[str]:
  29. available_locales = set()
  30. for provider_path in providers:
  31. provider_module = import_module(provider_path)
  32. if getattr(provider_module, "localized", False):
  33. langs = list_module(provider_module)
  34. available_locales.update(langs)
  35. return sorted(available_locales)
  36. def find_available_providers(modules: List[ModuleType]) -> List[str]:
  37. available_providers = set()
  38. for providers_mod in modules:
  39. if providers_mod.__package__:
  40. providers = [
  41. ".".join([providers_mod.__package__, mod]) for mod in list_module(providers_mod) if mod != "__pycache__"
  42. ]
  43. available_providers.update(providers)
  44. return sorted(available_providers)