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.

246 lines
9.0 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2015 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 mwparserfromhell
  26. from earwigbot import importer
  27. bs4 = importer.new("bs4")
  28. nltk = importer.new("nltk")
  29. converter = importer.new("pdfminer.converter")
  30. pdfinterp = importer.new("pdfminer.pdfinterp")
  31. pdfpage = importer.new("pdfminer.pdfpage")
  32. pdftypes = importer.new("pdfminer.pdftypes")
  33. psparser = importer.new("pdfminer.psparser")
  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):
  39. self.text = text
  40. def __repr__(self):
  41. """Return the canonical string representation of the text parser."""
  42. return "{0}(text={1!r})".format(self.__class__.__name__, self.text)
  43. def __str__(self):
  44. """Return a nice string representation of the text parser."""
  45. name = self.__class__.__name__
  46. return "<{0} of text with size {1}>".format(name, len(self.text))
  47. class ArticleTextParser(_BaseTextParser):
  48. """A parser that can strip and chunk wikicode article text."""
  49. TYPE = "Article"
  50. def strip(self):
  51. """Clean the page's raw text by removing templates and formatting.
  52. Return the page's text with all HTML and wikicode formatting removed,
  53. including templates, tables, and references. It retains punctuation
  54. (spacing, paragraphs, periods, commas, (semi)-colons, parentheses,
  55. quotes), original capitalization, and so forth. HTML entities are
  56. replaced by their unicode equivalents.
  57. The actual stripping is handled by :py:mod:`mwparserfromhell`.
  58. """
  59. def remove(code, node):
  60. """Remove a node from a code object, ignoring ValueError.
  61. Sometimes we will remove a node that contains another node we wish
  62. to remove, and we fail when we try to remove the inner one. Easiest
  63. solution is to just ignore the exception.
  64. """
  65. try:
  66. code.remove(node)
  67. except ValueError:
  68. pass
  69. wikicode = mwparserfromhell.parse(self.text)
  70. # Preemtively strip some links mwparser doesn't know about:
  71. bad_prefixes = ("file:", "image:", "category:")
  72. for link in wikicode.filter_wikilinks():
  73. if link.title.strip().lower().startswith(bad_prefixes):
  74. remove(wikicode, link)
  75. # Also strip references:
  76. for tag in wikicode.filter_tags(matches=lambda tag: tag.tag == "ref"):
  77. remove(wikicode, tag)
  78. clean = wikicode.strip_code(normalize=True, collapse=True)
  79. self.clean = re.sub("\n\n+", "\n", clean).strip()
  80. return self.clean
  81. def chunk(self, nltk_dir, max_chunks, min_query=8, max_query=128):
  82. """Convert the clean article text into a list of web-searchable chunks.
  83. No greater than *max_chunks* will be returned. Each chunk will only be
  84. a sentence or two long at most (no more than *max_query*). The idea is
  85. to return a sample of the article text rather than the whole, so we'll
  86. pick and choose from parts of it, especially if the article is large
  87. and *max_chunks* is low, so we don't end up just searching for just the
  88. first paragraph.
  89. This is implemented using :py:mod:`nltk` (http://nltk.org/). A base
  90. directory (*nltk_dir*) is required to store nltk's punctuation
  91. database. This is typically located in the bot's working directory.
  92. """
  93. datafile = path.join(nltk_dir, "tokenizers", "punkt", "english.pickle")
  94. try:
  95. tokenizer = nltk.data.load("file:" + datafile)
  96. except LookupError:
  97. nltk.download("punkt", nltk_dir)
  98. tokenizer = nltk.data.load("file:" + datafile)
  99. sentences = []
  100. for sentence in tokenizer.tokenize(self.clean):
  101. if len(sentence) > max_query:
  102. words = sentence.split()
  103. while len(" ".join(words)) > max_query:
  104. words.pop()
  105. sentence = " ".join(words)
  106. if len(sentence) < min_query:
  107. continue
  108. sentences.append(sentence)
  109. if max_chunks >= len(sentences):
  110. return sentences
  111. chunks = []
  112. while len(chunks) < max_chunks:
  113. if len(chunks) % 5 == 0:
  114. chunk = sentences.pop(0) # Pop from beginning
  115. elif len(chunks) % 5 == 1:
  116. chunk = sentences.pop() # Pop from end
  117. elif len(chunks) % 5 == 2:
  118. chunk = sentences.pop(len(sentences) / 2) # Pop from Q2
  119. elif len(chunks) % 5 == 3:
  120. chunk = sentences.pop(len(sentences) / 4) # Pop from Q1
  121. else:
  122. chunk = sentences.pop(3 * len(sentences) / 4) # Pop from Q3
  123. chunks.append(chunk)
  124. return chunks
  125. def get_links(self):
  126. """Return a list of all external links in the article.
  127. The list is restricted to things that we suspect we can parse: i.e.,
  128. those with schemes of ``http`` and ``https``.
  129. """
  130. schemes = ("http://", "https://")
  131. links = mwparserfromhell.parse(self.text).ifilter_external_links()
  132. return [unicode(link.url) for link in links
  133. if link.url.startswith(schemes)]
  134. class _HTMLParser(_BaseTextParser):
  135. """A parser that can extract the text from an HTML document."""
  136. TYPE = "HTML"
  137. hidden_tags = [
  138. "script", "style"
  139. ]
  140. def parse(self):
  141. """Return the actual text contained within an HTML document.
  142. Implemented using :py:mod:`BeautifulSoup <bs4>`
  143. (http://www.crummy.com/software/BeautifulSoup/).
  144. """
  145. try:
  146. soup = bs4.BeautifulSoup(self.text, "lxml").body
  147. except ValueError:
  148. soup = bs4.BeautifulSoup(self.text).body
  149. if not soup:
  150. # No <body> tag present in HTML ->
  151. # no scrapable content (possibly JS or <frame> magic):
  152. return ""
  153. is_comment = lambda text: isinstance(text, bs4.element.Comment)
  154. for comment in soup.find_all(text=is_comment):
  155. comment.extract()
  156. for tag in self.hidden_tags:
  157. for element in soup.find_all(tag):
  158. element.extract()
  159. return "\n".join(soup.stripped_strings)
  160. class _PDFParser(_BaseTextParser):
  161. """A parser that can extract text from a PDF file."""
  162. TYPE = "PDF"
  163. substitutions = [
  164. (u"\x0c", u"\n"),
  165. (u"\u2022", u" "),
  166. ]
  167. def parse(self):
  168. """Return extracted text from the PDF."""
  169. output = StringIO()
  170. manager = pdfinterp.PDFResourceManager()
  171. conv = converter.TextConverter(manager, output)
  172. interp = pdfinterp.PDFPageInterpreter(manager, conv)
  173. try:
  174. pages = pdfpage.PDFPage.get_pages(StringIO(self.text))
  175. for page in pages:
  176. interp.process_page(page)
  177. except (pdftypes.PDFException, psparser.PSException, AssertionError):
  178. return output.getvalue().decode("utf8")
  179. finally:
  180. conv.close()
  181. value = output.getvalue().decode("utf8")
  182. for orig, new in self.substitutions:
  183. value = value.replace(orig, new)
  184. return re.sub("\n\n+", "\n", value).strip()
  185. class _PlainTextParser(_BaseTextParser):
  186. """A parser that can unicode-ify and strip text from a plain text page."""
  187. TYPE = "Text"
  188. def parse(self):
  189. """Unicode-ify and strip whitespace from the plain text document."""
  190. converted = bs4.UnicodeDammit(self.text).unicode_markup
  191. return converted.strip() if converted else ""
  192. _CONTENT_TYPES = {
  193. "text/html": _HTMLParser,
  194. "application/xhtml+xml": _HTMLParser,
  195. "application/pdf": _PDFParser,
  196. "application/x-pdf": _PDFParser,
  197. "text/plain": _PlainTextParser
  198. }
  199. def get_parser(content_type):
  200. """Return the parser most able to handle a given content type, or None."""
  201. return _CONTENT_TYPES.get(content_type.split(";", 1)[0])