|
| 1 | +# Surveys every bus on the road right now and checks it against the app's |
| 2 | +# fleet table (app/src/main/assets/fleet.tsv), so the "what bus is coming" |
| 3 | +# lookup can be kept up to date as operators add buses. |
| 4 | +# |
| 5 | +# AT_API_KEY=... python tools/fleet_survey.py |
| 6 | +# |
| 7 | +# Prints the label formats in use, a sample of vehicles per operator prefix, |
| 8 | +# and every label the fleet table doesn't recognise, grouped into ranges. |
| 9 | +import collections, json, os, re, sys, urllib.request |
| 10 | + |
| 11 | +HERE = os.path.dirname(os.path.abspath(__file__)) |
| 12 | +FLEET = os.path.join(HERE, "..", "app", "src", "main", "assets", "fleet.tsv") |
| 13 | +KEY = os.environ.get("AT_API_KEY", "") |
| 14 | + |
| 15 | + |
| 16 | +def api(path): |
| 17 | + req = urllib.request.Request("https://api.at.govt.nz" + path, |
| 18 | + headers={"Ocp-Apim-Subscription-Key": KEY, |
| 19 | + "Accept": "application/json"}) |
| 20 | + return json.load(urllib.request.urlopen(req, timeout=60)) |
| 21 | + |
| 22 | + |
| 23 | +def load_fleet(): |
| 24 | + """Rows of (prefixes, first, last, operator, model, kind).""" |
| 25 | + rows = [] |
| 26 | + if not os.path.exists(FLEET): |
| 27 | + return rows |
| 28 | + for line in open(FLEET, encoding="utf-8"): |
| 29 | + line = line.rstrip("\n") |
| 30 | + if not line or line.startswith("#"): |
| 31 | + continue |
| 32 | + p = line.split("\t") |
| 33 | + rows.append((p[0].split(","), int(p[1]), int(p[2]), p[3], p[4], p[5] if len(p) > 5 else "")) |
| 34 | + return rows |
| 35 | + |
| 36 | + |
| 37 | +def split_label(label): |
| 38 | + """'TR3881' -> ('TR', 3881); 'NB 3563' -> ('NB', 3563).""" |
| 39 | + m = re.match(r"^\s*([A-Za-z]*)\s*0*(\d+)", label or "") |
| 40 | + return (m.group(1).upper(), int(m.group(2))) if m else ("", None) |
| 41 | + |
| 42 | + |
| 43 | +def lookup(fleet, prefix, num): |
| 44 | + for pre, a, b, op, model, kind in fleet: |
| 45 | + if (prefix in pre or "*" in pre) and a <= num <= b: |
| 46 | + return op, model |
| 47 | + return None |
| 48 | + |
| 49 | + |
| 50 | +def ranges(nums): |
| 51 | + nums = sorted(set(nums)) |
| 52 | + out, start, prev = [], None, None |
| 53 | + for n in nums: |
| 54 | + if start is None: |
| 55 | + start = prev = n |
| 56 | + elif n <= prev + 3: |
| 57 | + prev = n |
| 58 | + else: |
| 59 | + out.append((start, prev)); start = prev = n |
| 60 | + if start is not None: |
| 61 | + out.append((start, prev)) |
| 62 | + return ", ".join(str(a) if a == b else "%d-%d" % (a, b) for a, b in out) |
| 63 | + |
| 64 | + |
| 65 | +def main(): |
| 66 | + if not KEY: |
| 67 | + print("No AT_API_KEY, skipping the survey") |
| 68 | + return |
| 69 | + fleet = load_fleet() |
| 70 | + j = api("/realtime/legacy/vehiclelocations") |
| 71 | + ents = j.get("response", {}).get("entity", []) |
| 72 | + by_prefix = collections.defaultdict(list) |
| 73 | + keys = collections.Counter() |
| 74 | + for e in ents: |
| 75 | + v = e.get("vehicle") or {} |
| 76 | + info = v.get("vehicle") or {} |
| 77 | + keys.update(info.keys()) |
| 78 | + vid = str(info.get("id", "")) |
| 79 | + if vid.startswith("59"): # trains |
| 80 | + continue |
| 81 | + label = re.sub(r"\s+", " ", str(info.get("label", ""))).strip() |
| 82 | + route = ((v.get("trip") or {}).get("route_id") or "").split("-")[0] |
| 83 | + by_prefix[split_label(label)[0]].append((label, vid, info.get("license_plate", ""), route)) |
| 84 | + |
| 85 | + print("vehicles: %d, vehicle descriptor keys: %s" % (len(ents), dict(keys))) |
| 86 | + if "--raw" in sys.argv: |
| 87 | + buses = [e for e in ents if not str(((e.get("vehicle") or {}).get("vehicle") or {}).get("id", "")).startswith("59")] |
| 88 | + for e in buses[:3]: |
| 89 | + print(json.dumps(e)) |
| 90 | + print() |
| 91 | + print("%-6s %5s %-44s %s" % ("prefix", "count", "fleet numbers", "sample (label | id | plate | route)")) |
| 92 | + for pre, vs in sorted(by_prefix.items(), key=lambda kv: -len(kv[1])): |
| 93 | + nums = [split_label(l)[1] for l, _, _, _ in vs if split_label(l)[1] is not None] |
| 94 | + sample = "; ".join("%s | %s | %s | %s" % s for s in vs[:4]) |
| 95 | + print("%-6s %5d %-44s %s" % (pre or "-", len(vs), ranges(nums)[:44], sample)) |
| 96 | + |
| 97 | + print() |
| 98 | + unknown = collections.defaultdict(list) |
| 99 | + known = 0 |
| 100 | + for pre, vs in by_prefix.items(): |
| 101 | + for label, _, _, route in vs: |
| 102 | + _, n = split_label(label) |
| 103 | + if n is not None and lookup(fleet, pre, n): |
| 104 | + known += 1 |
| 105 | + else: |
| 106 | + unknown[pre].append((n, route)) |
| 107 | + total = sum(len(v) for v in by_prefix.values()) |
| 108 | + print("fleet table recognises %d of %d buses" % (known, total)) |
| 109 | + for pre, vs in sorted(unknown.items()): |
| 110 | + nums = [n for n, _ in vs if n is not None] |
| 111 | + routes = collections.Counter(r for _, r in vs).most_common(8) |
| 112 | + print(" unknown %-4s %s (routes: %s)" % (pre or "-", ranges(nums), ", ".join(r for r, _ in routes))) |
| 113 | + |
| 114 | + |
| 115 | +if __name__ == "__main__": |
| 116 | + main() |
0 commit comments