|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os |
| 3 | +import requests |
| 4 | +from tqdm import tqdm |
| 5 | +import zipfile |
| 6 | + |
| 7 | + |
| 8 | +_here = os.path.abspath(__file__) |
| 9 | +lib_path = os.path.dirname(os.path.dirname(_here)) |
| 10 | +meshes_path = os.path.join(lib_path, "meshes") |
| 11 | + |
| 12 | + |
| 13 | +def get_filename_from_url(url: str) -> str: |
| 14 | + local_filename = url.split('/')[-1] |
| 15 | + return os.path.join(meshes_path, local_filename) |
| 16 | + |
| 17 | + |
| 18 | +def is_download_needed(target_file_path: str) -> bool: |
| 19 | + if not os.path.exists(meshes_path): |
| 20 | + os.mkdir(meshes_path) |
| 21 | + return True |
| 22 | + if not os.path.exists(os.path.join(meshes_path, 'trees')): |
| 23 | + if not os.path.isfile(os.path.join(meshes_path, 'pybullet-tree-sim-meshes.zip')): # TODO: pass name into func |
| 24 | + return True |
| 25 | + else: |
| 26 | + return False |
| 27 | + else: |
| 28 | + return False |
| 29 | + |
| 30 | +def is_unzip_needed(target_file_path: str) -> bool: |
| 31 | + if not os.path.exists(os.path.join(meshes_path, 'trees')): |
| 32 | + return True |
| 33 | + else: |
| 34 | + return False |
| 35 | + |
| 36 | + |
| 37 | +def download_file(url: str, target_file_path: str) -> bool: |
| 38 | + try: |
| 39 | + # NOTE the stream=True parameter below |
| 40 | + with requests.get(url, stream=True) as r: |
| 41 | + r.raise_for_status() |
| 42 | + total_size = int(r.headers.get("content-length", 0)) |
| 43 | + with tqdm(total=total_size, unit='B', unit_scale=True) as progress_bar: |
| 44 | + with open(target_file_path, 'wb') as f: |
| 45 | + for chunk in r.iter_content(chunk_size=8192): |
| 46 | + # If you have chunk encoded response uncomment if |
| 47 | + # and set chunk_size parameter to None. |
| 48 | + # if chunk: |
| 49 | + progress_bar.update(len(chunk)) |
| 50 | + f.write(chunk) |
| 51 | + |
| 52 | + return True |
| 53 | + |
| 54 | + except Exception as e: |
| 55 | + print(f'{e}') |
| 56 | + return False |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | +def unzip(zip_file: str): |
| 61 | + with zipfile.ZipFile(zip_file, 'r') as zipper: |
| 62 | + zipper.extractall(os.path.dirname(zip_file)) |
| 63 | + return |
| 64 | + |
| 65 | + |
| 66 | +def main(): |
| 67 | + url = "https://zenodo.org/records/14991250/files/pybullet-tree-sim-meshes.zip" |
| 68 | + |
| 69 | + file_abs_path = get_filename_from_url(url=url) |
| 70 | + |
| 71 | + download_needed = is_download_needed(target_file_path=file_abs_path) |
| 72 | + if download_needed: |
| 73 | + download_file(url=url, target_file_path=file_abs_path) |
| 74 | + |
| 75 | + unzip_needed = is_unzip_needed(target_file_path=file_abs_path) |
| 76 | + if unzip_needed: |
| 77 | + unzip(zip_file=file_abs_path) |
| 78 | + return |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + main() |
0 commit comments