Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

afc_copyvios.py 8.0 KiB

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