A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

196 lines
7.1 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(15)
  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. if new_page.is_redirect():
  118. return STATUS_NONE # Ignore accepted AFC/R requests
  119. return STATUS_ACCEPT
  120. cats = self.categories
  121. sq = self.site.sql_query
  122. query = "SELECT 1 FROM categorylinks WHERE cl_to = ? AND cl_from = ?"
  123. match = lambda cat: list(sq(query, (cat.replace(" ", "_"), pageid)))
  124. if match(cats["pending"]):
  125. return STATUS_PEND
  126. elif match(cats["unsubmitted"]):
  127. return STATUS_NONE
  128. elif match(cats["declined"]):
  129. return STATUS_DECLINE
  130. return STATUS_NONE
  131. def get_date_counts(self, date):
  132. query = "SELECT COUNT(*) FROM page WHERE page_date = ? AND page_status = ?"
  133. statuses = [STATUS_PEND, STATUS_DECLINE, STATUS_ACCEPT]
  134. counts = {}
  135. with self.conn.cursor() as cursor:
  136. for status in statuses:
  137. cursor.execute(query, (date, status))
  138. count = cursor.fetchall()[0][0]
  139. counts[status] = count
  140. return counts
  141. def generate_chart(self, data):
  142. pends = [d[STATUS_PEND] for d in data.itervalues()]
  143. declines = [d[STATUS_DECLINE] for d in data.itervalues()]
  144. accepts = [d[STATUS_ACCEPT] for d in data.itervalues()]
  145. ind = arange(len(data))
  146. width = self.graph.get("width", 0.75)
  147. xstep = self.graph.get("xAxisStep", 6)
  148. xticks = arange(xstep-1, ind.size+xstep-1, xstep) + width/2.0
  149. xlabels = [d for c, d in zip(count(1), data.keys()) if not c % xstep]
  150. pcolor = self.graph.get("pendingColor", "y")
  151. dcolor = self.graph.get("declinedColor", "r")
  152. acolor = self.graph.get("acceptedColor", "g")
  153. p1 = plt.bar(ind, pends, width, color=pcolor)
  154. p2 = plt.bar(ind, declines, width, color=dcolor, bottom=pends)
  155. p3 = plt.bar(ind, accepts, width, color=acolor, bottom=declines)
  156. plt.title("AfC submissions per date")
  157. plt.ylabel("Submissions")
  158. plt.xlabel("Date")
  159. plt.xticks(xticks, xlabels)
  160. plt.legend((p1[0], p2[0], p3[0]), ("Pending", "Declined", "Accepted"))
  161. fig = plt.gcf()
  162. fig.set_size_inches(12, 9) # 1200, 900
  163. fig.autofmt_xdate()