File size: 2,149 Bytes
2a9dc4c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | """Locate and expose the sibling or configured LingoLOGOS codex kernel.
This module allows datasets/codex-python to remain an external package without
copying or modifying datasets/codex. When lingologos_codex is already importable, nothing
is changed; otherwise the bridge searches LINGOLOGOS_CODEX_ROOT and ancestor datasets/codex
directories and inserts the matching root on sys.path.
"""
from __future__ import annotations
import importlib
import os
import sys
from pathlib import Path
from typing import Optional
def find_codex_root(start: Optional[Path] = None) -> Optional[Path]:
"""Return the path to the codex package root if found on disk."""
env_root = os.environ.get("LINGOLOGOS_CODEX_ROOT", "").strip()
if env_root:
candidate = Path(env_root).expanduser().resolve()
if (candidate / "lingologos_codex").is_dir():
return candidate
anchor = (start or Path(__file__)).resolve()
for parent in [anchor, *anchor.parents]:
direct = parent / "lingologos_codex"
if direct.is_dir():
return parent
sibling_codex = parent / "codex"
if (sibling_codex / "lingologos_codex").is_dir():
return sibling_codex
datasets_codex = parent / "datasets" / "codex"
if (datasets_codex / "lingologos_codex").is_dir():
return datasets_codex
return None
def ensure_codex_on_path(start: Optional[Path] = None) -> Path:
"""Ensure lingologos_codex is importable and return the resolved codex root."""
try:
mod = importlib.import_module("lingologos_codex")
mod_file = getattr(mod, "__file__", None)
if mod_file:
return Path(mod_file).resolve().parent.parent
except ImportError:
pass
codex_root = find_codex_root(start=start)
if codex_root is None:
raise ImportError(
"Unable to locate lingologos_codex. Install lingologos-codex or set LINGOLOGOS_CODEX_ROOT."
)
codex_str = str(codex_root)
if codex_str not in sys.path:
sys.path.insert(0, codex_str)
importlib.import_module("lingologos_codex")
return codex_root
|