A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 regels
17 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2017 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import re
  23. from earwigbot import exceptions
  24. from earwigbot.tasks import Task
  25. from earwigbot.wiki import constants
  26. class WikiProjectTagger(Task):
  27. """A task to tag talk pages with WikiProject banners.
  28. Usage: :command:`earwigbot -t wikiproject_tagger PATH
  29. --banner BANNER (--category CAT | --file FILE) [--summary SUM] [--update]
  30. [--append PARAMS] [--autoassess [CLASSES]] [--only-with BANNER]
  31. [--nocreate] [--recursive [NUM]] [--genfixes] [--site SITE] [--dry-run]`
  32. .. glossary::
  33. ``--banner BANNER``
  34. the page name of the banner to add, without a namespace (unless the
  35. namespace is something other than ``Template``) so
  36. ``--banner WikiProject Biography`` for ``{{WikiProject Biography}}``
  37. ``--category CAT`` or ``--file FILE``
  38. determines which pages to tag; either all pages in a category (to
  39. include subcategories as well, see ``--recursive``) or all
  40. pages/categories in a file (utf-8 encoded and path relative to the
  41. current directory)
  42. ``--summary SUM``
  43. an optional edit summary to use; defaults to
  44. ``"Tagging with WikiProject banner {{BANNER}}."``
  45. ``--update``
  46. updates existing banners with new fields; should include at least one
  47. of ``--append`` or ``--autoassess`` to be useful
  48. ``--append PARAMS``
  49. optional comma-separated parameters to append to the banner (after an
  50. auto-assessment, if any); use syntax ``importance=low,taskforce=yes``
  51. to add ``|importance=low|taskforce=yes``
  52. ``--autoassess [CLASSES]``
  53. try to assess each article's class automatically based on the class of
  54. other banners on the same page; if CLASSES is given as a
  55. comma-separated list, only those classes will be auto-assessed
  56. ``--only-with BANNER``
  57. only tag pages that already have the given banner
  58. ``--nocreate``
  59. don't create new talk pages with just a banner if the page doesn't
  60. already exist
  61. ``--recursive NUM``
  62. recursively go through subcategories up to a maximum depth of ``NUM``,
  63. or if ``NUM`` isn't provided, go infinitely (this can be dangerous)
  64. ``--genfixes``
  65. apply general fixes to the page if already making other changes
  66. ``--site SITE``
  67. the ID of the site to tag pages on, defaulting to the default site
  68. ``--dry-run``
  69. don't actually make any edits, just log the pages that would have been
  70. edited
  71. """
  72. name = "wikiproject_tagger"
  73. # Regexes for template names that should always go above the banner, based
  74. # on [[Wikipedia:Talk page layout]]:
  75. TOP_TEMPS = [
  76. r"skip ?to ?(toc|talk|toctalk)$",
  77. r"ga ?nominee$",
  78. r"(user ?)?talk ?(header|page|page ?header)$",
  79. r"community ?article ?probation$",
  80. r"censor(-nudity)?$",
  81. r"blp(o| ?others?)?$",
  82. r"controvers(ial2?|y)$",
  83. r"(not ?(a ?)?)?forum$",
  84. r"tv(episode|series)talk$",
  85. r"recurring ?themes$",
  86. r"faq$",
  87. r"(round ?in ?)?circ(les|ular)$",
  88. r"ar(ti|it)cle ?(history|milestones)$",
  89. r"failed ?ga$",
  90. r"old ?prod( ?full)?$",
  91. r"(old|previous) ?afd$",
  92. r"((wikiproject|wp) ?)?bio(graph(y|ies))?$",
  93. ]
  94. @staticmethod
  95. def _upperfirst(text):
  96. """Try to uppercase the first letter of a string."""
  97. try:
  98. return text[0].upper() + text[1:]
  99. except IndexError:
  100. return text
  101. def run(self, **kwargs):
  102. """Main entry point for the bot task."""
  103. if "file" not in kwargs and "category" not in kwargs:
  104. log = "No pages to tag; I need either a 'category' or a 'file' passed as kwargs"
  105. self.logger.error(log)
  106. return
  107. if "banner" not in kwargs:
  108. log = "Needs a banner to add passed as the 'banner' kwarg"
  109. self.logger.error(log)
  110. return
  111. site = self.bot.wiki.get_site(name=kwargs.get("site"))
  112. banner = kwargs["banner"]
  113. summary = kwargs.get("summary", "Tagging with WikiProject banner $3.")
  114. update = kwargs.get("update", False)
  115. append = kwargs.get("append")
  116. autoassess = kwargs.get("autoassess", False)
  117. ow_banner = kwargs.get("only-with")
  118. nocreate = kwargs.get("nocreate", False)
  119. recursive = kwargs.get("recursive", 0)
  120. genfixes = kwargs.get("genfixes", False)
  121. dry_run = kwargs.get("dry-run", False)
  122. banner, names = self.get_names(site, banner)
  123. if not names:
  124. return
  125. if ow_banner:
  126. _, only_with = self.get_names(site, ow_banner)
  127. if not only_with:
  128. return
  129. else:
  130. only_with = None
  131. job = _Job(banner=banner, names=names, summary=summary, update=update,
  132. append=append, autoassess=autoassess, only_with=only_with,
  133. nocreate=nocreate, genfixes=genfixes, dry_run=dry_run)
  134. try:
  135. self.run_job(kwargs, site, job, recursive)
  136. except _ShutoffEnabled:
  137. return
  138. def run_job(self, kwargs, site, job, recursive):
  139. """Run a tagging *job* on a given *site*."""
  140. if "category" in kwargs:
  141. title = kwargs["category"]
  142. title = self.guess_namespace(site, title, constants.NS_CATEGORY)
  143. self.process_category(site.get_page(title), job, recursive)
  144. if "file" in kwargs:
  145. with open(kwargs["file"], "r") as fileobj:
  146. for line in fileobj:
  147. if line.strip():
  148. line = line.decode("utf8")
  149. if line.startswith("[[") and line.endswith("]]"):
  150. line = line[2:-2]
  151. page = site.get_page(line)
  152. if page.namespace == constants.NS_CATEGORY:
  153. self.process_category(page, job, recursive)
  154. else:
  155. self.process_page(page, job)
  156. def guess_namespace(self, site, title, assumed):
  157. """If the given *title* does not have an explicit namespace, guess it.
  158. For example, when transcluding templates, the namespace is guessed to
  159. be ``NS_TEMPLATE`` unless one is explicitly declared (so ``{{foo}}`` ->
  160. ``[[Template:Foo]]``, but ``{{:foo}}`` -> ``[[Foo]]``).
  161. """
  162. prefix = title.split(":", 1)[0]
  163. if prefix == title:
  164. return u":".join((site.namespace_id_to_name(assumed), title))
  165. try:
  166. site.namespace_name_to_id(prefix)
  167. except exceptions.NamespaceNotFoundError:
  168. return u":".join((site.namespace_id_to_name(assumed), title))
  169. return title
  170. def get_names(self, site, banner):
  171. """Return all possible aliases for a given *banner* template."""
  172. title = self.guess_namespace(site, banner, constants.NS_TEMPLATE)
  173. if title == banner:
  174. banner = banner.split(":", 1)[1]
  175. page = site.get_page(title)
  176. if page.exists != page.PAGE_EXISTS:
  177. self.logger.error(u"Banner [[%s]] does not exist", title)
  178. return banner, None
  179. names = {banner, title}
  180. result = site.api_query(action="query", list="backlinks", bllimit=500,
  181. blfilterredir="redirects", bltitle=title)
  182. for backlink in result["query"]["backlinks"]:
  183. names.add(backlink["title"])
  184. if backlink["ns"] == constants.NS_TEMPLATE:
  185. names.add(backlink["title"].split(":", 1)[1])
  186. log = u"Found %s aliases for banner [[%s]]"
  187. self.logger.debug(log, len(names), title)
  188. return banner, names
  189. def process_category(self, page, job, recursive):
  190. """Try to tag all pages in the given category."""
  191. self.logger.info(u"Processing category: [[%s]]", page.title)
  192. for member in page.get_members():
  193. if member.namespace == constants.NS_CATEGORY:
  194. if recursive is True:
  195. self.process_category(member, job, True)
  196. elif recursive > 0:
  197. self.process_category(member, job, recursive - 1)
  198. else:
  199. self.process_page(member, job)
  200. def process_page(self, page, job):
  201. """Try to tag a specific *page* using the *job* description."""
  202. if job.counter % 10 == 0: # Do a shutoff check every ten pages
  203. if self.shutoff_enabled(page.site):
  204. raise _ShutoffEnabled()
  205. job.counter += 1
  206. if not page.is_talkpage:
  207. page = page.toggle_talk()
  208. try:
  209. code = page.parse()
  210. except exceptions.PageNotFoundError:
  211. self.process_new_page(page, job)
  212. return
  213. except exceptions.InvalidPageError:
  214. self.logger.error(u"Skipping invalid page: [[%s]]", page.title)
  215. return
  216. is_update = False
  217. for template in code.ifilter_templates(recursive=True):
  218. if template.name.matches(job.names):
  219. if job.update:
  220. banner = template
  221. is_update = True
  222. break
  223. else:
  224. log = u"Skipping page: [[%s]]; already tagged with '%s'"
  225. self.logger.info(log, page.title, template.name)
  226. return
  227. if job.only_with:
  228. if not any(template.name.matches(job.only_with)
  229. for template in code.ifilter_templates(recursive=True)):
  230. log = u"Skipping page: [[%s]]; fails only-with condition"
  231. self.logger.info(log, page.title)
  232. return
  233. if is_update:
  234. old_banner = unicode(banner)
  235. self.update_banner(banner, job, code)
  236. if banner == old_banner:
  237. log = u"Skipping page: [[%s]]; already tagged and no updates"
  238. self.logger.info(log, page.title)
  239. return
  240. self.logger.info(u"Updating banner on page: [[%s]]", page.title)
  241. banner = banner.encode("utf8")
  242. else:
  243. self.logger.info(u"Tagging page: [[%s]]", page.title)
  244. banner = self.make_banner(job, code)
  245. shell = self.get_banner_shell(code)
  246. if shell:
  247. if shell.has_param(1):
  248. shell.get(1).value.insert(0, banner + "\n")
  249. else:
  250. shell.add(1, banner)
  251. else:
  252. self.add_banner(code, banner)
  253. if job.genfixes:
  254. self.apply_genfixes(code)
  255. self.save_page(page, job, unicode(code), banner)
  256. def process_new_page(self, page, job):
  257. """Try to tag a *page* that doesn't exist yet using the *job*."""
  258. if job.nocreate or job.only_with:
  259. log = u"Skipping nonexistent page: [[%s]]"
  260. self.logger.info(log, page.title)
  261. else:
  262. self.logger.info(u"Tagging new page: [[%s]]", page.title)
  263. banner = self.make_banner(job)
  264. self.save_page(page, job, banner, banner)
  265. def save_page(self, page, job, text, banner):
  266. """Save a page with an updated banner."""
  267. if job.dry_run:
  268. self.logger.debug(u"[DRY RUN] Banner: %s", banner)
  269. else:
  270. summary = job.summary.replace("$3", banner)
  271. page.edit(text, self.make_summary(summary), minor=True)
  272. def make_banner(self, job, code=None):
  273. """Return banner text to add based on a *job* and a page's *code*."""
  274. banner = job.banner
  275. if code is not None and job.autoassess is not False:
  276. assessment = self.get_autoassessment(code, job.autoassess)
  277. if assessment:
  278. banner += "|class=" + assessment
  279. if job.append:
  280. banner += "|" + "|".join(job.append.split(","))
  281. return "{{" + banner + "}}"
  282. def update_banner(self, banner, job, code):
  283. """Update an existing *banner* based on a *job* and a page's *code*."""
  284. has = lambda key: (banner.has(key) and
  285. banner.get(key).value.strip() not in ("", "?"))
  286. if job.autoassess is not False:
  287. if not has("class"):
  288. assessment = self.get_autoassessment(code, job.autoassess)
  289. if assessment:
  290. banner.add("class", assessment)
  291. if job.append:
  292. for param in job.append.split(","):
  293. key, value = param.split("=", 1)
  294. if not has(key):
  295. banner.add(key, value)
  296. def get_autoassessment(self, code, only_classes=None):
  297. if only_classes is None:
  298. classnames = ["a", "b", "book", "c", "category", "dab", "fa",
  299. "fl", "ga", "list", "redirect", "start", "stub",
  300. "template"]
  301. else:
  302. classnames = [klass.strip().lower()
  303. for klass in only_classes.split(",")]
  304. classes = {klass: 0 for klass in classnames}
  305. for template in code.ifilter_templates(recursive=True):
  306. if template.has("class"):
  307. value = unicode(template.get("class").value).lower()
  308. if value in classes:
  309. classes[value] += 1
  310. values = tuple(classes.values())
  311. best = max(values)
  312. if best:
  313. confidence = float(best) / sum(values)
  314. if confidence > 0.75:
  315. rank = tuple(classes.keys())[values.index(best)]
  316. if rank in ("fa", "fl", "ga"):
  317. return rank.upper()
  318. else:
  319. return self._upperfirst(rank)
  320. return None
  321. def get_banner_shell(self, code):
  322. """Return the banner shell template within *code*, else ``None``."""
  323. regex = r"^\{\{\s*((WikiProject|WP)[ _]?Banner[ _]?S(hell)?|W(BPS|PBS|PB)|Shell)"
  324. shells = code.filter_templates(matches=regex)
  325. if not shells:
  326. shells = code.filter_templates(matches=regex, recursive=True)
  327. if shells:
  328. log = u"Inserting banner into shell: %s"
  329. self.logger.debug(log, shells[0].name)
  330. return shells[0]
  331. def add_banner(self, code, banner):
  332. """Add *banner* to *code*, following template order conventions."""
  333. index = 0
  334. for i, template in enumerate(code.ifilter_templates()):
  335. name = template.name.lower().replace("_", " ")
  336. for regex in self.TOP_TEMPS:
  337. if re.match(regex, name):
  338. self.logger.debug(u"Skipping top template: %s", name)
  339. index = i + 1
  340. self.logger.debug(u"Inserting banner at index %s", index)
  341. code.insert(index, banner)
  342. def apply_genfixes(self, code):
  343. """Apply general fixes to *code*, such as template substitution."""
  344. regex = (r"^\{\{\s*((un|no)?s(i((gn|ng)(ed3?)?|g))?|usu|tilde|"
  345. r"forgot to sign|without signature)")
  346. for template in code.ifilter_templates(matches=regex):
  347. self.logger.debug("Applying genfix: substitute {{unsigned}}")
  348. template.name = "subst:unsigned"
  349. class _Job(object):
  350. """Represents a single wikiproject-tagging task.
  351. Stores information on the banner to add, the edit summary to use, whether
  352. or not to autoassess and create new pages from scratch, and a counter of
  353. the number of pages edited.
  354. """
  355. def __init__(self, **kwargs):
  356. self.banner = kwargs["banner"]
  357. self.names = kwargs["names"]
  358. self.summary = kwargs["summary"]
  359. self.update = kwargs["update"]
  360. self.append = kwargs["append"]
  361. self.autoassess = kwargs["autoassess"]
  362. self.only_with = kwargs["only_with"]
  363. self.nocreate = kwargs["nocreate"]
  364. self.genfixes = kwargs["genfixes"]
  365. self.dry_run = kwargs["dry_run"]
  366. self.counter = 0
  367. class _ShutoffEnabled(Exception):
  368. """Raised by process_page() if shutoff is enabled. Caught by run(), which
  369. will then stop the task."""
  370. pass