Page MenuHomec4science

presentation_helper.py
No OneTemporary

File Metadata

Created
Sun, May 12, 15:56

presentation_helper.py

#!/usr/bin/env pyton
################################################################
from sympy import *
import numpy as np
import sympy
import IPython
from IPython.display import display, Math
from IPython.display import HTML
import os
import fnmatch
import shutil
import subprocess
import base64
import matplotlib.pyplot as plt
import matplotlib.figure
from IPython.core.interactiveshell import InteractiveShell
from wand.image import Image as WImage
from wand.color import Color
from io import BytesIO
from tempfile import NamedTemporaryFile
from tempfile import mkdtemp
from pygments import highlight
from pygments.lexers import CppLexer
from pygments.lexers import MatlabLexer
from pygments.formatters import HtmlFormatter
################################################################
def findImageFile(filename):
if os.path.isfile(filename):
return filename
tool_dir = os.path.dirname(__file__)
image_dir = os.path.join(tool_dir, '..', 'images')
pattern = os.path.basename(filename)
found = []
for root, dirnames, filenames in os.walk(image_dir):
for filename in fnmatch.filter(filenames, pattern):
found.append(os.path.join(root, filename))
if len(found) == 0:
raise Exception("file not found: {0}".format(filename))
if len(found) == 1:
return found[0]
raise Exception("Several files were found:\n{0}".format(found))
################################################################
def _print_latex_png(o):
o = o._repr_latex_()
dvioptions = None
exprbuffer = BytesIO()
# from IPython.core.debugger import Tracer
# Tracer()()
preview(o, output='png', viewer='BytesIO',
outputbuffer=exprbuffer, packages=('xcolor',),
dvioptions=dvioptions)
return exprbuffer.getvalue()
################################################################
def init_printing():
sympy.init_printing()
# f = InteractiveShell.instance().display_formatter
f = InteractiveShell.instance().display_formatter.formatters['image/png']
f.for_type(IPython.core.display.Math, func=_print_latex_png)
# print f.type_printers
################################################################
VIDEO_TAG = """<video controls>
<source src="data:video/x-m4v;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>"""
def anim_to_html(anim):
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.mp4') as f:
anim.save(f.name, fps=1./(anim._interval*1e-3),
extra_args=['-vcodec', 'libx264',
'-pix_fmt', 'yuv420p'])
video = open(f.name, "rb").read()
toto = video.encode("base64")
# print anim._encoded_video
return VIDEO_TAG.format(toto)
################################################################
def display_animation(anim):
plt.close(anim._fig)
return HTML(anim_to_html(anim))
################################################################
def display_images(objs, display_flag=True, **kwargs):
htmls = [display_image(o, display_flag=False, **kwargs)
for o in objs]
width = 100/len(htmls)
htmls_withdiv = ["" for h in htmls]
for i, h in enumerate(htmls):
htmls_withdiv[i] = '<div style="width:{0}%;'.format(width)
if i == 0:
htmls_withdiv[i] += 'float:left'
if i == len(htmls) - 1:
htmls_withdiv[i] += 'float:right'
htmls_withdiv[i] += '"> {0} </div>'.format(h)
html = '\n'.join(htmls_withdiv)
html = '<div>' + html + '</div>'
if display_flag:
display(HTML(html))
return html
def display_image(obj, resolution=150, width=None, height=None,
display_flag=True):
if type(obj) == matplotlib.figure.Figure:
png = InteractiveShell.instance().display_formatter.format(obj)
elif type(obj) == str:
try:
fname = findImageFile(obj)
except Exception as e:
return str(e)
img = WImage(filename=fname, resolution=resolution)
img.trim()
with Color('#FDFDFD') as white:
twenty_percent = int(65535 * 0.2)
img.transparent_color(white, alpha=0.0, fuzz=twenty_percent)
if (width is None) and (height is None):
display(img)
return img
png = InteractiveShell.instance().display_formatter.format(img)
else:
raise Exception('unknown obj type for an image')
size_tag = ""
if width is not None:
size_tag += 'width="{0}"'.format(width)
if height is not None:
size_tag += 'height="{0}"'.format(height)
data = png[0]['image/png']
html = r'<img src="data:image/png;base64,{0}" {1}/>'.format(
base64.b64encode(data), size_tag)
if display_flag:
display(HTML(html))
return html
################################################################
def makeAnimationFromImageFiles(filenames, framerate):
temp_dir = mkdtemp()
ext = None
for idx, f in enumerate(filenames):
_dir = os.path.dirname(f)
base = os.path.basename(f)
base, _ext = os.path.splitext(base)
ext = _ext
if ext == '.pdf':
_png = os.path.join(_dir, base+".png")
subprocess.call('convert {0} {1}'.format(f, _png), shell=True)
ext = ".png"
f = _png
new_name = "file{0:05d}{1}".format(idx, ext)
new_name = os.path.join(temp_dir, new_name)
# print base, ext
# print new_name
# print "copy {0} to {1}".format(f,new_name)
shutil.copyfile(f, new_name)
pattern = os.path.join(temp_dir, 'file%05d'+ext)
with NamedTemporaryFile(suffix='.mp4') as f:
cmd = ('ffmpeg -y -framerate {2} -i {0} -vf "scale=trunc(iw/2)*2:'
'trunc(ih/2)*2" -c:v libx264 -r 30 '
'-pix_fmt yuv420p {1}').format(pattern, f.name, framerate)
# print cmd
subprocess.call(cmd, shell=True)
video = open(f.name, "rb").read()
toto = video.encode("base64")
shutil.rmtree(temp_dir)
return HTML(VIDEO_TAG.format(toto))
################################################################
class Pigment(object):
def __init__(self, lexer=CppLexer(), formatter=HtmlFormatter(full=True),
includes=[], header="\n"):
self.lexer = lexer
self.formatter = formatter
self.header = header
self.includes = includes
self._insertIncludes()
def _insertIncludes(self):
if len(self.includes) > 0:
self.header = ('\n'.join(['#include <{0}>'.format(inc)
for inc in self.includes])
+ '\n' + self.header)
def appendToHeader(self, content):
self.header += content
def render(self, snippet, embed=False, header=""):
colored_snippet = highlight(snippet, self.lexer, self.formatter)
f = NamedTemporaryFile(suffix='.cc')
# name = f.name
# name = '/tmp/test.cc'
# f = open(name,'w')
if embed is True:
snippet = "int main(){\n" + snippet + "\n}\n"
snippet = self.header + '\n' + header + '\n' + snippet
f.write(snippet)
f.flush()
p = subprocess.Popen('g++ -I {1} -c {0}'.format(f.name, os.getcwd()),
shell=True, stderr=subprocess.PIPE)
p.wait()
ret = p.returncode
if ret != 0:
out = p.stderr.read()
# return colored_snippet.decode() + '\n' + out
print(out)
f.delete = False
raise Exception('compilation failed')
return colored_snippet
################################################################
def printMatlab(code):
html_snippet = highlight(
code, MatlabLexer(),
HtmlFormatter(full=True, style='colorful',
classprefix='matlab_'))
display(HTML(html_snippet))
# return html_snippet
################################################################
def displayClassDiagram(classes, resolution=150,
width=None, height=None):
with NamedTemporaryFile(suffix='.classes') as f:
f.write(classes)
f.flush()
with NamedTemporaryFile(suffix='.png') as fout:
# print 'class_dumper_dot.py --colaboration_no -c {0}
# -o {1} -f png'.format(f.name, fout.name)
# ret = subprocess.call('class_dumper_dot.py --colaboration_no
# -c {0} -o {1} -f png'.format(f.name, fout.name), shell=True)
img = WImage(filename=fout.name, resolution=resolution)
with Color('#FDFDFD') as white:
twenty_percent = int(65535 * 0.2)
img.transparent_color(white, alpha=0.0, fuzz=twenty_percent)
png = InteractiveShell.instance().display_formatter.format(img)
size_tag = ""
if width is not None:
size_tag += 'width="{0}"'.format(width)
if height is not None:
size_tag += 'height="{0}"'.format(height)
data = png[0]['image/png']
html = r'<img src="data:image/png;base64,{0}" {1}/>'.format(
base64.b64encode(data), size_tag)
display(HTML(html))
return html
################################################################
init_printing()

Event Timeline