|
| 1 | +import json |
| 2 | +import os |
| 3 | + |
| 4 | +ENCODE = "utf-8" |
| 5 | + |
| 6 | + |
| 7 | +class PrecomputeData: |
| 8 | + def __init__(self, dir_path: str) -> None: |
| 9 | + """ |
| 10 | + Initialize the PrecomputeData object. |
| 11 | +
|
| 12 | + Parameters |
| 13 | + ---------- |
| 14 | + dir_path : str |
| 15 | + The directory path to save the precompute data. |
| 16 | +
|
| 17 | + Raises |
| 18 | + ------ |
| 19 | + Exception |
| 20 | + """ |
| 21 | + self._dir_path = dir_path |
| 22 | + |
| 23 | + def read_json_data(self, module_name: str) -> dict: |
| 24 | + """ |
| 25 | + Read the precompute data from the file. |
| 26 | +
|
| 27 | + Returns |
| 28 | + ------- |
| 29 | + dict |
| 30 | + The precompute data. |
| 31 | +
|
| 32 | + Raises |
| 33 | + ------ |
| 34 | + Exception |
| 35 | + """ |
| 36 | + |
| 37 | + with open(f"{self._dir_path}/{module_name}.json", "r", encoding=ENCODE) as file: |
| 38 | + return json.load(file) |
| 39 | + |
| 40 | + def write_json_data(self, data: dict, module_name: str) -> None: |
| 41 | + """ |
| 42 | + Write the precompute data to the file. |
| 43 | +
|
| 44 | + Parameters |
| 45 | + ---------- |
| 46 | + data : dict |
| 47 | + The data to write. |
| 48 | +
|
| 49 | + Raises |
| 50 | + ------ |
| 51 | + Exception |
| 52 | + """ |
| 53 | + if not os.path.exists(self._dir_path): |
| 54 | + os.makedirs(self._dir_path) |
| 55 | + |
| 56 | + with open(f"{self._dir_path}/{module_name}.json", "w", encoding=ENCODE) as file: |
| 57 | + json.dump(data, file, indent=4) |
| 58 | + |
| 59 | + def remove_precompute_data(self) -> None: |
| 60 | + """ |
| 61 | + Remove the precompute data file. |
| 62 | + """ |
| 63 | + if os.path.exists(self._dir_path): |
| 64 | + os.remove(self._dir_path) |
| 65 | + |
| 66 | + def is_available(self) -> bool: |
| 67 | + """ |
| 68 | + Check if the precompute data is available. |
| 69 | +
|
| 70 | + Returns |
| 71 | + ------- |
| 72 | + bool |
| 73 | + True if the precompute data is available, False otherwise. |
| 74 | + """ |
| 75 | + return os.path.exists(self._dir_path) |
0 commit comments