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.

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