File size: 2,660 Bytes
d99d623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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