Пример #1
0
def generar_fichero_pdf_mes(listaArchivosXLSX):
    # esto es para escoger el archivo xlsx
    print(f"Archivos de excel encontrados en directorio")
    for i in range(len(listaArchivosXLSX)):
        print(f"{(i+1)} = {listaArchivosXLSX[i]}")
    opcion_archivo = introducirOpcion(len(listaArchivosXLSX))
    archivo_xlsx_escogido = listaArchivosXLSX[(opcion_archivo - 1)]
    # esto es para escoger el sheet del archivo escogido
    xlsx_File = pd.ExcelFile(archivo_xlsx_escogido)
    xlsx_Sheets = xlsx_File.sheet_names
    for y in range(len(xlsx_Sheets)):
        print(f"{(y+1)} = {xlsx_Sheets[y]}")
    opcion_sheet = introducirOpcion(len(xlsx_Sheets))
    opcion_sheet_escogido = xlsx_Sheets[(opcion_sheet - 1)]
    # creamos dataframe y lo devolvemos como pdf
    dfMes = pd.read_excel(archivo_xlsx_escogido,
                          sheet_name=opcion_sheet_escogido)
    dataframe = dfMes.loc[:, [
        'fecha', 'tmin', 'horatmin', 'tmax', 'horatmax', 'tmed'
    ]]
    #replace .xlsx a .pdf
    archivo_pdf = archivo_xlsx_escogido.replace(".xlsx", ".pdf")
    # Convertimos la plantilla .pug a html, especificando el valor
    html = pug_to_html("C:\\WPy64-3810\\notebooks\\L13\\template_mes.pug",
                       title="Informe mensual temperaturas Agoncillo",
                       dataframe=dataframe)
    write_report(html, archivo_pdf)
Пример #2
0
def sequenticon_batch_pdf(sequences, target=None, title="Sequenticons batch"):
    """Generate a PDF report with sequenticons for a batch of sequences.

    Parameters
    ----------

    sequences
      A list of either ``name, sequence`` tuples, or Biopython records (with
      different IDs), or paths to genbank or fasta files containing one or
      more record each.

    target
      path to a PDF file, file-like object, or None to return raw PDF data.

    title
      Title that will appear in the document
    """
    now = datetime.now().strftime("%Y-%m-%d %H:%M")
    sequenticons = sequenticon_batch(sequences, output_format='html_image')
    html = pug_to_html(
        PUG_TEMPLATE,
        sidebar_text="Generated on %s by Sequenticon version %s" %
        (now, __version__),
        sequenticon_logo_url=os.path.join(ASSETS_PATH, 'logo.png'),
        sequenticons=sequenticons,
        title=title)
    return write_report(html, target, extra_stylesheets=(STYLESHEET, ))
Пример #3
0
def create_report_summary(variables):

    variables = {
        'title': 'Brain Health Report',
        'logo':
        '/Users/suhaas/Desktop/ReactN/analytics/reactrack/REACT_logo.png',
        'exam_history_and_map_graph':
        '/Users/suhaas/Desktop/ReactN/analytics/test.png',
        'user_id': 'random_hash_basically',
        'name': 'Mary Smith',
        'age': '55',
        'location': 'LCB - Norwood',
        'date': '4/26/2020 1:11p',
        'VOR_phase_lag': 0.5,
        'VOR_bpm': 100,
        'VOR_nystagmus': 'No',
        'default_color': 'teal',
        'self_paced': None,
        'prosaccade_reaction_time_color': 'red',
        'prosaccade_acc_color': 'green',
        'prosaccade_catch_up_color': 'purple'
    }

    html = pug_to_html('./VOR_battery2_template.pug', **variables)
    write_report(html, 'VOR_2_Summary_Example.pdf')
