anktui/preview.py

83 lines
2.6 KiB
Python

import imgkit
import sys
import os
from threading import Thread
from libsixel.encoder import Encoder, SIXEL_OPTFLAG_WIDTH, SIXEL_OPTFLAG_COLORS
from tempfile import NamedTemporaryFile
HTML_WIDTH = 720
def preview(html, width, height, img, htmlWidth=HTML_WIDTH):
options = {
'encoding': 'utf-8',
'width': htmlWidth,
'height': int(htmlWidth/width*height),
'quiet': None,
'enable-local-file-access': None
}
#with NamedTemporaryFile(suffix='.png') as img:
def render():
with NamedTemporaryFile(suffix='.html') as page:
page.write(bytes(html, encoding='utf-8'))
with open('test.html', 'w') as test:
test.write(html)
page.flush()
imgkit.from_file(page.name, img.name, options=options)
th = Thread(target=render)
th.start()
#render()
def update(width, img):
sys.stdout.write('\x1b[1;1H')
sys.stdout.flush()
encoder = Encoder()
encoder.setopt(SIXEL_OPTFLAG_WIDTH, str(width))
encoder.setopt(SIXEL_OPTFLAG_COLORS, '256')
encoder.encode(img.name)
def previewCard(template, style, content, width, height, img, htmlWidth=HTML_WIDTH, frontSide=None):
if frontSide:
template = template.replace('{{FrontSide}}', frontSide)
for field in content:
# conditional sections
formated = ''
i = 0
remove = False
while i < len(template):
section = template[i:i + len(field) + 5]
if section in ('{{#'+field+'}}', '{{^'+field+'}}'):
i += len(field) + 5
if (section[2] == '#' and not content[field]) or (section[2] == '^' and content[field]):
remove = True
if section == '{{/'+field+'}}':
i += len(field) + 5
if remove:
remove = False
if not remove and i < len(template):
formated += template[i]
i += 1;
template = formated.replace('{{'+field+'}}', content[field])
template = '<style>'+style+'</style>'+template
preview(TEMPLATE.replace('{{CONTENT}}', template)
.replace('{{WD}}', os.getcwd()),
width, height, img, htmlWidth)
TEMPLATE_FILE = 'template.html'
with open(TEMPLATE_FILE) as templateFile:
TEMPLATE = templateFile.read()
if __name__ == '__main__':
preview('<h1>Hello World!</h1>', 500, 500)
previewCard('<h1>{{Front}}</h1>',
'h1{color:cyan;}',
{
'Front': 'Hello World!',
'Back': 'From Python...'
},
500, 500)