コード例 #1
0
ファイル: core.py プロジェクト: Silmathoron/beampy
    def __init__(self, title=None, **kwargs):

        # Add a slide to the global counter
        if 'slide' in document._global_counter:
            document._global_counter['slide'] += 1
        else:
            document._global_counter['slide'] = 0
        # Init group counter
        document._global_counter['group'] = 0

        # check args from THEME
        self.args = check_function_args(slide, kwargs)

        # The id for this slide
        self.id = gcs()
        self.slide_num = document._global_counter['slide']

        # Change from dict to class
        self.tmpout = ''
        self.contents = {}
        self.element_keys = []
        self.cpt_anim = 0
        self.num = document._global_counter['slide']+1
        self.title = title
        self.curwidth = document._width
        self.num_layers = 0 # Store the number of layers in this slide

        # Store all outputs
        self.svgout = []
        self.svgdefout = []  # Store module definition for slide
        self.htmlout = {}  # Html is a dict, each key dict is a layer htmlout[0] = [html, html, html] etc...
        self.scriptout = []
        self.animout = []
        self.svgheader = ''
        self.svgfooter = '\n</svg>\n'
        self.svglayers = {}  # Store slide final svg (without svg defs stored in self.svgdefout) for the given layer

        # Do we need to render the THEME layout on this slide
        self.render_layout = True

        # Add the slide to the document contents list
        document._slides[self.id] = self

        # Manage groups inside one slide the lower level of group is 0 and correspond
        # to the main slide
        self.groupsid = {}
        self.cur_group_level = -1
        g0 = group(x=0, y=0, width=document._width, height=document._height)
        self.groupsid[0] = [g0.id]  # store groups id objects in this list

        if title is not None:
            from beampy.modules.title import title as bptitle
            self.title_element = bptitle(title)
            self.ytop = float(convert_unit(self.title.reserved_y))
        else:
            self.ytop = 0
            self.title_element = None

        # Add ytop to the slide main group
        g0.yoffset = self.ytop
コード例 #2
0
ファイル: core.py プロジェクト: hchauvet/beampy
    def __init__(self, title= None, **kwargs):

        #Add a slide to the global counter
        if 'slide' in document._global_counter:
            document._global_counter['slide'] += 1
        else:
            document._global_counter['slide'] = 0
        #Init group counter
        document._global_counter['group'] = 0

        #check args from THEME
        self.args = check_function_args(slide, kwargs)

        out = {'title':title,
               'contents': {},
               'num':document._global_counter['slide']+1,
               'groups': [],
               "args": self.args,
               'htmlout': '', #store rendered htmlelements inside the slide
               'animout': [], #store svg rendered part of animatesvg
               'scriptout': '', #store javascript defined in element['script']
               'cpt_anim': 0,
               'element_keys': [] #list to store elements id in order
               }

        #The id for this slide
        self.id = gcs()


        #Change from dict to class
        self.tmpout = out
        self.contents = out['contents']
        self.element_keys = out['element_keys']
        self.cpt_anim = 0
        self.num = out['num']
        self.title = title

        #Store all outputs
        self.svgout = []
        self.htmlout = []
        self.scriptout = []
        self.animout = []
        self.svgheader = ''
        self.svgfooter = '\n</svg>\n'

        self.cpt_anim = 0
        self.groups = []

        #Add the slide to the document contents list
        document._contents[self.id] = out
        document._slides[self.id] = self

        if title!= None:
            from beampy.modules.title import title as bptitle
            bptitle( title )
            self.ytop = float(convert_unit(self.title.reserved_y))
        else:
            self.ytop = 0
