yangwang825 commited on
Commit
0737fe3
·
verified ·
1 Parent(s): f6b2bff

Update fsdkaggle2019-script.py

Browse files
Files changed (1) hide show
  1. fsdkaggle2019-script.py +90 -49
fsdkaggle2019-script.py CHANGED
@@ -4,10 +4,14 @@
4
 
5
 
6
  import os
7
- import requests
 
 
 
8
  import textwrap
9
  import datasets
10
  import itertools
 
11
  import pandas as pd
12
  import typing as tp
13
  from pathlib import Path
@@ -171,59 +175,96 @@ def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False):
171
 
172
 
173
  def download_file(
174
- download_url, download_path, split_name, filename, resume_byte_pos=None
 
 
 
 
 
175
  ):
176
- """
177
- Download file from given URL
178
 
179
- Arguments
180
  ---------
181
- download_url : str
182
- URL of file being downloaded
183
- download_path : str
184
- Full path of the file that is to be downloaded
185
- (or already downloaded)
186
- split_name : str
187
- Split name of the file being downloaded
188
- e.g. read_speech
189
- filename : str
190
- Filename of the file being downloaded
191
- resume_byte_pos: (int, optional)
192
- Starting byte position for resuming the download.
193
- Default is None, which means a fresh download.
194
-
195
- Returns
196
- -------
197
- bool
198
- If True, the file need not be downloaded again.
199
- Else the download might have failed or is incomplete.
200
  """
201
- print("Downloading:", split_name, "=>", filename)
202
- resume_header = (
203
- {"Range": f"bytes={resume_byte_pos}-"} if resume_byte_pos else None
204
- )
205
- response = requests.get(download_url, headers=resume_header, stream=True)
206
- file_size = int(response.headers.get("Content-Length"))
207
-
208
- mode = "ab" if resume_byte_pos else "wb"
209
- initial_pos = resume_byte_pos if resume_byte_pos else 0
210
-
211
- with open(download_path, mode) as f:
212
- with tqdm(
213
- total=file_size,
 
 
 
 
 
 
 
214
  unit="B",
215
  unit_scale=True,
216
- unit_divisor=1024,
217
- initial=initial_pos,
218
  miniters=1,
219
- ) as pbar:
220
- for chunk in response.iter_content(32 * 1024):
221
- f.write(chunk)
222
- pbar.update(len(chunk))
223
-
224
- # Validate downloaded file
225
- if validate_file(download_url, download_path):
226
- return True
227
  else:
228
- print("Download failed. Moving on.")
229
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
 
6
  import os
7
+ import tqdm
8
+ import gzip
9
+ import shutil
10
+ import pathlib
11
  import textwrap
12
  import datasets
13
  import itertools
14
+ import urllib.request
15
  import pandas as pd
16
  import typing as tp
17
  from pathlib import Path
 
175
 
176
 
177
  def download_file(
178
+ source,
179
+ dest,
180
+ unpack=False,
181
+ dest_unpack=None,
182
+ replace_existing=False,
183
+ write_permissions=False,
184
  ):
185
+ """Downloads the file from the given source and saves it in the given
186
+ destination path.
187
 
188
+ Arguments
189
  ---------
190
+ source : path or url
191
+ Path of the source file. If the source is an URL, it downloads it from
192
+ the web.
193
+ dest : path
194
+ Destination path.
195
+ unpack : bool
196
+ If True, it unpacks the data in the dest folder.
197
+ dest_unpack: path
198
+ Path where to store the unpacked dataset
199
+ replace_existing : bool
200
+ If True, replaces the existing files.
201
+ write_permissions: bool
202
+ When set to True, all the files in the dest_unpack directory will be granted write permissions.
203
+ This option is active only when unpack=True.
 
 
 
 
 
204
  """
205
+ class DownloadProgressBar(tqdm.tqdm):
206
+ """DownloadProgressBar class."""
207
+
208
+ def update_to(self, b=1, bsize=1, tsize=None):
209
+ """Needed to support multigpu training."""
210
+ if tsize is not None:
211
+ self.total = tsize
212
+ self.update(b * bsize - self.n)
213
+
214
+ # Create the destination directory if it doesn't exist
215
+ dest_dir = pathlib.Path(dest).resolve().parent
216
+ dest_dir.mkdir(parents=True, exist_ok=True)
217
+ if "http" not in source:
218
+ shutil.copyfile(source, dest)
219
+
220
+ elif not os.path.isfile(dest) or (
221
+ os.path.isfile(dest) and replace_existing
222
+ ):
223
+ print(f"Downloading {source} to {dest}")
224
+ with DownloadProgressBar(
225
  unit="B",
226
  unit_scale=True,
 
 
227
  miniters=1,
228
+ desc=source.split("/")[-1],
229
+ ) as t:
230
+ urllib.request.urlretrieve(
231
+ source, filename=dest, reporthook=t.update_to
232
+ )
 
 
 
233
  else:
234
+ print(f"{dest} exists. Skipping download")
235
+
236
+ # Unpack if necessary
237
+ if unpack:
238
+ if dest_unpack is None:
239
+ dest_unpack = os.path.dirname(dest)
240
+ print(f"Extracting {dest} to {dest_unpack}")
241
+ # shutil unpack_archive does not work with tar.gz files
242
+ if (
243
+ source.endswith(".tar.gz")
244
+ or source.endswith(".tgz")
245
+ or source.endswith(".gz")
246
+ ):
247
+ out = dest.replace(".gz", "")
248
+ with gzip.open(dest, "rb") as f_in:
249
+ with open(out, "wb") as f_out:
250
+ shutil.copyfileobj(f_in, f_out)
251
+ else:
252
+ shutil.unpack_archive(dest, dest_unpack)
253
+ if write_permissions:
254
+ set_writing_permissions(dest_unpack)
255
+
256
+
257
+ def set_writing_permissions(folder_path):
258
+ """
259
+ This function sets user writing permissions to all the files in the given folder.
260
+
261
+ Arguments
262
+ ---------
263
+ folder_path : folder
264
+ Folder whose files will be granted write permissions.
265
+ """
266
+ for root, dirs, files in os.walk(folder_path):
267
+ for file_name in files:
268
+ file_path = os.path.join(root, file_name)
269
+ # Set writing permissions (mode 0o666) to the file
270
+ os.chmod(file_path, 0o666)