Zeel commited on
Commit
b90f50d
·
1 Parent(s): b3b03f0
Files changed (1) hide show
  1. app.py +128 -125
app.py CHANGED
@@ -32,141 +32,144 @@ with cols[1]:
32
  file_url = st.query_params.get("file_url", None)
33
  print(f"{file_url=}")
34
 
35
- if file_url:
36
- if ("file_url" in st.session_state) and (st.session_state.file_url == file_url):
37
- # st.toast("Using cached data")
38
- input_gdf = st.session_state.input_gdf
39
- else:
40
- st.session_state.file_url = file_url
41
- if file_url.startswith("https://drive.google.com/file/d/"):
42
- ID = file_url.replace("https://drive.google.com/file/d/", "").split("/")[0]
43
- file_url = f"https://drive.google.com/uc?id={ID}"
44
- elif file_url.startswith("https://drive.google.com/open?id="):
45
- ID = file_url.replace("https://drive.google.com/open?id=", "")
46
- file_url = f"https://drive.google.com/uc?id={ID}"
47
-
48
- input_gdf = gpd.read_file(file_url)
49
- input_gdf = input_gdf.to_crs(epsg=7761) # Gujarat zone
50
- st.session_state.input_gdf = input_gdf
51
- # st.toast("Data loaded and cached")
52
-
53
- def format_fn(x):
54
- return input_gdf.drop(columns=["geometry"]).loc[x].to_dict()
55
-
56
- with st.expander("Advanced Controls", expanded=False):
57
- input_geometry_idx = st.selectbox("Select the geometry", input_gdf.index, format_func=format_fn)
58
- map_type = st.radio(
59
- "",
60
- ["Esri Satellite Map", "Google Hybrid Map (displays place names)", "Google Satellite Map"],
61
- horizontal=True,
62
- )
63
- height = st.number_input("Map height (px)", 1, 10000, 600, 1)
64
-
65
- geometry_gdf = input_gdf[input_gdf.index == input_geometry_idx]
66
-
67
- m = leafmap.Map()
68
-
69
- st.markdown(
70
- """
71
- <style>
72
- .stRadio [role=radiogroup]{
73
- align-items: center;
74
- justify-content: center;
75
- }
76
- </style>
77
- """,
78
- unsafe_allow_html=True,
79
  )
 
80
 
81
- if map_type == "Google Hybrid Map (displays place names)":
82
- st.write(
83
- "<h4><div style='text-align: center;'>Google Hybrid (displays place names)</div></h4>",
84
- unsafe_allow_html=True,
85
- )
86
- m.add_basemap("HYBRID")
87
- elif map_type == "Google Satellite Map":
88
- st.write("<h4><div style='text-align: center;'>Google Satellite</div></h4>", unsafe_allow_html=True)
89
- m.add_basemap("SATELLITE")
90
- elif map_type == "Esri Satellite Map":
91
- st.write("<h4><div style='text-align: center;'>Esri - 2024/10/10</div></h4>", unsafe_allow_html=True)
92
- m.add_wms_layer(
93
- "https://wayback.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/WMTS/1.0.0/GoogleMapsCompatible/MapServer/tile/56450/{z}/{y}/{x}",
94
- layers="0",
95
- )
96
- else:
97
- st.error("Invalid map type")
98
- st.stop()
99
- m.add_gdf(
100
- geometry_gdf.to_crs(epsg=4326),
101
- layer_name="Geometry",
102
- zoom_to_layer=True,
103
- style_function=lambda x: {"color": "red", "fillOpacity": 0.0},
 
 
 
 
 
 
104
  )
