Spaces:
Running
Running
TransitPulse: planning model running in the browser
Browse files- README.md +16 -3
- data.json +0 -0
- index.html +168 -18
- model.json +0 -0
- predict.js +159 -0
README.md
CHANGED
|
@@ -1,10 +1,23 @@
|
|
| 1 |
---
|
| 2 |
title: TransitPulse
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: blue
|
| 5 |
-
colorTo:
|
| 6 |
sdk: static
|
|
|
|
| 7 |
pinned: false
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: TransitPulse
|
| 3 |
+
emoji: 🚌
|
| 4 |
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
sdk: static
|
| 7 |
+
app_file: index.html
|
| 8 |
pinned: false
|
| 9 |
+
short_description: Hourly bus ridership predictions for 24 NYC bus routes
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# TransitPulse
|
| 13 |
+
|
| 14 |
+
Predict hourly bus ridership for 24 MTA routes in New York (January to September 2025).
|
| 15 |
+
Pick a route, a date and an hour; the page shows the predicted riders and the predicted profile for the whole day.
|
| 16 |
+
|
| 17 |
+
This is a static Space: the Gradient Boosting model runs in your browser. Its 500 trees were exported from
|
| 18 |
+
scikit-learn to `model.json`, and `predict.js` adds them up exactly like scikit-learn; the predictions were
|
| 19 |
+
checked to be identical to the Python model.
|
| 20 |
+
|
| 21 |
+
Model card: https://huggingface.co/ayanjawed/transitpulse-planning-model
|
| 22 |
+
Code: https://github.com/ayanmirza99/ML-Project
|
| 23 |
+
Course project for CT-378 Machine Learning.
|
data.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
index.html
CHANGED
|
@@ -1,19 +1,169 @@
|
|
| 1 |
-
<!
|
| 2 |
-
<html>
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|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
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<title>TransitPulse</title>
|
| 6 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 7 |
+
<style>
|
| 8 |
+
:root { --ink: #1f2933; --muted: #52606d; --line: #d9e2ec; --accent: #d9480f; --bar: #4c72b0; --bg: #ffffff; --panel: #f5f7fa; --error: #b00020; }
|
| 9 |
+
@media (prefers-color-scheme: dark) {
|
| 10 |
+
:root { --ink: #e4e7eb; --muted: #9aa5b1; --line: #3e4c59; --accent: #ff8a4c; --bar: #7da2e0; --bg: #14181d; --panel: #1f262e; --error: #ff6b81; }
|
| 11 |
+
}
|
| 12 |
+
* { box-sizing: border-box; }
|
| 13 |
+
body { font-family: system-ui, -apple-system, "Segoe UI", sans-serif; max-width: 780px; margin: 0 auto; padding: 1.5rem 16px 3rem; color: var(--ink); background: var(--bg); line-height: 1.5; }
|
| 14 |
+
h1 { margin: 0 0 0.2rem; font-size: 1.8rem; }
|
| 15 |
+
.lead { margin: 0 0 1.2rem; color: var(--muted); }
|
| 16 |
+
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 1rem; }
|
| 17 |
+
label { display: block; margin-top: 0.7rem; font-weight: 600; font-size: 0.92rem; }
|
| 18 |
+
input, select, button { font: inherit; }
|
| 19 |
+
input, select { padding: 0.45rem; width: 100%; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); }
|
| 20 |
+
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 0.7rem; }
|
| 21 |
+
.check { display: flex; gap: 0.5rem; align-items: center; font-weight: 400; margin-top: 1rem; }
|
| 22 |
+
.check input { width: auto; }
|
| 23 |
+
button { margin-top: 1rem; padding: 0.6rem 1.4rem; border: 0; border-radius: 6px; background: var(--accent); color: #fff; font-weight: 600; cursor: pointer; }
|
| 24 |
+
button:disabled { opacity: 0.5; cursor: wait; }
|
| 25 |
+
#error { margin-top: 1rem; color: var(--error); font-weight: 600; }
|
| 26 |
+
#result { margin-top: 1.4rem; }
|
| 27 |
+
.big { font-size: 2.4rem; font-weight: 700; line-height: 1.1; }
|
| 28 |
+
.sub { color: var(--muted); }
|
| 29 |
+
canvas { display: block; width: 100%; height: 260px; margin-top: 1rem; }
|
| 30 |
+
footer { margin-top: 2rem; font-size: 0.9rem; color: var(--muted); }
|
| 31 |
+
a { color: var(--accent); }
|
| 32 |
+
</style>
|
| 33 |
+
</head>
|
| 34 |
+
<body>
|
| 35 |
+
<h1>🚌 TransitPulse</h1>
|
| 36 |
+
<p class="lead">Predict hourly bus ridership for one MTA bus route in New York, to help planners decide where buses are needed.</p>
|
| 37 |
+
|
| 38 |
+
<div class="panel">
|
| 39 |
+
<label for="route">Route</label>
|
| 40 |
+
<select id="route" disabled><option>Loading the model…</option></select>
|
| 41 |
+
|
| 42 |
+
<div class="grid">
|
| 43 |
+
<div><label for="date">Date</label><input id="date" type="date"></div>
|
| 44 |
+
<div><label for="hour">Hour (0-23)</label><input id="hour" type="number" min="0" max="23" step="1" value="8"></div>
|
| 45 |
+
</div>
|
| 46 |
+
|
| 47 |
+
<label class="check"><input type="checkbox" id="customWeather"> Enter the weather myself (otherwise the recorded weather for that date is used)</label>
|
| 48 |
+
<div class="grid" id="weatherBox" hidden>
|
| 49 |
+
<div><label for="temperature_2m">Temperature (°C)</label><input id="temperature_2m" type="number" step="0.1" value="15"></div>
|
| 50 |
+
<div><label for="precipitation">Rain (mm/h)</label><input id="precipitation" type="number" step="0.1" value="0"></div>
|
| 51 |
+
<div><label for="snowfall">Snow (cm/h)</label><input id="snowfall" type="number" step="0.1" value="0"></div>
|
| 52 |
+
<div><label for="wind_speed_10m">Wind (km/h)</label><input id="wind_speed_10m" type="number" step="0.1" value="10"></div>
|
| 53 |
+
</div>
|
| 54 |
+
|
| 55 |
+
<button id="go" disabled>Predict</button>
|
| 56 |
+
<div id="error" role="alert"></div>
|
| 57 |
+
</div>
|
| 58 |
+
|
| 59 |
+
<div id="result" hidden>
|
| 60 |
+
<div class="sub" id="resultLabel"></div>
|
| 61 |
+
<div class="big" id="resultValue"></div>
|
| 62 |
+
<canvas id="chart" aria-label="Predicted riders for each hour of the day"></canvas>
|
| 63 |
+
<div class="sub">Predicted riders for every hour of that day; the chosen hour is highlighted.</div>
|
| 64 |
+
</div>
|
| 65 |
+
|
| 66 |
+
<footer>
|
| 67 |
+
<p><strong>Limits:</strong> the model only knows the 24 routes it was trained on and dates from 2025-01-06 to 2025-09-28.
|
| 68 |
+
Typical error on the test period was about 65 riders per route-hour (about 14.5% of an average hour).</p>
|
| 69 |
+
<p>Gradient Boosting model trained on MTA bus ridership, MTA schedules and Open-Meteo weather.
|
| 70 |
+
The same model runs here in your browser: its 500 trees were exported from scikit-learn, and the predictions were checked to match the Python model.</p>
|
| 71 |
+
<p><a href="https://huggingface.co/ayanjawed/transitpulse-planning-model">Model card</a> ·
|
| 72 |
+
<a href="https://github.com/ayanmirza99/ML-Project">Code</a> ·
|
| 73 |
+
<a href="https://ml-project-wuwhhjv3aqsnuxh5x5tdwi.streamlit.app/">Streamlit version</a> ·
|
| 74 |
+
CT-378 Machine Learning course project</p>
|
| 75 |
+
</footer>
|
| 76 |
+
|
| 77 |
+
<script src="predict.js"></script>
|
| 78 |
+
<script>
|
| 79 |
+
const $ = (id) => document.getElementById(id);
|
| 80 |
+
const WEATHER_FIELDS = ["temperature_2m", "precipitation", "snowfall", "wind_speed_10m"];
|
| 81 |
+
let model = null, data = null;
|
| 82 |
+
|
| 83 |
+
function showError(message) {
|
| 84 |
+
$("error").textContent = message;
|
| 85 |
+
$("result").hidden = true;
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
function drawChart(profile, chosenHour) {
|
| 89 |
+
const canvas = $("chart");
|
| 90 |
+
const ratio = window.devicePixelRatio || 1;
|
| 91 |
+
const width = canvas.clientWidth, height = canvas.clientHeight;
|
| 92 |
+
canvas.width = width * ratio;
|
| 93 |
+
canvas.height = height * ratio;
|
| 94 |
+
const ctx = canvas.getContext("2d");
|
| 95 |
+
ctx.scale(ratio, ratio);
|
| 96 |
+
const styles = getComputedStyle(document.documentElement);
|
| 97 |
+
const color = (name) => styles.getPropertyValue(name).trim();
|
| 98 |
+
|
| 99 |
+
const left = 44, bottom = 22, top = 8;
|
| 100 |
+
const plotHeight = height - bottom - top;
|
| 101 |
+
const max = Math.max(...profile.map((p) => p.predicted_riders), 1);
|
| 102 |
+
const slot = (width - left) / 24;
|
| 103 |
+
|
| 104 |
+
ctx.font = "11px system-ui, sans-serif";
|
| 105 |
+
ctx.fillStyle = color("--muted");
|
| 106 |
+
ctx.strokeStyle = color("--line");
|
| 107 |
+
ctx.textAlign = "right";
|
| 108 |
+
[0, 0.5, 1].forEach((f) => {
|
| 109 |
+
const y = top + plotHeight * (1 - f);
|
| 110 |
+
ctx.beginPath(); ctx.moveTo(left, y); ctx.lineTo(width, y); ctx.stroke();
|
| 111 |
+
ctx.fillText(Math.round(max * f).toLocaleString(), left - 6, y + 4);
|
| 112 |
+
});
|
| 113 |
+
ctx.textAlign = "center";
|
| 114 |
+
profile.forEach((p) => {
|
| 115 |
+
const h = (p.predicted_riders / max) * plotHeight;
|
| 116 |
+
ctx.fillStyle = p.hour === chosenHour ? color("--accent") : color("--bar");
|
| 117 |
+
ctx.fillRect(left + p.hour * slot + 2, top + plotHeight - h, Math.max(slot - 4, 1), h);
|
| 118 |
+
if (p.hour % 3 === 0) {
|
| 119 |
+
ctx.fillStyle = color("--muted");
|
| 120 |
+
ctx.fillText(String(p.hour), left + p.hour * slot + slot / 2, height - 6);
|
| 121 |
+
}
|
| 122 |
+
});
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
function predict() {
|
| 126 |
+
$("error").textContent = "";
|
| 127 |
+
const hourText = $("hour").value.trim();
|
| 128 |
+
const hour = /^-?\d+$/.test(hourText) ? Number(hourText) : NaN;
|
| 129 |
+
let weather = null;
|
| 130 |
+
if ($("customWeather").checked) {
|
| 131 |
+
weather = {};
|
| 132 |
+
for (const field of WEATHER_FIELDS) {
|
| 133 |
+
const text = $(field).value.trim();
|
| 134 |
+
weather[field] = text === "" ? NaN : Number(text);
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
try {
|
| 138 |
+
const result = TransitPulse.predictHour(model, data, $("route").value, $("date").value, hour, weather);
|
| 139 |
+
$("resultLabel").textContent = `Predicted riders on ${result.route} at ${result.hour}:00 on ${result.date}`;
|
| 140 |
+
$("resultValue").textContent = result.predicted_riders.toLocaleString();
|
| 141 |
+
$("result").hidden = false;
|
| 142 |
+
drawChart(result.daily_profile, result.hour);
|
| 143 |
+
} catch (error) {
|
| 144 |
+
showError(error instanceof TransitPulse.InputError ? error.message : "Something went wrong: " + error.message);
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
Promise.all([fetch("model.json"), fetch("data.json")])
|
| 149 |
+
.then((responses) => Promise.all(responses.map((r) => { if (!r.ok) throw new Error(r.statusText); return r.json(); })))
|
| 150 |
+
.then(([loadedModel, loadedData]) => {
|
| 151 |
+
model = loadedModel;
|
| 152 |
+
data = loadedData;
|
| 153 |
+
$("route").innerHTML = data.route_names.map((r) => `<option>${r}</option>`).join("");
|
| 154 |
+
$("route").value = data.route_names[0];
|
| 155 |
+
$("route").disabled = false;
|
| 156 |
+
$("date").min = data.first_date;
|
| 157 |
+
$("date").max = data.last_date;
|
| 158 |
+
$("date").value = data.default_date;
|
| 159 |
+
$("go").disabled = false;
|
| 160 |
+
predict();
|
| 161 |
+
})
|
| 162 |
+
.catch((error) => showError("Could not load the model files: " + error.message));
|
| 163 |
+
|
| 164 |
+
$("customWeather").addEventListener("change", (e) => { $("weatherBox").hidden = !e.target.checked; });
|
| 165 |
+
$("go").addEventListener("click", predict);
|
| 166 |
+
window.addEventListener("resize", () => { if (!$("result").hidden) predict(); });
|
| 167 |
+
</script>
|
| 168 |
+
</body>
|
| 169 |
</html>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
|
|
| 1 |
+
// TransitPulse planning model, running in the browser (used by the Hugging Face static Space).
|
| 2 |
+
//
|
| 3 |
+
// The model is the scikit-learn pipeline saved in models/planning_model.joblib:
|
| 4 |
+
// 1. one-hot encoding of bus_route and borough (the other 18 inputs pass through unchanged),
|
| 5 |
+
// 2. a HistGradientBoostingRegressor with 500 trees.
|
| 6 |
+
// app/build_hf_space.py exports that pipeline to model.json (the trees) and the lookup tables
|
| 7 |
+
// (route facts, schedule, recorded weather, calendar) to data.json.
|
| 8 |
+
// This file rebuilds the input row exactly like app/features.py and adds up the trees exactly
|
| 9 |
+
// like scikit-learn does. app/verify_static_space.py checks that the results are identical.
|
| 10 |
+
// The same file runs in the browser (window.TransitPulse) and in Node.js (module.exports) for the check.
|
| 11 |
+
|
| 12 |
+
(function (root) {
|
| 13 |
+
"use strict";
|
| 14 |
+
|
| 15 |
+
// ---- the model --------------------------------------------------------------------------
|
| 16 |
+
|
| 17 |
+
// Walk one tree from the root to a leaf. feature = -1 marks a leaf.
|
| 18 |
+
// scikit-learn's rule: go left when the value is <= the threshold (missing values follow missing_left).
|
| 19 |
+
function treeValue(tree, x) {
|
| 20 |
+
let node = 0;
|
| 21 |
+
while (tree.feature[node] !== -1) {
|
| 22 |
+
const v = x[tree.feature[node]];
|
| 23 |
+
const goLeft = Number.isNaN(v) ? tree.missing_left[node] === 1 : v <= tree.threshold[node];
|
| 24 |
+
node = goLeft ? tree.left[node] : tree.right[node];
|
| 25 |
+
}
|
| 26 |
+
return tree.value[node];
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// Prediction = starting value (training mean) + the sum of all 500 tree outputs, in the same order as scikit-learn.
|
| 30 |
+
function rawPredict(model, x) {
|
| 31 |
+
let total = 0;
|
| 32 |
+
total += model.baseline;
|
| 33 |
+
for (const tree of model.trees) total += treeValue(tree, x);
|
| 34 |
+
return total;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// Same column order as the ColumnTransformer: one-hot columns first, then the numeric columns.
|
| 38 |
+
function encode(model, row) {
|
| 39 |
+
const x = [];
|
| 40 |
+
for (const [column, categories] of model.onehot) {
|
| 41 |
+
for (const category of categories) x.push(row[column] === category ? 1 : 0);
|
| 42 |
+
}
|
| 43 |
+
for (const column of model.numeric) x.push(row[column]);
|
| 44 |
+
return x;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// numpy.round rounds halves to the nearest even number (2.5 -> 2); Math.round would give 3.
|
| 48 |
+
function roundHalfEven(value) {
|
| 49 |
+
const down = Math.floor(value);
|
| 50 |
+
const diff = value - down;
|
| 51 |
+
if (diff < 0.5) return down;
|
| 52 |
+
if (diff > 0.5) return down + 1;
|
| 53 |
+
return down % 2 === 0 ? down : down + 1;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// ---- input checks (same messages as app/features.py) ------------------------------------
|
| 57 |
+
|
| 58 |
+
class InputError extends Error {}
|
| 59 |
+
|
| 60 |
+
function pyFloat(n) {
|
| 61 |
+
// Python prints the float limits as -30.0, 45.0, ...
|
| 62 |
+
return Number.isInteger(n) ? n.toFixed(1) : String(n);
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
function checkRoute(data, route) {
|
| 66 |
+
if (!Object.prototype.hasOwnProperty.call(data.routes, route)) {
|
| 67 |
+
throw new InputError(`Unknown route '${route}'. Choose one of: ${data.route_names.join(", ")}.`);
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
function checkDate(data, date) {
|
| 72 |
+
const text = String(date);
|
| 73 |
+
const parsed = new Date(text + "T00:00:00Z");
|
| 74 |
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== text) {
|
| 75 |
+
throw new InputError(`Date '${date}' is not valid. Use the format YYYY-MM-DD.`);
|
| 76 |
+
}
|
| 77 |
+
if (!Object.prototype.hasOwnProperty.call(data.calendar, text)) {
|
| 78 |
+
throw new InputError(`Date must be between ${data.first_date} and ${data.last_date}, the period the model was trained on.`);
|
| 79 |
+
}
|
| 80 |
+
return text;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
function checkHour(hour) {
|
| 84 |
+
if (typeof hour !== "number" || !Number.isInteger(hour) || hour < 0 || hour > 23) {
|
| 85 |
+
throw new InputError("Hour must be a whole number from 0 to 23.");
|
| 86 |
+
}
|
| 87 |
+
return hour;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
function checkWeather(data, weather) {
|
| 91 |
+
const clean = {};
|
| 92 |
+
for (const [name, value] of Object.entries(weather || {})) {
|
| 93 |
+
if (value === null || value === undefined) continue;
|
| 94 |
+
if (!Object.prototype.hasOwnProperty.call(data.weather_limits, name)) {
|
| 95 |
+
throw new InputError(`Unknown weather field '${name}'. Allowed: ${Object.keys(data.weather_limits).join(", ")}.`);
|
| 96 |
+
}
|
| 97 |
+
const [low, high] = data.weather_limits[name];
|
| 98 |
+
if (typeof value !== "number" || !Number.isFinite(value) || value < low || value > high) {
|
| 99 |
+
throw new InputError(`${name} must be a number between ${pyFloat(low)} and ${pyFloat(high)}.`);
|
| 100 |
+
}
|
| 101 |
+
clean[name] = value;
|
| 102 |
+
}
|
| 103 |
+
return clean;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
// ---- building the model's input rows (mirrors features.day_features) --------------------
|
| 107 |
+
|
| 108 |
+
function dayRows(data, route, date, weather) {
|
| 109 |
+
checkRoute(data, route);
|
| 110 |
+
const day = checkDate(data, date);
|
| 111 |
+
const chosenWeather = checkWeather(data, weather);
|
| 112 |
+
|
| 113 |
+
const calendar = data.calendar[day];
|
| 114 |
+
const dayType = calendar.day_of_week < 5 ? "weekday" : calendar.day_of_week === 5 ? "saturday" : "sunday";
|
| 115 |
+
const schedule = data.schedule[route][dayType];
|
| 116 |
+
const recorded = data.weather[day];
|
| 117 |
+
|
| 118 |
+
const rows = [];
|
| 119 |
+
for (let hour = 0; hour < 24; hour++) {
|
| 120 |
+
const row = {
|
| 121 |
+
bus_route: route,
|
| 122 |
+
hour: hour,
|
| 123 |
+
day_of_week: calendar.day_of_week,
|
| 124 |
+
is_weekend: calendar.day_of_week >= 5 ? 1 : 0,
|
| 125 |
+
hour_sin: data.hour_sin[hour],
|
| 126 |
+
hour_cos: data.hour_cos[hour],
|
| 127 |
+
is_am_peak: hour >= 7 && hour <= 9 ? 1 : 0,
|
| 128 |
+
is_pm_peak: hour >= 16 && hour <= 19 ? 1 : 0,
|
| 129 |
+
is_holiday: calendar.is_holiday,
|
| 130 |
+
is_school_day: calendar.is_school_day,
|
| 131 |
+
};
|
| 132 |
+
Object.assign(row, data.routes[route]);
|
| 133 |
+
data.schedule_columns.forEach((column, i) => { row[column] = schedule[hour][i]; });
|
| 134 |
+
for (const column of Object.keys(data.weather_limits)) {
|
| 135 |
+
row[column] = column in chosenWeather ? chosenWeather[column] : recorded[column][hour];
|
| 136 |
+
}
|
| 137 |
+
rows.push(row);
|
| 138 |
+
}
|
| 139 |
+
return rows;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
// Predicted riders for each hour of the day: never below 0, rounded to whole riders.
|
| 143 |
+
function predictDay(model, data, route, date, weather) {
|
| 144 |
+
return dayRows(data, route, date, weather).map((row) => ({
|
| 145 |
+
hour: row.hour,
|
| 146 |
+
predicted_riders: roundHalfEven(Math.max(rawPredict(model, encode(model, row)), 0)),
|
| 147 |
+
}));
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
function predictHour(model, data, route, date, hour, weather) {
|
| 151 |
+
checkHour(hour);
|
| 152 |
+
const profile = predictDay(model, data, route, date, weather);
|
| 153 |
+
return { route, date, hour, predicted_riders: profile[hour].predicted_riders, daily_profile: profile };
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
const api = { InputError, treeValue, rawPredict, encode, roundHalfEven, dayRows, predictDay, predictHour };
|
| 157 |
+
if (typeof module === "object" && module.exports) module.exports = api;
|
| 158 |
+
else root.TransitPulse = api;
|
| 159 |
+
})(typeof window !== "undefined" ? window : globalThis);
|