lps_gen.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. self.cal.add('x-wr-calname', 'LibrePlanet %s' % self.lp_year)
  98. # RFC 2445 requires DTSTAMP to be in UTC. DTSTAMP is used in
  99. # VEVENT (Event object, see `add_event` method).
  100. self.dtstamp = vDatetime(datetime.now(pytz.utc))
  101. # used to generate uid for ical.
  102. self.ucounter = 0
  103. def gen_uid(self):
  104. """Returns an unique id.
  105. Used for Event object.
  106. """
  107. self.ucounter = self.ucounter + 1
  108. return '%s@LP%s@libreplanet.org' % (str(self.ucounter),
  109. self.lp_year)
  110. def get_timeslot(self, s):
  111. """Get start and end time for a timeslot.
  112. """
  113. timeslot = self.timeslot_re.search(s)
  114. if (not timeslot) or (len(timeslot.groups()) < 3):
  115. return None, None, None
  116. t_start = timeslot.group(1)
  117. t_end = timeslot.group(2)
  118. name = timeslot.group(3)
  119. return t_start, t_end, name
  120. def get_month_day(self, s):
  121. """Get month and day.
  122. """
  123. month_day = self.month_day_re.search(s)
  124. if (not month_day) or (len(month_day.groups()) < 2):
  125. return None, None
  126. month = month_day.group(1)
  127. day = month_day.group(2)
  128. return month, day
  129. def mk_datetime(self, month, day, time):
  130. """Returns datetime object (EST).
  131. """
  132. # Day %d
  133. # Month %B
  134. # Year %Y
  135. # Hour %H (24-hr)
  136. # Minute %M (zero padded)
  137. # Second %S (zero padded)
  138. datetime_fmt = '%d %B %Y %H:%M:%S'
  139. eastern = timezone('US/Eastern')
  140. hour = time.split(':')[0]
  141. minute = time.split(':')[1]
  142. datetime_str = '%s %s %s %s:%s:%s' % (day, month, self.lp_year,
  143. hour.zfill(2),
  144. minute.zfill(2),
  145. '00')
  146. dt_object = datetime.strptime(datetime_str, datetime_fmt)
  147. return vDatetime(eastern.localize(dt_object))
  148. def mk_attendee(self, speaker):
  149. """Make Attendee to be added to an Event object.
  150. See `add_event` method.
  151. """
  152. # Get rid of HTML (<a> element, etc) in `speaker`
  153. speaker = BeautifulSoup(speaker, 'html.parser').get_text()
  154. attendee = vCalAddress('invalid:nomail')
  155. attendee.params['cn'] = vText(speaker)
  156. attendee.params['ROLE'] = vText('REQ-PARTICIPANT')
  157. attendee.params['CUTYPE'] = vText('INDIVIDUAL')
  158. return attendee
  159. def add_event(self, month, day, t_start, t_end, t_name, session,
  160. session_info):
  161. """Adds event to calendar.
  162. """
  163. event = Event()
  164. event['uid'] = self.gen_uid()
  165. event['dtstamp'] = self.dtstamp
  166. event['class'] = vText('PUBLIC')
  167. event['status'] = vText('CONFIRMED')
  168. event['method'] = vText('PUBLISH')
  169. if session == 'st-from-ts':
  170. event['summary'] = t_name
  171. else:
  172. event['summary'] = session
  173. event['location'] = vText(session_info['room'])
  174. # Get rid of HTML in 'desc'
  175. desc = BeautifulSoup(' '.join(
  176. session_info['desc']).replace(
  177. '\n', ' '), 'html.parser').get_text()
  178. event['description'] = desc
  179. # Add speakers
  180. for speaker in session_info['speakers']:
  181. event.add('attendee', self.mk_attendee(speaker), encode=0)
  182. dt_start = self.mk_datetime(month, day, t_start)
  183. dt_end = self.mk_datetime(month, day, t_end)
  184. event['dtstart'] = dt_start
  185. event['dtend'] = dt_end
  186. # Add to calendar
  187. self.cal.add_component(event)
  188. return event
  189. def gen_ical(self):
  190. """Parse LP schedule dict and generate iCal Calendar object.
  191. """
  192. for day_str, timeslots in self.lps_dict.iteritems():
  193. month, day = self.get_month_day(day_str)
  194. if not month:
  195. # month, day not specified; cannot generate ical for
  196. # this day
  197. continue
  198. for timeslot_str, sessions in timeslots.iteritems():
  199. t_start, t_end, t_name = self.get_timeslot(timeslot_str)
  200. if not t_start:
  201. # timeslot not specified; cannot generate ical for
  202. # this timeslot
  203. continue
  204. for session, session_info in sessions.iteritems():
  205. self.add_event(month, day, t_start, t_end, t_name,
  206. session, session_info)
  207. return self.cal.to_ical()
  208. def to_ical(self):
  209. """Writes iCal to disk.
  210. """
  211. filename = 'lp%s-schedule.ics' % self.lp_year
  212. write_file(filename, self.gen_ical())
  213. return filename
  214. class LPSRenderer(Renderer):
  215. """Helps convert Markdown version of LP schedule to a dictionary.
  216. """
  217. def __init__(self, **kwargs):
  218. super(LPSRenderer, self).__init__(**kwargs)
  219. self.last_day = None
  220. self.last_time_slot = None
  221. self.last_session = None
  222. # Denotes the no. of the paragraph under a session; this
  223. # information will be helpful in identifying the "speaker",
  224. # "room" and session "description".
  225. self.no_paragraph = None
  226. # Contains a list of speakers' names which are marked up for
  227. # auto-linking[1], but don't have an id to link to.
  228. #
  229. # [1]: Markup for auto-linking speakers is [John Hacker]().
  230. self.speakers_noids = []
  231. # If it is 'False', then the 'speaker.ids' file was not found;
  232. # otherwise it is an OrderedDict containing the mapping of
  233. # speakers and their corresponding id.
  234. self.speakers_ids = json_read('speakers.ids')
  235. def get_uid(self, speaker):
  236. """Generate unique id for `speaker`.
  237. Returns unique id for `speaker` if it exists; `False` otherwise.
  238. """
  239. if not self.speakers_ids:
  240. # There is no speakers_ids OrderedDict available.
  241. return False
  242. speaker = unicode(speaker)
  243. if speaker in self.speakers_ids.keys():
  244. return self.speakers_ids[speaker]
  245. else:
  246. # speaker not found in speakers_ids OrderedDict.
  247. return False
  248. def _check_session_title_exists(self):
  249. """Checks if :py:attr:`.last_session` is set.
  250. If :py:attr:`.last_session` is not set and first paragraph is
  251. encountered, then it is assumed that the current timeslot is in
  252. the following format::
  253. ### 9:00 - 10:45: Opening Keynote - Beyond unfree...
  254. [Cory Doctorow][doctorow]
  255. Room 32-123
  256. Software has eaten the world...
  257. This method is meant to be called from the
  258. :py:method:`.paragraph` method.
  259. """
  260. if not self.last_session and self.no_paragraph == 0:
  261. # Current timeslot has only one session and there
  262. # no session title.
  263. #
  264. # st-from-ts -> session title from time slot.
  265. lps_dict[self.last_day][self.last_time_slot][
  266. 'st-from-ts'] = OrderedDict()
  267. self.last_session = 'st-from-ts'
  268. def link(self, link, title, text):
  269. # Here, we catch speaker names that have to be autolinked and
  270. # autolink them if there is an id available for the speaker.
  271. if not link:
  272. # We found a speaker that has to be autolinked.
  273. # Here, `text` is the speaker' name.
  274. id_ = self.get_uid(text)
  275. if id_:
  276. link = 'speakers.html#%s' % id_
  277. else:
  278. # Oh no, there is no id for this speaker.
  279. self.speakers_noids.append(text)
  280. # Don't linkify this speaker; they don't have an id.
  281. return text
  282. return super(LPSRenderer, self).link(link, title, text)
  283. def header(self, text, level, raw=None):
  284. global lps_dict
  285. if level == 2:
  286. # Add new day.
  287. lps_dict[text] = OrderedDict()
  288. self.last_day = text
  289. elif level == 3:
  290. # Add new timeslot
  291. lps_dict[self.last_day][text] = OrderedDict()
  292. self.last_time_slot = text
  293. # New timeslot, reset paragraphs processed and
  294. # last session.
  295. self.no_paragraph = 0
  296. self.last_session = None
  297. elif level == 4:
  298. # Add new session
  299. lps_dict[self.last_day][self.last_time_slot][
  300. text] = OrderedDict()
  301. self.last_session = text
  302. # We found a new session; set no of paragraphs processed
  303. # to 0.
  304. self.no_paragraph = 0
  305. return super(LPSRenderer, self).header(text, level, raw)
  306. def paragraph(self, text):
  307. global lps_dict
  308. self._check_session_title_exists()
  309. p = super(LPSRenderer, self).paragraph(text)
  310. if self.no_paragraph == 0:
  311. # Speaker
  312. speakers = text.split(', ')
  313. lps_dict[self.last_day][self.last_time_slot][
  314. self.last_session]['speakers'] = speakers
  315. self.no_paragraph = self.no_paragraph + 1
  316. elif self.no_paragraph == 1:
  317. # Room
  318. lps_dict[self.last_day][self.last_time_slot][
  319. self.last_session]['room'] = text
  320. # Initialize description
  321. lps_dict[self.last_day][self.last_time_slot][
  322. self.last_session]['desc'] = []
  323. self.no_paragraph = self.no_paragraph + 1
  324. elif self.no_paragraph > 1:
  325. lps_dict[self.last_day][self.last_time_slot][
  326. self.last_session]['desc'].append(text)
  327. return p
  328. class LPSpeakersRenderer(Renderer):
  329. """Helps convert Markdown version of LP speakers to a dictionary.
  330. """
  331. def __init__(self, **kwargs):
  332. super(LPSpeakersRenderer, self).__init__(**kwargs)
  333. global lpspeakers_dict
  334. lpspeakers_dict = OrderedDict()
  335. lpspeakers_dict['keynote-speakers'] = []
  336. lpspeakers_dict['speakers'] = []
  337. # Type of present speaker being processed; can either be
  338. # 'keynote-speakers' or 'speakers'.
  339. self.speaker_type = None
  340. # Maintain a dict of speakers and their IDs.
  341. self.speakers_ids = OrderedDict()
  342. def mk_uid(self, speaker_block):
  343. """Returns a unique id.
  344. """
  345. # 'John HÖcker, Onion Project' -> 'John HÖcker'
  346. speaker = unicode(speaker_block.split(', ')[0])
  347. # 'John HÖcker' -> 'John Hacker'
  348. ascii_speaker = unidecode(speaker)
  349. # 'John Hacker' -> 'hacker'
  350. id_ = ascii_speaker.split()[-1].lower()
  351. if id_ not in self.speakers_ids.values():
  352. self.speakers_ids[speaker]= id_
  353. return id_
  354. else:
  355. # 'John Hacker' -> 'john_hacker'
  356. id_ = '_'.join([s.lower() for s in ascii_speaker.split()])
  357. self.speakers_ids[speaker] = id_
  358. return id_
  359. def header(self, text, level, raw=None):
  360. global lpspeakers_dict
  361. if level == 1:
  362. self.speaker_type = 'keynote-speakers'
  363. lpspeakers_dict[self.speaker_type].append(OrderedDict())
  364. lpspeakers_dict[self.speaker_type][-1]['speaker'] = text
  365. lpspeakers_dict[self.speaker_type][-1][
  366. 'id'] = self.mk_uid(text)
  367. lpspeakers_dict[self.speaker_type][-1][
  368. 'bio'] = []
  369. elif level == 2:
  370. self.speaker_type = 'speakers'
  371. lpspeakers_dict[self.speaker_type].append(OrderedDict())
  372. lpspeakers_dict[self.speaker_type][
  373. -1]['speaker'] = text.split(', ')[0]
  374. lpspeakers_dict[self.speaker_type][
  375. -1]['id'] = self.mk_uid(text)
  376. lpspeakers_dict[self.speaker_type][
  377. -1]['bio'] = []
  378. return super(LPSpeakersRenderer, self).header(text, level, raw)
  379. def image(self, src, title, text):
  380. global lpspeakers_dict
  381. lpspeakers_dict[self.speaker_type][-1]['img_url'] = src
  382. lpspeakers_dict[self.speaker_type][-1]['img_alt'] = text
  383. return super(LPSpeakersRenderer, self).image(src, title, text)
  384. def paragraph(self, text):
  385. global lpspeakers_dict
  386. p = super(LPSpeakersRenderer, self).paragraph(text)
  387. if text.startswith('<img'):
  388. # ignore
  389. return p
  390. lpspeakers_dict[self.speaker_type][-1]['bio'].append(text)
  391. return p
  392. class LPSMarkdown(Markdown):
  393. """Converts MD LP schedule to a dictionary.
  394. Returns the Markdown version of LP schedule as a dictionary.
  395. """
  396. def __init__(self, inline=None, block=None, **kwargs):
  397. """
  398. Initialize with LPSRenderer as the renderer.
  399. """
  400. self.sessions_renderer = LPSRenderer()
  401. super(LPSMarkdown, self).__init__(
  402. renderer=self.sessions_renderer,
  403. inline=None, block=None,
  404. **kwargs)
  405. def parse(self, text):
  406. global lps_dict
  407. lps_dict = OrderedDict()
  408. html = super(LPSMarkdown, self).parse(text)
  409. # Write list of speakers with no ids to `speakers.noids`.
  410. json_write('speakers.noids',
  411. self.sessions_renderer.speakers_noids)
  412. return lps_dict
  413. class LPSpeakersMarkdown(Markdown):
  414. """Converts MD LP speakers to a dictionary.
  415. Returns the Markdown version of LP speakers as a dictionary.
  416. """
  417. def __init__(self, inline=None, block=None, **kwargs):
  418. """
  419. Initialize with LPSpeakersRenderer as the renderer.
  420. """
  421. self.speakers_renderer = LPSpeakersRenderer()
  422. super(LPSpeakersMarkdown, self).__init__(
  423. renderer=self.speakers_renderer,
  424. inline=None, block=None,
  425. **kwargs)
  426. def parse(self, text):
  427. global lpspeakers_dict
  428. html = super(LPSpeakersMarkdown, self).parse(text)
  429. # Write mapping of speakers and their ids to `speakers.ids`.
  430. json_write('speakers.ids', self.speakers_renderer.speakers_ids)
  431. return lpspeakers_dict
  432. def RenderHTML(lp_dict, template):
  433. """Renders LP schedule/speakers in HTML from a python dictionary.
  434. Returns the HTML as a string.
  435. """
  436. env = Environment(loader=FileSystemLoader(path.dirname(template)),
  437. trim_blocks=True, lstrip_blocks=True)
  438. template_name = path.basename(template)
  439. template = None
  440. try:
  441. template = env.get_template(template_name)
  442. except TemplateNotFound as e:
  443. print "Template %s not found." % template_name
  444. exit(1)
  445. lp_html = template.render(lp_dict=lp_dict)
  446. return str(BeautifulSoup(lp_html, 'html.parser')).strip()
  447. def main():
  448. parser = ArgumentParser()
  449. group = parser.add_mutually_exclusive_group()
  450. group.add_argument("-s", "--schedule", action="store_true",
  451. help="Generate LP schedule")
  452. group.add_argument("-sp", "--speakers", action="store_true",
  453. help="Generate LP speakers")
  454. parser.add_argument("--ical", type=int,
  455. help="Specify LP year as argument; "
  456. + "generates iCal")
  457. parser.add_argument("--version", action="version",
  458. version='lpschedule-generator version %s'
  459. % __version__,
  460. help="Show version number and exit.")
  461. parser.add_argument("lp_t",
  462. help="Path to the LP template.")
  463. parser.add_argument("lp_md",
  464. help="Path to the LP markdown.")
  465. args = parser.parse_args()
  466. lp_template = args.lp_t
  467. lp_md_content = read_file(path.abspath(args.lp_md))
  468. if path.exists(lp_template) and lp_md_content:
  469. if args.schedule:
  470. markdown = LPSMarkdown()
  471. elif args.speakers:
  472. markdown = LPSpeakersMarkdown()
  473. else:
  474. parser.error('No action requested, add -s or -sp switch')
  475. lp_dict = markdown(lp_md_content)
  476. lp_html = RenderHTML(lp_dict, lp_template)
  477. if args.ical and args.schedule:
  478. LPiCal(lp_dict, args.ical).to_ical()
  479. else:
  480. exit(1)
  481. if lp_html:
  482. # stdout lps html
  483. print lp_html
  484. else:
  485. print 'Error generating LP HTML.'
  486. if __name__ == "__main__":
  487. main()