Ejemplo n.º 1
0
def add_paracols_environment(doc, ncols, columnsep, sloppy=True):
    doc.append(
        Command('setlength',
                NoEscape('\columnsep'),
                extra_arguments=Arguments(columnsep)))
    paracols = ParacolEnvironment(arguments=Arguments(ncols))
    if sloppy:
        sloppy = SloppyParacolsEnvironment()
        doc.append(sloppy)
    doc.append(paracols)
    return paracols
Ejemplo n.º 2
0
    def generate_pdf(self, *args, instructor_key = False, **kwargs):
        # Delete the old content
        self.preamble.clear()

        # Set the key flags
        if instructor_key:
            self.preamble.append(Command('setbool', Arguments('instructorKey', 'true')))
            self.preamble.append(Command('setbool', Arguments('studentKey', 'true')))
        else:
            self.preamble.append(Command('setbool', Arguments('instructorKey', 'false')))
            self.preamble.append(Command('setbool', Arguments('studentKey', 'false')))

        super().generate_pdf(*args, **kwargs)
Ejemplo n.º 3
0
 def __init__(self):
     pdf_path = Arguments(self.filename)
     pdf_path.escape = False
     options = Options(pages=r'{1,2}')
     options.escape = False
     pdf_length = Arguments('-2')
     pdf_length.escape = False
     super().__init__(data=[
         NewPage(),
         Command('includepdf', pdf_path, options),
         Command('addtocounter', 'page', None, extra_arguments=pdf_length),
     ])
     self.packages.append(Package('pdfpages'))
Ejemplo n.º 4
0
def weekview_table(doc: Document, camp: Camp):
    # content for this page
    days = camp.get_days()

    # add packages
    doc.packages.add(Package('caption', options='tableposition=top'))
    doc.packages.add(Package('graphicx'))
    doc.packages.add(Package('float'))
    doc.packages.add(Package('floatpag'))

    with doc.create(Sidewaystable(options='p!')):

        doc.append(Command('small'))

        # define table look
        doc.append(Command('caption*', arguments=Arguments(NoEscape(r'\textbf{Wochenplan Sommerlager 2021} Achtung Datum falsch!!!'))))
        doc.append(Command('centering'))
        doc.append(Command('newcolumntype', arguments='Y',
                           extra_arguments=Arguments(NoEscape(r'>{\centering\arraybackslash}X'))))
        doc.append(Command('newcommand*'))
        doc.append(Command('rot', arguments=Command('rotatebox', options='origin=c', arguments='270')))
        doc.append(Command('renewcommand', arguments=Command('arraystretch'), extra_arguments='2.25'))

        column_template = r'| >{\bfseries}Y |'
        for _ in days:
            column_template += ' Y | '

        doc.append(NoEscape(r'\makebox[\textwidth]{'))  # open makebox

        with doc.create(Tabularx(NoEscape(column_template),
                                 width_argument=NoEscape(r'1.15\textwidth'))) as table_content:
            # reset with since we use custom columntypes
            table_content.width = len(days) + 1

            # add header
            table_content.add_hline()
            table_content.add_row([''] + days)
            table_content.add_hline()
            table_content.add_hline()

            # get meal data
            meals = camp.get_meals_for_weekview()

            # add meals
            for meal_name in meals.keys():
                table_content.add_row([meal_name] + meals[meal_name])
                table_content.add_hline()

        doc.append(Command('thisfloatpagestyle', arguments='empty'))
        doc.append(NoEscape(r'}%'))  # close makebox
