vice-speaker-rotator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/usr/bin/env python3
  2. from datetime import date,timedelta
  3. import sys, argparse
  4. from argparse import RawTextHelpFormatter
  5. # text appended to the end of generated emails
  6. email_body = """
  7. Full speaker schedule:
  8. https://cs.uwaterloo.ca/twiki/view/CrySP/SpeakerSchedule
  9. Other upcoming events:
  10. https://cs.uwaterloo.ca/twiki/view/CrySP/UpcomingEvents
  11. """
  12. def str_to_date(string_date):
  13. return date(*[int(s) for s in string_date.split('-')])
  14. class CryspCalendar:
  15. """Representation of a CrySP weekly meeting schedule for a term"""
  16. def __init__(self, start, end=None, weeks=None, names=[],
  17. constraints=[], practice_talks=[], half_practices=[], notes=[],
  18. no_repeat=False):
  19. self.dates = self.meeting_dates(start, end, weeks)
  20. self.names = names
  21. self.constraints = self.parse_constraints(constraints)
  22. self.practice_talks = self.parse_practice_talks(practice_talks)
  23. self.practice_talks.update(self.parse_practice_talks(half_practices,
  24. half=True))
  25. self.notes = self.parse_notes(notes)
  26. self.notes.update(self.parse_notes(practice_talks))
  27. self.notes.update(self.parse_notes(half_practices))
  28. self.verify_constraints()
  29. self.no_repeat = no_repeat
  30. def meeting_dates(self, start, end=None, weeks=None):
  31. first_meeting = str_to_date(start)
  32. last_meeting = None
  33. if end:
  34. last_meeting = str_to_date(end)
  35. if weeks:
  36. last_meeting = max(first_meeting + timedelta(weeks=weeks),
  37. last_meeting)
  38. ret = []
  39. next_meeting = first_meeting
  40. one_week = timedelta(weeks=1)
  41. while next_meeting <= last_meeting:
  42. ret.append(next_meeting)
  43. next_meeting += one_week
  44. return ret
  45. def parse_constraints(self, constraints):
  46. constraint_dict = {}
  47. for constraint in constraints:
  48. name = constraint[0]
  49. date_strs = constraint[1:]
  50. dates = []
  51. for date_str in date_strs:
  52. dates.append(str_to_date(date_str))
  53. constraint_dict[name] = dates
  54. return constraint_dict
  55. def parse_practice_talks(self, practice, half=False):
  56. practice_dict = {}
  57. for talk in practice:
  58. name = talk[0]
  59. day = str_to_date(talk[1])
  60. if day in practice_dict:
  61. assert half,\
  62. 'conflicting talks: %s and %s on %s' %\
  63. (practice_dict[day][0], name, day)
  64. practice_dict[day].append(name)
  65. elif half:
  66. practice_dict[day] = [name,]
  67. else:
  68. practice_dict[day] = [name, '']
  69. return practice_dict
  70. def parse_notes(self, notes):
  71. notes_dict = {}
  72. for note in notes:
  73. day = str_to_date(note[1])
  74. message = note[2]
  75. assert day not in notes_dict or notes_dict[day] == message,\
  76. 'conflicting notes: "%s" and "%s" on %s' %\
  77. (notes_dict[day], message, note[1])
  78. notes_dict[day] = message
  79. return notes_dict
  80. def verify_constraints(self):
  81. for name in self.constraints:
  82. for day in self.constraints[name]:
  83. assert day in self.dates,\
  84. 'constraint added for %s on %s, which is not a meeting date' %\
  85. (name, day)
  86. for day in self.practice_talks:
  87. assert day in self.dates,\
  88. 'talk by %s designated on %s, which is not a meeting date' %\
  89. (self.practice_talks[day][0], day)
  90. for day in self.notes:
  91. assert day in self.dates,\
  92. 'note "%s" designated on %s, which is not a meeting date' %\
  93. (self.notes[day], day)
  94. def pop_name(self, day, names, i):
  95. """Pops the name of the next available on day from the names stack,
  96. where 'i' is which speaker they would be for that day (0 or 1).
  97. Returns None if no speakers are left in the given names stack."""
  98. name = None
  99. if day in self.practice_talks:
  100. if i < len(self.practice_talks[day]):
  101. name = self.practice_talks[day][i]
  102. if name is None:
  103. constrained_names = (name for name in names \
  104. if name not in self.constraints \
  105. or day not in self.constraints[name])
  106. name = next(constrained_names, None)
  107. if name and name in names:
  108. names.remove(name)
  109. return name
  110. def next_speaker(self, day, names, i):
  111. """Wrapper for pop_name() that repopulates names stack if needed."""
  112. name = self.pop_name(day, names, i)
  113. if name or self.no_repeat:
  114. return name
  115. names.extend(self.names)
  116. return self.pop_name(day, names, i)
  117. def date_to_speakers(self, day, names):
  118. speaker1 = self.next_speaker(day, names, 0)
  119. speaker2 = self.next_speaker(day, names, 1)
  120. note = self.notes.get(day, '')
  121. return speaker1, speaker2, note
  122. def table(self):
  123. """Returns a string containing a twiki table."""
  124. table = '| *Date* | *Speakers* | *Notes* |\n'
  125. names = self.names.copy()
  126. for day in self.dates:
  127. table += day.strftime('| %b %e |')
  128. speaker1, speaker2, note = self.date_to_speakers(day, names)
  129. if speaker1:
  130. table += ' ' + speaker1
  131. if speaker2:
  132. table += ', ' + speaker2
  133. table += ' | ' + note + ' |\n'
  134. return table
  135. def email(self, weeks=2, today=date.today()):
  136. """Returns a string for emailing to the lab who is speaking next"""
  137. emailstr = ''
  138. names = self.names.copy()
  139. i = 0
  140. for day in self.dates:
  141. if day <= today:
  142. self.date_to_speakers(day, names)
  143. continue
  144. i += 1
  145. if i > weeks:
  146. break
  147. speaker1, speaker2, note = self.date_to_speakers(day, names)
  148. emailstr += day.strftime('%b %e: ')
  149. if speaker1:
  150. emailstr += speaker1
  151. if speaker2:
  152. emailstr += ', ' + speaker2
  153. if note != '':
  154. emailstr += ' (' + note + ')'
  155. else:
  156. emailstr += note
  157. emailstr += '\n'
  158. emailstr += email_body
  159. return emailstr
  160. def parse_constraintsfile(filename):
  161. with open(filename, 'r') as f:
  162. tweaks = {'c': [], 'p': [], 'h': [], 'n': []}
  163. for line in f:
  164. l = [x.strip() for x in line.rstrip().split(',')]
  165. tweaks[l[0]].append(l[1:])
  166. return tweaks['c'], tweaks['p'], tweaks['h'], tweaks['n']
  167. def make_parser():
  168. parser = argparse.ArgumentParser(description =
  169. 'Print a speaker schedule for the CrySP weekly meetings.',
  170. formatter_class=RawTextHelpFormatter)
  171. parser.add_argument('-s', '--start',
  172. metavar = 'DATE', required = True,
  173. help =
  174. 'date of the first meeting in ISO format\n' +\
  175. '(yyyy-mm-dd)')
  176. parser.add_argument('-e', '--end', metavar = 'DATE',
  177. help =
  178. 'last date to schedule a meeting on or before\n' +\
  179. '(if -w also specified, uses whatever is shortest)')
  180. parser.add_argument('-w', '--weeks', type=int,
  181. help =
  182. 'number of weeks to schedule for\n' +\
  183. '(if -e also specified, uses whatever is shortest)')
  184. group = parser.add_mutually_exclusive_group()
  185. group.add_argument('-n', '--names',
  186. nargs = '+', default = [], metavar = 'NAME',
  187. help =
  188. 'names to schedule in their speaking order')
  189. group.add_argument('-f', '--namesfile',
  190. metavar = 'FILE',
  191. help =
  192. 'path of a file that contains a comma-seperated\n' +\
  193. ' list of names to schedule in their speaking order')
  194. parser.add_argument('-c', '--constraintsfile',
  195. metavar = 'FILE',
  196. help =
  197. 'Provide constraints, practice talks, and notes\n' +\
  198. 'via supplied csv file. The CSV can contain the\n' +\
  199. 'following lines:\n' +\
  200. 'constraints - dates where someone cannot speak:\n' +\
  201. '"c,[name],[date1],[date2],[...]"\n' +\
  202. 'notes - goes in the notes column for that date:\n' +\
  203. '"n,[date],[note]"\n' +\
  204. 'practice talks - dates where something other than\n' +\
  205. 'the usual CrySP meeting talks is happening:\n' +\
  206. '"p,[name],[date],[note (e.g., "practice talk")]"\n' +\
  207. 'half-slot - a rare case where someone/thing needs\n' +\
  208. 'only one of the speaker slots on this date:\n' +\
  209. '"h,[name],[date],[note]"\n')
  210. parser.add_argument('-r', '--no-repeat',
  211. action = 'store_true',
  212. help =
  213. 'disables repeating the list of names')
  214. parser.add_argument('-E', '--email',
  215. nargs = '?', const = 2, default = False,
  216. metavar = 'WEEKS',
  217. help =
  218. 'print an email for notifying who is speaking\n' +\
  219. 'the next two (or specified) weeks')
  220. return parser
  221. def main(argv=None):
  222. if argv is None:
  223. argv = sys.argv
  224. parser = make_parser()
  225. args = parser.parse_args()
  226. if not args.end and not args.weeks:
  227. parser.error('requires -w/--weeks or -e/--end')
  228. if args.namesfile:
  229. with open(args.namesfile, 'r') as f:
  230. names = [x.strip() for x in f.read().split(',')]
  231. else:
  232. names = args.names
  233. if args.constraintsfile:
  234. constraints, practice, halves, notes = \
  235. parse_constraintsfile(args.constraintsfile)
  236. cal = CryspCalendar(args.start, args.end, args.weeks, names,
  237. constraints, practice, halves, notes,
  238. args.no_repeat)
  239. else:
  240. cal = CryspCalendar(args.start, args.end, args.weeks, names,
  241. no_repeat=args.no_repeat)
  242. print(cal.table() if not args.email else cal.email(int(args.email)))
  243. return 0;
  244. if __name__ == '__main__':
  245. sys.exit(main())