A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

447 строки
17 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. self._logger.exception("Failed to fetch URL: %s", url)
  108. return None
  109. try:
  110. size = int(response.headers.get("Content-Length", 0))
  111. except ValueError:
  112. return None
  113. content_type = response.headers.get("Content-Type", "text/plain")
  114. content_type = content_type.split(";", 1)[0]
  115. parser_class = get_parser(content_type)
  116. if not parser_class and (
  117. not allow_content_types or content_type not in allow_content_types):
  118. return None
  119. if not parser_class:
  120. parser_class = get_parser("text/plain")
  121. if size > (15 if parser_class.TYPE == "PDF" else 2) * 1024 ** 2:
  122. return None
  123. try:
  124. # Additional safety check for pages using Transfer-Encoding: chunked
  125. # where we can't read the Content-Length
  126. content = response.read(_MAX_RAW_SIZE + 1)
  127. except (URLError, socket_error):
  128. return None
  129. if len(content) > _MAX_RAW_SIZE:
  130. return None
  131. if response.headers.get("Content-Encoding") == "gzip":
  132. stream = StringIO(content)
  133. gzipper = GzipFile(fileobj=stream)
  134. try:
  135. content = gzipper.read()
  136. except (IOError, struct_error):
  137. return None
  138. if len(content) > _MAX_RAW_SIZE:
  139. return None
  140. return _OpenedURL(content, parser_class)
  141. def _open_url(self, source, redirects=0):
  142. """Open a URL and return its parsed content, or None.
  143. First, we will decompress the content if the headers contain "gzip" as
  144. its content encoding. Then, we will return the content stripped using
  145. an HTML parser if the headers indicate it is HTML, or return the
  146. content directly if it is plain text. If we don't understand the
  147. content type, we'll return None.
  148. If a URLError was raised while opening the URL or an IOError was raised
  149. while decompressing, None will be returned.
  150. """
  151. if source.headers:
  152. self._opener.addheaders = source.headers
  153. result = self._open_url_raw(source.url, timeout=source.timeout)
  154. if result is None:
  155. return None
  156. args = source.parser_args.copy() if source.parser_args else {}
  157. args["open_url"] = functools.partial(self._open_url_raw, timeout=source.timeout)
  158. parser = result.parser_class(result.content, url=source.url, args=args)
  159. try:
  160. return parser.parse()
  161. except ParserRedirectError as exc:
  162. if redirects >= _MAX_REDIRECTS:
  163. return None
  164. source.url = exc.url.decode("utf8")
  165. return self._open_url(source, redirects=redirects + 1)
  166. def _acquire_new_site(self):
  167. """Block for a new unassigned site queue."""
  168. if self._until:
  169. timeout = self._until - time.time()
  170. if timeout <= 0:
  171. raise Empty
  172. else:
  173. timeout = None
  174. self._logger.debug("Waiting for new site queue")
  175. site, queue = self._queues.unassigned.get(timeout=timeout)
  176. if site is StopIteration:
  177. raise StopIteration
  178. self._logger.debug(u"Acquired new site queue: {0}".format(site))
  179. self._site = site
  180. self._queue = queue
  181. def _dequeue(self):
  182. """Remove a source from one of the queues."""
  183. if not self._site:
  184. self._acquire_new_site()
  185. logmsg = u"Fetching source URL from queue {0}"
  186. self._logger.debug(logmsg.format(self._site))
  187. self._queues.lock.acquire()
  188. try:
  189. source = self._queue.popleft()
  190. except IndexError:
  191. self._logger.debug("Queue is empty")
  192. del self._queues.sites[self._site]
  193. self._site = None
  194. self._queue = None
  195. self._queues.lock.release()
  196. return self._dequeue()
  197. self._logger.debug(u"Got source URL: {0}".format(source.url))
  198. if source.skipped:
  199. self._logger.debug("Source has been skipped")
  200. self._queues.lock.release()
  201. return self._dequeue()
  202. source.start_work()
  203. self._queues.lock.release()
  204. return source
  205. def _handle_once(self):
  206. """Handle a single source from one of the queues."""
  207. try:
  208. source = self._dequeue()
  209. except Empty:
  210. self._logger.debug("Exiting: queue timed out")
  211. return False
  212. except StopIteration:
  213. self._logger.debug("Exiting: got stop signal")
  214. return False
  215. try:
  216. text = self._open_url(source)
  217. except ParserExclusionError:
  218. self._logger.debug("Source excluded by content parser")
  219. source.skipped = source.excluded = True
  220. source.finish_work()
  221. except Exception:
  222. self._logger.exception("Uncaught exception in worker")
  223. source.skip()
  224. source.finish_work()
  225. else:
  226. chain = MarkovChain(text) if text else None
  227. source.workspace.compare(source, chain)
  228. return True
  229. def _run(self):
  230. """Main entry point for the worker thread.
  231. We will keep fetching URLs from the queues and handling them until
  232. either we run out of time, or we get an exit signal that the queue is
  233. now empty.
  234. """
  235. while True:
  236. try:
  237. if not self._handle_once():
  238. break
  239. except Exception:
  240. self._logger.exception("Uncaught exception in worker")
  241. time.sleep(5) # Delay if we get stuck in a busy loop
  242. def start(self):
  243. """Start the copyvio worker in a new thread."""
  244. thread = Thread(target=self._run, name="cvworker-" + self._name)
  245. thread.daemon = True
  246. thread.start()
  247. class CopyvioWorkspace(object):
  248. """Manages a single copyvio check distributed across threads."""
  249. def __init__(self, article, min_confidence, max_time, logger, headers,
  250. url_timeout=5, num_workers=8, short_circuit=True,
  251. parser_args=None, exclude_check=None):
  252. self.sources = []
  253. self.finished = False
  254. self.possible_miss = False
  255. self._article = article
  256. self._logger = logger.getChild("copyvios")
  257. self._min_confidence = min_confidence
  258. self._start_time = time.time()
  259. self._until = (self._start_time + max_time) if max_time > 0 else None
  260. self._handled_urls = set()
  261. self._finish_lock = Lock()
  262. self._short_circuit = short_circuit
  263. self._source_args = {
  264. "workspace": self, "headers": headers, "timeout": url_timeout,
  265. "parser_args": parser_args}
  266. self._exclude_check = exclude_check
  267. if _is_globalized:
  268. self._queues = _global_queues
  269. else:
  270. self._queues = _CopyvioQueues()
  271. self._num_workers = num_workers
  272. for i in xrange(num_workers):
  273. name = "local-{0:04}.{1}".format(id(self) % 10000, i)
  274. _CopyvioWorker(name, self._queues, self._until).start()
  275. def _calculate_confidence(self, delta):
  276. """Return the confidence of a violation as a float between 0 and 1."""
  277. def conf_with_article_and_delta(article, delta):
  278. """Calculate confidence using the article and delta chain sizes."""
  279. # This piecewise function exhibits exponential growth until it
  280. # reaches the default "suspect" confidence threshold, at which
  281. # point it transitions to polynomial growth with a limit of 1 as
  282. # (delta / article) approaches 1.
  283. # A graph can be viewed here: http://goo.gl/mKPhvr
  284. ratio = delta / article
  285. if ratio <= 0.52763:
  286. return -log(1 - ratio)
  287. else:
  288. return (-0.8939 * (ratio ** 2)) + (1.8948 * ratio) - 0.0009
  289. def conf_with_delta(delta):
  290. """Calculate confidence using just the delta chain size."""
  291. # This piecewise function was derived from experimental data using
  292. # reference points at (0, 0), (100, 0.5), (250, 0.75), (500, 0.9),
  293. # and (1000, 0.95), with a limit of 1 as delta approaches infinity.
  294. # A graph can be viewed here: http://goo.gl/lVl7or
  295. if delta <= 100:
  296. return delta / (delta + 100)
  297. elif delta <= 250:
  298. return (delta - 25) / (delta + 50)
  299. elif delta <= 500:
  300. return (10.5 * delta - 750) / (10 * delta)
  301. else:
  302. return (delta - 50) / delta
  303. d_size = float(delta.size)
  304. return abs(max(conf_with_article_and_delta(self._article.size, d_size),
  305. conf_with_delta(d_size)))
  306. def _finish_early(self):
  307. """Finish handling links prematurely (if we've hit min_confidence)."""
  308. self._logger.debug("Confidence threshold met; skipping remaining sources")
  309. with self._queues.lock:
  310. for source in self.sources:
  311. source.skip()
  312. self.finished = True
  313. def enqueue(self, urls):
  314. """Put a list of URLs into the various worker queues."""
  315. for url in urls:
  316. with self._queues.lock:
  317. if url in self._handled_urls:
  318. continue
  319. self._handled_urls.add(url)
  320. source = CopyvioSource(url=url, **self._source_args)
  321. self.sources.append(source)
  322. if self._exclude_check and self._exclude_check(url):
  323. self._logger.debug(u"enqueue(): exclude {0}".format(url))
  324. source.excluded = True
  325. source.skip()
  326. continue
  327. if self._short_circuit and self.finished:
  328. self._logger.debug(u"enqueue(): auto-skip {0}".format(url))
  329. source.skip()
  330. continue
  331. try:
  332. key = tldextract.extract(url).registered_domain
  333. except ImportError: # Fall back on very naive method
  334. from urlparse import urlparse
  335. key = u".".join(urlparse(url).netloc.split(".")[-2:])
  336. logmsg = u"enqueue(): {0} {1} -> {2}"
  337. if key in self._queues.sites:
  338. self._logger.debug(logmsg.format("append", key, url))
  339. self._queues.sites[key].append(source)
  340. else:
  341. self._logger.debug(logmsg.format("new", key, url))
  342. self._queues.sites[key] = queue = deque()
  343. queue.append(source)
  344. self._queues.unassigned.put((key, queue))
  345. def compare(self, source, source_chain):
  346. """Compare a source to the article; call _finish_early if necessary."""
  347. if source_chain:
  348. delta = MarkovChainIntersection(self._article, source_chain)
  349. conf = self._calculate_confidence(delta)
  350. else:
  351. conf = 0.0
  352. self._logger.debug(u"compare(): {0} -> {1}".format(source.url, conf))
  353. with self._finish_lock:
  354. if source_chain:
  355. source.update(conf, source_chain, delta)
  356. source.finish_work()
  357. if not self.finished and conf >= self._min_confidence:
  358. if self._short_circuit:
  359. self._finish_early()
  360. else:
  361. self.finished = True
  362. def wait(self):
  363. """Wait for the workers to finish handling the sources."""
  364. self._logger.debug("Waiting on {0} sources".format(len(self.sources)))
  365. for source in self.sources:
  366. source.join(self._until)
  367. with self._finish_lock:
  368. pass # Wait for any remaining comparisons to be finished
  369. if not _is_globalized:
  370. for i in xrange(self._num_workers):
  371. self._queues.unassigned.put((StopIteration, None))
  372. def get_result(self, num_queries=0):
  373. """Return a CopyvioCheckResult containing the results of this check."""
  374. def cmpfunc(s1, s2):
  375. if s2.confidence != s1.confidence:
  376. return 1 if s2.confidence > s1.confidence else -1
  377. if s2.excluded != s1.excluded:
  378. return 1 if s1.excluded else -1
  379. return int(s1.skipped) - int(s2.skipped)
  380. self.sources.sort(cmpfunc)
  381. return CopyvioCheckResult(self.finished, self.sources, num_queries,
  382. time.time() - self._start_time, self._article,
  383. self.possible_miss)