diff --git a/Slides/presentation_helper.py b/Slides/presentation_helper.py index c250b0a..7be27a3 100644 --- a/Slides/presentation_helper.py +++ b/Slides/presentation_helper.py @@ -1,339 +1,276 @@ #!/usr/bin/env pyton ################################################################ from sympy import * 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 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 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 = 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] = '
{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'] html = r''.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 - - snip = bytes(snippet, 'utf-8') - f.write(snip) - 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''.format( base64.b64encode(data), size_tag) display(HTML(html)) return html ################################################################ 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() diff --git a/scripts/pLatex b/scripts/pLatex index eb28d81..07fa094 100755 --- a/scripts/pLatex +++ b/scripts/pLatex @@ -1,39 +1,39 @@ #! /usr/bin/python3 import subprocess import os.path import argparse from PythonLatex.generate_latex import interpretPython ################################################################ parser = argparse.ArgumentParser(description='Python embedded in Latex tool') parser.add_argument('filename_in', type=str, help='The path of the file to parse') parser.add_argument('--reexec_flag', action='store_true', help='TODO') parser.add_argument('-g', '--generate_pdf', action='store_true', help='Ask to generate the pdf directly') parser.add_argument('-c', '--continue_flag', action='store_true', help='Ask to continue even after errors') args = parser.parse_args() filename_in = args.filename_in reexec_flag = args.reexec_flag _continue = args.continue_flag generate_pdf = args.generate_pdf basename, ext = os.path.splitext(filename_in) if not ext == '.ptex': raise Exception('invalid file extension: "{0}"'.format(ext)) filename_out = basename + '.tex' ################################################################ out = interpretPython(filename_in, _continue, reexec_flag) fout = open(filename_out, 'w') fout.write(out) fout.close() log = open('log.latex', 'w') if generate_pdf is True: ret = subprocess.call( 'pdflatex -interaction nonstopmode ' + filename_out, shell=True, stdout=log, stderr=log) if ret: - subprocess.call('pdflatex ' + filename_out, shell=True) + subprocess.call('rubber -d ' + filename_out, shell=True) ################################################################