예제 #1
0
def generate_user_stories(schema: PLDSchema, locale: LocaleDictionary,
                          document: Document) -> Document:
    document.append(NewPage())
    with document.create(Section(title=locale.user_stories)) as section:
        section: Section

        for deliverable in schema.deliverables:
            with section.create(
                    Subsection(title=deliverable.name)) as subsection:
                subsection: Subsection
                if deliverable.description is not None:
                    subsection.append(MediumText(data=deliverable.description))
                for subset in deliverable.subsets:
                    with subsection.create(
                            Subsubsection(title=subset.name)) as subsubsection:
                        subsubsection: Subsubsection
                        if subset.description is not None:
                            subsubsection.append(
                                MediumText(data=subset.description))
                        for user_story in subset.user_stories:
                            with subsubsection.create(
                                    Paragraph(
                                        title=user_story.name)) as paragraph:
                                paragraph: Paragraph
                                paragraph.append(Command("mbox", ""))
                                paragraph.append(NoEscape("\\\\\n"))
                                generate_user_story(user_story, locale,
                                                    paragraph)
    return document
예제 #2
0
def generate_eva_report():

    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    reportStyle = PageStyle("reportStyle")

    with reportStyle.create(Head("R")) as left_header:
        with left_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='l')) as title_wrapper:
            title_wrapper.append(LargeText(bold("RiMEA-Projekt")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Anlyse")))

    doc.preamble.append(reportStyle)

    doc.change_document_style("reportStyle")

    with doc.create(LongTabu("X[c] X[c]", row_height=1.5)) as report_table:
        report_table.add_row(["Test", "evacuation time(s)"], mapper=bold)
        report_table.add_hline()

    for i in range(1, 4):
        report_table.add_row(i, get_evac_time(i)[0])

    doc.append(NewPage())

    doc.generate_pdf("RiMEA-Projekt-Evacution-Analyse", clean_tex=False)
예제 #3
0
파일: args.py 프로젝트: cmrfrd/PyLaTeX
def test_basic():
    # Tests the basic commands and environments
    # Basic commands
    new_page = NewPage()
    repr(new_page)

    new_line = NewLine()
    repr(new_line)

    line_break = LineBreak()
    repr(line_break)

    h_fill = HFill()
    repr(h_fill)

    # Basic environments
    huge = HugeText("Huge")
    huge.append("Huge 2")
    repr(huge)

    large = LargeText("Large")
    large.append("Large 2")
    repr(large)

    medium = MediumText("Medium")
    medium.append("Medium 2")
    repr(medium)

    small = SmallText("Small")
    small.append("Small 2")
    repr(small)

    footnote = FootnoteText("Footnote")
    footnote.append("Footnote 2")
    repr(footnote)

    text_color = TextColor("green", "GreenText")
    text_color.append("More Green Text")
    repr(text_color)
예제 #4
0
def test_basic():
    # Tests the basic commands and environments
    # Basic commands
    new_page = NewPage()
    repr(new_page)

    new_line = NewLine()
    repr(new_line)

    line_break = LineBreak()
    repr(line_break)

    h_fill = HFill()
    repr(h_fill)

    # Basic environments
    huge = HugeText("Huge")
    huge.append("Huge 2")
    repr(huge)

    large = LargeText("Large")
    large.append("Large 2")
    repr(large)

    medium = MediumText("Medium")
    medium.append("Medium 2")
    repr(medium)

    small = SmallText("Small")
    small.append("Small 2")
    repr(small)

    footnote = FootnoteText("Footnote")
    footnote.append("Footnote 2")
    repr(footnote)

    text_color = TextColor("green", "GreenText")
    text_color.append("More Green Text")
    repr(text_color)
예제 #5
0
def compile_document_week(no):
    "produce a pdf of the weeks workout"

    # input accessory lifts for main lifts
    bench = [('Decline DB Press (4 x 12)'), ('Face pull (4 x 12)'),
             ('Low/High flyes ss/w press (4 x 12)'), ('Press ups (4 x Max)')]
    # squat = [('Leg press (4 x 15)'), ('Leg extension (4 x 12)'),
    #          ('Leg curl (4 x 12)'), ('Roll out (4 x Max)')]
    squat = [('Smith Front/Back (4 x 12)'), ('Calf Raises (4 x 12)'),
             ('Walking Lunges (4 x 12)'), ('Roll out (4 x Max)')]
    dead = [('Pendlay Row (4 x 8-12)'), ('Hip thrust (4 x 8-12)'),
            ('Pull up (4 x Max)'), ('Leg raise (4 x 8-12)')]
    press = [('Landmine press (4 x 8-12)'), ('Lateral/Rear raises (4 x 8-12)'),
             ('DB Curls (4 x 8-12)'), ('Roll outs (4 x Max)')]

    acc = [bench, squat, press, dead]

    # input main lifts and one rep maxes
    # last updated 21/03/2017
    main_lifts = [('Bench', 90), ('Squat', 128), ('Military Press', 63),
                  ('Deadlift', 143)]

    date = t.strftime("%d/%m/%Y")
    doc = Document()
    doc.packages.append(Package('geometry', options=['margin=2cm']))
    doc.packages.append(Package('times'))
    doc.packages.append(Package('float'))
    doc.packages.append(Package('graphicx'))
    header = generate_header()
    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add title
    doc.append(LineBreak())
    doc.append(LargeText(bold("8/6/3 Workout Routine")))
    doc.append(LineBreak())
    doc.append(MediumText(bold("As of: " + date)))
    doc.append(LineBreak())

    # Add workout for a week
    gen_week(doc, main_lifts, no, acc)
    date_1 = t.strftime("%Y%m%d")
    directory = "/home/thomas/Documents/workout_print/workouts"
    filename = (directory + "/workout_routine_week_" + str(no) + "_" + date_1)
    doc.generate_pdf(filename, clean_tex=True)
예제 #6
0
    def write_header(self, doc):
        # def write_header(self):

        # Add document header
        header = PageStyle("header")
        # Create left header
        with header.create(Head("L")):
            header.append(
                "Center for Reflected Text Analytics (CRETA)\nUniversity of Stuttgart"
            )
            # header.append(LineBreak())
            # header.append("R3")
        ## Create center header
        # with header.create(Head("C")):
        #    header.append("Company")
        # Create right header
        with header.create(Head("R")):
            header.append(NoEscape(r'\today'))
        ## Create left footer
        # with header.create(Foot("L")):
        #    header.append("Left Footer")
        ## Create center footer
        with header.create(Foot("C")):
            header.append(simple_page_number())
        ## Create right footer
        # with header.create(Foot("R")):
        #    header.append("Right Footer")

        doc.preamble.append(header)
        doc.change_document_style("header")

        # Add Heading
        with doc.create(MiniPage(align='c')):
            doc.append(LargeText(bold("rCAT v0.1")))
            doc.append(LineBreak())
            doc.append(MediumText(bold("Relational Character Analysis Tool")))

        return doc
예제 #7
0
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("__")
        header.append(LineBreak())
        header.append("_")
    # Create center header
    with header.create(Head("C")):
        header.append("____")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='l')):
        doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD")))
        doc.append(LineBreak())
        doc.append(MediumText(bold(" ")))
    doc.generate_pdf("header", clean_tex=False)

    return print('nice')
예제 #8
0
def generate_header():
    geometry_options = {"margin": "0.7in"}
    doc = Document(geometry_options=geometry_options)
    # Add document header
    header = PageStyle("header")
    # Create left header
    with header.create(Head("L")):
        header.append("Page date: ")
        header.append(LineBreak())
        header.append("R3")
    # Create center header
    with header.create(Head("C")):
        header.append("Company")
    # Create right header
    with header.create(Head("R")):
        header.append(simple_page_number())
    # Create left footer
    with header.create(Foot("L")):
        header.append("Left Footer")
    # Create center footer
    with header.create(Foot("C")):
        header.append("Center Footer")
    # Create right footer
    with header.create(Foot("R")):
        header.append("Right Footer")

    doc.preamble.append(header)
    doc.change_document_style("header")

    # Add Heading
    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold("Title")))
        doc.append(LineBreak())
        doc.append(MediumText(bold("As at:")))

    doc.generate_pdf("header", clean_tex=False)
예제 #9
0
    def fill(self):
        with self.doc.create(
                Section("{} FPGA system map".format(self.fpga_name))):
            self.doc.append(self.fpga.fpga_description)
            self.doc.append(NewLine())
            self.doc.append(NewLine())
            self.doc.append(MediumText(bold('Slave Port Map')))
            self.doc.append(NewLine())
            self.doc.append(NewLine())
            fpga_system_table = Tabular('|c|c|c|c|c|')
            fpga_system_table.add_hline()
            fpga_system_table.add_row(
                ('Hex', 'Range (Bytes)', 'Slave Port', 'Protocol', 'Port No.'))
            fpga_system_table.add_hline()

            for slave_port, slave_dict in self.fpga.address_map.items():
                fpga_system_table.add_row(
                    (str(hex(slave_dict['base'])), str(slave_dict['span']),
                     slave_port, slave_dict['type'], slave_dict['port_index']))
                fpga_system_table.add_hline()
            self.doc.append(fpga_system_table)

        for periph_name, periph in self.fpga.peripherals.items():
            self.peripheral_fill(periph, periph_name)
예제 #10
0
def details():
    if __name__ == '__main__':


        image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg')
        logo_file = os.path.join(os.path.dirname(__file__),'sample-logo.png')

        geometry_options = {"tmargin": "1cm", "lmargin": "3cm"}
        doc = Document(geometry_options=geometry_options)
        header = PageStyle("header")
        with header.create(Head("R")):
            header.append(simple_page_number())
        with header.create(Foot("C")):
            header.append("Center Footer")
        first_page = PageStyle("firstpage")
        with first_page.create(Head("L")) as header_left:
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='c')) as logo_wrapper

        with doc.create(MiniPage(align='l')):
            doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD")))
            doc.append(LineBreak())
            doc.append(MediumText(bold(" ")))
        logo_wrapper.append(StandAloneGraphic(image_options="width=120px",
                                              filename=logo_file))
        with doc.create(Section('Home Adress')):
            doc.append('Some regular text and some')
            doc.append(italic('italic text. '))
            doc.append('\nAlso some crazy characters: $&#{}')
            with doc.create(Subsection('Math that is incorrect')):
                doc.append(Math(data=['2*3', '=', 9]))

            with doc.create(Subsection('Table of something')):
                with doc.create(Tabular('rc|cl')) as table:
                    table.add_hline()
                    table.add_row((1, 2, 3, 4))
                    table.add_hline(1, 2)
                    table.add_empty_row()
                    table.add_row((4, 5, 6, 7))

        a = np.array([[100, 10, 20]]).T
        M = np.matrix([[2, 3, 4],
                       [0, 0, 1],
                       [0, 0, 2]])

        with doc.create(Section('The fancy stuff')):
            with doc.create(Subsection('Correct matrix equations')):
                doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))

            with doc.create(Subsection('Alignat math environment')):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(r'\frac{a}{b} &= 0 \\')
                    agn.extend([Matrix(M), Matrix(a), '&=', Matrix(M * a)])

            with doc.create(Subsection('Beautiful graphs')):
                with doc.create(TikZ()):
                    plot_options = 'height=4cm, width=6cm, grid=major'
                    with doc.create(Axis(options=plot_options)) as plot:
                        plot.append(Plot(name='model', func='-x^5 - 242'))

                        coordinates = [
                            (-4.77778, 2027.60977),
                            (-3.55556, 347.84069),
                            (-2.33333, 22.58953),
                            (-1.11111, -493.50066),
                            (0.11111, 46.66082),
                            (1.33333, -205.56286),
                            (2.55556, -341.40638),
                            (3.77778, -1169.24780),
                            (5.00000, -3269.56775),
                        ]

                        plot.append(Plot(name='estimate', coordinates=coordinates))

            with doc.create(Subsection('Cute kitten pictures')):
                with doc.create(Figure(position='h!')) as kitten_pic:
                    kitten_pic.add_image(image_filename, width='120px')
                    kitten_pic.add_caption('Look it\'s on its back')

        doc.generate_pdf('full', clean_tex=False)
