A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

230 lines
8.8 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by 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 collections import OrderedDict
  23. from datetime import datetime, timedelta
  24. from itertools import count
  25. from os.path import expanduser
  26. from threading import Lock
  27. from time import sleep
  28. from matplotlib import pyplot as plt
  29. from numpy import arange
  30. import oursql
  31. from earwigbot import wiki
  32. from earwigbot.tasks import BaseTask
  33. __all__ = ["Task"]
  34. class Task(BaseTask):
  35. """A task to generate charts about AfC submissions over time.
  36. The main function of the task is to work through the "AfC submissions by
  37. date" categories (e.g. [[Category:AfC submissions by date/12 July 2011]])
  38. and determine the number of declined, accepted, and currently pending
  39. submissions every day.
  40. This information is saved to a MySQL database ("u_earwig_afc_history") and
  41. used to generate a graph showing the number of AfC submissions by date
  42. with matplotlib and numpy. The chart is saved as a PNG to
  43. config.tasks["afc_history"]["graph"]["dest"], which defaults to
  44. "afc_history.png".
  45. """
  46. name = "afc_history"
  47. # Valid submission statuses:
  48. STATUS_NONE = 0
  49. STATUS_PEND = 1
  50. STATUS_DECLINE = 2
  51. STATUS_ACCEPT = 3
  52. def setup(self):
  53. cfg = self.config.tasks.get(self.name, {})
  54. self.num_days = cfg.get("days", 90)
  55. self.categories = cfg.get("categories", {})
  56. # Graph stuff:
  57. self.graph = cfg.get("graph", {})
  58. self.destination = self.graph.get("dest", "afc_history.png")
  59. # Connection data for our SQL database:
  60. kwargs = cfg.get("sql", {})
  61. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  62. self.conn_data = kwargs
  63. self.db_access_lock = Lock()
  64. def run(self, **kwargs):
  65. self.site = self.bot.wiki.get_site()
  66. with self.db_access_lock:
  67. self.conn = oursql.connect(**self.conn_data)
  68. action = kwargs.get("action")
  69. try:
  70. num_days = int(kwargs.get("days", self.num_days))
  71. if action == "update":
  72. self.update(num_days)
  73. elif action == "generate":
  74. self.generate(num_days)
  75. finally:
  76. self.conn.close()
  77. def update(self, num_days):
  78. self.logger.info("Updating past {0} days".format(num_days))
  79. generator = self.backwards_cat_iterator()
  80. for d in xrange(num_days):
  81. category = generator.next()
  82. date = category.title.split("/")[-1]
  83. self.update_date(date, category)
  84. sleep(10)
  85. self.logger.info("Update complete")
  86. def generate(self, num_days):
  87. self.logger.info("Generating chart for past {0} days".format(num_days))
  88. data = OrderedDict()
  89. generator = self.backwards_cat_iterator()
  90. for d in xrange(num_days):
  91. category = generator.next()
  92. date = category.title.split("/")[-1]
  93. data[date] = self.get_date_counts(date)
  94. data = OrderedDict(reversed(data.items())) # Oldest to most recent
  95. self.generate_chart(data)
  96. dest = expanduser(self.destination)
  97. plt.savefig(dest)
  98. self.logger.info("Chart saved to {0}".format(dest))
  99. def backwards_cat_iterator(self):
  100. date_base = self.categories["dateBase"]
  101. current = datetime.utcnow()
  102. while 1:
  103. subcat = current.strftime("%d %B %Y")
  104. title = "/".join((date_base, subcat))
  105. yield self.site.get_category(title)
  106. current -= timedelta(1) # Subtract one day from date
  107. def update_date(self, date, category):
  108. msg = "Updating {0} ([[{1}]])".format(date, category.title)
  109. self.logger.debug(msg)
  110. q_select = "SELECT page_date, page_status FROM page WHERE page_id = ?"
  111. q_delete = "DELETE FROM page WHERE page_id = ?"
  112. q_update = "UPDATE page SET page_date = ?, page_status = ? WHERE page_id = ?"
  113. q_insert = "INSERT INTO page VALUES (?, ?, ?)"
  114. members = category.get_members(use_sql=True)
  115. with self.conn.cursor() as cursor:
  116. for title, pageid in members:
  117. cursor.execute(q_select, (pageid,))
  118. stored = cursor.fetchall()
  119. status = self.get_status(title, pageid)
  120. if status == self.STATUS_NONE:
  121. if stored:
  122. cursor.execute(q_delete, (pageid,))
  123. continue
  124. if stored:
  125. stored_date, stored_status = list(stored)[0]
  126. if date != stored_date or status != stored_status:
  127. cursor.execute(q_update, (date, status, pageid))
  128. else:
  129. cursor.execute(q_insert, (pageid, date, status))
  130. def get_status(self, title, pageid):
  131. page = self.site.get_page(title)
  132. ns = page.namespace
  133. if ns == wiki.NS_FILE_TALK: # Ignore accepted FFU requests
  134. return self.STATUS_NONE
  135. if ns == wiki.NS_TALK:
  136. new_page = page.toggle_talk()
  137. sleep(2)
  138. if new_page.is_redirect:
  139. return self.STATUS_NONE # Ignore accepted AFC/R requests
  140. return self.STATUS_ACCEPT
  141. cats = self.categories
  142. sq = self.site.sql_query
  143. query = "SELECT 1 FROM categorylinks WHERE cl_to = ? AND cl_from = ?"
  144. match = lambda cat: list(sq(query, (cat.replace(" ", "_"), pageid)))
  145. if match(cats["pending"]):
  146. return self.STATUS_PEND
  147. elif match(cats["unsubmitted"]):
  148. return self.STATUS_NONE
  149. elif match(cats["declined"]):
  150. return self.STATUS_DECLINE
  151. return self.STATUS_NONE
  152. def get_date_counts(self, date):
  153. query = "SELECT COUNT(*) FROM page WHERE page_date = ? AND page_status = ?"
  154. statuses = [self.STATUS_PEND, self.STATUS_DECLINE, self.STATUS_ACCEPT]
  155. counts = {}
  156. with self.conn.cursor() as cursor:
  157. for status in statuses:
  158. cursor.execute(query, (date, status))
  159. count = cursor.fetchall()[0][0]
  160. counts[status] = count
  161. return counts
  162. def generate_chart(self, data):
  163. plt.title(self.graph.get("title", "AfC submissions by date"))
  164. plt.xlabel(self.graph.get("xaxis", "Date"))
  165. plt.ylabel(self.graph.get("yaxis", "Submissions"))
  166. pends = [d[self.STATUS_PEND] for d in data.itervalues()]
  167. declines = [d[self.STATUS_DECLINE] for d in data.itervalues()]
  168. accepts = [d[self.STATUS_ACCEPT] for d in data.itervalues()]
  169. pends_declines = [p + d for p, d in zip(pends, declines)]
  170. ind = arange(len(data))
  171. xsize = self.graph.get("xsize", 1200)
  172. ysize = self.graph.get("ysize", 900)
  173. width = self.graph.get("width", 1)
  174. xstep = self.graph.get("xAxisStep", 6)
  175. pcolor = self.graph.get("pendingColor", "#f0e460")
  176. dcolor = self.graph.get("declinedColor", "#f291a6")
  177. acolor = self.graph.get("acceptedColor", "#81fc4c")
  178. p1 = plt.bar(ind, pends, width, color=pcolor)
  179. p2 = plt.bar(ind, declines, width, color=dcolor, bottom=pends)
  180. p3 = plt.bar(ind, accepts, width, color=acolor, bottom=pends_declines)
  181. xticks = arange(xstep-1, ind.size+xstep-1, xstep) + width/2.0
  182. xlabels = [d for c, d in zip(count(1), data.keys()) if not c % xstep]
  183. plt.xticks(xticks, xlabels)
  184. plt.yticks(arange(0, plt.ylim()[1], 10))
  185. plt.tick_params(direction="out")
  186. leg = plt.legend((p1[0], p2[0], p3[0]), ("Pending", "Declined",
  187. "Accepted"), loc="upper left", fancybox=True)
  188. leg.get_frame().set_alpha(0.5)
  189. fig = plt.gcf()
  190. fig.set_size_inches(xsize/100, ysize/100)
  191. fig.autofmt_xdate()
  192. ax = plt.gca()
  193. ax.yaxis.grid(True)