コード例 #3
0
def video(videofile, **kwargs):
    """
    Add video in webm/ogg/mp4 format

    arguments
    ---------

    width = None -> document._width
    heigh = None -> document._height

    x ['center']: x position
    y ['auto']: y position

    autoplay [False]: To launch video when slide appears

    control [True]: Display video control bar

    still_image_time [0]: extract the still image for pdf export at the given still_image_time in second
    """

    #Check function args
    args = check_function_args(video, kwargs)

    #if no width is given get the default width
    if args['width'] == None:
        args['width'] = str(document._width)

    #check extension
    ext = None
    if '.webm' in videofile.lower():
        ext = 'webm'
    elif '.ogg' in videofile.lower():
        ext = 'ogg'
    elif '.mp4' in videofile.lower():
        ext = 'mp4'
    else:
        print('Video need to be in webm/ogg/mp4(h.264) format!')

    if ext != None:
        args['ext'] = ext
        args['filename'] = videofile

        #Add video to the document type_nohtml used to remplace video by svg still image when not exported to HTML5
        videout = {
            'type': 'html',
            'type_nohtml': 'svg',
            'content': '',
            'args': args,
            "render": render_video,
            'filename': videofile
        }

        return add_to_slide(videout,
                            x=args['x'],
                            y=args['y'],
                            width=args['width'],
                            height=None)
コード例 #4
0
def animatesvg(files_folder, **kwargs):
    """
        Function to create svg animation from a folder containing svg files

        - files_folder: Folder containing svg like "./my_folder/"

        - x['center']: x coordinate of the image
                       'center': center image relative to document._width
                       '+1cm": place image relative to previous element

        - y['auto']: y coordinate of the image
                     'auto': distribute all slide element on document._height
                     'center': center image relative to document._height (ignore other slide elements)
                     '+3cm': place image relative to previous element

        - start[0]: svg image number to start the sequence
        - end['end']: svg image number to stop the sequence
        - width[None]: Width of the figure (None = slide width)
        - fps[25]: animation framerate
        - autoplay[False]: autoplay animation when slide is displayed

    """

    #Check input args for this module
    args = check_function_args(animatesvg, kwargs)

    if args['width'] == None:
        args['width'] = str(document._width)

    #Read all svg files
    svg_files = glob.glob(files_folder + '*.svg')

    #Need to sort using the first digits finded in the name
    svg_files = sorted(svg_files,
                       key=lambda x: int(''.join(re.findall(r'\d+', x))))

    #check how many images we wants
    if args['end'] == 'end':
        args['end'] = len(svg_files)

    svg_files = svg_files[args['start']:args['end']]

    svgcontent = []
    for svgf in svg_files:
        with open(svgf, 'r') as f:
            svgcontent += [f.read()]

    animout = {
        'type': 'animatesvg',
        'content': svgcontent,
        'args': args,
        "render": render_animatesvg
    }

    return add_to_slide(animout, args['x'], args['y'], args['width'], None)
コード例 #5
0
ファイル: animatesvg.py プロジェクト: frankier/beampy
def animatesvg(files_folder, **kwargs):
    """
        Function to create svg animation from a folder containing svg files

        - files_folder: Folder containing svg like "./my_folder/"

        - x['center']: x coordinate of the image
                       'center': center image relative to document._width
                       '+1cm": place image relative to previous element

        - y['auto']: y coordinate of the image
                     'auto': distribute all slide element on document._height
                     'center': center image relative to document._height (ignore other slide elements)
                     '+3cm': place image relative to previous element

        - start[0]: svg image number to start the sequence
        - end['end']: svg image number to stop the sequence
        - width[None]: Width of the figure (None = slide width)
        - fps[25]: animation framerate
        - autoplay[False]: autoplay animation when slide is displayed

    """

    #Check input args for this module
    args = check_function_args(animatesvg, kwargs)

    if args['width'] == None:
        args['width'] = str(document._width)

    #Read all svg files
    svg_files = glob.glob(files_folder+'*.svg')

    #Need to sort using the first digits finded in the name
    svg_files = sorted(svg_files, key=lambda x: int(''.join(re.findall(r'\d+', x))))

    #check how many images we wants
    if args['end'] == 'end':
        args['end'] = len(svg_files)

    svg_files = svg_files[args['start']:args['end']]

    svgcontent = []
    for svgf in svg_files:
        with open(svgf,'r') as f:
            svgcontent += [f.read()]

    animout = {'type': 'animatesvg', 'content': svgcontent, 'args': args,
               "render": render_animatesvg }

    return add_to_slide( animout, args['x'], args['y'], args['width'], None)
