iDie/csv2json.py

117 lines
4.3 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import csv
import json
import os
from glob import glob
from creole.rest_tools.clean_writer import rest2html
TITLE_PREFIX = "iDie ::"
sheet = csv.reader(open('slides.csv'))
keys = sheet.__next__()
# get_content will remove all files we use
# and in the end of the process, only orphans
# will remain
orphans = glob('slides/*.rst')
def get_content(slide, default):
if not slide: # Happens for home slide
slide = '_home'
filename = 'slides/{}.rst'.format(slide)
# Yes. This is a side effect. Sorry.
if filename in orphans:
orphans.remove(filename)
if not os.path.isfile(filename):
desc = default.strip()
# if desc:
# desc = "**תוכן זמני:** {}".format(desc)
open(filename, 'w').write(desc)
print('Created {}.'.format(filename))
return rest2html(open(filename).read())
def post_process(content):
"currently, only [עריכת-רשימות] is dealt with"
return content.replace('[עריכת-רשימות]',
"""<a class="notes-edit-button" title="עריכת הרשימות שלי" rel="modal:open" href="#notes-modal"><i class="fa fa-file-signature"></i></a>""")
def format_slide_param(key, value):
return format('data-{}="{}"'.format(
key.strip(), value.strip()))
def get_slide_params(d):
params = []
if d.get('real-id', '').strip():
params.append(format_slide_param('real-id', d['real-id']))
if d.get('real-title', '').strip():
params.append(format_slide_param('real-title', d['real-title']))
if d.get('theme', '').strip():
params.append(format_slide_param('theme', d['theme'].lower()))
if d.get('bg-image','').strip():
params.append(format_slide_param('background-image', d['bg-image']))
if d.get('bg-style','').strip().lower()=='tile':
params.append(format_slide_param('background-size', 'auto'))
params.append(format_slide_param('background-repeat', 'repeat'))
if d.get('bg-opacity','').strip():
params.append(format_slide_param('background-opacity', d['bg-opacity']))
if d.get('bg-position','').strip():
params.append(format_slide_param('background-position', d['bg-position']))
return ' '.join(params)
def main():
col_id = None
col = None
cols = []
real_title = ''
real_id = ''
for r in sheet:
d = dict(zip(keys,r))
if not d['slide'].strip(): # new column
if col is not None: # deal with previous col
col['has_slides'] = len(col['slides'])>0
cols.append(col)
col_id = d['column']
content = d['html'].strip() or get_content(col_id, d['description'])
col = {
'id': col_id,
'title': d['title'],
'params': get_slide_params(d),
'content': post_process(content),
'has_menu': False,
'slides': []}
else:
slide_id = '_'.join(filter(None, [col_id, d['slide']]))
headline = d['title']
if headline:
real_title = headline
real_id = slide_id
else:
headline = '{} (המשך)'.format(real_title)
if len(col['slides']):
col['slides'][-1]['next'] = slide_id
d['real-id'] = real_id;
d['real-title'] = real_title;
content = d['html'].strip() or get_content(slide_id, d['description'])
col['slides'].append({
'id': slide_id,
'title': d['title'],
'headline': headline,
'params': get_slide_params(d),
'has_menu': False,
'content': post_process(content)})
col['has_slides'] = len(col['slides'])>0
cols.append(col)
cols[0]['has_menu'] = True
cols[0]['menu'] = [{"id": c['id'], "title": c['title']} for c in cols[1:]]
json.dump({"title": cols[0]['title'], "columns": cols, "title_prefix": TITLE_PREFIX}, open('slides.json', 'w'), indent=4)
print('successfully wrote slides.json')
if orphans:
print('Note! The following rst files are not mentioned in the csv sheet (orphans):')
for f in sorted(orphans):
print(' {}'.format(f))
if __name__=='__main__':
main()