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.

418 lines
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. else:
  242. self.logger.info(u"Tagging page: [[%s]]", page.title)
  243. banner = self.make_banner(job, code)
  244. shell = self.get_banner_shell(code)
  245. if shell:
  246. if shell.has_param(1):
  247. shell.get(1).value.insert(0, banner + "\n")
  248. else:
  249. shell.add(1, banner)
  250. else:
  251. self.add_banner(code, banner)
  252. if job.genfixes:
  253. self.apply_genfixes(code)
  254. if job.dry_run:
  255. self.logger.debug(u"DRY RUN: Banner: %s", banner)
  256. else:
  257. summary = job.summary.replace("$3", banner)
  258. page.edit(unicode(code), self.make_summary(summary))
  259. def process_new_page(self, page, job):
  260. """Try to tag a *page* that doesn't exist yet using the *job*."""
  261. if job.nocreate or job.only_with:
  262. log = u"Skipping nonexistent page: [[%s]]"
  263. self.logger.info(log, page.title)
  264. else:
  265. self.logger.info(u"Tagging new page: [[%s]]", page.title)
  266. banner = self.make_banner(job)
  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(banner, self.make_summary(summary))
  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. if job.autoassess is not False:
  285. if not banner.has("class") or not banner.get("class").value:
  286. assessment = self.get_autoassessment(code, job.autoassess)
  287. if assessment:
  288. banner.add("class", assessment)
  289. if job.append:
  290. for param in job.append.split(","):
  291. key, value = param.split("=", 1)
  292. if not banner.has(key) or not banner.get(key).value:
  293. banner.add(key, value)
  294. def get_autoassessment(self, code, only_classes=None):
  295. if only_classes is None:
  296. classnames = ["a", "b", "book", "c", "category", "dab", "fa",
  297. "fl", "ga", "list", "redirect", "start", "stub",
  298. "template"]
  299. else:
  300. classnames = [klass.strip().lower()
  301. for klass in only_classes.split(",")]
  302. classes = {klass: 0 for klass in classnames}
  303. for template in code.ifilter_templates(recursive=True):
  304. if template.has("class"):
  305. value = unicode(template.get("class").value).lower()
  306. if value in classes:
  307. classes[value] += 1
  308. values = tuple(classes.values())
  309. if values:
  310. best = max(values)
  311. confidence = float(best) / sum(values)
  312. if confidence > 0.75:
  313. rank = tuple(classes.keys())[values.index(best)]
  314. if rank in ("fa", "fl", "ga"):
  315. return rank.upper()
  316. else:
  317. return self._upperfirst(rank)
  318. return None
  319. def get_banner_shell(self, code):
  320. """Return the banner shell template within *code*, else ``None``."""
  321. regex = r"^\{\{\s*((WikiProject|WP)[ _]?Banner[ _]?S(hell)?|W(BPS|PBS|PB)|Shell)"
  322. shells = code.filter_templates(matches=regex)
  323. if not shells:
  324. shells = code.filter_templates(matches=regex, recursive=True)
  325. if shells:
  326. log = u"Inserting banner into shell: %s"
  327. self.logger.debug(log, shells[0].name)
  328. return shells[0]
  329. def add_banner(self, code, banner):
  330. """Add *banner* to *code*, following template order conventions."""
  331. index = 0
  332. for i, template in enumerate(code.ifilter_templates()):
  333. name = template.name.lower().replace("_", " ")
  334. for regex in self.TOP_TEMPS:
  335. if re.match(regex, name):
  336. self.logger.debug(u"Skipping top template: %s", name)
  337. index = i + 1
  338. self.logger.debug(u"Inserting banner at index %s", index)
  339. code.insert(index, banner)
  340. def apply_genfixes(self, code):
  341. """Apply general fixes to *code*, such as template substitution."""
  342. regex = (r"^\{\{\s*((un|no)?s(i((gn|ng)(ed3?)?|g))?|usu|tilde|"
  343. r"forgot to sign|without signature)")
  344. for template in code.ifilter_templates(matches=regex):
  345. self.logger.debug("Applying genfix: substitute {{unsigned}}")
  346. template.name = "subst:unsigned"
  347. class _Job(object):
  348. """Represents a single wikiproject-tagging task.
  349. Stores information on the banner to add, the edit summary to use, whether
  350. or not to autoassess and create new pages from scratch, and a counter of
  351. the number of pages edited.
  352. """
  353. def __init__(self, **kwargs):
  354. self.banner = kwargs["banner"]
  355. self.names = kwargs["names"]
  356. self.summary = kwargs["summary"]
  357. self.update = kwargs["update"]
  358. self.append = kwargs["append"]
  359. self.autoassess = kwargs["autoassess"]
  360. self.only_with = kwargs["only_with"]
  361. self.nocreate = kwargs["nocreate"]
  362. self.genfixes = kwargs["genfixes"]
  363. self.dry_run = kwargs["dry_run"]
  364. self.counter = 0
  365. class _ShutoffEnabled(Exception):
  366. """Raised by process_page() if shutoff is enabled. Caught by run(), which
  367. will then stop the task."""
  368. pass