Пример #4
0
 def write_to(self, path: str):
     with tempfile.NamedTemporaryFile(suffix=".pug", mode="w") as pugfile:
         figures = 0
         for element in self.__body._flatten():
             if element["kind"] == "title":
                 level = max(min(element["level"], 6), 1)
                 pugfile.write("h%d %s\n\n" % (level, element["text"]))
             elif element["kind"] == "paragraph":
                 pugfile.write("p %s\n\n" % (element["text"], ))
             elif element["kind"] == "figure":
                 figures += 1
                 pugfile.write('img(src="%s", alt="Figure %d")\n\n' %
                               (element["url"], figures))
             elif element["kind"] == "table":
                 pugfile.write("table.ui.celled.table\n")
                 table: PDFReportsReportTable = element["table"]
                 for i, row in enumerate(table._rows):
                     row = [str(el) for el in row]
                     cell_el = "td"
                     if i == 0:
                         pugfile.write("  thead\n")
                         cell_el = "th"
                     elif i == 1:
                         pugfile.write("  tbody\n")
                     pugfile.write("    tr\n")
                     for cell in row:
                         pugfile.write("      %s %s\n" % (cell_el, cell))
                 pugfile.write("\n")
             else:
                 raise NotImplementedError(str(element))
         pugfile.flush()
         html = pug_to_html(pugfile.name)
         write_report(html, path)
Пример #5
0
def test_basics(tmpdir):
    template_path = os.path.join('tests', 'data', "example_template.pug")
    pdf_path = os.path.join(str(tmpdir), 'test.pdf')
    html = pug_to_html(template_path, title="Summary of your order")
    write_report(html, pdf_path)
    with open(pdf_path, "rb") as f:
        reader = PdfFileReader(f)
        assert reader.numPages == 2
Пример #6
0
def saboteurs_pug_to_html(**context):
    defaults = {
        "logo_url": os.path.join(THIS_PATH, "assets", "logo.png"),
        "sidebar_text": "Generated by Saboteurs version " + __version__,
    }
    for k in defaults:
        if k not in context:
            context[k] = defaults[k]
    return pug_to_html(TEMPLATE, **context)
Пример #7
0
def main():
    # Get user input
    topic = sys.argv[1]
    mode = int(sys.argv[2])

    # Mode dictionary
    modeselect = {
        0: noblank,
        1: kanjitest,
        2: hiraganatest,
        3: englishtest,
        4: randomtest,
    }

    # import vocabulary from csv file
    filename = topic + ".xls"
    try:
        vocabulary = pd.read_excel("xls_files/" + filename)
        vocabulary.columns = ['kanji', 'hiragana', 'english']
    except:
        print("Filename " + "xls_files/" + filename +
              " invalid (wrong path or xls format invisible character)")
        return (1)

    try:
        toprint, modetitle = modeselect.get(mode,
                                            lambda: "error mode")(vocabulary)
        # Shuffle
        toprint = toprint.iloc[np.random.permutation(len(toprint))]
    except:
        print("Mode " + str(mode) + " invalid")
        print(
            "Mode => 0: noblank - 1: Kanji test - 2: reading test - 3: translation test - 4: random test"
        )
        return (1)

    # Convert to pdf
    date = strftime("%Y_%m_%d", gmtime())
    pdffilename = topic + "_" + modetitle + "_" + date
    html = pug_to_html("template.pug",
                       title="Japanese for Engineering",
                       vocab=topic,
                       dataframe=toprint,
                       size=len(toprint))

    try:
        print("PDF saving as " + pdffilename)
        write_report(html, pdf_path + pdffilename + ".pdf")
        print("Done !")
        return (0)
    except:
        print("Please close the existing pdf with the same name")
        return (1)
Пример #8
0
def genedom_pug_to_html(template, **context):
    now = datetime.now().strftime("%Y-%m-%d %H:%M")
    defaults = {
        'genedom_sidebar_text':
        "Generated on %s by Genedom version %s" % (now, __version__),
        'genedom_logo_url':
        os.path.join(ASSETS_PATH, 'imgs', 'logo.png'),
    }
    for k in defaults:
        if k not in context:
            context[k] = defaults[k]
    return pug_to_html(template, **context)
Пример #9
0
def dnacauldron_pug_to_html(template, **context):
    now = datetime.now().strftime("%Y-%m-%d")
    defaults = {
        "sidebar_text":
        "Generated on %s by DNA Cauldron version %s" % (now, __version__),
        "dc_logo_url":
        os.path.join(ASSETS_PATH, "imgs", "logo.png"),
    }
    for k in defaults:
        if k not in context:
            context[k] = defaults[k]
    return pug_to_html(template, **context)
