nguyenminh4099 commited on
Commit
9b6b71a
·
verified ·
1 Parent(s): 37990ef

Upload date-data.py

Browse files
Files changed (1) hide show
  1. date-data.py +79 -21
date-data.py CHANGED
@@ -1,6 +1,8 @@
1
  import os
2
  import re
 
3
  import datasets
 
4
  from huggingface_hub import HfFileSystem
5
  from typing import List
6
 
@@ -10,11 +12,12 @@ fs = HfFileSystem()
10
  _CITATION = """
11
  """
12
 
13
- _DESCRIPTION = """This dataset contain file about datetime date.
 
14
  It's created with purpose is practice loading dataset from hugging face hub."""
15
 
16
-
17
- _HOMEPAGE = """
18
  """
19
 
20
  _REPO = "datasets/nguyenminh4099/date-data"
@@ -22,7 +25,10 @@ _BRANCH = "main"
22
  _REPO_BRANCH = f"{_REPO}@{_BRANCH}"
23
 
24
  _REPO_URL = f"https://huggingface.co/{_REPO}/resolve/{_BRANCH}"
25
- _URL = os.path.join(_REPO_URL, "data", "{filename}.zip")
 
 
 
26
 
27
  _CONFIGS = ['all']
28
  _CONFIGS.extend(
@@ -31,6 +37,8 @@ _CONFIGS.extend(
31
  if file.endswith('.zip')
32
  )
33
 
 
 
34
  class DateDataConfig(datasets.BuilderConfig):
35
  def __init__(
36
  self,
@@ -40,11 +48,26 @@ class DateDataConfig(datasets.BuilderConfig):
40
  super(DateDataConfig, self).__init__(
41
  name=name,
42
  version=datasets.Version("1.0.0"),
43
- description=_DESCRIPTION,
44
  )
 
 
 
 
 
 
45
 
46
- class DateDate(datasets.GeneratorBasedBuilder):
47
- BUILDER_CONFIGS = [DateDataConfig(name=name) for name in _CONFIGS]
 
 
 
 
 
 
 
 
 
 
48
  DEFAULT_CONFIG_NAME = 'all'
49
 
50
  def _info(self) -> datasets.DatasetInfo:
@@ -60,6 +83,7 @@ class DateDate(datasets.GeneratorBasedBuilder):
60
  "year": datasets.Value('string'),
61
  "file_path": datasets.Value('string'),
62
  })
 
63
  return datasets.DatasetInfo(
64
  features=features,
65
  description=_DESCRIPTION,
@@ -71,36 +95,69 @@ class DateDate(datasets.GeneratorBasedBuilder):
71
  self,
72
  dl_manager: datasets.DownloadManager,
73
  ) -> List[datasets.SplitGenerator]:
74
- config_names = _CONFIGS[1:] if self.config.name == 'all' else [self.config.name]
 
 
 
 
 
 
 
 
75
 
76
- data_dirs = dl_manager.download_and_extract(
77
- [_URL.format(filename=zipfile) for zipfile in config_names]
78
- )
79
-
80
  return [
81
  datasets.SplitGenerator(
82
  name=datasets.Split.TRAIN,
83
  gen_kwargs={
84
- "data_dirs": data_dirs,
 
85
  }
86
  )
87
  ]
88
 
89
  def _generate_examples(
90
  self,
91
- data_dirs: List[str],
 
92
  ) -> dict:
93
- print(data_dirs)
94
- for i, data_dir in enumerate(data_dirs):
95
- sample = self._extract_datetime("Wed Oct 16 11:08:00 +07 2024")
96
- sample.update((('id','123'),('file_path',"null")))
97
- print(data_dir)
98
- yield i, sample
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
  def _read_txt(
101
  self,
102
  file_name: str,
103
- ) -> str:
104
  with open(file=file_name, mode='r') as f:
105
  return self._extract_datetime(f.read())
106
 
@@ -121,3 +178,4 @@ class DateDate(datasets.GeneratorBasedBuilder):
121
  "timezone": components[6],
122
  "year": components[7],
123
  }
 
 
1
  import os
2
  import re
3
+ import sys
4
  import datasets
5
+ import pandas as pd
6
  from huggingface_hub import HfFileSystem
7
  from typing import List
8
 
 
12
  _CITATION = """
13
  """
14
 
15
+ _DESCRIPTION = """\
16
+ This dataset contain file about datetime date.
17
  It's created with purpose is practice loading dataset from hugging face hub."""
18
 
19
+ _HOMEPAGE = """\
20
+ https://github.com/minhnv4099
21
  """