예제 #11
0
def get_document(document_title='Report',
                 author='Entail AS',
                 fig_ext=u'.pdf',
                 header_logofilename='entail.pdf',
                 logo_image_option_header="width=250px",
                 workflow_ID=0):
    global _fig_ext
    _fig_ext = fig_ext

    geometry_options = {
        "head": "70pt",
        "margin": "1.5cm",
        "bottom": "1.5cm",
        "includeheadfoot": True
    }
    document_options = ['a4paper']
    doc = Document(geometry_options=geometry_options,
                   document_options=document_options)

    # packages
    doc.packages.append(Package('booktabs'))
    doc.packages.append(Package('chngcntr'))
    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('titlepic'))
    doc.packages.append(Package('float'))
    # page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.25\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                header_logofilename).replace('\\', '/')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=80px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.75\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold(document_title)))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold(NoEscape(r'\today'))))

    # Add footer
    with first_page.create(Foot("C")) as center_footer:
        center_footer.append(simple_page_number())
    with first_page.create(Foot("R")) as right_footer:
        with right_footer.create(
                MiniPage(width=NoEscape(r"0.15\textwidth"),
                         pos='r')) as logo_wrapper:
            logo_file = os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                'tailor.png').replace('\\', '/')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

    doc.preamble.append(first_page)
    doc.change_document_style("firstpage")
    doc.preamble.append(Command('title', document_title))
    logo_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             header_logofilename).replace('\\', '/')
    doc.preamble.append(
        Command(
            'titlepic',
            StandAloneGraphic(image_options=logo_image_option_header,
                              filename=logo_file)))
    # doc.preamble.append(Command('author', author))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.preamble.append(
        Command(
            'hypersetup',
            arguments=
            'colorlinks, citecolor=black, filecolor=black, linkcolor=black, urlcolor=black',
            packages=[Package('hyperref')]))
    doc.preamble.append(NoEscape(r'\counterwithin{figure}{section}'))
    doc.append(NoEscape(r'\maketitle'))

    # Add disclaimer
    doc.append(NewPage())
    doc.append(NoEscape(r'\textbf{Disclaimer}'))
    doc.append(NoEscape(r'\newline'))
    doc.append(NoEscape(r'\vspace{0.2in}'))

    temptext = f'This is in automatically generated report. '
    if workflow_ID == 0:
        temptext += f'The report was generated '
    else:
        temptext += f'The results are extracted from Workflow ID {workflow_ID} '
    temptext += f'on the {datetime.datetime.now().strftime("%m/%d/%Y at %H:%M:%S")}. '
    temptext += f'Errors may occur and it is the user’s responsibility to interpret the reported data '
    temptext += f'with sound engineering judgement.'
    doc.append(temptext)

    doc.append(NewPage())
    doc.append(Command('tableofcontents'))
    doc.append(NewPage())

    return doc
예제 #12
0
    def generar(self, Carrera, Asignatura, Curso, listaPreguntas, aleatorio):

        today = str(self.__fecha)

        geometry_options = {
            "head": "48pt",
            "margin": "0.5in",
            "bottom": "0.6in",
            "includeheadfoot": True
        }

        doc = Document(geometry_options=geometry_options)

        header = PageStyle("header")  # DEFINIMOS LA VARIABLE CON ESTILO

        #image_filename = os.path.join(os.path.dirname("__file__"), '../static/zigmap.png') # IMAGEN UNAB

        #data_folder = os.path.join("../", "static/zigmap.png")

        #file_to_open = os.path.join(data_folder, "zigmap.png")

        #image_filename = data_folder
        image_filename = "zigmap.png"

        # Generating first page style
        first_page = PageStyle("firstpage")

        # Header image
        with first_page.create(Head("L")) as header_left:

            with header_left.create(
                    SubFigure(
                        position='L',
                        width=NoEscape(r'0.10\linewidth'))) as logo_wrapper:

                print("IMAGEN")
                #logo_wrapper.add_image('zigmap.png', width=NoEscape(r'\linewidth'))

        # Add document title
        with first_page.create(Head("C")) as center_header:
            with center_header.create(
                    MiniPage(width=NoEscape(r"0.49\textwidth"),
                             pos='c',
                             align='c')) as title_wrapper:
                title_wrapper.append(LargeText(bold(self.__nombre)))

        # Add document title
        with first_page.create(Head("R")) as right_header:
            with right_header.create(
                    MiniPage(width=NoEscape(r"0.49\textwidth"),
                             pos='c',
                             align='r')) as title_wrapper:
                #title_wrapper.append(LargeText(bold("Solemne II")))
                #title_wrapper.append(LineBreak())
                title_wrapper.append(MediumText(bold(
                    Asignatura.get_nombreA())))

        # Add footer
        with first_page.create(Foot("C")) as footer:
            message = "Programación II"
            with footer.create(
                    Tabularx("X X X X", width_argument=NoEscape(
                        r"\textwidth"))) as footer_table:

                footer_table.add_row([
                    MultiColumn(4, align='l', data=TextColor("black", message))
                ])
                footer_table.add_hline(color="black")
                footer_table.add_empty_row()

                branch_address = MiniPage(width=NoEscape(r"0.45\textwidth"),
                                          pos='t',
                                          align='l')
                branch_address.append(
                    MediumText("Facultad de " + Carrera.get_facultad()))
                branch_address.append("\n")
                branch_address.append("")

                branch_address2 = MiniPage(width=NoEscape(r"0.10\textwidth"),
                                           pos='t')
                branch_address2.append("")
                branch_address2.append("\n")
                branch_address2.append("")

                document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                            pos='t',
                                            align='r')
                document_details.append(self.__fecha)
                document_details.append(LineBreak())
                document_details.append("")  # simple_page_number()

                footer_table.add_row([
                    branch_address, branch_address2, branch_address2,
                    document_details
                ])

        doc.preamble.append(first_page)
        # End first page style

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

        ####################################################
        # Add customer information
        with doc.create(Tabu("X[l] X[r]")) as first_page_table:
            customer = MiniPage(width=NoEscape(r"0.55\textwidth"), pos='h')
            customer.append("Nombre: ___________________________________")
            customer.append("\n")
            customer.append("    Rut:  _______________")
            customer.append("\n")
            customer.append("Nota: ______________")
            customer.append("\n")
            customer.append("\n")

            # Add branch information
            branch = MiniPage(width=NoEscape(r"0.35\textwidth"),
                              pos='t!',
                              align='r')

            if self.__unidad == "unidad1":
                branch.append(bold("Unidad: 1"))
            elif self.__unidad == "unidad2":
                branch.append(bold("Unidad: 2"))
            else:
                branch.append(bold("Unidades: 1 & 2"))
            branch.append(LineBreak())

            branch.append(bold("Curso: "))
            branch.append(bold(Curso.get_cod()))
            branch.append(LineBreak())

            branch.append(bold("Ponderación: "))
            branch.append(bold(self.__ponderacion + "%"))
            branch.append(LineBreak())

            first_page_table.add_row([customer, branch])

        doc.append(LargeText(bold("Indicaciones:")))

        # INDICACIONES

        with doc.create(Itemize()) as itemize:
            doc.append(LineBreak())
            itemize.add_item(
                " Lea atentamente los enunciados de cada pregunta antes de contestar."
            )
            itemize.add_item(
                " Conteste su evaluación en silencio, está prohibido conversar o gesticulizar en la sala durante la prueba."
            )
            itemize.add_item(
                " Dispone de 90 minutos para realizar esta evaluación.")
            itemize.add_item(
                " Marque la alternativa con lapiz pasta, no se aceptan marcadas con lapiz grafito."
            )
            itemize.add_item(
                " Utilice solamente sus materiales, está prohibido solicitar materiales a sus compañeros."
            )
            # you can append to existing items
            itemize.append(Command("ldots"))

        doc.change_document_style("firstpage")
        doc.add_color(name="lightgray", model="gray", description="0.80")
        customer.append(LineBreak())

        now = str(datetime.today())

        for p in listaPreguntas:
            with doc.create(Section('Pregunta - ' + p.get_tipo())):

                doc.append(p.get_contenido())

        doc.append(NewPage())

        nombreFile = str(
            self.__nombre) + " - " + self.get_fecha() + " - " + str(aleatorio)

        print(
            "--------------------------ANTES DE DIR------------------------------"
        )

        try:
            # GENERANDO PDF
            doc.generate_pdf(filepath="tests/" + nombreFile,
                             clean_tex=True,
                             clean=True)
            #doc.generate_pdf(dirName + "/" + nombreFile, clean_tex=False)

        except FileNotFoundError as e:
            doc.generate_pdf(filepath="../tests/" + nombreFile,
                             clean_tex=True,
                             clean=True)
