feat: harden maps export for CAD and improve satellite/OSM workflow

Cap zoom to real imagery, attach a BricsCAD-safe DXF IMAGE at the selected extent, and consolidate startup plus Overpass/address handling.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Michael-A-SloanandCursor committed 2026-08-31 15:43:01 -04:00
1 parent fadfb807ec
commit 7769a4412e
8 files changed
+1186 -330

No files matched your search

+410 -79
View File
@@ -4,50 +4,100 @@
*/
const express = require('express');
const path = require('path');
const { exec } = require('child_process');
const { exec, spawn, execSync } = require('child_process');
const fs = require('fs');
const multer = require('multer');
const app = express();
const PORT = process.env.PORT || 3456;
const URL = `http://localhost:${PORT}`;
const APP_URL = `http://localhost:${PORT}`;
const ML_SEGMENT_URL = process.env.ML_SEGMENT_URL || 'http://127.0.0.1:3457';
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 16 * 1024 * 1024 } });
function openBrowser() {
const plat = process.platform;
const cmd = plat === 'win32' ? `start "" "${URL}"` : plat === 'darwin' ? `open "${URL}"` : `xdg-open "${URL}"`;
const cmd = plat === 'win32' ? `start "" "${APP_URL}"` : plat === 'darwin' ? `open "${APP_URL}"` : `xdg-open "${APP_URL}"`;
exec(cmd, () => {});
}
app.use(express.json({ limit: '1mb' }));
app.use(express.static(path.join(__dirname, 'public')));
// Public Overpass mirrors; rotated and retried on 429/503/504.
// Public Overpass mirrors. Prefer instances without tight rate limits; skip a host after it fails.
const OVERPASS_ENDPOINTS = [
'https://overpass.kumi.systems/api/interpreter',
'https://overpass-api.de/api/interpreter',
'https://overpass.openstreetmap.fr/api/interpreter',
'https://overpass-api.de/api/interpreter',
'https://lz4.overpass-api.de/api/interpreter',
'https://overpass.private.coffee/api/interpreter'
];
const OVERPASS_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool; https://github.com)';
const OVERPASS_MIN_INTERVAL_MS = Number(process.env.OVERPASS_MIN_INTERVAL_MS) || 1000;
const OVERPASS_MAX_RETRIES = Number(process.env.OVERPASS_MAX_RETRIES) || 3;
const OVERPASS_BACKOFF_BASE_MS = Number(process.env.OVERPASS_BACKOFF_BASE_MS) || 2000;
const OVERPASS_USER_AGENT = 'MAPS-to-DXF-standalone/1.1 (local CAD export tool; contact: local user)';
const OVERPASS_MIN_INTERVAL_MS = Number(process.env.OVERPASS_MIN_INTERVAL_MS) || 800;
const OVERPASS_FAILOVER_GAP_MS = 200;
const OVERPASS_BACKOFF_BASE_MS = Number(process.env.OVERPASS_BACKOFF_BASE_MS) || 800;
const OVERPASS_TILE_MAX_DEG = Number(process.env.OVERPASS_TILE_MAX_DEG) || 0.018;
const OVERPASS_MAX_TILES = Number(process.env.OVERPASS_MAX_TILES) || 9;
const RETRYABLE_OVERPASS_STATUSES = new Set([429, 502, 503, 504]);
const OVERPASS_CACHE_TTL_MS = Number(process.env.OVERPASS_CACHE_TTL_MS) || 5 * 60 * 1000;
const OVERPASS_TIMEOUT_FAST_MS = Number(process.env.OVERPASS_TIMEOUT_FAST_MS) || 8000;
const OVERPASS_TIMEOUT_SLOW_MS = Number(process.env.OVERPASS_TIMEOUT_SLOW_MS) || 12000;
const RETRYABLE_OVERPASS_STATUSES = new Set([408, 429, 502, 503, 504, 520, 521, 522, 524]);
let lastOverpassRequestAt = 0;
let lastGoodEndpointIdx = 0;
let throttleChain = Promise.resolve();
const overpassCache = new Map();
const endpointCooldownUntil = new Map();
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function throttleOverpass(skip) {
if (skip) return;
const now = Date.now();
const wait = OVERPASS_MIN_INTERVAL_MS - (now - lastOverpassRequestAt);
if (wait > 0) await sleep(wait);
lastOverpassRequestAt = Date.now();
function throttleOverpass(intervalMs) {
const min = intervalMs == null ? OVERPASS_MIN_INTERVAL_MS : intervalMs;
const run = throttleChain.then(async () => {
const now = Date.now();
const wait = min - (now - lastOverpassRequestAt);
if (wait > 0) await sleep(wait);
lastOverpassRequestAt = Date.now();
});
throttleChain = run.catch(() => {});
return run;
}
function isRetryableOverpassError(e) {
if (!e) return false;
if (e.retryable === true) return true;
if (RETRYABLE_OVERPASS_STATUSES.has(e.status)) return true;
if (e.name === 'AbortError' || /timed out|timeout|rate.?limit|too many|unavailable|error page/i.test(e.message || '')) return true;
return e.retryable !== false;
}
function markEndpointCooldown(url, ms) {
const until = Date.now() + Math.max(ms, 5000);
endpointCooldownUntil.set(url, until);
}
function isEndpointCooling(url) {
return Date.now() < (endpointCooldownUntil.get(url) || 0);
}
function cacheKey(bbox, layers) {
return JSON.stringify({ bbox, layers: layers || null });
}
function cacheGet(key) {
const hit = overpassCache.get(key);
if (!hit) return null;
if (Date.now() - hit.at > OVERPASS_CACHE_TTL_MS) {
overpassCache.delete(key);
return null;
}
return hit.data;
}
function cacheSet(key, data) {
overpassCache.set(key, { at: Date.now(), data });
if (overpassCache.size > 40) {
overpassCache.delete(overpassCache.keys().next().value);
}
}
function layerEnabled(layers, key) {
@@ -81,7 +131,7 @@ function buildOverpassQuery(bbox, layers) {
if (parts.length === 0) {
parts.push(`way["highway"]${b};`);
}
return `[out:json][timeout:15];(${parts.join('')});(._;>;);out body;`;
return `[out:json][timeout:10];(${parts.join('')});(._;>;);out body qt;`;
}
function splitBbox(bbox) {
@@ -114,36 +164,51 @@ function splitBbox(bbox) {
function parseOverpassResponse(text, status) {
const looksLikeJson = /^\s*[\{\[]/.test(text);
if (!looksLikeJson) {
const err = /<[?]xml|<!DOCTYPE|<html/i.test(text)
? new Error('OpenStreetMap Overpass server returned an error page instead of data. Wait a minute and try again, or use a smaller map area.')
const html = /<[?]xml|<!DOCTYPE|<html/i.test(text);
const err = html
? new Error('OpenStreetMap Overpass server is busy. Retrying another server…')
: new Error('Overpass returned invalid response. Try again.');
err.retryable = RETRYABLE_OVERPASS_STATUSES.has(status);
err.retryable = true;
return { error: err };
}
let data;
try {
data = JSON.parse(text);
} catch (_) {
return { error: new Error('Overpass returned invalid JSON. Try again later.') };
const err = new Error('Overpass returned invalid JSON. Try again later.');
err.retryable = true;
return { error: err };
}
if (data.remark && /timeout|rate.?limit|too many|slot/i.test(String(data.remark))) {
if (!Array.isArray(data.elements) || data.elements.length === 0) {
const err = new Error(String(data.remark));
err.retryable = true;
return { error: err };
}
}
if (data.error && (!status || status < 400)) {
const err = new Error(typeof data.error === 'string' ? data.error : 'Overpass error');
err.retryable = true;
return { error: err };
}
if (data.error) return { error: new Error(data.error) };
if (!status || status < 400) return { data };
let msg = `Overpass ${status}`;
if (data.remark) msg = data.remark;
else if (typeof data.error === 'string') msg = data.error;
return { error: new Error(msg), retryable: RETRYABLE_OVERPASS_STATUSES.has(status) };
return { error: new Error(msg), retryable: RETRYABLE_OVERPASS_STATUSES.has(status) || status === 406 };
}
async function fetchOverpassOnce(query, url, timeoutMs, skipThrottle) {
await throttleOverpass(skipThrottle);
async function fetchOverpassOnce(query, url, timeoutMs, intervalMs) {
await throttleOverpass(intervalMs);
const controller = new AbortController();
const to = setTimeout(() => controller.abort(), timeoutMs);
try {
const r = await fetch(url, {
method: 'POST',
body: query,
body: new URLSearchParams({ data: query }).toString(),
headers: {
'Content-Type': 'text/plain',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json',
'User-Agent': OVERPASS_USER_AGENT
},
signal: controller.signal
@@ -153,15 +218,16 @@ async function fetchOverpassOnce(query, url, timeoutMs, skipThrottle) {
const parsed = parseOverpassResponse(text, r.status);
if (parsed.data) return parsed.data;
const err = parsed.error || new Error(`Overpass ${r.status}`);
err.retryable = parsed.retryable ?? RETRYABLE_OVERPASS_STATUSES.has(r.status);
err.retryable = parsed.retryable !== false;
err.status = r.status;
const retryAfter = parseInt(r.headers.get('Retry-After'), 10);
if (retryAfter > 0) err.retryAfterMs = retryAfter * 1000;
else if (r.status === 429) err.retryAfterMs = 30000;
throw err;
} catch (e) {
clearTimeout(to);
if (e.name === 'AbortError') {
const err = new Error('Request timed out. Try a smaller area or try again later.');
const err = new Error('Request timed out. Trying another map server…');
err.retryable = true;
throw err;
}
@@ -169,26 +235,46 @@ async function fetchOverpassOnce(query, url, timeoutMs, skipThrottle) {
}
}
async function fetchOverpass(query, timeoutMs = 25000, skipThrottle) {
async function fetchOverpass(query) {
let lastError;
const startIdx = Math.floor(Math.random() * OVERPASS_ENDPOINTS.length);
for (let endpointOffset = 0; endpointOffset < OVERPASS_ENDPOINTS.length; endpointOffset++) {
const url = OVERPASS_ENDPOINTS[(startIdx + endpointOffset) % OVERPASS_ENDPOINTS.length];
for (let attempt = 0; attempt < OVERPASS_MAX_RETRIES; attempt++) {
const n = OVERPASS_ENDPOINTS.length;
const startIdx = lastGoodEndpointIdx;
const timeouts = [OVERPASS_TIMEOUT_FAST_MS, OVERPASS_TIMEOUT_SLOW_MS];
for (let round = 0; round < timeouts.length; round++) {
let tried = 0;
for (let i = 0; i < n; i++) {
const idx = (startIdx + i) % n;
const url = OVERPASS_ENDPOINTS[idx];
if (isEndpointCooling(url)) continue;
tried++;
const gap = tried === 1 && round === 0 ? OVERPASS_MIN_INTERVAL_MS : OVERPASS_FAILOVER_GAP_MS;
try {
return await fetchOverpassOnce(query, url, timeoutMs, skipThrottle && endpointOffset === 0 && attempt === 0);
const data = await fetchOverpassOnce(query, url, timeouts[round], gap);
lastGoodEndpointIdx = idx;
return data;
} catch (e) {
lastError = e;
const retryable = e.retryable !== false && (e.retryable || e.status === 429);
if (!retryable || attempt >= OVERPASS_MAX_RETRIES - 1) break;
const delay = e.retryAfterMs || OVERPASS_BACKOFF_BASE_MS * Math.pow(2, attempt);
console.warn(`Overpass retry ${attempt + 1}/${OVERPASS_MAX_RETRIES} on ${url} after ${delay}ms: ${e.message}`);
await sleep(delay);
skipThrottle = false;
const timedOut = e.name === 'AbortError' || /timed out/i.test(e.message || '');
const cooldownMs = e.status === 429
? (e.retryAfterMs || 30000)
: (timedOut ? 45000 : (e.status === 503 || e.status === 504 ? 12000 : 0));
if (cooldownMs) markEndpointCooldown(url, cooldownMs);
console.warn(`Overpass ${url}: ${e.message}`);
}
}
if (!tried) {
let waitMs = OVERPASS_BACKOFF_BASE_MS;
endpointCooldownUntil.forEach((until) => {
const left = until - Date.now();
if (left > 0 && left < waitMs) waitMs = left;
});
console.warn('All Overpass endpoints in cooldown; waiting ' + waitMs + 'ms');
await sleep(Math.max(waitMs, 400));
} else if (round === 0) {
await sleep(OVERPASS_BACKOFF_BASE_MS);
}
}
throw lastError || new Error('All Overpass servers failed. Wait a few minutes and try again, or use a smaller map area.');
throw lastError || new Error('All Overpass servers failed. Wait a minute and try again, or use a smaller map area.');
}
app.post('/api/overpass/plan', (req, res) => {
@@ -206,62 +292,265 @@ app.post('/api/overpass', async (req, res) => {
return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' });
}
const bbox = { south, west, north, east };
const key = cacheKey(bbox, layers);
const cached = cacheGet(key);
if (cached) return res.json(cached);
try {
const query = buildOverpassQuery(bbox, layers);
const data = await fetchOverpass(query, 25000, true);
const data = await fetchOverpass(query);
cacheSet(key, data);
res.json(data);
} catch (e) {
const msg = e.message || 'Overpass request failed';
console.error('Overpass error:', msg);
const status = e.status === 429 ? 429 : 502;
res.status(status).json({ error: msg });
res.status(status).json({ error: msg, retryAfterMs: e.retryAfterMs || 8000 });
}
});
// Geocode address/place via OpenStreetMap Nominatim (no API key; use respectful User-Agent)
// Geocode via OpenStreetMap Nominatim + Photon (no Google API key).
const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search';
const GEOCODE_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool)';
const PHOTON_URL = 'https://photon.komoot.io/api/';
const GEOCODE_USER_AGENT = 'MAPS-to-DXF-standalone/1.1 (local CAD export tool)';
function isAllowedMapsHost(hostname) {
const h = String(hostname || '').toLowerCase();
return (
h === 'maps.app.goo.gl' ||
h === 'goo.gl' ||
h === 'google.com' ||
h.endsWith('.google.com') ||
h === 'maps.google.com'
);
}
function scoreGeocodeHit(item, query) {
let s = Number(item.importance) || 0;
const addr = item.address || {};
const house = String(addr.house_number || '');
const qHouse = query.match(/\b(\d{1,6})\b/);
if (house && qHouse && house === qHouse[1]) s += 3;
else if (house) s += 1.2;
const cls = item.class || '';
const type = item.type || '';
if (cls === 'building' || type === 'house' || type === 'residential' && cls === 'building') s += 1.5;
if (cls === 'amenity' || cls === 'shop' || cls === 'industrial' || cls === 'office') s += 1;
if (cls === 'highway') s -= 0.9;
if (cls === 'place' && /city|town|village|county|state|suburb/.test(type)) s -= 1.6;
const name = String(item.display_name || '').toLowerCase();
const tokens = query.toLowerCase().replace(/[^\w\s]/g, ' ').split(/\s+/).filter((t) => t.length > 1);
tokens.forEach((t) => { if (name.includes(t)) s += 0.12; });
return s;
}
function pickBestGeocode(hits, query) {
if (!hits || !hits.length) return null;
let best = hits[0];
let bestScore = scoreGeocodeHit(best, query);
for (let i = 1; i < hits.length; i++) {
const sc = scoreGeocodeHit(hits[i], query);
if (sc > bestScore) {
best = hits[i];
bestScore = sc;
}
}
return best;
}
function normalizeNominatimHits(data) {
return (data || []).map((x) => ({
lat: parseFloat(x.lat),
lon: parseFloat(x.lon),
display_name: x.display_name || '',
class: x.class,
type: x.type,
importance: x.importance,
address: x.address || {}
})).filter((x) => !isNaN(x.lat) && !isNaN(x.lon));
}
function normalizePhotonHits(data) {
return ((data && data.features) || []).map((f) => {
const p = f.properties || {};
const c = (f.geometry && f.geometry.coordinates) || [];
const parts = [p.name, p.housenumber, p.street, p.city, p.state, p.country].filter(Boolean);
return {
lat: parseFloat(c[1]),
lon: parseFloat(c[0]),
display_name: parts.join(', '),
class: p.osm_key,
type: p.osm_value,
importance: 0.4,
address: { house_number: p.housenumber, road: p.street, city: p.city }
};
}).filter((x) => !isNaN(x.lat) && !isNaN(x.lon));
}
async function nominatimSearch(q) {
const params = new URLSearchParams({
q: q,
format: 'jsonv2',
limit: '8',
addressdetails: '1'
});
const r = await fetch(NOMINATIM_URL + '?' + params, {
headers: { 'User-Agent': GEOCODE_USER_AGENT, 'Accept-Language': 'en' }
});
const text = await r.text();
if (!r.ok || !/^\s*[\{\[]/.test(text)) return [];
try {
return normalizeNominatimHits(JSON.parse(text));
} catch (_) {
return [];
}
}
async function photonSearch(q) {
const r = await fetch(PHOTON_URL + '?limit=8&q=' + encodeURIComponent(q), {
headers: { 'User-Agent': GEOCODE_USER_AGENT }
});
const text = await r.text();
if (!r.ok || !/^\s*[\{\[]/.test(text)) return [];
try {
return normalizePhotonHits(JSON.parse(text));
} catch (_) {
return [];
}
}
function extractMapsLocationFromText(s) {
if (!s) return null;
const pins = [];
const pinRe = /!3d(-?\d+\.?\d*)!4d(-?\d+\.?\d*)/g;
let m;
while ((m = pinRe.exec(s)) !== null) {
pins.push({ lat: parseFloat(m[1]), lon: parseFloat(m[2]) });
}
const at = s.match(/@(-?\d+\.?\d*),(-?\d+\.?\d*)/);
const zoomM = s.match(/@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*m\b/i);
let lat;
let lon;
if (pins.length) {
lat = pins[pins.length - 1].lat;
lon = pins[pins.length - 1].lon;
} else if (at) {
lat = parseFloat(at[1]);
lon = parseFloat(at[2]);
} else {
return null;
}
if (isNaN(lat) || isNaN(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
let displayName = null;
const place = s.match(/\/maps\/place\/([^/@?#]+)/i);
if (place && place[1]) {
try {
displayName = decodeURIComponent(place[1].replace(/\+/g, ' ')).trim();
} catch (_) {
displayName = place[1].replace(/\+/g, ' ');
}
}
return {
lat,
lon,
viewMeters: zoomM ? Math.min(50000, Math.max(50, parseFloat(zoomM[1]))) : undefined,
display_name: displayName || ''
};
}
async function fetchGoogleMapsPin(rawUrl) {
const current = new URL(rawUrl.trim());
if (current.protocol !== 'https:' || !isAllowedMapsHost(current.hostname)) {
const err = new Error('Paste a Google Maps or maps.app.goo.gl link.');
err.status = 400;
throw err;
}
const r = await fetch(current.href, {
method: 'GET',
redirect: 'follow',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept-Language': 'en-US,en;q=0.9'
}
});
const html = await r.text();
const finalUrl = r.url || current.href;
const loc = extractMapsLocationFromText(finalUrl) || extractMapsLocationFromText(html);
if (!loc) {
const err = new Error('Could not read a pin from that Google Maps link.');
err.status = 404;
throw err;
}
return {
lat: loc.lat,
lon: loc.lon,
viewMeters: loc.viewMeters,
display_name: loc.display_name || '',
url: finalUrl
};
}
app.get('/api/maps-pin', async (req, res) => {
const raw = req.query.url;
if (!raw || typeof raw !== 'string') {
return res.status(400).json({ error: 'Missing url' });
}
try {
const data = await fetchGoogleMapsPin(raw);
res.json(data);
} catch (e) {
if (e.code === 'ERR_INVALID_URL' || e.message === 'Invalid URL') {
return res.status(400).json({ error: 'Invalid URL' });
}
console.error('Maps pin error:', e.message);
res.status(e.status || 502).json({ error: e.message || 'Could not open that Maps link.' });
}
});
app.get('/api/resolve-url', async (req, res) => {
const raw = req.query.url;
if (!raw || typeof raw !== 'string') {
return res.status(400).json({ error: 'Missing url' });
}
try {
const data = await fetchGoogleMapsPin(raw);
res.json(data);
} catch (e) {
res.status(e.status || 502).json({ error: e.message || 'Could not expand that Maps link.' });
}
});
app.get('/api/geocode', async (req, res) => {
const q = req.query.q;
if (!q || typeof q !== 'string' || q.trim().length === 0) {
return res.status(400).json({ error: 'Missing or empty query (q)' });
}
const params = new URLSearchParams({
q: q.trim(),
format: 'json',
limit: '5',
addressdetails: '0'
});
let query = q.trim();
if (/^https?:/i.test(query)) {
return res.status(400).json({ error: 'That looks like a link, not an address. Paste a Google Maps URL with a pin, or type the street address.' });
}
if (/\b[A-Z]{2}\b/.test(query) && !/united states|\busa\b/i.test(query)) {
query = query + ', USA';
}
try {
const r = await fetch(`${NOMINATIM_URL}?${params}`, {
headers: { 'User-Agent': GEOCODE_USER_AGENT }
});
const text = await r.text();
if (!r.ok) {
return res.status(502).json({ error: 'Geocoding service unavailable' });
}
if (!/^\s*[\{\[]/.test(text)) {
if (/<\?xml|<!DOCTYPE|<html/i.test(text)) {
return res.status(502).json({ error: 'Geocoding service returned an error page. Try again in a moment.' });
let hits = await nominatimSearch(query);
if (!hits.length) hits = await photonSearch(q.trim());
else {
const best = pickBestGeocode(hits, q.trim());
const weak = !best || (best.class === 'highway') || (best.class === 'place' && /city|town|village/.test(best.type || ''));
if (weak) {
const extra = await photonSearch(q.trim());
hits = hits.concat(extra);
}
return res.status(502).json({ error: 'Geocoding service returned invalid response.' });
}
let data;
try {
data = JSON.parse(text);
} catch (parseErr) {
return res.status(502).json({ error: 'Geocoding service returned invalid data. Try again.' });
const best = pickBestGeocode(hits, q.trim());
if (!best) {
return res.status(404).json({ error: 'No location found for this address. Paste a Google Maps link to the pin for an exact spot.' });
}
if (!Array.isArray(data) || data.length === 0) {
return res.status(404).json({ error: 'No location found for this address or place name.' });
}
const first = data[0];
res.json({
lat: parseFloat(first.lat),
lon: parseFloat(first.lon),
display_name: first.display_name || '',
results: data.slice(0, 5).map((x) => ({ lat: parseFloat(x.lat), lon: parseFloat(x.lon), display_name: x.display_name || '' }))
lat: best.lat,
lon: best.lon,
display_name: best.display_name || '',
results: hits.slice(0, 5).map((x) => ({ lat: x.lat, lon: x.lon, display_name: x.display_name || '' }))
});
} catch (e) {
console.error('Geocode error:', e.message);
@@ -275,6 +564,7 @@ app.get('/', (req, res) => {
const TILE_SOURCES = {
esri: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile',
clarity: 'https://clarity.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile',
usgs: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile'
};
@@ -336,13 +626,54 @@ app.post('/api/segment', upload.single('image'), async (req, res) => {
} catch (e) {
console.error('Segment proxy error:', e.message);
res.status(503).json({
error: 'Server-side ML not available. Start the Python server: cd ml_server && pip install -r requirements.txt && python segment_server.py'
error: 'Server-side ML not available. Restart with Start.bat (Python is optional). Satellite tracing still works.'
});
}
});
function resolvePython() {
const cmds = process.platform === 'win32' ? ['python', 'py'] : ['python3', 'python'];
for (let i = 0; i < cmds.length; i++) {
try {
execSync(cmds[i] + ' --version', { stdio: 'ignore' });
return cmds[i];
} catch (_) {}
}
return null;
}
let mlChild = null;
function stopMlServer() {
if (!mlChild) return;
try { mlChild.kill(); } catch (_) {}
mlChild = null;
}
function startMlServer() {
const dir = path.join(__dirname, 'ml_server');
const script = path.join(dir, 'segment_server.py');
if (!fs.existsSync(script)) return;
const py = resolvePython();
if (!py) {
console.log('Python not found — ML segmentation off. Satellite tracing still works.');
return;
}
mlChild = spawn(py, [script], {
cwd: dir,
stdio: 'ignore',
windowsHide: true
});
mlChild.on('error', () => { mlChild = null; });
mlChild.on('exit', () => { mlChild = null; });
process.on('exit', stopMlServer);
process.on('SIGINT', () => { stopMlServer(); process.exit(0); });
process.on('SIGTERM', () => { stopMlServer(); process.exit(0); });
}
startMlServer();
const server = app.listen(PORT, () => {
console.log('MAPS to DXF — ' + URL);
console.log('MAPS to DXF — ' + APP_URL);
openBrowser();
});
server.on('error', (err) => {