-
Notifications
You must be signed in to change notification settings - Fork 127
some updates to module_stft , module_resample, random_utils and io.download #96
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JanekEbb
wants to merge
7
commits into
fgnt:master
Choose a base branch
from
JanekEbb:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
19e14f9
ensure _samples_to_stft_frames does return non-negative number and ad…
JanekEbb 08126d3
add epsilon in normalizer in resample_sox to prevent division by zero
JanekEbb 22f8382
add choice to random_utils
JanekEbb 4898777
some cleanup and adding extract argument in download utils
JanekEbb 81a9b72
merge PR review
JanekEbb 3e4188a
fix random_utils.choice doc tests
JanekEbb 481bc2d
fix sample_index_to_stft_frame_index doctest on windows
JanekEbb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,184 +1,143 @@ | ||
|
|
||
| import os | ||
| import socket | ||
| import sys | ||
| import tarfile | ||
| import zipfile | ||
| import warnings | ||
| from pathlib import Path | ||
| from urllib.request import urlretrieve | ||
| from concurrent.futures import ProcessPoolExecutor | ||
|
|
||
| from tqdm import tqdm | ||
|
|
||
|
|
||
| def download_file(remote_file, local_file, exist_ok=False): | ||
| def download_file(remote_file, local_file, exist_ok=False, extract=False): | ||
| """ | ||
| Download single file to local_dir | ||
|
|
||
| Args: | ||
| remote_file: | ||
| local_file: | ||
| exist_ok: | ||
| extract: | ||
| progress_par: | ||
|
|
||
| Returns: | ||
|
|
||
| """ | ||
| local_file = Path(local_file) | ||
| if not local_file.exists(): | ||
| def progress_hook(t): | ||
| """ | ||
| https://raw.githubusercontent.com/tqdm/tqdm/master/examples/tqdm_wget.py | ||
|
|
||
| Wraps tqdm instance. Don't forget to close() or __exit__() | ||
| the tqdm instance once you're done with it (easiest using | ||
| `with` syntax). | ||
| """ | ||
|
|
||
| last_b = 0 | ||
|
|
||
| def inner(b=1, bsize=1, tsize=None): | ||
| """ | ||
| b : int, optional | ||
| Number of blocks just transferred [default: 1]. | ||
| bsize : int, optional | ||
| Size of each block (in tqdm units) [default: 1]. | ||
| tsize : int, optional | ||
| Total size (in tqdm units). If [default: None] | ||
| remains unchanged. | ||
| """ | ||
| nonlocal last_b | ||
| if tsize is not None: | ||
| t.total = tsize | ||
| t.update((b - last_b) * bsize) | ||
| last_b = b | ||
|
|
||
| return inner | ||
|
|
||
| tmp_file = str(local_file) + '.tmp' | ||
| with tqdm( | ||
| desc="{0: >25s}".format(Path(remote_file).stem), | ||
| file=sys.stdout, | ||
| unit='B', | ||
| unit_scale=True, | ||
| miniters=1, | ||
| leave=False, | ||
| ascii=True | ||
| ) as t: | ||
| urlretrieve( | ||
| str(remote_file), | ||
| filename=tmp_file, | ||
| reporthook=progress_hook(t), | ||
| data=None | ||
| ) | ||
| urlretrieve( | ||
| str(remote_file), | ||
| filename=tmp_file, | ||
| data=None | ||
| ) | ||
| os.rename(tmp_file, local_file) | ||
| elif not exist_ok: | ||
| raise FileExistsError(local_file) | ||
| if extract: | ||
| extract_file(local_file, exist_ok=exist_ok) | ||
| return local_file | ||
|
|
||
|
|
||
| def extract_file(local_file, exist_ok=False): | ||
| def extract_file(local_file, target_dir=None, exist_ok=False): | ||
| """ | ||
| If local_file is .zip or .tar.gz files are extracted. | ||
|
|
||
| Args: | ||
| local_file: | ||
| target_dir: | ||
| exist_ok: | ||
|
|
||
| Returns: | ||
|
|
||
| """ | ||
| local_file = Path(local_file) | ||
| local_dir = local_file.parent | ||
| if local_file.exists(): | ||
|
|
||
| if local_file.name.endswith('.zip'): | ||
| with zipfile.ZipFile(local_file, "r") as z: | ||
| # Start extraction | ||
| members = z.infolist() | ||
| for i, member in enumerate(members): | ||
| target_file = local_dir / member.filename | ||
| if not target_file.exists(): | ||
| try: | ||
| z.extract(member=member, path=local_dir) | ||
| except KeyboardInterrupt: | ||
| # Delete latest file, since most likely it | ||
| # was not extracted fully | ||
| if target_file.exists(): | ||
| os.remove(target_file) | ||
| raise | ||
| elif not exist_ok: | ||
| raise FileExistsError(target_file) | ||
| os.remove(local_file) | ||
|
|
||
| elif local_file.name.endswith('.tar.gz'): | ||
| with tarfile.open(local_file, "r:gz") as tar: | ||
| for i, tar_info in enumerate(tar): | ||
| target_file = local_dir / tar_info.name | ||
| if not target_file.exists(): | ||
| try: | ||
| tar.extract(tar_info, local_dir) | ||
| except KeyboardInterrupt: | ||
| # Delete latest file, since most likely it | ||
| # was not extracted fully | ||
| if target_file.exists(): | ||
| os.remove(target_file) | ||
| raise | ||
| elif not exist_ok: | ||
| raise FileExistsError(target_file) | ||
| tar.members = [] | ||
| os.remove(local_file) | ||
|
|
||
|
|
||
| def download_file_list(file_list, target_dir, exist_ok=False, logger=None): | ||
| assert local_file.exists(), local_file | ||
| if target_dir is None: | ||
| target_dir = local_file.parent | ||
| else: | ||
| target_dir = Path(target_dir) | ||
| target_dir.mkdir(parents=True, exist_ok=True) | ||
| if local_file.name.endswith('.zip'): | ||
| with zipfile.ZipFile(local_file, "r") as z: | ||
| # Start extraction | ||
| members = z.infolist() | ||
| for i, member in enumerate(members): | ||
| target_file = target_dir / member.filename | ||
| if not target_file.exists(): | ||
| try: | ||
| z.extract(member=member, path=target_dir) | ||
| except KeyboardInterrupt: | ||
| # Delete latest file, since most likely it | ||
| # was not extracted fully | ||
| if target_file.exists(): | ||
| os.remove(target_file) | ||
| raise | ||
| elif not exist_ok: | ||
| raise FileExistsError(target_file) | ||
| os.remove(local_file) | ||
|
|
||
| elif local_file.name.endswith('.tar.gz') or local_file.name.endswith('.tar'): | ||
| mode = "r:gz" if local_file.name.endswith('.tar.gz') else "r" | ||
| with tarfile.open(local_file, mode) as tar: | ||
| for i, tar_info in enumerate(tar): | ||
| target_file = target_dir / tar_info.name | ||
| if not target_file.exists(): | ||
| try: | ||
| tar.extract(tar_info, target_dir) | ||
| except KeyboardInterrupt: | ||
| # Delete latest file, since most likely it | ||
| # was not extracted fully | ||
| if target_file.exists(): | ||
| os.remove(target_file) | ||
| raise | ||
| elif not exist_ok: | ||
| raise FileExistsError(target_file) | ||
| tar.members = [] | ||
| os.remove(local_file) | ||
| else: | ||
| warnings.warn("Unsupported file format: Cannot extract file.") | ||
|
|
||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there a reason, that you didn't define an else path with a raise? If not, could you raise a warning, when there is an unsupported suffix? |
||
|
|
||
| def download_file_list(file_list, target_dir, extract=True, exist_ok=False, num_workers=1): | ||
| """ | ||
| Download file_list to target_dir | ||
|
|
||
| Args: | ||
| file_list: | ||
| target_dir: | ||
| exist_ok: | ||
| logger: | ||
| extract: | ||
| num_workers: | ||
|
|
||
| Returns: | ||
|
|
||
| """ | ||
|
|
||
| target_dir = Path(target_dir) | ||
| os.makedirs(target_dir, exist_ok=True) | ||
|
|
||
| item_progress = tqdm( | ||
| file_list, desc="{0: <25s}".format('Download files'), | ||
| file=sys.stdout, leave=False, ascii=True) | ||
|
|
||
| local_files = list() | ||
| for remote_file in item_progress: | ||
| local_files.append( | ||
| download_file( | ||
| remote_file, | ||
| target_dir / Path(remote_file).name, | ||
| exist_ok=exist_ok | ||
| ) | ||
| ) | ||
|
|
||
| item_progress = tqdm( | ||
| local_files, | ||
| desc="{0: <25s}".format('Extract files'), | ||
| file=sys.stdout, | ||
| leave=False, | ||
| ascii=True | ||
| ) | ||
|
|
||
| if logger is not None: | ||
| logger.info('Starting Extraction') | ||
| for _id, local_file in enumerate(item_progress): | ||
| if local_file and local_file.exists(): | ||
| if logger is not None: | ||
| logger.info( | ||
| ' {title:<15s} [{item_id:d}/{total:d}] {package:<30s}' | ||
| .format( | ||
| title='Extract files ', | ||
| item_id=_id, | ||
| total=len(item_progress), | ||
| package=local_file | ||
| ) | ||
| ) | ||
| extract_file(local_file, exist_ok=exist_ok) | ||
| pbar = tqdm(initial=0, total=len(file_list)) | ||
|
|
||
| if isinstance(extract, bool): | ||
| extract = len(file_list) * [extract] | ||
| assert len(extract) == len(file_list), (len(extract), len(file_list)) | ||
| if num_workers > 1: | ||
| with ProcessPoolExecutor(num_workers) as ex: | ||
| for _ in ex.map( | ||
| download_file, | ||
| file_list, | ||
| [target_dir / Path(f).name.split('?')[0] for f in file_list], # extract file names from urls discarding query strings | ||
| len(file_list) * [exist_ok], | ||
| extract, | ||
| ): | ||
| pbar.update(1) | ||
| else: | ||
| for _ in map( | ||
| download_file, | ||
| file_list, | ||
| [target_dir / Path(f).name.split('?')[0] for f in file_list], | ||
| len(file_list) * [exist_ok], | ||
| extract, | ||
| ): | ||
| pbar.update(1) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
progress_baris no arg