A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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