"""Optional GDAL-backed raster helpers (GDAL is loaded only when called)."""from__future__importannotationsimportosfrompathlibimportPathimportreimportsubprocess__all__=["convert_tif_to_cog","confirm_cog","validate_tif_for_ingest"]
[docs]defconvert_tif_to_cog(local_tif:str|Path,cog_path:str|Path|None=None,overwrite:bool=True,options:list[str]|None=None,)->None:"""Convert a GeoTIFF using gdal_translate and atomically replace its output."""tif_path=Path(local_tif)output_path=tif_path.with_suffix(".cog.tif")ifcog_pathisNoneelsePath(cog_path)ifoutput_path.exists()andnotoverwrite:returnifoptionsisNone:options=["-co","COMPRESS=LZW","-co","TILED=YES","-co","BIGTIFF=IF_SAFER",]elifnotisinstance(options,list):raiseValueError("options must be a list of GDAL creation options")normalized_options:list[str]=[]foroptioninoptions:ifnotisinstance(option,str):raiseValueError("options entries must be strings")stripped=option.strip()ifstripped.startswith("-co "):# Legacy callers supplied each creation option as one string._,value=stripped.split(None,1)normalized_options.extend(["-co",value])else:normalized_options.append(stripped)partial_path=output_path.with_name(f"{output_path.stem}.partial{output_path.suffix}")cmd=["gdal_translate",*normalized_options,str(tif_path),str(partial_path)]partial_path.unlink(missing_ok=True)try:subprocess.run(cmd,check=True)os.replace(partial_path,output_path)finally:partial_path.unlink(missing_ok=True)
[docs]defconfirm_cog(local_tif:str|Path)->bool:"""Check gdalinfo output for the COG layout marker."""result=subprocess.run(["gdalinfo",str(Path(local_tif))],capture_output=True,text=True)returnresult.returncode==0andre.search(r"^\s*LAYOUT=COG\s*$",result.stdout,re.MULTILINE)isnotNone
[docs]defvalidate_tif_for_ingest(local_tif:str|Path)->None:"""Fail fast when a TIFF cannot be opened and sampled by optional GDAL."""tif_path=Path(local_tif)ifnottif_path.exists():raiseFileNotFoundError(f"Input TIFF does not exist: {tif_path}")try:fromosgeoimportgdalexceptModuleNotFoundErrorasexc:raiseModuleNotFoundError("GDAL Python bindings are required for raster validation in geeViz. ""Install the GDAL Python bindings using a platform-compatible GDAL build.")fromexcgdal.UseExceptions()dataset=Nonetry:dataset=gdal.Open(str(tif_path),gdal.GA_ReadOnly)ifdatasetisNone:raiseRuntimeError("GDAL returned null dataset")band=dataset.GetRasterBand(1)ifbandisNone:raiseRuntimeError("No raster band found in dataset")band.ReadAsArray(0,0,1,1)band.ReadAsArray(max(dataset.RasterXSize-1,0),max(dataset.RasterYSize-1,0),1,1)exceptRuntimeErrorasexc:raiseRuntimeError("Input TIFF failed GDAL readability checks and cannot be ingested safely.\n"f"File: {tif_path}\nReason: {exc}")fromexcfinally:dataset=None