Joshua Sundance Bailey commited on
Commit
d0f4020
·
unverified ·
2 Parent(s): 20c266f c6718c6

Merge pull request #2 from joshuasundance-swca/kml_tricks

Browse files
geospatial-data-converter/kml_tricks.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import zipfile
2
+ from io import StringIO
3
+
4
+ import bs4
5
+ import geopandas as gpd
6
+ import lxml # nosec
7
+ import pandas as pd
8
+
9
+
10
+ def parse_descriptions_to_geodf(geodf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
11
+ """Parses Descriptions from Google Earth file to a GeoDataFrame object"""
12
+
13
+ dataframes = []
14
+
15
+ # Iterate over descriptions and extract data
16
+ for desc in geodf["Description"]:
17
+ desc_as_io = StringIO(desc)
18
+
19
+ # Try to read the description into a DataFrame
20
+ parsed_html = pd.read_html(desc_as_io)
21
+ try:
22
+ temp_df = parsed_html[1].T
23
+ except IndexError:
24
+ temp_df = parsed_html[0].T
25
+
26
+ # Set DataFrame header and remove the first row
27
+ temp_df.columns = temp_df.iloc[0]
28
+ temp_df = temp_df.iloc[1:]
29
+
30
+ dataframes.append(temp_df)
31
+
32
+ # Combine all DataFrames
33
+ combined_df = pd.concat(dataframes, ignore_index=True)
34
+
35
+ # Add geometry data
36
+ combined_df["geometry"] = geodf["geometry"]
37
+
38
+ # Create a GeoDataFrame with the combined data and original CRS
39
+ result_geodf = gpd.GeoDataFrame(combined_df, crs=geodf.crs)
40
+
41
+ return result_geodf
42
+
43
+
44
+ def load_kmz_as_geodf(file_path: str) -> gpd.GeoDataFrame:
45
+ """Loads a KMZ file into a GeoPandas DataFrame, assuming the KMZ contains one KML file"""
46
+
47
+ # Open the KMZ file
48
+ with zipfile.ZipFile(file_path, "r") as kmz:
49
+ # List all KML files in the KMZ
50
+ kml_files = [file for file in kmz.namelist() if file.endswith(".kml")]
51
+
52
+ # Ensure there's only one KML file in the KMZ
53
+ if len(kml_files) != 1:
54
+ raise IndexError(
55
+ "KMZ contains more than one KML. Please extract or convert to multiple KMLs.",
56
+ )
57
+
58
+ # Read the KML file into a GeoDataFrame
59
+ geodf = gpd.read_file(
60
+ f"zip://{file_path}/{kml_files[0]}",
61
+ driver="KML",
62
+ engine="pyogrio",
63
+ )
64
+
65
+ return geodf
66
+
67
+
68
+ def load_ge_file(file_path: str) -> gpd.GeoDataFrame:
69
+ """Loads a KML or KMZ file and parses its descriptions into a GeoDataFrame"""
70
+
71
+ if file_path.endswith(".kml"):
72
+ return parse_descriptions_to_geodf(
73
+ gpd.read_file(file_path, driver="KML", engine="pyogrio"),
74
+ )
75
+ elif file_path.endswith(".kmz"):
76
+ return parse_descriptions_to_geodf(load_kmz_as_geodf(file_path))
77
+ raise ValueError("The file must have a .kml or .kmz extension.")
78
+
79
+
80
+ def extract_data_from_kml_code(kml_code: str) -> pd.DataFrame:
81
+ """Extracts data from KML code into a DataFrame using SimpleData tags, excluding embedded tables in feature descriptions"""
82
+
83
+ # Parse the KML source code
84
+ soup = bs4.BeautifulSoup(kml_code, "html.parser")
85
+
86
+ # Find all SchemaData tags (representing rows)
87
+ schema_data_tags = soup.find_all("schemadata")
88
+
89
+ # Create a generator that yields a dictionary for each row, containing the Placemark name and each SimpleData field
90
+ row_dicts = (
91
+ {
92
+ "Placemark_name": tag.parent.parent.find("name").text,
93
+ **{field.get("name"): field.text for field in tag.find_all("simpledata")},
94
+ }
95
+ for tag in schema_data_tags
96
+ )
97
+
98
+ # Convert the row dictionaries into a DataFrame
99
+ df = pd.DataFrame(row_dicts)
100
+
101
+ return df
102
+
103
+
104
+ def extract_kml_code_from_file(file_path: str) -> str:
105
+ """Extracts KML source code from a Google Earth file (KML or KMZ)"""
106
+
107
+ file_extension = file_path.lower().split(".")[-1]
108
+
109
+ if file_extension == "kml":
110
+ with open(file_path, "r") as kml_file:
111
+ kml_code = kml_file.read()
112
+ elif file_extension == "kmz":
113
+ with zipfile.ZipFile(file_path) as kmz_file:
114
+ # Find all KML files in the KMZ
115
+ kml_files = [
116
+ file for file in kmz_file.namelist() if file.lower().endswith(".kml")
117
+ ]
118
+
119
+ if len(kml_files) != 1:
120
+ raise IndexError(
121
+ "KMZ file contains more than one KML. Please extract or convert to multiple KMLs.",
122
+ )
123
+
124
+ with kmz_file.open(kml_files[0]) as kml_file:
125
+ # Decode the KML file's content from bytes to string
126
+ kml_code = kml_file.read().decode()
127
+ else:
128
+ raise ValueError("The input file must have a .kml or .kmz extension.")
129
+
130
+ return kml_code
131
+
132
+
133
+ def extract_data_from_ge_file(file_path: str) -> gpd.GeoDataFrame:
134
+ """Extracts data from a Google Earth file (KML or KMZ) into a GeoDataFrame using SimpleData tags, excluding embedded tables in feature descriptions"""
135
+
136
+ data_df = extract_data_from_kml_code(extract_kml_code_from_file(file_path))
137
+
138
+ if file_path.endswith(".kmz"):
139
+ ge_file_gdf = load_kmz_as_geodf(file_path)
140
+ else:
141
+ ge_file_gdf = gpd.read_file(file_path, driver="KML", engine="pyogrio")
142
+
143
+ geo_df = gpd.GeoDataFrame(
144
+ data_df,
145
+ geometry=ge_file_gdf["geometry"],
146
+ crs=ge_file_gdf.crs,
147
+ )
148
+
149
+ return geo_df
150
+
151
+
152
+ def load_ge_data(file_path: str) -> gpd.GeoDataFrame:
153
+ """Extracts data from a Google Earth file (KML or KMZ) and handles errors due to parsing issues"""
154
+
155
+ kml_code = extract_kml_code_from_file(file_path)
156
+
157
+ # Choose the extraction method based on the presence of SimpleData or SimpleField tags in the KML code
158
+ primary_func, fallback_func = (
159
+ (extract_data_from_ge_file, load_ge_file)
160
+ if any(tag in kml_code.lower() for tag in ("<simpledata", "<simplefield"))
161
+ else (load_ge_file, extract_data_from_ge_file)
162
+ )
163
+
164
+ try:
165
+ data_df = primary_func(file_path)
166
+ except (
167
+ pd.errors.ParserError,
168
+ lxml.etree.ParserError,
169
+ lxml.etree.XMLSyntaxError,
170
+ ValueError,
171
+ ):
172
+ data_df = fallback_func(file_path)
173
+
174
+ return data_df
geospatial-data-converter/utils.py CHANGED
@@ -6,6 +6,8 @@ from typing import BinaryIO
6
 
7
  import geopandas as gpd
8
 
 
 
9
  output_format_dict = {
10
  "ESRI Shapefile": ("shp", "zip", "application/zip"), # must be zipped
11
  "OpenFileGDB": ("gdb", "zip", "application/zip"), # must be zipped
@@ -17,7 +19,9 @@ output_format_dict = {
17
 
18
  def read_file(file: BinaryIO, *args, **kwargs) -> gpd.GeoDataFrame:
19
  """Read a file and return a GeoDataFrame"""
20
- if file.name.lower().endswith(".zip"):
 
 
21
  with TemporaryDirectory() as tmp_dir:
22
  tmp_file_path = os.path.join(tmp_dir, file.name)
23
  with open(tmp_file_path, "wb") as tmp_file:
@@ -28,6 +32,12 @@ def read_file(file: BinaryIO, *args, **kwargs) -> gpd.GeoDataFrame:
28
  engine="pyogrio",
29
  **kwargs,
30
  )
 
 
 
 
 
 
31
  return gpd.read_file(file, *args, engine="pyogrio", **kwargs)
32
 
33
 
 
6
 
7
  import geopandas as gpd
8
 
9
+ from kml_tricks import load_ge_data
10
+
11
  output_format_dict = {
12
  "ESRI Shapefile": ("shp", "zip", "application/zip"), # must be zipped
13
  "OpenFileGDB": ("gdb", "zip", "application/zip"), # must be zipped
 
19
 
20
  def read_file(file: BinaryIO, *args, **kwargs) -> gpd.GeoDataFrame:
21
  """Read a file and return a GeoDataFrame"""
22
+ basename, ext = os.path.splitext(os.path.basename(file.name))
23
+ ext = ext.lower().strip(".")
24
+ if ext == "zip":
25
  with TemporaryDirectory() as tmp_dir:
26
  tmp_file_path = os.path.join(tmp_dir, file.name)
27
  with open(tmp_file_path, "wb") as tmp_file:
 
32
  engine="pyogrio",
33
  **kwargs,
34
  )
35
+ elif ext in ("kml", "kmz"):
36
+ with TemporaryDirectory() as tmp_dir:
37
+ tmp_file_path = os.path.join(tmp_dir, file.name)
38
+ with open(tmp_file_path, "wb") as tmp_file:
39
+ tmp_file.write(file.read())
40
+ return load_ge_data(tmp_file_path)
41
  return gpd.read_file(file, *args, engine="pyogrio", **kwargs)
42
 
43
 
requirements.txt CHANGED
@@ -1,3 +1,5 @@
 
1
  geopandas==0.14.0
 
2
  pyogrio==0.6.0
3
  streamlit==1.27.2
 
1
+ beautifulsoup4==4.12.2
2
  geopandas==0.14.0
3
+ lxml==4.9.3
4
  pyogrio==0.6.0
5
  streamlit==1.27.2