~phroa/boat-map

boat-map/make-map.py -rw-r--r-- 6.7 KiB
37260409Jack Stratton Show special columns in the schedule 8 months ago
                                                                                
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
import time
from collections import defaultdict

from lxml import html
import requests
import simdjson
from PIL import Image, ImageDraw

# https://geojson.io, draw a rectangle
MAP = [
    [-123.04893493652342, 48.478838892384104],
    [-122.65480041503905, 48.478838892384104],
    [-122.65480041503905, 48.62610126300646],
    [-123.04893493652342, 48.62610126300646],
]

VESSELS = "https://www.wsdot.com/ferries/vesselwatch/Vessels.ashx"
SCHEDULE = "https://www.wsdot.com/ferries/schedule/scheduledetailbyroute.aspx?route=ana-sj"
OVERPASS = "https://overpass-api.de/api/interpreter"

MIN_LON = min(MAP, key=lambda coord: coord[0])[0]
MIN_LAT = min(MAP, key=lambda coord: coord[1])[1]
MAX_LON = max(MAP, key=lambda coord: coord[0])[0]
MAX_LAT = max(MAP, key=lambda coord: coord[1])[1]

LON_RANGE = MAX_LON - MIN_LON
LAT_RANGE = MAX_LAT - MIN_LAT

WIDTH = 648
HEIGHT = 480
MAP_HEIGHT = int(1.5 * WIDTH * LAT_RANGE / LON_RANGE)

SCREEN = Image.new("1", (WIDTH, HEIGHT), color=1)
DRAW = ImageDraw.Draw(SCREEN)
MOVING = Image.open("moving.png")
STOPPED = Image.open("stopped.png")


OVERPASS_QUERY = f"""
[out:json];
(
  way[place=island]({MIN_LAT}, {MIN_LON}, {MAX_LAT}, {MAX_LON});
  rel[place=island]({MIN_LAT}, {MIN_LON}, {MAX_LAT}, {MAX_LON});
);
convert item ::=::,::geom=geom(),_osm_type=type(); // magic
out geom qt;
"""


def latlon_to_xy(lat: float, lon: float) -> (float, float):
    x = WIDTH * (lon - MIN_LON) / LON_RANGE
    y = min(MAP_HEIGHT, MAP_HEIGHT - (MAP_HEIGHT * (lat - MIN_LAT) / LAT_RANGE))
    return x, y


def draw_coastlines(coastlines):
    def linestring(item):
        screen_coords = []
        coords = item["coordinates"]
        for lon, lat in coords:
            screen_coords.append(latlon_to_xy(lat, lon))
        DRAW.line(screen_coords, width=1, joint="curve")

    for sequence in coastlines["elements"]:
        item = sequence["geometry"]
        t = item["type"]
        if t == "LineString":
            linestring(item)
        elif t == "GeometryCollection":
            for i in item["geometries"]:
                linestring(i)
        else:
            raise

    DRAW.rectangle((0, 0, WIDTH - 1, MAP_HEIGHT))


def paste(src: Image, dest_x, dest_y):
    center_x = src.width / 2
    center_y = src.height / 2

    for x in range(src.width):
        for y in range(src.height):
            alpha = src.getpixel((x, y))[-1]
            # PIL alpha compositing cannot be used directly since the images aren't both RGBA.
            # this copies a pixel value to the screen only if the alpha channel in the original is nontransparent.
            if alpha > 0:
                DRAW.point((dest_x + x - center_x, dest_y + y - center_y))


def draw_boats():
    boats = requests.get(VESSELS).json()["vessellist"]
    boats = filter(lambda boat: boat["route"] == "ANA-SJ", boats)
    boats = filter(lambda boat: boat["aterm_id"] != "", boats)
    for boat in boats:
        boat_lat = boat["lat"]
        boat_lon = boat["lon"]

        x, y = latlon_to_xy(boat_lat, boat_lon)

        label = f"{boat['name'][:3].upper()} {boat['pos']}"
        if boat["eta"] == "Calculating":
            label += f" {boat['lastdock'][0]}->{boat['aterm'][0]} departing at {boat['nextdep']}"
            # the frickin image is not centered lol
            paste(STOPPED, x - 2, y)
        else:
            label += f" {boat['lastdock'][0]}->{boat['aterm'][0]} ETA {boat['eta']}"
            paste(MOVING.rotate(-boat["head"]), x, y)
        DRAW.point((x, y))
        DRAW.text((x, y), label, anchor="mm")