Ejemplo n.º 5
0
    def create_manual_context_topics(self):
        with self.doc.create(Section(
                Constants.ITEM_TYPE.title() +
                ' context-rich topic models (manual)')):

            with self.doc.create(Tabular(self.table_format)) as table:
                table.add_hline()
                table.add_row(self.headers, mapper=bold_mapper)
                table.add_hline()

                for topic in context_words[Constants.ITEM_TYPE]:
                    color_id = self.manual_context_topic_colors[topic]
                    color = self.rgb_tuples[color_id]
                    id_cell = str(topic)+str('|||')+str(color[0]) + \
                        '|||'+str(color[1])+'|||'+str(color[2])
                    row = [id_cell]
                    for word in list(context_words[Constants.ITEM_TYPE][topic])[:self.num_cols + 1]:
                        word_color = word+str('|||')+str(color[0])+'|||' + \
                            str(color[1])+'|||'+str(color[2])
                        row.append(word_color)
                    table.add_row(row, mapper=background_color_mapper)

                table.add_hline()

            self.doc.append(UnsafeCommand('par'))
            # self.doc.append(
            #     'Number of context-rich topics: %d' %
            #     len(context_words[Constants.ITEM_TYPE]))
            self.doc.append(ColorBoxCommand(
                arguments=Arguments(
                    1, 1, 1, 'Number of context-rich topics: ' +
                            str(len(context_words[Constants.ITEM_TYPE])))))
Ejemplo n.º 6
0
 def _document_fe_graph(self) -> None:
     """Add FE execution graphs into the traceability document.
     """
     with self.doc.create(Section("FastEstimator Architecture")):
         for mode in self.system.pipeline.data.keys():
             scheduled_items = self.system.pipeline.get_scheduled_items(
                 mode) + self.system.network.get_scheduled_items(mode) + self.system.traces
             signature_epochs = get_signature_epochs(scheduled_items, total_epochs=self.system.epoch_idx, mode=mode)
             epochs_with_data = self.system.pipeline.get_epochs_with_data(total_epochs=self.system.epoch_idx,
                                                                          mode=mode)
             if set(signature_epochs) & epochs_with_data:
                 self.doc.append(NoEscape(r'\FloatBarrier'))
                 with self.doc.create(Subsection(mode.capitalize())):
                     for epoch in signature_epochs:
                         if epoch not in epochs_with_data:
                             continue
                         self.doc.append(NoEscape(r'\FloatBarrier'))
                         with self.doc.create(
                                 Subsubsection(f"Epoch {epoch}",
                                               label=Label(Marker(name=f"{mode}{epoch}", prefix="ssubsec")))):
                             diagram = self._draw_diagram(mode, epoch)
                             ltx = d2t.dot2tex(diagram.to_string(), figonly=True)
                             args = Arguments(**{'max width': r'\textwidth, max height=0.9\textheight'})
                             args.escape = False
                             with self.doc.create(Center()):
                                 with self.doc.create(AdjustBox(arguments=args)) as box:
                                     box.append(NoEscape(ltx))
Ejemplo n.º 7
0
def generate_docs(config):
    """
        Function used to generate two pdf:

        -results.pdf: which shows all statistics about each formula with each
         benchmarked method.

        -summary.pdf: which count the number of times that each method is
         better than another.
    """
    # Let's create the documents (result & summary)
    doc = Document(documentclass='standalone')
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('color'))
    doc.packages.append(Package('colortbl'))
    doc2 = Document(documentclass='standalone')

    # Declare colors in result document
    doc.append(
        DefineColor(arguments=Arguments('Gray', 'rgb', '0.7, 0.7, 0.7')))
    doc.append(DefineColor(arguments=Arguments('Green', 'rgb', '0.4, 1, 0.4')))
    doc.append(DefineColor(arguments=Arguments('Red', 'rgb', '0.8, 0, 0')))
    doc.append(DefineColor(arguments=Arguments('Yelw', 'rgb', '1, 0.98, 0.4')))
    doc.append(DefineColor(arguments=Arguments('Purpl', 'rgb', '1, 0.6, 1')))

    # Create Table with format : True is result format, False is summary format
    table = Tabular(add_fmt(len(config.l), True))
    table2 = Tabular(add_fmt(len(config.l), False))

    # Write everything
    write_results(table, config)
    write_summary(table2, config)

    # Output PDF
    doc.append(table)
    doc2.append(table2)
    doc.generate_pdf('results')
    doc2.generate_pdf('summary')
