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.

412 lines
16 KiB

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