1 """This module contains winterrodeln specific functions that are processing the MediaWiki markup.
4 import xml.etree.ElementTree
6 from typing import Tuple, Optional, List, OrderedDict, Union, Dict
9 from mwparserfromhell.nodes import Template, Wikilink
11 import wrpylib.wrvalidators
12 import wrpylib.mwmarkup
14 from wrpylib.wrvalidators import LonLat, opt_lonlat_from_str, opt_lonlat_to_str, opt_uint_from_str, opt_uint_to_str, \
15 opt_str_opt_comment_enum_to_str, lift_german_to_str, webauskunft_to_str, cachet_german_to_str, \
16 opt_phone_comment_enum_to_str, lift_german_from_str, GASTHAUSBOX_DICT, opt_difficulty_german_from_str, \
17 opt_avalanches_german_from_str, opt_public_transport_german_from_str, \
18 opt_tristate_german_comment_from_str, rodelbahnbox_to_str, lonlat_to_str, opt_no_or_str_to_str, \
19 opt_no_or_str_from_str, opt_tristate_german_from_str
22 def split_lon_lat(value: Optional[LonLat]) -> Union[LonLat, Tuple[None, None]]:
28 def join_lon_lat(lon: Optional[float], lat: Optional[float]) -> Optional[LonLat]:
29 if lon is None or lat is None:
31 return LonLat(lon, lat)
34 def sledrun_from_rodelbahnbox(value: OrderedDict, sledrun: object):
35 """Takes a Rodelbahnbox as returned by rodelbahnbox_from_str (that is, an OrderedDict) and
36 updates the sledrun instance with all values present in the Rodelbahnbox. Other values are not
37 updated. Does not validate the arguments."""
38 # sledrun.page_id = None # this field is not updated because it is not present in the RodelbahnBox
39 # sledrun.page_title = None # this field is not updated because it is not present in the RodelbahnBox
40 # sledrun.name_url = None # this field is not updated because it is not present in the RodelbahnBox
41 sledrun.position_longitude, sledrun.position_latitude = split_lon_lat(value['Position'])
42 sledrun.top_longitude, sledrun.top_latitude = split_lon_lat(value['Position oben'])
43 sledrun.top_elevation = value['Höhe oben']
44 sledrun.bottom_longitude, sledrun.bottom_latitude = split_lon_lat(value['Position unten'])
45 sledrun.bottom_elevation = value['Höhe unten']
46 sledrun.length = value['Länge']
47 sledrun.difficulty = value['Schwierigkeit']
48 sledrun.avalanches = value['Lawinen']
49 sledrun.operator = opt_no_or_str_to_str(value['Betreiber'])
50 sledrun.public_transport = value['Öffentliche Anreise']
51 sledrun.walkup_possible = value['Aufstieg möglich']
52 sledrun.walkup_time = value['Gehzeit']
53 sledrun.walkup_separate, sledrun.walkup_separate_comment = value['Aufstieg getrennt']
54 sledrun.lift = None if value['Aufstiegshilfe'] is None else len(value['Aufstiegshilfe']) > 0
55 sledrun.lift_details = lift_german_to_str(value['Aufstiegshilfe'])
56 sledrun.night_light, sledrun.night_light_comment = value['Beleuchtungsanlage']
57 sledrun.night_light_days, sledrun.night_light_days_comment = value['Beleuchtungstage']
58 sledrun.sled_rental = None if value['Rodelverleih'] is None else len(value['Rodelverleih']) > 0
59 sledrun.sled_rental_comment = opt_str_opt_comment_enum_to_str(value['Rodelverleih'])
60 sledrun.cachet = cachet_german_to_str(value['Gütesiegel'])
61 sledrun.information_web = webauskunft_to_str(value['Webauskunft'])
62 sledrun.information_phone = opt_phone_comment_enum_to_str(value['Telefonauskunft'])
63 sledrun.image = value['Bild']
64 sledrun.show_in_overview = value['In Übersichtskarte']
65 sledrun.forum_id = value['Forumid']
66 # sledrun.under_construction = None # this field is not updated because it is not present in the RodelbahnBox
70 def sledrun_to_rodelbahnbox(sledrun) -> collections.OrderedDict:
71 """Takes a sledrun instance that might come from the database and converts it to a OrderedDict ready
72 to be formatted as RodelbahnBox."""
73 value = collections.OrderedDict()
74 value['Position'] = join_lon_lat(sledrun.position_longitude, sledrun.position_latitude)
75 value['Position oben'] = join_lon_lat(sledrun.top_longitude, sledrun.top_latitude)
76 value['Höhe oben'] = sledrun.top_elevation
77 value['Position unten'] = join_lon_lat(sledrun.bottom_longitude, sledrun.bottom_latitude)
78 value['Höhe unten'] = sledrun.bottom_elevation
79 value['Länge'] = sledrun.length
80 value['Schwierigkeit'] = sledrun.difficulty
81 value['Lawinen'] = sledrun.avalanches
82 value['Betreiber'] = opt_no_or_str_from_str(sledrun.operator)
83 value['Öffentliche Anreise'] = sledrun.public_transport
84 value['Aufstieg möglich'] = sledrun.walkup_possible
85 value['Gehzeit'] = sledrun.walkup_time
86 value['Aufstieg getrennt'] = sledrun.walkup_separate, sledrun.walkup_separate_comment
87 value['Aufstiegshilfe'] = lift_german_from_str(sledrun.lift_details)
88 value['Beleuchtungsanlage'] = sledrun.night_light, sledrun.night_light_comment
89 value['Beleuchtungstage'] = sledrun.night_light_days, sledrun.night_light_days_comment
90 value['Rodelverleih'] = sledrun.sled_rental, sledrun.sled_rental_comment
91 value['Gütesiegel'] = sledrun.cachet
92 value['Webauskunft'] = sledrun.information_web
93 value['Telefonauskunft'] = sledrun.information_phone
94 value['Bild'] = sledrun.image
95 value['In Übersichtskarte'] = sledrun.show_in_overview
96 value['Forumid'] = sledrun.forum_id
100 def inn_from_gasthausbox(value, inn):
101 """Converts a dict with Gasthausbox properties to a Inn class. Does no validation.
102 value is a dict of properties as returned by gasthausbox_from_str."""
103 # page_id = None # this field is not updated because it is not present in the Gasthausbox
104 # page_title = None # this field is not updated because it is not present in the Gasthausbox
105 def convtodb(val, key):
106 v = GASTHAUSBOX_DICT[key].to_str(val[key])
110 inn.position_longitude, inn.position_latitude = split_lon_lat(value['Position'])
111 inn.position_elevation = value['Höhe']
112 inn.operator = value['Betreiber']
113 inn.seats = value['Sitzplätze']
114 inn.overnight, inn.overnight_comment = value['Übernachtung']
115 inn.smoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] < 0.9
116 inn.nonsmoker_area = None if value['Rauchfrei'] is None else value['Rauchfrei'] > 0.1
117 inn.sled_rental, inn.sled_rental_comment = value['Rodelverleih']
118 inn.mobile_provider = convtodb(value, 'Handyempfang')
119 inn.homepage = convtodb(value, 'Homepage')
120 inn.email_list = convtodb(value, 'E-Mail')
121 inn.phone_list = convtodb(value, 'Telefon')
122 inn.image = value['Bild']
123 inn.sledding_list = convtodb(value, 'Rodelbahnen')
124 # under_construction = None # this field is not updated because it is not present in the GasthausBox
128 def inn_to_gasthausbox(inn) -> collections.OrderedDict:
129 """Converts an inn class to a dict of Gasthausbox properties. inn is an Inn instance."""
130 def convfromdb(val, key):
131 v = '' if val is None else val
132 return GASTHAUSBOX_DICT[key].from_str(v)
133 value = collections.OrderedDict()
134 value['Position'] = join_lon_lat(inn.position_longitude, inn.position_latitude)
135 value['Höhe'] = inn.position_elevation
136 value['Betreiber'] = inn.operator
137 value['Sitzplätze'] = inn.seats
138 value['Übernachtung'] = (inn.overnight, inn.overnight_comment)
139 value['Rauchfrei'] = {(False, True): 0.0, (True, True): 0.5, (True, False): 1.0} \
140 .get((inn.nonsmoker_area, inn.smoker_area), None)
141 value['Rodelverleih'] = (inn.sled_rental, inn.sled_rental_comment)
142 value['Handyempfang'] = convfromdb(inn.mobile_provider, 'Handyempfang')
143 value['Homepage'] = convfromdb(inn.homepage, 'Homepage')
144 value['E-Mail'] = convfromdb(inn.email_list, 'E-Mail')
145 value['Telefon'] = convfromdb(inn.phone_list, 'Telefon')
146 value['Bild'] = inn.image
147 value['Rodelbahnen'] = convfromdb(inn.sledding_list, 'Rodelbahnen')
151 def lonlat_ele_from_template(template) -> Tuple[Optional[LonLat], Optional[int]]:
152 """Template is a `mwparserfromhell.nodes.template.Template` instance. Returns (lonlat, ele)."""
153 lonlat = opt_lonlat_from_str(template.params[0].strip())
154 ele = opt_uint_from_str(template.params[1].strip())
158 def latlon_ele_to_template(lonlat_ele: Tuple[Optional[LonLat], Optional[int]], name: str) -> Template:
159 lonlat, ele = lonlat_ele
160 template = Template(name)
161 template.add(1, opt_lonlat_to_str(lonlat))
162 template.add(2, opt_uint_to_str(ele))
163 wrpylib.mwmarkup.format_template_oneline(template)
167 def lonlat_to_json(lonlat: LonLat) -> dict:
168 return {'longitude': lonlat.lon, 'latitude': lonlat.lat}
171 def lonlat_ele_to_json(lonlat: Optional[LonLat], ele: Optional[int]) -> dict:
173 if lonlat is not None:
174 result['position'] = lonlat_to_json(lonlat)
176 result['elevation'] = ele
180 class ParseError(RuntimeError):
181 """Exception used by some of the functions"""
185 def parse_wrmap_coordinates(coords: str) -> List[List[float]]:
186 """gets a string coordinates and returns an array of lon/lat coordinate pairs, e.g.
190 [[11.87, 47.12], [11.70, 47.13]]"""
193 for match in re.finditer(r'\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*', coords):
194 if match.start() != pos:
196 result.append([float(match.groups()[1]), float(match.groups()[0])])
199 if pos == len(coords):
201 raise RuntimeError(f'Wrong coordinate format: {coords}')
204 WRMAP_POINT_TYPES = ['gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt']
205 WRMAP_LINE_TYPES = ['rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie']
208 def parse_wrmap(wikitext: str) -> dict:
209 """Parses the '<wrmap ...>content</wrmap>' of the Winterrodeln wrmap extension.
210 If wikitext does not contain the <wrmap> tag or if the <wrmap> tag contains
211 invalid formatted lines, a ParseError is raised.
212 Use wrpylib.mwmarkup.find_tag(wikitext, 'wrmap') to find the wrmap tag within an arbitrary
213 wikitext before using this function.
215 :param wikitext: wikitext containing only the template. Example:
218 <wrmap lat="47.2417134" lon="11.21408895" zoom="14" width="700" height="400">
219 <gasthaus name="Rosskogelhütte" wiki="Rosskogelhütte">47.240689 11.190454</gasthaus>
220 <parkplatz>47.245789 11.238971</parkplatz>
221 <haltestelle name="Oberperfuss Rangger Köpfl Lift">47.245711 11.238283</haltestelle>
229 :returns: GeoJSON as nested Python datatype
233 wrmap_xml = xml.etree.ElementTree.fromstring(wikitext)
234 except xml.etree.ElementTree.ParseError as e:
235 row, column = e.position
236 raise ParseError(f"XML parse error on row {row}, column {column}: {e}")
237 if wrmap_xml.tag not in ['wrmap', 'wrgmap']:
238 raise ParseError('No valid tag name')
240 # convert XML to geojson (http://www.geojson.org/geojson-spec.html)
242 for feature in wrmap_xml:
243 # determine feature type
244 is_point = feature.tag in WRMAP_POINT_TYPES
245 is_line = feature.tag in WRMAP_LINE_TYPES
246 if not is_point and not is_line:
247 raise ParseError(f'Unknown element <{feature.tag}>.')
251 properties = {'type': feature.tag}
252 allowed_properties = {'name', 'wiki'}
253 wrong_properties = set(feature.attrib.keys()) - allowed_properties
254 if len(wrong_properties) > 0:
255 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
256 properties.update(feature.attrib)
257 coordinates = parse_wrmap_coordinates(feature.text)
258 if len(coordinates) != 1:
259 raise ParseError(f'The element <{feature.tag}> has to have exactly one coordinate pair.')
260 json_features.append({
262 'geometry': {'type': 'Point', 'coordinates': coordinates[0]},
263 'properties': properties})
267 properties = {'type': feature.tag}
268 allowed_properties = {'farbe', 'dicke'}
269 wrong_properties = set(feature.attrib.keys()) - allowed_properties
270 if len(wrong_properties) > 0:
271 raise ParseError(f"The attribute '{list(wrong_properties)[0]}' is not allowed at <{feature.tag}>.")
272 if 'farbe' in feature.attrib:
273 if not re.match('#[0-9a-fA-F]{6}$', feature.attrib['farbe']):
274 raise ParseError('The attribute "farbe" has to have a format like "#a0bb43".')
275 properties['strokeColor'] = feature.attrib['farbe'] # e.g. #a200b7
276 if 'dicke' in feature.attrib:
278 properties['strokeWidth'] = int(feature.attrib['dicke']) # e.g. 6
280 raise ParseError('The attribute "dicke" has to be an integer.')
281 json_features.append({
283 'geometry': {'type': 'LineString', 'coordinates': parse_wrmap_coordinates(feature.text)},
284 'properties': properties})
288 for k, v in wrmap_xml.attrib.items():
289 if k in ['lat', 'lon']:
291 properties[k] = float(v)
293 raise ParseError(f'Attribute "{k}" has to be a float value.')
294 elif k in ['zoom', 'width', 'height']:
296 properties[k] = int(v)
298 raise ParseError(f'Attribute "{k}" has to be an integer value.')
300 raise ParseError(f'Unknown attribute "{k}".')
303 'type': 'FeatureCollection',
304 'features': json_features,
305 'properties': properties}
310 def create_wrmap_coordinates(coords):
313 result.append(f'{coord[1]:.6f} N {coord[0]:.6f} E')
314 return '\n'.join(result)
317 def create_wrmap(geojson: Dict) -> str:
318 """Creates a <wrmap> wikitext from geojson (as python types)."""
319 wrmap_xml = xml.etree.ElementTree.Element('wrmap')
320 wrmap_xml.text = '\n\n'
321 for k, v in geojson['properties'].items():
322 if k in ['lon', 'lat']:
323 wrmap_xml.attrib[k] = f'{v:.6f}'
325 wrmap_xml.attrib[k] = str(v)
327 assert geojson['type'] == 'FeatureCollection'
328 json_features = geojson['features']
329 last_json_feature = None
330 for json_feature in json_features:
331 feature_xml = xml.etree.ElementTree.SubElement(wrmap_xml, json_feature['properties']['type'])
332 geo = json_feature['geometry']
333 if geo['type'] == 'Point':
334 feature_xml.text = create_wrmap_coordinates([geo['coordinates']])
335 if last_json_feature is not None:
336 last_json_feature.tail = '\n'
338 if last_json_feature is not None:
339 last_json_feature.tail = '\n\n'
340 feature_xml.text = '\n' + create_wrmap_coordinates(geo['coordinates']) + '\n'
341 last_json_feature = feature_xml
342 feature_xml.attrib = json_feature['properties']
343 del feature_xml.attrib['type']
345 if last_json_feature is not None:
346 last_json_feature.tail = '\n\n'
347 return xml.etree.ElementTree.tostring(wrmap_xml, encoding='utf-8').decode('utf-8')
350 def german_bool(value: Union[bool, jinja2.Undefined]) -> Union[str, jinja2.Undefined]:
351 if jinja2.is_undefined(value):
353 return wrpylib.wrvalidators.bool_german_to_str(value)
357 def create_wrmap(self, geojson: Dict) -> str:
358 return create_wrmap(geojson)
360 def json_position(self, value: dict) -> str:
361 lon_lat = LonLat(value['longitude'], value['latitude'])
362 return lonlat_to_str(lon_lat)
364 def json_pos_ele_position(self, value: dict) -> str:
365 pos = value.get('position')
368 return self.json_position(pos)
370 def json_pos_ele_elevation(self, value: dict) -> str:
371 return value.get('elevation', '')
373 def json_wr_page(self, value: dict) -> str:
374 return str(Wikilink(value['title'], value.get('text')))
376 def list_template(self, name: str, value: List[str]) -> str:
377 return str(wrpylib.mwmarkup.create_template(name, value))
379 def json_template(self, value) -> str:
382 for p in value.get('parameter', []):
383 v = p.get('value', '')
388 return str(wrpylib.mwmarkup.create_template(value['name'], args, kwargs))
391 def create_sledrun_wiki(sledrun_json: Dict, map_json: Optional[Dict], impressions_title: Optional[str] = None) -> str:
392 env = jinja2.Environment(
393 loader=jinja2.PackageLoader("wrpylib"),
394 autoescape=jinja2.select_autoescape(),
396 env.filters["german_bool"] = german_bool
397 template = env.get_template("sledrun_wiki.txt")
399 def position_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
400 if value is not None:
401 lon = value.get('longitude')
402 lat = value.get('latitude')
403 if lon is not None and lat is not None:
404 return LonLat(lon, lat)
407 def position_ele_to_lon_lat(value: Optional[dict]) -> Optional[LonLat]:
408 if value is not None:
409 return position_to_lon_lat(value.get("position"))
412 def position_ele_to_ele(value: Optional[dict]) -> Optional[int]:
413 if value is not None:
414 ele = value.get('elevation')
419 def aufstiegshilfe() -> Optional[List[Tuple[str, Optional[str]]]]:
420 ws = sledrun_json.get('walkup_supports')
423 return [(w['type'], w.get('comment')) for w in ws]
425 def rodelverleih() -> Optional[List[Tuple[str, Optional[str]]]]:
426 v = sledrun_json.get('sled_rental')
435 n = Jinja2Tools().json_wr_page(p)
439 def cachet() -> Optional[List]:
440 v = sledrun_json.get('cachet')
446 def webauskunft() -> Tuple[Optional[bool], Optional[str]]:
447 info_web = sledrun_json.get('info_web')
450 if len(info_web) == 0:
452 return True, info_web[0]['url']
454 def telefonauskunft() -> Optional[List[Tuple[str, str]]]:
455 info_phone = sledrun_json.get('info_phone')
456 if info_phone is None:
458 return [(pc['phone'], pc['name']) for pc in info_phone]
460 def betreiber() -> str:
461 has_operator = sledrun_json.get('has_operator')
462 if has_operator is None:
463 return sledrun_json.get('operator')
465 return sledrun_json.get('operator')
468 sledrun_rbb_json = collections.OrderedDict([
469 ('Position', position_to_lon_lat(sledrun_json.get('position'))),
470 ('Position oben', position_ele_to_lon_lat(sledrun_json.get('top'))),
471 ('Höhe oben', position_ele_to_ele(sledrun_json.get('top'))),
472 ('Position unten', position_ele_to_lon_lat(sledrun_json.get('bottom'))),
473 ('Höhe unten', position_ele_to_ele(sledrun_json.get('bottom'))),
474 ('Länge', sledrun_json.get('length')),
475 ('Schwierigkeit', opt_difficulty_german_from_str(sledrun_json.get('difficulty', ''))),
476 ('Lawinen', opt_avalanches_german_from_str(sledrun_json.get('avalanches', ''))),
477 ('Betreiber', (sledrun_json.get('has_operator'), sledrun_json.get('operator'))),
478 ('Öffentliche Anreise', opt_public_transport_german_from_str(sledrun_json.get('public_transport', ''))),
479 ('Aufstieg möglich', sledrun_json.get('walkup_possible')),
480 ('Aufstieg getrennt', opt_tristate_german_comment_from_str(sledrun_json.get('walkup_separate', ''))),
481 ('Gehzeit', sledrun_json.get('walkup_time')),
482 ('Aufstiegshilfe', aufstiegshilfe()),
483 ('Beleuchtungsanlage', (opt_tristate_german_from_str(sledrun_json.get('nightlight_possible', '')),
484 sledrun_json.get('nightlight_possible_comment'))),
485 ('Beleuchtungstage', (sledrun_json.get('nightlight_weekdays_count'),
486 sledrun_json.get('nightlight_weekdays_comment'))),
487 ('Rodelverleih', rodelverleih()),
488 ('Gütesiegel', cachet()),
489 ('Webauskunft', webauskunft()),
490 ('Telefonauskunft', telefonauskunft()),
491 ('Bild', sledrun_json.get('image')),
492 ('In Übersichtskarte', sledrun_json.get('show_in_overview')),
493 ('Forumid', sledrun_json.get('forum_id'))
496 rodelbahnbox = rodelbahnbox_to_str(sledrun_rbb_json)
498 return template.render(sledrun_json=sledrun_json,
499 rodelbahnbox=rodelbahnbox,
500 map_json=map_json, impressions_title=impressions_title,
501 h=Jinja2Tools(), **sledrun_json)