def draw_schedule():
    response = requests.get(SCHEDULE)
    if not response.ok:
        return

    root = html.fromstring(response.content)
    schedule_lines = defaultdict(list)
    current_label = None
    table = root.xpath('//*[@class="schedgridbyroute"]')[0]

    current_time = time.localtime()

    for row in table.xpath('tr'):
        header = row.xpath('td/h4[@id="sailingDescription"]/text()')
        # Section header
        if len(header) > 0:
            current_label = header[0]
            continue

        # Terminal names
        headers = row.xpath('td/h4[@id="sailingTerminal"]')
        if len(headers) > 0:
            continue

        # Filter out non-body rows
        if 'HighlightOnHover' not in row.attrib['class']:
            continue

        line = []
        times = []
        for col in row.xpath('td'):
            cell_contents = ''.join(col.xpath('descendant::*/text()')).replace('\xa0', '').strip()
            # Track special cases in the schedule except for the "Indicates an arrival time" note
            extra = len(col.xpath('div/div/img[@title!="Indicates an arrival time"]')) > 0
            pm = len(col.xpath('div/div[@class="pm"]')) > 0 and ':' in cell_contents

            if '-' in cell_contents:
                cell_contents = ''
            elif pm:
                hour, minute = map(int, cell_contents.split(':'))
                times.append(60 * ((hour if hour != 12 else 0) + 12) + minute)
            elif ':' in cell_contents:
                hour, minute = map(int, cell_contents.split(':'))
                times.append(60 * hour + minute)
            elif 'Noon' in cell_contents:
                times.append(60 * 12)
            elif 'Midnight' in cell_contents:
                times.append(60 * 24)

            if extra:
                cell_contents += '*'
            elif pm:
                cell_contents += 'p'
            line.append(cell_contents)
        if (current_time.tm_hour + 1) * 60 + current_time.tm_min < max(times):
            schedule_lines[current_label].append('{}  {:6} {:6} {:6} {:6} {:6}'.format(*line))

    if 'Daily' in ''.join(schedule_lines.keys()):
        left_col = 'Leave Westbound (Daily)'
        right_col = 'Leave Eastbound (Daily)'
    else:
        mf_or_satsun = 'Saturday and Sunday' if time.localtime().tm_wday > 4 else 'Monday through Friday'
        left_col = f'Leave Westbound ({mf_or_satsun})'
        right_col = f'Leave Eastbound ({mf_or_satsun})'

    left_lines = '   Anac.  Lopez  Shaw   Orcas  Friday\n' + '\n'.join(schedule_lines[left_col])
    right_lines = '   Friday Orcas  Shaw   Lopez  Anac.\n' + '\n'.join(schedule_lines[right_col])

    DRAW.multiline_text((2, MAP_HEIGHT + 2), left_lines)
    DRAW.multiline_text((WIDTH / 2 + 2, MAP_HEIGHT + 2), right_lines)

def main():
    filename = f"coastlines-{hash((MIN_LAT, MIN_LON, MAX_LAT, MAX_LON))}.json"
    try:
        with open(filename) as f:
            coastlines = simdjson.load(f)
    except FileNotFoundError:
        print("Downloading coastlines")
        coastlines = requests.get(OVERPASS, {"data": OVERPASS_QUERY}).json()
        with open(filename, "w") as f:
            simdjson.dump(coastlines, f)

    draw_coastlines(coastlines)
    draw_boats()
    draw_schedule()

    SCREEN.save("map.bmp", "BMP")


if __name__ == "__main__":
    main()