|
| 1 | + |
| 2 | +from configparser import ConfigParser |
| 3 | +import os |
| 4 | +import requests |
| 5 | +import shutil |
| 6 | +import sys |
| 7 | +from zipfile import ZipFile |
| 8 | + |
| 9 | +class DownloadError(Exception): |
| 10 | + def __init__(self, message, code=None): |
| 11 | + super().__init__(message) |
| 12 | + self.code = code |
| 13 | + |
| 14 | +def _download_and_extract(file_url: str, extract_dir: str) -> bool: |
| 15 | + response = requests.get(file_url) |
| 16 | + LOCAL_FILE = "download.zip" |
| 17 | + |
| 18 | + if response.status_code == 200: |
| 19 | + with open(LOCAL_FILE, "wb") as f: |
| 20 | + f.write(response.content) |
| 21 | + print(f"{LOCAL_FILE} downloaded from {file_url}.") |
| 22 | + |
| 23 | + with ZipFile(LOCAL_FILE, "r") as z: |
| 24 | + z.extractall(extract_dir) |
| 25 | + print(f"{LOCAL_FILE} extracted to {extract_dir}.") |
| 26 | + |
| 27 | + os.remove(LOCAL_FILE) |
| 28 | + else: |
| 29 | + raise DownloadError(f"Failed to download {file_url}.", code=response.status_code) |
| 30 | + |
| 31 | +def download_shapefiles(): |
| 32 | + # create output directory |
| 33 | + script_dir = os.path.abspath(os.path.dirname(__file__)) |
| 34 | + extract_dir = os.path.join(script_dir, "..", "shapefiles") |
| 35 | + |
| 36 | + if os.path.exists(extract_dir): |
| 37 | + shutil.rmtree(extract_dir) |
| 38 | + shutil.os.makedirs(extract_dir) |
| 39 | + |
| 40 | + # get current configuration |
| 41 | + CONFIG_FILE = "config.ini" |
| 42 | + config = ConfigParser() |
| 43 | + config.read(os.path.join(script_dir, CONFIG_FILE)) |
| 44 | + SECTION = "shapefiles" |
| 45 | + |
| 46 | + url_template = config.get(SECTION, "url") |
| 47 | + current_year = config.getint(SECTION, "current_year") |
| 48 | + entities = config.get(SECTION, "entities").split(",") |
| 49 | + res = config.get(SECTION, "res") |
| 50 | + |
| 51 | + year = current_year + 1 |
| 52 | + |
| 53 | + try: |
| 54 | + # attempt shapefile downloads |
| 55 | + for entity in entities: |
| 56 | + url = url_template.format(year=year, entity=entity, res=res) |
| 57 | + _download_and_extract(url, extract_dir) |
| 58 | + |
| 59 | + if (gh_env := os.getenv("GITHUB_ENV")): |
| 60 | + with open(gh_env, "a") as f: |
| 61 | + f.write(f"{entity}_shp_path=cb_{year}_us_{entity}_{res}.shp") |
| 62 | + |
| 63 | + # update current year |
| 64 | + config.set(SECTION, "current_year", f"{year}") |
| 65 | + with open(CONFIG_FILE, "w") as f: |
| 66 | + config.write(f) |
| 67 | + except DownloadError as e: |
| 68 | + if e.code == 404: # i.e. shapefiles not found |
| 69 | + print(f"The shapefiles for {year} were not found. Better luck next time!") |
| 70 | + else: # other download errors |
| 71 | + print(e) |
| 72 | + |
| 73 | + sys.exit(e.code) |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + download_shapefiles() |
0 commit comments