コード例 #6
0
def itemize(items_list, **kwargs):
    '''

	Generates a list or an enumeration.

	See THEME['itemize'] for option

	TODO: ADD doc for function arguments
	'''

    args = check_function_args(itemize, kwargs)
    number = 1

    if args['width'] != None:
        in_width = float(convert_unit(args['width'])) - float(
            convert_unit(args['item_indent']))
    else:
        in_width = float(document._width) - float(
            convert_unit(args['item_indent']))

    with group(width=args['width'], x=args['x'], y=args['y']):

        for i, the_item in enumerate(items_list):

            if args['item_style'] == 'bullet':
                item_char = r'$\bullet$'

            elif args['item_style'] == 'number':
                item_char = str(number) + r'.'
                number += 1

            else:
                item_char = args['item_style']

            # Add color

            item_char = color_text(item_char, args['item_color'])
            the_item = color_text(the_item, args['text_color'])

            if i == 0:
                text(item_char + r' ' + the_item,
                     x=args['item_indent'],
                     y=0,
                     width=in_width)
            else:
                text(item_char + r' ' + the_item,
                     x=args['item_indent'],
                     y=args['item_spacing'],
                     width=in_width)
コード例 #7
0
ファイル: video.py プロジェクト: frankier/beampy
def video(videofile, **kwargs):
    """
    Add video in webm/ogg/mp4 format

    arguments
    ---------

    width = None -> document._width
    heigh = None -> document._height

    x ['center']: x position
    y ['auto']: y position

    autoplay [False]: To launch video when slide appears

    control [True]: Display video control bar

    still_image_time [0]: extract the still image for pdf export at the given still_image_time in second
    """

    #Check function args
    args = check_function_args(video, kwargs)

    #if no width is given get the default width
    if args['width'] == None:
        args['width'] = str(document._width)

    #check extension
    ext = None
    if '.webm' in videofile.lower():
        ext = 'webm'
    elif '.ogg' in videofile.lower():
        ext = 'ogg'
    elif '.mp4' in videofile.lower():
        ext = 'mp4'
    else:
        print('Video need to be in webm/ogg/mp4(h.264) format!')

    if ext != None:
        args['ext'] = ext
        args['filename'] = videofile

        #Add video to the document type_nohtml used to remplace video by svg still image when not exported to HTML5
        videout = {'type': 'html', 'type_nohtml': 'svg', 'content': '', 'args': args,
                   "render": render_video,
                   'filename': videofile}

        return add_to_slide( videout, x=args['x'], y=args['y'], width=args['width'], height=None  )
コード例 #8
0
ファイル: biblio.py プロジェクト: MycrofD/beampy
def cite( list_authors, **kwargs):
    """
    function to write citation on slide

    Arguments
    ---------

    list_authors : python list of authors
    """

    citestr = '[' + ', '.join(list_authors) + ']'

    #Check arguments
    args = check_function_args(cite, kwargs)

    text( citestr, **args)
