]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/blob - bots/update_sledrun_json_from_wikitext_car_distances.py
Add script to remove unnecessary night light and sledrun rental descriptions.
[philipp/winterrodeln/wrpylib.git] / bots / update_sledrun_json_from_wikitext_car_distances.py
1 #!/usr/bin/python
2 """
3 User script for pywikibot (https://gerrit.wikimedia.org/r/pywikibot/core.git), tested with version 6.6.1.
4 Put it in directory scripts/userscripts.
5
6 Update a sledrun JSON page from a detail in a sledrun wikitext page.
7
8 The following generators and filters are supported:
9
10 &params;
11 """
12 import io
13 import json
14 import re
15 from itertools import takewhile, dropwhile
16 from typing import Optional
17
18 import jsonschema
19 import mwparserfromhell
20 from mwparserfromhell.nodes.extras import Parameter
21
22 import pywikibot
23 from mwparserfromhell.nodes import Tag, Text, ExternalLink, Template, Wikilink, Heading
24 from mwparserfromhell.wikicode import Wikicode
25 from pywikibot import pagegenerators, Page
26 from pywikibot.bot import (
27     AutomaticTWSummaryBot,
28     ConfigParserBot,
29     ExistingPageBot,
30     NoRedirectPageBot,
31     SingleSiteBot,
32 )
33 from pywikibot.logging import warning
34 from pywikibot.site._namespace import BuiltinNamespace
35 from wrpylib.json_tools import order_json_keys
36
37 from wrpylib.wrmwmarkup import create_sledrun_wiki, lonlat_to_json, lonlat_ele_to_json, parse_wrmap
38 from wrpylib.wrvalidators import rodelbahnbox_from_template, tristate_german_to_str, difficulty_german_to_str, \
39     avalanches_german_to_str, public_transport_german_to_str, opt_lonlat_from_str, \
40     opt_uint_from_str
41 from wrpylib.lib_sledrun_wikitext_to_json import optional_set, get_sledrun_description
42
43 docuReplacements = {'&params;': pagegenerators.parameterHelp}
44
45
46 class UpdateSledrunJsonFromWikiText(
47     SingleSiteBot,
48     ConfigParserBot,
49     ExistingPageBot,
50     AutomaticTWSummaryBot,
51 ):
52     def setup(self) -> None:
53         schema = Page(self.site, 'Winterrodeln:Datenschema/Rodelbahn/V1.json')
54         assert schema.content_model == 'json'
55         self.sledrun_schema = json.loads(schema.text)
56
57     def treat_page(self) -> None:
58         """Load the given page, do some changes, and save it."""
59         wikitext_content_model = 'wikitext'
60         if self.current_page.content_model != wikitext_content_model:
61             warning(f"The content model of {self.current_page.title()} is {self.current_page.content_model} "
62                     f"instead of {wikitext_content_model}.")
63             return
64
65         sledrun_json_page = Page(self.site, self.current_page.title() + '/Rodelbahn.json')
66         if not sledrun_json_page.exists():
67             return
68         sledrun_json = json.loads(sledrun_json_page.text)
69         sledrun_json_orig = json.loads(sledrun_json_page.text)
70         sledrun_json_orig_text = json.dumps(sledrun_json_orig, ensure_ascii=False, indent=4)
71
72         car_distances = []
73         for line in self.current_page.text.split('\n'):
74             match = re.match(r"\*\* [Vv]on \'\'\'(.+)\'\'\'(.*): ([\d.,]+) km", line.rstrip())
75             if match:
76                 ya, yb, yc = match.groups()
77                 yc = float(yc.replace(',', '.'))
78                 car_distances.append({
79                     'km': yc,
80                     'route': (ya.strip() + ' ' + yb.strip()).strip(),
81                 })
82             else:
83                 match = re.match(r"\*\* [Vv]on (.+): ([\d.,]+) km", line.rstrip())
84                 if match:
85                     ya, yb = match.groups()
86                     yb = float(yb.replace(',', '.'))
87                     car_distances.append({
88                         'km': yb,
89                         'route': ya.strip(),
90                     })
91         if len(car_distances) > 0:
92             sledrun_json['car_distances'] = car_distances
93
94         jsonschema.validate(instance=sledrun_json, schema=self.sledrun_schema)
95         sledrun_json_ordered = order_json_keys(sledrun_json, self.sledrun_schema)
96         assert sledrun_json_ordered == sledrun_json
97         if sledrun_json == sledrun_json_orig:
98             return
99         sledrun_json_text = json.dumps(sledrun_json_ordered, ensure_ascii=False, indent=4)
100         summary = 'Entfernung mit dem Auto im Rodelbahn JSON aktualisiert vom Wikitext.'
101         self.userPut(sledrun_json_page, sledrun_json_orig_text, sledrun_json_text, summary=summary, contentmodel='json')
102
103
104 def main(*args: str) -> None:
105     local_args = pywikibot.handle_args(args)
106     gen_factory = pagegenerators.GeneratorFactory()
107     gen_factory.handle_args(local_args)
108     gen = gen_factory.getCombinedGenerator(preload=True)
109     if gen:
110         bot = UpdateSledrunJsonFromWikiText(generator=gen)
111         bot.run()
112     else:
113         pywikibot.bot.suggest_help(missing_generator=True)
114
115
116 if __name__ == '__main__':
117     main()