/** * Standalone server: serves the GUI and proxies Overpass API (avoids CORS). * Run: npm start then open http://localhost:3456 */ const express = require('express'); const path = require('path'); const { exec } = require('child_process'); const multer = require('multer'); const app = express(); const PORT = process.env.PORT || 3456; const 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}"`; 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. const OVERPASS_ENDPOINTS = [ 'https://overpass.kumi.systems/api/interpreter', 'https://overpass-api.de/api/interpreter', 'https://overpass.openstreetmap.fr/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_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]); let lastOverpassRequestAt = 0; 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 layerEnabled(layers, key) { return !layers || layers[key] !== false; } function buildOverpassQuery(bbox, layers) { const b = `(${bbox.south},${bbox.west},${bbox.north},${bbox.east})`; const parts = []; if (layerEnabled(layers, 'roads') || layerEnabled(layers, 'paths')) { parts.push(`way["highway"]${b};`); } if (layerEnabled(layers, 'railways')) parts.push(`way["railway"]${b};`); if (layerEnabled(layers, 'buildings')) parts.push(`way["building"]${b};`); if (layerEnabled(layers, 'parkingOutline')) parts.push(`way["amenity"="parking"]${b};`); if (layerEnabled(layers, 'landuse')) parts.push(`way["landuse"]${b};`); if (layerEnabled(layers, 'water')) parts.push(`way["natural"="water"]${b};`); if (layerEnabled(layers, 'parks')) parts.push(`way["leisure"]${b};`); if (layerEnabled(layers, 'barriers')) parts.push(`way["barrier"]${b};`); if (layerEnabled(layers, 'power')) parts.push(`way["power"]${b};`); if (layerEnabled(layers, 'boundary')) parts.push(`way["boundary"]${b};`); if (layerEnabled(layers, 'man_made')) { parts.push(`way["man_made"="embankment"]${b};`); parts.push(`way["man_made"="cutline"]${b};`); } if (layerEnabled(layers, 'trees')) { parts.push(`node["natural"="tree"]${b};`); parts.push(`node["natural"="tree_row"]${b};`); } if (layerEnabled(layers, 'parkingSpaces')) parts.push(`node["amenity"="parking_space"]${b};`); if (parts.length === 0) { parts.push(`way["highway"]${b};`); } return `[out:json][timeout:15];(${parts.join('')});(._;>;);out body;`; } function splitBbox(bbox) { const latSpan = bbox.north - bbox.south; const lonSpan = bbox.east - bbox.west; let nLat = Math.max(1, Math.ceil(latSpan / OVERPASS_TILE_MAX_DEG)); let nLon = Math.max(1, Math.ceil(lonSpan / OVERPASS_TILE_MAX_DEG)); while (nLat * nLon > OVERPASS_MAX_TILES) { if (nLat >= nLon && nLat > 1) nLat--; else if (nLon > 1) nLon--; else break; } if (nLat === 1 && nLon === 1) return [bbox]; const tiles = []; const latStep = latSpan / nLat; const lonStep = lonSpan / nLon; for (let i = 0; i < nLat; i++) { for (let j = 0; j < nLon; j++) { tiles.push({ south: bbox.south + i * latStep, north: bbox.south + (i + 1) * latStep, west: bbox.west + j * lonStep, east: bbox.west + (j + 1) * lonStep }); } } return tiles; } function parseOverpassResponse(text, status) { const looksLikeJson = /^\s*[\{\[]/.test(text); if (!looksLikeJson) { const err = /<[?]xml| controller.abort(), timeoutMs); try { const r = await fetch(url, { method: 'POST', body: query, headers: { 'Content-Type': 'text/plain', 'User-Agent': OVERPASS_USER_AGENT }, signal: controller.signal }); const text = await r.text(); clearTimeout(to); 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.status = r.status; const retryAfter = parseInt(r.headers.get('Retry-After'), 10); if (retryAfter > 0) err.retryAfterMs = retryAfter * 1000; 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.'); err.retryable = true; throw err; } throw e; } } async function fetchOverpass(query, timeoutMs = 25000, skipThrottle) { 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++) { try { return await fetchOverpassOnce(query, url, timeoutMs, skipThrottle && endpointOffset === 0 && attempt === 0); } 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; } } } throw lastError || new Error('All Overpass servers failed. Wait a few minutes and try again, or use a smaller map area.'); } app.post('/api/overpass/plan', (req, res) => { const { south, west, north, east } = req.body || {}; if (typeof south !== 'number' || typeof north !== 'number' || typeof west !== 'number' || typeof east !== 'number') { return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' }); } const tiles = splitBbox({ south, west, north, east }); res.json({ tiles, count: tiles.length }); }); app.post('/api/overpass', async (req, res) => { const { south, west, north, east, layers } = req.body || {}; if (typeof south !== 'number' || typeof north !== 'number' || typeof west !== 'number' || typeof east !== 'number') { return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' }); } const bbox = { south, west, north, east }; try { const query = buildOverpassQuery(bbox, layers); const data = await fetchOverpass(query, 25000, true); 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 }); } }); // Geocode address/place via OpenStreetMap Nominatim (no API key; use respectful User-Agent) const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search'; const GEOCODE_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool)'; 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' }); 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| ({ lat: parseFloat(x.lat), lon: parseFloat(x.lon), display_name: x.display_name || '' })) }); } catch (e) { console.error('Geocode error:', e.message); res.status(502).json({ error: e.message || 'Geocoding failed' }); } }); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); const TILE_SOURCES = { esri: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile', usgs: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile' }; app.get('/api/tile/:z/:y/:x', async (req, res) => { const { z, y, x } = req.params; const sourceKey = String(req.query.source || 'esri').toLowerCase(); const base = TILE_SOURCES[sourceKey] || TILE_SOURCES.esri; const url = `${base}/${z}/${y}/${x}`; try { const r = await fetch(url); if (!r.ok) { res.status(r.status).end(); return; } const buf = await r.arrayBuffer(); res.set('Cache-Control', 'public, max-age=86400'); res.set('Access-Control-Allow-Origin', '*'); res.type('image/png').send(Buffer.from(buf)); } catch (e) { res.status(502).end(); } }); app.post('/api/segment', upload.single('image'), async (req, res) => { if (!req.file || !req.file.buffer) { return res.status(400).json({ error: 'Missing image file' }); } const minX = req.body.minX != null ? String(req.body.minX) : ''; const maxX = req.body.maxX != null ? String(req.body.maxX) : ''; const minY = req.body.minY != null ? String(req.body.minY) : ''; const maxY = req.body.maxY != null ? String(req.body.maxY) : ''; const form = new FormData(); form.append('image', new Blob([req.file.buffer]), req.file.originalname || 'image.png'); form.append('minX', minX); form.append('maxX', maxX); form.append('minY', minY); form.append('maxY', maxY); try { const r = await fetch(`${ML_SEGMENT_URL}/segment`, { method: 'POST', body: form }); const text = await r.text(); if (!r.ok) { let err = { error: 'Segmentation server error' }; try { const j = JSON.parse(text); if (j.error) err = j; } catch (_) {} return res.status(r.status === 503 ? 503 : 502).json(err); } let data; try { data = JSON.parse(text); } catch (_) { return res.status(502).json({ error: 'Invalid response from segmentation server' }); } res.json(data); } 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' }); } }); const server = app.listen(PORT, () => { console.log('MAPS to DXF — ' + URL); openBrowser(); }); server.on('error', (err) => { if (err.code === 'EADDRINUSE') { console.error(''); console.error('Port ' + PORT + ' is already in use.'); console.error('Close the other MAPS to DXF console window, or run Start.bat again (it will free the port).'); console.error(''); process.exit(1); } throw err; });