コード例 #9
0
ファイル: itemize.py プロジェクト: frankier/beampy
def itemize( items_list, **kwargs):

	'''

	Generates a list or an enumeration.

	See THEME['itemize'] for option

	TODO: ADD doc for function arguments
	'''

	args = check_function_args(itemize, kwargs)
	number = 1

	if args['width']!=None:
		in_width = float(convert_unit(args['width'])) - float(convert_unit(args['item_indent']))
	else:
		in_width = float(document._width) - float(convert_unit(args['item_indent']))

	with group(width=args['width'], x=args['x'], y=args['y']):

		for i, the_item in enumerate(items_list) :

			if args['item_style'] == 'bullet' :
				item_char = r'$\bullet$'

			elif args['item_style'] == 'number' :
				item_char = str(number) + r'.'
				number += 1

			else :
				item_char = item_style

			# Add color

			item_char = color_text( item_char, args['item_color'] )
			the_item = color_text( the_item, args['text_color'] )

			if i == 0 :
				text( item_char + r' ' + the_item, x = args['item_indent'],
				y = 0, width=in_width )
			else:
				text( item_char + r' ' + the_item, x = args['item_indent'],
				y = args['item_spacing'], width=in_width )
コード例 #10
0
ファイル: title.py プロジェクト: frankier/beampy
def title( title_text , **kwargs):
    """
        Add a title to a slide
    """

    #Check function arguments from THEME
    args = check_function_args(title, kwargs)
    #Add text arguments because we use the text render
    args = inherit_function_args('text', args)

    if args['width'] == None:
        args['width'] = document._width
    
    titleout = {'type': 'svg',
                'content':title_text,
                "args":args,
                "render": render_text }

    document._contents[gcs()]['title']=titleout
    out = add_to_slide(titleout, args['x'], args['y'], width=args['width'], height=None)
コード例 #11
0
ファイル: biblio.py プロジェクト: ncdingari/beampy
def cite( list_authors, **kwargs):
    """
    function to write citation on slide

    Arguments
    ---------

    list_authors : python list of authors
    """
    
    # in case there is only one citation
    if type(list_authors) == type( 'this_is_a_string' ) :
        list_authors = [ list_authors ]

    citestr = '[' + ', '.join(list_authors) + ']'

    #Check arguments
    args = check_function_args(cite, kwargs)

    text( citestr, **args)
コード例 #12
0
ファイル: text.py プロジェクト: frankier/beampy
def text(textin, **kwargs):
    """
        Function to add a text to the current slide

        Options
        -------

        - x['center']: x coordinate of the image
                       'center': center image relative to document._width
                       '+1cm": place image relative to previous element

        - y['auto']: y coordinate of the image
                     'auto': distribute all slide element on document._height
                     'center': center image relative to document._height (ignore other slide elements)
                     '+3cm': place image relative to previous element

        Exemples
        --------

        text('this is my text', '20', '20')
    """

    args = check_function_args(text, kwargs)

    #Check width
    if args['width'] == None:
        args['width'] = document._width

    textout = {
        'type': 'text',
        'content': textin,
        'args': args,
        "render": render_text
    }

    #Add text to the document
    return add_to_slide(textout,
                        x=args['x'],
                        y=args['y'],
                        width=args['width'],
                        height=None)
コード例 #13
0
ファイル: tikz.py プロジェクト: frankier/beampy
def tikz(tikscommands, **kwargs):
    """
        Function to render tikz commands to svg

        options:
        --------
        - tikz_header: allow to add extra tikslibraries and style, everything that
                       is included befor \begin{document}

                       exp:
                       tikz_header = " \usetikzlibrary{shapes.geometric}
                                     % Vector Styles
                                     \tikzstyle{load}   = [ultra thick,-latex]
                                     \tikzstyle{stress} = [-latex]
                                     \tikzstyle{dim}    = [latex-latex]
                                     \tikzstyle{axis}   = [-latex,black!55]
                                     "
        - tex_packages: Add extra \usepackages in tex document.
                        Need to be a list of string

                        expl:
                        tex_packages = ['xolors','tikz-3dplot']

        - figure_options: options for \begin{tikzfigure}[options]

        - figure_anchor ['top_left']: set the anchor of tikz output svg 'top_left', 'bottom_left', 'top_right', bottom_right'
    """

    args = check_function_args(tikz, kwargs)

    textout = {'type': 'tikz', 'content': tikscommands,
               'args': args,
               "render": render_tikz}


    return add_to_slide( textout, args['x'], args['y'], None, None )
