diff --git a/Slides/presentation_helper.py b/Slides/presentation_helper.py index 6683708..d63970f 100644 --- a/Slides/presentation_helper.py +++ b/Slides/presentation_helper.py @@ -1,309 +1,311 @@ #!/usr/bin/env pyton ################################################################ from sympy import * import base64 import sympy import PyPDF2 import io import IPython from IPython.display import display from IPython.display import HTML import os import fnmatch import shutil import subprocess 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 ################################################################ 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 registerFormatter(_type, _format, formatter_functor): f = InteractiveShell.instance().display_formatter.formatters[_format] f.for_type(_type, func=formatter_functor) ################################################################ def init_printing(): sympy.init_printing() registerFormatter(IPython.core.display.Math, 'image/png', _print_latex_png) # f = InteractiveShell.instance().display_formatter.formatters['image/png'] # f.for_type(IPython.core.display.Math, func=_print_latex_png) ################################################################ VIDEO_TAG = """""" 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 = base64.b64encode(video).decode() # 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] = '
{0}
'.format(h) html = '\n'.join(htmls_withdiv) html = '
' + html + '
' 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'] data = base64.b64encode(data).decode('utf-8') html = r'You cannot see the image with this browser/mailer'.format( - base64.b64encode(data).decode('utf8'), size_tag) + html = (r'You cannot see the image with this browser/mailer'.format( + base64.b64encode(data).decode('utf8'), size_tag)) display(HTML(html)) return html ################################################################ def makeClassDiagramImage(classes, resolution=150, width=None, height=None): with NamedTemporaryFile(suffix='.classes', delete=False) as f: f.write(classes.encode('utf-8')) f.flush() - fout = os.path.splitext(f.name)[0] + '.png' + fout = os.path.splitext(f.name)[0] + '.svg' _command = ('class_dumper_dot.py --collaboration_no ' '-c {0} -o {1} -f svg'.format(f.name, fout)) # print(_command) - subprocess.call(_command, shell=True) + ret = subprocess.call(_command, shell=True) + if ret: + raise RuntimeError('could not launch commad:', _command) return fout ################################################################ def pdf_page_to_png(src_filename, pagenums=None, resolution=72): """ Returns specified PDF page as wand.image.Image png. :param PyPDF2.PdfFileReader src_pdf: PDF from which to take pages. :param int pagenum: Page number to take. :param int resolution: Resolution for resulting png in DPI. """ src_pdf = PyPDF2.PdfFileReader(file(src_filename, "rb")) # print dir(src_pdf) # print src_pdf.numPages if pagenums is None: pagenums = [0] res = [] for n in pagenums: dst_pdf = PyPDF2.PdfFileWriter() dst_pdf.addPage(src_pdf.getPage(n)) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = WImage(file=pdf_bytes, resolution=resolution) img.convert("png") res.append(img) return res ################################################################ init_printing()