File size: 5,202 Bytes
60eb61b
e9a40a0
9b6b71a
60eb61b
9b6b71a
60eb61b
 
 
 
 
 
 
 
 
9b6b71a
 
f0eebb6
60eb61b
9b6b71a
 
60eb61b
 
 
 
 
 
12973c2
9b6b71a
 
 
 
60eb61b
 
 
 
885e372
60eb61b
 
 
9b6b71a
 
60eb61b
 
 
 
 
 
 
 
 
 
9b6b71a
 
 
 
 
 
60eb61b
9b6b71a
 
 
 
 
 
 
 
 
 
 
 
60eb61b
 
b2d2e08
60eb61b
 
 
 
 
7d2c88f
 
 
60eb61b
7d2c88f
60eb61b
 
9b6b71a
60eb61b
 
 
 
 
 
 
 
 
 
 
9b6b71a
 
 
 
 
 
 
 
 
60eb61b
2521560
 
 
 
9b6b71a
 
2521560
 
 
60eb61b
 
 
9b6b71a
 
60eb61b
9b6b71a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b05b325
60eb61b
 
 
9b6b71a
60eb61b
 
 
 
 
 
 
 
0c44420
60eb61b
 
 
 
 
 
 
 
 
 
 
9b6b71a
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import os
import re
import sys
import datasets
import pandas as pd
from huggingface_hub import HfFileSystem
from typing import List

logger = datasets.logging.get_logger(name=__name__)
fs = HfFileSystem()

_CITATION = """
"""

_DESCRIPTION = """\
    This dataset contain file about datetime date. 
    It's created with purpose is practice loading dataset from hugging face hub."""

_HOMEPAGE = """\
    https://github.com/minhnv4099
"""

_REPO = "datasets/nguyenminh4099/date-data"
_BRANCH = "main"
_REPO_BRANCH = f"{_REPO}@{_BRANCH}"

_REPO_URL = f"https://huggingface.co/{_REPO}/resolve/{_BRANCH}"
_URLS = {
    'zipfile': os.path.join(_REPO_URL, "data", "{}.zip"),
    'metadata': _REPO_URL + "/metadata.parquet",
}

_CONFIGS = ['all']
_CONFIGS.extend(
    os.path.basename(file)[:-4]
    for file in fs.listdir(_REPO_BRANCH + "/data/", detail=False)
    if file.endswith('.zip')
)


# TODO: Define Dataset Builder config
class DateDataConfig(datasets.BuilderConfig):
    def __init__(
        self,
        name: str,
        **kwargs,        
    ):
        super(DateDataConfig, self).__init__(
            name=name,
            version=datasets.Version("1.0.0"),
        )
        # self.metadata = metadata
        # self.url = kwargs.get('url', "https://huggingface.co/datasets/nguyenminh4099/date-data")
        # self.data_url = kwargs.get('data_url', None)
        # self.description = kwargs.get('description', _DESCRIPTION)
        # logger.info('call BuilderConfig')


# TODO: Define Dataset Builder
class DateData(datasets.GeneratorBasedBuilder):
    logger.info('call dataset builder')

    BUILDER_CONFIGS = [
        DateDataConfig(
            name=name,
            # metadata=_URLS['metadata'],
            # data_url=_URLS['zipfile'].format(name),
        ) 
        for name in _CONFIGS
    ]
    DEFAULT_CONFIG_NAME = 'all'

    def _info(self) -> datasets.DatasetInfo:
        features = datasets.Features({
            "id": datasets.Value('string'),
            "dow": datasets.Value('string'),
            "month": datasets.Value('string'),
            "dom": datasets.Value('string'),
            "hour": datasets.Value('string'),
            "min": datasets.Value('string'),
            "second": datasets.Value('string'),
            "timezone": datasets.Value('string'),
            "year": datasets.Value('string'),
            "file_path": datasets.Value('string'),
        })
        print(self.config)
        return datasets.DatasetInfo(
            features=features,
            description=_DESCRIPTION,
            citation=_CITATION,
            homepage=_HOMEPAGE,
        )

    def _split_generators(
        self,
        dl_manager: datasets.DownloadManager,
    ) -> List[datasets.SplitGenerator]:
        logger.info("Call _split_generators")
    
        configs = _CONFIGS[1:5] if self.config.name == 'all' else [self.config.name]
        data_files = {
            config : _URLS['zipfile'].format(config)
            for config in configs
        }
        data_dict = dl_manager.download_and_extract(data_files)
        print(data_dict)

        return [
                datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "metadata": _URLS['metadata'],
                    "data_dict": data_dict,
                }
            )
        ]

    def _generate_examples(
        self,
        metadata: str,
        data_dict: dict,
    ) -> dict:
        logger.info("Call _generate_examples")
        infos = datasets.load_dataset(
            "parquet",
            data_files=[metadata],
            split='train',
        )
        metadata_df = infos.to_pandas()
        data_df = pd.DataFrame(
            {
                "shard" : list(data_dict.keys()),
                "data_dir" : list(data_dict.values()),
            },
            columns=['shard', 'data_dir'],
            index=range(len(data_dict))
        )

        metadata_df = metadata_df.merge(
            right=data_df,
            how='right',
            left_on='shard',
            right_on='shard',
            sort=True,
        )

        for i, sample in enumerate(metadata_df.itertuples()):
            file_name = os.path.join(
                sample.data_dir, sample.id + ".txt"
            )
            example = self._read_txt(file_name=file_name)
            example['id'] = sample.id
            example['file_path'] = file_name
            
            yield i, example

    def _read_txt(
        self,
        file_name: str,
    ) -> dict:
        with open(file=file_name, mode='r') as f:
            return self._extract_datetime(f.read())
    
    def _extract_datetime(
        self,
        datetime_string: str,
    ) -> dict:
        datetime_string = datetime_string.strip("./ ")
        components = re.split(pattern=r'[\s\:]+', string=datetime_string)

        return {
            "dow": components[0],
            "month": components[1],
            "dom": components[2],
            "hour": components[3],
            "min": components[4],
            "second": components[5],
            "timezone": components[6],
            "year": components[7],
        }
DateData()