Пример #10
0
def generar_fichero_pdf_todos_meses(listaArchivosXLSX):
    for i in range(len(listaArchivosXLSX)):
        # creamos dataframe y lo devolvemos como pdf
        archivo_xlsx = listaArchivosXLSX[i]
        dfMes = pd.read_excel(archivo_xlsx, sheet_name="Sheet1")
        dataframe = dfMes.loc[:, [
            'fecha', 'tmin', 'horatmin', 'tmax', 'horatmax', 'tmed'
        ]]
        #replace .xlsx a .pdf
        archivo_pdf = archivo_xlsx.replace(".xlsx", ".pdf")
        # Convertimos la plantilla .pug a html, especificando el valor
        html = pug_to_html("C:\\WPy64-3810\\notebooks\\L13\\template_mes.pug",
                           title="Informe mensual temperaturas Agoncillo",
                           dataframe=dataframe)
        write_report(html, archivo_pdf)
Пример #11
0
def test_with_plots_and_tables(tmpdir):
    template_path = os.path.join('tests', 'data', "with_plots_and_tables.pug")
    assert os.path.exists(template_path)

    dataframe = pandas.DataFrame.from_records({
        "Name": ["Anna", "Bob", "Claire", "Denis"],
        "Age": [12,22,33,44],
        "Height (cm)": [140, 175, 173, 185]
    }, columns=["Name", "Age", "Height (cm)"])

    pdf_path = os.path.join(str(tmpdir), 'test.pdf')
    html = pug_to_html(template_path, dataframe=dataframe)
    write_report(html, pdf_path)
    with open(pdf_path, "rb") as f:
        reader = PdfFileReader(f)
        assert reader.numPages == 2

    pdf_data = write_report(html)
    assert len(pdf_data) > 10000
Пример #12
0
def generate_report(context,\
                    outfilename='default.pdf'):
    """
    Generate a pdf report.

    Args:
        context (dict) : context contains the information to fill in the report

    """
    module_id = context['module_id']
    module_name = context['module_name']
    title = f'Calibration results for module #{module_id} "{module_name}"'
    css = preload_stylesheet(args.template_style)

    #for i in range(context['ndetectors']):
    #testplot    = os.path.abspath(context['det1_nm'][0])
    testplot = ''
    html = pug_to_html(args.template,\
                       title=title,\
                       context=context,\
                       my_name=context['name'],\
                       det_id1='n.a.',\
                       det_1_stripA=testplot)
    write_report(html, outfilename, extra_stylesheets=[css])
Пример #13
0
import collections
import os
import pickle

from pdf_reports import pug_to_html, write_report

with open('result.pkl', 'rb') as fd:
    data = pickle.load(fd)

# reorder tags data
tags_data = collections.OrderedDict(
    sorted(data['tags'].items(), key=lambda x: x[1]['number'], reverse=True))

html = pug_to_html("template.pug",
                   title='NER 模型性能报告',
                   sentence=data['sentence'],
                   tags=tags_data)

# Remove old file
if os.path.exists('report.pdf'):
    os.remove('report.pdf')

write_report(html, "report.pdf")
Пример #14
0
from pdf_reports import pug_to_html, write_report
import matplotlib.pyplot as plt
import pandas as pd
# img = plt.imread('logo.png')
df = pd.DataFrame.from_records(
    {
        "Name": ["Anna", "Bob", "Claire", "Denis"],
        "Age": [12, 22, 33, 44],
        "Height (cm)": [140, 175, 173, 185]
    },
    columns=["Name", "Age", "Height (cm)"])
print(df)
html = pug_to_html("template.pug",
                   title="Vessel Report",
                   dataframe=df,
                   img="/home/calcgen2/pressureVessel/del_me/logo.png")
write_report(html, "example_me.pdf")
"""PDF report generation from a Pug template embedding code to generate
plots and tables.

A HTML page is generated from a template and rendered as a local PDF file.
"""

import pandas
import matplotlib.pyplot as plt
from pdf_reports import pug_to_html, write_report

dataframe = pandas.DataFrame.from_records(
    {
        "Name": ["Anna", "Bob", "Claire", "Denis"],
        "Age": [12, 22, 33, 44],
        "Height (cm)": [140, 175, 173, 185]
    },
    columns=["Name", "Age", "Height (cm)"])

html = pug_to_html("with_plots_and_tables.pug", dataframe=dataframe)
write_report(html, "with_plots_and_tables.pdf")
Пример #16
0
    'lecturas muy largas[%]'
]
antes = filtrado_df[antes_col]  #.index('total de lecturas antes del filtrado')
desp = filtrado_df[
    despues_col]  #.set_index('total de lecturas despues del filtrado')
NNN = filtrado_df[NNN_col]  #.set_index('lecturas lowqual[%]')