Ejemplo n.º 8
0
    def dumps(self):
        # Delete the old preamble
        self.preamble.clear()
        # Set the key flags
        if self.instructor_key:
            self.preamble.append(
                Command('setbool', Arguments('instructorKey', 'true')))
            self.preamble.append(
                Command('setbool', Arguments('studentKey', 'true')))
        else:
            self.preamble.append(
                Command('setbool', Arguments('instructorKey', 'false')))
            self.preamble.append(
                Command('setbool', Arguments('studentKey', 'false')))

        self.preamble.append(self.headfoot)
        self.change_length('\headheight', self.head_height)

        # Delete the old body
        self.clear()
        self.change_document_style(self.headfoot.name)
        # Update the body
        if self.nameline:
            # Add the name line
            self.append(Command('ExamNameLine'))

        if self.instructions:
            # Add the instructions
            self.append(self.instructions)

        if self.hints:
            # Add the hints
            self.append(self.hints)

        self.append(self.body)

        return super().dumps()
Ejemplo n.º 9
0
def make_preamble(dolidoc, issue, date):
    assert isinstance(dolidoc, Document)
    assert isinstance(issue, int)
    assert isinstance(date, datetime.datetime)
    # packages
    dolidoc.packages.pop(
    )  # to remove stupid package lastpage added by pylatex
    # preamble itself
    dolidoc.preamble.append(Command("currentissue",
                                    issue))  # substitute correct values
    dolidoc.preamble.append(Command("currentyear", date.year))
    dolidoc.preamble.append(Command("currentmonth", date.month))
    dolidoc.preamble.append(Command("currentday", date.day))
    dolidoc.preamble.append(
        Command("titleformat",
                options='block',
                arguments=Command("section"),
                extra_arguments=Arguments(
                    NoEscape(r"\large\bfseries\filcenter"),
                    Command("thesection"), Command("1em"),
                    Command("MakeUppercase"))))
    return dolidoc
Ejemplo n.º 10
0
    def build_text(self, review):
        words = extract_words(review)
        doc_parts = []
        new_words = []
        for word in words:
            word_found = False
            for topic_id in self.automatic_context_topic_ids:
                if word in self.topic_words_map[topic_id]:
                    self.tag_word(word)
                    doc_parts.append(' '.join(new_words))
                    # doc_parts.append('topic: %d word: %s' % (topic_id, word))
                    color_id = self.automatic_context_topic_colors[topic_id]
                    color = self.rgb_tuples[color_id]
                    doc_parts.append(ColorBoxCommand(
                        arguments=Arguments(
                            color[0], color[1], color[2], word)))
                    new_words = []
                    word_found = True
                    break
            if not word_found:
                new_words.append(word)
        doc_parts.append(' '.join(new_words))

        return doc_parts
Ejemplo n.º 11
0
    geometry_options = {"tmargin": "1cm", "lmargin": "2cm"}
    doc = Document(geometry_options=geometry_options)

    doc.packages.append(Package("babel", options=Options("russian")))
    doc.packages.append(Package("float"))

    with doc.create(
            Section("Задача: реализуйте конечный автомат.", numbering=False)):
        for variant in sorted(Path("tasks").glob("*"),
                              key=lambda path: int(path.stem)):
            with doc.create(
                    Subsection(f"Вариант: {variant.stem}", numbering=False)):
                with open("tasks/payload.txt") as payload:
                    for line in payload:
                        doc.append(line)

                with doc.create(
                        Subsection(f"Схема конечного автомата:",
                                   numbering=False)):
                    with doc.create(Figure(position="H")) as pic:
                        pic.add_image(str(variant.joinpath("fsm.png")),
                                      width="200px")

                with doc.create(
                        Subsection(f"Примеры выполнения:", numbering=False)):
                    for path in variant.glob("path*.txt"):
                        doc.append(
                            Listing(arguments=Arguments(str(path), 0, 10), ))
    doc.generate_pdf("tasks", clean_tex=False)
Ejemplo n.º 12
0
with doc.create(Section('Custom commands')):
    doc.append(
        NoEscape(r"""
        The following is a demonstration of a custom \LaTeX{}
        command with a couple of parameters.
        """))

    # Define the new command
    new_comm = UnsafeCommand('newcommand',
                             '\exampleCommand',
                             options=3,
                             extra_arguments=r'\color{#1} #2 #3 \color{black}')
    doc.append(new_comm)

    # Use our newly created command with different arguments
    doc.append(ExampleCommand(arguments=Arguments('blue', 'Hello', 'World!')))
    doc.append(ExampleCommand(arguments=Arguments('green', 'Hello', 'World!')))
    doc.append(ExampleCommand(arguments=Arguments('red', 'Hello', 'World!')))