예제 #13
0
def report(model=False,
           examples=False,
           tr_pr=False,
           lo_acc=False,
           pr_rec=False,
           score=False,
           conf_matrix=False,
           roc_auc=False,
           auc_pr=False,
           hist=False,
           hist2D=False,
           name=False):

    import numpy as np
    import os
    from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, FlushLeft, MediumText
    from pylatex import Plot, Figure, Matrix, Alignat, MultiColumn, Command, SubFigure, NoEscape, HorizontalSpace
    from pylatex.utils import italic, bold

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

    with doc.create(Section('CLASSIFICATION REPORT', numbering=0)):

        # CNN architecture
        if model == True:
            if os.path.exists('images/model.pdf'):
                model = 'images/model.pdf'
                with doc.create(
                        Subsection('Architecture of the Neural Network',
                                   numbering=0)):
                    with doc.create(Figure(position='!htb')) as loss_acc:
                        loss_acc.add_image(model,
                                           width=NoEscape(r'0.65\textheight'))
            else:
                print("Model architecture image not found! Skipping.")

        # plot some example images
        if examples == True:
            if (os.path.exists('images/TP.pdf')
                    and os.path.exists('images/TN.pdf')):
                example_TP = 'images/TP.pdf'
                example_TN = 'images/TN.pdf'
                with doc.create(
                        Subsection('TP/FP/TN/FN Test Set Examples',
                                   numbering=0)):
                    doc.append(
                        'TP - true positives, TN - true negatives, FP - false positives, FN - False negaties'
                    )
                    with doc.create(Figure(position='!htb')) as imagesRow1:
                        doc.append(Command('centering'))
                        with doc.create(
                                SubFigure(
                                    position='c',
                                    width=NoEscape(
                                        r'0.33\linewidth'))) as left_image:
                            left_image.add_image(
                                example_TP, width=NoEscape(r'0.95\linewidth'))
                            left_image.add_caption("Examples of TP")

                        with doc.create(
                                SubFigure(
                                    position='c',
                                    width=NoEscape(
                                        r'0.33\linewidth'))) as right_image:
                            right_image.add_image(
                                example_TN, width=NoEscape(r'0.95\linewidth'))
                            right_image.add_caption("Examples of TN")

                if (os.path.exists('images/FP.pdf')
                        and os.path.exists('images/FN.pdf')):
                    example_FP = 'images/FP.pdf'
                    example_FN = 'images/FN.pdf'
                    with doc.create(Figure(position='!htb')) as imagesRow2:
                        doc.append(Command('centering'))
                        with doc.create(
                                SubFigure(
                                    position='c',
                                    width=NoEscape(
                                        r'0.33\linewidth'))) as left_image:
                            left_image.add_image(
                                example_FP, width=NoEscape(r'0.95\linewidth'))
                            left_image.add_caption("Examples of FP")

                        with doc.create(
                                SubFigure(
                                    position='c',
                                    width=NoEscape(
                                        r'0.33\linewidth'))) as right_image:
                            right_image.add_image(
                                example_FN, width=NoEscape(r'0.95\linewidth'))
                            right_image.add_caption("Examples of FN")
            else:
                print("Example images not found! Skipping.")

        # True values VS predicted output values
        if tr_pr == True:
            if os.path.exists('images/true_pred.pdf'):
                true_pred = 'images/true_pred.pdf'
                with doc.create(
                        Subsection(
                            'Comparison of True Labes and Output Values for Test Set',
                            numbering=0)):
                    with doc.create(Figure(position='!htb')) as tr_pr:
                        tr_pr.add_image(true_pred, width='200px')
            else:
                print(
                    "Image comparing true labes and output values not found! Skipping."
                )

        # True values VS predicted output values
        if lo_acc == True:
            if os.path.exists('images/loss_acc.pdf'):
                lo_acc = 'images/loss_acc.pdf'
                with doc.create(
                        Subsection('Training and Validation Loss and Accuracy',
                                   numbering=0)):
                    with doc.create(Figure(position='!htb')) as loss_acc:
                        loss_acc.add_image(lo_acc, width='260px')
            else:
                print("Loss Accuracy plot not found! Skipping.")

        # Training precision / recall
        if pr_rec == True:
            if os.path.exists('images/prec_recall.pdf'):
                pr_rec = 'images/prec_recall.pdf'
                with doc.create(
                        Subsection('Test Set Precission and Recall',
                                   numbering=0)):
                    doc.append(
                        '''Precision/Recall curve shows the trade-off between returning 
                        accurate results (high precision), as well as returning a majority of all positive results (high 
                        recall) for different tresholds. It should be used when class imbalance problem occurs. A model with 
                        perfect classification skill is depicted as a point at (1,1). Area Under the Curve (AUC)
                        for the perfect classifier will be 1.''')
                    with doc.create(Figure(position='!htb')) as pre_recall:
                        pre_recall.add_image(pr_rec, width='220px')
                        doc.append(HorizontalSpace("2cm"))
                        doc.append(MediumText('AUC = ' + str(auc_pr)))
            else:
                print("Precision Recall plot not found! Skipping.")

        # plot confusion matrix
        if conf_matrix == True:
            if os.path.exists('images/conf.pdf'):
                conf_matrix = 'images/conf.pdf'
                with doc.create(
                        Subsection('Test Set Confusion Matrix', numbering=0)):
                    with doc.create(Figure(position='!htb')) as conf:
                        conf.add_image(conf_matrix, width='230px')
            else:
                print("Confusion matrix not found! Skipping.")

        # all scoring matrics
        if score == True:
            if os.path.exists('images/scoring.npy'):
                scoring = np.load('images/scoring.npy')
                acc = scoring[0]
                precision = scoring[1]
                recall = scoring[2]
                f1 = scoring[3]
                brier = scoring[4]
                with doc.create(
                        Subsection('Classification Scoring for Test Set',
                                   numbering=0)):
                    doc.append(
                        'TP - true positives, TN - true negatives, FP - false positives, FN - False negaties \n\n'
                    )
                    doc.append(
                        'The performance of a classifier can be described by:\n'
                    )
                    doc.append(bold('Accuracy '))
                    doc.append(' - (TP+TN)/(TP+TN+FP+FN) \n')
                    doc.append(bold('Precision '))
                    doc.append(
                        ' (Purity, Positive Predictive Value) - TP/(TP+FP) \n')
                    doc.append(bold('Recall '))
                    doc.append(
                        ' (Completeness, True Positive Rate - TP/(TP+FN) \n ')
                    doc.append(bold('F1 Score '))
                    doc.append(
                        ' = 2 (Precision * Recall)/(Precision + Recall).\n')
                    doc.append(bold('Brier Score '))
                    doc.append(
                        ''' - mean squared error (MSE) between predicted probabilities (between 0 and 1) and the 
                        expected values (0 or 1). Brier score summarizes the magnitude of the forecasting error and takes a 
                        value between 0 and 1 (with better models having score close to 0).\n\n'''
                    )
                    with doc.create(Tabular('|l|l|')) as table:
                        table.add_hline()
                        table.add_row((bold('Metric'), bold('Score')))
                        table.add_hline()
                        table.add_row(('Accuracy', '%.2f' % acc))
                        table.add_row(('Precision', '%.2f' % precision))
                        table.add_row(('Recall', '%.2f' % recall))
                        table.add_row(('F1 Score', '%.2f' % f1))
                        table.add_row(('Brier Score', '%.2f' % brier))
                        table.add_hline()
                    doc.append('\n\n')
            else:
                print("Scoring file not found! Skipping.")

        # plot ROC and AUC
        if roc_auc == True:
            if (os.path.exists('images/ROC.pdf')
                    and os.path.exists('images/auc.npy')):
                roc = 'images/ROC.pdf'
                auc_save = np.load('images/auc.npy')
                auc = auc_save
                with doc.create(
                        Subsection(
                            'Reciever Operating Characteristic (ROC) and Area Under the Curve (AUC) for Test Set',
                            numbering=0)):
                    doc.append(
                        '''The ROC curve graphically shows the trade-off between between 
                    true-positive rate and false-positive rate.The AUC summarizes the ROC curve - where the 
                    AUC is close to unity, classification is successful, while an AUC of 0.5 indicates the 
                    model is performs as well as a random guess.''')
                    with doc.create(Figure(position='!htb')) as roc_curve:
                        roc_curve.add_image(roc, width='220px')
                        doc.append(HorizontalSpace("2cm"))
                        doc.append(
                            MediumText('AUC = ' + str(auc) +
                                       '\n\n\n\n\n\n\n\n'))
            else:
                print("Roc curve image and/or AUC not found! Skipping.")

        # plot histogram of output values
        if hist == True:
            if os.path.exists('images/histogram.pdf'):
                hist = 'images/histogram.pdf'
                with doc.create(
                        Subsection(
                            'Histogram of the Output Probabilities for Test Set',
                            numbering=0)):
                    with doc.create(Figure(position='!htb')) as histogram:
                        histogram.add_image(hist, width='230px')
            else:
                print("Histogram image not found! Skipping.")

        # plot 2D histogram of output values and some object parameter
        if hist2D == True:
            if os.path.exists('images/2Dhistogram.pdf'):
                hist_2d = 'images/2Dhistogram.pdf'
                with doc.create(
                        Subsection(
                            '2D Histogram of the Output vs One Object Feature for Test Set',
                            numbering=0)):
                    with doc.create(Figure(position='!htb')) as histogram_2d:
                        histogram_2d.add_image(hist_2d, width='230px')
            else:
                print("2D Histogram image not found! Skipping.")

    if name == False:
        doc.generate_pdf('report', clean_tex=False)
    else:
        doc.generate_pdf(name, clean_tex=False)
    return
