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.

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