trackers/generateplaces.py

121 lines
5.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import orgparse,os,re,sys,variables
import time
from datetime import datetime
from geopy.geocoders import Nominatim
try:
if sys.argv[1] == "local":
local = True
else:
local = False
except:
local = False
if variables.trackplaces == True:
thisyear = datetime.now().strftime("%Y")
year = variables.placestartyear
concernedfiles = []
geo = Nominatim(user_agent="python3")
while year < int(thisyear) + 1:
month = 0
while month < 13:
if month < 10:
strmonth = "0" + str(month)
else:
strmonth = str(month)
recdir = str(year) + "/" + strmonth + "/"
fullpath = variables.orgpath + recdir
if os.path.exists(fullpath):
for file in sorted(os.listdir(fullpath)):
filename = fullpath + str(file)
if filename.endswith(".org"):
concernedfiles.append(filename)
month = month + 1
year = year + 1
places = []
placenames = []
for file in concernedfiles:
filedate = file[-14:-4]
dateobj = datetime.strptime(filedate,"%Y-%m-%d")
parsefile = orgparse.load(file)
try:
for node in parsefile.children:
if node.heading == "places":
for action in node.children:
if action.heading == "visited":
for place in action.children:
placename = re.sub(" <.*>","",re.sub("<.*> ","",place.heading))
if placename not in placenames:
status = "new"
placenames.append(placename)
else:
status = "existing"
if "<" in place.heading:
dates = re.sub(" [A-Z][a-z][a-z]","",re.sub("--"," to ",re.sub(">","",re.sub("<","",(re.findall("\<.*\>",place.heading)[0])))))
else:
dates = filedate
if status == "new":
try:
lookup = placename + ", " + variables.disambig[placename]
except:
lookup = placename
thedict = {"name":placename,"dates":[dates],"lookup":lookup}
places.append(thedict)
else:
twodict = {"name":placename,"dates":[dates]}
for origplace in places:
if twodict["name"] == origplace["name"]:
origplace["dates"].extend(twodict["dates"])
except:
pass
for place in places:
place["dates"] = list(dict.fromkeys(place["dates"]))
theplaces = sorted(places,key=lambda d: d["name"])
for place in theplaces:
print("Fetching " + place["name"])
place["lat"] = None
while place["lat"] == None:
try:
place["lat"] = geo.geocode(place["lookup"]).latitude
except:
time.sleep(3)
continue
place["long"] = None
while place["long"] == None:
try:
place["long"] = geo.geocode(place["lookup"]).longitude
except:
time.sleep(3)
continue
alllats = []
alllongs = []
for place in theplaces:
if place["lat"] != 0:
alllats.append(place["lat"])
if place["long"] != 0:
alllongs.append(place["long"])
avglat = (max(alllats) + min(alllats))/2
avglong = (max(alllongs) + min(alllongs))/2
writefile = open("placebuild/index.html","w")
writefile.write("<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <base target=\"_top\">\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> \n <title>Map</title>\n <link rel=\"stylesheet\" href=\"")
if local:
writefile.write(variables.domain)
writefile.write(variables.placecss + "\">\n <link rel=\"stylesheet\" href=\"https://unpkg.com/leaflet@1.9.4/dist/leaflet.css\" integrity=\"sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=\" crossorigin=\"\"/>\n <script src=\"https://unpkg.com/leaflet@1.9.4/dist/leaflet.js\" integrity=\"sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=\" crossorigin=\"\"></script>\n <style>\n #map {\n width: 90vw;\n height: 90vh;\n margin: auto;\n }\n </style>\n </head>\n <body>\n <div id=\"map\" style=\"width: 90vw; height: 90vh;\"></div>\n <script>\n const map = L.map('map').fitBounds([[" + str(min(alllats)) + ", " + str(min(alllongs)) + "],[" + str(max(alllats)) + ", " + str(max(alllongs)) + "]]);\n const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {\n attribution: '&copy; <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a>'\n }).addTo(map);\n")
for place in theplaces:
saniname = re.sub(" ","",(re.sub("","",(re.sub("-","",place["name"])))))
writefile.write(" const " + saniname + " = L.marker([" + str(place["lat"]) + ", " + str(place["long"]) + "]).addTo(map).bindTooltip('<h2>" + place["name"] + "</h2><ul>")
for date in place["dates"]:
writefile.write("<li><code>" + date + "</code></li>")
writefile.write("</ul>');\n")
writefile.write(" </script>\n </body>\n</html>")