A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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