A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

209 Zeilen
7.6 KiB

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