A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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