vice-speaker-rotator.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. #!/usr/bin/env python3
  2. from datetime import date, timedelta
  3. import sys
  4. import argparse
  5. from argparse import RawTextHelpFormatter
  6. import yaml
  7. # text appended to the end of generated emails
  8. email_body = """
  9. Full speaker schedule:
  10. https://cs.uwaterloo.ca/twiki/view/CrySP/SpeakerSchedule
  11. Other upcoming events:
  12. https://cs.uwaterloo.ca/twiki/view/CrySP/UpcomingEvents
  13. """
  14. def str_to_date(string_date):
  15. if type(string_date) is date:
  16. return string_date
  17. try:
  18. return date(*[int(s) for s in string_date.split('-')])
  19. except:
  20. print("invalid date: " + string_date)
  21. sys.exit()
  22. class CryspCalendar:
  23. """Representation of a CrySP weekly meeting schedule for a term"""
  24. def __init__(self, start, end=None, weeks=None, names=[],
  25. constraints=[], practice_talks=[], half_practices=[],
  26. notes=[], irc_handles=dict(), no_repeat=False):
  27. self.dates = self.meeting_dates(start, end, weeks)
  28. self.names = names
  29. self.constraints = self.parse_constraints(constraints)
  30. self.practice_talks = self.parse_practice_talks(practice_talks)
  31. self.practice_talks.update(self.parse_practice_talks(half_practices,
  32. half=True))
  33. self.notes = self.parse_notes(notes)
  34. self.notes.update(self.parse_notes(map(lambda l: l[1:],
  35. practice_talks)))
  36. self.notes.update(self.parse_notes(map(lambda l: l[1:],
  37. half_practices)))
  38. self.verify_constraints()
  39. self.irc_handles = irc_handles
  40. self.no_repeat = no_repeat
  41. def meeting_dates(self, start, end=None, weeks=None):
  42. first_meeting = str_to_date(start)
  43. last_meeting = None
  44. if end:
  45. last_meeting = str_to_date(end)
  46. if weeks:
  47. last_meeting = min(first_meeting + timedelta(weeks=weeks),
  48. last_meeting)
  49. ret = []
  50. next_meeting = first_meeting
  51. one_week = timedelta(weeks=1)
  52. while next_meeting <= last_meeting:
  53. ret.append(next_meeting)
  54. next_meeting += one_week
  55. return ret
  56. def parse_constraints(self, constraints):
  57. """takes an iterable of (name,datestr,...) tuples"""
  58. constraint_dict = {}
  59. for constraint in constraints:
  60. name = constraint[0]
  61. date_strs = constraint[1:]
  62. dates = []
  63. for date_str in date_strs:
  64. if type(date_str) is not date and '--' in date_str:
  65. # date_range = list(map(str_to_date, date_str.split('--')))
  66. date_range = date_str.split('--')
  67. date_range = [str_to_date(date_range[0]),
  68. str_to_date(date_range[1])]
  69. [dates.append(d) for d in self.dates
  70. if date_range[0] <= d <= date_range[1]]
  71. else:
  72. dates.append(str_to_date(date_str))
  73. constraint_dict[name] = dates
  74. return constraint_dict
  75. def parse_practice_talks(self, practice, half=False):
  76. """'practice' is an iterable of (name, day, note) tuples"""
  77. practice_dict = {}
  78. for talk in practice:
  79. name = talk[0]
  80. day = str_to_date(talk[1])
  81. if day in practice_dict:
  82. assert half,\
  83. 'conflicting talks: %s and %s on %s' %\
  84. (practice_dict[day][0], name, day)
  85. practice_dict[day].append(name)
  86. elif half:
  87. practice_dict[day] = [name, ]
  88. else:
  89. practice_dict[day] = [name, '']
  90. return practice_dict
  91. def parse_notes(self, notes):
  92. """takes an iterable of (day, note) tuples"""
  93. notes_dict = {}
  94. for note in notes:
  95. day = str_to_date(note[0])
  96. message = note[1]
  97. assert day not in notes_dict or notes_dict[day] == message,\
  98. 'conflicting notes: "%s" and "%s" on %s' %\
  99. (notes_dict[day], message, note[0])
  100. notes_dict[day] = message
  101. return notes_dict
  102. def verify_constraints(self):
  103. for name in self.constraints:
  104. for day in self.constraints[name]:
  105. assert day in self.dates,\
  106. "constraint %s on %s isnt a meeting date" %\
  107. (name, day)
  108. for day in self.practice_talks:
  109. assert day in self.dates,\
  110. 'talk by %s designated on %s, which is not a meeting date' %\
  111. (self.practice_talks[day][0], day)
  112. for day in self.notes:
  113. assert day in self.dates,\
  114. 'note "%s" designated on %s, which is not a meeting date' %\
  115. (self.notes[day], day)
  116. def pop_name(self, day, names, i):
  117. """Pops the name of the next available on day from the names stack,
  118. where 'i' is which speaker they would be for that day (0 or 1).
  119. Returns None if no speakers are left in the given names stack."""
  120. name = None
  121. if day in self.practice_talks:
  122. if i < len(self.practice_talks[day]):
  123. name = self.practice_talks[day][i]
  124. if name is None:
  125. constrained_names = (name for name in names
  126. if name not in self.constraints
  127. or day not in self.constraints[name])
  128. name = next(constrained_names, None)
  129. if name and name in names:
  130. names.remove(name)
  131. return name
  132. def next_speaker(self, day, names, i):
  133. """Wrapper for pop_name() that repopulates names stack if needed."""
  134. name = self.pop_name(day, names, i)
  135. if name or self.no_repeat:
  136. return name
  137. names.extend(self.names)
  138. return self.pop_name(day, names, i)
  139. def date_to_speakers(self, day, names):
  140. speaker1 = self.next_speaker(day, names, 0)
  141. speaker2 = self.next_speaker(day, names, 1)
  142. note = self.notes.get(day, '')
  143. return speaker1, speaker2, note
  144. def table(self, today=date.today()):
  145. """Returns a string containing a twiki table."""
  146. table = '| *Date* | *Speakers* | *Notes* |\n'
  147. names = self.names.copy()
  148. for day in self.dates:
  149. color = "%SILVER% " if day <= today else ""
  150. endcolor = " %ENDCOLOR%" if day <= today else ""
  151. speaker1, speaker2, note = self.date_to_speakers(day, names)
  152. speaker2 = ', ' + speaker2 if speaker2 else ""
  153. row = "| {}{}{} | {}{}{}{} | {}{}{} |\n".format(
  154. color, day.strftime('%b %e'), endcolor,
  155. color, speaker1, speaker2, endcolor,
  156. color, note, endcolor
  157. )
  158. table += row
  159. return table
  160. def email(self, weeks=2, today=date.today()):
  161. """Returns a string for emailing to the lab who is speaking next"""
  162. emailstr = ''
  163. names = self.names.copy()
  164. i = 0
  165. for day in self.dates:
  166. if day <= today:
  167. self.date_to_speakers(day, names)
  168. continue
  169. i += 1
  170. if i > weeks:
  171. break
  172. speaker1, speaker2, note = self.date_to_speakers(day, names)
  173. emailstr += day.strftime('%b %e: ')
  174. if speaker1:
  175. emailstr += speaker1
  176. if speaker2:
  177. emailstr += ', ' + speaker2
  178. if note != '':
  179. emailstr += ' (' + note + ')'
  180. else:
  181. emailstr += note
  182. emailstr += '\n'
  183. emailstr += email_body
  184. return emailstr
  185. def irc(self, today=date.today()):
  186. """Returns a string for putting in the IRC channel topic"""
  187. names = self.names.copy()
  188. i = 0
  189. for day in self.dates:
  190. if day <= today:
  191. self.date_to_speakers(day, names)
  192. continue
  193. i += 1
  194. speaker1, speaker2, note = self.date_to_speakers(day, names)
  195. if speaker1:
  196. speaker1 = self.irc_handles.get(speaker1, speaker1)
  197. if speaker2:
  198. speaker2 = ', ' + self.irc_handles.get(speaker2, speaker2)
  199. if note != '':
  200. note = ' (' + note + ')'
  201. return "{}{}{}".format(speaker1, speaker2, note)
  202. def parse_constraintsfile(filename):
  203. with open(filename, 'r') as f:
  204. tweaks = {'c': [], 'p': [], 'h': [], 'n': []}
  205. for line in f:
  206. line = [x.strip() for x in line.rstrip().split(',')]
  207. tweaks[line[0]].append(line[1:])
  208. return tweaks['c'], tweaks['p'], tweaks['h'], tweaks['n']
  209. def parse_yaml(filename, today=date.today()):
  210. with open(filename, 'r') as f:
  211. struct = yaml.safe_load(f)
  212. currentTerm = None
  213. for term in struct['terms'].values():
  214. if 'start' in term and 'end' in term:
  215. term['end'] = str_to_date(term['end'])
  216. term['start'] = str_to_date(term['start'])
  217. if currentTerm is None or (term['end'] >= today and
  218. term['start'] > currentTerm['start']):
  219. currentTerm = term
  220. names = currentTerm['speakers']
  221. for name in names:
  222. assert name not in currentTerm['out']
  223. def triple_check(field_name, location):
  224. return field_name in location and \
  225. location[field_name] is not None and \
  226. len(location[field_name]) > 0
  227. constraints = [[name] + struct['speakers'][name]['constraints']
  228. for name in names
  229. if triple_check('constraints', struct['speakers'][name])]
  230. practice_talks = [(talk['name'], talk['date'], talk['note'])
  231. for talk in currentTerm['practice_talks']]
  232. half_practices = [(talk['name'], talk['date'], talk['note'])
  233. for talk in currentTerm['half_practices']]
  234. for speaker in struct['speakers']:
  235. location = struct['speakers'][speaker]
  236. if triple_check('practice_talks', location):
  237. practice_talks += {(speaker, talk['date'], talk['note'])
  238. for talk in location['practice_talks']}
  239. if triple_check('half_practices', location):
  240. half_practices += {(speaker, talk['date'], talk['note'])
  241. for talk in location['half_practices']}
  242. notes = [(note['date'], note['note']) for note in currentTerm['notes']]
  243. irc_handles = {name: struct['speakers'][name]['irc']
  244. for name in struct['speakers']
  245. if 'irc' in struct['speakers'][name]}
  246. return CryspCalendar(currentTerm['start'], currentTerm['end'],
  247. names=names, constraints=constraints,
  248. practice_talks=practice_talks,
  249. half_practices=half_practices,
  250. notes=notes, irc_handles=irc_handles)
  251. def make_parser():
  252. parser = argparse.ArgumentParser(description='''\
  253. Print a speaker schedule for the CrySP weekly meetings.
  254. All dates are ISO formatted (yyyy-mm-dd). Constraints in files can also be
  255. ranges of ISO formatted dates (yyyy-mm-dd--yyyy-mm-dd).''',
  256. epilog='''\
  257. Now that the lab is so large, you likely want to use one of the file options,
  258. probably YAML. The command line options still function if you want to play
  259. with how this script works to learn, though.
  260. The YAML file has the following format:
  261. There are two main objects, a "terms" object that stores data about particular
  262. terms, and a "speakers" ojbect that stores data about the speakers.
  263. The "terms" object contains any number of term objects with any name. Each
  264. term has the following objects:
  265. start: the date of the first meeting
  266. end: a date on and beyond which there are no more meetings
  267. speakers: an ordered list of names for each speaker this term
  268. out: a list to store lab members who won't speak this term (ignored)
  269. practice_talks: a list of practice talks, of the form
  270. {date: _, name: _, note: _}
  271. half_practices: a list of half practice talks (format is the same)
  272. notes: notes, of the form
  273. {date: _, note: _}
  274. The "speakers" object contains any number of speaker objects. The name of each
  275. speaker object should be the same as the name in the speakers list, if they
  276. are speaking this term. The names can have spaces. Each speaker object has
  277. the following objects:
  278. irc: the IRC handle of the speaker, if they're in CrySP IRC
  279. email: the email address of the speaker (check the UW whitepages if need be)
  280. constraints: a list of dates/date ranges the speaker cannot speak on
  281. practice_talks: a list of practice talks, each of the form:
  282. {date: _, note: _}
  283. half_practices: a list of half practice talks (format is the same)
  284. ''',
  285. formatter_class=RawTextHelpFormatter)
  286. parser.add_argument('-y', '--yaml',
  287. metavar='FILE',
  288. help='full description of the term via YAML file.')
  289. parser.add_argument('-s', '--start',
  290. metavar='DATE',
  291. help='date of the first meeting')
  292. parser.add_argument('-e', '--end', metavar='DATE',
  293. help='last date to schedule a meeting on or before\n'
  294. '(if -w also specified, uses whatever is shortest)')
  295. parser.add_argument('-w', '--weeks', type=int,
  296. help='number of weeks to schedule for\n'
  297. '(if -e also specified, uses whatever is shortest)')
  298. group = parser.add_mutually_exclusive_group()
  299. group.add_argument('-n', '--names',
  300. nargs='+', default=[], metavar='NAME',
  301. help='names to schedule in their speaking order')
  302. group.add_argument('-f', '--namesfile',
  303. metavar='FILE',
  304. help='path of a file that contains a comma-seperated\n'
  305. 'list of names to schedule in their speaking order')
  306. parser.add_argument('-c', '--constraintsfile',
  307. metavar='FILE',
  308. help='Provide constraints, practice talks, and notes\n'
  309. 'via supplied CSV file. The CSV can contain the\n'
  310. 'following lines:\n'
  311. 'constraints - dates where someone cannot speak:\n'
  312. '"c,[name],[date/range1],[date/range2],[...]"\n'
  313. 'notes - goes in the notes column for that date:\n'
  314. '"n,[date],[note]"\n'
  315. 'practice talks - dates where something other than\n'
  316. 'the usual CrySP meeting talks is happening:\n'
  317. '"p,[name],[date],[note (e.g., "practice talk")]"\n'
  318. 'half-slot - a rare case where someone/thing needs\n'
  319. 'only one of the speaker slots on this date:\n'
  320. '"h,[name],[date],[note]"\n')
  321. parser.add_argument('-r', '--no-repeat',
  322. action='store_true',
  323. help='disables repeating the list of names')
  324. parser.add_argument('-E', '--email',
  325. nargs='?', const=2, default=False,
  326. metavar='WEEKS',
  327. help='print an email for notifying who is speaking\n'
  328. 'the next two (or specified) weeks')
  329. parser.add_argument('-i', '--irc',
  330. action='store_true',
  331. help='print names formatted for an irc channel topic')
  332. parser.add_argument('-d', '--today',
  333. default=date.today(), metavar='DATE',
  334. help='pretend the script is being run on the day DATE')
  335. return parser
  336. def old_format(args):
  337. if args.namesfile:
  338. with open(args.namesfile, 'r') as f:
  339. names = [x.strip() for x in f.read().split(',')]
  340. else:
  341. names = args.names
  342. if args.constraintsfile:
  343. constraints, practice, halves, notes = \
  344. parse_constraintsfile(args.constraintsfile)
  345. return CryspCalendar(args.start, args.end, args.weeks, names,
  346. constraints, practice, halves, notes,
  347. args.no_repeat)
  348. return CryspCalendar(args.start, args.end, args.weeks, names,
  349. no_repeat=args.no_repeat)
  350. def main(argv=None):
  351. if argv is None:
  352. argv = sys.argv
  353. parser = make_parser()
  354. args = parser.parse_args()
  355. if not args.end and not args.weeks and not args.yaml:
  356. parser.error('requires -w/--weeks or -e/--end')
  357. if not args.yaml:
  358. cal = old_format(args)
  359. else:
  360. cal = parse_yaml(args.yaml)
  361. today = str_to_date(args.today)
  362. if args.email:
  363. print(cal.email(int(args.email), today))
  364. elif args.irc:
  365. print(cal.irc(today))
  366. else:
  367. print(cal.table(today))
  368. return 0
  369. if __name__ == '__main__':
  370. sys.exit(main())