-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayer.py
More file actions
542 lines (441 loc) · 17.9 KB
/
Copy pathlayer.py
File metadata and controls
542 lines (441 loc) · 17.9 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import argparse
import csv
import json
import os
import pathlib
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from zipfile import BadZipfile, ZipFile
import requests
from fastkml import kml
from fastkml.containers import Folder
from fastkml.features import Placemark
from pygeoif import MultiLineString
from pygeoif.geometry import Point
import sidc
DATA_REPO_API_URL = "https://api.github.com/repos/owlmaps/UAControlMapBackups/contents/"
class MapData:
"""MapData"""
def __init__(self):
self.data = {
"timeline": {},
"unit_map": {},
"fortifications": [],
"dragon_teeth": [],
}
self.unit_count = {}
self.wanted_size = 0
self.geolocations = {}
self.base_date_key = ""
self.dates = []
self.unit_check = {}
self.session = requests.Session()
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0",
"Accept-Encoding": "*",
"Connection": "keep-alive",
}
def _request(self, url, content="raw"):
is_success = False
for _ in range(5):
try:
r = self.session.get(url, timeout=20)
r.raise_for_status()
is_success = True
break
except requests.exceptions.Timeout:
print("The request timed out")
continue
except requests.exceptions.RequestException as e:
print("An error occurred:")
print(e.args[0])
continue
if not is_success:
return None
if content == "json":
return r.json()
if content == "text":
return r.text
return r.content
def add_unit_to_map(self, unit):
# generate a new key and add unit to map
# and update unit_names check list
new_unit_key = len(self.data["unit_map"].keys()) + 1
self.data["unit_map"][new_unit_key] = {"n": unit["n"], "s": unit["s"]}
# update the unit check dict
self.unit_check[unit["n"]] = new_unit_key
# pylint: disable-msg=too-many-locals
def get_units_and_count(self, kml_root):
data = {
"units": {"ru": [], "ua": []},
"count": {"ru": 0, "ua": 0},
}
ru_unit_folder_keys = ["Russian Unit Positions"]
ua_unit_folder_keys = ["Ukrainian Unit Positions"]
unit_folder = {"ru": [], "ua": []}
for feature in kml_root.features:
if isinstance(feature, Folder):
if feature.name in ru_unit_folder_keys:
unit_folder["ru"].append(feature)
if feature.name in ua_unit_folder_keys:
unit_folder["ua"].append(feature)
for side, folders in unit_folder.items():
# print(side)
for folder in folders:
# print(folder.name)
data["count"][side] += len(list(folder.features))
for unit in folder.features:
# print(f'{unit.name} -> {type(unit)} -> {type(unit.geometry)}')
# ignore all units that are not placemarks
# or where their geometry is not a point
if not isinstance(unit, Placemark):
continue
if not isinstance(unit.geometry, Point):
continue
# print(f'{unit.name} -> {type(unit)}')
if unit.name not in self.unit_check:
unit_map_data = {"n": unit.name, "s": side}
self.add_unit_to_map(unit_map_data)
unit_id = self.unit_check[unit.name]
lon = unit.geometry.coords[0][0] # type: ignore
lat = unit.geometry.coords[0][1] # type: ignore
unit_data = [unit_id, [lon, lat]]
data["units"][side].append(unit_data)
return data
def get_fortifications(self, kml_root):
# print('get_fortifications()')
areas_key = "Important Areas"
areas = None
for feature in kml_root.features:
if isinstance(feature, Folder):
if feature.name == areas_key:
areas = feature
if areas is None:
print("no areas folder")
return
fortifications = []
dragonteeth = []
for feature in areas.features:
if isinstance(feature, Placemark):
if (feature.name and feature.name.startswith("Trenches")) or (
feature.name and feature.name.startswith("Fortifications")
):
fortifications.append(feature)
if feature.name and feature.name.startswith("Dragon"):
dragonteeth.append(feature)
for fortification in fortifications:
if isinstance(fortification.geometry, MultiLineString):
for geom in fortification.geometry.geoms:
coords = []
for c in geom.coords: # type: ignore
coords.append([c[1], c[0]])
self.data["fortifications"].append(coords)
for dgt in dragonteeth:
if isinstance(dgt.geometry, MultiLineString):
for geom in dgt.geometry.geoms:
coords = []
for c in geom.coords: # type: ignore
coords.append([c[1], c[0]])
self.data["dragon_teeth"].append(coords)
def get_frontline(self, kml_root):
data = [] # list of coordinates
frontline_key = "Frontline"
frontline_folder = None
# frontline folder
for feature in kml_root.features:
if isinstance(feature, Folder):
if feature.name == frontline_key:
frontline_folder = feature
# frotline data
if frontline_folder is not None:
for feature in frontline_folder.features:
if feature.name == frontline_key:
if isinstance(feature, Placemark):
coords = feature.geometry.coords # type: ignore
for c in coords:
data.append([c[1], c[0]])
return data
def process_kmz(self, item):
# init data set
data = {
"date_key": item["real_data_date"],
"unit_count": {"ru": 0, "ua": 0},
"units": {"ru": [], "ua": []},
"frontline": [],
}
# request remote file
file_name = f'./tmp/{item["name"]}'
content = self._request(item["url"])
# some checks
if content is None:
data["bad_data"] = True
return data
# write kmz file to tmp dir
with open(file_name, mode="wb") as f:
f.write(content) # type: ignore
# unzip the kmz and read the doc.kml file
try:
with ZipFile(file_name) as zf:
# open doc
with zf.open("doc.kml") as f:
doc = f.read()
except BadZipfile:
print("bad zipfile")
# remove tmp file
if os.path.exists(file_name):
os.remove(file_name)
data["bad_data"] = True
return data
# parse kml
k = kml.KML.from_string(doc) # type: ignore
# get root
kml_doc = list(k.features)
kml_root = kml_doc[0]
# get units & count
unit_data = self.get_units_and_count(kml_root)
# print(unit_data)
data["unit_count"] = unit_data["count"]
data["units"] = unit_data["units"]
# get frontline data
frontline_data = self.get_frontline(kml_root)
data["frontline"] = frontline_data
# if latest dataset, get all:
# + fortifications
if item["is_latest"]:
self.base_date_key = item["real_data_date"]
self.get_fortifications(kml_root)
# remove tmp file
if os.path.exists(file_name):
os.remove(file_name)
# fnally, return processed kmz data
return data
def get_kmz_list(self):
# get json file listing
file_list_json = self._request(DATA_REPO_API_URL, "json")
# sub method to filter all kmz files
def filter_kmz(item):
if (
item["type"] == "file"
and ".kmz" in item["path"]
and not "latest.kmz" in item["path"]
):
return True
return False
# apply filter kmz method
kmz_list = list(filter(filter_kmz, file_list_json)) # type: ignore
# sub method to reoganize the data object
def prepare_data(item):
date_string = item["name"].split("_")[0]
return {
"file_date_string": date_string,
"real_data_date": self.substract_day(date_string, out_format="%Y%m%d"),
"name": item["name"],
"url": item["download_url"],
"is_latest": False,
}
# apply prepare data method
data_list = list(map(prepare_data, kmz_list))
# return final data
return data_list
def substract_day(self, date_key, in_format="%y%m%d", out_format="%y%m%d"):
delta = timedelta(days=1) # 1 day timedelta
curdate = datetime.strptime(date_key, in_format)
fixed_date = curdate - delta
fixed_date_key = fixed_date.strftime(out_format)
return fixed_date_key
def generate_date_range_list(self, data_list):
# extract the real data dates into a list
dates_list = list(map(lambda x: x["real_data_date"], data_list))
# find min and max date
min_date = min(dates_list)
max_date = max(dates_list)
# format min & max date
start = datetime.strptime(min_date, "%Y%m%d")
end = datetime.strptime(max_date, "%Y%m%d")
# define time delta (1 day)
delta = timedelta(days=1)
# init dates list
dates = []
# build date list with a step of 1 day
while start <= end:
dates.append(start.strftime("%Y%m%d"))
start += delta
# return date range list
return dates
def init_data(self, dates):
# init an empty data set for each date in the full date range
for date_str in dates:
self.data["timeline"][date_str] = {
"unit_count": {"ru": 0, "ua": 0},
"units": {"ru": [], "ua": []},
"frontline": [],
}
def write_count_csv(self, dates):
with open("unit_count.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
field = ["date", "ru", "ua"]
writer.writerow(field)
for date_str in dates:
s = date_str.replace("-", "")[2:]
item = self.unit_count[s]
writer.writerow([s, item["ru"], item["ua"]])
def save_data(self):
base_data = {
"date": self.base_date_key,
"unit_map": self.data["unit_map"],
"dates": self.dates,
"fortifications": self.data["fortifications"],
"dragon_teeth": self.data["dragon_teeth"],
}
with open("./data/base.json", "w", encoding="utf-8") as fh:
json.dump(base_data, fh, sort_keys=True, separators=(",", ":"))
for date_key in self.data["timeline"]:
with open(f"./data/{date_key}.json", "w", encoding="utf-8") as fh:
json.dump(
self.data["timeline"][date_key],
fh,
sort_keys=True,
separators=(",", ":"),
)
def update(self):
print("UPDATE DATA")
self.create_tmp_dir()
# read the kmz backup repository
data_list = self.get_kmz_list()
# generate a full date range list, starting from the earliest kmz date
dates = self.generate_date_range_list(data_list)
self.dates = dates
# get local data files
files = [f.stem for f in pathlib.Path("./data").iterdir() if f.is_file()]
if "base" in files:
files.remove("base") # remove 'base' from list
# create a diff to find all missing data
s = set(files)
diff = [x for x in dates if x not in s]
print(diff)
if len(diff) == 0:
print("nothing to update")
return
# so we have missing data
# add latest date to the diff list
diff.append(dates[-1])
print(diff)
# load old base data
with open("./data/base.json", encoding="utf-8") as fh:
file_contents = fh.read()
base_data = json.loads(file_contents)
# init some data with the old base data
self.base_date_key = base_data["date"]
# self.data['fortifications'] = base_data['fortifications']
# self.data['dragon_teeth'] = base_data['dragon_teeth']
# self.data['styles'] = base_data['styles']
self.data["unit_map"] = base_data["unit_map"]
# keys are strings (from json) -> convert to int
self.data["unit_map"] = {int(k): v for k, v in self.data["unit_map"].items()}
# create unit check dict
for k, v in self.data["unit_map"].items():
self.unit_check[v["n"]] = k
# based on the diff, prepare the wanted data
# which is just a list of kmz to process
wanted_data = []
for x in data_list:
if x["real_data_date"] in diff:
wanted_data.append(x)
# if we process newer data, than we already have,
# set is_latest flag
current_base_data_date = base_data["date"]
new_latest_date = None
for wd in wanted_data:
if current_base_data_date <= wd["real_data_date"]:
new_latest_date = wd["real_data_date"]
if new_latest_date is not None:
print("update latest flag")
for wd in wanted_data:
if new_latest_date == wd["real_data_date"]:
wd["is_latest"] = True
print(wanted_data)
# init data (will be filled later on)
self.init_data(diff)
# threadpool to process the data
with ThreadPoolExecutor(max_workers=5) as executor:
thread = executor.map(self.process_kmz, wanted_data)
for result in thread:
date_key = result["date_key"]
self.data["timeline"][date_key]["unit_count"] = result["unit_count"]
self.data["timeline"][date_key]["units"] = result["units"]
self.data["timeline"][date_key]["frontline"] = result["frontline"]
# update sidc
self.data["unit_map"] = sidc.update(self.data["unit_map"])
# finally, save the data to <date>.json & base.json
self.save_data()
def generate(self):
self.create_tmp_dir()
# read the kmz backup repository
data_list = self.get_kmz_list()
# flag latest item (from which we extract the base data, like frontline ect.)
data_list[-1]["is_latest"] = True
# generate a full date range list, starting from the earliest kmz date
dates = self.generate_date_range_list(data_list)
self.dates = dates
# init data (will be filled later on)
self.init_data(dates)
# define what data we want to process
wanted_data = data_list
# wanted_data = data_list[-2:]
# threadpool to process the data
with ThreadPoolExecutor(max_workers=5) as executor:
thread = executor.map(self.process_kmz, wanted_data)
for result in thread:
date_key = result["date_key"]
self.data["timeline"][date_key]["unit_count"] = result["unit_count"]
self.data["timeline"][date_key]["units"] = result["units"]
self.data["timeline"][date_key]["frontline"] = result["frontline"]
# update sidc
self.data["unit_map"] = sidc.update(self.data["unit_map"])
# finally, save the data to <date>.json & base.json
self.save_data()
def check_sidc(self):
data = {}
try:
with open("./data/base.json", "r", encoding="utf-8") as fh:
data = json.load(fh)
except json.JSONDecodeError as e:
print("Invalid JSON syntax:", e)
sidc.check(data["unit_map"])
def force_sidc(self):
data = {}
try:
with open("./data/base.json", "r", encoding="utf-8") as fh:
data = json.load(fh)
except json.JSONDecodeError as e:
print("Invalid JSON syntax:", e)
if "unit_map" in data:
data["unit_map"] = sidc.update(data["unit_map"])
# safe json file
with open("./data/base.json", "w", encoding="utf-8") as fh:
json.dump(data, fh, sort_keys=True, separators=(",", ":"))
def create_tmp_dir(self):
os.makedirs("./tmp", exist_ok=True)
if __name__ == "__main__":
# args setup
argParser = argparse.ArgumentParser()
grp = argParser.add_mutually_exclusive_group(required=True)
grp.add_argument(
"-g", "--generate", action="store_true", help="generate data from scratch"
)
grp.add_argument("-u", "--update", action="store_true", help="update data")
grp.add_argument("-s", "--sidc", action="store_true", help="check unit 2 sidc")
grp.add_argument("-f", "--force", action="store_true", help="force sidc update")
args = argParser.parse_args()
# INIT MapData CLASS
mapdata = MapData()
# depending on the type of action we
# now run generate or update
if args.generate:
mapdata.generate()
elif args.update:
mapdata.update()
elif args.sidc:
mapdata.check_sidc()
elif args.force:
mapdata.force_sidc()