firms_client.init
Download what working offline needs, once: country archives and WorldCover tiles.
init() is the step a server or an installer runs before its first
request. It fetches, into the data directory:
- the yearly archives of
countryforyears(VIIRS S-NPP by default), as~firms_client.download_archive()would on first use; - the whole ESA WorldCover tiles (3 degrees a side, 2021, v200, CC BY 4.0)
that touch
bbox, under the bucket's own path inworldcover/, whereWorldCover.synced() <firms_client.WorldCover.synced>()reads them. A tile of open sea does not exist (HTTP 404) and is skipped. Over Italy: 23 tiles, 1.3 GB. Norasteriois needed to download them.
A file already there is skipped, so running it again costs one request per
missing sea tile and nothing else; a download goes to a .part file and
is renamed when complete, so a file that exists is whole. A file that
fails is recorded and the rest goes on: run it again to resume.
It takes the caller's httpx.AsyncClient (or makes one) and retries
nothing unless given a ~firms_client.RetryPolicy: an application
with its own retry wraps the whole call, or calls
~firms_client.download_archive() and download_worldcover_tile()
one file at a time.
The static-source mask is not downloaded: it is built from the archives,
offline, the first time ~firms_client.fetch_static_mask() is called.
~firms_client.sync does all three, with a cropped WorldCover copy.
1"""Download what working offline needs, once: country archives and WorldCover tiles. 2 3:func:`init` is the step a server or an installer runs before its first 4request. It fetches, into the data directory: 5 6* the yearly archives of ``country`` for ``years`` (VIIRS S-NPP by default), 7 as :func:`~firms_client.download_archive` would on first use; 8* the whole ESA WorldCover tiles (3 degrees a side, 2021, v200, CC BY 4.0) 9 that touch ``bbox``, under the bucket's own path in ``worldcover/``, where 10 :meth:`WorldCover.synced() <firms_client.WorldCover.synced>` reads them. 11 A tile of open sea does not exist (HTTP 404) and is skipped. Over Italy: 12 23 tiles, 1.3 GB. No ``rasterio`` is needed to download them. 13 14A file already there is skipped, so running it again costs one request per 15missing sea tile and nothing else; a download goes to a ``.part`` file and 16is renamed when complete, so a file that exists is whole. A file that 17fails is recorded and the rest goes on: run it again to resume. 18 19It takes the caller's ``httpx.AsyncClient`` (or makes one) and retries 20nothing unless given a :class:`~firms_client.RetryPolicy`: an application 21with its own retry wraps the whole call, or calls 22:func:`~firms_client.download_archive` and :func:`download_worldcover_tile` 23one file at a time. 24 25The static-source mask is not downloaded: it is built from the archives, 26offline, the first time :func:`~firms_client.fetch_static_mask` is called. 27:func:`~firms_client.sync` does all three, with a cropped WorldCover copy. 28""" 29 30from __future__ import annotations 31 32import math 33from collections.abc import Iterable 34from dataclasses import asdict, dataclass, field 35from pathlib import Path 36from typing import Any 37 38import httpx 39 40from firms_client.client import default_directory, download_archive 41from firms_client.errors import FirmsError 42from firms_client.landcover import WORLDCOVER_DIR, WORLDCOVER_URL, WorldCover 43from firms_client.retry import RetryableStatusError, RetryPolicy, retryable, with_retries 44from firms_client.sources import VIIRS_SNPP, ArchiveProduct, BBox, archive_filename 45 46_CHUNK = 1 << 20 47#: The side of a WorldCover tile, degrees. 48TILE_DEG = 3 49 50 51@dataclass(slots=True) 52class InitReport: 53 """What :func:`init` did, file by file (names, not paths).""" 54 55 directory: str 56 downloaded: list[str] = field(default_factory=list) 57 skipped: list[str] = field(default_factory=list) 58 missing: list[str] = field(default_factory=list) 59 failed: dict[str, str] = field(default_factory=dict) 60 61 @property 62 def ok(self) -> bool: 63 """No file failed: what exists is all there is.""" 64 return not self.failed 65 66 def as_dict(self) -> dict[str, Any]: 67 """JSON-ready.""" 68 return {**asdict(self), "ok": self.ok} 69 70 71def worldcover_tiles(bbox: BBox, *, year: int = 2021) -> list[str]: 72 """The bucket URLs of the WorldCover tiles that touch ``bbox`` (west, south, east, north).""" 73 west, south, east, north = bbox 74 land = WorldCover(year=year) 75 return [ 76 land.tile(lat + TILE_DEG / 2, lon + TILE_DEG / 2) 77 for lat in range( 78 math.floor(south / TILE_DEG) * TILE_DEG, 79 math.ceil(north / TILE_DEG) * TILE_DEG, 80 TILE_DEG, 81 ) 82 for lon in range( 83 math.floor(west / TILE_DEG) * TILE_DEG, math.ceil(east / TILE_DEG) * TILE_DEG, TILE_DEG 84 ) 85 ] 86 87 88def worldcover_path(url: str, directory: Path | None = None) -> Path: 89 """Where a tile of the bucket lives in the data directory.""" 90 return ( 91 (directory or default_directory()) / WORLDCOVER_DIR / url.removeprefix(WORLDCOVER_URL + "/") 92 ) 93 94 95async def download_worldcover_tile( 96 client: httpx.AsyncClient, 97 url: str, 98 directory: Path | None = None, 99 *, 100 retry: RetryPolicy | None = None, 101) -> Path | None: 102 """One whole WorldCover tile into the data directory; ``None`` if it does not exist (sea). 103 104 A tile already there is returned without asking the bucket. 105 """ 106 path = worldcover_path(url, directory) 107 if path.exists(): 108 return path 109 partial = path.with_name(f"{path.name}.part") 110 111 async def attempt(final: bool) -> bool: 112 async with client.stream("GET", url) as response: 113 if response.status_code == 404: 114 return False 115 if retryable(retry, response, final): 116 raise RetryableStatusError(response) 117 response.raise_for_status() 118 path.parent.mkdir(parents=True, exist_ok=True) 119 with partial.open("wb") as out: 120 async for chunk in response.aiter_bytes(_CHUNK): 121 out.write(chunk) 122 return True 123 124 try: 125 if not await with_retries(retry, attempt): 126 return None 127 partial.rename(path) 128 finally: 129 partial.unlink(missing_ok=True) 130 return path 131 132 133async def init( 134 directory: Path | None = None, 135 *, 136 country: str, 137 years: Iterable[int], 138 bbox: BBox | None = None, 139 products: tuple[ArchiveProduct, ...] = (VIIRS_SNPP,), 140 client: httpx.AsyncClient | None = None, 141 retry: RetryPolicy | None = None, 142) -> InitReport: 143 """Archives of ``country`` for ``years`` and the WorldCover tiles over ``bbox``; see the module. 144 145 ``directory`` defaults to :func:`~firms_client.default_directory`. 146 ``missing`` lists the years not published (and the sea tiles), which 147 are not errors; ``failed`` maps a file to its error. 148 """ 149 folder = directory or default_directory() 150 report = InitReport(directory=str(folder)) 151 own = client is None 152 http = client or httpx.AsyncClient(timeout=600, follow_redirects=True) 153 try: 154 for product in products: 155 for year in years: 156 if year < product.first_year: 157 continue 158 name = archive_filename(product, year, country) 159 if (folder / name).exists(): 160 report.skipped.append(name) 161 continue 162 try: 163 found = await download_archive( 164 http, product, year, country, folder, retry=retry 165 ) 166 except (httpx.HTTPError, FirmsError, OSError) as error: 167 report.failed[name] = str(error) or type(error).__name__ 168 continue 169 (report.downloaded if found is not None else report.missing).append(name) 170 for url in worldcover_tiles(bbox) if bbox is not None else []: 171 name = url.rsplit("/", 1)[-1] 172 if worldcover_path(url, folder).exists(): 173 report.skipped.append(name) 174 continue 175 try: 176 found = await download_worldcover_tile(http, url, folder, retry=retry) 177 except (httpx.HTTPError, OSError) as error: 178 report.failed[name] = str(error) or type(error).__name__ 179 continue 180 (report.downloaded if found is not None else report.missing).append(name) 181 finally: 182 if own: 183 await http.aclose() 184 return report
52@dataclass(slots=True) 53class InitReport: 54 """What :func:`init` did, file by file (names, not paths).""" 55 56 directory: str 57 downloaded: list[str] = field(default_factory=list) 58 skipped: list[str] = field(default_factory=list) 59 missing: list[str] = field(default_factory=list) 60 failed: dict[str, str] = field(default_factory=dict) 61 62 @property 63 def ok(self) -> bool: 64 """No file failed: what exists is all there is.""" 65 return not self.failed 66 67 def as_dict(self) -> dict[str, Any]: 68 """JSON-ready.""" 69 return {**asdict(self), "ok": self.ok}
What init() did, file by file (names, not paths).
72def worldcover_tiles(bbox: BBox, *, year: int = 2021) -> list[str]: 73 """The bucket URLs of the WorldCover tiles that touch ``bbox`` (west, south, east, north).""" 74 west, south, east, north = bbox 75 land = WorldCover(year=year) 76 return [ 77 land.tile(lat + TILE_DEG / 2, lon + TILE_DEG / 2) 78 for lat in range( 79 math.floor(south / TILE_DEG) * TILE_DEG, 80 math.ceil(north / TILE_DEG) * TILE_DEG, 81 TILE_DEG, 82 ) 83 for lon in range( 84 math.floor(west / TILE_DEG) * TILE_DEG, math.ceil(east / TILE_DEG) * TILE_DEG, TILE_DEG 85 ) 86 ]
The bucket URLs of the WorldCover tiles that touch bbox (west, south, east, north).
89def worldcover_path(url: str, directory: Path | None = None) -> Path: 90 """Where a tile of the bucket lives in the data directory.""" 91 return ( 92 (directory or default_directory()) / WORLDCOVER_DIR / url.removeprefix(WORLDCOVER_URL + "/") 93 )
Where a tile of the bucket lives in the data directory.
96async def download_worldcover_tile( 97 client: httpx.AsyncClient, 98 url: str, 99 directory: Path | None = None, 100 *, 101 retry: RetryPolicy | None = None, 102) -> Path | None: 103 """One whole WorldCover tile into the data directory; ``None`` if it does not exist (sea). 104 105 A tile already there is returned without asking the bucket. 106 """ 107 path = worldcover_path(url, directory) 108 if path.exists(): 109 return path 110 partial = path.with_name(f"{path.name}.part") 111 112 async def attempt(final: bool) -> bool: 113 async with client.stream("GET", url) as response: 114 if response.status_code == 404: 115 return False 116 if retryable(retry, response, final): 117 raise RetryableStatusError(response) 118 response.raise_for_status() 119 path.parent.mkdir(parents=True, exist_ok=True) 120 with partial.open("wb") as out: 121 async for chunk in response.aiter_bytes(_CHUNK): 122 out.write(chunk) 123 return True 124 125 try: 126 if not await with_retries(retry, attempt): 127 return None 128 partial.rename(path) 129 finally: 130 partial.unlink(missing_ok=True) 131 return path
One whole WorldCover tile into the data directory; None if it does not exist (sea).
A tile already there is returned without asking the bucket.
134async def init( 135 directory: Path | None = None, 136 *, 137 country: str, 138 years: Iterable[int], 139 bbox: BBox | None = None, 140 products: tuple[ArchiveProduct, ...] = (VIIRS_SNPP,), 141 client: httpx.AsyncClient | None = None, 142 retry: RetryPolicy | None = None, 143) -> InitReport: 144 """Archives of ``country`` for ``years`` and the WorldCover tiles over ``bbox``; see the module. 145 146 ``directory`` defaults to :func:`~firms_client.default_directory`. 147 ``missing`` lists the years not published (and the sea tiles), which 148 are not errors; ``failed`` maps a file to its error. 149 """ 150 folder = directory or default_directory() 151 report = InitReport(directory=str(folder)) 152 own = client is None 153 http = client or httpx.AsyncClient(timeout=600, follow_redirects=True) 154 try: 155 for product in products: 156 for year in years: 157 if year < product.first_year: 158 continue 159 name = archive_filename(product, year, country) 160 if (folder / name).exists(): 161 report.skipped.append(name) 162 continue 163 try: 164 found = await download_archive( 165 http, product, year, country, folder, retry=retry 166 ) 167 except (httpx.HTTPError, FirmsError, OSError) as error: 168 report.failed[name] = str(error) or type(error).__name__ 169 continue 170 (report.downloaded if found is not None else report.missing).append(name) 171 for url in worldcover_tiles(bbox) if bbox is not None else []: 172 name = url.rsplit("/", 1)[-1] 173 if worldcover_path(url, folder).exists(): 174 report.skipped.append(name) 175 continue 176 try: 177 found = await download_worldcover_tile(http, url, folder, retry=retry) 178 except (httpx.HTTPError, OSError) as error: 179 report.failed[name] = str(error) or type(error).__name__ 180 continue 181 (report.downloaded if found is not None else report.missing).append(name) 182 finally: 183 if own: 184 await http.aclose() 185 return report
Archives of country for years and the WorldCover tiles over bbox; see the module.
directory defaults to ~firms_client.default_directory().
missing lists the years not published (and the sea tiles), which
are not errors; failed maps a file to its error.