Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

download-dataset.py 7.3 KB

You have to be logged in to leave a comment. Sign In
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
  1. '''
  2. Downloads datasets from Hugging Face to datasets/dataset-name.
  3. Example:
  4. python download-dataset.py tatsu-lab/alpaca
  5. NOTE: this file is based on `download-model.py` and heavily modified
  6. '''
  7. import argparse
  8. import base64
  9. import datetime
  10. import json
  11. import re
  12. import sys
  13. from pathlib import Path
  14. import subprocess
  15. import requests
  16. import tqdm
  17. from tqdm.contrib.concurrent import thread_map
  18. import os
  19. parser = argparse.ArgumentParser()
  20. parser.add_argument('DATASET', type=str, default=None, nargs='?')
  21. parser.add_argument('--branch', type=str, default='main', help='Name of the Git branch to download from.')
  22. parser.add_argument('--threads', type=int, default=8, help='Number of files to download simultaneously.')
  23. parser.add_argument('--output', type=str, default=None, help='The folder where the dataset should be saved.')
  24. args = parser.parse_args()
  25. def get_file(url_info, output_folder):
  26. url = url_info['link']
  27. filename = url_info['path']
  28. dir_and_basename = filename.rsplit('/', 1)
  29. dir = dir_and_basename[0] if len(dir_and_basename) == 2 else ''
  30. if not (output_folder / dir).exists():
  31. (output_folder / dir).mkdir(parents=True, exist_ok=True)
  32. total_size = url_info['size']
  33. output_file = output_folder / Path(filename)
  34. if output_file.exists() and output_file.stat().st_size == total_size:
  35. print(f"Downloaded: {output_file}")
  36. return
  37. with open(output_folder / filename, 'wb') as f:
  38. token = os.environ.get("HUGGINGFACE_TOKEN")
  39. r = requests.get(url, stream=True, headers={"authorization" : f'Bearer {token}'})
  40. block_size = 1024
  41. with tqdm.tqdm(postfix=f'File: {filename}', total=total_size, unit='iB', unit_scale=True, bar_format='{l_bar}{bar}| {n_fmt:6}/{total_fmt:6} {rate_fmt:6} {postfix}') as t:
  42. for data in r.iter_content(block_size):
  43. t.update(len(data))
  44. f.write(data)
  45. def get_file_by_aria2(url, output_folder):
  46. filename = url.split('/')[-1]
  47. # r = requests.get(url, stream=True)
  48. # total_size = int(r.headers.get('content-length', 0))
  49. if (output_folder / Path(filename)).exists() and not (output_folder / Path(f"{filename}.aria2")).exists():
  50. print(f"Downloaded: {filename}")
  51. return
  52. # full_dir = f"{Path('/app/text-generation-webui/') / output_folder}"
  53. # print(f"aria2p downloading {url} to {full_dir} as {filename}")
  54. # aria2.add_uris(url, options={'dir': full_dir, 'out': filename})
  55. # /app/text-generation-webui/models
  56. aria_command = f"aria2c -c -x 16 -s 16 -k 1M {url} -d {output_folder} -o {filename}"
  57. print(f"Running: {aria_command}")
  58. # # call command line aria2c to download
  59. subprocess.run(aria_command, shell=True, check=True)
  60. def sanitize_branch_name(branch_name):
  61. pattern = re.compile(r"^[a-zA-Z0-9._-]+$")
  62. if pattern.match(branch_name):
  63. return branch_name
  64. else:
  65. raise ValueError("Invalid branch name. Only alphanumeric characters, period, underscore and dash are allowed.")
  66. def get_download_links_from_huggingface(dataset, branch, dir=None):
  67. base = "https://huggingface.co"
  68. page = f"/api/datasets/{dataset}/tree/{branch}"
  69. if dir is not None:
  70. page = f'{page}/{dir}'
  71. cursor = b""
  72. links = []
  73. sha256 = []
  74. # TODO support passing in
  75. token = os.environ.get("HUGGINGFACE_TOKEN")
  76. headers = { "authorization" : f'Bearer {token}'}
  77. while True:
  78. api_url = f"{base}{page}"
  79. if cursor != b"":
  80. api_url = f"{api_url}?cursor={cursor.decode()}"
  81. print(api_url)
  82. content = requests.get(api_url, headers=headers).content
  83. print(content)
  84. dict = json.loads(content)
  85. if 'error' in dict:
  86. # print(f'Ignoring error: {dict["error"]}')
  87. break
  88. if len(dict) == 0:
  89. break
  90. for i in range(len(dict)):
  91. item = dict[i]
  92. fname = item['path']
  93. # print(f'{item}')
  94. if item['type'] == 'directory':
  95. print(f'Gathering: {fname}')
  96. dir_links, dir_sha256 = get_download_links_from_huggingface(dataset, branch, dir=fname)
  97. links.extend(dir_links)
  98. # TODO: also add dir_sha256, fix fname in the process
  99. if item['type'] == 'file':
  100. link = f"https://huggingface.co/datasets/{dataset}/resolve/{branch}/{fname}"
  101. # print(f'{link}')
  102. url_info = {"link": link, "path": fname, "size": item["size"]}
  103. if 'lfs' in item:
  104. oid = item['lfs']['oid']
  105. sha256.append([fname, oid])
  106. url_info["sha256sum"] = oid
  107. links.append(url_info)
  108. cursor_file = dict[-1]["path"]
  109. # print(f'Using file {cursor_file} as cursor')
  110. curson_json = f'{{"file_name":"{cursor_file}"}}'
  111. cursor = base64.b64encode(curson_json.encode()) + b':50'
  112. cursor = base64.b64encode(cursor)
  113. cursor = cursor.replace(b'=', b'%3D')
  114. return links, sha256
  115. def download_files(file_list, output_folder, num_threads=8):
  116. thread_map(lambda url_info: get_file(url_info, output_folder), file_list, max_workers=num_threads)
  117. if __name__ == '__main__':
  118. # determine the root of the repo and cd to it
  119. ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
  120. os.chdir(ROOT)
  121. print(f"Working directory changed to: {ROOT}")
  122. dataset = args.DATASET
  123. branch = args.branch
  124. if dataset is None:
  125. print("Error: Please specify a dataset to download.")
  126. sys.exit()
  127. else:
  128. if dataset[-1] == '/':
  129. dataset = dataset[:-1]
  130. branch = args.branch
  131. if branch is None:
  132. branch = "main"
  133. else:
  134. try:
  135. branch = sanitize_branch_name(branch)
  136. except ValueError as err_branch:
  137. print(f"Error: {err_branch}")
  138. sys.exit()
  139. if args.output is not None:
  140. base_folder = args.output
  141. else:
  142. base_folder = 'datasets'
  143. output_folder = f"{'_'.join(dataset.split('/')[-2:])}"
  144. if branch != 'main':
  145. output_folder += f'_{branch}'
  146. # Creating the folder and writing the metadata
  147. output_folder = Path(base_folder) / output_folder
  148. if not output_folder.exists():
  149. output_folder.mkdir(parents=True, exist_ok=True)
  150. links_file = output_folder / 'links.json'
  151. links, sha256 = [], []
  152. # TODO expire logic
  153. if links_file.exists():
  154. with open(links_file, 'r') as f:
  155. links = json.load(f)
  156. # TODO fix sha256
  157. else:
  158. links, sha256 = get_download_links_from_huggingface(dataset, branch)
  159. with open(links_file, 'w') as f:
  160. json.dump(links, f)
  161. with open(output_folder / 'huggingface-metadata.txt', 'w') as f:
  162. f.write(f'url: https://huggingface.co/{dataset}\n')
  163. f.write(f'branch: {branch}\n')
  164. f.write(f'download date: {str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))}\n')
  165. sha256_str = ''
  166. for i in range(len(sha256)):
  167. sha256_str += f' {sha256[i][1]} {sha256[i][0]}\n'
  168. if sha256_str != '':
  169. f.write(f'sha256sum:\n{sha256_str}')
  170. # Downloading the files
  171. print(f"Downloading the dataset to {output_folder}")
  172. download_files(links, output_folder, args.threads)
  173. print()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...