"""Repository asset resolution shared by BMC tutorial notebooks. When opening an individual notebook, save this file beside its Python source. """ def repo_file(path, *, base_url="https://raw.githubusercontent.com/BMClab/BMC/master/"): """Find a repository file beside this notebook, or fetch a temporary copy. Local files take precedence. Only file acquisition falls back to GitHub; parsing errors remain visible to the calling notebook. urllib3 selects its browser transport automatically without platform-specific imports. """ import hashlib import tempfile from pathlib import Path, PurePosixPath from urllib.parse import quote import marimo as mo import urllib3 relative = PurePosixPath(path) if relative.is_absolute() or ".." in relative.parts or "\\" in str(path): raise ValueError("Use a repository-relative path such as data/walk.trc") location = mo.notebook_dir() if location is not None: directory = Path(location).resolve() for base in (directory, *directory.parents): local = base.joinpath(*relative.parts) if local.is_file(): return local url = base_url.rstrip("/") + "/" + quote(relative.as_posix(), safe="/") key = hashlib.sha256(base_url.rstrip("/").encode()).hexdigest()[:16] cached = (Path(tempfile.gettempdir()) / "bmc-notebooks-v2" / key).joinpath(*relative.parts) if not cached.is_file(): response = urllib3.request("GET", url, timeout=30.0, retries=2) if response.status != 200: raise OSError(f"Cannot load {path}: HTTP {response.status} from {url}") cached.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=cached.parent, delete=False) as download: temporary = Path(download.name) download.write(response.data) try: temporary.replace(cached) finally: temporary.unlink(missing_ok=True) return cached