A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

443 Zeilen
18 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]] [--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. ``--tag-categories``
  65. also tag category pages; will autoassess with ``|class=category`` if
  66. ``--autoassess`` is given
  67. ``--site SITE``
  68. the ID of the site to tag pages on, defaulting to the default site
  69. ``--dry-run``
  70. don't actually make any edits, just log the pages that would have been
  71. edited
  72. """
  73. name = "wikiproject_tagger"
  74. # Regexes for template names that should always go above the banner, based
  75. # on [[Wikipedia:Talk page layout]]:
  76. TOP_TEMPS = [
  77. r"skip ?to ?(toc|talk|toctalk)$",
  78. r"ga ?nominee$",
  79. r"(user ?)?talk ?(header|page|page ?header)$",
  80. r"community ?article ?probation$",
  81. r"censor(-nudity)?$",
  82. r"blp(o| ?others?)?$",
  83. r"controvers(ial2?|y)$",
  84. r"(not ?(a ?)?)?forum$",
  85. r"tv(episode|series)talk$",
  86. r"recurring ?themes$",
  87. r"faq$",
  88. r"(round ?in ?)?circ(les|ular)$",
  89. r"ar(ti|it)cle ?(history|milestones)$",
  90. r"failed ?ga$",
  91. r"old ?prod( ?full)?$",
  92. r"(old|previous) ?afd$",
  93. r"((wikiproject|wp) ?)?bio(graph(y|ies))?$",
  94. ]
  95. @staticmethod
  96. def _upperfirst(text):
  97. """Try to uppercase the first letter of a string."""
  98. try:
  99. return text[0].upper() + text[1:]
  100. except IndexError:
  101. return text
  102. def run(self, **kwargs):
  103. """Main entry point for the bot task."""
  104. if "file" not in kwargs and "category" not in kwargs:
  105. log = "No pages to tag; I need either a 'category' or a 'file' passed as kwargs"
  106. self.logger.error(log)
  107. return
  108. if "banner" not in kwargs:
  109. log = "Needs a banner to add passed as the 'banner' kwarg"
  110. self.logger.error(log)
  111. return
  112. site = self.bot.wiki.get_site(name=kwargs.get("site"))
  113. banner = kwargs["banner"]
  114. summary = kwargs.get("summary", "Tagging with WikiProject banner $3.")
  115. update = kwargs.get("update", False)
  116. append = kwargs.get("append")
  117. autoassess = kwargs.get("autoassess", False)
  118. ow_banner = kwargs.get("only-with")
  119. nocreate = kwargs.get("nocreate", False)
  120. recursive = kwargs.get("recursive", 0)
  121. tag_categories = kwargs.get("tag-categories", False)
  122. dry_run = kwargs.get("dry-run", False)
  123. banner, names = self.get_names(site, banner)
  124. if not names:
  125. return
  126. if ow_banner:
  127. _, only_with = self.get_names(site, ow_banner)
  128. if not only_with:
  129. return
  130. else:
  131. only_with = None
  132. job = _Job(banner=banner, names=names, summary=summary, update=update,
  133. append=append, autoassess=autoassess, only_with=only_with,
  134. nocreate=nocreate, tag_categories=tag_categories,
  135. dry_run=dry_run)
  136. try:
  137. self.run_job(kwargs, site, job, recursive)
  138. except _ShutoffEnabled:
  139. return
  140. def run_job(self, kwargs, site, job, recursive):
  141. """Run a tagging *job* on a given *site*."""
  142. if "category" in kwargs:
  143. title = kwargs["category"]
  144. title = self.guess_namespace(site, title, constants.NS_CATEGORY)
  145. self.process_category(site.get_page(title), job, recursive)
  146. if "file" in kwargs:
  147. with open(kwargs["file"], "r") as fileobj:
  148. for line in fileobj:
  149. if line.strip():
  150. line = line.decode("utf8")
  151. if line.startswith("[[") and line.endswith("]]"):
  152. line = line[2:-2]
  153. page = site.get_page(line)
  154. if page.namespace == constants.NS_CATEGORY:
  155. self.process_category(page, job, recursive)
  156. else:
  157. self.process_page(page, job)
  158. def guess_namespace(self, site, title, assumed):
  159. """If the given *title* does not have an explicit namespace, guess it.
  160. For example, when transcluding templates, the namespace is guessed to
  161. be ``NS_TEMPLATE`` unless one is explicitly declared (so ``{{foo}}`` ->
  162. ``[[Template:Foo]]``, but ``{{:foo}}`` -> ``[[Foo]]``).
  163. """
  164. prefix = title.split(":", 1)[0]
  165. if prefix == title:
  166. return u":".join((site.namespace_id_to_name(assumed), title))
  167. try:
  168. site.namespace_name_to_id(prefix)
  169. except exceptions.NamespaceNotFoundError:
  170. return u":".join((site.namespace_id_to_name(assumed), title))
  171. return title
  172. def get_names(self, site, banner):
  173. """Return all possible aliases for a given *banner* template."""
  174. title = self.guess_namespace(site, banner, constants.NS_TEMPLATE)
  175. if title == banner:
  176. banner = banner.split(":", 1)[1]
  177. page = site.get_page(title)
  178. if page.exists != page.PAGE_EXISTS:
  179. self.logger.error(u"Banner [[%s]] does not exist", title)
  180. return banner, None
  181. names = {banner, title}
  182. result = site.api_query(action="query", list="backlinks", bllimit=500,
  183. blfilterredir="redirects", bltitle=title)
  184. for backlink in result["query"]["backlinks"]:
  185. names.add(backlink["title"])
  186. if backlink["ns"] == constants.NS_TEMPLATE:
  187. names.add(backlink["title"].split(":", 1)[1])
  188. log = u"Found %s aliases for banner [[%s]]"
  189. self.logger.debug(log, len(names), title)
  190. return banner, names
  191. def process_category(self, page, job, recursive):
  192. """Try to tag all pages in the given category."""
  193. self.logger.info(u"Processing category: [[%s]]", page.title)
  194. if job.tag_categories:
  195. self.process_page(page, job, is_category=True)
  196. for member in page.get_members():
  197. if member.namespace == constants.NS_CATEGORY:
  198. if recursive is True:
  199. self.process_category(member, job, True)
  200. elif recursive > 0:
  201. self.process_category(member, job, recursive - 1)
  202. elif job.tag_categories:
  203. self.process_page(member, job, is_category=True)
  204. else:
  205. self.process_page(member, job)
  206. def process_page(self, page, job, is_category=False):
  207. """Try to tag a specific *page* using the *job* description."""
  208. if job.counter % 10 == 0: # Do a shutoff check every ten pages
  209. if self.shutoff_enabled(page.site):
  210. raise _ShutoffEnabled()
  211. job.counter += 1
  212. if not page.is_talkpage:
  213. page = page.toggle_talk()
  214. try:
  215. code = page.parse()
  216. except exceptions.PageNotFoundError:
  217. self.process_new_page(page, job)
  218. return
  219. except exceptions.InvalidPageError:
  220. self.logger.error(u"Skipping invalid page: [[%s]]", page.title)
  221. return
  222. is_update = False
  223. for template in code.ifilter_templates(recursive=True):
  224. if template.name.matches(job.names):
  225. if job.update:
  226. banner = template
  227. is_update = True
  228. break
  229. else:
  230. log = u"Skipping page: [[%s]]; already tagged with '%s'"
  231. self.logger.info(log, page.title, template.name)
  232. return
  233. if job.only_with:
  234. if not any(template.name.matches(job.only_with)
  235. for template in code.ifilter_templates(recursive=True)):
  236. log = u"Skipping page: [[%s]]; fails only-with condition"
  237. self.logger.info(log, page.title)
  238. return
  239. if is_update:
  240. old_banner = unicode(banner)
  241. self.update_banner(banner, job, code, is_category=is_category)
  242. if banner == old_banner:
  243. log = u"Skipping page: [[%s]]; already tagged and no updates"
  244. self.logger.info(log, page.title)
  245. return
  246. self.logger.info(u"Updating banner on page: [[%s]]", page.title)
  247. banner = banner.encode("utf8")
  248. else:
  249. self.logger.info(u"Tagging page: [[%s]]", page.title)
  250. banner = self.make_banner(job, code, is_category=is_category)
  251. shell = self.get_banner_shell(code)
  252. if shell:
  253. self.add_banner_to_shell(shell, banner)
  254. else:
  255. self.add_banner(code, banner)
  256. self.save_page(page, job, unicode(code), banner)
  257. def process_new_page(self, page, job):
  258. """Try to tag a *page* that doesn't exist yet using the *job*."""
  259. if job.nocreate or job.only_with:
  260. log = u"Skipping nonexistent page: [[%s]]"
  261. self.logger.info(log, page.title)
  262. else:
  263. self.logger.info(u"Tagging new page: [[%s]]", page.title)
  264. banner = self.make_banner(job)
  265. self.save_page(page, job, banner, banner)
  266. def save_page(self, page, job, text, banner):
  267. """Save a page with an updated banner."""
  268. if job.dry_run:
  269. self.logger.debug(u"[DRY RUN] Banner: %s", banner)
  270. else:
  271. summary = job.summary.replace("$3", banner)
  272. page.edit(text, self.make_summary(summary), minor=True)
  273. def make_banner(self, job, code=None, is_category=False):
  274. """Return banner text to add based on a *job* and a page's *code*."""
  275. banner = job.banner
  276. if code is not None and job.autoassess is not False:
  277. assess, reason = self.get_autoassessment(
  278. code, job.autoassess, is_category=is_category)
  279. if assess:
  280. banner += "|class=" + assess
  281. if reason:
  282. banner += "|auto=" + reason
  283. if job.append:
  284. banner += "|" + "|".join(job.append.split(","))
  285. return "{{" + banner + "}}"
  286. def update_banner(self, banner, job, code, is_category=False):
  287. """Update an existing *banner* based on a *job* and a page's *code*."""
  288. has = lambda key: (banner.has(key) and
  289. banner.get(key).value.strip() not in ("", "?"))
  290. if job.autoassess is not False:
  291. if not has("class"):
  292. assess, reason = self.get_autoassessment(
  293. code, job.autoassess, is_category=is_category)
  294. if assess:
  295. banner.add("class", assess)
  296. if reason:
  297. banner.add("auto", reason)
  298. if job.append:
  299. for param in job.append.split(","):
  300. key, value = param.split("=", 1)
  301. if not has(key):
  302. banner.add(key, value)
  303. def get_autoassessment(self, code, only_classes=None, is_category=False):
  304. """Get an autoassessment for a page.
  305. Return (assessed class as a string or None, assessment reason or None).
  306. """
  307. if only_classes is None:
  308. classnames = ["a", "b", "book", "c", "category", "dab", "fa",
  309. "fl", "ga", "list", "redirect", "start", "stub",
  310. "template"]
  311. else:
  312. classnames = [klass.strip().lower()
  313. for klass in only_classes.split(",")]
  314. if is_category:
  315. return ("category" if "category" in classnames else None), None
  316. classes = {klass: 0 for klass in classnames}
  317. for template in code.ifilter_templates(recursive=True):
  318. if template.has("class"):
  319. value = unicode(template.get("class").value).lower()
  320. if value in classes:
  321. classes[value] += 1
  322. values = tuple(classes.values())
  323. best = max(values)
  324. if best:
  325. confidence = float(best) / sum(values)
  326. if confidence > 0.75:
  327. rank = tuple(classes.keys())[values.index(best)]
  328. if rank in ("fa", "fl", "ga"):
  329. return rank.upper(), "inherit"
  330. else:
  331. return self._upperfirst(rank), "inherit"
  332. return None, None
  333. def get_banner_shell(self, code):
  334. """Return the banner shell template within *code*, else ``None``."""
  335. regex = r"^\{\{\s*((WikiProject|WP)[ _]?Banner[ _]?S(hell)?|W(BPS|PBS|PB)|Shell)"
  336. shells = code.filter_templates(matches=regex)
  337. if not shells:
  338. shells = code.filter_templates(matches=regex, recursive=True)
  339. if shells:
  340. log = u"Inserting banner into shell: %s"
  341. self.logger.debug(log, shells[0].name)
  342. return shells[0]
  343. def add_banner_to_shell(self, shell, banner):
  344. """Add *banner* to *shell*."""
  345. if shell.has_param(1):
  346. if unicode(shell.get(1).value).endswith("\n"):
  347. banner += "\n"
  348. else:
  349. banner = "\n" + banner
  350. shell.get(1).value.append(banner)
  351. else:
  352. shell.add(1, banner)
  353. def add_banner(self, code, banner):
  354. """Add *banner* to *code*, following template order conventions."""
  355. index = 0
  356. for i, template in enumerate(code.ifilter_templates()):
  357. name = template.name.lower().replace("_", " ")
  358. for regex in self.TOP_TEMPS:
  359. if re.match(regex, name):
  360. self.logger.debug(u"Adding after top template: %s", name)
  361. index = i + 1
  362. if "wikiproject" in name or name.startswith("wp"):
  363. self.logger.debug(u"Adding after banner template: %s", name)
  364. index = i + 1
  365. self.logger.debug(u"Inserting banner at index %s", index)
  366. if index > 0 and not unicode(code.get(index - 1)).endswith("\n"):
  367. banner = "\n" + banner
  368. code.insert(index, banner + "\n")
  369. class _Job(object):
  370. """Represents a single wikiproject-tagging task.
  371. Stores information on the banner to add, the edit summary to use, whether
  372. or not to autoassess and create new pages from scratch, and a counter of
  373. the number of pages edited.
  374. """
  375. def __init__(self, **kwargs):
  376. self.banner = kwargs["banner"]
  377. self.names = kwargs["names"]
  378. self.summary = kwargs["summary"]
  379. self.update = kwargs["update"]
  380. self.append = kwargs["append"]
  381. self.autoassess = kwargs["autoassess"]
  382. self.only_with = kwargs["only_with"]
  383. self.nocreate = kwargs["nocreate"]
  384. self.tag_categories = kwargs["tag_categories"]
  385. self.dry_run = kwargs["dry_run"]
  386. self.counter = 0
  387. class _ShutoffEnabled(Exception):
  388. """Raised by process_page() if shutoff is enabled. Caught by run(), which
  389. will then stop the task."""
  390. pass