lps_gen.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2015-2017 lpschedule-generator contributors. See
  4. # CONTRIBUTORS.
  5. #
  6. # This file is part of lpschedule-generator.
  7. #
  8. # lpschedule-generator is free software: you can redistribute it
  9. # and/or modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation, either version 3 of
  11. # the License, or (at your option) any later version.
  12. #
  13. # lpschedule-generator is distributed in the hope that it will be
  14. # useful, but WITHOUT ANY WARRANTY; without even the implied
  15. # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  16. # See the GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with lpschedule-generator (see COPYING). If not, see
  20. # <http://www.gnu.org/licenses/>.
  21. import json
  22. import re
  23. import sys
  24. import pytz
  25. from argparse import ArgumentParser
  26. from collections import OrderedDict
  27. from datetime import datetime
  28. from os import path
  29. from bs4 import BeautifulSoup
  30. from icalendar import Calendar, Event, vCalAddress, vText, vDatetime
  31. from jinja2 import Environment, FileSystemLoader
  32. from jinja2.exceptions import TemplateNotFound
  33. from mistune import Renderer, Markdown
  34. from pytz import timezone
  35. from unidecode import unidecode
  36. from lpschedule_generator._version import __version__
  37. # unicode magic
  38. reload(sys)
  39. sys.setdefaultencoding('utf-8')
  40. # Python dictionary that will contain the lp schedule.
  41. lps_dict = OrderedDict()
  42. # Python dictionary that will contain the lp speakers.
  43. lpspeakers_dict = OrderedDict()
  44. def read_file(filename):
  45. """Read file and return it as a string.
  46. :param str filename: Absolute pathname of the file.
  47. """
  48. content = ''
  49. try:
  50. with open(filename, 'rb') as f:
  51. for line in f:
  52. content = content + line
  53. except IOError:
  54. print "Error: unable to open %s" % filename
  55. return content
  56. def write_file(filename, filecontent):
  57. """Write `filecontent` to `filename`.
  58. :param str filename:
  59. Absolute pathname of the file.
  60. :param str filecontent:
  61. Data to write to `filename`.
  62. """
  63. file_ = None
  64. try:
  65. file_ = open(filename, 'wb')
  66. file_.write(filecontent)
  67. file_.close()
  68. except IOError:
  69. print "Error creating and writing content to %s" % filename
  70. exit(1)
  71. def json_write(filename, obj):
  72. """Serialize `obj` to JSON formatted `str` to `filename`.
  73. `filename` is written relative to the current working directory.
  74. """
  75. write_file(filename, json.dumps(obj, ensure_ascii=False, indent=4))
  76. def json_read(filename):
  77. """Deserialize JSON from `filename` into Python object.
  78. """
  79. if not path.isfile(filename):
  80. return False
  81. return json.loads(read_file(filename),
  82. object_pairs_hook=OrderedDict)
  83. class LPiCal(object):
  84. """Used for producing iCal for LP schedule.
  85. """
  86. def __init__(self, lps_dict, lp_year):
  87. self.lps_dict = lps_dict
  88. self.lp_year = str(lp_year)
  89. # Matches strings like '09:45 - 10:30: Lorem ipsum dolor sit.'
  90. self.timeslot_re = re.compile(r'(\d+:\d+).+?(\d+:\d+):'
  91. + r'\s*(.+\b)')
  92. # Matches strings like 'Saturday, March 19'
  93. self.month_day_re = re.compile(r'\w+,\s*([a-zA-Z]+)\s*(\d+)')
  94. self.cal = Calendar()
  95. self.cal.add('prodid', '-//lpschedule generator//mxm.dk//')
  96. self.cal.add('version', '2.0')
  97. # RFC 2445 requires DTSTAMP to be in UTC. DTSTAMP is used in
  98. # VEVENT (Event object, see `add_event` method).
  99. self.dtstamp = vDatetime(datetime.now(pytz.utc))
  100. # used to generate uid for ical.
  101. self.ucounter = 0
  102. def gen_uid(self):
  103. """Returns an unique id.
  104. Used for Event object.
  105. """
  106. self.ucounter = self.ucounter + 1
  107. return '%s@LP%s@libreplanet.org' % (str(self.ucounter),
  108. self.lp_year)
  109. def get_timeslot(self, s):
  110. """Get start and end time for a timeslot.
  111. """
  112. timeslot = self.timeslot_re.search(s)
  113. if (not timeslot) or (len(timeslot.groups()) < 3):
  114. return None, None, None
  115. t_start = timeslot.group(1)
  116. t_end = timeslot.group(2)
  117. name = timeslot.group(3)
  118. return t_start, t_end, name
  119. def get_month_day(self, s):
  120. """Get month and day.
  121. """
  122. month_day = self.month_day_re.search(s)
  123. if (not month_day) or (len(month_day.groups()) < 2):
  124. return None, None
  125. month = month_day.group(1)
  126. day = month_day.group(2)
  127. return month, day
  128. def mk_datetime(self, month, day, time):
  129. """Returns datetime object (EST).
  130. """
  131. # Day %d
  132. # Month %B
  133. # Year %Y
  134. # Hour %H (24-hr)
  135. # Minute %M (zero padded)
  136. # Second %S (zero padded)
  137. datetime_fmt = '%d %B %Y %H:%M:%S'
  138. eastern = timezone('US/Eastern')
  139. hour = time.split(':')[0]
  140. minute = time.split(':')[1]
  141. datetime_str = '%s %s %s %s:%s:%s' % (day, month, self.lp_year,
  142. hour.zfill(2),
  143. minute.zfill(2),
  144. '00')
  145. dt_object = datetime.strptime(datetime_str, datetime_fmt)
  146. return vDatetime(eastern.localize(dt_object))
  147. def mk_attendee(self, speaker):
  148. """Make Attendee to be added to an Event object.
  149. See `add_event` method.
  150. """
  151. # Get rid of HTML (<a> element, etc) in `speaker`
  152. speaker = BeautifulSoup(speaker, 'html.parser').get_text()
  153. attendee = vCalAddress('invalid:nomail')
  154. attendee.params['cn'] = vText(speaker)
  155. attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
  156. attendee.params['CUTYPE'] = vText('INDIVIDUAL')
  157. return attendee
  158. def add_event(self, month, day, t_start, t_end, t_name, session,
  159. session_info):
  160. """Adds event to calendar.
  161. """
  162. event = Event()
  163. event['uid'] = self.gen_uid()
  164. event['dtstamp'] = self.dtstamp
  165. event['class'] = vText('PUBLIC')
  166. event['status'] = vText('CONFIRMED')
  167. event['method'] = vText('PUBLISH')
  168. if session == 'st-from-ts':
  169. event['summary'] = t_name
  170. else:
  171. event['summary'] = session
  172. event['location'] = vText(session_info['room'])
  173. # Get rid of HTML in 'desc'
  174. desc = BeautifulSoup(' '.join(
  175. session_info['desc']).replace(
  176. '\n', ' '), 'html.parser').get_text()
  177. event['description'] = desc
  178. # Add speakers
  179. for speaker in session_info['speakers']:
  180. event.add('attendee', self.mk_attendee(speaker), encode=0)
  181. dt_start = self.mk_datetime(month, day, t_start)
  182. dt_end = self.mk_datetime(month, day, t_end)
  183. event['dtstart'] = dt_start
  184. event['dtend'] = dt_end
  185. # Add to calendar
  186. self.cal.add_component(event)
  187. return event
  188. def gen_ical(self):
  189. """Parse LP schedule dict and generate iCal Calendar object.
  190. """
  191. for day_str, timeslots in self.lps_dict.iteritems():
  192. month, day = self.get_month_day(day_str)
  193. if not month:
  194. # month, day not specified; cannot generate ical for
  195. # this day
  196. continue
  197. for timeslot_str, sessions in timeslots.iteritems():
  198. t_start, t_end, t_name = self.get_timeslot(timeslot_str)
  199. if not t_start:
  200. # timeslot not specified; cannot generate ical for
  201. # this timeslot
  202. continue
  203. for session, session_info in sessions.iteritems():
  204. self.add_event(month, day, t_start, t_end, t_name,
  205. session, session_info)
  206. return self.cal.to_ical()
  207. def to_ical(self):
  208. """Writes iCal to disk.
  209. """
  210. filename = 'lp%s-schedule.ics' % self.lp_year
  211. write_file(filename, self.gen_ical())
  212. return filename
  213. class LPSRenderer(Renderer):
  214. """Helps convert Markdown version of LP schedule to a dictionary.
  215. """
  216. def __init__(self, **kwargs):
  217. super(LPSRenderer, self).__init__(**kwargs)
  218. self.last_day = None
  219. self.last_time_slot = None
  220. self.last_session = None
  221. # Denotes the no. of the paragraph under a session; this
  222. # information will be helpful in identifying the "speaker",
  223. # "room" and session "description".
  224. self.no_paragraph = None
  225. # Contains a list of speakers' names which are marked up for
  226. # auto-linking[1], but don't have an id to link to.
  227. #
  228. # [1]: Markup for auto-linking speakers is [John Hacker]().
  229. self.speakers_noids = []
  230. # If it is 'False', then the 'speaker.ids' file was not found;
  231. # otherwise it is an OrderedDict containing the mapping of
  232. # speakers and their corresponding id.
  233. self.speakers_ids = json_read('speakers.ids')
  234. def get_uid(self, speaker):
  235. """Generate unique id for `speaker`.
  236. Returns unique id for `speaker` if it exists; `False` otherwise.
  237. """
  238. if not self.speakers_ids:
  239. # There is no speakers_ids OrderedDict available.
  240. return False
  241. speaker = unicode(speaker)
  242. if speaker in self.speakers_ids.keys():
  243. return self.speakers_ids[speaker]
  244. else:
  245. # speaker not found in speakers_ids OrderedDict.
  246. return False
  247. def _check_session_title_exists(self):
  248. """Checks if :py:attr:`.last_session` is set.
  249. If :py:attr:`.last_session` is not set and first paragraph is
  250. encountered, then it is assumed that the current timeslot is in
  251. the following format::
  252. ### 9:00 - 10:45: Opening Keynote - Beyond unfree...
  253. [Cory Doctorow][doctorow]
  254. Room 32-123
  255. Software has eaten the world...
  256. This method is meant to be called from the
  257. :py:method:`.paragraph` method.
  258. """
  259. if not self.last_session and self.no_paragraph == 0:
  260. # Current timeslot has only one session and there
  261. # no session title.
  262. #
  263. # st-from-ts -> session title from time slot.
  264. lps_dict[self.last_day][self.last_time_slot][
  265. 'st-from-ts'] = OrderedDict()
  266. self.last_session = 'st-from-ts'
  267. def link(self, link, title, text):
  268. # Here, we catch speaker names that have to be autolinked and
  269. # autolink them if there is an id available for the speaker.
  270. if not link:
  271. # We found a speaker that has to be autolinked.
  272. # Here, `text` is the speaker' name.
  273. id_ = self.get_uid(text)
  274. if id_:
  275. link = 'speakers.html#%s' % id_
  276. else:
  277. # Oh no, there is no id for this speaker.
  278. self.speakers_noids.append(text)
  279. # Don't linkify this speaker; they don't have an id.
  280. return text
  281. return super(LPSRenderer, self).link(link, title, text)
  282. def header(self, text, level, raw=None):
  283. global lps_dict
  284. if level == 2:
  285. # Add new day.
  286. lps_dict[text] = OrderedDict()
  287. self.last_day = text
  288. elif level == 3:
  289. # Add new timeslot
  290. lps_dict[self.last_day][text] = OrderedDict()
  291. self.last_time_slot = text
  292. # New timeslot, reset paragraphs processed and
  293. # last session.
  294. self.no_paragraph = 0
  295. self.last_session = None
  296. elif level == 4:
  297. # Add new session
  298. lps_dict[self.last_day][self.last_time_slot][
  299. text] = OrderedDict()
  300. self.last_session = text
  301. # We found a new session; set no of paragraphs processed
  302. # to 0.
  303. self.no_paragraph = 0
  304. return super(LPSRenderer, self).header(text, level, raw)
  305. def paragraph(self, text):
  306. global lps_dict
  307. self._check_session_title_exists()
  308. p = super(LPSRenderer, self).paragraph(text)
  309. if self.no_paragraph == 0:
  310. # Speaker
  311. speakers = text.split(', ')
  312. lps_dict[self.last_day][self.last_time_slot][
  313. self.last_session]['speakers'] = speakers
  314. self.no_paragraph = self.no_paragraph + 1
  315. elif self.no_paragraph == 1:
  316. # Room
  317. lps_dict[self.last_day][self.last_time_slot][
  318. self.last_session]['room'] = text
  319. # Initialize description
  320. lps_dict[self.last_day][self.last_time_slot][
  321. self.last_session]['desc'] = []
  322. self.no_paragraph = self.no_paragraph + 1
  323. elif self.no_paragraph > 1:
  324. lps_dict[self.last_day][self.last_time_slot][
  325. self.last_session]['desc'].append(text)
  326. return p
  327. class LPSpeakersRenderer(Renderer):
  328. """Helps convert Markdown version of LP speakers to a dictionary.
  329. """
  330. def __init__(self, **kwargs):
  331. super(LPSpeakersRenderer, self).__init__(**kwargs)
  332. global lpspeakers_dict
  333. lpspeakers_dict = OrderedDict()
  334. lpspeakers_dict['keynote-speakers'] = []
  335. lpspeakers_dict['speakers'] = []
  336. # Type of present speaker being processed; can either be
  337. # 'keynote-speakers' or 'speakers'.
  338. self.speaker_type = None
  339. # Maintain a dict of speakers and their IDs.
  340. self.speakers_ids = OrderedDict()
  341. def mk_uid(self, speaker_block):
  342. """Returns a unique id.
  343. """
  344. # 'John HÖcker, Onion Project' -> 'John HÖcker'
  345. speaker = unicode(speaker_block.split(', ')[0])
  346. # 'John HÖcker' -> 'John Hacker'
  347. ascii_speaker = unidecode(speaker)
  348. # 'John Hacker' -> 'hacker'
  349. id_ = ascii_speaker.split()[-1].lower()
  350. if id_ not in self.speakers_ids.values():
  351. self.speakers_ids[speaker]= id_
  352. return id_
  353. else:
  354. # 'John Hacker' -> 'john_hacker'
  355. id_ = '_'.join([s.lower() for s in ascii_speaker.split()])
  356. self.speakers_ids[speaker] = id_
  357. return id_
  358. def header(self, text, level, raw=None):
  359. global lpspeakers_dict
  360. if level == 1:
  361. self.speaker_type = 'keynote-speakers'
  362. lpspeakers_dict[self.speaker_type].append(OrderedDict())
  363. lpspeakers_dict[self.speaker_type][-1]['speaker'] = text
  364. lpspeakers_dict[self.speaker_type][-1][
  365. 'id'] = self.mk_uid(text)
  366. lpspeakers_dict[self.speaker_type][-1][
  367. 'bio'] = []
  368. elif level == 2:
  369. self.speaker_type = 'speakers'
  370. lpspeakers_dict[self.speaker_type].append(OrderedDict())
  371. lpspeakers_dict[self.speaker_type][
  372. -1]['speaker'] = text.split(', ')[0]
  373. lpspeakers_dict[self.speaker_type][
  374. -1]['id'] = self.mk_uid(text)
  375. lpspeakers_dict[self.speaker_type][
  376. -1]['bio'] = []
  377. return super(LPSpeakersRenderer, self).header(text, level, raw)
  378. def image(self, src, title, text):
  379. global lpspeakers_dict
  380. lpspeakers_dict[self.speaker_type][-1]['img_url'] = src
  381. lpspeakers_dict[self.speaker_type][-1]['img_alt'] = text
  382. return super(LPSpeakersRenderer, self).image(src, title, text)
  383. def paragraph(self, text):
  384. global lpspeakers_dict
  385. p = super(LPSpeakersRenderer, self).paragraph(text)
  386. if text.startswith('<img'):
  387. # ignore
  388. return p
  389. lpspeakers_dict[self.speaker_type][-1]['bio'].append(text)
  390. return p
  391. class LPSMarkdown(Markdown):
  392. """Converts MD LP schedule to a dictionary.
  393. Returns the Markdown version of LP schedule as a dictionary.
  394. """
  395. def __init__(self, inline=None, block=None, **kwargs):
  396. """
  397. Initialize with LPSRenderer as the renderer.
  398. """
  399. self.sessions_renderer = LPSRenderer()
  400. super(LPSMarkdown, self).__init__(
  401. renderer=self.sessions_renderer,
  402. inline=None, block=None,
  403. **kwargs)
  404. def parse(self, text):
  405. global lps_dict
  406. lps_dict = OrderedDict()
  407. html = super(LPSMarkdown, self).parse(text)
  408. # Write list of speakers with no ids to `speakers.noids`.
  409. json_write('speakers.noids',
  410. self.sessions_renderer.speakers_noids)
  411. return lps_dict
  412. class LPSpeakersMarkdown(Markdown):
  413. """Converts MD LP speakers to a dictionary.
  414. Returns the Markdown version of LP speakers as a dictionary.
  415. """
  416. def __init__(self, inline=None, block=None, **kwargs):
  417. """
  418. Initialize with LPSpeakersRenderer as the renderer.
  419. """
  420. self.speakers_renderer = LPSpeakersRenderer()
  421. super(LPSpeakersMarkdown, self).__init__(
  422. renderer=self.speakers_renderer,
  423. inline=None, block=None,
  424. **kwargs)
  425. def parse(self, text):
  426. global lpspeakers_dict
  427. html = super(LPSpeakersMarkdown, self).parse(text)
  428. # Write mapping of speakers and their ids to `speakers.ids`.
  429. json_write('speakers.ids', self.speakers_renderer.speakers_ids)
  430. return lpspeakers_dict
  431. def RenderHTML(lp_dict, template):
  432. """Renders LP schedule/speakers in HTML from a python dictionary.
  433. Returns the HTML as a string.
  434. """
  435. env = Environment(loader=FileSystemLoader(path.dirname(template)),
  436. trim_blocks=True, lstrip_blocks=True)
  437. template_name = path.basename(template)
  438. template = None
  439. try:
  440. template = env.get_template(template_name)
  441. except TemplateNotFound as e:
  442. print "Template %s not found." % template_name
  443. exit(1)
  444. lp_html = template.render(lp_dict=lp_dict)
  445. return str(BeautifulSoup(lp_html, 'html.parser')).strip()
  446. def main():
  447. parser = ArgumentParser()
  448. group = parser.add_mutually_exclusive_group()
  449. group.add_argument("-s", "--schedule", action="store_true",
  450. help="Generate LP schedule")
  451. group.add_argument("-sp", "--speakers", action="store_true",
  452. help="Generate LP speakers")
  453. parser.add_argument("--ical", type=int,
  454. help="Specify LP year as argument; "
  455. + "generates iCal")
  456. parser.add_argument("--version", action="version",
  457. version='lpschedule-generator version %s'
  458. % __version__,
  459. help="Show version number and exit.")
  460. parser.add_argument("lp_t",
  461. help="Path to the LP template.")
  462. parser.add_argument("lp_md",
  463. help="Path to the LP markdown.")
  464. args = parser.parse_args()
  465. lp_template = args.lp_t
  466. lp_md_content = read_file(path.abspath(args.lp_md))
  467. if path.exists(lp_template) and lp_md_content:
  468. if args.schedule:
  469. markdown = LPSMarkdown()
  470. elif args.speakers:
  471. markdown = LPSpeakersMarkdown()
  472. else:
  473. parser.error('No action requested, add -s or -sp switch')
  474. lp_dict = markdown(lp_md_content)
  475. lp_html = RenderHTML(lp_dict, lp_template)
  476. if args.ical and args.schedule:
  477. LPiCal(lp_dict, args.ical).to_ical()
  478. else:
  479. exit(1)
  480. if lp_html:
  481. # stdout lps html
  482. print lp_html
  483. else:
  484. print 'Error generating LP HTML.'
  485. if __name__ == "__main__":
  486. main()