コード例 #14
0
    def __init__(self, title=None, **kwargs):

        #Add a slide to the global counter
        if 'slide' in document._global_counter:
            document._global_counter['slide'] += 1
        else:
            document._global_counter['slide'] = 0
        #Init group counter
        document._global_counter['group'] = 0

        #check args from THEME
        self.args = check_function_args(slide, kwargs)

        out = {
            'title': title,
            'contents': {},
            'num': document._global_counter['slide'] + 1,
            'groups': [],
            "args": self.args,
            'htmlout': '',  #store rendered htmlelements inside the slide
            'animout': [],  #store svg rendered part of animatesvg
            'scriptout': '',  #store javascript defined in element['script']
            'cpt_anim': 0,
            'element_keys': []  #list to store elements id in order
        }

        #The id for this slide
        self.id = gcs()
        self.slide_num = document._global_counter['slide']

        #Change from dict to class
        self.tmpout = out
        self.contents = out['contents']
        self.element_keys = out['element_keys']
        self.cpt_anim = 0
        self.num = out['num']
        self.title = title

        #Store all outputs
        self.svgout = []
        self.htmlout = []
        self.scriptout = []
        self.animout = []
        self.svgheader = ''
        self.svgfooter = '\n</svg>\n'

        #Do we need to render the THEME layout on this slide
        self.render_layout = True

        #If we want to add background slide decodaration like header-bar or footer informations
        self.cpt_anim = 0
        self.groups = []

        #Add the slide to the document contents list
        document._contents[self.id] = out
        document._slides[self.id] = self

        if title != None:
            from beampy.modules.title import title as bptitle
            bptitle(title)
            self.ytop = float(convert_unit(self.title.reserved_y))
        else:
            self.ytop = 0
コード例 #15
0
def figure(filename, ext=None, **kwargs):
    """
        Add figure to current slide
        Accepted format: [svg, png, jpeg, bokeh figure]

        - x['center']: x coordinate of the image
                       'center': center image relative to document._width
                       '+1cm": place image relative to previous element

        - y['auto']: y coordinate of the image
                     'auto': distribute all slide element on document._height
                     'center': center image relative to document._height (ignore other slide elements)
                     '+3cm': place image relative to previous element
https://duckduckgo.com/?q=feder+inra&t=ffab
        - height[None]: Image heigt

        - ext[None]: Image format, if None, format is guessed from filename.

    """

    args = check_function_args(figure, kwargs)

    #Check if the given filename is a string
    if type(filename) == type(''):
        #Check extension
        if ext == None:
            if '.svg' in filename.lower():
                ext = 'svg'

            if '.png' in filename.lower():
                ext = 'png'

            if ( '.jpeg' in filename.lower() ) or ( '.jpg' in filename.lower() ):
                ext = 'jpeg'

            if '.pdf' in filename.lower():
                ext = 'pdf'

    else:
        if "bokeh" in str(type(filename)):
            ext = 'bokeh'

    ######################################


    if ext == None:
        print("figure format can't be guessed from file name")
        sys.exit(1)

    #Bokeh image
    elif ext == 'bokeh':
        #print('I got a bokeh figure')
        figscript, figdiv = components(filename, wrap_script=False)

        #Todo get width and height from a bokeh figure
        if args['width'] == None:
            args['width'] = '%ipx'%filename.plot_width
        if args['height'] == None:
            args['height'] = '%ipx'%filename.plot_height

        #Transform figscript to givea function name load_bokehjs
        tmp = figscript.splitlines()
        goodscript = '\n'.join( ['["load_bokeh"] = function() {'] + tmp[1:-1] + ['};\n'] )
        args['ext'] = ext
        args['script']=goodscript

        figout = {'type': 'html',
                  'content': figdiv,
                  'args': args,
                  'render': render_figure}

        return add_to_slide( figout, args['x'], args['y'], args['width'], args['height'] )


    #Other filetype images
    else:

        if args['width'] == None:
            args['width'] = document._width

        args['ext']=ext
        args['filename']=filename

        figout = {'type': 'figure', 'content': filename, 'args': args,
                  "render": render_figure}

        return add_to_slide( figout, args['x'], args['y'], args['width'], args['height'] )
