Files
2026-12-01 19:59:12 +01:00

216 lines
8.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
from typing import Any, Dict, Mapping
from qgis.core import (
QgsCoordinateReferenceSystem,
QgsFeature,
QgsFeatureSink,
QgsFields,
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterEnum,
QgsProcessingParameterExtent,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterNumber,
QgsProcessingParameterString,
QgsVectorLayer,
QgsWkbTypes,
)
from qgis.PyQt.QtCore import QVariant
from .. import area as area_mod
from .. import config, geojson, layers, style
from ..client import split_collection
from ..compat import string_field
from ..errors import GeoDonkeyError
from ..i18n import tr
from .base import GeoDonkeyAlgorithm
MODE_WORDS = 0
MODE_TAGS = 1
MODE_QUERY = 2
SINKS = (
("OUTPUT_POINTS", "Point", QgsWkbTypes.Type.Point, "Points"),
("OUTPUT_LINES", "Line", QgsWkbTypes.Type.MultiLineString, "Lines"),
("OUTPUT_POLYGONS", "Polygon", QgsWkbTypes.Type.MultiPolygon, "Areas"),
)
def output_fields() -> QgsFields:
fields = QgsFields()
for name, _kind in geojson.PROCESSING_FIELDS:
fields.append(string_field(name))
return fields
class DonkeyOsmAlgorithm(GeoDonkeyAlgorithm):
ICON = "osm.svg"
GROUP = "OpenStreetMap"
GROUP_ID = "openstreetmap"
COST_KEY = "osm"
MODE = "MODE"
QUERY = "QUERY"
EXTENT = "EXTENT"
TYPES = "TYPES"
LIMIT = "LIMIT"
def createInstance(self): # noqa: N802
return DonkeyOsmAlgorithm()
def name(self) -> str:
return "donkeyosm"
def displayName(self) -> str: # noqa: N802
return tr("DonkeyOSM query")
def shortHelpString(self) -> str: # noqa: N802
return tr(
"<p>Queries OpenStreetMap data through the DonkeyOSM service of "
"geodonkey.com and returns it as three layers: points, lines and "
"areas.</p>"
"<p><b>Search mode</b> decides how the query text is read: as "
"everyday words, as a comma separated list of OSM tags "
"(<code>shop=bakery,amenity=cafe</code>), or as a DonkeyOSM line "
"query (one selection per line).</p>"
"<p><b>Every run costs {coins} DonkeyCoins</b> once the free calls "
"of the current hour are used up. The API key is taken from the "
"plugin settings.</p>"
"<p>All outputs share the same five fields: <code>osm_type</code>, "
"<code>osm_id</code>, <code>osm_url</code>, <code>name</code> and "
"<code>tags</code>. <code>tags</code> holds the complete OSM tags "
"as JSON text, so the schema stays the same no matter what the "
"query finds.</p>"
"<p>Data © OpenStreetMap contributors, ODbL.</p>"
).format(coins=config.COIN_COSTS.get("osm", 3))
def initAlgorithm(self, configuration=None): # noqa: N802
self.addParameter(QgsProcessingParameterEnum(
self.MODE, tr("Search mode"),
options=[tr("Plain language"), tr("OSM tags"), tr("Custom line query")],
defaultValue=MODE_WORDS))
self.addParameter(QgsProcessingParameterString(
self.QUERY, tr("Query"), multiLine=True))
self.addParameter(QgsProcessingParameterExtent(
self.EXTENT, tr("Area")))
self.addParameter(QgsProcessingParameterString(
self.TYPES, tr("OSM element types (node, way, relation)"),
defaultValue="", optional=True))
self.addParameter(QgsProcessingParameterNumber(
self.LIMIT, tr("Maximum objects"),
type=QgsProcessingParameterNumber.Type.Integer,
minValue=1, maxValue=config.OSM_LIMIT_PRO,
defaultValue=config.OSM_LIMIT_DEFAULT))
for key, _group, _wkb, label in SINKS:
self.addParameter(QgsProcessingParameterFeatureSink(
key, tr(label), type=QgsProcessing.SourceType.TypeVectorAnyGeometry,
optional=True, createByDefault=True))
def processAlgorithm(self, parameters, context, feedback): # noqa: N802
mode = self.parameterAsEnum(parameters, self.MODE, context)
text = (self.parameterAsString(parameters, self.QUERY, context) or "").strip()
types = (self.parameterAsString(parameters, self.TYPES, context) or "").strip()
limit = self.parameterAsInt(parameters, self.LIMIT, context)
if not text:
raise QgsProcessingException(tr("The query is empty."))
rect = self.parameterAsExtent(parameters, self.EXTENT, context,
QgsCoordinateReferenceSystem("EPSG:4326"))
if rect.isEmpty():
raise QgsProcessingException(tr("The area is empty."))
try:
area = area_mod.bbox_param(rect.xMinimum(), rect.yMinimum(),
rect.xMaximum(), rect.yMaximum())
except GeoDonkeyError as exc:
raise QgsProcessingException(exc.message)
client = self.client(feedback)
feedback.pushInfo(tr("Area: {area}").format(area=area_mod.describe(area)))
feedback.setProgress(5)
try:
if mode == MODE_QUERY:
payload = client.osm_query(text, area, limit=limit, feedback=feedback)
elif mode == MODE_TAGS:
payload = client.osm_search(area, tags=text, types=types,
limit=limit, feedback=feedback)
else:
payload = client.osm_search(area, words=text, types=types,
limit=limit, feedback=feedback)
except GeoDonkeyError as exc:
self.fail(exc, feedback)
if feedback.isCanceled():
return {}
feedback.setProgress(50)
collection, meta = split_collection(payload)
self.report(client, feedback)
if meta.get("truncated"):
feedback.pushWarning(tr(
"The limit of {limit} was reached – the result is incomplete.").format(
limit=meta.get("limit") or limit))
feedback.pushInfo(geojson.attribution(meta, config.DEFAULT_ATTRIBUTION))
buckets, without = geojson.split_by_geometry(collection)
if without:
feedback.pushInfo(tr("{count} objects without geometry were skipped.").format(
count=without))
results: Dict[str, Any] = {}
for index, (key, group, wkb, _label) in enumerate(SINKS):
if feedback.isCanceled():
return results
sink, dest = self.parameterAsSink(
parameters, key, context, output_fields(), wkb,
QgsCoordinateReferenceSystem("EPSG:4326"))
if sink is None:
continue
part = buckets.get(group)
if part:
self._fill(sink, part, group, feedback)
self.style(context, dest, style.osm_plan(group))
results[key] = dest
feedback.setProgress(50 + (index + 1) * 15)
return results
@staticmethod
def _fill(sink: QgsFeatureSink, part: Mapping[str, Any], group: str,
feedback) -> None:
folder = layers.result_folder()
path = geojson.write_collection(folder, "processing-%s" % group.lower(), part)
layer = QgsVectorLayer(geojson.ogr_uri(path, group, flatten=False),
"donkeyosm", "ogr")
if not layer.isValid():
raise QgsProcessingException(
tr("QGIS could not read the result file: {path}").format(path=path))
names = [field.name() for field in layer.fields()]
for feature in layer.getFeatures():
if feedback.isCanceled():
return
raw = {name: _plain(feature[name]) for name in names}
row = geojson.processing_row({"properties": raw})
out = QgsFeature(output_fields())
out.setGeometry(feature.geometry())
out.setAttributes([row[name] for name, _kind in geojson.PROCESSING_FIELDS])
sink.addFeature(out, QgsFeatureSink.Flag.FastInsert)
def _plain(value):
if value is None:
return None
if isinstance(value, QVariant):
return None if value.isNull() else value.value()
return value