A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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