|
| 1 | +import os |
| 2 | + |
| 3 | +import pandas as pd |
| 4 | +import pyreadr |
| 5 | + |
| 6 | + |
| 7 | +class Datatoy: |
| 8 | + """Easily install & load curated Republic of Korea public datasets from https://github.com/statgarten/datatoys""" |
| 9 | + |
| 10 | + DATATOYS_URL = "https://github.com/statgarten/datatoys" |
| 11 | + README_POSTFIX = "/blob/main/README.md" |
| 12 | + DOWNLOAD_DIR = f"{os.path.join(os.getcwd(), '.datatoys')}" |
| 13 | + DATASET_HEADER_KO = "데이터셋" |
| 14 | + |
| 15 | + def __init__(self): |
| 16 | + self.__create_download_directory() |
| 17 | + self.manifest = self.get_manifest() |
| 18 | + |
| 19 | + def __create_download_directory(self): |
| 20 | + os.makedirs(self.DOWNLOAD_DIR, exist_ok=True) |
| 21 | + assert os.path.exists(self.DOWNLOAD_DIR) |
| 22 | + |
| 23 | + def _dataset_downloaded(self, dataset_nm: str) -> bool: |
| 24 | + return os.path.exists(f"{self.DOWNLOAD_DIR}/{dataset_nm}.rda") |
| 25 | + |
| 26 | + def _dataset_in_manifest(self, dataset_nm: str) -> bool: |
| 27 | + return dataset_nm in self.get_manifest_dataset_names() |
| 28 | + |
| 29 | + def get_manifest(self) -> pd.DataFrame: |
| 30 | + url = self.DATATOYS_URL + self.README_POSTFIX |
| 31 | + response = pd.read_html(url) |
| 32 | + assert len(response) == 1 and isinstance(response[0], pd.DataFrame) |
| 33 | + return response.pop() |
| 34 | + |
| 35 | + def get_manifest_dataset_names(self) -> list: |
| 36 | + return self.manifest.loc[:, self.DATASET_HEADER_KO].tolist() |
| 37 | + |
| 38 | + def show_manifest(self): |
| 39 | + print(self.get_manifest()) |
| 40 | + |
| 41 | + def install(self, dataset_nm: str) -> bool: |
| 42 | + """Install the dataset to the download directory. |
| 43 | + |
| 44 | + Args: |
| 45 | + dataset_nm (str): The name of the dataset to be deleted. |
| 46 | + |
| 47 | + Returns: |
| 48 | + return: return True if successfully installed otherwise false. |
| 49 | + |
| 50 | + Raises: |
| 51 | + raise ValueError: raise ValueError if the dataset is not in the manifest. |
| 52 | + """ |
| 53 | + |
| 54 | + remote_url = f"{self.DATATOYS_URL}/blob/main/data/{dataset_nm}.rda?raw=true" |
| 55 | + dst_path = f"{self.DOWNLOAD_DIR}/{dataset_nm}.rda" |
| 56 | + if not self._dataset_in_manifest(dataset_nm): |
| 57 | + raise ValueError( |
| 58 | + f"Dataset `{dataset_nm}` is not in the manifest. Check the manifest with `Datatoy().show_manifest()`." |
| 59 | + ) |
| 60 | + try: |
| 61 | + pyreadr.download_file(remote_url, dst_path) |
| 62 | + except Exception as e: |
| 63 | + print(f"Exception occured while downloading {remote_url}", e) |
| 64 | + return False |
| 65 | + assert self._dataset_downloaded(dataset_nm) |
| 66 | + return True |
| 67 | + |
| 68 | + def load(self, dataset_nm: str) -> pd.DataFrame: |
| 69 | + """Load the dataset from the download directory. |
| 70 | + |
| 71 | + Calls `Datatoy().install()` if the dataset is not downloaded. |
| 72 | + |
| 73 | + Args: |
| 74 | + dataset_nm (str): The name of the dataset to be deleted. |
| 75 | + |
| 76 | + Returns: |
| 77 | + return: pandas.DataFrame |
| 78 | + """ |
| 79 | + |
| 80 | + dst_path = f"{self.DOWNLOAD_DIR}/{dataset_nm}.rda" |
| 81 | + if not self._dataset_downloaded(dataset_nm): |
| 82 | + print(f"Dataset `{dataset_nm}` is not installed. Installing it first.") |
| 83 | + self.install(dataset_nm) |
| 84 | + res = pyreadr.read_r(dst_path) |
| 85 | + data = res.get(dataset_nm) |
| 86 | + assert isinstance(data, pd.DataFrame) |
| 87 | + return data |
| 88 | + |
| 89 | + def clean(self, dataset_nm: str) -> bool: |
| 90 | + """Delete the dataset from the download directory. |
| 91 | + |
| 92 | + Args: |
| 93 | + dataset_nm (str): The name of the dataset to be deleted. |
| 94 | + |
| 95 | + Returns: |
| 96 | + return: return True if the dataset is deleted successfully otherwise false. |
| 97 | + """ |
| 98 | + |
| 99 | + dst_path = f"{self.DOWNLOAD_DIR}/{dataset_nm}.rda" |
| 100 | + if self._dataset_downloaded(dataset_nm): |
| 101 | + os.remove(dst_path) |
| 102 | + return True |
| 103 | + return False |
| 104 | + |
| 105 | + def clean_all(self): |
| 106 | + """Cleanup all datasets within the download directory.""" |
| 107 | + |
| 108 | + for dataset_nm in self.get_manifest_dataset_names(): |
| 109 | + self.clean(dataset_nm) |
| 110 | + |
| 111 | + |
| 112 | +if __name__ == "__main__": |
| 113 | + dt = Datatoy() |
| 114 | + dt.show_manifest() |
| 115 | + dataset_nm = "karaoke" |
| 116 | + df = dt.load("karaoke") |
| 117 | + print(df.head()) |
| 118 | + dt.clean(dataset_nm) |
0 commit comments