lps_gen.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 {}'.format(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 {}'.format(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.items():
  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.items():
  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.items():
  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 _process_video(self, text):
  269. """Process the video text.
  270. If it's a link, just extract the link and return it.
  271. This method is meant to be called from the
  272. :py:method:`.paragraph` method.
  273. """
  274. soup = BeautifulSoup(text, 'html.parser')
  275. links = soup.find_all('a')
  276. if len(links) == 0:
  277. # no links found, so
  278. return text
  279. # link(s) found, return the first link's href.
  280. return links[0]['href']
  281. def link(self, link, title, text):
  282. # Here, we catch speaker names that have to be autolinked and
  283. # autolink them if there is an id available for the speaker.
  284. if not link:
  285. # We found a speaker that has to be autolinked.
  286. # Here, `text` is the speaker' name.
  287. id_ = self.get_uid(text)
  288. if id_:
  289. link = 'speakers.html#%s' % id_
  290. else:
  291. # Oh no, there is no id for this speaker.
  292. self.speakers_noids.append(text)
  293. # Don't linkify this speaker; they don't have an id.
  294. return text
  295. return super(LPSRenderer, self).link(link, title, text)
  296. def header(self, text, level, raw=None):
  297. global lps_dict
  298. if level == 2:
  299. # Add new day.
  300. lps_dict[text] = OrderedDict()
  301. self.last_day = text
  302. elif level == 3:
  303. # Add new timeslot
  304. lps_dict[self.last_day][text] = OrderedDict()
  305. self.last_time_slot = text
  306. # New timeslot, reset paragraphs processed and
  307. # last session.
  308. self.no_paragraph = 0
  309. self.last_session = None
  310. elif level == 4:
  311. # Add new session
  312. lps_dict[self.last_day][self.last_time_slot][
  313. text] = OrderedDict()
  314. self.last_session = text
  315. # We found a new session; set no of paragraphs processed
  316. # to 0.
  317. self.no_paragraph = 0
  318. return super(LPSRenderer, self).header(text, level, raw)
  319. def paragraph(self, text):
  320. global lps_dict
  321. self._check_session_title_exists()
  322. p = super(LPSRenderer, self).paragraph(text)
  323. if self.no_paragraph == 0:
  324. # Speaker
  325. speakers = text.split(', ')
  326. lps_dict[self.last_day][self.last_time_slot][
  327. self.last_session]['speakers'] = speakers
  328. self.no_paragraph = self.no_paragraph + 1
  329. elif self.no_paragraph == 1:
  330. # Room
  331. lps_dict[self.last_day][self.last_time_slot][
  332. self.last_session]['room'] = text
  333. self.no_paragraph = self.no_paragraph + 1
  334. elif self.no_paragraph == 2:
  335. lps_dict[self.last_day][self.last_time_slot][
  336. self.last_session]['video'] = self._process_video(text)
  337. # Initialize description
  338. lps_dict[self.last_day][self.last_time_slot][
  339. self.last_session]['desc'] = []
  340. self.no_paragraph = self.no_paragraph + 1
  341. elif self.no_paragraph > 1:
  342. lps_dict[self.last_day][self.last_time_slot][
  343. self.last_session]['desc'].append(text)
  344. return p
  345. class LPSpeakersRenderer(Renderer):
  346. """Helps convert Markdown version of LP speakers to a dictionary.
  347. """
  348. def __init__(self, **kwargs):
  349. super(LPSpeakersRenderer, self).__init__(**kwargs)
  350. global lpspeakers_dict
  351. lpspeakers_dict = OrderedDict()
  352. lpspeakers_dict['keynote-speakers'] = []
  353. lpspeakers_dict['speakers'] = []
  354. # Type of present speaker being processed; can either be
  355. # 'keynote-speakers' or 'speakers'.
  356. self.speaker_type = None
  357. # Maintain a dict of speakers and their IDs.
  358. self.speakers_ids = OrderedDict()
  359. def mk_uid(self, speaker_block):
  360. """Returns a unique id.
  361. """
  362. # 'John HÖcker, Onion Project' -> 'John HÖcker'
  363. speaker = unicode(speaker_block.split(', ')[0])
  364. # 'John HÖcker' -> 'John Hacker'
  365. ascii_speaker = unidecode(speaker)
  366. # 'John Hacker' -> 'hacker'
  367. id_ = ascii_speaker.split()[-1].lower()
  368. if id_ not in self.speakers_ids.values():
  369. self.speakers_ids[speaker]= id_
  370. return id_
  371. else:
  372. # 'John Hacker' -> 'john_hacker'
  373. id_ = '_'.join([s.lower() for s in ascii_speaker.split()])
  374. self.speakers_ids[speaker] = id_
  375. return id_
  376. def header(self, text, level, raw=None):
  377. global lpspeakers_dict
  378. if level == 1:
  379. self.speaker_type = 'keynote-speakers'
  380. lpspeakers_dict[self.speaker_type].append(OrderedDict())
  381. lpspeakers_dict[self.speaker_type][-1]['speaker'] = text
  382. lpspeakers_dict[self.speaker_type][-1][
  383. 'id'] = self.mk_uid(text)
  384. lpspeakers_dict[self.speaker_type][-1][
  385. 'bio'] = []
  386. elif level == 2:
  387. self.speaker_type = 'speakers'
  388. lpspeakers_dict[self.speaker_type].append(OrderedDict())
  389. lpspeakers_dict[self.speaker_type][
  390. -1]['speaker'] = text.split(', ')[0]
  391. lpspeakers_dict[self.speaker_type][
  392. -1]['id'] = self.mk_uid(text)
  393. lpspeakers_dict[self.speaker_type][
  394. -1]['bio'] = []
  395. return super(LPSpeakersRenderer, self).header(text, level, raw)
  396. def image(self, src, title, text):
  397. global lpspeakers_dict
  398. lpspeakers_dict[self.speaker_type][-1]['img_url'] = src
  399. lpspeakers_dict[self.speaker_type][-1]['img_alt'] = text
  400. return super(LPSpeakersRenderer, self).image(src, title, text)
  401. def paragraph(self, text):
  402. global lpspeakers_dict
  403. p = super(LPSpeakersRenderer, self).paragraph(text)
  404. if text.startswith('<img'):
  405. # ignore
  406. return p
  407. lpspeakers_dict[self.speaker_type][-1]['bio'].append(text)
  408. return p
  409. class LPSMarkdown(Markdown):
  410. """Converts MD LP schedule to a dictionary.
  411. Returns the Markdown version of LP schedule as a dictionary.
  412. """
  413. def __init__(self, inline=None, block=None, **kwargs):
  414. """
  415. Initialize with LPSRenderer as the renderer.
  416. """
  417. self.sessions_renderer = LPSRenderer()
  418. super(LPSMarkdown, self).__init__(
  419. renderer=self.sessions_renderer,
  420. inline=None, block=None,
  421. **kwargs)
  422. def parse(self, text):
  423. global lps_dict
  424. lps_dict = OrderedDict()
  425. html = super(LPSMarkdown, self).parse(text)
  426. # Write list of speakers with no ids to `speakers.noids`.
  427. json_write('speakers.noids',
  428. self.sessions_renderer.speakers_noids)
  429. return lps_dict
  430. class LPSpeakersMarkdown(Markdown):
  431. """Converts MD LP speakers to a dictionary.
  432. Returns the Markdown version of LP speakers as a dictionary.
  433. """
  434. def __init__(self, inline=None, block=None, **kwargs):
  435. """
  436. Initialize with LPSpeakersRenderer as the renderer.
  437. """
  438. self.speakers_renderer = LPSpeakersRenderer()
  439. super(LPSpeakersMarkdown, self).__init__(
  440. renderer=self.speakers_renderer,
  441. inline=None, block=None,
  442. **kwargs)
  443. def parse(self, text):
  444. global lpspeakers_dict
  445. html = super(LPSpeakersMarkdown, self).parse(text)
  446. # Write mapping of speakers and their ids to `speakers.ids`.
  447. json_write('speakers.ids', self.speakers_renderer.speakers_ids)
  448. return lpspeakers_dict
  449. def RenderHTML(lp_dict, template):
  450. """Renders LP schedule/speakers in HTML from a python dictionary.
  451. Returns the HTML as a string.
  452. """
  453. env = Environment(loader=FileSystemLoader(path.dirname(template)),
  454. trim_blocks=True, lstrip_blocks=True)
  455. template_name = path.basename(template)
  456. template = None
  457. try:
  458. template = env.get_template(template_name)
  459. except TemplateNotFound as e:
  460. print('Template {} not found.'.format(template_name))
  461. exit(1)
  462. lp_html = template.render(lp_dict=lp_dict)
  463. return str(BeautifulSoup(lp_html, 'html.parser')).strip()
  464. def main():
  465. parser = ArgumentParser()
  466. group = parser.add_mutually_exclusive_group()
  467. group.add_argument("-s", "--schedule", action="store_true",
  468. help="Generate LP schedule")
  469. group.add_argument("-sp", "--speakers", action="store_true",
  470. help="Generate LP speakers")
  471. parser.add_argument("--ical", type=int,
  472. help="Specify LP year as argument; "
  473. + "generates iCal")
  474. parser.add_argument("--version", action="version",
  475. version='lpschedule-generator version %s'
  476. % __version__,
  477. help="Show version number and exit.")
  478. parser.add_argument("lp_t",
  479. help="Path to the LP template.")
  480. parser.add_argument("lp_md",
  481. help="Path to the LP markdown.")
  482. args = parser.parse_args()
  483. lp_template = args.lp_t
  484. lp_md_content = read_file(path.abspath(args.lp_md))
  485. if path.exists(lp_template) and lp_md_content:
  486. if args.schedule:
  487. markdown = LPSMarkdown()
  488. elif args.speakers:
  489. markdown = LPSpeakersMarkdown()
  490. else:
  491. parser.error('No action requested, add -s or -sp switch')
  492. lp_dict = markdown(lp_md_content)
  493. lp_html = RenderHTML(lp_dict, lp_template)
  494. if args.ical and args.schedule:
  495. LPiCal(lp_dict, args.ical).to_ical()
  496. else:
  497. exit(1)
  498. if lp_html:
  499. # stdout lps html
  500. print(lp_html)
  501. else:
  502. print('Error generating LP HTML.')
  503. if __name__ == "__main__":
  504. main()