Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

210 рядки
9.4 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2013 Ben Kurtovic <ben.kurtovic@verizon.net>
  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 hashlib import sha256
  23. from os.path import expanduser
  24. from threading import Lock
  25. from urllib import quote
  26. import mwparserfromhell
  27. import oursql
  28. from earwigbot.tasks import Task
  29. class AFCCopyvios(Task):
  30. """A task to check newly-edited [[WP:AFC]] submissions for copyright
  31. violations."""
  32. name = "afc_copyvios"
  33. number = 1
  34. def setup(self):
  35. cfg = self.config.tasks.get(self.name, {})
  36. self.template = cfg.get("template", "AfC suspected copyvio")
  37. self.ignore_list = cfg.get("ignoreList", [])
  38. self.min_confidence = cfg.get("minConfidence", 0.5)
  39. self.max_queries = cfg.get("maxQueries", 10)
  40. self.max_time = cfg.get("maxTime", 150)
  41. self.cache_results = cfg.get("cacheResults", False)
  42. default_summary = "Tagging suspected [[WP:COPYVIO|copyright violation]] of {url}."
  43. self.summary = self.make_summary(cfg.get("summary", default_summary))
  44. default_tags = [
  45. "Db-g12", "Db-copyvio", "Copyvio", "Copyviocore" "Copypaste"]
  46. self.tags = default_tags + cfg.get("tags", [])
  47. # Connection data for our SQL database:
  48. kwargs = cfg.get("sql", {})
  49. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  50. self.conn_data = kwargs
  51. self.db_access_lock = Lock()
  52. def run(self, **kwargs):
  53. """Entry point for the bot task.
  54. Takes a page title in kwargs and checks it for copyvios, adding
  55. {{self.template}} at the top if a copyvio has been detected. A page is
  56. only checked once (processed pages are stored by page_id in an SQL
  57. database).
  58. """
  59. if self.shutoff_enabled():
  60. return
  61. title = kwargs["page"]
  62. page = self.bot.wiki.get_site().get_page(title)
  63. with self.db_access_lock:
  64. self.conn = oursql.connect(**self.conn_data)
  65. self.process(page)
  66. def process(self, page):
  67. """Detect copyvios in 'page' and add a note if any are found."""
  68. title = page.title
  69. if title in self.ignore_list:
  70. msg = u"Skipping page in ignore list: [[{0}]]"
  71. self.logger.info(msg.format(title))
  72. return
  73. pageid = page.pageid
  74. if self.has_been_processed(pageid):
  75. msg = u"Skipping check on already processed page [[{0}]]"
  76. self.logger.info(msg.format(title))
  77. return
  78. elif self.is_tagged(page.get()):
  79. msg = u"Skipping check on already tagged page [[{0}]]"
  80. self.logger.info(msg.format(title))
  81. return
  82. self.logger.info(u"Checking [[{0}]]".format(title))
  83. result = page.copyvio_check(self.min_confidence, self.max_queries,
  84. self.max_time)
  85. url = result.url
  86. orig_conf = "{0}%".format(round(result.confidence * 100, 2))
  87. if result.violation:
  88. # Things can change in the minute that it takes to do a check.
  89. # Confirm that a violation still holds true:
  90. page.load()
  91. if self.is_tagged(page.get()):
  92. msg = u"A violation was detected in [[{0}]], but it was tagged"
  93. msg += " by someone else while checking (best: {1} at {2} confidence)"
  94. self.logger.info(msg.format(title, url, orig_conf))
  95. self._trial_reporter(title, False, url, orig_conf, result.queries, result.time, msg)
  96. self.log_processed(pageid)
  97. return
  98. confirm = page.copyvio_compare(url, self.min_confidence)
  99. new_conf = "{0}%".format(round(confirm.confidence * 100, 2))
  100. if not confirm.violation:
  101. msg = u"A violation was detected in [[{0}]], but couldn't be confirmed."
  102. msg += u" It may have just been edited (best: {1} at {2} -> {3} confidence)"
  103. self.logger.info(msg.format(title, url, orig_conf, new_conf))
  104. self._trial_reporter(title, False, url, orig_conf, result.queries, result.time, msg)
  105. self.log_processed(pageid)
  106. return
  107. safeurl = quote(url.encode("utf8"), safe="/:").decode("utf8")
  108. content = page.get()
  109. template = u"\{\{{0}|url={1}|confidence={2}\}\}\n"
  110. template = template.format(self.template, safeurl, new_conf)
  111. newtext = template + content
  112. # if "{url}" in self.summary:
  113. # page.edit(newtext, self.summary.format(url=url))
  114. # else:
  115. # page.edit(newtext, self.summary)
  116. msg = u"Found violation: [[{0}]] -> {1} ({2} confidence)"
  117. self.logger.info(msg.format(title, url, new_conf))
  118. self._trial_reporter(title, True, url, new_conf, result.queries, result.time, msg)
  119. else:
  120. msg = u"No violations detected in [[{0}]] (best: {1} at {2} confidence)"
  121. self.logger.info(msg.format(title, url, orig_conf))
  122. self._trial_reporter(title, False, url, orig_conf, result.queries, result.time, msg)
  123. self.log_processed(pageid)
  124. if self.cache_results:
  125. self.cache_result(page, result)
  126. def _trial_reporter(self, title, violation, url, conf, queries, time, msg):
  127. from datetime import datetime
  128. date = datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC")
  129. data = u"\n" + ("-" * 80) + u"\n"
  130. data += u"[[{0}]] at {1}\n".format(title, date)
  131. data += u"Violation? {0}\n".format("***YES***" if violation else "No")
  132. data += u"Confidence: {0}\n".format(conf)
  133. data += u"Best match: {0}\n".format(url)
  134. data += u"Num queries: {0}\n".format(queries)
  135. data += u"Time: {0}\n".format(time)
  136. data += u"Log message: {0}\n".format(msg)
  137. with open("/data/project/earwigbot/public_html/copyvio_bot_trial.txt", "a") as fp:
  138. fp.write(data.encode("utf8"))
  139. def is_tagged(self, text):
  140. """Return whether the text contains a copyvio check template."""
  141. code = mwparserfromhell.parse(text)
  142. for template in code.ifilter_templates():
  143. for tag in self.tags:
  144. if template.name.matches(tag):
  145. return True
  146. return False
  147. def has_been_processed(self, pageid):
  148. """Returns True if pageid was processed before, otherwise False."""
  149. query = "SELECT 1 FROM processed WHERE page_id = ?"
  150. with self.conn.cursor() as cursor:
  151. cursor.execute(query, (pageid,))
  152. results = cursor.fetchall()
  153. return True if results else False
  154. def log_processed(self, pageid):
  155. """Adds pageid to our database of processed pages.
  156. Raises an exception if the page has already been processed.
  157. """
  158. query = "INSERT INTO processed VALUES (?)"
  159. with self.conn.cursor() as cursor:
  160. cursor.execute(query, (pageid,))
  161. def cache_result(self, page, result):
  162. """Store the check's result in a cache table temporarily.
  163. The cache contains the page's ID, a hash of its content, the URL of the
  164. best match, the time of caching, and the number of queries used. It
  165. will replace any existing cache entries for that page.
  166. The cache is intended for EarwigBot's complementary Toolserver web
  167. interface, in which copyvio checks can be done separately from the bot.
  168. The cache saves time and money by saving the result of the web search
  169. but neither the result of the comparison nor any actual text (which
  170. could violate data retention policy). Cache entries are (intended to
  171. be) retained for three days; this task does not remove old entries
  172. (that is handled by the Toolserver component).
  173. This will only be called if ``cache_results == True`` in the task's
  174. config, which is ``False`` by default.
  175. """
  176. pageid = page.pageid
  177. hash = sha256(page.get().encode("utf8")).hexdigest()
  178. query1 = "SELECT 1 FROM cache WHERE cache_id = ?"
  179. query2 = "DELETE FROM cache WHERE cache_id = ?"
  180. query3 = "INSERT INTO cache VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, ?)"
  181. with self.conn.cursor() as cursor:
  182. cursor.execute(query1, (pageid,))
  183. if cursor.fetchall():
  184. cursor.execute(query2, (pageid,))
  185. args = (pageid, hash, result.url, result.queries, 0)
  186. cursor.execute(query3, args)