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.

147 lines
5.7 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2013 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 errno
  23. from os import path
  24. import mwparserfromhell
  25. from earwigbot import importer
  26. bs4 = importer.new("bs4")
  27. nltk = importer.new("nltk")
  28. __all__ = ["BaseTextParser", "ArticleTextParser", "HTMLTextParser"]
  29. class BaseTextParser(object):
  30. """Base class for a parser that handles text."""
  31. def __init__(self, text):
  32. self.text = text
  33. def __repr__(self):
  34. """Return the canonical string representation of the text parser."""
  35. return "{0}(text={1!r})".format(self.__class__.__name__, self.text)
  36. def __str__(self):
  37. """Return a nice string representation of the text parser."""
  38. name = self.__class__.__name__
  39. return "<{0} of text with size {1}>".format(name, len(self.text))
  40. class ArticleTextParser(BaseTextParser):
  41. """A parser that can strip and chunk wikicode article text."""
  42. def strip(self):
  43. """Clean the page's raw text by removing templates and formatting.
  44. Return the page's text with all HTML and wikicode formatting removed,
  45. including templates, tables, and references. It retains punctuation
  46. (spacing, paragraphs, periods, commas, (semi)-colons, parentheses,
  47. quotes), original capitalization, and so forth. HTML entities are
  48. replaced by their unicode equivalents.
  49. The actual stripping is handled by :py:mod:`mwparserfromhell`.
  50. """
  51. wikicode = mwparserfromhell.parse(self.text)
  52. clean = wikicode.strip_code(normalize=True, collapse=True)
  53. self.clean = clean.replace("\n\n", "\n") # Collapse extra newlines
  54. return self.clean
  55. def chunk(self, nltk_dir, max_chunks, max_query=256):
  56. """Convert the clean article text into a list of web-searchable chunks.
  57. No greater than *max_chunks* will be returned. Each chunk will only be
  58. a sentence or two long at most (no more than *max_query*). The idea is
  59. to return a sample of the article text rather than the whole, so we'll
  60. pick and choose from parts of it, especially if the article is large
  61. and *max_chunks* is low, so we don't end up just searching for just the
  62. first paragraph.
  63. This is implemented using :py:mod:`nltk` (http://nltk.org/). A base
  64. directory (*nltk_dir*) is required to store nltk's punctuation
  65. database. This is typically located in the bot's working directory.
  66. """
  67. datafile = path.join(nltk_dir, "tokenizers", "punkt", "english.pickle")
  68. try:
  69. tokenizer = nltk.data.load("file:" + datafile)
  70. except IOError as exc:
  71. if exc.errno != errno.ENOENT:
  72. raise
  73. nltk.download("punkt", nltk_dir)
  74. tokenizer = nltk.data.load("file:" + datafile)
  75. sentences = []
  76. for sentence in tokenizer.tokenize(self.clean):
  77. if len(sentence) > max_query:
  78. words = sentence.split()
  79. while len(" ".join(words)) > max_query:
  80. words.pop()
  81. sentence = " ".join(words)
  82. sentences.append(sentence)
  83. if max_chunks >= len(sentences):
  84. return sentences
  85. chunks = []
  86. while len(chunks) < max_chunks:
  87. if len(chunks) % 5 == 0:
  88. chunk = sentences.pop(0) # Pop from beginning
  89. elif len(chunks) % 5 == 1:
  90. chunk = sentences.pop() # Pop from end
  91. elif len(chunks) % 5 == 2:
  92. chunk = sentences.pop(len(sentences) / 2) # Pop from Q2
  93. elif len(chunks) % 5 == 3:
  94. chunk = sentences.pop(len(sentences) / 4) # Pop from Q1
  95. else:
  96. chunk = sentences.pop(3 * len(sentences) / 4) # Pop from Q3
  97. chunks.append(chunk)
  98. return chunks
  99. class HTMLTextParser(BaseTextParser):
  100. """A parser that can extract the text from an HTML document."""
  101. hidden_tags = [
  102. "script", "style"
  103. ]
  104. def strip(self):
  105. """Return the actual text contained within an HTML document.
  106. Implemented using :py:mod:`BeautifulSoup <bs4>`
  107. (http://www.crummy.com/software/BeautifulSoup/).
  108. """
  109. try:
  110. soup = bs4.BeautifulSoup(self.text, "lxml").body
  111. except ValueError:
  112. soup = bs4.BeautifulSoup(self.text).body
  113. is_comment = lambda text: isinstance(text, bs4.element.Comment)
  114. for comment in soup.find_all(text=is_comment):
  115. comment.extract()
  116. for tag in self.hidden_tags:
  117. for element in soup.find_all(tag):
  118. element.extract()
  119. return "\n".join(soup.stripped_strings)