예제 #14
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=120px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Bank Account Statement")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Date")))

    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(
                Tabularx(
                    "X X X X",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_row(
                [MultiColumn(4, align='l', data=TextColor("blue", message))])
            footer_table.add_hline(color="blue")
            footer_table.add_empty_row()

            branch_address = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                      pos='t')
            branch_address.append("960 - 22nd street east")
            branch_address.append("\n")
            branch_address.append("Saskatoon, SK")

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append("1000")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([
                branch_address, branch_address, branch_address,
                document_details
            ])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        customer.append("Verna Volcano")
        customer.append("\n")
        customer.append("For some Person")
        customer.append("\n")
        customer.append("Address1")
        customer.append("\n")
        customer.append("Address2")
        customer.append("\n")
        customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')
        branch.append("Branch no.")
        branch.append(LineBreak())
        branch.append(bold("1181..."))
        branch.append(LineBreak())
        branch.append(bold("TIB Cheque"))

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(
            ["date", "description", "debits($)", "credits($)", "balance($)"],
            mapper=bold,
            color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()
        row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
        for i in range(30):
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.append(NewPage())

    # Add cheque images
    with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
        cheque_file = os.path.join(os.path.dirname(__file__),
                                   'chequeexample.png')
        cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
        for i in range(0, 20):
            cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
예제 #15
0
with doc.create(MiniPage(width=r"\textwidth")) as page:
    with page.create(TextBlock(100, 0, 0)):
        page.append("**** Ten Thousand Dollars")

    with page.create(TextBlock(100, 0, 30)):
        page.append("COMPANY NAME")
        page.append("\nSTREET, ADDRESS")
        page.append("\nCITY, POSTAL CODE")

    with page.create(TextBlock(100, 150, 40)):
        page.append(HugeText(bold("VOID")))

    with page.create(TextBlock(80, 150, 0)):
        page.append("DATE")
        page.append(MediumText(bold("2016 06 07\n")))
        page.append(HorizontalSpace("10mm"))
        page.append(SmallText("Y/A M/M D/J"))

    with page.create(TextBlock(70, 150, 30)):
        page.append(MediumText(bold("$***** 10,000.00")))

    page.append(VerticalSpace("100mm"))

doc.generate_pdf("textblock", clean_tex=False)
"""
Asked for 1 installation when I ran the code
"""
"""
rishikesh agrawani@DESKTOP-8AATOO4 MINGW64 /d/projects/Python/PyLaTex (master)
$ cd 17_textblock_example/
예제 #16
0
    def fill(self):
        # with self.doc.create(Section("{} library.".format(self.config['hdl_library_name']))):
        # with self.doc.create(Section("{} library".format(self.periph_lib_name))):
        # main_section = Section("{} library".format(self.periph_lib_name))
        # self.doc.append(LargeText(bold('{} library'.format(self.periph_lib_name))))
        # periph_section = Section("Peripherals", numbering = False)
        # i = 1
        # for periph_name in self.periph_lib['peripherals'].keys():
        # self.doc.append("{} {}".format(str(i), periph_name))
        # i = i+1
        # self.doc.append(NewLine())
        # with self.doc.create(Section("Peripherals")):
        added_instances = []
        # for peri_info in self.config['peripherals']:
        # peri_class = Peripheral(peri_info)
        for periph_name, periph in self.periph_lib['peripherals'].items():
            if periph_name in added_instances:
                continue
            added_instances.append(periph_name)

            # with self.doc.create(Section(periph_name, numbering=True)):
            # with self.doc.create(Subsection(periph_name, numbering=True)):
            # self.doc.append(peri_class.get_kv('peripheral_description').replace('"', ''))
            self.doc.append(NewPage())
            periph_subsection = Section(periph_name, numbering=True)
            periph_subsection.append(periph.get_description().replace(
                '""', ''))

            # Peripheral System Map Table
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_subsection.append(MediumText(bold('Local Slave Port Map')))
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_system_table = Tabular('|c|c|c|c|')
            # periph_system_table.add_row((MultiColumn(4,data=MediumText(bold('System Map'))),))
            periph_system_table.add_hline()
            periph_system_table.add_row(
                ('Hex', 'Range (Bytes)', 'Slave Port', 'Protocol'))
            periph_system_table.add_hline()

            # peripheral system address map
            dummyFPGA = FPGA(None)
            dummyFPGA.peripherals.update({periph_name: periph})
            dummyFPGA.create_address_map()
            # for slave in periph.slaves:
            for slave_port, slave_dict in dummyFPGA.address_map.items():
                periph_system_table.add_row(
                    (str(hex(slave_dict['base'])), str(slave_dict['span']),
                     slave_port, slave_dict['type']))
                periph_system_table.add_hline()
            periph_subsection.append(periph_system_table)

            # self.doc.append(periph.get_description().replace('""',''))
            # self.doc.append(NewLine())

            #self.doc.append(MediumText(bold("slave ports.")))

            # for val_info, val_type in ((periph.registers, 'Registers'),
            # (periph.rams, 'Rams'),
            # (periph.fifos, 'Fifos')):
            periph_reg_section = Subsection(
                "{} register slave".format(periph_name), numbering=False)
            periph_reg_table = Tabular('|c|c|c|c|')
            periph_reg_table.add_hline()
            periph_reg_table.add_row(('Base Address', 'Range',
                                      'Register group', 'Number of Slaves'))
            periph_reg_table.add_hline()
            # slave_subsections = ("{} slaves".format(periph_name), numbering=False)
            # slave_subsections = []
            # slave_subsections.append(NewLine())
            # slave_subsections.append(MediumText(bold("Slave Ports for peripheral " + periph_name + "\n")))
            slave_subsections = Subsection(
                "Slave Ports for peripheral \'{}\'".format(periph_name),
                numbering=False)
            for slave in periph.slaves:

                # if len(val_info) == 0: # not sure what this is for
                # continue

                #self.doc.add(text=val_type, size="medium")

                # added_val_types = []
                # for key, val in sorted(val_info.items()):
                # if val.name() in added_val_types:
                # continue
                # added_val_types.append(val.name())
                slave_subsection = Subsection("Slave Port: {} ({})".format(
                    slave.name(),
                    'Register block' if isinstance(slave, Register) else
                    'RAM' if isinstance(slave, RAM) else 'FIFO'),
                                              numbering=True)
                slave_subsection.append(slave.get_kv('slave_description'))
                slave_subsection.append(NewLine())
                # slave_subsection.append("Slave Type: {}".format('REGISTER' if isinstance(slave, Register) else 'RAM' if isinstance(slave, RAM) else 'FIFO'))
                slave_subsection.append(NewLine())
                slave_subsection.append("Address Length: {}".format(
                    str(slave.address_length())))
                slave_subsection.append(NewLine())
                slave_subsection.append("Number of Slaves: {}".format(
                    str(slave.number_of_slaves())))
                slave_subsection.append(NewLine())
                slave_subsection.append(NewLine())

                # if val_type == 'Registers':
                if isinstance(slave, Register):  # expand registers and fields
                    for ram in slave.rams:
                        periph_reg_table.add_row(
                            (str(ram.base_address()),
                             str(ram.number_of_fields() * WIDTH_IN_BYTES),
                             ram.name() + ' (RAM)',
                             str(slave.number_of_slaves())))
                        periph_reg_table.add_hline()
                    periph_reg_table.add_row(
                        (str(slave.base_address()),
                         str(slave.address_length()), slave.name(),
                         str(slave.number_of_slaves())))
                    periph_reg_table.add_hline()
                    added_field_groups = []
                    # with self.doc.create(Subsection("{} Register Fields".format(val.name().lower()), numbering=True)):
                    # if val.get_kv('slave_description') is not None:
                    # slave_subsection.append(val.get_kv('slave_description').replace('"', ''))

                    # generate register table i.e. by word
                    group_address = -1
                    group_list = []
                    for field in slave.fields:
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            group_list.append(field)
                            # addr_name = field.group_name() if field.group_name() != "None" else field.name()

                            # slave_table.add_row(str(hex(field.address_offset())), addr_name)
                            # slave_table.add_hline()
                    c_max_rows = 30
                    nof_cols = ceil(
                        len(group_list) / c_max_rows
                    )  # register table has max length of c_max_rows
                    nof_rows = min(len(group_list), c_max_rows)
                    slave_table = Tabular('|c|c|' * nof_cols)
                    slave_table.add_hline()
                    slave_table.add_row(['Hex', 'Field Group'] * nof_cols)
                    # slave_table.add_row((*['Hex','Field Group']*nof_cols))
                    slave_table.add_hline()
                    for i in range(nof_rows):
                        row = []
                        for j in range(nof_cols):
                            if i + c_max_rows * j < len(group_list):
                                field.group_name() if field.group_name(
                                ) != "None" else field.name()
                                row.extend([
                                    str(
                                        hex(group_list[i + c_max_rows *
                                                       j].address_offset())),
                                    group_list[i + c_max_rows * j].name()
                                ])
                            else:
                                row.extend(['', ''])
                        slave_table.add_row(row)
                        # slave_table.add_row(*row)
                        slave_table.add_hline()

                    slave_subsection.append(slave_table)
                    slave_subsection.append(NewPage())

                    group_address = -1
                    for field in slave.fields:
                        # if field.group_name() is None or field.group_name() != last_group: # base on group_address instead
                        # print("field {} address {} bit{}".format(field.name(), str(field.address_offset()), str(field.bit_offset())))
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            # group_page = MiniPage()
                            group_subsection = Subsection('{} {}'.format(
                                str(hex(field.address_offset())),
                                field.name() if field.group_name() == 'None'
                                else field.group_name()),
                                                          numbering=False)
                            group_fields = [
                                field for field in slave.fields
                                if field.address_offset() == group_address
                            ]
                            if len(group_fields) > 10:
                                slave_subsection.append(NewPage())
                            group_subsection = gen_reg_tables(
                                group_subsection, group_fields)
                            for field in group_fields[::-1]:
                                field_name = field.name() if field.group_name(
                                ) == 'None' else field.name().split(
                                    field.group_name() + '_')[-1]
                                bit_string = "Bit {}".format(
                                    str(field.bit_offset())) if field.width(
                                    ) == 1 else "Bits {}:{}".format(
                                        str(field.bit_offset() +
                                            field.width() -
                                            1), str(field.bit_offset()))
                                group_subsection.append(
                                    bold("{}\t\t{} ({}):".format(
                                        bit_string, field_name,
                                        field.access_mode())))
                                group_subsection.append("\t\t{}".format(
                                    field.field_description()))
                                group_subsection.append(NewLine())
                                group_subsection.append(NewLine())
                            # group_page.append(group_subsection)
                            slave_subsection.append(group_subsection)
                else:  # RAM or FIFO
                    slave_subsection.append("Data width: {}".format(
                        slave.width()))
                    slave_subsection.append(NewLine())
                    if isinstance(slave, RAM):
                        slave_subsection.append("User data width: {}".format(
                            slave.user_width()))

                slave_subsections.append(slave_subsection)
            periph_reg_section.append(periph_reg_table)
            self.doc.append(periph_subsection)
            if any([isinstance(slave, Register) for slave in periph.slaves]):
                self.doc.append(periph_reg_section)
            # for i in range(len(slave_subsections)):
            # self.doc.append(slave_subsections[i])
            self.doc.append(slave_subsections)

            # self.doc.append(periph_section)
            self.doc.append(NewPage())
예제 #17
0
def generate_report(main_title, name, title, email, payroll):

    # For saving the report in the Desktop folder
    dir_output=os.path.join(
        '~',
        'Desktop',
        'absconbest_payroll',
        'output'
    )
    dir_output=os.path.expanduser(dir_output)
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating
    # first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
            MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c')
        ) as logo_wrapper:
            logo_file = 'logo.png'
            logo_wrapper.append(
                StandAloneGraphic(
                    image_options="width=120px",
                    filename=logo_file
                )
            )

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(MiniPage(
            width=NoEscape(r"0.49\textwidth"),
            pos='c',
            align='r')
        ) as title_wrapper:
            title_wrapper.append(LargeText(bold('Payroll Report')))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold(main_title)))

    # Add footer
    with first_page.create(Foot("C")):
        first_page.append(simple_page_number())

    doc.preamble.append(first_page)

    #Add employee information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        employee = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        employee.append(name)
        employee.append("\n")
        employee.append(title)
        employee.append("\n")
        employee.append(email)

        #Dummy table
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
                          align='r')
        # branch.append(bold("1181..."))
        # branch.append(LineBreak())
        # branch.append(bold("TIB Cheque"))

        first_page_table.add_row([employee, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    #Add payroll table
    with doc.create(LongTabu("X[l] X[c] X[c] X[c] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(['Work',
                            'Rate Per Hour ($)',
                            'Time in Minutes',
                            'Time in Hours',
                            'Wage ($)'],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()

        #Following Pandas' API
        payroll=payroll.reset_index()
        for i in range(len(payroll.index)):
            try:
                row = [payroll['Work'][i],
                       round(payroll['Rate Per Hour'][i],0),
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            except TypeError:
                row = [payroll['Work'][i],
                       'n/a',
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            if (i%2)==0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)
        # data_table.add_row([payroll['Work'][l_p],
        #                     round(payroll['TIM'][l_p],0),
        #                     round(payroll['TIH'][l_p],3),
        #                     '',
        #                     round(payroll['Wage'][l_p],1)]
        # )

    doc.append(NewPage())

    doc.generate_pdf(
        filepath=os.path.join(
dir_output,
            main_title.lower().replace(" ","_").replace(",",""),
        ),
        clean_tex=True,
        clean=True,
    )
예제 #18
0
    def create(self):
        try:
            self.status['text'] = 'Загрузка, подождите'
            self.root.update()
            # Настройки отступов, языка
            geometry_options = {
                "tmargin": "2cm",
                "lmargin": "3cm",
                "rmargin": "1.5cm",
                "bmargin": "2cm"
            }
            doc = Document(geometry_options=geometry_options)
            doc.packages.add(
                Package('grffile',
                        options=['encoding', 'filenameencoding=utf8']))
            doc.packages.add(Package('babel', options=['russian']))

            # Вставляем логотип МИРЭА
            image_filename = os.path.join(os.path.dirname(__file__),
                                          'логотип.png')
            with doc.create(Figure(position='h!')) as logo:
                logo.add_image(image_filename, width='80px')

            # Обложка
            doc.change_length(r"\TPHorizModule", "1mm")
            doc.change_length(r"\TPVertModule", "1mm")
            with doc.create(MiniPage(width=r"\textwidth")) as page:
                # Центральная часть обложки
                with page.create(TextBlock(180, 0, 0)):
                    page.append(Command('centering'))
                    page.append('МИНОБРНАУКИ РОССИИ\n')
                    page.append(
                        'Федеральное государственное бюджетное образовательное учреждение высшего образования\n'
                    )
                    page.append(
                        MediumText(
                            bold(
                                '«МИРЭА - Российский Технологический Университет»\n'
                            )))
                    page.append(LargeText(bold('РТУ МИРЭА\n')))
                    page.append(LineBreak())
                    page.append(
                        MediumText(
                            bold(
                                'Институт комплексной безопасности и специального приборостроения\n'
                            )))
                    page.append(LineBreak())
                    page.append(
                        'Кафедра КБ-8 «Информационное Противоборство»\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LargeText('Отчёт\n'))
                    page.append(f'{str(self.entry1.get())}\n')

                # Правая часть обложки
                with page.create(TextBlock(80, 88, 120)):
                    if self.your_var.get() == 0:
                        page.append('Выполнил:\n')
                        page.append(
                            f'Студент {str(self.entry2.get())} курса\n')
                    else:
                        page.append('Выполнила:\n')
                        page.append(
                            f'Студентка {str(self.entry2.get())} курса\n')
                    page.append(f'Группа {str(self.entry3.get())}\n')
                    page.append(f'Шифр {str(self.entry4.get())}\n')
                    page.append(f'{str(self.entry5.get())}\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    if self.var.get() == 0:
                        page.append('Проверил:\n')
                    else:
                        page.append('Проверила:\n')
                    page.append(f'{str(self.entry6.get())}\n')

            # Нижний колонтитул
            header = PageStyle("header")
            with header.create(Foot("C")):
                header.append(f'Москва, {time.now().timetuple().tm_year}\n')
            doc.preamble.append(header)
            doc.change_document_style("header")

            doc.generate_pdf("title", clean_tex=False)
            self.status['text'] = 'Готово!'

        except FileNotFoundError as e:
            self.status['text'] = str(e)
예제 #19
0
    def portada(Diccionario, eficiencia,T_Hornilla):
        global doc
        doc = Document()
        geometry_options = {"tmargin": "4cm", "rmargin": "2cm", "lmargin": "4cm", "bmargin": "3cm"} 
        doc = Document(geometry_options=geometry_options)
        doc.packages.append(Package('babel', options=['spanish']))
        doc.packages.append(Package('background', options=['pages=all']))
        doc.packages.append(NoEscape('\\backgroundsetup{placement=center,\n angle=0, scale=1, contents={\includegraphics{Membrete.pdf}}, opacity=1}\n'))   
        
        with doc.create(Center()) as centered:
                    centered.append(TextColor('white','HH')) 
                    for i in range(10):
                        centered.append(LineBreak())   
                    centered.append(HugeText('PROPUESTA DE VALOR PARA LA CONSTRUCCIÓN DE UNA HORNILLA '))
                    centered.append(LineBreak()) 
                    centered.append(SmallText('(Generado por HornillAPP)'))
                    for i in range(8):
                        centered.append(LineBreak()) 
                    
        with doc.create(Figure(position='h!')) as imagesRow1:
            with doc.create(SubFigure(
                    position='b',
                    width=NoEscape(r'1\linewidth'))) as left_imagesRow1:
                left_imagesRow1.add_image('IconoAPP.png')
            imagesRow1.append(LineBreak())
                                    
        with doc.create(Center()) as centered:
                    centered.append(TextColor('white','HH')) 
                    for i in range(8):
                        centered.append(LineBreak())
                    #centered.append(VerticalSpace('50')) 
                    centered.append(LargeText('Presentado por: AGROSAVIA'))
                    centered.append(LineBreak())
                    centered.append(SmallText('(Corporación Colombiana de Investigación Agropecuaria)'))
        doc.append(NewPage())
        
        with doc.create(MediumText(' ')) as tlg:
                    tlg.append(TextColor('white','HH')) 
                    tlg.append(LineBreak())
                    tlg.append('Bogotá D.C., ')
                    tlg.append(Command(' ',NoEscape('\\today')))
                    tlg.append('\n \n') #Salto de línea en parráfo
                    tlg.append(LineBreak()) #Salto de línea en parráfo
                    tlg.append('\nSeñor (es):') 
                    tlg.append('\n'+str(Diccionario['Nombre de usuario']))
                    if(str(Diccionario['Departamento'])=='--'):
                        tlg.append('\n'+str(Diccionario['Pais'])+'.')    
                    else:
                        tlg.append('\n'+str(Diccionario['Ciudad'])+', '+str(Diccionario['Departamento'])+'.')
                    tlg.append('\n \n') #Salto de línea en parráfo
                    tlg.append('\nApreciado(s) productor(es):')
                    tlg.append('\n \n') #Salto de línea en parráfo
                    Parrafo= ('Con base en la información suministrada, está aplicación propone (ver Sección 1) la construcción de una hornilla '+
                              T_Hornilla+' con capacidad de '+ str(Diccionario['Capacidad estimada de la hornilla']) +' kg/h'+' (la eficiencia estimada de la hornilla es del '+ str(round(Diccionario['Eficiencia de la hornilla']))+'%) '+'; adecuada para el procesamiento de hasta '+
                              str(Diccionario['Área cosechada al mes'])+
                              ' ha'+' de caña, con una producción de panela '+ str(round(float(Diccionario['Producción de panela por molienda [t]'])))+
                              ' t por molienda y un periodo vegetativo de '+ str(Diccionario['Periodo vegetativo'])+' meses. Teniendo en cuenta que'+
                              ' se realizan '+str(Diccionario['Número de moliendas al año'])+' moliendas al año se estableció una jornada laboral de '+
                              str(Diccionario['Días de trabajo de la hornilla por semana'])+ ' días a la semana de '+str(Diccionario['Horas de trabajo de la hornilla por día'])+ ' horas laborables cada una.'+
                              '\n Además, la aplicación estima que para garantizar una operación apropiada de la hornilla '+
                              ' se requiere de un área disponible de al menos '+str(round(Diccionario['Capacidad estimada de la hornilla']*4.3))+' m²'
                              )
                    tlg.append(Parrafo)                
                    Parrafo= (', cuya productividad puede aumentar al incorporar el sistema de recuperación de calor (hasta '+str(round(Diccionario['Capacidad estimada de la hornilla']+25))+' kg/h) como se muestra en las tablas del análisis financiero y al final del informe.'
                              +' No obstante, la corporación ofrece los siguientes servicios de asistencia técnica para ajustar los valores provistos en esta propuesta de valor:'
                              )
                    tlg.append(Parrafo)
                    
                    with tlg.create(Itemize()) as itemize:
                        itemize.add_item('Estudio detallado para la construcción e instalación de la hornilla.')
                        itemize.add_item('Al menos tres visitas técnicas de dos funcionarios de AGROSAVIA para la puesta en marcha y '+
                                         'capacitación de los operarios en el manejo de la hornilla y en la producción de panela '+
                                         'saborizada, granulada o moldeada en presentación pastilla de chocolate.')
                        itemize.add_item('Entrega de un ejemplar de la guía tecnológica para el manejo integral del sistema '+
                                         'productivo de la caña panelera y una para el mantenimiento de la hornilla.')

                    Parrafo= ('Cualquier inquietud AGROSAVIA está presta a atenderla.\n'+
                              'Cordial saludo.\n'+
                              '\n \n \n'+
                              'AGROSAVIA (Corporación colombiana de investigación agropecuaria)')            
                    tlg.append(Parrafo)            

                    Parrafo= ('\n \n Nota: Está propuesta de valor se basa en condiciones del terreno ideales y estacionarias, por lo que, '+
                              'AGROSAVIA no se hace responsable de la reproducción total o parcial del material aquí suministrado sin una aprobación '+
                              'corporativa.')
                    tlg.append(Parrafo)
                    
        doc.append(NewPage())
        
        with doc.create(MediumText(' ')) as tlg:
                    tlg.append(LargeText(bold('Contenido')))
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Sección 1')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Información del usuario.')
                                                        item.add_item('Características de la caña sembrada.')
                                                        item.add_item('Características del molino.')
                                                        item.add_item('Consideraciones generales para el manejo de la hornilla.')
                                                        item.add_item('Análisis financiero.')
                                            itemize.add_item('Sección 2')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Diagramas mecánicos de la hornilla.')
                                                        item.add_item('Diagramas mecánicos de la camára.')
                                                        item.add_item('Diagramas mecánicos de la chimenea.')
                                                        item.add_item('Diagramas mecánicos del ducto.')
                                                        item.add_item('Diagramas mecánicos de la hornilla con recuperador de calor.')
        doc.append(NewPage())

        #PORTADA PARA LA SECCIÓN 1 
        
        with doc.create(Center()) as centered:
                    centered.append(TextColor('white','HH')) 
                    for i in range(15):
                        centered.append(LineBreak())   
                    centered.append(HugeText('SECCIÓN 1:'))
                    centered.append(LineBreak())
                    centered.append(HugeText('INFORMACIÓN TÉCNICA Y FINANCIERA')) 
        doc.append(NewPage())
예제 #20
0
def generate_unique(cpm):
    geometry_options = {
        "head": "60pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    first_page = PageStyle("firstpage")

    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='L')) as logo_wrapper:
            logo_file = os.path.join(current_app.root_path,
                                     "static/logo/sf.png")
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=120px",
                                  filename=logo_file))

    with first_page.create(Head("R")) as header_right:
        with header_right.create(
                MiniPage(width=NoEscape(r'0.49\textwidth'), pos='c',
                         align='r')) as wrapper_right:
            wrapper_right.append(LargeText(bold('SOCIALFISH')))
            wrapper_right.append(LineBreak())
            wrapper_right.append(MediumText(bold('UNDEADSEC')))
            wrapper_right.append(LineBreak())
            wrapper_right.append(NoEscape(r'\today'))

    with first_page.create(Head('C')) as header_center:
        header_center.append('CAPTURE REPORT')

    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"

    doc.preamble.append(first_page)

    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')

        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    with doc.create(LongTabu("X[15l]", row_height=1.8)) as data_table:
        data_table.add_row(["Organization\nCapture IP\nBrowser\nLog\n"],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()

        result_query, result_count = generate_report(cpm)
        x = 0

        for i in range(result_count):

            url = result_query[1 + x].split('//')[1]
            ip = result_query[7 + x]
            log_dict = literal_eval(result_query[2 + x])

            if 'skstamp' in log_dict.keys():
                rm_trash = log_dict.pop('skstamp')
            elif 'utf8' in log_dict.keys():
                rm_trash = log_dict.pop('utf8')

            browser = result_query[4 + x] + ' v' + result_query[5 + x]
            x = 8 * (i + 1)

            row_tex = [
                url + '\n' + ip + '\n' + browser + '\n' + str(log_dict) + '\n'
            ]

            if (i % 2) == 0:
                data_table.add_row(row_tex, color="lightgray")
            else:
                data_table.add_row(row_tex)

    doc.append(NewPage())
    pdf_name = 'Report{}'.format(strftime('-%y%m'))
    doc.generate_pdf(pdf_name, clean_tex=False)
    open_new(os.getcwd() + '/' + pdf_name + '.pdf')
예제 #21
0
    # Header
    with doc.create(Center()) as centered:
        centered.append(FootnoteText(bold(lorem(4))))
        centered.append(FootnoteText(lorem(12)))
        centered.append(LineBreak())
        centered.append(FootnoteText(lorem(19)))
        centered.append(LineBreak())
        centered.append(FootnoteText(lorem(17)))
        centered.append(LineBreak())
        centered.append(FootnoteText(lorem(17)))

        centered.append(LineBreak())
        centered.append(LineBreak())

        centered.append(MediumText(bold(lorem(5))))

    # Title
    doc.append(HorizontalSpace("250pt"))

    with doc.create(Tabular(table_spec="|l r|", row_height=1.8)) as data_table:
        data_table.add_hline()
        data_table.add_row(
            [MediumText(bold(lorem(3))),
             MediumText(bold("XXXXXXXXXXXXXX"))])
        data_table.add_hline()

    doc.append(HorizontalSpace("160pt"))

    with doc.create(Tabular(table_spec="|c|", row_height=1.8)) as date_table:
        date_table.add_hline()
예제 #22
0
def report(context, json_report, json_varreport, rulegraph_img):

    config = json_report
    sample_config = json.load(open(json_report))
    var_config = json.load(open(get_config(json_varreport)))

    tex_path = os.path.abspath(
        os.path.join(sample_config["analysis"]["analysis_dir"],
                     "delivery_report"))

    if not rulegraph_img:
        rulegraph_img = sample_config['analysis']['dag']

    os.makedirs(tex_path, exist_ok=True)

    geometry_options = {
        "head": "40pt",
        "headheight": "130pt",
        "headsep": "1cm",
        "margin": "1.5cm",
        "bottom": "1.5cm",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    doc.packages.append(Package('lscape'))
    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('float'))
    doc.packages.append(Package('caption', options='labelfont=bf'))
    doc.append(
        NoEscape(
            r'\captionsetup[table]{labelsep=space, justification=raggedright, singlelinecheck=off}'
        ))

    #Add first page style
    first_page = PageStyle("header", header_thickness=1)

    #Add Header
    with first_page.create(Head("C")) as mid_header:

        with mid_header.create(
                MiniPage(width=NoEscape(r"0.2\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__), '..',
                                     'assests/cg.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

        with mid_header.create(
                Tabularx(
                    "p{3cm} p{2cm} X X p{4cm} p{3cm}",
                    width_argument=NoEscape(r"0.8\textwidth"))) as mid_table:
            mid_table.add_row(
                [MultiColumn(6, align='r', data=simple_page_number())])
            mid_table.add_row([
                MultiColumn(6,
                            align='c',
                            data=MediumText("Molecular report on"))
            ])
            mid_table.add_row([
                MultiColumn(6,
                            align='c',
                            data=MediumText(get_sample_name(config)))
            ])
            mid_table.add_empty_row()
            mid_table.add_row([
                'gender', "NA", " ", " ", 'Sample recieved:',
                sample_config['analysis']['date']['sample_received']
            ])
            mid_table.add_row([
                'tumor type', "NA", " ", " ", 'Analysis completion:',
                sample_config['analysis']['date']['analysis_finish']
            ])
            mid_table.add_row([
                'analysis type', "NA", " ", " ", 'PDF Report date:',
                datetime.now().strftime("%Y-%m-%d %H:%M")
            ])
            mid_table.add_row(
                ['sample type', "NA", " ", " ", 'Delivery date', "NA"])
            mid_table.add_row([
                'sample origin', "NA", " ", " ", 'Analysis:',
                r'BALSAMIC v' + sample_config['analysis']['BALSAMIC']
            ])

    doc.preamble.append(first_page)

    #End First page

    #    doc.preamble.append(
    #        Command(
    #            'title',
    #            NoEscape(r'BALSAMIC v' + sample_config["analysis"]["BALSAMIC"] +
    #                     r'\\ \large Developer Report')))
    #    doc.preamble.append(
    #        Command('author', 'Patient ID: ' + get_sample_name(config)))
    #    doc.preamble.append(Command('date', NoEscape(r'\today')))
    #    doc.append(NoEscape(r'\maketitle'))
    doc.change_document_style("header")

    with doc.create(Section(title='Analysis report', numbering=True)):

        with doc.create(
                Subsection('Summary of variants and variant callers',
                           numbering=True)):
            doc.append(
                "Placeholder for text about BAM alignment metrics and variant callers. Here comes the info on reads, "
                +
                "QC metrics, align metrics, and general sample information. preferabily in table format."
            )
            doc.append("\n")

            summary_tables = ["TMB", "VarClass", "VarCaller", "VarCallerClass"]
            for i in summary_tables:

                shellcmd = [
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "..", "..", "scripts/VariantReport.R")
                ]
                shellcmd.extend([
                    "--infile", sample_config["vcf"]["merged"]["SNV"],
                    "--genomeSize", sample_config["bed"]["genome_size"],
                    "--type", "latex", "--mode", i, "--outfile",
                    os.path.join(tex_path,
                                 sample_config['analysis']['sample_id'])
                ])
                print(" ".join(shellcmd))

                outTab = subprocess.check_output(shellcmd)
                doc.append(
                    NoEscape(
                        outTab.decode('utf-8').replace("\\centering",
                                                       "\\small")))
            doc.append(NoEscape(r'\normalsize'))
            doc.append(NewPage())

        with doc.create(Subsection("Summary of MVL report", numbering=True)):
            doc.append(
                "Placeholder for general description of MVL settings. A mention to summary "
                +
                "pipeline, summary of MVL settings. Gene coverage for identified genes should go here. Figures!"
            )
            outCov = dict()

            cmd_param = defaultdict(list)
            J = defaultdict(list)
            for i in var_config["filters"]:
                cmd_param["TUMOR_DP"].append(
                    var_config["filters"][i]["TUMOR"]["DP"])
                cmd_param["TUMOR_AD"].append(
                    var_config["filters"][i]["TUMOR"]["AD"])
                cmd_param["TUMOR_AFmax"].append(
                    var_config["filters"][i]["TUMOR"]["AF_max"])
                cmd_param["TUMOR_AFmin"].append(
                    var_config["filters"][i]["TUMOR"]["AF_min"])
                cmd_param["TUMOR_inMVL"].append(
                    var_config["filters"][i]["in_mvl"])
                cmd_param["var_type"].append(",".join(
                    ["SNP", "INDEL", "MNP", "OTHER"]))
                cmd_param["varcaller"].append(",".join(
                    var_config["filters"][i]["variantcaller"]))
                cmd_param["ann"].append(
                    ",".join(var_config["filters"][i]["annotation"]["SNV"]) +
                    "," +
                    ",".join(var_config["filters"][i]["annotation"]["INDEL"]))
                cmd_param["name"].append(i.replace("_", "\_"))
                cmd_param["outfile_tex"].append(tex_path + "/" + i + ".tex")
                cmd_param["outfile_gene"].append(tex_path + "/" + i +
                                                 ".genelist")

            for i in cmd_param:
                J[i] = ";".join(cmd_param[i])

            shellcmd = [
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "..",
                             "..", "scripts/VariantReport.R")
            ]
            shellcmd.extend([
                "--infile", "'" + sample_config["vcf"]["merged"]["SNV"] + "'",
                "--dp", "'" + J["TUMOR_DP"] + "'", "--tumorad",
                "'" + J["TUMOR_AD"] + "'", "--afmax",
                "'" + J["TUMOR_AFmax"] + "'", "--afmin",
                "'" + J["TUMOR_AFmin"] + "'", "--inMVL",
                "'" + J["TUMOR_inMVL"] + "'", "--exclusiveSets", "TRUE",
                "--vartype", "'" + J["var_type"] + "'", "--varcaller",
                "'" + J["varcaller"] + "'", "--ann", "'" + J["ann"] + "'",
                "--name", "'" + J["name"] + "'", "--type", "latex"
            ])

            subprocess.check_output(
                " ".join(shellcmd +
                         ["--outfile", "'" + J["outfile_tex"] + "'"]),
                shell=True)

            print(" ".join(shellcmd +
                           ["--outfile", "'" + J["outfile_tex"] + "'"]))
            subprocess.check_output(" ".join(shellcmd + [
                "--outfile", "'" + J["outfile_gene"] + "'", "--exportGene", "T"
            ]),
                                    shell=True)

            for c, i in enumerate(var_config["filters"]):
                with doc.create(
                        Subsubsection(var_config["filters"][i]["name"],
                                      numbering=True)):
                    print(cmd_param["outfile_tex"])
                    fname = cmd_param["outfile_tex"][c]
                    if os.stat(fname).st_size > 10:
                        #get gene list
                        with open(cmd_param["outfile_gene"][c]) as myfile:
                            genes = myfile.read().replace('\n', '')

                        with open(fname, 'r') as myfile:
                            data = myfile.read()  #.replace('\n', '')

                        #doc.append(NoEscape(r'\begin{landscape}'))
                        #longtable instead of tabular makes the table span multiple pages, but the header doesn't span. Occasionally
                        #the alignment also is messed up. There must be a hidden package conflict OR general alignment issues.
                        #doc.append(NoEscape(varreport.replace("{tabular}","{longtable}")))
                        doc.append(
                            NoEscape(
                                data.replace("\\centering", "\\scriptsize")))

                        for s in sample_config["bed"]["exon_cov"]:
                            shellcmd = [
                                os.path.join(
                                    os.path.dirname(os.path.abspath(__file__)),
                                    "..", "scripts/CoverageRep.R")
                            ]
                            shellcmd.extend([
                                "--infile",
                                sample_config["bed"]["exon_cov"][s],
                                "--genename", genes, "--name",
                                s.replace("_", "\_"), "--type", "latex"
                            ])
                            outCov = subprocess.check_output(shellcmd)

                            doc.append(
                                NoEscape(
                                    outCov.decode('utf-8').replace(
                                        "\\centering", "\\scriptsize")))
                        #doc.append(NoEscape(r'\end{landscape}'))
                    else:
                        doc.append("No variants were found for this filter")

#                doc.append(NoEscape(r'\normalsize'))

            doc.append(NewPage())

        with doc.create(Subsection('Coverage report')):
            for s in sample_config["bed"]["target_cov"]:
                with doc.create(Figure(position='h!')) as cov_img:
                    covplot = ".".join(
                        [os.path.join(tex_path, s), "Coverage.pdf"])
                    shellcmd = [
                        os.path.join(
                            os.path.dirname(os.path.abspath(__file__)), "..",
                            "..", "scripts/CoveragePlot.R")
                    ]
                    shellcmd.extend([
                        "--infile", sample_config["bed"]["target_cov"][s],
                        "--outfile", covplot, "--title",
                        s.replace("_", "\_")
                    ])
                    subprocess.check_output(shellcmd)
                    cov_img.add_image(covplot, width='450px')
                    cov_img.add_caption('Coverage report for sample ' +
                                        s.replace("_", "\_"))

            doc.append(NewPage())
        with doc.create(Subsection('Analysis pipeline')):
            with doc.create(Figure(position='h!')) as pipeline_img:
                pipeline_img.add_image(rulegraph_img, width='450px')
                pipeline_img.add_caption('BALSAMIC pipeline')
            doc.append(NewPage())

    with doc.create(Section(title="Appendix", numbering=True)):
        with doc.create(Subsection("MVL settings", numbering=True)):
            fmt = "p{3cm}" * (len(var_config["filters"]) + 1)
            with doc.create(Tabular(fmt)) as data_table:
                header_row1 = [""]
                for i in var_config["filters"]:
                    header_row1.append(var_config["filters"][i]["name"])
                data_table.add_hline()
                data_table.add_row(header_row1,
                                   mapper=[bold],
                                   color="lightgray")
                data_table.add_hline()
                data_table.add_empty_row()
                column = list(var_config["filters"][next(
                    iter(var_config["filters"]))]["TUMOR"].keys())
                for i in column:
                    row = [i]
                    for j in var_config["filters"]:
                        row.append(var_config["filters"][j]["TUMOR"][i])
                    data_table.add_row(row)

                row = ["MVL"]
                for i in var_config["filters"]:
                    row.append(var_config["filters"][i]["in_mvl"])

                row = ["Variantcallers"]
                for i in var_config["filters"]:
                    row.append("\n".join(
                        var_config["filters"][i]["variantcaller"]))
                data_table.add_row(row)
                data_table.add_hline()

        with doc.create(
                Subsection("Bioinformatic tool in pipeline", numbering=True)):
            doc.append(
                "The following Bioinformatic tools were used in the analysis:\n\n"
            )
            with doc.create(Tabular("p{4cm}p{4cm}")) as data_table:
                data_table.add_hline()
                conda_env = glob.glob(
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "..", "..", "conda_yaml/*.yaml"))

                pkgs = get_package_split(conda_env)

                data_table.add_row(["Package", "Version"], color="lightgray")
                data_table.add_hline()
                data_table.add_row(
                    ["BALSAMIC", sample_config['analysis']['BALSAMIC']])

                for k, v in pkgs.items():
                    data_table.add_row([k, v])
            doc.append(NewPage())

    print(tex_path)
    doc.generate_tex(os.path.join(tex_path, get_sample_name(config)))
    #    doc.generate_pdf(
    #        os.path.join(tex_path, get_sample_name(config)), clean_tex=False)
    shellcmd = [
        "pdflatex", "-output-directory=" + tex_path,
        os.path.join(tex_path, get_sample_name(config)) + ".tex", "1>",
        "/dev/null"
    ]
    #generate_pdf doesn't run AUX files properly and ends up with incorrect total page numbers. So subprocess for
    #pdflatex is called twice instead.

    print(" ".join(shellcmd))
    subprocess.run(" ".join(shellcmd), shell=True)
    subprocess.run(" ".join(shellcmd), shell=True)
예제 #23
0
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options,
                   document_options="a4paper")

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    with first_page.create(Head("L")) as header_left:
        with header_left.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__), logo_name)
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("Sjain ventures ltd")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("C-246, Vallabhnagar")))
            title_wrapper.append(LineBreak())
            # title_wrapper.append(TextColor("gray", MediumText(bold("Raipur, CG"))))
            title_wrapper.append(MediumText(bold("Raipur, CG")))

    # Add footer
    # with first_page.create(Foot("C")) as footer:
    #     message = "Important message please read"
    #     with footer.create(Tabularx(
    #             "X X X X",
    #             width_argument=NoEscape(r"\textwidth"))) as footer_table:

    #         footer_table.add_row(
    #             [MultiColumn(4, align='l', data=TextColor("blue", message))])
    #         footer_table.add_hline(color="blue")
    #         footer_table.add_empty_row()

    #         branch_address = MiniPage(
    #             width=NoEscape(r"0.25\textwidth"),
    #             pos='t')
    #         branch_address.append("960 - 22nd street east")
    #         branch_address.append("\n")
    #         branch_address.append("Saskatoon, SK")

    #         document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
    #                                     pos='t', align='r')
    #         document_details.append("1000")
    #         document_details.append(LineBreak())
    #         document_details.append(simple_page_number())

    #         footer_table.add_row([branch_address, branch_address,
    #                               branch_address, document_details])

    # Newly added
    with first_page.create(Foot("L")) as right_footer:
        with right_footer.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='l',
                         align='l')) as contact_wrapper:
            contact_wrapper.append(MediumText(bold("Alok Kumar Sharma")))
            contact_wrapper.append(LineBreak())
            contact_wrapper.append(MediumText("*****@*****.**"))
            contact_wrapper.append(LineBreak())
            contact_wrapper.append(MediumText("+91 7877681234"))

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[r]")) as first_page_table:
        # customer = MiniPage(width=NoEscape(r"0.9\textwidth"), pos='h')
        # customer.append("Verna Volcano")
        # customer.append("\n")
        # customer.append("For some Person")
        # customer.append("\n")
        # customer.append("Address1")
        # customer.append("\n")
        # customer.append("Address2")
        # customer.append("\n")
        # customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')
        branch.append("http://sjainventures.com")
        branch.append(LineBreak())
        branch.append("*****@*****.**")
        # branch.append(LineBreak())
        # branch.append("+91 7877681234")

        first_page_table.add_row([branch])  # [customer, branch]
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    # with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
    #                          row_height=1.5)) as data_table:
    #     data_table.add_row(["date",
    #                         "description",
    #                         "debits($)",
    #                         "credits($)",
    #                         "balance($)"],
    #                        mapper=bold,
    #                        color="lightgray")
    #     data_table.add_empty_row()
    #     data_table.add_hline()
    #     row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
    #     for i in range(25):
    #         if (i % 2) == 0:
    #             data_table.add_row(row, color="lightgray")
    #         else:
    #             data_table.add_row(row)

    with doc.create(Paragraph("Dear Rishikesh,")) as para1:
        para1.append(lorem_ipsum.LOREM_IPSUM_TEXT2)

    # doc.append(NewPage())

    # Add cheque images
    # with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
    #     cheque_file = os.path.join(os.path.dirname(__file__),
    #                                'facebook_logo.png')
    #     cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
    #     for i in range(0, 20):
    #         cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("complex_report", clean_tex=False)
예제 #24
0
        }

        doc = make_doc(coverfile,
                       title="Cover Letter",
                       author=data['personal']['name'],
                       geometry_options=geometry_options)

        first_page = PageStyle("firstpage")

        with first_page.create(Head("R")) as h:

            with h.create(
                    MiniPage(width=NoEscape(r"\textwidth"), pos='r',
                             align='r')) as w:
                w.append(VerticalSpace(NoEscape("-10pt")))
                w.append(MediumText(bold(data['personal']['name'])))
                w.append(LineBreak())
                w.append(phone_format(data['personal']['phone']) + " ")
                w.append(Command("url", data['personal']['email'][0]))
                w.append(VerticalSpace('2pt'))
                w.append(Command("hrule"))

        address = [u['department'], u['university']
                   ] + [i for i in u['contact']['address']]

        with first_page.create(Head("L")) as h:
            # h.append(VerticalSpace(NoEscape('-30pt')))
            h.append(
                StandAloneGraphic(
                    image_options=["height=1cm", "keepaspectratio=true"],
                    filename=logoimg.resolve().as_posix()))
예제 #25
0
    def seccion1(D1, D2):
        global doc
        '''>>>>>>>>>>>>>>>Presentación de los datos de usuario<<<<<<<<<<<<<<<<<'''        
        doc = Documento_Latex.titulos_I (doc, 'DATOS DEL USUARIO PARA GENERAR EL INFORME')   
        with doc.create(Tabular('lccccl')) as table:
            for i in D1:
                if(str(i)=='DATOS DE ENTRADA'):
                    break
                else:
                    if((SM(None, 'Altura', i).ratio()<0.85) and
                       (SM(None, 'Variedad de Caña', i).ratio()<0.85) and
                       (SM(None, 'Usa fertilizante', i).ratio()<0.85) and
                       (SM(None, 'Grados Brix de la panela (promedio)', i).ratio()<0.85) and
                       (SM(None, '--', str(D1[i])).ratio()<0.85)):
                        T1=str(D1[i])
                        #Arreglo para asignar unidades y mostrarlas en el informe
                        if (str(i)=='Área caña sembrada'):
                            T1=str(D1[i])+" ha" 
                        elif (str(i)=='Crecimiento aproximado del área sembrada'):
                            T1=str(D1[i])+" ha"
                        elif (str(i)=='Caña esperada por hectárea'):
                            T1=str(D1[i])+" t/ha"
                        elif (str(i)=='Número de moliendas'):
                            T1=str(D1[i])+" semanal(es)"                    
                        elif (str(i)=='Periodo vegetativo'):
                            T1=str(D1[i])+" mes(es)"                   
                        elif (str(i)=='Caña molida al mes'):
                            T1=str(D1[i])+" t/mes" 
                        elif (str(i)=='Área cosechada al mes'):
                            T1=str(D1[i])+" ha/mes" 
                        elif (str(i)=='Caña molida a la semana'):
                            T1=str(D1[i])+" t/semana" 
                        elif (str(i)=='Caña molida por Hora'):
                            T1=str(D1[i])+" t/hora"
                        elif (str(i)=='Área cosechada al mes'):
                            T1=str(D1[i]*12)+" L/año"
                        elif (str(i)=='Caña molida al año'):
                            T1=str(D1[i])+" t/año"
                        elif (str(i)=='Jugo producido al año'):
                            T1=str(D1[i])+" t/año"
                        elif (str(i)=='Bagazo secado al año'):
                            T1=str(D1[i])+" t/año"
                        table.add_row((bold(str(i)), ' ', ' ', ' ', ' ',T1))
        doc.append(NewPage())
        
        '''>>>>>>>>>>>>>>>>>>>>Presentación de los datos de la caña<<<<<<<<<<<<<<<<<<<<<<<'''
        doc = Documento_Latex.titulos_I (doc, 'CARACTERÍSTICAS DE LAS VARIEDADES DE CAÑA SELECCIONADAS')
        Canas=pd.read_excel('static/Temp/Temp4.xlsx',skipcolumn = 0,)
        Carpe=pd.read_excel('static/Temp/Temp5.xlsx',skipcolumn = 0,)
        Eti = Canas.iloc[0].values
        Val = Canas.iloc[1].values
        Car = Carpe.iloc[0].values
        
        conta=1
        for i in range (len(Car)-1):
            with doc.create(Tabular('lcccccl')) as table:
                for j in range (1,8):
                    table.add_row((bold(str(Eti[conta])), ' ', ' ', ' ', ' ', ' ', str(Val[conta])))
                    conta=conta+1
                conta=conta+1
            doc.append(LineBreak())
            doc.append('\n')
            doc.append(LineBreak())
        
        for i in range (1,len(Car),3):
            with doc.create(Figure(position='h!')) as imagesRow1:
                for j in range(3):
                    if((i+j)<len(Car)):
                        with doc.create(
                            SubFigure(width=NoEscape(r'0.33\linewidth'))) as left_imagesRow1:
                            left_imagesRow1.add_image(Car[i+j], width=NoEscape(r'0.95\linewidth'))
                            left_imagesRow1.add_caption('Variedad de caña '+str(i+j))
                imagesRow1.append(LineBreak())
                imagesRow1.append(NewPage())  
        
        doc.append(NewPage())
        doc.append(TextColor('white','HH')) 
        doc.append(NewPage())
        
        '''>>>>>>>>>>>>>>>>>>>>Presentación de los molinos seleccionados<<<<<<<<<<<<<<<<<<<<<<<'''   
        doc = Documento_Latex.titulos_I (doc, 'MOLINOS PRESELECCIONADOS PARA ESTE DISEÑO')
        Molino=pd.read_excel('static/Temp/Temp.xlsx',skipcolumn = 0,)
        Carpe=pd.read_excel('static/Temp/Temp5.xlsx',skipcolumn = 0,)
        Eti = Canas.iloc[0].values
        Val = Canas.iloc[1].values
        Car = Carpe.iloc[0].values
        Marca=Molino['Marca'].values
        Modelo=Molino['Modelo'].values
        Kilos=Molino['kg/hora'].values
        Diesel=Molino['Diesel'].values
        Electrico=Molino['Electrico'].values
        Valor=Molino['Precio'].values

        with doc.create(Tabular('lcccccl')) as table:
                table.add_row((TextColor('red',bold('VALOR APROXIMADO DE UN MOLINO: ')),
                               ' ', ' ', ' ', ' ', ' ', 
                               TextColor('red', Documento_Latex.Formato_Moneda(sum(Valor)/len(Valor), "$", 2))))
        doc.append(LineBreak())
                
        with doc.create(Tabular('ccccc')) as table:  
            table.add_row("MARCA", "MODELO", "KG POR HORA", "DIESEL O GASOLINA (HP)", "ELÉCTRICO (HP)")
            table.add_empty_row()
            for i in range(len(Marca)):
                table.add_row(str(Marca[i]),
                              str(Modelo[i]), 
                              str(Kilos[i]), 
                              str(Diesel[i]), 
                              str(Electrico[i]))
                
            doc.append(LineBreak())
            doc.append('\n')
            doc.append(LineBreak())
        
        for i in range (1,len(Modelo),3):
            with doc.create(Figure(position='h!')) as imagesRow1:
                for j in range(3):
                    if((i-1)+j<len(Modelo)):
                        with doc.create(
                            SubFigure(width=NoEscape(r'0.33\linewidth'))) as left_imagesRow1:
                            left_imagesRow1.add_image('Molinos/'+str(Modelo[(i-1)+j]+'.jpg'), width=NoEscape(r'0.95\linewidth'))
                            left_imagesRow1.add_caption(str(Modelo[(i-1)+j]))
                imagesRow1.append(LineBreak())
                imagesRow1.append(NewPage()) 
        
        doc.append(NewPage())
        doc.append(TextColor('white','HH')) 
        doc.append(NewPage())                

        #MANUAL DE OPERACIÓN DE LA HORNILLA                   
        with doc.create(MediumText(' ')) as tlg:
                    tlg.append(LargeText(bold('Consideraciones para el manejo de la hornilla')))
                    
                    Parrafo= ('\n \nEl trapiche panelero es un lugar donde se procesa la caña de azúcar para producir la panela. Está constituido por las áreas de molienda, prelimpieza, hornilla, moldeo y almacenamiento.')           
                    tlg.append(Parrafo)

                    Parrafo= ('\n La hornilla panelera, está conformada, por el cenicero, la cámara, la chimenea y el ducto, sobre el cual se asientan directamente los intercambiadores de calor, en los que se deposita el jugo. En la hornilla panelera, se genera y transfiere el calor necesario para concentrar en un sistema de evaporación abierta, el jugo de la caña; de tal forma que la cantidad de energía aprovechada se relaciona directamente con el suministro de aire y bagazo, la eficiencia de la combustión, y la cantidad de energía disipada a los alrededores. Estas variables de operación y transferencia se relacionan entre si y debido a su complejidad y cantidad, dificultan las tareas de manipulación y diseño de la hornilla.')           
                    tlg.append(Parrafo)
                    
                    tlg.append(LargeText(bold('\n \n Manejo de las hornillas paneleras')))
                    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Tenga en cuenta las siguientes indicaciones.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Durante las pruebas iniciales y periodos de capacitación, los operarios que manejan la hornilla deben tener experiencia para evitar la disminución en la calidad de la panela y vida util de los equipos instalados.')
                                                        item.add_item('El trabajo continuo de la hornilla aumenta la capacidad de producción y evita la perdida de energía, puesto que, al no enfriarse durante las horas de la noche se reduce el efecto del cambio térmico sobre los ladrillos de la estructura.')
                                                        item.add_item('La combustión en la hornilla será buena, si se alimenta con pequeñas cantidades de bagazo cada 150 segundos y la válvula de la chimenea tiene una apertura 60° para garantizar un flujo de aire suficientemente alto que produzca llama, sin arrastrar combustible en los gases residuales.')
                                                        item.add_item('La entrada de aire por orificios diferentes a los proyectados en el diseño inicial debe evitarse a toda costa, para aumentar la eficiencia de la combustión y reducir el material particulado de los gases en la chimenea.')
                                                        item.add_item('Elimine obstáculos en las entradas de aire diseñadas para la hornilla y retire periódicamente la ceniza la parrilla para evitar la formación de escoria.')
                                                        item.add_item('El cenicero y su entrada deben mantenerse despejada a fin de no obstruir el paso del aire.')
                                                        item.add_item('El bagazo para alimentar la hornilla debe tener las condiciones de humedad mencionadas en el diseño.')
                                                        item.add_item('Almacene el bagazo por dos semanas en la bagacera, y así, obtendrá un bagazo con al menos un 30% de humedad.')
                                                        item.add_item('Ajuste el tiro de la chimenea usando la válvula mariposa cuando tenga bagazo con mayor humedad.')
                                                        item.add_item('La válvula no opera en tiempo real y cuando se encuentra a medio cerrar se aumenta la velocidad de calentamiento en la zona de evaporación al pie de la entrada del bagazo. Sin embargo, cuando se encuentra abierta el calentamiento se presenta al pie de la chimenea.')
                                                        item.add_item('El tiempo de residencia del jugo en la hornilla, influye en la calidad de la panela y este es directamente proporcional al aumento de los azucares invertidos.')
                                                        item.add_item('Las falcas en las pailas son de seguridad, no deben usarse para contener una mayor cantidad de jugo. Por tanto para aumentar la transferencia de calor al jugo y mejorar la calidad de la panela es importante manejar la cantidad de jugo mínima en cada paila.')
                                                        item.add_item('El nivel del jugo en las pailas semiesféricas, siempre debe estar por encima de la línea de contacto de los gases de combustión con la paila a fin de evitar quemadura en la panela.')
                                                        item.add_item('La paila clarificadora debe calentar lo más rápido posible para que permita remover la cachaza. Además, la velocidad mínima de calentamiento debe ser de 1.5°C/min.')
                                                        item.add_item('Elimine residuos de la caña o jugos presentes sobre la superficie de las pailas concentradoras de panela y cachaza periódicamente, para que el producto se pegue al fondo. Lo cual disminuye el paso del calor y deterioran la calidad del producto.')

                    tlg.append(LargeText(bold('Mantenimiento de la hornilla')))
                    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Después de cada molienda.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Limpie y desinfecte las instalaciones, pailas, equipos y utensilios, antes de iniciar nuevamente la producción de panela.')
                                                        item.add_item('Un encelamiento de los moldes, utensilios de madera y prelimpiadores.')
                                                        item.add_item('Dejar en remojo con agua limpia las pailas durante el enfriamiento de la hornilla.')
                                                        item.add_item('Retirar la ceniza del cenicero y el ducto.')
                                                   
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Cada seis moliendas.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Retirar el hollín formado en la superficie de las pailas, por donde se transfiere el calor.')
                                                        item.add_item('Limpiar los ductos de las pailas piro-tubulares, con ayuda de un raspador o un costal de fique.')
    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Cada seis meses.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Realice una limpieza general e inspección del estado de los ductos.')
                                                        item.add_item('Realice un mantenimiento de las paredes del ducto y la cámara.')
                                                        
                    tlg.append(LargeText(bold('Recomendaciones de construcción del trapiche')))
                    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Algunos parámetros para tener en cuenta son.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('El suministro de agua ser potable y continuo.')
                                                        item.add_item('Los alrededores de las fábricas deben estar libre de posibles focos de infección.')
                                                        item.add_item('Las áreas de trabajo de cada subproceso deben estar delimitadas.')
                                                        item.add_item('Las áreas de procesamiento y empaque deben estar separadas de las áreas de recepción y desechos.')
                                                        item.add_item('Las uniones de las baldosas deben recubrirse de materiales plásticos que faciliten la limpieza.')
                                                        item.add_item('Las salientes de las paredes, dinteles de ventanas y suspensiones del techo deben ser curvas e inclinadas.')
                                                        item.add_item('Los pisos y las paredes se deben construir con materiales anticorrosivos, no absorbentes y de alto transito.')
                                                        item.add_item('Las áreas de procesos deben tener en el centro un canal de drenaje con 3° de inclinación y una parrilla removible para realizar su limpieza.')
                                                        item.add_item('Los pisos deben tener una leve inclinación (3°) para realizar el drenado.')
                                                        item.add_item('Los desagües deben tener rejillas de seguridad para impedir el paso de animales.')
                                                        item.add_item('Los ambientes debe ser ventilados.')
                                                        item.add_item('Los vapores deben contar con su propio escape para evitar la presencia de moho en paredes y techos.')
                                                        item.add_item('Los ductos de ventilación deben estar cubiertos de mallas protectoras.')
                                                        item.add_item('Los ambientes deben estar bien iluminados.')
                                                        item.add_item('Las bases o cimientos deben ser lisos para evitar la presencia de insectos o residuos.')
                                                        item.add_item('Los espacios entre los equipos o equipos y paredes deben estar sellados.')
                                                        item.add_item('Los baños, habitaciones y casilleros, deben estar aseados y alejados de las áreas de procesamiento y producto terminado.')
                                                        item.add_item('Las diferentes áreas deben disponer de un sitio para el aseo de las manos con sus respectivos implementos, tales como; jabón líquido, cepillos y toallas desechables.')

                    tlg.append(LargeText(bold('Higiene y desinfección en el trapiche')))
                   
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Tenga en cuenta las siguientes indicaciones para su cuidado personal.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('El objetivo de la higiene en los alimentos es alargar la vida útil del producto, y proteger al consumidor final de las enfermedades producidas al ingerir alimentos contaminados.')
                                                        item.add_item('La higienización de un trapiche requiere de una limpieza con detergente y de una esterilización industrial o satanización (desinfectante y bactericida).')
                                                        item.add_item('Los equipos y utensilios deben limpiarse y desinfectarse al final e inicio de cada molienda.')
                                                        item.add_item('La limpieza se realiza siguiendo estas pautas: proteger las materias prima y los productos terminados, raspar los residuos sólidos con una espátula sobre un recogedor y lavar con agua limpia, cepillo y detergente')
                                                        item.add_item('La esterilización se realiza con calor (vapor de agua, agua hirviendo), o un esterilizante químico (bactericida, desinfectante).Cuando se emplea agua caliente debe estar hirviendo (90°C) o en el caso del esterilizante químico puede usarse una solución clorada, de vinagre y una lechada de cal.')
                                                        item.add_item('Las soluciones desinfectantes deben aplicarse en solución con un rociador, empezando por la parte inferior.')
                                                        item.add_item('Antes de la esterilización la superficie debe estar limpia y totalmente escurrida.')
                                                        item.add_item('Las superficies en contacto con el alimento deben ser lisas, exentas de huecos, grietas y evitar las esquinas cuadradas.')
                                                        item.add_item('La industria de alimentos usa ampliamente el acero inoxidable y plásticos como el teflón por la facilidad de higienización, y su poca alteración al contacto con los alimentos.')
                                                        item.add_item('No debe usarse el cobre, bronce, estaño, aluminio, madera y zinc para las superficies que están en contacto con el alimento.')
                                                        item.add_item('No emplee en la limpieza esponjas o cepillos metálicos que rayen las superficies.')
                                                        item.add_item('Las pailas se lavan con arena de peña y esponja para desmancharla.')
                                                        item.add_item('Ningún tipo de rosca debe estar en contacto con el alimento.')
                                                        item.add_item('Se debe mantener una inclinación de superficies y tubería para el drenaje de 1 centímetro por metro.')
                                                        item.add_item('Se deben usar conexiones hidraulicas y uniones que sean de fácil limpieza.')
                                                        item.add_item('Se debe evitar la unión de acero inoxidable con otros metales.')
                                                        item.add_item('El hipoclorito ejerce una rápida acción bactericida sin dejar residuos tóxicos.')
                                                        item.add_item('No es aconsejable el uso de cloro en material de acero inoxidable.')
                                                        item.add_item('En la esterilización del acero inoxidable, puede utilizarse agua caliente, vapor o solución de 0.25 litros de vinagre en 10 litros de agua.')
                                                        item.add_item('Los materiales plásticos se deben lavar con una solución de 5.0 gramos de bicarbonato (2 cucharadas) en l0 litros de agua clorada y dejar secar durante 30 minutos.')
                                                        item.add_item('La esterilización del acero inoxidable puede hacerse con agua caliente, vapor o solución de 0.25 litros de vinagre en 10 litros de agua.')
                                                        item.add_item('Las superficies de madera se limpian con espátula para eliminar los residuos sólidos. Después remojar en detergente durante 5 minutos, luego cepillar, lavar con agua limpia, y finalmente rociar con solución de 12 gramos de cal (una cucharadita) en 10 litros de agua dejar secar.')  
                                                        item.add_item('Los utensilios de madera se dejan en un recipiente plástico limpio, con solución de 12 gramos de cal (una cucharadita) en 10 litros de agua.')  
                                                        item.add_item('Cambiar la solución donde se sumergen los utensilios de madera cada cuatro horas.') 
                                                        item.add_item('Los utensilios y gaveras no deben dejarse sobre el suelo o superficies no desinfectadas.') 
                                                        item.add_item('Evitar la caída de grasa mecánica en los alimentos.')

        doc.append(NewPage())