feat: add standalone maps-to-dxf web application

Node.js/Express server with web GUI for converting Google Maps links to DXF files. Includes optional Python ML server for satellite lot detection.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Michael-A-SloanandCursor committed 2026-06-25 15:30:38 -04:00
1 parent b035ed1763
commit 7c20a404bf
14 files changed
+4491

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# Dependencies
node_modules/
# Environment
.env
.env.local
.env.*.local
# OS
.DS_Store
Thumbs.db
# Logs
*.log
npm-debug.log*
# Optional
.idea/
.vscode/
*.swp
*.swo
+48
View File
@@ -0,0 +1,48 @@
# Push this project to your GitHub account
The folder is already a Git repo with an initial commit. To put it on GitHub:
---
## Option A — GitHub website
1. **Create the repo on GitHub**
- Go to [github.com/new](https://github.com/new).
- Repository name: `MAPS-to-DXF-standalone` (or any name you like).
- Choose **Public** or **Private**.
- Do **not** add a README, .gitignore, or license (they’re already in this project).
- Click **Create repository**.
2. **Connect and push from your PC**
- Open a terminal in this folder and run (replace `YOUR_USERNAME` with your GitHub username):
```bash
git remote add origin https://github.com/YOUR_USERNAME/MAPS-to-DXF-standalone.git
git branch -M main
git push -u origin main
```
If your repo name is different, use that name in the URL instead of `MAPS-to-DXF-standalone`.
---
## Option B — GitHub CLI (if you use `gh`)
From this folder:
```bash
gh repo create MAPS-to-DXF-standalone --source=. --remote=origin --push
```
Use `--public` or `--private` as you prefer. If the repo already exists on GitHub, use:
```bash
gh repo create MAPS-to-DXF-standalone --source=. --remote=origin --push
```
(or add the remote manually and run `git push -u origin main`).
---
After a successful push, your repo will be at:
`https://github.com/YOUR_USERNAME/MAPS-to-DXF-standalone`
+103
View File
@@ -0,0 +1,103 @@
# MAPS to DXF — Standalone GUI
Turn a **Google Maps link** into a **DXF map** with roads, rails, buildings, and **lot boundaries**. No Google Sheets. Run locally, export to your computer.
---
## Requirements
- **Node.js** (v18 or newer) — for the local server and Overpass/satellite proxy
---
## How to run
**Easiest:** Double-click **Start.bat**.
- If Node.js isn’t installed, the script will try to install it (Windows Package Manager) or open the Node.js download page. After installing, run **Start.bat** again.
- If Node.js is installed: the app starts, your browser opens to the app. Keep the console window open while using it; close it to stop the server.
**Or from a terminal:**
```bash
cd MAPS-to-DXF-standalone
npm install # first time only
npm start
```
Then open **http://localhost:3456** in your browser.
---
## Workflow
1. **Paste** a Google Maps URL that contains coordinates (e.g. `https://www.google.com/maps/@40.7128,-74.0060,...`).
2. **Load preview** — fetches OpenStreetMap data and draws roads, rails, buildings, water, parks.
3. **Show satellite imagery** — optional; useful for aligning lot boundaries.
4. **Add lots** (choose one or combine):
- **Select detection area** → drag a rectangle → **Add selection as lot** — use the blue box as one property lot (building + parking).
- **Select detection area** → **Detect lots from imagery** — auto-detect inside the rectangle (smaller lots ~80 m²).
- **Detect lots from imagery** (no selection) — auto-detect over the full view (often finds building outlines).
- **Draw lot** — click to add vertices, double-click or **Close lot** to finish one polygon.
5. **Edit lots** — drag lot corners to correct positions.
6. **Export DXF** — downloads the DXF and (if satellite was used) a PNG; keep both in the same folder for CAD.
---
## Port
Default port is **3456**. To use another:
```bash
PORT=8080 npm start
```
Then open http://localhost:8080
---
## Why a local server?
- **Overpass API** (OpenStreetMap) blocks direct browser requests (CORS). The Node server proxies Overpass and satellite tile requests.
- DXF and PNG are generated in the browser and downloaded to your machine; nothing is stored on a remote server.
---
## Files
| File / folder | Role |
|--------------------|------|
| `Start.bat` | One-click run on Windows (installs Node if needed, then `npm start`) |
| `server.js` | Express server: serves `public/`, proxies Overpass and tile API |
| `public/index.html`| Single-page UI + canvas preview + all map/lot/edit logic (inline script) |
| `public/app.js` | Shared helpers: OSM→preview, DXF generation, OSM lot/concave-hull logic |
---
## Server-side ML and OSM-guided trace
- **Generate drawing from imagery** — Vectorizes satellite imagery into the DXF (client-side edge detection).
- **Use server-side ML segmentation** — Sends the imagery to a small Python server that runs OpenCV Canny + contours and classifies buildings, trees, and lots. Export writes separate DXF layers: **IMAGERY_BUILDINGS**, **IMAGERY_TREES**, **IMAGERY_LOTS**.
**To enable:** In a second terminal:
```bash
cd ml_server
pip install -r requirements.txt
python segment_server.py
```
The Python server runs on **http://127.0.0.1:3457**. The Node app proxies `/api/segment` to it. If the Python server is not running, the checkbox will show an error when you use it.
- **Snap imagery trace to OSM** — When enabled, trace points are snapped to nearby OSM buildings, roads, and landuse (within ~1.5 m). Use this to align the imagery trace with OSM where data exists.
---
## Going further: satellite imagery & ML
This app uses **OpenStreetMap** for vectors and optional **edge detection** (or server-side segmentation) on satellite imagery. For custom ML models and training data, see the satellite-image-deep-learning ecosystem:
- **[satellite-image-deep-learning/software](https://github.com/satellite-image-deep-learning/software)** — Curated list of software for satellite & aerial imagery ML: frameworks (TorchGeo, Raster Vision), **Label Maker** (pair OSM + satellite tiles for ML-ready data), image chipping/tiling, STAC, and QGIS plugins.
- **Label Maker** — Pairs satellite imagery with OpenStreetMap vector data to create training datasets; useful if you want to train or run models that segment buildings, roads, or land use.
- **Raster Vision, TorchGeo, segmentation tools** — For server-side or Python pipelines that segment imagery (buildings, trees, etc.) and export vectors; you can run these externally and import the resulting GeoJSON or DXF into your workflow.
- **Tile downloaders & COG tools** — The list includes MapTilesDownloader, sentinelsat, and Cloud Optimized GeoTIFF tools if you need different imagery sources or formats.
Run this app for quick OSM-based DXF + optional edge trace; use the [software list](https://github.com/satellite-image-deep-learning/software) when you need ML-based segmentation or custom training data.
+51
View File
@@ -0,0 +1,51 @@
@echo off
title MAPS to DXF
cd /d "%~dp0"
where node >nul 2>&1
if %errorlevel% neq 0 (
echo Node.js not found. Installing via Windows Package Manager...
winget install OpenJS.NodeJS.LTS --accept-package-agreements --accept-source-agreements 2>nul
if %errorlevel% neq 0 (
echo.
echo Could not install Node.js automatically. Opening download page...
start https://nodejs.org/
echo.
echo After installing Node.js, close this window and double-click Start.bat again.
pause
exit /b 1
)
echo.
echo Node.js installed. Please close this window, then double-click Start.bat again.
pause
exit /b 0
)
if not exist "node_modules" (
echo Installing dependencies...
call npm install
) else if not exist "node_modules\multer" (
echo Installing missing dependencies...
call npm install
)
if exist "ml_server\segment_server.py" (
where python >nul 2>&1
if %errorlevel% equ 0 (
start "MAPS to DXF - ML Server" cmd /k "call %~sdp0Start_ML_Server.bat"
timeout /t 2 /nobreak >nul
) else (
where py >nul 2>&1
if %errorlevel% equ 0 (
start "MAPS to DXF - ML Server" cmd /k "call %~sdp0Start_ML_Server.bat"
timeout /t 2 /nobreak >nul
)
)
)
echo Starting MAPS to DXF...
echo Browser will open. Keep this window open while using the app.
if exist "ml_server\segment_server.py" echo (ML server started in the other window - enable "Use server-side ML segmentation" in the app.)
echo.
call npm start
pause
+40
View File
@@ -0,0 +1,40 @@
@echo off
title MAPS to DXF - ML segmentation server
cd /d "%~dp0"
where python >nul 2>&1
if %errorlevel% neq 0 (
where py >nul 2>&1
if %errorlevel% neq 0 (
echo Python not found. Install Python from https://www.python.org/downloads/
echo Then run this script again.
pause
exit /b 1
)
set PY=py
) else (
set PY=python
)
if not exist "ml_server" (
echo ml_server folder not found.
pause
exit /b 1
)
cd ml_server
echo Installing Python dependencies...
"%PY%" -m pip install -r requirements.txt -q
if %errorlevel% neq 0 (
echo.
echo Pip install failed. Try: pip install -r requirements.txt
pause
exit /b 1
)
echo.
echo ML segmentation server starting on http://127.0.0.1:3457
echo Keep this window open while using "Use server-side ML segmentation" in the app.
echo.
"%PY%" segment_server.py
pause
+103
View File
@@ -0,0 +1,103 @@
# AI DNA — MAPS to DXF Standalone
Quick reference for AI and developers jumping back into this repo: purpose, structure, conventions, and where to change what.
---
## Purpose
- **Input:** Google Maps URL (with `@lat,lon` in the URL).
- **Output:** DXF file (+ optional PNG satellite image) for use in CAD, with map features and **user-defined lot boundaries**.
- **Flow:** URL → coordinates → Overpass (OSM) data → preview on canvas → user adds/edits lots → export DXF/PNG.
---
## Stack
- **Backend:** Node.js + Express. Single server: `server.js`.
- **Frontend:** Vanilla JS, no build step. One HTML file with inline script + one shared JS file.
- **APIs:** Overpass (OSM), ESRI World Imagery tiles (proxied by server to avoid CORS).
---
## Repo layout
```
MAPS-to-DXF-standalone/
├── server.js # Express: static files, /api/overpass, /api/tile
├── package.json # express only
├── Start.bat # Windows: install Node if missing, npm install, npm start
├── README.md # User-facing run + workflow
├── ai_dna.md # This file — project DNA for AI/developers
└── public/
├── index.html # UI + canvas + all client state and map/lot/edit logic
└── app.js # Pure functions: extractCoordinates, buildPreviewData,
# generateHighDetailDXF, appendLotsToDXF,
# appendSatelliteImageToDXF, OSM lot/concave-hull helpers
```
- **Logic lives in:** `public/index.html` (state, drawing, mouse, detection, export) and `public/app.js` (OSM→preview, OSM→lots, DXF strings).
- **Server:** Only serves static files and proxies Overpass + tile URLs; no map/lot logic.
---
## Coordinate systems
- **Lat/lon:** From Google Maps URL; origin for the map is `centerOrigin = { lat, lon }`.
- **World (meters):** All OSM and lot geometry is in meters relative to `centerOrigin` (e.g. `x` = east, `y` = north). Used in preview data, lots array, and DXF.
- **Screen:** Canvas pixel coords. `toScreen(wx, wy)` and `screenToWorld(sx, sy)` convert using `scale`, `offsetX`, `offsetY`.
- **Detection rect:** Stored in world coords: `detectionRect = { minX, maxX, minY, maxY }`. When a “selection as lot” is used, that rectangle (4 corners in world) becomes one lot polygon.
---
## Lots
- **Storage:** `lots` is an array of polygons; each polygon is an array of `{ x, y }` in **world (meters)**.
- **Drawing:** Yellow dashed outline + light fill; in Edit mode, vertices are drawn and draggable.
- **Sources of lots:**
1. **Add selection as lot** — `detectionRect` (4 corners) pushed as one polygon.
2. **Detect lots from imagery** — edge detection + contours on satellite (full view or crop to `detectionRect`); contours converted to world, simplified, min area ~80 m².
3. **OSM fallback** — if imagery detection finds nothing: site boundary (concave hull of buildings/parking) or landuse polygons, optionally snapped to imagery edges.
4. **Draw lot** — user clicks to add vertices; close with double-click or “Close lot”.
- **Edit lots:** In Edit mode, `selectedVertex = { lotIndex, vertexIndex }`; mousemove updates `lots[lotIndex][vertexIndex]` in world coords.
- **DXF:** `appendLotsToDXF(dxfContent, lots)` writes LOTS layer LINE entities in the same world (meters) system.
---
## Key UI state (index.html)
- **Map:** `centerOrigin`, `previewData`, `osmData`, `scale`, `offsetX`, `offsetY`, `showSatellite`.
- **Lots:** `lots`, `currentLot` (in progress), `drawLotMode`, `editLotMode`, `selectedVertex`.
- **Detection area:** `detectionRect`, `selectAreaMode`, `rectStart`, `rectCurrent`.
- **Canvas:** Pan (drag), zoom (wheel), resize; in Draw/Edit/Select-area modes, mouse handlers branch before pan.
---
## Where to change what
| Goal | Where |
|------|--------|
| Add a new map layer or style | `public/index.html`: `drawVectorLayer()`, `color()`; `public/app.js`: `buildPreviewData`, `generateHighDetailDXF` |
| Change lot detection (min area, thresholds) | `public/index.html`: `detectLotsFromImagery()`, `minAreaWorld`, contour/edge params |
| Change DXF layers or format | `public/app.js`: `generateHighDetailDXF`, `appendLotsToDXF`, `appendSatelliteImageToDXF` |
| Add a new API or proxy | `server.js`: new route (e.g. `/api/...`), keep CORS/tile proxy pattern |
| Change OSM query or tags | `server.js`: Overpass query string; `public/app.js`: tag handling in `buildPreviewData` / `generateHighDetailDXF` |
| Fix coordinate math | `public/index.html`: `worldToLatLon`, `latLonToWorld`, `toScreen`, `screenToWorld`; tile helpers for extent/zoom |
| Add a new button/mode | `public/index.html`: new button, new state flag, branch in mousedown/mousemove/mouseup, and in `draw()` / `drawLotsLayer()` |
---
## Conventions
- **No build step** — edit `public/index.html` and `public/app.js`; refresh browser.
- **World = meters from origin** — keep all persistent geometry (preview, lots, DXF) in world coords; convert to/from screen only at draw and input.
- **Lots are closed polygons** — stored as lists of vertices; first and last are not duplicated; DXF writes segments between consecutive and last→first.
- **Server is stateless** — no session; all map/lot state lives in the client. Export is client-side (blob download).
---
## Quick test
1. Run `npm start`, open http://localhost:3456.
2. Paste a Google Maps URL with `@lat,lon`, click Load preview.
3. Enable satellite, use “Select detection area” → “Add selection as lot” → “Edit lots” to move a corner → Export DXF. Check DXF + PNG in same folder.
+36
View File
@@ -0,0 +1,36 @@
# ML segmentation server for MAPS-to-DXF
Run this server to enable **Use server-side ML segmentation** in the app. It traces buildings, trees, and lots from satellite imagery.
## Run
```bash
pip install -r requirements.txt
python segment_server.py
```
Or double-click **Start_ML_Server.bat** from the project root.
Server listens on **http://127.0.0.1:3457**. The Node app proxies `/api/segment` to it.
## Backends
**Default: OpenCV** (Canny + contours)
- **Canny** edge detection (50, 150) on blurred, contrast-stretched grayscale.
- **RETR_EXTERNAL** so only outer contours are used.
Ref: [jydhasan/google_map_trace](https://github.com/jydhasan/google_map_trace).
- **approxPolyDP** with epsilon = 1% of contour perimeter.
- Classification by area/compactness; contours &lt; 15 m² skipped.
**Optional: Threshold mode (map-style)** (enable “Threshold mode (map-style)” in the app)
- Inspired by [NYPL map-vectorizer](https://github.com/nypl-spacetime/map-vectorizer): brightness + contrast then threshold to get a binary image (dark = features, light = background), then contours.
- Good for line-drawing imagery or high-contrast maps (e.g. scanned plans). Same contour classification as the default path.
- Optional form params: `brightness` (default 0), `contrast` (default 1.0), `thresholdBlack` (default 160), `thresholdWhite` (default 255). Dark pixels below `thresholdBlack` become foreground.
**Optional: VTracer** (enable “Use VTracer (cleaner vectors)” in the app, or set `USE_VTRACER=1`)
- [visioncortex VTracer](https://github.com/visioncortex/vtracer): raster → SVG, O(n), compact output.
- `pip install vtracer` in this folder, then use the checkbox or env var.
- Uses binary/line-art mode and filter_speckle for cleaner building outlines.
+5
View File
@@ -0,0 +1,5 @@
flask>=2.0
opencv-python-headless>=4.5
numpy>=1.20
# Optional: pip install vtracer for alternative vectorization (cleaner outlines)
# vtracer>=0.6
+337
View File
@@ -0,0 +1,337 @@
"""
Server-side segmentation for MAPS-to-DXF.
Exposes POST /segment: image file + extent (minX, maxX, minY, maxY).
Returns JSON: { buildings: [{ points: [{x,y}] }], trees: [...], lots: [...] } in world meters.
Modes:
- OpenCV Canny + contours (default): good for aerial/satellite imagery.
- Threshold mode (NYPL map-vectorizer style): brightness + contrast + threshold to get
a binary image (lines/features dark, rest light), then contours. Good for line-drawing
or high-contrast maps. Inspired by https://github.com/nypl-spacetime/map-vectorizer.
Optional: pip install vtracer and set USE_VTRACER=1 for visioncortex VTracer.
"""
import os
import re
import xml.etree.ElementTree as ET
from flask import Flask, request, jsonify
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB
try:
import cv2
import numpy as np
HAS_OPENCV = True
except ImportError:
HAS_OPENCV = False
try:
import vtracer
HAS_VTRACER = True
except ImportError:
HAS_VTRACER = False
def pixel_contour_to_world(contour, img_w, img_h, min_x, max_x, min_y, max_y):
"""Convert contour (Nx1x2 OpenCV format) to world coords."""
out = []
for i in range(len(contour)):
pt = contour[i]
# OpenCV contour shape is (N, 1, 2)
px = float(pt[0][0])
py = float(pt[0][1])
x = min_x + (px / img_w) * (max_x - min_x)
y = max_y - (py / img_h) * (max_y - min_y) # image y down -> world y up
out.append({'x': round(x, 4), 'y': round(y, 4)})
return out
def polygon_area_world(points):
if len(points) < 3:
return 0.0
a = 0.0
for i in range(len(points)):
j = (i + 1) % len(points)
a += points[i]['x'] * points[j]['y'] - points[j]['x'] * points[i]['y']
return abs(a) / 2.0
def polygon_perimeter_world(points):
if len(points) < 2:
return 0.0
p = 0.0
for i in range(len(points)):
a, b = points[i], points[(i + 1) % len(points)]
p += ((b['x'] - a['x']) ** 2 + (b['y'] - a['y']) ** 2) ** 0.5
return p
def classify_contour(points):
"""Classify as 'building' | 'tree' | 'lot' | None. Lots must be parcel-like (compact)."""
area = polygon_area_world(points)
perim = polygon_perimeter_world(points)
if perim < 0.5:
return None
compactness = (4 * 3.14159265359 * area) / (perim * perim)
if 2 <= area <= 55 and compactness > 0.35:
return 'tree'
if 15 <= area <= 900 and compactness > 0.10:
return 'building'
# Lots: compactness > 0.08, 150–20k m² — avoids thin strips and irregular blobs
if 150 <= area <= 20000 and compactness > 0.08:
return 'lot'
return None
def douglas_peucker(points, eps):
if len(points) <= 2:
return points
a, b = points[0], points[-1]
max_d, idx = 0.0, 0
for i in range(1, len(points) - 1):
p = points[i]
d = abs((b['y'] - a['y']) * p['x'] - (b['x'] - a['x']) * p['y'] + b['x'] * a['y'] - b['y'] * a['x'])
denom = ((b['x'] - a['x']) ** 2 + (b['y'] - a['y']) ** 2) ** 0.5
if denom > 1e-10:
d /= denom
if d > max_d:
max_d, idx = d, i
if max_d < eps:
return [a, b]
left = douglas_peucker(points[: idx + 1], eps)
right = douglas_peucker(points[idx:], eps)
return left[:-1] + right
def _contours_to_result(contours, img_bgr, min_x, max_x, min_y, max_y):
"""Shared: filter contours, simplify, convert to world coords, classify. Returns { buildings, trees, lots }."""
h, w = img_bgr.shape[:2]
buildings = []
trees = []
lots = []
for cnt in contours:
if cnt.shape[0] < 4:
continue
epsilon = 0.01 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
if approx.shape[0] < 3:
continue
pts = pixel_contour_to_world(approx, w, h, min_x, max_x, min_y, max_y)
if polygon_area_world(pts) < 15:
continue
kind = classify_contour(pts)
if kind == 'building':
buildings.append(pts)
elif kind == 'tree':
trees.append(pts)
elif kind == 'lot':
lots.append(pts)
return {'buildings': buildings, 'trees': trees, 'lots': lots}
def segment_image_opencv(img_bgr, min_x, max_x, min_y, max_y):
"""OpenCV Canny + contours + classify. Returns { buildings, trees, lots }.
Uses RETR_EXTERNAL (outer contours only) and approxPolyDP (perimeter-scaled) from
github.com/jydhasan/google_map_trace for cleaner building outlines.
"""
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
lo, hi = blurred.min(), blurred.max()
if hi > lo:
blurred = ((blurred.astype(float) - lo) / (hi - lo) * 255).astype(np.uint8)
edges = cv2.Canny(blurred, 50, 150)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return _contours_to_result(contours, img_bgr, min_x, max_x, min_y, max_y)
def segment_image_threshold(img_bgr, min_x, max_x, min_y, max_y, brightness=0, contrast=1.0,
threshold_black=160, threshold_white=255):
"""NYPL map-vectorizer style: brightness + contrast then threshold to binary (dark = features).
Good for line-drawing or high-contrast maps. Dark pixels (below threshold_black) become
foreground; contour extraction and classification same as Canny path.
See https://github.com/nypl-spacetime/map-vectorizer
"""
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Brightness = add constant; contrast = multiply (GIMP-style)
prep = (blurred.astype(np.float32) * contrast + brightness).clip(0, 255).astype(np.uint8)
# Dark pixels (lines/features) -> white (255) so findContours gets them as foreground
_, binary = cv2.threshold(prep, threshold_black, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return _contours_to_result(contours, img_bgr, min_x, max_x, min_y, max_y)
def _parse_svg_path_d_to_polygons(d_string):
"""Parse SVG path 'd' attribute; return list of polygons as [(x,y), ...] in pixel space.
Handles M, L, Z (absolute coords only).
"""
if not d_string or not d_string.strip():
return []
polygons = []
tokens = re.findall(r'[MLHVCSQTAZ]|-?\d*\.?\d+(?:[eE][-+]?\d+)?', d_string)
i = 0
points = []
while i < len(tokens):
t = tokens[i]
if t.upper() in 'MLHVCSQTAZ':
cmd = t.upper()
i += 1
if cmd == 'M':
if points and len(points) >= 3:
polygons.append(points)
points = []
if i + 2 <= len(tokens):
try:
points.append((float(tokens[i]), float(tokens[i + 1])))
i += 2
except ValueError:
pass
elif cmd == 'L':
while i + 2 <= len(tokens) and tokens[i] not in 'MLHVCSQTAZ':
try:
points.append((float(tokens[i]), float(tokens[i + 1])))
i += 2
except ValueError:
break
elif cmd == 'Z':
if points and len(points) >= 3:
polygons.append(points)
points = []
else:
pass # skip H V C S Q T A for now
else:
i += 1
if points and len(points) >= 3:
polygons.append(points)
return polygons
def segment_image_vtracer(img_bgr, min_x, max_x, min_y, max_y):
"""Vectorize with VTracer (raster to SVG), parse paths, convert to world, classify.
Uses binary/line-art mode and filter_speckle for cleaner building outlines.
"""
import vtracer
h, w = img_bgr.shape[:2]
_, buf = cv2.imencode('.png', img_bgr)
img_bytes = buf.tobytes()
try:
# colormode='binary' for line-art; filter_speckle to drop small shapes (cars, noise)
svg_str = vtracer.convert_raw_image_to_svg(
img_bytes, img_format='png',
colormode='binary',
filter_speckle=4,
mode='polygon',
)
except Exception as e:
raise RuntimeError('VTracer conversion failed: ' + str(e))
if not svg_str or '<path' not in svg_str:
return {'buildings': [], 'trees': [], 'lots': []}
# Parse SVG: get viewBox or size for scale
root = ET.fromstring(svg_str)
vb = root.get('viewBox') or ''
if vb:
parts = vb.split()
if len(parts) >= 4:
vw, vh = float(parts[2]), float(parts[3])
else:
vw, vh = w, h
else:
vw, vh = float(root.get('width', w)), float(root.get('height', h))
scale_x = (max_x - min_x) / vw if vw else 1.0
scale_y = (max_y - min_y) / vh if vh else 1.0
buildings = []
trees = []
lots = []
for path_el in root.iter():
if 'path' not in path_el.tag:
continue
d = path_el.get('d')
if not d:
continue
for poly_px in _parse_svg_path_d_to_polygons(d):
if len(poly_px) < 3:
continue
pts = []
for px, py in poly_px:
x = min_x + (px / vw) * (max_x - min_x)
y = max_y - (py / vh) * (max_y - min_y)
pts.append({'x': round(x, 4), 'y': round(y, 4)})
if polygon_area_world(pts) < 15:
continue
kind = classify_contour(pts)
if kind == 'building':
buildings.append(pts)
elif kind == 'tree':
trees.append(pts)
elif kind == 'lot':
lots.append(pts)
return {'buildings': buildings, 'trees': trees, 'lots': lots}
def _parse_float_form(key, default):
v = request.form.get(key)
if v is None or v == '':
return default
try:
return float(v)
except (TypeError, ValueError):
return default
@app.route('/segment', methods=['POST'])
def segment():
use_vtracer = os.environ.get('USE_VTRACER', '').lower() in ('1', 'true', 'yes')
use_vtracer = use_vtracer or (request.form.get('useVtracer', '').lower() in ('1', 'true', 'yes'))
use_threshold = request.form.get('useThreshold', '').lower() in ('1', 'true', 'yes')
if use_vtracer and HAS_VTRACER:
backend = 'vtracer'
elif use_threshold and HAS_OPENCV:
backend = 'threshold'
elif HAS_OPENCV:
backend = 'opencv'
else:
return jsonify({'error': 'OpenCV not installed. pip install opencv-python-headless numpy'}), 503
if use_vtracer and not HAS_VTRACER:
return jsonify({'error': 'USE_VTRACER requested but vtracer not installed. pip install vtracer'}), 503
f = request.files.get('image')
if not f:
return jsonify({'error': 'Missing image file'}), 400
try:
min_x = float(request.form.get('minX', 0))
max_x = float(request.form.get('maxX', 0))
min_y = float(request.form.get('minY', 0))
max_y = float(request.form.get('maxY', 0))
except (TypeError, ValueError):
return jsonify({'error': 'Invalid extent (minX, maxX, minY, maxY)'}), 400
try:
buf = f.read()
nparr = np.frombuffer(buf, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if img is None:
return jsonify({'error': 'Could not decode image'}), 400
if backend == 'vtracer':
result = segment_image_vtracer(img, min_x, max_x, min_y, max_y)
elif backend == 'threshold':
brightness = _parse_float_form('brightness', 0)
contrast = _parse_float_form('contrast', 1.0)
thresh_black = _parse_float_form('thresholdBlack', 160)
thresh_white = _parse_float_form('thresholdWhite', 255)
result = segment_image_threshold(
img, min_x, max_x, min_y, max_y,
brightness=brightness, contrast=contrast,
threshold_black=int(thresh_black), threshold_white=int(thresh_white))
else:
result = segment_image_opencv(img, min_x, max_x, min_y, max_y)
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/health', methods=['GET'])
def health():
return jsonify({'ok': True, 'opencv': HAS_OPENCV, 'vtracer': HAS_VTRACER})
if __name__ == '__main__':
port = int(os.environ.get('ML_PORT', 3457))
app.run(host='127.0.0.1', port=port, threaded=True)
+998
View File
@@ -0,0 +1,998 @@
{
"name": "maps-to-dxf-standalone",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "maps-to-dxf-standalone",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.2",
"multer": "^1.4.5-lts.1"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.4",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz",
"integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "~1.2.0",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.14.0",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
"engines": [
"node >= 0.8"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^2.2.2",
"typedarray": "^0.0.6"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.22.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",
"integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "~1.20.3",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
"cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.3.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
"qs": "~6.14.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
"serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
"statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"statuses": "~2.0.2",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"license": "MIT"
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"license": "MIT",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/multer": {
"version": "1.4.5-lts.2",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz",
"integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==",
"deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.0.0",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.4",
"object-assign": "^4.1.1",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
"integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==",
"license": "MIT"
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/qs": {
"version": "6.14.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
"integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/readable-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.1",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "~2.4.1",
"range-parser": "~1.2.1",
"statuses": "~2.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.3",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "~0.19.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3",
"side-channel-list": "^1.0.0",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string_decoder/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "maps-to-dxf-standalone",
"version": "1.0.0",
"description": "Standalone GUI: paste a Maps link, preview map, export DXF (no Google Sheets).",
"main": "server.js",
"scripts": { "start": "node server.js" },
"dependencies": {
"express": "^4.18.2",
"multer": "^1.4.5-lts.1"
}
}
+807
View File
@@ -0,0 +1,807 @@
/**
* Client-side logic: coords, preview data, DXF generation (ported from Apps Script).
* Supports Google Maps and Google Earth (Web) links. Google Earth view/altitude/distance
* is used to optimize the requested area (smaller = faster Overpass and imagery).
*/
function extractCoordinates(url) {
const s = String(url).trim();
// Google Maps: ...@lat,lon... Google Earth Web: ...@lat,lon... or ...@lat,lon,altitudea,distanced...
const coordRegex = /@(-?\d+\.?\d*),(-?\d+\.?\d*)/;
const coordMatch = s.match(coordRegex);
if (!coordMatch || coordMatch.length < 3) return null;
const lat = parseFloat(coordMatch[1]);
const lon = parseFloat(coordMatch[2]);
let viewMeters = undefined;
// Google Earth Web: optional altitude (e.g. ,1234a) or distance (e.g. ,50000d) in meters; order may be ,100a,50000d
const distRegex = /@-?\d+\.?\d*,-?\d+\.?\d*(?:,\d+(?:\.\d*)?\s*a)?\s*,(\d+(?:\.\d*)?)\s*d/i;
const altRegex = /@-?\d+\.?\d*,-?\d+\.?\d*,(\d+(?:\.\d*)?)\s*a/i;
const distMatch = s.match(distRegex);
const altMatch = s.match(altRegex);
if (distMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(distMatch[1])));
else if (altMatch) viewMeters = Math.min(50000, Math.max(100, parseFloat(altMatch[1]) * 2));
return { lat, lon, viewMeters };
}
var DEFAULT_LAYER_OPTIONS = {
buildings: true,
roads: true,
railways: true,
paths: true,
water: true,
parks: true,
landuse: true,
parkingOutline: true,
parkingSpaces: true,
trees: true,
barriers: true,
power: true,
boundary: true,
man_made: true
};
function getWayLayerKey(el) {
if (!el.tags) return null;
if (el.tags.railway && ['rail', 'tram', 'subway', 'light_rail', 'monorail', 'preserved'].includes(el.tags.railway)) return 'railways';
if (el.tags.building) return 'buildings';
if (el.tags.amenity === 'parking') return 'parkingOutline';
if (el.tags.landuse) return 'landuse';
if (el.tags.natural === 'water' || el.tags.water) return 'water';
if (el.tags.leisure === 'park' || el.tags.leisure === 'garden') return 'parks';
if (el.tags.barrier) return 'barriers';
if (el.tags.highway) return ['footway', 'path', 'cycleway', 'pedestrian', 'steps'].includes(el.tags.highway) ? 'paths' : 'roads';
if (el.tags.power) return 'power';
if (el.tags.boundary) return 'boundary';
if (el.tags.man_made) return 'man_made';
return null;
}
function getNodeLayerKey(tags) {
if (!tags) return null;
if (tags.natural === 'tree' || tags.natural === 'tree_row') return 'trees';
if (tags.amenity === 'parking_space') return 'parkingSpaces';
return null;
}
function buildPreviewData(osmData, origin, layerOptions) {
const opts = layerOptions || DEFAULT_LAYER_OPTIONS;
const on = function (key) { return opts[key] !== false; };
const r2 = (v) => Math.round(v * 100) / 100;
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
const out = [];
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat,
tags: el.tags
};
}
});
const s = 8;
out.push(['L', -s, 0, s, 0, 4]);
out.push(['L', 0, -s, 0, s, 4]);
out.push(['C', 0, 0, s / 1.5, 4]);
const PARKING_SPOT_HW = 1.25;
const PARKING_SPOT_HH = 2.5;
for (const id in nodes) {
const n = nodes[id];
const nodeKey = getNodeLayerKey(n.tags);
if (!nodeKey || !on(nodeKey)) continue;
if (n.tags) {
if (n.tags.natural === 'tree' || n.tags.natural === 'tree_row') {
out.push(['C', r2(n.x), r2(n.y), 2.5, 3]);
} else if (n.tags.amenity === 'parking_space') {
out.push(['R', r2(n.x), r2(n.y), PARKING_SPOT_HW, PARKING_SPOT_HH, 9]);
}
}
}
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
let color = '7';
let isRoad = false;
let roadHalfWidth = 0;
let isRail = false;
if (el.tags) {
if (el.tags.railway && ['rail', 'tram', 'subway', 'light_rail', 'monorail', 'preserved'].includes(el.tags.railway)) {
isRail = true;
color = '6';
} else if (el.tags.building) color = '1';
else if (el.tags.amenity === 'parking') color = '9';
else if (el.tags.landuse) color = '253';
else if (el.tags.natural === 'water' || el.tags.water) color = '5';
else if (el.tags.leisure === 'park' || el.tags.leisure === 'garden') color = '3';
else if (el.tags.barrier) color = '8';
else if (el.tags.power) color = '8';
else if (el.tags.boundary) color = '253';
else if (el.tags.man_made) color = '8';
else if (el.tags.highway) {
if (['footway', 'path', 'cycleway', 'pedestrian', 'steps'].includes(el.tags.highway)) color = '2';
else {
isRoad = true;
if (['motorway', 'trunk'].includes(el.tags.highway)) roadHalfWidth = 8;
else if (['primary', 'secondary'].includes(el.tags.highway)) roadHalfWidth = 5;
else if (el.tags.highway === 'service') roadHalfWidth = 2.5;
else roadHalfWidth = 3;
if (['motorway', 'trunk'].includes(el.tags.highway)) color = '6';
else if (['primary', 'secondary'].includes(el.tags.highway)) color = '4';
else if (el.tags.highway === 'service') color = '8';
else color = '2';
}
}
}
for (let i = 0; i < el.nodes.length - 1; i++) {
const n1 = nodes[el.nodes[i]];
const n2 = nodes[el.nodes[i + 1]];
if (!n1 || !n2) continue;
const dx = n2.x - n1.x;
const dy = n2.y - n1.y;
const len = Math.sqrt(dx * dx + dy * dy);
let nx = 0, ny = 0;
if (len > 0) {
nx = -dy / len;
ny = dx / len;
}
if (isRail && len > 0) {
const halfGauge = 0.72, tieSpacing = 2.0, tieHalfLen = 1.2, ux = dx / len, uy = dy / len;
out.push(['L', r2(n1.x + nx * halfGauge), r2(n1.y + ny * halfGauge), r2(n2.x + nx * halfGauge), r2(n2.y + ny * halfGauge), 6]);
out.push(['L', r2(n1.x - nx * halfGauge), r2(n1.y - ny * halfGauge), r2(n2.x - nx * halfGauge), r2(n2.y - ny * halfGauge), 6]);
if (len < tieSpacing) {
const midX = (n1.x + n2.x) / 2, midY = (n1.y + n2.y) / 2;
out.push(['L', r2(midX - nx * tieHalfLen), r2(midY - ny * tieHalfLen), r2(midX + nx * tieHalfLen), r2(midY + ny * tieHalfLen), 8]);
} else {
for (let dist = 0; dist <= len; dist += tieSpacing) {
const posX = n1.x + ux * dist, posY = n1.y + uy * dist;
out.push(['L', r2(posX - nx * tieHalfLen), r2(posY - ny * tieHalfLen), r2(posX + nx * tieHalfLen), r2(posY + ny * tieHalfLen), 8]);
}
}
} else if (isRoad && roadHalfWidth > 0 && len > 0) {
out.push(['L', r2(n1.x + nx * roadHalfWidth), r2(n1.y + ny * roadHalfWidth), r2(n2.x + nx * roadHalfWidth), r2(n2.y + ny * roadHalfWidth), color]);
out.push(['L', r2(n1.x - nx * roadHalfWidth), r2(n1.y - ny * roadHalfWidth), r2(n2.x - nx * roadHalfWidth), r2(n2.y - ny * roadHalfWidth), color]);
} else {
out.push(['L', r2(n1.x), r2(n1.y), r2(n2.x), r2(n2.y), color]);
}
}
});
return out;
}
function generateHighDetailDXF(osmData, origin, layerOptions) {
const opts = layerOptions || DEFAULT_LAYER_OPTIONS;
const on = function (key) { return opts[key] !== false; };
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat,
tags: el.tags
};
}
});
let dxf = '0\nSECTION\n2\nHEADER\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n';
dxf += '0\nLTYPE\n2\nDASHED\n70\n0\n3\n_ _ _ _ _ _\n72\n65\n73\n2\n40\n2.0\n49\n1.25\n49\n-0.75\n0\nENDTAB\n0\nENDSEC\n';
dxf += '0\nSECTION\n2\nENTITIES\n';
const s = 8;
dxf += `0\nLINE\n8\nLOCATION_MARKER\n62\n4\n10\n-${s}\n20\n0\n11\n${s}\n21\n0\n`;
dxf += `0\nLINE\n8\nLOCATION_MARKER\n62\n4\n10\n0\n20\n-${s}\n11\n0\n21\n${s}\n`;
dxf += `0\nCIRCLE\n8\nLOCATION_MARKER\n62\n4\n10\n0\n20\n0\n40\n${s / 1.5}\n`;
const PARKING_HW = 1.25;
const PARKING_HH = 2.5;
for (const id in nodes) {
const n = nodes[id];
const nodeKey = getNodeLayerKey(n.tags);
if (!nodeKey || !on(nodeKey)) continue;
if (n.tags) {
if (n.tags.natural === 'tree' || n.tags.natural === 'tree_row') {
dxf += `0\nCIRCLE\n8\nLANDSCAPE_TREES\n62\n3\n10\n${n.x}\n20\n${n.y}\n40\n2.5\n`;
} else if (n.tags.amenity === 'parking_space') {
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x - PARKING_HW}\n20\n${n.y - PARKING_HH}\n11\n${n.x + PARKING_HW}\n21\n${n.y - PARKING_HH}\n`;
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x + PARKING_HW}\n20\n${n.y - PARKING_HH}\n11\n${n.x + PARKING_HW}\n21\n${n.y + PARKING_HH}\n`;
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x + PARKING_HW}\n20\n${n.y + PARKING_HH}\n11\n${n.x - PARKING_HW}\n21\n${n.y + PARKING_HH}\n`;
dxf += `0\nLINE\n8\nPARKING_SPACES\n62\n1\n10\n${n.x - PARKING_HW}\n20\n${n.y + PARKING_HH}\n11\n${n.x - PARKING_HW}\n21\n${n.y - PARKING_HH}\n`;
}
}
}
function addHatchForPolygon(layerName, points, colorCode, patternName, scale) {
if (!points || points.length < 3) return '';
const n = points.length;
const sc = scale != null ? scale : 1;
let s = `0\nHATCH\n8\n${layerName}\n62\n${colorCode}\n2\n${patternName}\n70\n1\n71\n0\n41\n${sc}\n91\n1\n92\n2\n93\n${n}\n72\n0\n73\n1\n`;
points.forEach(function(p) { s += `10\n${p.x}\n20\n${p.y}\n`; });
return s;
}
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 4) return;
if (el.nodes[0] !== el.nodes[el.nodes.length - 1]) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
const points = [];
for (let i = 0; i < el.nodes.length - 1; i++) {
const nn = nodes[el.nodes[i]];
if (nn) points.push({ x: nn.x, y: nn.y });
}
if (points.length < 3) return;
if (el.tags && el.tags.building) {
dxf += addHatchForPolygon('BUILDINGS_HATCH', points, 1, 'ANSI31', 0.8);
} else if (el.tags && el.tags.landuse) {
dxf += addHatchForPolygon('OPEN_LAND', points, 3, 'ANSI31', 0.5);
}
});
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
const wayKey = getWayLayerKey(el);
if (!wayKey || !on(wayKey)) return;
let layer = '0', color = '7', isRoad = false, roadHalfWidth = 0, isRail = false, lineType = 'CONTINUOUS';
if (el.tags) {
if (el.tags.railway && ['rail', 'tram', 'subway', 'light_rail', 'monorail', 'preserved'].includes(el.tags.railway)) {
isRail = true;
layer = 'RAILWAY_RAILS';
color = '6';
} else if (el.tags.building) {
layer = 'BUILDINGS';
color = '1';
} else if (el.tags.amenity === 'parking') {
layer = 'PARKING_OUTLINE';
color = '1'; /* red (original site-plan) */
} else if (el.tags.landuse) {
layer = 'SITE_BOUNDARIES';
color = '253';
lineType = 'DASHED';
} else if (el.tags.natural === 'water' || el.tags.water) {
layer = 'WATER';
color = '5';
} else if (el.tags.leisure === 'park' || el.tags.leisure === 'garden') {
layer = 'PARKS';
color = '3';
} else if (el.tags.barrier) {
layer = 'SITE_FENCES';
color = '8';
} else if (el.tags.power) {
layer = 'POWER';
color = '8';
} else if (el.tags.boundary) {
layer = 'BOUNDARY';
color = '253';
lineType = 'DASHED';
} else if (el.tags.man_made) {
layer = 'MAN_MADE';
color = '8';
} else if (el.tags.highway) {
if (['footway', 'path', 'cycleway', 'pedestrian', 'steps'].includes(el.tags.highway)) {
layer = 'ROADS_PATH';
color = '2';
} else {
isRoad = true;
if (['motorway', 'trunk'].includes(el.tags.highway)) {
layer = 'ROADS_HIGHWAY';
color = '6';
roadHalfWidth = 8;
} else if (['primary', 'secondary'].includes(el.tags.highway)) {
layer = 'ROADS_MAJOR';
color = '4';
roadHalfWidth = 5;
} else if (el.tags.highway === 'service') {
layer = 'ROADS_SERVICE';
color = '8';
roadHalfWidth = 2.5;
} else {
layer = 'ROADS_MINOR';
color = '2';
roadHalfWidth = 3;
}
}
}
}
for (let i = 0; i < el.nodes.length - 1; i++) {
const n1 = nodes[el.nodes[i]];
const n2 = nodes[el.nodes[i + 1]];
if (!n1 || !n2) continue;
const dx = n2.x - n1.x;
const dy = n2.y - n1.y;
const len = Math.sqrt(dx * dx + dy * dy);
let nx = 0, ny = 0;
if (len > 0) {
nx = -dy / len;
ny = dx / len;
}
if (isRail && len > 0) {
const halfGauge = 0.72, tieSpacing = 2.0, tieHalfLen = 1.2, ux = dx / len, uy = dy / len;
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x + nx * halfGauge}\n20\n${n1.y + ny * halfGauge}\n11\n${n2.x + nx * halfGauge}\n21\n${n2.y + ny * halfGauge}\n`;
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x - nx * halfGauge}\n20\n${n1.y - ny * halfGauge}\n11\n${n2.x - nx * halfGauge}\n21\n${n2.y - ny * halfGauge}\n`;
if (len < tieSpacing) {
const midX = (n1.x + n2.x) / 2, midY = (n1.y + n2.y) / 2;
dxf += `0\nLINE\n8\nRAILWAY_TIES\n62\n8\n10\n${midX - nx * tieHalfLen}\n20\n${midY - ny * tieHalfLen}\n11\n${midX + nx * tieHalfLen}\n21\n${midY + ny * tieHalfLen}\n`;
} else {
for (let dist = 0; dist <= len; dist += tieSpacing) {
const posX = n1.x + ux * dist, posY = n1.y + uy * dist;
dxf += `0\nLINE\n8\nRAILWAY_TIES\n62\n8\n10\n${posX - nx * tieHalfLen}\n20\n${posY - ny * tieHalfLen}\n11\n${posX + nx * tieHalfLen}\n21\n${posY + ny * tieHalfLen}\n`;
}
}
} else if (isRoad && roadHalfWidth > 0 && len > 0) {
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x + nx * roadHalfWidth}\n20\n${n1.y + ny * roadHalfWidth}\n11\n${n2.x + nx * roadHalfWidth}\n21\n${n2.y + ny * roadHalfWidth}\n`;
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n10\n${n1.x - nx * roadHalfWidth}\n20\n${n1.y - ny * roadHalfWidth}\n11\n${n2.x - nx * roadHalfWidth}\n21\n${n2.y - ny * roadHalfWidth}\n`;
} else {
dxf += `0\nLINE\n8\n${layer}\n62\n${color}\n6\n${lineType}\n10\n${n1.x}\n20\n${n1.y}\n11\n${n2.x}\n21\n${n2.y}\n`;
}
}
if (el.tags && el.tags.name && (isRoad || isRail)) {
const midIdx = Math.floor((el.nodes.length - 1) / 2);
const p1 = nodes[el.nodes[midIdx]];
const p2 = nodes[el.nodes[midIdx + 1]];
if (p1 && p2) {
const pdx = p2.x - p1.x, pdy = p2.y - p1.y;
let angle = (Math.atan2(pdy, pdx) * 180) / Math.PI;
if (angle > 90) angle -= 180;
if (angle < -90) angle += 180;
const mx = (p1.x + p2.x) / 2, my = (p1.y + p2.y) / 2;
const safeName = String(el.tags.name).replace(/[\\{}]/g, '');
const txtLayer = isRail ? 'LABELS_RAIL' : 'LABELS_ROADS';
dxf += `0\nTEXT\n8\n${txtLayer}\n62\n7\n10\n${mx}\n20\n${my}\n40\n5.0\n50\n${angle}\n1\n${safeName}\n72\n1\n73\n2\n11\n${mx}\n21\n${my}\n`;
}
}
});
dxf += '0\nENDSEC\n0\nEOF';
return dxf;
}
/**
* Convex hull (Graham scan). Returns hull points in CCW order.
*/
function convexHull(points) {
if (points.length < 3) return points.slice();
const pts = points.slice();
const start = pts.reduce((min, p, i) => (p.y < min.y || (p.y === min.y && p.x < min.x)) ? p : min, pts[0]);
pts.sort((a, b) => {
const ax = a.x - start.x, ay = a.y - start.y;
const bx = b.x - start.x, by = b.y - start.y;
const cross = ax * by - ay * bx;
if (Math.abs(cross) > 1e-10) return cross > 0 ? -1 : 1;
return (ax * ax + ay * ay) - (bx * bx + by * by);
});
const hull = [pts[0], pts[1]];
for (let i = 2; i < pts.length; i++) {
let p = pts[i];
while (hull.length >= 2) {
const a = hull[hull.length - 2], b = hull[hull.length - 1];
const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
if (cross <= 0) hull.pop();
else break;
}
hull.push(p);
}
return hull;
}
const CLUSTER_DISTANCE_METERS = 75;
const MAX_SITE_AREA = 25000;
const MAX_EDGE_METERS = 38;
function segmentIntersect(a1, a2, b1, b2) {
const ax = a2.x - a1.x, ay = a2.y - a1.y;
const bx = b2.x - b1.x, by = b2.y - b1.y;
const d = ax * by - ay * bx;
if (Math.abs(d) < 1e-10) return false;
const t = ((b1.x - a1.x) * by - (b1.y - a1.y) * bx) / d;
const u = ((b1.x - a1.x) * ay - (b1.y - a1.y) * ax) / d;
return t > 1e-6 && t < 1 - 1e-6 && u > 1e-6 && u < 1 - 1e-6;
}
function pointInPolygon(p, poly) {
let inside = false;
const n = poly.length;
for (let i = 0, j = n - 1; i < n; j = i++) {
const xi = poly[i].x, yi = poly[i].y, xj = poly[j].x, yj = poly[j].y;
if (((yi > p.y) !== (yj > p.y)) && (p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi)) inside = !inside;
}
return inside;
}
/**
* Concave hull: tighten convex hull by splitting edges longer than maxEdge.
* Keeps boundary closer to buildings so it's less likely to cross roads/lot lines.
*/
function concaveHull(points, maxEdge) {
if (points.length < 3) return points.slice();
let hull = convexHull(points);
const max2 = maxEdge * maxEdge;
for (let round = 0; round < 50; round++) {
let changed = false;
for (let i = 0; i < hull.length; i++) {
const a = hull[i];
const b = hull[(i + 1) % hull.length];
const len2 = (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
if (len2 <= max2) continue;
let best = null;
let bestMax2 = len2;
for (const p of points) {
if (p === a || p === b) continue;
const d1 = (p.x - a.x) ** 2 + (p.y - a.y) ** 2;
const d2 = (p.x - b.x) ** 2 + (p.y - b.y) ** 2;
if (d1 >= len2 || d2 >= len2) continue;
const testHull = hull.slice(0, i + 1).concat([p], hull.slice(i + 1));
let cross = false;
for (let j = 0; j < testHull.length && !cross; j++) {
const c = testHull[j], d = testHull[(j + 1) % testHull.length];
if (c === a || c === b || c === p || d === a || d === b || d === p) continue;
if (segmentIntersect(a, p, c, d) || segmentIntersect(p, b, c, d)) cross = true;
}
if (cross) continue;
const mp = Math.max(d1, d2);
if (mp < bestMax2) {
bestMax2 = mp;
best = p;
}
}
if (best) {
hull = hull.slice(0, i + 1).concat([best], hull.slice(i + 1));
changed = true;
break;
}
}
if (!changed) break;
}
return hull;
}
/**
* Site boundary = concave hull per cluster (tighter than convex so boundaries don't cross roads).
* Clusters buildings within ~75m; uses max edge length so lot lines/gaps are respected.
*/
function getOSMSiteBoundaryAsLot(osmData, origin) {
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat
};
}
});
const features = [];
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 3) return;
const closed = el.nodes[0] === el.nodes[el.nodes.length - 1];
const isBuilding = el.tags && el.tags.building;
const isParking = el.tags && el.tags.amenity === 'parking';
if (!closed || (!isBuilding && !isParking)) return;
const points = [];
for (let i = 0; i < el.nodes.length - 1; i++) {
const n = nodes[el.nodes[i]];
if (n) points.push({ x: n.x, y: n.y });
}
if (points.length < 3) return;
const cx = points.reduce((s, p) => s + p.x, 0) / points.length;
const cy = points.reduce((s, p) => s + p.y, 0) / points.length;
features.push({ points, centroid: { x: cx, y: cy } });
});
if (features.length === 0) return [];
const clusters = [];
for (const f of features) {
let best = -1;
let bestDist = CLUSTER_DISTANCE_METERS;
for (let i = 0; i < clusters.length; i++) {
const c = clusters[i];
const d = Math.hypot(f.centroid.x - c.cx, f.centroid.y - c.cy);
if (d < bestDist) {
bestDist = d;
best = i;
}
}
if (best >= 0) {
const c = clusters[best];
c.points.push(...f.points);
const n = c.count + 1;
c.cx = (c.cx * c.count + f.centroid.x) / n;
c.cy = (c.cy * c.count + f.centroid.y) / n;
c.count = n;
} else {
clusters.push({
points: f.points.slice(),
cx: f.centroid.x,
cy: f.centroid.y,
count: 1
});
}
}
const polygons = [];
for (const c of clusters) {
if (c.points.length < 3) continue;
const hull = concaveHull(c.points, MAX_EDGE_METERS);
const area = polygonAreaOSM(hull);
if (area >= 100 && area <= MAX_SITE_AREA) polygons.push(hull);
}
return polygons;
}
/**
* Get closed OSM landuse-only polygons as lot candidates (no buildings).
* Used when imagery finds no contours. For "whole property" use getOSMSiteBoundaryAsLot instead.
*/
function getOSMLotsAsPolygons(osmData, origin) {
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat
};
}
});
const polygons = [];
const MAX_LOT_AREA = 8000;
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 4) return;
const closed = el.nodes[0] === el.nodes[el.nodes.length - 1];
if (!closed) return;
if (!el.tags || !el.tags.landuse) return;
const poly = [];
for (let i = 0; i < el.nodes.length - 1; i++) {
const n = nodes[el.nodes[i]];
if (n) poly.push({ x: n.x, y: n.y });
}
if (poly.length >= 3) {
const area = polygonAreaOSM(poly);
if (area >= 20 && area <= MAX_LOT_AREA) polygons.push(poly);
}
});
return polygons;
}
function polygonAreaOSM(points) {
let a = 0;
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
a += points[i].x * points[j].y - points[j].x * points[i].y;
}
return Math.abs(a) / 2;
}
/**
* Append user-drawn lot polygons to DXF (same coordinate system as map).
* lots: array of polygons, each polygon = array of { x, y } in meters from origin.
*/
function appendLotsToDXF(dxfContent, lots) {
if (!lots || lots.length === 0) return dxfContent;
let block = '';
lots.forEach((poly) => {
if (!poly || poly.length < 2) return;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
block += `0\nLINE\n8\nLOTS\n62\n40\n10\n${a.x}\n20\n${a.y}\n11\n${b.x}\n21\n${b.y}\n`;
}
});
return dxfContent.replace('0\nENDSEC\n0\nEOF', block + '0\nENDSEC\n0\nEOF');
}
/**
* Polygon area in world coords (m²). Poly is array of { x, y }, closed.
*/
function polygonAreaWorld(poly) {
if (!poly || poly.length < 3) return 0;
let a = 0;
for (let i = 0; i < poly.length; i++) {
const j = (i + 1) % poly.length;
a += poly[i].x * poly[j].y - poly[j].x * poly[i].y;
}
return Math.abs(a) / 2;
}
/**
* Polygon perimeter in world coords (meters).
*/
function polygonPerimeter(poly) {
if (!poly || poly.length < 2) return 0;
let p = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
p += Math.hypot(b.x - a.x, b.y - a.y);
}
return p;
}
/**
* Classify an imagery contour for land-lot drawing: 'tree' | 'building' | 'lot' | null.
* Trees: small, round. Buildings: medium, compact. Lots: parcel-like (compact, not thin strips).
*/
function classifyImageryContour(poly) {
if (!poly || poly.length < 3) return null;
const area = polygonAreaWorld(poly);
const perim = polygonPerimeter(poly);
if (perim < 0.5) return null;
const compactness = (4 * Math.PI * area) / (perim * perim);
if (area >= 2 && area <= 55 && compactness > 0.35) return 'tree';
if (area >= 15 && area <= 900 && compactness > 0.10) return 'building';
// Lots: parcel-like shape (compactness > 0.08), 150–20k m² — avoids thin strips and noise
if (area >= 150 && area <= 20000 && compactness > 0.08) return 'lot';
return null;
}
/**
* Filter imagery polylines to only those suitable for land lot drawings (trees, buildings, lots).
* Returns { trees: [], buildings: [], lots: [], all: [] }.
*/
function filterImageryPolylinesForLotDrawing(polylines) {
const out = { trees: [], buildings: [], lots: [], all: [] };
if (!polylines || !polylines.length) return out;
polylines.forEach((poly) => {
const kind = classifyImageryContour(poly);
if (!kind) return;
out[kind].push(poly);
out.all.push(poly);
});
return out;
}
/**
* Build nodes map { id: { x, y, tags } } in meters from origin. Used for OSM snap and DXF.
*/
function getOSMNodesInMeters(osmData, origin) {
if (!osmData || !origin) return {};
const nodes = {};
const metersPerLat = 111132.92;
const metersPerLon = 111412.84 * Math.cos((origin.lat * Math.PI) / 180);
osmData.elements.forEach((el) => {
if (el.type === 'node') {
nodes[el.id] = {
x: (el.lon - origin.lon) * metersPerLon,
y: (el.lat - origin.lat) * metersPerLat,
tags: el.tags || {}
};
}
});
return nodes;
}
/**
* Collect OSM way segments (buildings, roads, etc.) for snapping. Returns array of { a: {x,y}, b: {x,y} }.
*/
function getOSMSnapSegments(osmData, nodes) {
if (!osmData || !osmData.elements || !nodes) return [];
const segments = [];
osmData.elements.forEach((el) => {
if (el.type !== 'way' || !el.nodes || el.nodes.length < 2) return;
const hasBuilding = el.tags && el.tags.building;
const hasHighway = el.tags && el.tags.highway;
const hasLanduse = el.tags && el.tags.landuse;
if (!hasBuilding && !hasHighway && !hasLanduse) return;
for (let i = 0; i < el.nodes.length - 1; i++) {
const n1 = nodes[el.nodes[i]];
const n2 = nodes[el.nodes[i + 1]];
if (n1 && n2) segments.push({ a: { x: n1.x, y: n1.y }, b: { x: n2.x, y: n2.y } });
}
});
return segments;
}
/**
* Project point p onto segment a-b. Returns { x, y, dist } of closest point and distance.
*/
function projectPointOnSegment(p, a, b) {
const dx = b.x - a.x, dy = b.y - a.y;
const lenSq = dx * dx + dy * dy;
if (lenSq < 1e-20) return { x: a.x, y: a.y, dist: Math.hypot(p.x - a.x, p.y - a.y) };
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq;
t = Math.max(0, Math.min(1, t));
const x = a.x + t * dx, y = a.y + t * dy;
return { x, y, dist: Math.hypot(p.x - x, p.y - y) };
}
/**
* Snap imagery trace polylines to OSM ways (buildings, roads, landuse) within maxSnapMeters.
* Returns new array of polylines with points snapped to nearest OSM segment when within distance.
*/
function snapTracePolylinesToOSM(polylines, osmData, nodes, maxSnapMeters) {
if (!polylines || polylines.length === 0) return polylines;
const segments = getOSMSnapSegments(osmData, nodes);
if (segments.length === 0) return polylines;
const maxD = maxSnapMeters != null ? maxSnapMeters : 1.5;
return polylines.map((poly) => {
if (!poly || poly.length < 2) return poly;
return poly.map((p) => {
let best = { x: p.x, y: p.y, dist: Infinity };
for (let i = 0; i < segments.length; i++) {
const proj = projectPointOnSegment(p, segments[i].a, segments[i].b);
if (proj.dist < best.dist && proj.dist <= maxD) best = { x: proj.x, y: proj.y, dist: proj.dist };
}
return { x: best.x, y: best.y };
});
});
}
/**
* Append vectorized satellite/imagery edges to DXF as lines.
* polylines: array of polylines. layerName: DXF layer (default IMAGERY_TRACE).
* minSegmentMeters, minLengthMeters: filter very short segments/lines.
*/
function appendImageryTraceToDXF(dxfContent, polylines, minSegmentMeters, minLengthMeters, layerName) {
if (!polylines || polylines.length === 0) return dxfContent;
const minSeg = minSegmentMeters != null ? minSegmentMeters : 0.2;
const minLen = minLengthMeters != null ? minLengthMeters : 0.5;
const layer = layerName || 'IMAGERY_TRACE';
let block = '';
polylines.forEach((poly) => {
if (!poly || poly.length < 2) return;
let totalLen = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
totalLen += Math.hypot(b.x - a.x, b.y - a.y);
}
if (totalLen < minLen) return;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
const len = Math.hypot(b.x - a.x, b.y - a.y);
if (len < minSeg) continue;
block += `0\nLINE\n8\n${layer}\n62\n7\n10\n${a.x}\n20\n${a.y}\n11\n${b.x}\n21\n${b.y}\n`;
}
});
return dxfContent.replace('0\nENDSEC\n0\nEOF', block + '0\nENDSEC\n0\nEOF');
}
/**
* Append satellite imagery reference to DXF so CAD shows the image as background.
* Also adds a visible bounding box (rectangle) on layer IMAGE_BOUNDS so the image extent is visible in CAD.
* imageFilename: e.g. "satellite.png" (same folder as DXF).
* minX, minY, maxX, maxY: extent in drawing units (meters from origin). Image is placed to fill this rect.
* widthPx, heightPx: image size in pixels.
*/
function appendSatelliteImageToDXF(dxfContent, imageFilename, minX, minY, maxX, maxY, widthPx, heightPx) {
const handle = '1F0';
const w = maxX - minX;
const h = maxY - minY;
const uPerPx = w / widthPx;
const vPerPx = h / heightPx;
/* Visible bounding box in CAD: four LINE entities (color 4 = cyan) so user sees the image extent */
const layer = 'IMAGE_BOUNDS';
const color = '4';
const boxLines =
`0\nLINE\n8\n${layer}\n62\n${color}\n10\n${minX}\n20\n${minY}\n30\n0\n11\n${maxX}\n21\n${minY}\n31\n0\n` +
`0\nLINE\n8\n${layer}\n62\n${color}\n10\n${maxX}\n20\n${minY}\n30\n0\n11\n${maxX}\n21\n${maxY}\n31\n0\n` +
`0\nLINE\n8\n${layer}\n62\n${color}\n10\n${maxX}\n20\n${maxY}\n30\n0\n11\n${minX}\n21\n${maxY}\n31\n0\n` +
`0\nLINE\n8\n${layer}\n62\n${color}\n10\n${minX}\n20\n${maxY}\n30\n0\n11\n${minX}\n21\n${minY}\n31\n0\n`;
const imageEntity =
`0\nIMAGE\n8\nSATELLITE_IMAGERY\n10\n${minX}\n20\n${minY}\n30\n0\n` +
`11\n${uPerPx}\n21\n0\n31\n0\n12\n0\n22\n${vPerPx}\n32\n0\n` +
`13\n${widthPx}\n23\n${heightPx}\n340\n${handle}\n`;
const objectsSection =
`0\nSECTION\n2\nOBJECTS\n` +
`0\nIMAGEDEF\n90\n${handle}\n1\n${imageFilename}\n13\n${widthPx}\n23\n${heightPx}\n` +
`0\nENDSEC\n0\nEOF`;
return dxfContent.replace('0\nENDSEC\n0\nEOF', boxLines + imageEntity + '0\nENDSEC\n' + objectsSection);
}
+1681
View File
File diff suppressed because it is too large. Load diff
+250
View File
@@ -0,0 +1,250 @@
/**
* 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|<!DOCTYPE|<html/i.test(text)) {
msg = 'This Overpass server returned an error page (overloaded or rate limit).';
}
lastError = new Error(msg);
continue;
}
if (!looksLikeJson) {
if (/<\?xml|<!DOCTYPE|<html/i.test(text)) {
lastError = new Error('OpenStreetMap Overpass server returned an error page instead of data. Wait a minute and try again, or try a smaller map area.');
} else {
lastError = new Error('Overpass returned invalid response. Try again.');
}
continue;
}
let data;
try {
data = JSON.parse(text);
} catch (parseErr) {
lastError = new Error('Overpass returned invalid JSON. Try again later.');
continue;
}
if (data.error) {
lastError = new Error(data.error);
continue;
}
return data;
} catch (e) {
clearTimeout(to);
if (e.name === 'AbortError') lastError = new Error('Request timed out. Try a smaller area or try again later.');
else lastError = e;
}
}
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', async (req, res) => {
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|<!DOCTYPE|<html/i.test(text)) {
return res.status(502).json({ error: 'Geocoding service returned an error page. Try again in a moment.' });
}
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.' });
}
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 || '' }))
});
} 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();
});