###profundidad
prof = pd.read_csv(bam_dp, sep='\t', index_col=0, header=None).T
prof_df_1 = prof.iloc[:, 1:5]
prof_df_2 = prof.iloc[:, 5:]

###alineamiento
alineamiento = pd.read_csv(a_qual, sep='\t', index_col=0, header=0).T
alineamiento_df = alineamiento.iloc[:, 0:]

html = pug_to_html(
    pug_template,
    title=sample_id,
    genero=sex_df,
    antes=antes,
    despues=desp,
    NNN=NNN,
    prof1=prof_df_1,
    prof2=prof_df_2,
    TSO=TSO,
    fecha=fecha_corrida,
    alineamiento=alineamiento_df
)  #, profundidad= muestra_prof_lib,version= version, N_lecturas_antes = N_lecturas_antes, N_lecturas_dps = N_lecturas_dps, N_lecturas_dps_percent = N_lecturas_dps_percent, lecturas_lowqual = lecturas_lowqual, lecturas_NN = lecturas_NN, short_reading = short_reading, too_long=too_long, q_30_bef=q_30_bef,q_30_aft=q_30_aft, q20_bef= q20_bef, q20_after=q20_after)
write_report(html, outfile)
from pdf_reports import pug_to_html, write_report

# Convertimos la plantilla .pug a html, especificando el valor
html = pug_to_html("template_EjemploSencillo1.pug", title="Informe")
write_report(html, "EjemploSencillo1.pdf")
Пример #18
0
def test_preload_stylesheet(tmpdir):
    css = preload_stylesheet(os.path.join('tests', 'data', 'style.scss'))
    html = pug_to_html(string="p {{ var }}", var="Bla")
    pdf_path = os.path.join(str(tmpdir), 'test.pdf')
    write_report(html, pdf_path, extra_stylesheets=[css])
Пример #19
0
from pdf_reports import pug_to_html, write_report, preload_stylesheet

css = preload_stylesheet('style.scss')
html = pug_to_html("template.pug", title="My report", my_name='Zulko')
write_report(html, "example.pdf", extra_stylesheets=[css])
Пример #20
0
def test_pug_to_html():
    html = pug_to_html(string="p {{ var }}", var="Bla")
    assert html == "<p>Bla</p>"
Пример #21
0
]
Gbases_col = [
    'GBases_before_trimm', 'GBases_after_trimm',
    'Gbases-mapped-(cigar)-in-Library', 'Gbases-without-dup-mapped-in-Library'
]
lib_col = ['Target-size-(GBPs)', 'maximum-length-in-Library']

al_reads = alineamiento[reads_col]
al_rates = alineamiento[rates_col]
al_Gbases = alineamiento[Gbases_col]
al_lib = alineamiento[lib_col]

html = pug_to_html(
    pug_template,
    title=sample_id,
    genero=sex_df,
    TSO=TSO,
    fecha=fecha_corrida,
    bases=bases,
    antes=antes,
    desp=desp,
    NNN=NNN,
    dp=dp,
    stats_dp=stats_dp,
    al_reads=al_reads,
    al_rates=al_rates,
    al_Gbases=al_Gbases,
    al_lib=al_lib
)  #, profundidad= muestra_prof_lib,version= version, N_lecturas_antes = N_lecturas_antes, N_lecturas_dps = N_lecturas_dps, N_lecturas_dps_percent = N_lecturas_dps_percent, lecturas_lowqual = lecturas_lowqual, lecturas_NN = lecturas_NN, short_reading = short_reading, too_long=too_long, q_30_bef=q_30_bef,q_30_aft=q_30_aft, q20_bef= q20_bef, q20_after=q20_after)
write_report(html, outfile)
Пример #22
0
"""Basic PDF report generation from a JINJA template with pdf_reports.

A HTML page is generated from a template and rendered as a local PDF file.
"""

from pdf_reports import pug_to_html, write_report

html = pug_to_html("example_template.pug", title="My report")
write_report(html, "example.pdf")
Пример #23
0
import pandas as pd
from datetime import datetime
from pdf_reports import pug_to_html, write_report

planilha = pd.read_excel("content/controle_de_gastos.xlsx")
hoje = datetime.now().date()
html = pug_to_html("content/modelo_de_relatorio.pug",
                   planilha=planilha,
                   hoje=hoje)

write_report(html, "controle_de_gastos_rel.pdf")