diff --git a/chirp/path_utils.py b/chirp/path_utils.py index 4ab1b3b4..cbe6a68e 100644 --- a/chirp/path_utils.py +++ b/chirp/path_utils.py @@ -18,6 +18,7 @@ General utilities to help with handling paths. """ import os +from typing import BinaryIO, TextIO from etils import epath @@ -33,3 +34,7 @@ def get_absolute_path(relative_path: os.PathLike[str] | str) -> epath.Path: """ file_path = epath.Path(__file__).parent / relative_path return file_path + + +def open_file(relative_path: os.PathLike[str] | str, mode) -> TextIO | BinaryIO: + return open(get_absolute_path(relative_path), mode) diff --git a/chirp/taxonomy/namespace_db.py b/chirp/taxonomy/namespace_db.py index 11b1def0..7fccea77 100644 --- a/chirp/taxonomy/namespace_db.py +++ b/chirp/taxonomy/namespace_db.py @@ -22,10 +22,9 @@ from chirp import path_utils from chirp.taxonomy import namespace +from etils import epath -TAXONOMY_DATABASE_FILENAME = os.fspath( - path_utils.get_absolute_path("taxonomy/taxonomy_database.json") -) +TAXONOMY_DATABASE_FILENAME = "taxonomy/taxonomy_database.json" @dataclasses.dataclass @@ -136,7 +135,8 @@ def dump_db(taxonomy_database: TaxonomyDatabase, validate: bool = True) -> str: @functools.cache def load_db( - path: str = TAXONOMY_DATABASE_FILENAME, validate: bool = True + path: os.PathLike[str] | str = TAXONOMY_DATABASE_FILENAME, + validate: bool = True, ) -> TaxonomyDatabase: """Load the taxonomy database. @@ -151,8 +151,7 @@ def load_db( Returns: The taxonomy database. """ - fileobj = open(path, "r") - with fileobj as f: + with path_utils.open_file(path, "r") as f: data = json.load(f) taxonomy_database = load_taxonomy_database(data) if validate: