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.

249 regels
10 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by Ben Kurtovic <ben.kurtovic@verizon.net>
  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 gzip import GzipFile
  23. from StringIO import StringIO
  24. from time import sleep, time
  25. from urllib2 import build_opener, URLError
  26. try:
  27. import oauth2 as oauth
  28. except ImportError:
  29. oauth = None
  30. from earwigbot.wiki.exceptions import *
  31. from earwigbot.wiki.copyvios.markov import MarkovChain, MarkovChainIntersection
  32. from earwigbot.wiki.copyvios.search import YahooBOSSSearchEngine
  33. class CopyvioCheckResult(object):
  34. def __init__(self, violation, confidence, url, queries, article, chains):
  35. self.violation = violation
  36. self.confidence = confidence
  37. self.url = url
  38. self.queries = queries
  39. self.article_chain = article
  40. self.source_chain = chains[0]
  41. self.delta_chain = chains[1]
  42. def __repr__(self):
  43. r = "CopyvioCheckResult(violation={0!r}, confidence={1!r}, url={2!r}, queries={3|r})"
  44. return r.format(self.violation, self.confidence, self.url, self.queries)
  45. class CopyvioMixin(object):
  46. """
  47. EarwigBot's Wiki Toolset: Copyright Violation Mixin
  48. This is a mixin that provides two public methods, copyvio_check() and
  49. copyvio_compare(). The former checks the page for copyright violations
  50. using a search engine API, and the latter compares the page against a
  51. specified URL. Credentials for the search engine API are stored in the
  52. site's config.
  53. """
  54. def __init__(self, site):
  55. self._opener = build_opener()
  56. self._opener.addheaders = site._opener.addheaders
  57. def _open_url_ignoring_errors(self, url):
  58. """Open a URL using self._opener and return its content, or None.
  59. Will decompress the content if the headers contain "gzip" as its
  60. content encoding, and will return None if URLError is raised while
  61. opening the URL. IOErrors while gunzipping a compressed response are
  62. ignored, and the original content is returned.
  63. """
  64. try:
  65. response = self._opener.open(url)
  66. except URLError:
  67. return None
  68. result = response.read()
  69. if response.headers.get("Content-Encoding") == "gzip":
  70. stream = StringIO(result)
  71. gzipper = GzipFile(fileobj=stream)
  72. try:
  73. result = gzipper.read()
  74. except IOError:
  75. pass
  76. return result
  77. def _select_search_engine(self):
  78. """Return a function that can be called to do web searches.
  79. The "function" is a functools.partial object that takes one argument, a
  80. query, and returns a list of URLs, ranked by importance. The underlying
  81. logic depends on the 'engine' argument; for example, if 'engine' is
  82. "Yahoo! BOSS", we'll use self._yahoo_boss_query for querying.
  83. Raises UnknownSearchEngineError if the 'engine' listed in our config is
  84. unknown to us, and UnsupportedSearchEngineError if we are missing a
  85. required package or module, like oauth2 for "Yahoo! BOSS".
  86. """
  87. engine, credentials = self._site._search_config
  88. if engine == "Yahoo! BOSS":
  89. if not oauth:
  90. e = "The package 'oauth2' could not be imported"
  91. raise UnsupportedSearchEngineError(e)
  92. return YahooBOSSSearchEngine(credentials)
  93. raise UnknownSearchEngineError(engine)
  94. def _copyvio_strip_html(self, html):
  95. """
  96. STUB
  97. """
  98. return html
  99. def _copyvio_strip_article(self, content):
  100. """Clean the page's raw text by removing templates and formatting.
  101. Returns the page's text with all HTML and wikicode formatting removed,
  102. including templates, tables, references, and the Bibliography/
  103. References/Sources/See also section(s). It retains punctuation
  104. (spacing, paragraphs, periods, commas, (semi)-colons, parentheses,
  105. quotes) and original capitalization, but not brackets (square and
  106. angular), abnormal spacing, nor anything else. HTML entities are
  107. replaced by their unicode equivalents.
  108. STUB
  109. """
  110. return content
  111. def _copyvio_chunk_article(self, content, max_chunks):
  112. """
  113. STUB
  114. """
  115. return [content]
  116. def _copyvio_compare_content(self, article, url):
  117. """
  118. DOCSTRING NEEDED
  119. """
  120. html = self._open_url_ignoring_errors(url)
  121. if not html:
  122. return 0
  123. source = MarkovChain(self._copyvio_strip_html(html))
  124. delta = MarkovChainIntersection(article, source)
  125. return float(delta.size()) / article.size(), (source, delta)
  126. def copyvio_check(self, min_confidence=0.5, max_queries=-1,
  127. interquery_sleep=1, force=False):
  128. """Check the page for copyright violations.
  129. Returns a _CopyvioCheckResult object with four useful attributes:
  130. "violation", "confidence", "url", and "queries". "confidence" is a
  131. number between 0 and 1; if it is less than "min_confidence", we could
  132. not find any indication of a violation (so "violation" will be False
  133. and "url" may or may not be None), otherwise it indicates the relative
  134. faith in our results, "violation" will be True, and "url" will be the
  135. place the article is suspected of being copied from. "queries" is the
  136. number of queries used to determine the results.
  137. "max_queries" is self-explanatory; we will never make more than this
  138. number of queries in a given check. If it's less than 0, we will not
  139. limit our number of queries.
  140. "interquery_sleep" is the minimum amount of time we will sleep between
  141. search engine queries, in seconds.
  142. "force" is simply passed to page.get() - it has the same behavior there
  143. as it does here.
  144. Raises CopyvioCheckError or subclasses (UnknownSearchEngineError,
  145. SearchQueryError, ...) on errors.
  146. """
  147. searcher = self._select_search_engine()
  148. handled_urls = []
  149. best_confidence = 0
  150. best_match = None
  151. num_queries = 0
  152. empty = MarkovChain("")
  153. best_chains = (empty, MarkovChainIntersection(empty, empty))
  154. content = self.get(force)
  155. clean = self._copyvio_strip_article(content)
  156. chunks = self._copyvio_chunk_article(clean, max_queries)
  157. article_chain = MarkovChain(clean)
  158. last_query = time()
  159. if article_chain.size() < 20: # Auto-fail very small articles
  160. return CopyvioCheckResult(False, best_confidence, best_match,
  161. num_queries, article_chain, best_chains)
  162. while (chunks and best_confidence < min_confidence and
  163. (max_queries < 0 or num_queries < max_queries)):
  164. urls = searcher.search(chunks.pop(0))
  165. urls = [url for url in urls if url not in handled_urls]
  166. for url in urls:
  167. handled_urls.append(url)
  168. conf, chains = self._copyvio_compare_content(article_chain, url)
  169. if conf > best_confidence:
  170. best_confidence = conf
  171. best_match = url
  172. best_chains = chains
  173. num_queries += 1
  174. diff = time() - last_query
  175. if diff < interquery_sleep:
  176. sleep(interquery_sleep - diff)
  177. last_query = time()
  178. if best_confidence >= min_confidence: # violation?
  179. v = True
  180. else:
  181. v = False
  182. return CopyvioCheckResult(v, best_confidence, best_match, num_queries,
  183. article_chain, best_chains)
  184. def copyvio_compare(self, url, min_confidence=0.5, force=False):
  185. """Check the page like copyvio_check(), but against a specific URL.
  186. This is essentially a reduced version of the above - a copyivo
  187. comparison is made using Markov chains and the result is returned in a
  188. _CopyvioCheckResult object - without using a search engine, as the
  189. suspected "violated" URL is supplied from the start.
  190. Its primary use is to generate a result when the URL is retrieved from
  191. a cache, like the one used in EarwigBot's Toolserver site. After a
  192. search is done, the resulting URL is stored in a cache for 24 hours so
  193. future checks against that page will not require another set of
  194. time-and-money-consuming search engine queries. However, the comparison
  195. itself (which includes the article's and the source's content) cannot
  196. be stored for data retention reasons, so a fresh comparison is made
  197. using this function.
  198. Since no searching is done, neither UnknownSearchEngineError nor
  199. SearchQueryError will be raised.
  200. """
  201. content = self.get(force)
  202. clean = self._copyvio_strip_article(content)
  203. article_chain = MarkovChain(clean)
  204. confidence, chains = self._copyvio_compare_content(article_chain, url)
  205. if confidence >= min_confidence:
  206. is_violation = True
  207. else:
  208. is_violation = False
  209. return CopyvioCheckResult(is_violation, confidence, url, 0,
  210. article_chain, chains)