A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

336 rader
12 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2019 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. from os import path
  23. import re
  24. from StringIO import StringIO
  25. import urlparse
  26. import mwparserfromhell
  27. from earwigbot import importer
  28. from earwigbot.exceptions import ParserExclusionError, ParserRedirectError
  29. bs4 = importer.new("bs4")
  30. nltk = importer.new("nltk")
  31. converter = importer.new("pdfminer.converter")
  32. pdfinterp = importer.new("pdfminer.pdfinterp")
  33. pdfpage = importer.new("pdfminer.pdfpage")
  34. __all__ = ["ArticleTextParser", "get_parser"]
  35. class _BaseTextParser(object):
  36. """Base class for a parser that handles text."""
  37. TYPE = None
  38. def __init__(self, text, url=None, args=None):
  39. self.text = text
  40. self.url = url
  41. self._args = args or {}
  42. def __repr__(self):
  43. """Return the canonical string representation of the text parser."""
  44. return "{0}(text={1!r})".format(self.__class__.__name__, self.text)
  45. def __str__(self):
  46. """Return a nice string representation of the text parser."""
  47. name = self.__class__.__name__
  48. return "<{0} of text with size {1}>".format(name, len(self.text))
  49. class ArticleTextParser(_BaseTextParser):
  50. """A parser that can strip and chunk wikicode article text."""
  51. TYPE = "Article"
  52. TEMPLATE_MERGE_THRESHOLD = 35
  53. NLTK_DEFAULT = "english"
  54. NLTK_LANGS = {
  55. "cs": "czech",
  56. "da": "danish",
  57. "de": "german",
  58. "el": "greek",
  59. "en": "english",
  60. "es": "spanish",
  61. "et": "estonian",
  62. "fi": "finnish",
  63. "fr": "french",
  64. "it": "italian",
  65. "nl": "dutch",
  66. "no": "norwegian",
  67. "pl": "polish",
  68. "pt": "portuguese",
  69. "sl": "slovene",
  70. "sv": "swedish",
  71. "tr": "turkish"
  72. }
  73. def _merge_templates(self, code):
  74. """Merge template contents in to wikicode when the values are long."""
  75. for template in code.filter_templates(recursive=code.RECURSE_OTHERS):
  76. chunks = []
  77. for param in template.params:
  78. if len(param.value) >= self.TEMPLATE_MERGE_THRESHOLD:
  79. self._merge_templates(param.value)
  80. chunks.append(param.value)
  81. if chunks:
  82. subst = u" ".join(map(unicode, chunks))
  83. code.replace(template, u" " + subst + u" ")
  84. else:
  85. code.remove(template)
  86. def _get_tokenizer(self):
  87. """Return a NLTK punctuation tokenizer for the article's language."""
  88. datafile = lambda lang: "file:" + path.join(
  89. self._args["nltk_dir"], "tokenizers", "punkt", lang + ".pickle")
  90. lang = self.NLTK_LANGS.get(self._args.get("lang"), self.NLTK_DEFAULT)
  91. try:
  92. nltk.data.load(datafile(self.NLTK_DEFAULT))
  93. except LookupError:
  94. nltk.download("punkt", self._args["nltk_dir"])
  95. return nltk.data.load(datafile(lang))
  96. def _get_sentences(self, min_query, max_query, split_thresh):
  97. """Split the article text into sentences of a certain length."""
  98. def cut_sentence(words):
  99. div = len(words)
  100. if div == 0:
  101. return []
  102. length = len(" ".join(words))
  103. while length > max_query:
  104. div -= 1
  105. length -= len(words[div]) + 1
  106. result = []
  107. if length >= split_thresh:
  108. result.append(" ".join(words[:div]))
  109. return result + cut_sentence(words[div + 1:])
  110. tokenizer = self._get_tokenizer()
  111. sentences = []
  112. if not hasattr(self, "clean"):
  113. self.strip()
  114. for sentence in tokenizer.tokenize(self.clean):
  115. if len(sentence) <= max_query:
  116. sentences.append(sentence)
  117. else:
  118. sentences.extend(cut_sentence(sentence.split()))
  119. return [sen for sen in sentences if len(sen) >= min_query]
  120. def strip(self):
  121. """Clean the page's raw text by removing templates and formatting.
  122. Return the page's text with all HTML and wikicode formatting removed,
  123. including templates, tables, and references. It retains punctuation
  124. (spacing, paragraphs, periods, commas, (semi)-colons, parentheses,
  125. quotes), original capitalization, and so forth. HTML entities are
  126. replaced by their unicode equivalents.
  127. The actual stripping is handled by :py:mod:`mwparserfromhell`.
  128. """
  129. def remove(code, node):
  130. """Remove a node from a code object, ignoring ValueError.
  131. Sometimes we will remove a node that contains another node we wish
  132. to remove, and we fail when we try to remove the inner one. Easiest
  133. solution is to just ignore the exception.
  134. """
  135. try:
  136. code.remove(node)
  137. except ValueError:
  138. pass
  139. wikicode = mwparserfromhell.parse(self.text)
  140. # Preemtively strip some links mwparser doesn't know about:
  141. bad_prefixes = ("file:", "image:", "category:")
  142. for link in wikicode.filter_wikilinks():
  143. if link.title.strip().lower().startswith(bad_prefixes):
  144. remove(wikicode, link)
  145. # Also strip references:
  146. for tag in wikicode.filter_tags(matches=lambda tag: tag.tag == "ref"):
  147. remove(wikicode, tag)
  148. # Merge in template contents when the values are long:
  149. self._merge_templates(wikicode)
  150. clean = wikicode.strip_code(normalize=True, collapse=True)
  151. self.clean = re.sub("\n\n+", "\n", clean).strip()
  152. return self.clean
  153. def chunk(self, max_chunks, min_query=8, max_query=128, split_thresh=32):
  154. """Convert the clean article text into a list of web-searchable chunks.
  155. No greater than *max_chunks* will be returned. Each chunk will only be
  156. a sentence or two long at most (no more than *max_query*). The idea is
  157. to return a sample of the article text rather than the whole, so we'll
  158. pick and choose from parts of it, especially if the article is large
  159. and *max_chunks* is low, so we don't end up just searching for just the
  160. first paragraph.
  161. This is implemented using :py:mod:`nltk` (http://nltk.org/). A base
  162. directory (*nltk_dir*) is required to store nltk's punctuation
  163. database, and should be passed as an argument to the constructor. It is
  164. typically located in the bot's working directory.
  165. """
  166. sentences = self._get_sentences(min_query, max_query, split_thresh)
  167. if len(sentences) <= max_chunks:
  168. return sentences
  169. chunks = []
  170. while len(chunks) < max_chunks:
  171. if len(chunks) % 5 == 0:
  172. chunk = sentences.pop(0) # Pop from beginning
  173. elif len(chunks) % 5 == 1:
  174. chunk = sentences.pop() # Pop from end
  175. elif len(chunks) % 5 == 2:
  176. chunk = sentences.pop(len(sentences) / 2) # Pop from Q2
  177. elif len(chunks) % 5 == 3:
  178. chunk = sentences.pop(len(sentences) / 4) # Pop from Q1
  179. else:
  180. chunk = sentences.pop(3 * len(sentences) / 4) # Pop from Q3
  181. chunks.append(chunk)
  182. return chunks
  183. def get_links(self):
  184. """Return a list of all external links in the article.
  185. The list is restricted to things that we suspect we can parse: i.e.,
  186. those with schemes of ``http`` and ``https``.
  187. """
  188. schemes = ("http://", "https://")
  189. links = mwparserfromhell.parse(self.text).ifilter_external_links()
  190. return [unicode(link.url) for link in links
  191. if link.url.startswith(schemes)]
  192. class _HTMLParser(_BaseTextParser):
  193. """A parser that can extract the text from an HTML document."""
  194. TYPE = "HTML"
  195. hidden_tags = [
  196. "script", "style"
  197. ]
  198. def _fail_if_mirror(self, soup):
  199. """Look for obvious signs that the given soup is a wiki mirror.
  200. If so, raise ParserExclusionError, which is caught in the workers and
  201. causes this source to excluded.
  202. """
  203. if "mirror_hints" not in self._args:
  204. return
  205. func = lambda attr: attr and any(
  206. hint in attr for hint in self._args["mirror_hints"])
  207. if soup.find_all(href=func) or soup.find_all(src=func):
  208. raise ParserExclusionError()
  209. def parse(self):
  210. """Return the actual text contained within an HTML document.
  211. Implemented using :py:mod:`BeautifulSoup <bs4>`
  212. (http://www.crummy.com/software/BeautifulSoup/).
  213. """
  214. try:
  215. soup = bs4.BeautifulSoup(self.text, "lxml")
  216. except ValueError:
  217. soup = bs4.BeautifulSoup(self.text)
  218. if not soup.body:
  219. # No <body> tag present in HTML ->
  220. # no scrapable content (possibly JS or <iframe> magic):
  221. return ""
  222. self._fail_if_mirror(soup)
  223. soup = soup.body
  224. if self.url:
  225. url = urlparse.urlparse(self.url)
  226. if url.netloc == "web.archive.org" and url.path.endswith(".pdf"):
  227. playback = soup.find(id="playback")
  228. if playback and "src" in playback.attrs:
  229. raise ParserRedirectError(playback.attrs["src"])
  230. is_comment = lambda text: isinstance(text, bs4.element.Comment)
  231. for comment in soup.find_all(text=is_comment):
  232. comment.extract()
  233. for tag in self.hidden_tags:
  234. for element in soup.find_all(tag):
  235. element.extract()
  236. return "\n".join(soup.stripped_strings)
  237. class _PDFParser(_BaseTextParser):
  238. """A parser that can extract text from a PDF file."""
  239. TYPE = "PDF"
  240. substitutions = [
  241. (u"\x0c", u"\n"),
  242. (u"\u2022", u" "),
  243. ]
  244. def parse(self):
  245. """Return extracted text from the PDF."""
  246. output = StringIO()
  247. manager = pdfinterp.PDFResourceManager()
  248. conv = converter.TextConverter(manager, output)
  249. interp = pdfinterp.PDFPageInterpreter(manager, conv)
  250. try:
  251. pages = pdfpage.PDFPage.get_pages(StringIO(self.text))
  252. for page in pages:
  253. interp.process_page(page)
  254. except Exception: # pylint: disable=broad-except
  255. return output.getvalue().decode("utf8")
  256. finally:
  257. conv.close()
  258. value = output.getvalue().decode("utf8")
  259. for orig, new in self.substitutions:
  260. value = value.replace(orig, new)
  261. return re.sub("\n\n+", "\n", value).strip()
  262. class _PlainTextParser(_BaseTextParser):
  263. """A parser that can unicode-ify and strip text from a plain text page."""
  264. TYPE = "Text"
  265. def parse(self):
  266. """Unicode-ify and strip whitespace from the plain text document."""
  267. converted = bs4.UnicodeDammit(self.text).unicode_markup
  268. return converted.strip() if converted else ""
  269. _CONTENT_TYPES = {
  270. "text/html": _HTMLParser,
  271. "application/xhtml+xml": _HTMLParser,
  272. "application/pdf": _PDFParser,
  273. "application/x-pdf": _PDFParser,
  274. "text/plain": _PlainTextParser
  275. }
  276. def get_parser(content_type):
  277. """Return the parser most able to handle a given content type, or None."""
  278. return _CONTENT_TYPES.get(content_type.split(";", 1)[0])