GeoDonkey for QGIS 1.12

This commit is contained in:
GeoDonkey committed 2026-12-01 19:59:12 +01:00
commit 20ab32da30
63 files changed
+11157

No files matched your search

+212
View File
@@ -0,0 +1,212 @@
from __future__ import annotations
import json
import os
import re
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
from .i18n import tr
GEOMETRY_GROUPS = {
"Point": "Point",
"MultiPoint": "Point",
"LineString": "Line",
"MultiLineString": "Line",
"Polygon": "Polygon",
"MultiPolygon": "Polygon",
}
GROUP_ORDER = ("Point", "Line", "Polygon")
OGR_GEOMETRY_TYPE = {
"Point": "Point",
"Line": "LineString",
"Polygon": "Polygon",
}
def geometry_group(feature: Mapping[str, Any]) -> Optional[str]:
if not isinstance(feature, Mapping):
return None
geometry = feature.get("geometry")
if not isinstance(geometry, Mapping):
return None
return GEOMETRY_GROUPS.get(geometry.get("type"))
def split_by_geometry(collection: Mapping[str, Any]) -> "Tuple[Dict[str, Dict[str, Any]], int]":
buckets: Dict[str, List[Any]] = {name: [] for name in GROUP_ORDER}
without = 0
for feature in (collection or {}).get("features") or []:
group = geometry_group(feature)
if group is None:
without += 1
continue
buckets[group].append(feature)
out: Dict[str, Dict[str, Any]] = {}
for name in GROUP_ORDER:
if buckets[name]:
out[name] = {"type": "FeatureCollection", "features": buckets[name]}
return out, without
def tag_keys(collection: Mapping[str, Any], limit: int = 0) -> List[str]:
keys = set()
for feature in (collection or {}).get("features") or []:
props = feature.get("properties") if isinstance(feature, Mapping) else None
tags = props.get("tags") if isinstance(props, Mapping) else None
if isinstance(tags, Mapping):
keys.update(str(k) for k in tags.keys())
names = sorted(keys)
return names[:limit] if limit else names
_UNSAFE = re.compile(r"[^0-9A-Za-zÄÖÜäöüß _.\-]+")
def safe_name(text: str, fallback: str = "donkeyosm", limit: int = 48) -> str:
cleaned = _UNSAFE.sub(" ", str(text or "")).strip()
cleaned = re.sub(r"\s+", " ", cleaned)
if not cleaned:
cleaned = fallback
if len(cleaned) > limit:
cleaned = cleaned[:limit].rstrip() + "…"
return cleaned
def write_collection(folder: str, basename: str, collection: Mapping[str, Any]) -> str:
path = os.path.join(folder, basename + ".geojson")
with open(path, "w", encoding="utf-8") as handle:
json.dump(collection, handle, ensure_ascii=False)
return path
def result_summary(meta: Mapping[str, Any], counts: Mapping[str, int],
without_geometry: int = 0) -> str:
total = sum(counts.values())
parts = [tr("{count} objects").format(count=total)]
detail = ", ".join(
"%s %s" % (counts[name], name.lower())
for name in GROUP_ORDER if counts.get(name))
if detail and len(counts) > 1:
parts.append("(%s)" % detail)
if without_geometry:
parts.append(tr("{count} without geometry").format(count=without_geometry))
if meta.get("truncated"):
parts.append(tr("limit of {limit} reached – the result is incomplete").format(
limit=meta.get("limit") or "?"))
return " · ".join(parts)
def attribution(meta: Mapping[str, Any], fallback: str = "") -> str:
for key in ("attribution", "provider"):
value = (meta or {}).get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return fallback
def ogr_uri(path: str, group: str = "", flatten: bool = True) -> str:
uri = path
if flatten:
uri += "|option:FLATTEN_NESTED_ATTRIBUTES=YES"
wanted = OGR_GEOMETRY_TYPE.get(group)
if wanted:
uri += "|geometrytype=" + wanted
return uri
WKT_PRECISION = 8
def _wkt_number(value: Any) -> str:
text = "%.*f" % (WKT_PRECISION, float(value))
if "." in text:
text = text.rstrip("0").rstrip(".")
return text or "0"
def _wkt_point(pair: Sequence[Any]) -> str:
return "%s %s" % (_wkt_number(pair[0]), _wkt_number(pair[1]))
def _wkt_list(items: Sequence[Any]) -> str:
return "(" + ", ".join(_wkt_point(pair) for pair in items) + ")"
def _wkt_rings(rings: Sequence[Any]) -> str:
return "(" + ", ".join(_wkt_list(ring) for ring in rings) + ")"
def to_wkt(geometry: Optional[Mapping[str, Any]]) -> Optional[str]:
if not isinstance(geometry, Mapping):
return None
kind = geometry.get("type")
coords = geometry.get("coordinates")
if not kind or coords is None:
return None
try:
if kind == "Point":
if not coords:
return None
return "POINT (%s)" % _wkt_point(coords)
if kind == "MultiPoint":
if not coords:
return None
return "MULTIPOINT (%s)" % ", ".join(
"(%s)" % _wkt_point(pair) for pair in coords)
if kind == "LineString":
if len(coords) < 2:
return None
return "LINESTRING %s" % _wkt_list(coords)
if kind == "MultiLineString":
parts = [part for part in coords if len(part) >= 2]
if not parts:
return None
return "MULTILINESTRING (%s)" % ", ".join(_wkt_list(p) for p in parts)
if kind == "Polygon":
rings = [ring for ring in coords if len(ring) >= 4]
if not rings:
return None
return "POLYGON %s" % _wkt_rings(rings)
if kind == "MultiPolygon":
parts = []
for polygon in coords:
rings = [ring for ring in polygon if len(ring) >= 4]
if rings:
parts.append(_wkt_rings(rings))
if not parts:
return None
return "MULTIPOLYGON (%s)" % ", ".join(parts)
except (TypeError, ValueError, IndexError):
return None
return None
PROCESSING_FIELDS: Sequence[Tuple[str, str]] = (
("osm_type", "string"),
("osm_id", "string"),
("osm_url", "string"),
("name", "string"),
("tags", "string"),
)
def processing_row(feature: Mapping[str, Any]) -> Dict[str, str]:
props = feature.get("properties") if isinstance(feature, Mapping) else None
props = props if isinstance(props, Mapping) else {}
tags = props.get("tags")
if isinstance(tags, str) and tags.strip():
try:
parsed = json.loads(tags)
except ValueError:
parsed = None
tags = parsed if isinstance(parsed, dict) else {}
tags = tags if isinstance(tags, Mapping) else {}
return {
"osm_type": str(props.get("osm_type") or ""),
"osm_id": str(props.get("osm_id") or ""),
"osm_url": str(props.get("osm_url") or ""),
"name": str(tags.get("name") or ""),
"tags": json.dumps(tags, ensure_ascii=False, sort_keys=True) if tags else "",
}