File size: 10,333 Bytes
843b944
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import tempfile
from pathlib import Path

import folium
import geopandas as gpd
import numpy as np
import rasterio
import streamlit as st
from streamlit_folium import st_folium

from spatial_toolkit_py import inspection, io_conversions, workflows


st.set_page_config(page_title="Spatial Toolkit", layout="wide")

TOOL_CONTEXT = {
    "create_raster_stack": "Combine several aligned raster layers into one stack. Example: stack annual rainfall, temperature, and canopy cover before habitat modelling.",
    "netcdf_to_tiff": "Extract gridded climate or ocean data into GeoTIFF. Example: convert monthly NetCDF climate layers into TIFFs for local analysis.",
    "ascii_to_tiff": "Bring legacy ASCII grids into a standard raster format. Example: convert an old DEM grid to TIFF before stacking it with newer layers.",
    "tiff_to_netcdf": "Export raster outputs into NetCDF for model sharing. Example: package a derived climate surface for downstream time-series workflows.",
    "tiff_to_ascii": "Export a GeoTIFF to ASCII grid for older tools. Example: prepare a resistance surface for a legacy connectivity workflow.",
    "shp_to_tiff": "Convert vector boundaries or classes to raster cells. Example: rasterise soil polygons onto the same grid as environmental covariates.",
    "tiff_to_shp": "Convert raster classes into vector features. Example: turn a binary habitat suitability raster into polygons for review and editing.",
    "raster_qc_tool": "Run a quick raster quality-control report before modelling. Example: check CRS, extent, resolution, and bands before stacking predictors.",
}

WORKFLOW_CONTEXT = {
    "raster_qc": "Check CRS, extent, resolution, band count, names, and missing values. Example: verify predictor rasters before building a species distribution model."
}

TOOL_CATEGORIES = {
    "Convert": [
        "netcdf_to_tiff",
        "ascii_to_tiff",
        "tiff_to_netcdf",
        "tiff_to_ascii",
        "shp_to_tiff",
        "tiff_to_shp",
    ],
    "Raster": [
        "create_raster_stack",
    ],
    "Vector": [],
    "QC": [
        "raster_qc_tool",
    ],
}


def choose_primary_spatial_path(paths):
    preferred_order = [".shp", ".gpkg", ".geojson", ".tif", ".tiff", ".nc", ".asc"]

    for suffix in preferred_order:
        for path in paths:
            if path.suffix.lower() == suffix:
                return str(path)

    raise ValueError("No supported spatial file was found in the dropped files.")


def load_uploaded_content(uploaded_files):
    if not uploaded_files:
        return None

    target_dir = Path(tempfile.mkdtemp(prefix="spatialtoolkit-upload-"))
    saved_paths = []

    for uploaded_file in uploaded_files:
        destination = target_dir / uploaded_file.name
        destination.write_bytes(uploaded_file.getbuffer())
        saved_paths.append(destination)

    vector_paths = [path for path in saved_paths if path.suffix.lower() in {".shp", ".gpkg", ".geojson"}]
    raster_paths = [path for path in saved_paths if path.suffix.lower() in {".tif", ".tiff", ".nc", ".asc"}]

    if vector_paths:
        primary_path = choose_primary_spatial_path(vector_paths)
        return {"kind": "vector", "paths": [str(path) for path in saved_paths], "primary_path": primary_path}

    if len(raster_paths) > 1:
        return {
            "kind": "raster_stack",
            "paths": [str(path) for path in raster_paths],
            "primary_path": str(raster_paths[0]),
        }

    if len(raster_paths) == 1:
        return {"kind": "raster", "paths": [str(raster_paths[0])], "primary_path": str(raster_paths[0])}

    raise ValueError("No supported spatial file was found in the dropped files.")


def build_metadata_summary(content):
    if content["kind"] == "raster_stack":
        metadata = inspection.get_spatial_metadata(content["primary_path"])
        metadata["type"] = "raster_stack"
        metadata["stack_size"] = len(content["paths"])
        metadata["stack_members"] = [Path(path).name for path in content["paths"]]
        return metadata

    return inspection.get_spatial_metadata(content["primary_path"])


def build_raster_overlay(path: str):
    with rasterio.open(path) as src:
        max_dim = 512
        scale = max(src.width, src.height) / max_dim
        if scale > 1:
            out_height = max(1, int(src.height / scale))
            out_width = max(1, int(src.width / scale))
            band = src.read(
                1,
                out_shape=(out_height, out_width),
                masked=True,
                resampling=rasterio.enums.Resampling.bilinear,
            )
        else:
            band = src.read(1, masked=True)

        bounds = src.bounds

    data = np.ma.filled(band, np.nan).astype("float32")
    finite = np.isfinite(data)
    if not finite.any():
        rgba = np.zeros((*data.shape, 4), dtype=np.uint8)
    else:
        low, high = np.nanpercentile(data[finite], [2, 98])
        if high <= low:
          high = low + 1
        scaled = np.clip((data - low) / (high - low), 0, 1)
        rgba = np.zeros((*data.shape, 4), dtype=np.uint8)
        rgba[..., 0] = (scaled * 34 + 11).astype(np.uint8)
        rgba[..., 1] = (scaled * 166 + 60).astype(np.uint8)
        rgba[..., 2] = (scaled * 120 + 73).astype(np.uint8)
        rgba[..., 3] = np.where(finite, 220, 0).astype(np.uint8)

    overlay_bounds = [[bounds.bottom, bounds.left], [bounds.top, bounds.right]]
    return rgba, overlay_bounds