22
 
23
  _REPO = "datasets/nguyenminh4099/date-data"
 
25
  _REPO_BRANCH = f"{_REPO}@{_BRANCH}"
26
 
27
  _REPO_URL = f"https://huggingface.co/{_REPO}/resolve/{_BRANCH}"
28
+ _URLS = {
29
+ 'zipfile': os.path.join(_REPO_URL, "data", "{}.zip"),
30
+ 'metadata': _REPO_URL + "/metadata.parquet",
31
+ }
32
 
33
  _CONFIGS = ['all']
34
  _CONFIGS.extend(
 
37
  if file.endswith('.zip')
38
  )
39
 
40
+
41
+ # TODO: Define Dataset Builder config
42
  class DateDataConfig(datasets.BuilderConfig):
43
  def __init__(
44
  self,
 
48
  super(DateDataConfig, self).__init__(
49
  name=name,
50
  version=datasets.Version("1.0.0"),
 
51
  )
52
+ # self.metadata = metadata
53
+ # self.url = kwargs.get('url', "https://huggingface.co/datasets/nguyenminh4099/date-data")
54
+ # self.data_url = kwargs.get('data_url', None)
55
+ # self.description = kwargs.get('description', _DESCRIPTION)
56
+ # logger.info('call BuilderConfig')
57
+
58
 
59
+ # TODO: Define Dataset Builder
60
+ class DateData(datasets.GeneratorBasedBuilder):
61
+ logger.info('call dataset builder')
62
+
63
+ BUILDER_CONFIGS = [
64
+ DateDataConfig(
65
+ name=name,
66
+ # metadata=_URLS['metadata'],
67
+ # data_url=_URLS['zipfile'].format(name),
68
+ )
69
+ for name in _CONFIGS
70
+ ]
71
  DEFAULT_CONFIG_NAME = 'all'
72
 
73
  def _info(self) -> datasets.DatasetInfo:
 
83
  "year": datasets.Value('string'),
84
  "file_path": datasets.Value('string'),
85
  })
86
+ print(self.config)
87
  return datasets.DatasetInfo(
88
  features=features,
89
  description=_DESCRIPTION,
 
95
  self,
96
  dl_manager: datasets.DownloadManager,
97
  ) -> List[datasets.SplitGenerator]:
98
+ logger.info("Call _split_generators")
99
+
100
+ configs = _CONFIGS[1:5] if self.config.name == 'all' else [self.config.name]
101
+ data_files = {
102
+ config : _URLS['zipfile'].format(config)
103
+ for config in configs
104
+ }
105
+ data_dict = dl_manager.download_and_extract(data_files)
106
+ print(data_dict)
107
 
 
 
 
 
108
  return [
109
  datasets.SplitGenerator(
110
  name=datasets.Split.TRAIN,
111
  gen_kwargs={
112
+ "metadata": _URLS['metadata'],
113
+ "data_dict": data_dict,
114
  }
115
  )
116
  ]
117
 
118
  def _generate_examples(
119
  self,
120
+ metadata: str,
121
+ data_dict: dict,
122
  ) -> dict:
123
+ logger.info("Call _generate_examples")
124
+ infos = datasets.load_dataset(
125
+ "parquet",
126
+ data_files=[metadata],
127
+ split='train',
128
+ )
129
+ metadata_df = infos.to_pandas()
130
+ data_df = pd.DataFrame(
131
+ {
132
+ "shard" : list(data_dict.keys()),
133
+ "data_dir" : list(data_dict.values()),
134
+ },
135
+ columns=['shard', 'data_dir'],
136
+ index=range(len(data_dict))
137
+ )
138
+
139
+ metadata_df = metadata_df.merge(
140
+ right=data_df,
141
+ how='right',
142
+ left_on='shard',
143
+ right_on='shard',
144
+ sort=True,
145
+ )
146
+
147
+ for i, sample in enumerate(metadata_df.itertuples()):
148
+ file_name = os.path.join(
149
+ sample.data_dir, sample.id + ".txt"
150
+ )
151
+ example = self._read_txt(file_name=file_name)
152
+ example['id'] = sample.id
153
+ example['file_path'] = file_name
154
+
155
+ yield i, example
156
 
157
  def _read_txt(
158
  self,
159
  file_name: str,
160
+ ) -> dict:
161
  with open(file=file_name, mode='r') as f:
162
  return self._extract_datetime(f.read())
163
 
 
178
  "timezone": components[6],
179
  "year": components[7],
180
  }
181
+ DateData()