A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

154 linhas
6.4 KiB

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