Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 

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