Joshua Sundance Bailey
commited on
Commit
·
c6718c6
1
Parent(s):
11a4b10
messy old code
Browse files
geospatial-data-converter/kml_tricks.py
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
import zipfile
|
2 |
from io import StringIO
|
3 |
-
from typing import Any
|
4 |
|
5 |
import bs4
|
6 |
import geopandas as gpd
|
@@ -8,100 +7,168 @@ import lxml # nosec
|
|
8 |
import pandas as pd
|
9 |
|
10 |
|
11 |
-
def
|
12 |
-
|
13 |
-
for desc in gdf["Description"]:
|
14 |
-
try:
|
15 |
-
html_df = pd.read_html(StringIO(desc), flavor="lxml")
|
16 |
-
yield html_df[-1].T
|
17 |
-
except (lxml.etree.ParserError, lxml.etree.XMLSyntaxError) as e:
|
18 |
-
raise pd.errors.ParserError from e
|
19 |
|
20 |
-
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
|
|
28 |
|
29 |
-
|
|
|
|
|
30 |
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
kml_files = [f for f in kmz.namelist() if f.endswith(".kml")]
|
35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
if len(kml_files) != 1:
|
37 |
raise IndexError(
|
38 |
-
"KMZ contains more than one KML.
|
39 |
)
|
40 |
|
41 |
-
|
42 |
-
|
|
|
43 |
driver="KML",
|
44 |
engine="pyogrio",
|
45 |
)
|
46 |
|
|
|
47 |
|
48 |
-
def parse_file_to_gdf(path: str) -> gpd.GeoDataFrame:
|
49 |
-
if path.endswith(".kml"):
|
50 |
-
return parse_description_to_gdf(
|
51 |
-
gpd.read_file(path, driver="KML", engine="pyogrio"),
|
52 |
-
)
|
53 |
|
54 |
-
|
55 |
-
|
56 |
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
|
60 |
def extract_data_from_kml_code(kml_code: str) -> pd.DataFrame:
|
61 |
-
|
62 |
-
|
|
|
|
|
63 |
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
)
|
68 |
|
69 |
-
|
|
|
|
|
|
|
70 |
|
71 |
|
72 |
-
def
|
|
|
|
|
73 |
file_extension = file_path.lower().split(".")[-1]
|
74 |
|
75 |
if file_extension == "kml":
|
76 |
-
with open(file_path, "r") as
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
-
if file_extension == "kmz":
|
80 |
-
with zipfile.ZipFile(file_path) as kmz:
|
81 |
-
kml_files = [f for f in kmz.namelist() if f.lower().endswith(".kml")]
|
82 |
if len(kml_files) != 1:
|
83 |
raise IndexError(
|
84 |
-
"KMZ contains more than one KML.
|
85 |
)
|
86 |
-
with kmz.open(kml_files[0]) as kml:
|
87 |
-
return kml.read().decode()
|
88 |
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
|
92 |
-
def
|
93 |
-
|
|
|
|
|
94 |
|
95 |
if file_path.endswith(".kmz"):
|
96 |
-
|
97 |
else:
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
100 |
-
|
|
|
101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
-
def read_ge_file(file_path: str) -> gpd.GeoDataFrame:
|
104 |
try:
|
105 |
-
|
106 |
-
except (
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import zipfile
|
2 |
from io import StringIO
|
|
|
3 |
|
4 |
import bs4
|
5 |
import geopandas as gpd
|
|
|
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/kml_tricks_before.py
DELETED
@@ -1,141 +0,0 @@
|
|
1 |
-
import zipfile
|
2 |
-
from io import StringIO
|
3 |
-
|
4 |
-
import bs4
|
5 |
-
import fiona
|
6 |
-
import geopandas as gpd
|
7 |
-
import lxml # nosec
|
8 |
-
import pandas as pd
|
9 |
-
|
10 |
-
fiona.drvsupport.supported_drivers["KML"] = "rw"
|
11 |
-
|
12 |
-
|
13 |
-
def desctogdf(gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
14 |
-
"""Parses Descriptions from Google Earth file to create a legit gpd.GeoDataFrame"""
|
15 |
-
dfs = []
|
16 |
-
len(gdf)
|
17 |
-
# pull chunks of data from feature descriptions
|
18 |
-
for idx, desc in enumerate(gdf["Description"], start=1):
|
19 |
-
desc = StringIO(desc)
|
20 |
-
try:
|
21 |
-
tmpdf = pd.read_html(desc)[1].T
|
22 |
-
except IndexError:
|
23 |
-
tmpdf = pd.read_html(desc)[0].T
|
24 |
-
tmpdf.columns = tmpdf.iloc[0]
|
25 |
-
tmpdf = tmpdf.iloc[1:]
|
26 |
-
dfs.append(tmpdf)
|
27 |
-
# join chunks together
|
28 |
-
ccdf = pd.concat(dfs, ignore_index=True)
|
29 |
-
ccdf["geometry"] = gdf["geometry"]
|
30 |
-
df = gpd.GeoDataFrame(ccdf, crs=gdf.crs)
|
31 |
-
return df
|
32 |
-
|
33 |
-
|
34 |
-
def readkmz(path: str) -> gpd.GeoDataFrame:
|
35 |
-
"""Simply read kmz using geopandas/fiona without parsing Descriptions"""
|
36 |
-
# get name of kml in kmz (should be doc.kml but we don't assume)
|
37 |
-
with zipfile.ZipFile(path, "r") as kmz:
|
38 |
-
namelist = [f for f in kmz.namelist() if f.endswith(".kml")]
|
39 |
-
if len(namelist) != 1:
|
40 |
-
# this should never really happen
|
41 |
-
raise IndexError(
|
42 |
-
"kmz contains more than one kml. Extract or convert to multiple kmls.",
|
43 |
-
)
|
44 |
-
# return GeoDataFrame by reading contents of kmz
|
45 |
-
return gpd.read_file("zip://{}\\{}".format(path, namelist[0]), driver="KML")
|
46 |
-
|
47 |
-
|
48 |
-
def ge_togdf(gefile: str) -> gpd.GeoDataFrame:
|
49 |
-
"""Return gpd.GeoDataFrame after reading kmz or kml and parsing Descriptions"""
|
50 |
-
if gefile.endswith(".kml"):
|
51 |
-
gdf = desctogdf(gpd.read_file(gefile, driver="KML"))
|
52 |
-
elif gefile.endswith(".kmz"):
|
53 |
-
gdf = desctogdf(readkmz(gefile))
|
54 |
-
else:
|
55 |
-
raise ValueError("File must end with .kml or .kmz")
|
56 |
-
return gdf
|
57 |
-
|
58 |
-
|
59 |
-
def simpledata_fromcode(kmlcode: str) -> pd.DataFrame:
|
60 |
-
"""Return DataFrame extracted from KML code
|
61 |
-
parameter kmlcode (str): kml source code
|
62 |
-
Uses simpledata tags, NOT embedded tables in feature descriptions
|
63 |
-
"""
|
64 |
-
# get the KML source code as a BeautifulSoup object
|
65 |
-
soup = bs4.BeautifulSoup(kmlcode, "html.parser")
|
66 |
-
# find all rows (schemadata tags) in the soup
|
67 |
-
rowtags = soup.find_all("schemadata")
|
68 |
-
# generator expression yielding a {name: value} dict for each row
|
69 |
-
rowdicts = (
|
70 |
-
{
|
71 |
-
**{"Placemark_name": row.parent.parent.find("name").text},
|
72 |
-
**{field.get("name"): field.text for field in row.find_all("simpledata")},
|
73 |
-
}
|
74 |
-
for row in rowtags
|
75 |
-
)
|
76 |
-
# return pd.DataFrame from row dict generator
|
77 |
-
return pd.DataFrame(rowdicts)
|
78 |
-
|
79 |
-
|
80 |
-
def kmlcode_fromfile(gefile: str) -> str:
|
81 |
-
"""Return kml source code (str) extracted from Google Earth File
|
82 |
-
parameter gefile (str): absolute or relative path to Google Earth file
|
83 |
-
(kmz or kml)
|
84 |
-
Uses simpledata tags, NOT embedded tables in feature descriptions
|
85 |
-
"""
|
86 |
-
fileextension = gefile.lower().split(".")[-1]
|
87 |
-
if fileextension == "kml":
|
88 |
-
with open(gefile, "r") as kml:
|
89 |
-
kmlsrc = kml.read()
|
90 |
-
elif fileextension == "kmz":
|
91 |
-
with zipfile.ZipFile(gefile) as kmz:
|
92 |
-
# there should only be one kml file and it should be named doc.kml
|
93 |
-
# we won't make that assumption
|
94 |
-
kmls = [f for f in kmz.namelist() if f.lower().endswith(".kml")]
|
95 |
-
if len(kmls) != 1:
|
96 |
-
raise IndexError(
|
97 |
-
"kmz contains more than one kml. Extract or convert to multiple kmls.",
|
98 |
-
)
|
99 |
-
with kmz.open(kmls[0]) as kml:
|
100 |
-
# .decode() because zipfile.ZipFile.open(name).read() -> bytes
|
101 |
-
kmlsrc = kml.read().decode()
|
102 |
-
else:
|
103 |
-
raise ValueError("parameter gefile must end with .kml or .kmz")
|
104 |
-
return kmlsrc
|
105 |
-
|
106 |
-
|
107 |
-
def simpledata_fromfile(gefile: str) -> gpd.GeoDataFrame:
|
108 |
-
"""Return DataFrame extracted from Google Earth File
|
109 |
-
parameter gefile (str): absolute or relative path to Google Earth file
|
110 |
-
(kmz or kml)
|
111 |
-
Uses simpledata tags, NOT embedded tables in feature descriptions
|
112 |
-
"""
|
113 |
-
df = simpledata_fromcode(kmlcode_fromfile(gefile))
|
114 |
-
if gefile.endswith(".kmz"):
|
115 |
-
gefile_gdf = readkmz(gefile)
|
116 |
-
else:
|
117 |
-
gefile_gdf = gpd.read_file(gefile, driver="KML")
|
118 |
-
gdf = gpd.GeoDataFrame(df, geometry=gefile_gdf["geometry"], crs=gefile_gdf.crs)
|
119 |
-
return gdf
|
120 |
-
|
121 |
-
|
122 |
-
def readge(gefile: str) -> pd.DataFrame:
|
123 |
-
"""Extract data from Google Earth file & save as zip
|
124 |
-
parameter gefile (str): absolute or relative path to Google Earth file
|
125 |
-
parameter zipfile (str): absolute or relative path to output zip file
|
126 |
-
Will read simpledata tags OR embedded tables in feature descriptions
|
127 |
-
"""
|
128 |
-
code = kmlcode_fromfile(gefile)
|
129 |
-
func1, func2 = ge_togdf, simpledata_fromfile
|
130 |
-
if any((tag in code.lower() for tag in ("<simpledata", "<simplefield"))):
|
131 |
-
func1, func2 = func2, func1
|
132 |
-
try:
|
133 |
-
df = func1(gefile)
|
134 |
-
except (
|
135 |
-
pd.errors.ParserError,
|
136 |
-
lxml.etree.ParserError,
|
137 |
-
lxml.etree.XMLSyntaxError,
|
138 |
-
ValueError,
|
139 |
-
):
|
140 |
-
df = func2(gefile)
|
141 |
-
return df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
geospatial-data-converter/kml_tricks_refactor.py
DELETED
@@ -1,171 +0,0 @@
|
|
1 |
-
import zipfile
|
2 |
-
from io import StringIO
|
3 |
-
|
4 |
-
import bs4
|
5 |
-
import fiona
|
6 |
-
import geopandas as gpd
|
7 |
-
import lxml # nosec
|
8 |
-
import pandas as pd
|
9 |
-
|
10 |
-
fiona.drvsupport.supported_drivers["KML"] = "rw"
|
11 |
-
|
12 |
-
|
13 |
-
def parse_descriptions_to_geodf(geodf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
|
14 |
-
"""Parses Descriptions from Google Earth file to a GeoDataFrame object"""
|
15 |
-
|
16 |
-
dataframes = []
|
17 |
-
|
18 |
-
# Iterate over descriptions and extract data
|
19 |
-
for desc in geodf["Description"]:
|
20 |
-
desc_as_io = StringIO(desc)
|
21 |
-
|
22 |
-
# Try to read the description into a DataFrame
|
23 |
-
parsed_html = pd.read_html(desc_as_io)
|
24 |
-
try:
|
25 |
-
temp_df = parsed_html[1].T
|
26 |
-
except IndexError:
|
27 |
-
temp_df = parsed_html[0].T
|
28 |
-
|
29 |
-
# Set DataFrame header and remove the first row
|
30 |
-
temp_df.columns = temp_df.iloc[0]
|
31 |
-
temp_df = temp_df.iloc[1:]
|
32 |
-
|
33 |
-
dataframes.append(temp_df)
|
34 |
-
|
35 |
-
# Combine all DataFrames
|
36 |
-
combined_df = pd.concat(dataframes, ignore_index=True)
|
37 |
-
|
38 |
-
# Add geometry data
|
39 |
-
combined_df["geometry"] = geodf["geometry"]
|
40 |
-
|
41 |
-
# Create a GeoDataFrame with the combined data and original CRS
|
42 |
-
result_geodf = gpd.GeoDataFrame(combined_df, crs=geodf.crs)
|
43 |
-
|
44 |
-
return result_geodf
|
45 |
-
|
46 |
-
|
47 |
-
def load_kmz_as_geodf(file_path: str) -> gpd.GeoDataFrame:
|
48 |
-
"""Loads a KMZ file into a GeoPandas DataFrame, assuming the KMZ contains one KML file"""
|
49 |
-
|
50 |
-
# Open the KMZ file
|
51 |
-
with zipfile.ZipFile(file_path, "r") as kmz:
|
52 |
-
# List all KML files in the KMZ
|
53 |
-
kml_files = [file for file in kmz.namelist() if file.endswith(".kml")]
|
54 |
-
|
55 |
-
# Ensure there's only one KML file in the KMZ
|
56 |
-
if len(kml_files) != 1:
|
57 |
-
raise IndexError(
|
58 |
-
"KMZ contains more than one KML. Please extract or convert to multiple KMLs.",
|
59 |
-
)
|
60 |
-
|
61 |
-
# Read the KML file into a GeoDataFrame
|
62 |
-
geodf = gpd.read_file(f"zip://{file_path}/{kml_files[0]}", driver="KML")
|
63 |
-
|
64 |
-
return geodf
|
65 |
-
|
66 |
-
|
67 |
-
def load_ge_file(file_path: str) -> gpd.GeoDataFrame:
|
68 |
-
"""Loads a KML or KMZ file and parses its descriptions into a GeoDataFrame"""
|
69 |
-
|
70 |
-
if file_path.endswith(".kml"):
|
71 |
-
return parse_descriptions_to_geodf(gpd.read_file(file_path, driver="KML"))
|
72 |
-
elif file_path.endswith(".kmz"):
|
73 |
-
return parse_descriptions_to_geodf(load_kmz_as_geodf(file_path))
|
74 |
-
raise ValueError("The file must have a .kml or .kmz extension.")
|
75 |
-
|
76 |
-
|
77 |
-
def extract_data_from_kml_code(kml_code: str) -> pd.DataFrame:
|
78 |
-
"""Extracts data from KML code into a DataFrame using SimpleData tags, excluding embedded tables in feature descriptions"""
|
79 |
-
|
80 |
-
# Parse the KML source code
|
81 |
-
soup = bs4.BeautifulSoup(kml_code, "html.parser")
|
82 |
-
|
83 |
-
# Find all SchemaData tags (representing rows)
|
84 |
-
schema_data_tags = soup.find_all("schemadata")
|
85 |
-
|
86 |
-
# Create a generator that yields a dictionary for each row, containing the Placemark name and each SimpleData field
|
87 |
-
row_dicts = (
|
88 |
-
{
|
89 |
-
"Placemark_name": tag.parent.parent.find("name").text,
|
90 |
-
**{field.get("name"): field.text for field in tag.find_all("simpledata")},
|
91 |
-
}
|
92 |
-
for tag in schema_data_tags
|
93 |
-
)
|
94 |
-
|
95 |
-
# Convert the row dictionaries into a DataFrame
|
96 |
-
df = pd.DataFrame(row_dicts)
|
97 |
-
|
98 |
-
return df
|
99 |
-
|
100 |
-
|
101 |
-
def extract_kml_code_from_file(file_path: str) -> str:
|
102 |
-
"""Extracts KML source code from a Google Earth file (KML or KMZ)"""
|
103 |
-
|
104 |
-
file_extension = file_path.lower().split(".")[-1]
|
105 |
-
|
106 |
-
if file_extension == "kml":
|
107 |
-
with open(file_path, "r") as kml_file:
|
108 |
-
kml_code = kml_file.read()
|
109 |
-
elif file_extension == "kmz":
|
110 |
-
with zipfile.ZipFile(file_path) as kmz_file:
|
111 |
-
# Find all KML files in the KMZ
|
112 |
-
kml_files = [
|
113 |
-
file for file in kmz_file.namelist() if file.lower().endswith(".kml")
|
114 |
-
]
|
115 |
-
|
116 |
-
if len(kml_files) != 1:
|
117 |
-
raise IndexError(
|
118 |
-
"KMZ file contains more than one KML. Please extract or convert to multiple KMLs.",
|
119 |
-
)
|
120 |
-
|
121 |
-
with kmz_file.open(kml_files[0]) as kml_file:
|
122 |
-
# Decode the KML file's content from bytes to string
|
123 |
-
kml_code = kml_file.read().decode()
|
124 |
-
else:
|
125 |
-
raise ValueError("The input file must have a .kml or .kmz extension.")
|
126 |
-
|
127 |
-
return kml_code
|
128 |
-
|
129 |
-
|
130 |
-
def extract_data_from_ge_file(file_path: str) -> gpd.GeoDataFrame:
|
131 |
-
"""Extracts data from a Google Earth file (KML or KMZ) into a GeoDataFrame using SimpleData tags, excluding embedded tables in feature descriptions"""
|
132 |
-
|
133 |
-
data_df = extract_data_from_kml_code(extract_kml_code_from_file(file_path))
|
134 |
-
|
135 |
-
if file_path.endswith(".kmz"):
|
136 |
-
ge_file_gdf = load_kmz_as_geodf(file_path)
|
137 |
-
else:
|
138 |
-
ge_file_gdf = gpd.read_file(file_path, driver="KML")
|
139 |
-
|
140 |
-
geo_df = gpd.GeoDataFrame(
|
141 |
-
data_df,
|
142 |
-
geometry=ge_file_gdf["geometry"],
|
143 |
-
crs=ge_file_gdf.crs,
|
144 |
-
)
|
145 |
-
|
146 |
-
return geo_df
|
147 |
-
|
148 |
-
|
149 |
-
def load_ge_data(file_path: str) -> pd.DataFrame:
|
150 |
-
"""Extracts data from a Google Earth file (KML or KMZ) and handles errors due to parsing issues"""
|
151 |
-
|
152 |
-
kml_code = extract_kml_code_from_file(file_path)
|
153 |
-
|
154 |
-
# Choose the extraction method based on the presence of SimpleData or SimpleField tags in the KML code
|
155 |
-
primary_func, fallback_func = (
|
156 |
-
(extract_data_from_ge_file, load_ge_file)
|
157 |
-
if any(tag in kml_code.lower() for tag in ("<simpledata", "<simplefield"))
|
158 |
-
else (load_ge_file, extract_data_from_ge_file)
|
159 |
-
)
|
160 |
-
|
161 |
-
try:
|
162 |
-
data_df = primary_func(file_path)
|
163 |
-
except (
|
164 |
-
pd.errors.ParserError,
|
165 |
-
lxml.etree.ParserError,
|
166 |
-
lxml.etree.XMLSyntaxError,
|
167 |
-
ValueError,
|
168 |
-
):
|
169 |
-
data_df = fallback_func(file_path)
|
170 |
-
|
171 |
-
return data_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
geospatial-data-converter/utils.py
CHANGED
@@ -6,9 +6,7 @@ from typing import BinaryIO
|
|
6 |
|
7 |
import geopandas as gpd
|
8 |
|
9 |
-
|
10 |
-
# from kml_tricks_before import readge as read_ge_file
|
11 |
-
from kml_tricks_refactor import load_ge_data as read_ge_file
|
12 |
|
13 |
output_format_dict = {
|
14 |
"ESRI Shapefile": ("shp", "zip", "application/zip"), # must be zipped
|
@@ -39,7 +37,7 @@ def read_file(file: BinaryIO, *args, **kwargs) -> gpd.GeoDataFrame:
|
|
39 |
tmp_file_path = os.path.join(tmp_dir, file.name)
|
40 |
with open(tmp_file_path, "wb") as tmp_file:
|
41 |
tmp_file.write(file.read())
|
42 |
-
return
|
43 |
return gpd.read_file(file, *args, engine="pyogrio", **kwargs)
|
44 |
|
45 |
|
|
|
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
|
|
|
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 |
|