A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

373 linhas
14 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2014 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 collections import deque
  23. from gzip import GzipFile
  24. from logging import getLogger
  25. from math import log
  26. from Queue import Empty, Queue
  27. from socket import error
  28. from StringIO import StringIO
  29. from threading import Lock, Thread
  30. from time import time
  31. from urllib2 import build_opener, URLError
  32. from earwigbot import importer
  33. from earwigbot.wiki.copyvios.markov import MarkovChain, MarkovChainIntersection
  34. from earwigbot.wiki.copyvios.parsers import HTMLTextParser
  35. from earwigbot.wiki.copyvios.result import CopyvioCheckResult, CopyvioSource
  36. tldextract = importer.new("tldextract")
  37. __all__ = ["globalize", "localize", "CopyvioWorkspace"]
  38. _is_globalized = False
  39. _global_queues = None
  40. _global_workers = []
  41. def globalize(num_workers=8):
  42. """Cause all copyvio checks to be done by one global set of workers.
  43. This is useful when checks are being done through a web interface where
  44. large numbers of simulatenous requests could be problematic. The global
  45. workers are spawned when the function is called, run continuously, and
  46. intelligently handle multiple checks.
  47. This function is not thread-safe and should only be called when no checks
  48. are being done. It has no effect if it has already been called.
  49. """
  50. global _is_globalized, _global_queues
  51. if _is_globalized:
  52. return
  53. _global_queues = _CopyvioQueues()
  54. for i in xrange(num_workers):
  55. worker = _CopyvioWorker("global-{0}".format(i), _global_queues)
  56. worker.start()
  57. _global_workers.append(worker)
  58. _is_globalized = True
  59. def localize():
  60. """Return to using page-specific workers for copyvio checks.
  61. This disables changes made by :func:`globalize`, including stoping the
  62. global worker threads.
  63. This function is not thread-safe and should only be called when no checks
  64. are being done.
  65. """
  66. global _is_globalized, _global_queues, _global_workers
  67. if not _is_globalized:
  68. return
  69. for i in xrange(len(_global_workers)):
  70. _global_queues.unassigned.put((StopIteration, None))
  71. _global_queues = None
  72. _global_workers = []
  73. _is_globalized = False
  74. class _CopyvioQueues(object):
  75. """Stores data necessary to maintain the various queues during a check."""
  76. def __init__(self):
  77. self.lock = Lock()
  78. self.sites = {}
  79. self.unassigned = Queue()
  80. class _CopyvioWorker(object):
  81. """A multithreaded URL opener/parser instance."""
  82. def __init__(self, name, queues, until=None):
  83. self._name = name
  84. self._queues = queues
  85. self._until = until
  86. self._site = None
  87. self._queue = None
  88. self._opener = build_opener()
  89. self._logger = getLogger("earwigbot.wiki.cvworker." + name)
  90. def _open_url(self, source):
  91. """Open a URL and return its parsed content, or None.
  92. First, we will decompress the content if the headers contain "gzip" as
  93. its content encoding. Then, we will return the content stripped using
  94. an HTML parser if the headers indicate it is HTML, or return the
  95. content directly if it is plain text. If we don't understand the
  96. content type, we'll return None.
  97. If a URLError was raised while opening the URL or an IOError was raised
  98. while decompressing, None will be returned.
  99. """
  100. if source.headers:
  101. self._opener.addheaders = source.headers
  102. url = source.url.encode("utf8")
  103. try:
  104. response = self._opener.open(url, timeout=source.timeout)
  105. except (URLError, error):
  106. return None
  107. try:
  108. size = int(response.headers.get("Content-Length", 0))
  109. except ValueError:
  110. return None
  111. if size > 1024 ** 2: # Ignore URLs larger than a megabyte
  112. return None
  113. ctype_full = response.headers.get("Content-Type", "text/plain")
  114. ctype = ctype_full.split(";", 1)[0]
  115. if ctype in ["text/html", "application/xhtml+xml"]:
  116. handler = lambda res: HTMLTextParser(res).strip()
  117. elif ctype == "text/plain":
  118. handler = lambda res: res.strip()
  119. else:
  120. return None
  121. try:
  122. content = response.read()
  123. except (URLError, error):
  124. return None
  125. if response.headers.get("Content-Encoding") == "gzip":
  126. stream = StringIO(content)
  127. gzipper = GzipFile(fileobj=stream)
  128. try:
  129. content = gzipper.read(2 * 1024 ** 2)
  130. except IOError:
  131. return None
  132. return handler(content)
  133. def _acquire_new_site(self):
  134. """Block for a new unassigned site queue."""
  135. if self._until:
  136. timeout = self._until - time()
  137. if timeout <= 0:
  138. raise Empty
  139. else:
  140. timeout = None
  141. self._logger.debug("Waiting for new site queue")
  142. site, queue = self._queues.unassigned.get(timeout=timeout)
  143. if site is StopIteration:
  144. raise StopIteration
  145. self._logger.debug(u"Acquired new site queue: {0}".format(site))
  146. self._site = site
  147. self._queue = queue
  148. def _dequeue(self):
  149. """Remove a source from one of the queues."""
  150. if not self._site:
  151. self._acquire_new_site()
  152. logmsg = u"Fetching source URL from queue {0}"
  153. self._logger.debug(logmsg.format(self._site))
  154. self._queues.lock.acquire()
  155. try:
  156. source = self._queue.popleft()
  157. except IndexError:
  158. self._logger.debug("Queue is empty")
  159. del self._queues.sites[self._site]
  160. self._site = None
  161. self._queue = None
  162. self._queues.lock.release()
  163. return self._dequeue()
  164. self._logger.debug(u"Got source URL: {0}".format(source.url))
  165. if source.skipped:
  166. self._logger.debug("Source has been skipped")
  167. self._queues.lock.release()
  168. return self._dequeue()
  169. source.start_work()
  170. self._queues.lock.release()
  171. return source
  172. def _run(self):
  173. """Main entry point for the worker thread.
  174. We will keep fetching URLs from the queues and handling them until
  175. either we run out of time, or we get an exit signal that the queue is
  176. now empty.
  177. """
  178. while True:
  179. try:
  180. source = self._dequeue()
  181. except Empty:
  182. self._logger.debug("Exiting: queue timed out")
  183. return
  184. except StopIteration:
  185. self._logger.debug("Exiting: got stop signal")
  186. return
  187. text = self._open_url(source)
  188. source.workspace.compare(source, MarkovChain(text or ""))
  189. def start(self):
  190. """Start the copyvio worker in a new thread."""
  191. thread = Thread(target=self._run, name="cvworker-" + self._name)
  192. thread.daemon = True
  193. thread.start()
  194. class CopyvioWorkspace(object):
  195. """Manages a single copyvio check distributed across threads."""
  196. def __init__(self, article, min_confidence, max_time, logger, headers,
  197. url_timeout=5, num_workers=8, short_circuit=True):
  198. self.sources = []
  199. self.finished = False
  200. self._article = article
  201. self._logger = logger.getChild("copyvios")
  202. self._min_confidence = min_confidence
  203. self._start_time = time()
  204. self._until = (self._start_time + max_time) if max_time > 0 else None
  205. self._handled_urls = []
  206. self._finish_lock = Lock()
  207. self._short_circuit = short_circuit
  208. self._source_args = {"workspace": self, "headers": headers,
  209. "timeout": url_timeout}
  210. if _is_globalized:
  211. self._queues = _global_queues
  212. else:
  213. self._queues = _CopyvioQueues()
  214. self._num_workers = num_workers
  215. for i in xrange(num_workers):
  216. name = "local-{0:04}.{1}".format(id(self) % 10000, i)
  217. _CopyvioWorker(name, self._queues, self._until).start()
  218. def _calculate_confidence(self, delta):
  219. """Return the confidence of a violation as a float between 0 and 1."""
  220. def conf_with_article_and_delta(article, delta):
  221. """Calculate confidence using the article and delta chain sizes."""
  222. # This piecewise function, C_AΔ(Δ), was defined such that
  223. # confidence exhibits exponential growth until it reaches the
  224. # default "suspect" confidence threshold, at which point it
  225. # transitions to polynomial growth with lim (A/Δ)→1 C_AΔ(A,Δ) = 1.
  226. # A graph can be viewed here:
  227. # http://benkurtovic.com/static/article-delta_confidence_function.pdf
  228. ratio = delta / article
  229. if ratio <= 0.52763:
  230. return log(1 / (1 - ratio))
  231. else:
  232. return (-0.8939 * (ratio ** 2)) + (1.8948 * ratio) - 0.0009
  233. def conf_with_delta(delta):
  234. """Calculate confidence using just the delta chain size."""
  235. # This piecewise function, C_Δ(Δ), was derived from experimental
  236. # data using reference points at (0, 0), (100, 0.5), (250, 0.75),
  237. # (500, 0.9), and (1000, 0.95) with lim Δ→+∞ C_Δ(Δ) = 1.
  238. # A graph can be viewed here:
  239. # http://benkurtovic.com/static/delta_confidence_function.pdf
  240. if delta <= 100:
  241. return delta / (delta + 100)
  242. elif delta <= 250:
  243. return (delta - 25) / (delta + 50)
  244. elif delta <= 500:
  245. return (10.5 * delta - 750) / (10 * delta)
  246. else:
  247. return (delta - 50) / delta
  248. d_size = float(delta.size)
  249. return max(conf_with_article_and_delta(self._article.size, d_size),
  250. conf_with_delta(d_size))
  251. def _finish_early(self):
  252. """Finish handling links prematurely (if we've hit min_confidence)."""
  253. self._logger.debug("Confidence threshold met; skipping remaining sources")
  254. with self._queues.lock:
  255. for source in self.sources:
  256. source.skip()
  257. self.finished = True
  258. def enqueue(self, urls, exclude_check=None):
  259. """Put a list of URLs into the various worker queues.
  260. *exclude_check* is an optional exclusion function that takes a URL and
  261. returns ``True`` if we should skip it and ``False`` otherwise.
  262. """
  263. for url in urls:
  264. with self._queues.lock:
  265. if self._short_circuit and self.finished:
  266. break
  267. if url in self._handled_urls:
  268. continue
  269. self._handled_urls.append(url)
  270. if exclude_check and exclude_check(url):
  271. continue
  272. try:
  273. key = tldextract.extract(url).registered_domain
  274. except ImportError: # Fall back on very naive method
  275. from urlparse import urlparse
  276. key = u".".join(urlparse(url).netloc.split(".")[-2:])
  277. source = CopyvioSource(url=url, **self._source_args)
  278. self.sources.append(source)
  279. logmsg = u"enqueue(): {0} {1} -> {2}"
  280. if key in self._queues.sites:
  281. self._logger.debug(logmsg.format("append", key, url))
  282. self._queues.sites[key].append(source)
  283. else:
  284. self._logger.debug(logmsg.format("new", key, url))
  285. self._queues.sites[key] = queue = deque()
  286. queue.append(source)
  287. self._queues.unassigned.put((key, queue))
  288. def compare(self, source, source_chain):
  289. """Compare a source to the article; call _finish_early if necessary."""
  290. delta = MarkovChainIntersection(self._article, source_chain)
  291. conf = self._calculate_confidence(delta)
  292. self._logger.debug(u"compare(): {0} -> {1}".format(source.url, conf))
  293. with self._finish_lock:
  294. source.finish_work(conf, source_chain, delta)
  295. if not self.finished and conf >= self._min_confidence:
  296. if self._short_circuit:
  297. self._finish_early()
  298. else:
  299. self.finished = True
  300. def wait(self):
  301. """Wait for the workers to finish handling the sources."""
  302. self._logger.debug("Waiting on {0} sources".format(len(self.sources)))
  303. for source in self.sources:
  304. source.join(self._until)
  305. with self._finish_lock:
  306. pass # Wait for any remaining comparisons to be finished
  307. if not _is_globalized:
  308. for i in xrange(self._num_workers):
  309. self._queues.unassigned.put((StopIteration, None))
  310. def get_result(self, num_queries=0):
  311. """Return a CopyvioCheckResult containing the results of this check."""
  312. def cmpfunc(s1, s2):
  313. if s2.confidence != s1.confidence:
  314. return 1 if s2.confidence > s1.confidence else -1
  315. return int(s1.skipped) - int(s2.skipped)
  316. self.sources.sort(cmpfunc)
  317. return CopyvioCheckResult(self.finished, self.sources, num_queries,
  318. time() - self._start_time, self._article)