with doc.create(Section('Custom environments')):
    doc.append(
        NoEscape(r"""
        The following is a demonstration of a custom \LaTeX{}
        environment using the mdframed package.
        """))

    # Define a style for our box
    mdf_style_definition = UnsafeCommand('mdfdefinestyle',
                                         arguments=[
                                             'my_style',
                                             ('linecolor=#1,'
Ejemplo n.º 13
0
def generate_recipes_pdf(recipes, pdf_opts, display_opts, ingredient_df):
    """ Generate a .tex and .pef from the recipes given
    recipes is an ordered list of RecipeTuple namedtuples
    """

    print "Generating {}.tex".format(pdf_opts.pdf_filename)
    pylatex.config.active = pylatex.config.Version1(indent=False)

    # Determine some settings based on the number of cols
    if pdf_opts.ncols == 1:
        side_margin = '1.75in'
        colsep = '44pt'
    elif pdf_opts.ncols == 2:
        side_margin = '0.8in'
        colsep = '50pt'
    elif pdf_opts.ncols == 3:
        side_margin = '0.5in'
        colsep = '44pt'
    else:
        side_margin = '0.5in'
        colsep = '30pt'

    # Document setup
    doc_opts = {
        'geometry_options': {
            'showframe': pdf_opts.debug,
            'left': side_margin,
            'right': side_margin,
            'top': '0.4in',
            'bottom': '0.2in',
            'headheight': '29pt',
            'includehead': True,
            'includefoot': True,
        }
    }
    doc = Document(**doc_opts)
    doc.documentclass = Command('documentclass',
                                options=Options('11pt', 'portrait',
                                                'letterpaper'),
                                arguments=Arguments('article'))

    # http://www.tug.dk/FontCatalogue/computermoderntypewriterproportional/
    doc.preamble.append(
        Command(r'renewcommand*\ttdefault', extra_arguments='cmvtt'))
    doc.preamble.append(
        Command(r'renewcommand*\familydefault',
                extra_arguments=NoEscape(r'\ttdefault')))

    # apply a header and footer to the document
    setup_header_footer(doc, pdf_opts, display_opts)

    # Columns setup and fill
    paracols = add_paracols_environment(doc,
                                        pdf_opts.ncols,
                                        colsep,
                                        sloppy=False)
    for i, recipe in enumerate(recipes, 1):
        paracols.append(format_recipe(recipe, display_opts))
        switch = 'switchcolumn'
        if pdf_opts.align:
            switch += '*' if (i % pdf_opts.ncols) == 0 else ''
        paracols.append(Command(switch))

    # append a page on the ingredients
    if pdf_opts.liquor_list or pdf_opts.liquor_list_own_page:
        append_liquor_list(doc,
                           ingredient_df,
                           own_page=pdf_opts.liquor_list_own_page)

    print "Compiling {}.pdf".format(pdf_opts.pdf_filename)
    doc.generate_pdf(pdf_opts.pdf_filename, clean_tex=False)
    print "Done"
    return True
Ejemplo n.º 14
0
def generate_tables(args):

    if args.change_directory:
        os.chdir(args.change_directory)

    config = load_experiments_config(args.config, args)

    exps = Experiment.load_all(config.experiments,
                               config_file=args.config,
                               base_path=config.options.base_path,
                               cache_dir=config.options.cache_dir,
                               seq_name_mapping=config.seq_name_mapping)

    doc = Document(geometry_options={"tmargin": "1cm", "lmargin": "1cm"})

    export_basepath = "{}-export".format(config.options.output_path)

    curr = doc

    hide_all = False
    for spec in config.results:
        if spec.show:

            if spec["class"] == "section":
                if spec.clearpage:
                    curr.append(NewPage())
                if spec.pagewidth:
                    curr.append(
                        Command("SetPageScreenWidth",
                                Arguments(spec.pagewidth)))
                else:
                    curr.append(Command("RestorePageScreenWidth"))
                hide_all = False
                curr = Section(spec.name)
                doc.append(curr)
                continue

            if hide_all:
                continue

            if spec.clearpage:
                curr.append(NewPage())

            elif spec["class"] == "results_table":
                elem = ResultsTable(
                    exps,
                    spec,
                    show_values_failed_runs=config.options.
                    show_values_failed_runs,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            elif spec["class"] == "summarize_sequences_table":
                elem = SummarizeSequencesTable(
                    exps,
                    spec,
                    show_values_failed_runs=config.options.
                    show_values_failed_runs,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            elif spec["class"] == "plot":
                elem = Plot(
                    exps,
                    spec,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            else:
                raise RuntimeError("Invalid results class {}".format(
                    spec["class"]))

            curr.append(elem)
        else:
            if spec["class"] == "section":
                hide_all = True
                continue

    # generate auxiliary tex files
    if config.options.screenread:
        output_dir = os.path.dirname(config.options.output_path)
        screenread_path = output_dir + "/screenread.sty"
        with open(screenread_path, "w") as f:
            f.write(screenread_sty)
        doc.packages.add(Package('screenread'))

    # create nofloatfigure environment
    doc.preamble.append(
        Command(
            "newenvironment",
            Arguments("nofloatfigure",
                      Command("captionsetup", Arguments(type="figure")), "")))
    doc.packages.add(Package('caption'))
    doc.packages.add(Package('mathtools'))

    # render latex
    doc.generate_pdf(config.options.output_path,
                     clean_tex=not args.dont_clean_tex)

    # cleanup
    if config.options.screenread and not args.dont_clean_tex:
        os.remove(screenread_path)

    # open the generated pdf
    if args.open:
        os_open_file(config.options.output_path + ".pdf")
Ejemplo n.º 15
0
 def __init__(self, *args):
     path = NoEscape(Arguments(args).dumps())
     super(GraphicsPath, self).__init__(arguments=path)
Ejemplo n.º 16
0
 def CompileContent(self):
     """
     """
     self.arguments = Arguments(NoEscape(self.content.replace("#", r"\#")))
Ejemplo n.º 17
0
def processLaTex():

    titlePage = r'''
\renewcommand{\maketitle}{%

	\begin{titlepage} % Suppresses headers and footers on the title page

	\centering % Centre everything on the title page
	
	\scshape % Use small caps for all text on the title page
	
	\vspace*{\baselineskip} % White space at the top of the page
	
	%------------------------------------------------
	%	Title
	%------------------------------------------------
	
	\rule{\textwidth}{1.6pt}\vspace*{-\baselineskip}\vspace*{2pt} % Thick horizontal rule
	\rule{\textwidth}{0.4pt} % Thin horizontal rule
	
	\vspace{0.75\baselineskip} % Whitespace above the title
	
	{\LARGE THE DICTIONARY \\ OF COLLECTED WORDS\\} % Title
	
	\vspace{0.75\baselineskip} % Whitespace below the title
	
	\rule{\textwidth}{0.4pt}\vspace*{-\baselineskip}\vspace{3.2pt} % Thin horizontal rule
	\rule{\textwidth}{1.6pt} % Thick horizontal rule
	
	\vspace{2\baselineskip} % Whitespace after the title block
	
	%------------------------------------------------
	%	Subtitle
	%------------------------------------------------
	
	A Number of Fascinating and Fundamental Words Presented in a Dictionary Way % Subtitle or further description
	
	\vspace*{3\baselineskip} % Whitespace under the subtitle
    \vspace*{3\baselineskip} % Whitespace under the subtitle
    \vspace*{3\baselineskip} % Whitespace under the subtitle
	
	%------------------------------------------------
	%	Editor(s)
	%------------------------------------------------
	
	Edited By
	
	\vspace{0.5\baselineskip} % Whitespace before the editors
	
	{\scshape\Large Arafat Hasan \\} % Editor list
	
	\vspace{0.5\baselineskip} % Whitespace below the editor list
	
	\textit{Mawlana Bhashani Science and Technology University \\ Tangail, Bangladesh} % Editor affiliation
	
	\vfill % Whitespace between editor names and publisher logo
	
	%------------------------------------------------
	%	Publisher
	%------------------------------------------------
	
	%\plogo % Publisher logo
	
	%\vspace{0.3\baselineskip} % Whitespace under the publisher logo
	
	\the\year % Publication year
	
	%{\large publisher} % Publisher

	\end{titlepage}
}
'''

    pdfMeta = r'''
\usepackage[xetex,
            pdfauthor={Arafat Hasan},
            pdftitle={The Dictionary of Collected Words},
            pdfsubject={A Personal Dictionary},
            pdfkeywords={Personal Dictionary},
            pdfproducer={XeLaTeX on Ubuntu},
            pdfcreator={XeLaTeX}]{hyperref}
   '''


    geometry_options = {"top":"2.3cm","bottom":"2.0cm", "left":"2.5cm",\
            "right":"2.0cm", "columnsep":"27pt"}
    doc = Document('TheDictionaryOfCollectedWords',
                   geometry_options=geometry_options)
    doc.documentclass = Command(
        'documentclass',
        options=['10pt', 'a4paper', 'twoside'],
        arguments=['book'],
    )

    doc.packages.append(Package('palatino'))
    doc.packages.append(Package('microtype'))
    doc.packages.append(Package('multicol'))
    doc.packages.append(Package('fontspec'))
    doc.packages.append(Package('enumitem'))
    doc.packages.append(Package('graphicx'))
    doc.packages.append(Package('PTSerif'))
    doc.packages.append(Package('titlesec', NoEscape('bf, sf, center')))
    doc.packages.append(Package('fancyhdr'))


    doc.preamble.append(Command('usepackage', \
            NoEscape(r'xcolor'), 'svgnames'))

    doc.preamble.append(NoEscape(pdfMeta))
    doc.preamble.append(NoEscape('%'))
    doc.preamble.append(NoEscape('%'))

    doc.preamble.append(Command('setmainfont', \
            'TeX Gyre Pagella', 'Numbers=OldStyle'))


    doc.preamble.append(Command('fancyhead', \
            NoEscape(r'\textsf{\rightmark}'), 'L'))
    doc.preamble.append(Command('fancyhead', \
            NoEscape(r'\textsf{\leftmark}'), 'R'))

    doc.preamble.append(NoEscape('%'))
    doc.preamble.append(NoEscape('%'))

    doc.preamble.append(Command('renewcommand', \
        arguments=Arguments(NoEscape(r'\headrulewidth'), '1.4pt')))

    doc.preamble.append(Command('fancyfoot', \
            NoEscape(r'\textbf{\textsf{\thepage}}'), 'C'))

    doc.preamble.append(Command('renewcommand', \
        arguments=Arguments(NoEscape(r'\footrulewidth'), '1.4pt')))

    doc.preamble.append(Command('pagestyle', 'fancy'))

    doc.append(NoEscape(r'\setlength{\parindent}{-0.7em}'))

    new_comm = UnsafeCommand('newcommand', '\entry', options=7, \
    extra_arguments=NoEscape(r'\textbf{#1}\markboth{#1}{#1}\ {{\fontspec{Doulos SIL} #2}}\  {{\fontspec{Kalpurush} \small {#3}}}\ {#4}\ {#5}\ {\textit{#6}}\ {#7}'))
    doc.preamble.append(new_comm)

    color_bullet = UnsafeCommand('newcommand', '\colorBulletS', options=1, \
    extra_arguments=NoEscape(r'\colorbox[RGB]{171,171,171}{\makebox(11,2){\textcolor{white}{{\tiny \textbf{#1}}}}}'))
    doc.preamble.append(color_bullet)

    color_bullet = UnsafeCommand('newcommand', '\colorBullet', options=1, \
    extra_arguments=NoEscape(r'\colorbox[RGB]{171,171,171}{\makebox(22, 1){\textcolor{white}{{\tiny \textbf{#1}}}}}'))
    doc.preamble.append(color_bullet)

    doc.preamble.append(
        NoEscape(
            r'\newcommand{\plogo}{\fbox{$\mathcal{PL}$}} % Generic dummy publisher logo'
        ))

    doc.preamble.append(NoEscape('%'))
    doc.preamble.append(NoEscape('%'))

    doc.preamble.append(NoEscape(titlePage))
    doc.append(NoEscape(r'\maketitle'))
    entriesList = list(fileData.keys())
    entriesList.sort()

    currentSection = "a"
    sectionStr = "\chapter*{" + currentSection.upper() + "}"
    doc.append(NoEscape(sectionStr))
    doc.append(NoEscape(r'\begin{multicols}{2}'))

    for item in entriesList:
        entryList = fileData[item]
        for entry in entryList:
            word = entry.get('word', "")
            bengali = entry.get('bengali', "")
            prep = entry.get('prep', "")
            ownExample = entry.get('example', "")
            origin = entry.get('origin', "")
            phonetic = entry.get('phonetic', "")
            meaning = entry.get('meaning', {})

            word = escape_latex(word)
            bengali = escape_latex(bengali)
            prep = escape_latex(prep)
            ownExample = escape_latex(ownExample)
            origin = escape_latex(origin)
            phonetic = escape_latex(phonetic)

            if len(prep): prep = " \\colorBullet{OTHER} " + prep
            if len(origin): origin = " \\colorBullet{ORIGIN} " + origin

            partsOfSpeech = list(meaning.keys())

            if len(partsOfSpeech) == 1:
                partStr = ""
            else:
                partStr = "\\small{\\textsf{\\textit{" + escape_latex(
                    ", ".join(partsOfSpeech)) + "}}}"

            for part in partsOfSpeech:
                escapePart = escape_latex(str(part))
                onepart = meaning[part]
                deffCnt = 0
                if len(partsOfSpeech) == 1:
                    strGen = "\\textsf{\\textit{" + escapePart + "}}\\"
                else:
                    strGen = "\\\\{\\fontspec{DejaVu Sans}▪ }\\textsf{\\textit{" + escapePart + "}}\\\\"

                for deff in onepart:
                    deffCnt = deffCnt + 1
                    definition = deff.get('definition', "")
                    example = deff.get('example', "")
                    synonyms = deff.get('synonyms', {})

                    definition = escape_latex(definition)
                    example = escape_latex(example)
                    synonyms = escape_latex(", ".join(synonyms))
                    if len(synonyms):
                        synonyms = " \\colorBulletS{SYN} " + synonyms

                    strGen = strGen + " \\textbf{" + str(
                        deffCnt
                    ) + "} " + definition + " {\\fontspec{DejaVu Sans}◇} " + "\\textit{" + example + "}" + synonyms

                partStr = partStr + " " + strGen

            # lorem = "\entry{"+word+"}{"+phonetic+"}{"+bengali+"}{"+partStr+"}" + "{" + prep +"}" + "{" + ownExample + "}" + "{" + origin + "}" // With origin
            lorem = "\entry{" + word + "}{" + phonetic + "}{" + bengali + "}{" + partStr + "}" + "{" + prep + "}" + "{" + ownExample + "}"
            if item[0] is not currentSection[0]:
                currentSection = item[0]
                sectionStr = "\section*{" + currentSection.upper() + "}"
                doc.append(NoEscape(r'\end{multicols}'))
                doc.append(NoEscape(r'\pagebreak'))
                doc.append(NoEscape(sectionStr))
                doc.append(NoEscape(r'\begin{multicols}{2}'))
            doc.append(NoEscape(lorem))
            doc.append(NoEscape(r'\par'))

    doc.append(NoEscape(r'\end{multicols}'))
    doc.generate_pdf(clean_tex=False, compiler='xelatex')
    doc.generate_tex()

    tex = doc.dumps()
Ejemplo n.º 18
0
# -*- coding: utf-8 -*-
r"""A test to make sure the document compiles with inputenc set to `None`."""

from pylatex.base_classes import Arguments
from pylatex import Document

doc = Document('no_inputenc', inputenc=None)
doc.append('test text')

# Make sure inputenc isn't used
assert not any([p.arguments == Arguments('inputenc') for p in doc.packages])

doc.generate_pdf(clean=True, clean_tex=False, silent=False)