import os import subprocess import xarray as xr import geopandas as gpd import rioxarray def listar_datas_ecmwf(): try: resultado = subprocess.run( ["gsutil", "ls", "gs://garagem/previsao/ecmwf_nc/"], capture_output=True, text=True, check=True ) linhas = resultado.stdout.strip().split("\n") datas = [linha.strip().split("/")[-2] for linha in linhas if linha.strip()] return sorted(datas, reverse=True) except subprocess.CalledProcessError: return [] def carregar_netCDF(path): return xr.open_dataset(path) def recortar_com_shapefile(da, shape): da = da.rio.write_crs("epsg:4326") return da.rio.clip(shape.geometry, shape.crs, drop=True) '''def baixar_arquivo_gcs(nome_arquivo, destino_local="/tmp", bucket_path=None): """ Baixa um arquivo do GCS para o diretório local. Se bucket_path não for informado, assume gs://garagem/previsao/acumulados/... """ import subprocess from config import DATA, HORA if bucket_path is None: bucket_path = f"gs://garagem/previsao/acumulados/{DATA}/{HORA}/" origem = f"{bucket_path}{nome_arquivo}" destino = os.path.join(destino_local, nome_arquivo) try: subprocess.run(["gsutil", "cp", origem, destino], check=True) return destino except subprocess.CalledProcessError as e: print(f"❌ Erro ao baixar {nome_arquivo} do GCS: {e}") return None''' def baixar_arquivo_gcs(gcs_path): """ Baixa um arquivo do Google Cloud Storage para um diretório temporário. """ if not gcs_path.startswith("gs://"): raise ValueError(f"Invalid GCS path: {gcs_path}") local_path = f"/tmp/{gcs_path.split('/')[-1]}" # Extract filename for local path try: subprocess.run(["gsutil", "cp", gcs_path, local_path], check=True) return local_path except subprocess.CalledProcessError as e: print(f"❌ Erro ao baixar {gcs_path}: {e}") return None def abrir_dado_precip(path_local, recorte="Sem recorte", shape_path="/home/gabriela-vitelli/shapefiles/BUFFER_EFC_25KM_reconstruido.shp"): """ Abre o arquivo NetCDF, recorta se necessário e retorna o DataArray da precipitação. """ import xarray as xr import rioxarray import geopandas as gpd ds = xr.open_dataset(path_local, engine="netcdf4") varname = list(ds.data_vars)[0] da = ds[varname] if recorte == "EFC": shape = gpd.read_file(shape_path) da = da.rio.write_crs("EPSG:4326") da = da.rio.clip(shape.geometry.values, shape.crs, drop=True) return da