/** * 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'))); // Multiple public Overpass API instances; we try each until one returns valid JSON. const OVERPASS_ENDPOINTS = [ 'https://overpass-api.de/api/interpreter', 'https://overpass.kumi.systems/api/interpreter', 'https://overpass.openstreetmap.fr/api/interpreter' ]; const OVERPASS_USER_AGENT = 'MAPS-to-DXF-standalone/1.0 (local mapping tool; https://github.com)'; async function fetchOverpass(query, timeoutMs = 45000) { let lastError; for (const url of OVERPASS_ENDPOINTS) { const controller = new AbortController(); const to = setTimeout(() => 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 looksLikeJson = /^\s*[\{\[]/.test(text); if (!r.ok) { let msg = `Overpass ${r.status}`; if (looksLikeJson) { try { const err = JSON.parse(text); if (err.error) msg = err.error; } catch (_) {} } else if (/<\?xml| { const bbox = req.body; if (!bbox || typeof bbox.south !== 'number' || typeof bbox.north !== 'number') { return res.status(400).json({ error: 'Invalid bbox: need south, west, north, east' }); } const query = ` [out:json][timeout:25]; ( way["highway"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["railway"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["building"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["amenity"="parking"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["landuse"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["natural"="water"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["leisure"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["barrier"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["power"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["boundary"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["man_made"="embankment"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); way["man_made"="cutline"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); node["natural"="tree"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); node["natural"="tree_row"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); node["amenity"="parking_space"](${bbox.south},${bbox.west},${bbox.north},${bbox.east}); ); (._;>;); out body; `; try { const data = await fetchOverpass(query); res.json(data); } catch (e) { const msg = e.message || 'Overpass request failed'; console.error('Overpass error:', msg); res.status(502).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_BASE = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile'; // Proxy to Python ML segmentation server (run: cd ml_server && pip install -r requirements.txt && python segment_server.py) 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' }); } }); app.get('/api/tile/:z/:y/:x', async (req, res) => { const { z, y, x } = req.params; const url = `${TILE_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.listen(PORT, () => { console.log('MAPS to DXF — ' + URL); openBrowser(); });