105
- m.to_streamlit(height=height)
106
-
107
- # Metrics
108
- stats_df = pd.DataFrame()
109
- stats_df["Points"] = json.loads(geometry_gdf.to_crs(4326).to_json())["features"][0]["geometry"]["coordinates"]
110
- stats_df["Centroid"] = geometry_gdf.centroid.to_crs(4326).item()
111
- stats_df["Area (ha)"] = geometry_gdf.geometry.area.item() / 10000
112
- stats_df["Perimeter (m)"] = geometry_gdf.geometry.length.item()
113
-
114
- st.write("<h3><div style='text-align: center;'>Geometry Metrics</div></h3>", unsafe_allow_html=True)
115
- # st.markdown(
116
- # f"""| Metric | Value |
117
- # | --- | --- |
118
- # | Area (ha) | {stats_df['Area (ha)'].item():.2f} ha|
119
- # | Perimeter (m) | {stats_df['Perimeter (m)'].item():.2f} m |"""
120
- # unsafe_allow_html=True)
121
- centroid_lon = stats_df["Centroid"].item().xy[0][0]
122
- centroid_lat = stats_df["Centroid"].item().xy[1][0]
123
- centroid_url = f"http://maps.google.com/maps?q={centroid_lat},{centroid_lon}&layer=satellite"
124
- st.markdown(
125
- f"""
126
- <div style="display: flex; justify-content: center;">
127
- <table>
128
- <tr>
129
- <th>Metric</th>
130
- <th>Value</th>
131
- </tr>
132
- <td>Centroid</td>
133
- <td>
134
- ({centroid_lon:.5f}, {centroid_lat:.5f})
135
- <a href="{centroid_url}" target="_blank">
136
- <button>View on Google Maps</button>
137
- </a>
138
- </td>
139
- </tr>
140
- <td>Area (ha)</td>
141
- <td>{stats_df['Area (ha)'].item():.2f} ha</td>
142
- </tr>
143
- <tr>
144
- <td>Perimeter (m)</td>
145
- <td>{stats_df['Perimeter (m)'].item():.2f} m</td>
146
- </tr>
147
- </table>
148
- </div>
149
- """,
150
  unsafe_allow_html=True,
151
  )
152
- print(stats_df["Points"].item())
153
- print(type(stats_df["Points"].item()))
154
-
155
- csv = stats_df.T.to_csv(index=True)
156
- st.download_button(
157
- "Download Geometry Metrics", csv, f"{file_url}_metrics.csv", "text/csv", use_container_width=True
 
 
 
158
  )
159
-
160
  else:
161
- st.warning("Please provide a KML or GeoJSON URL as a query parameter, e.g., `?file_url=<your_file_url>`")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
  # Add HTML button to open in Google Earth
164
  st.markdown(
165
  f"""
166
- <div style="display: flex; justify-content: center;">
167
- <a href="https://huggingface.co/spaces/SustainabilityLabIITGN/NDVI_PERG?file_url={file_url}" target="_blank">
168
- <button>Click for NDVI Timeseries</button>
169
- </a>
170
- """,
171
  unsafe_allow_html=True,
172
  )
 
32
  file_url = st.query_params.get("file_url", None)
33
  print(f"{file_url=}")
34
 
35
+ if not file_url:
36
+ st.warning(
37
+ "Please provide a KML or GeoJSON URL as a query parameter, e.g., `?file_url=<your_file_url>` or upload a file."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  )
39
+ file_url = st.file_uploader("Upload KML/GeoJSON file", type=["geojson", "kml", "shp"])
40
 
41
+
42
+ if ("file_url" in st.session_state) and (st.session_state.file_url == file_url):
43
+ # st.toast("Using cached data")
44
+ input_gdf = st.session_state.input_gdf
45
+ else:
46
+ st.session_state.file_url = file_url
47
+ if file_url.startswith("https://drive.google.com/file/d/"):
48
+ ID = file_url.replace("https://drive.google.com/file/d/", "").split("/")[0]
49
+ file_url = f"https://drive.google.com/uc?id={ID}"
50
+ elif file_url.startswith("https://drive.google.com/open?id="):
51
+ ID = file_url.replace("https://drive.google.com/open?id=", "")
52
+ file_url = f"https://drive.google.com/uc?id={ID}"
53
+
54
+ input_gdf = gpd.read_file(file_url)
55
+ input_gdf = input_gdf.to_crs(epsg=7761) # Gujarat zone
56
+ st.session_state.input_gdf = input_gdf
57
+ # st.toast("Data loaded and cached")
58
+
59
+
60
+ def format_fn(x):
61
+ return input_gdf.drop(columns=["geometry"]).loc[x].to_dict()
62
+
63
+
64
+ with st.expander("Advanced Controls", expanded=False):
65
+ input_geometry_idx = st.selectbox("Select the geometry", input_gdf.index, format_func=format_fn)
66
+ map_type = st.radio(
67
+ "",
68
+ ["Esri Satellite Map", "Google Hybrid Map (displays place names)", "Google Satellite Map"],
69
+ horizontal=True,
70
  )
