pinout.vvzero.com/markjaml.py

67 lines
2.0 KiB
Python
Raw Normal View History

import json
import re
import unicodedata
2016-09-14 01:27:55 +08:00
try:
import markdown
except ImportError:
2017-01-21 18:55:37 +08:00
exit("This script requires the Markdown module\nInstall with: sudo pip install Markdown")
2016-09-14 01:27:55 +08:00
try:
import yaml
except ImportError:
2017-01-21 18:55:37 +08:00
exit("This script requires the yaml module\nInstall with: sudo pip install PyYAML")
2016-09-14 01:27:55 +08:00
2015-11-18 21:52:15 +08:00
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicode(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub('[^\w\s-]', '-', value).strip().lower()
return re.sub('[-\s]+', '-', value)
2015-11-18 21:52:15 +08:00
def load(file):
2015-11-18 21:52:15 +08:00
'''
Loads and parses JSON-embedded Markdown file, chopping out and
parsing any JSON contained therein.
2015-11-18 21:52:15 +08:00
Returns an object that includes the JSON data, and the parsed HTML.
'''
markson = open(file).read()
2019-10-10 05:51:17 +08:00
markson = markson.replace('\r', '')
2020-08-22 22:19:45 +08:00
_data = re.search(re.compile(r'<!--(JSON:|\n---\n)(.*?)-->', re.DOTALL), markson)
2020-08-22 22:19:45 +08:00
_markdown = re.sub(re.compile(r'<!--(JSON:|\n---\n)(.*?)-->', re.DOTALL), '', markson)
2015-11-18 21:52:15 +08:00
_html = markdown.markdown(_markdown, extensions=['fenced_code'])
2015-11-18 21:52:15 +08:00
# Scan for the Title in the Markdown file, this is always assumed
# to be the first string starting with a single hash/pound ( # ) sign
_title = re.search(re.compile(r'^#[^\#](.*)$', re.MULTILINE), markson)
2019-10-10 05:51:17 +08:00
if _title is not None:
2015-11-18 21:52:15 +08:00
_title = _title.group(0).replace('#', '').strip()
2019-10-10 05:51:17 +08:00
if _data is not None:
2015-11-18 21:52:15 +08:00
_type = _data.group(0)[4:8].upper().strip()
2015-11-18 21:52:15 +08:00
if _type == 'JSON':
_data = re.search('\{(.*)\}', _data.group(0), re.DOTALL).group(0)
_data = json.loads(_data)
elif _type == '---':
_data = re.search('\n(.*)\n', _data.group(0), re.DOTALL).group(0)
_data = yaml.safe_load(_data)
2015-11-18 21:52:15 +08:00
else:
data = {}
2015-11-18 21:52:15 +08:00
_data['title'] = _title
2019-10-10 05:51:17 +08:00
elif _title is not None:
_data = {'title': _title}
2019-10-10 06:39:55 +08:00
return {'data': _data, 'html': _html}