def render_map(content):
    if content is None:
        return

    if content["kind"] in {"raster", "raster_stack"}:
        metadata = inspection.get_spatial_metadata(content["primary_path"])
        bounds = metadata["bounds"]
        center = [(bounds[1] + bounds[3]) / 2, (bounds[0] + bounds[2]) / 2]
        fmap = folium.Map(location=center, zoom_start=5, tiles="CartoDB positron")
        image, overlay_bounds = build_raster_overlay(content["primary_path"])
        folium.raster_layers.ImageOverlay(
            image=image,
            bounds=overlay_bounds,
            opacity=0.85,
            interactive=False,
        ).add_to(fmap)
        fmap.fit_bounds(overlay_bounds)
        st_folium(fmap, use_container_width=True, height=520)
        return

    vector = gpd.read_file(content["primary_path"])
    bounds = vector.total_bounds
    center = [(bounds[1] + bounds[3]) / 2, (bounds[0] + bounds[2]) / 2]
    fmap = folium.Map(location=center, zoom_start=6, tiles="CartoDB positron")
    folium.GeoJson(vector.to_json()).add_to(fmap)
    fmap.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
    st_folium(fmap, use_container_width=True, height=520)


st.title("Spatial Toolkit")
st.caption("Python / Streamlit track for ecological GIS utilities")

uploaded = st.file_uploader(
    "Browse or drag and drop spatial files once",
    type=["tif", "tiff", "nc", "asc", "shp", "geojson", "gpkg", "dbf", "shx", "prj"],
    accept_multiple_files=True,
)
st.caption("Drop a single raster, multiple rasters for a stack, or a full shapefile bundle.")

mode = st.radio("Choose what to do", ["Inspect", "Tools", "Workflows"], horizontal=True)
content = load_uploaded_content(uploaded) if uploaded else None

if mode == "Inspect":
    st.subheader("Layer inspection")
    if content:
        render_map(content)
        metadata = build_metadata_summary(content)
        st.json(metadata)

        if metadata["type"] == "vector":
            st.subheader("Attribute table")
            st.dataframe(inspection.get_attribute_table(content["primary_path"]))
    else:
        st.info("Load a raster, raster stack, or vector layer to inspect it.")

if mode == "Tools":
    st.subheader("Conversions and stack building")
    tool_category = st.selectbox("Category", list(TOOL_CATEGORIES.keys()))
    available_tools = TOOL_CATEGORIES[tool_category]
    if not available_tools:
        st.info("This category is planned but no Python app tools are exposed here yet.")
        st.stop()

    tool = st.selectbox("Tool", available_tools)
    st.info(TOOL_CONTEXT[tool])
    default_suffix = {
        "create_raster_stack": ".tif",
        "netcdf_to_tiff": ".tif",
        "ascii_to_tiff": ".tif",
        "tiff_to_netcdf": ".nc",
        "tiff_to_ascii": ".asc",
        "shp_to_tiff": ".tif",
        "tiff_to_shp": ".shp",
        "raster_qc_tool": ".txt",
    }[tool]
    output_path = st.text_input(
        "Output path",
        value=str(Path(tempfile.gettempdir()) / f"spatial-tool-output{default_suffix}"),
    )

    if st.button("Run tool", type="primary"):
        if not content:
            st.error("Load files first.")
        elif tool == "create_raster_stack":
            if content["kind"] != "raster_stack":
                st.error("Drop multiple raster files first to create a raster stack.")
            else:
                result = io_conversions.create_raster_stack(content["paths"], output_path)
                st.success(f"Created raster stack: {result}")
        elif tool == "raster_qc_tool":
            if content["kind"] not in {"raster", "raster_stack"}:
                st.error("Load a raster or raster stack first.")
            else:
                result = inspection.raster_quality_report(content["primary_path"])
                st.dataframe(result)
        else:
            tool_map = {
                "netcdf_to_tiff": io_conversions.netcdf_to_tiff,
                "ascii_to_tiff": io_conversions.ascii_to_tiff,
                "tiff_to_netcdf": io_conversions.tiff_to_netcdf,
                "tiff_to_ascii": io_conversions.tiff_to_ascii,
                "shp_to_tiff": io_conversions.shp_to_tiff,
                "tiff_to_shp": io_conversions.tiff_to_shp,
            }
            result = tool_map[tool](content["primary_path"], output_path)
            st.success(f"Completed: {result}")

if mode == "Workflows":
    st.subheader("Workflows")
    workflow_name = st.selectbox("Workflow", ["raster_qc"])
    st.info(WORKFLOW_CONTEXT[workflow_name])

    if st.button("Run workflow"):
        if not content:
            st.error("Load files first.")
        elif content["kind"] not in {"raster", "raster_stack"}:
            st.error("Load a raster or raster stack for workflows.")
        else:
            result = workflows.run_named_workflow(workflow_name, content["primary_path"])
            st.json(result)