71
+ height = st.number_input("Map height (px)", 1, 10000, 600, 1)
72
+
73
+ geometry_gdf = input_gdf[input_gdf.index == input_geometry_idx]
74
+
75
+ m = leafmap.Map()
76
+
77
+ st.markdown(
78
+ """
79
+ <style>
80
+ .stRadio [role=radiogroup]{
81
+ align-items: center;
82
+ justify-content: center;
83
+ }
84
+ </style>
85
+ """,
86
+ unsafe_allow_html=True,
87
+ )
88
+
89
+ if map_type == "Google Hybrid Map (displays place names)":
90
+ st.write(
91
+ "<h4><div style='text-align: center;'>Google Hybrid (displays place names)</div></h4>",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  unsafe_allow_html=True,
93
  )
94
+ m.add_basemap("HYBRID")
95
+ elif map_type == "Google Satellite Map":
96
+ st.write("<h4><div style='text-align: center;'>Google Satellite</div></h4>", unsafe_allow_html=True)
97
+ m.add_basemap("SATELLITE")
98
+ elif map_type == "Esri Satellite Map":
99
+ st.write("<h4><div style='text-align: center;'>Esri - 2024/10/10</div></h4>", unsafe_allow_html=True)
100
+ m.add_wms_layer(
101
+ "https://wayback.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/WMTS/1.0.0/GoogleMapsCompatible/MapServer/tile/56450/{z}/{y}/{x}",
102
+ layers="0",
103
  )
 
104
  else:
105
+ st.error("Invalid map type")
106
+ st.stop()
107
+ m.add_gdf(
108
+ geometry_gdf.to_crs(epsg=4326),
109
+ layer_name="Geometry",
110
+ zoom_to_layer=True,
111
+ style_function=lambda x: {"color": "red", "fillOpacity": 0.0},
112
+ )
113
+ m.to_streamlit(height=height)
114
+
115
+ # Metrics
116
+ stats_df = pd.DataFrame()
117
+ stats_df["Points"] = json.loads(geometry_gdf.to_crs(4326).to_json())["features"][0]["geometry"]["coordinates"]
118
+ stats_df["Centroid"] = geometry_gdf.centroid.to_crs(4326).item()
119
+ stats_df["Area (ha)"] = geometry_gdf.geometry.area.item() / 10000
120
+ stats_df["Perimeter (m)"] = geometry_gdf.geometry.length.item()
121
+
122
+ st.write("<h3><div style='text-align: center;'>Geometry Metrics</div></h3>", unsafe_allow_html=True)
123
+ # st.markdown(
124
+ # f"""| Metric | Value |
125
+ # | --- | --- |
126
+ # | Area (ha) | {stats_df['Area (ha)'].item():.2f} ha|
127
+ # | Perimeter (m) | {stats_df['Perimeter (m)'].item():.2f} m |"""
128
+ # unsafe_allow_html=True)
129
+ centroid_lon = stats_df["Centroid"].item().xy[0][0]
130
+ centroid_lat = stats_df["Centroid"].item().xy[1][0]
131
+ centroid_url = f"http://maps.google.com/maps?q={centroid_lat},{centroid_lon}&layer=satellite"
132
+ st.markdown(
133
+ f"""
134
+ <div style="display: flex; justify-content: center;">
135
+ <table>
136
+ <tr>
137
+ <th>Metric</th>
138
+ <th>Value</th>
139
+ </tr>
140
+ <td>Centroid</td>
141
+ <td>
142
+ ({centroid_lon:.5f}, {centroid_lat:.5f})
143
+ <a href="{centroid_url}" target="_blank">
144
+ <button>View on Google Maps</button>
145
+ </a>
146
+ </td>
147
+ </tr>
148
+ <td>Area (ha)</td>
149
+ <td>{stats_df['Area (ha)'].item():.2f} ha</td>
150
+ </tr>
151
+ <tr>
152
+ <td>Perimeter (m)</td>
153
+ <td>{stats_df['Perimeter (m)'].item():.2f} m</td>
154
+ </tr>
155
+ </table>
156
+ </div>
157
+ """,
158
+ unsafe_allow_html=True,
159
+ )
160
+ print(stats_df["Points"].item())
161
+ print(type(stats_df["Points"].item()))
162
+
163
+ csv = stats_df.T.to_csv(index=True)
164
+ st.download_button("Download Geometry Metrics", csv, f"{file_url}_metrics.csv", "text/csv", use_container_width=True)
165
 
166
  # Add HTML button to open in Google Earth
167
  st.markdown(
168
  f"""
169
+ <div style="display: flex; justify-content: center;">
170
+ <a href="https://huggingface.co/spaces/SustainabilityLabIITGN/NDVI_PERG?file_url={file_url}" target="_blank">
171
+ <button>Click for NDVI Timeseries</button>
172
+ </a>
173
+ """,
174
  unsafe_allow_html=True,
175
  )