コード例 #16
0
def itemize(items_list, **kwargs):
    '''
    Generates a list or an enumeration.

    Parameters
    ----------

    items_list : list of str
        List of item sentences.

    x : int or float or {'center', 'auto'} or str, optional
        Horizontal position for the item list (the default is 'center'). See
        positioning system of Beampy.

    y : int or float or {'center', 'auto'} or str, optional
        Vertical position for the item list (the default is 'auto'). See
        positioning system of Beampy.

    width : int or float or None, optional
       Width of the group containing items (the default is None, which implies
       that the width is computed to fit the longest item width).

    item_style : {'bullet','number'} or str, optional
        Style of the item markers (the default theme sets this value to
        'bullet', which implies that item marker decorator is a bullet). The
        bullet could be replaced by any string, including latex symbols. When
        `item_style`='number', the item makers is an increasing number to
        create an enumeration.

    item_spacing : int or float or str, optional
        Vertical spacing between items (the default theme sets this value to
        '+1cm'). `item_spacing` accepts the same values as Beampy `x` or `y`.

    item_indent : int or float or str, optional
        Horizontal item indent (the default theme sets this value to '0cm').
        `item_indent` accepts the same values as Beampy `x` or `y`.

    item_color : str, optional
        Color of item marker (the default theme sets this value to
        doc._theme['title']['color']). Color could be given as svg-color-names
        or HTML color hex values (expl: #fffff for white).

    text_color : str, optional
        Color of the item texts (the default theme sets this value to
        doc._theme['text']['color']). Color could be given as svg-color-names
        or HTML color hex values (expl: #fffff for white).

    item_layers : (list of int or string) or None, optional
        Place items into layers to animate them (the default theme sets this
        value to None, which implies that all items are displayed on the same
        layer). The list should have the same length as the `items_list`. The
        item in `item_layers` list could refers to a given layer number, given
        as int, or use python list index syntax (like ':', ':-1', '3:') given
        as string.

        >>> itemize(['item1 on all layers', 'item2 on layer 1'],
                    item_layers=[':',1])

    '''

    args = check_function_args(itemize, kwargs)
    number = 1

    if args['width'] is not None:
        in_width = float(convert_unit(args['width'])) - float(
            convert_unit(args['item_indent']))
    else:
        in_width = float(document._width) - float(
            convert_unit(args['item_indent']))

    if args['item_layers'] is not None:
        if len(items_list) != len(args['item_layers']):
            raise ValueError(
                'Length of item_layers is not the same as the length of items_list'
            )

    with group(width=args['width'], x=args['x'], y=args['y']) as groupitem:

        for i, the_item in enumerate(items_list):

            if args['item_style'] == 'bullet':
                item_char = r'$\bullet$'

            elif args['item_style'] == 'number':
                item_char = str(number) + r'.'
                number += 1

            else:
                item_char = args['item_style']

            # Add color

            item_char = color_text(item_char, args['item_color'])
            the_item = color_text(the_item, args['text_color'])

            if i == 0:
                t = text(item_char + r' ' + the_item,
                         x=args['item_indent'],
                         y=0,
                         width=in_width)
            else:
                t = text(item_char + r' ' + the_item,
                         x=args['item_indent'],
                         y=args['item_spacing'],
                         width=in_width)

            # Add layers to item
            if args['item_layers'] is not None:
                layer = args['item_layers'][i]
                if isinstance(layer, str):
                    eval('t[%s]' % layer)
                else:
                    t[args['item_layers'][i]]

    return groupitem