def generate_pdf(stroka): pdf_path = get_dir('odli_pdf') + '\\' +stroka.Surname +' '+ stroka.Firstname +' '+ stroka.Patronymic logo_image = r'miaclogo.png' pdf = Document(pdf_path) pdf.packages.add(Package('babel',options='russian')) pdf.packages.add(Package('pdfx', options= NoEscape('a-1b') )) pdf.packages.add(Package('inputenc',options='utf8')) pdf.packages.add(Package('fontenc',options='T2A')) pdf.packages.add(Package('geometry',options='a5paper')) 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='l')) as logo_wrapper: logo_wrapper.append(StandAloneGraphic(image_options="width=120px",filename=logo_image)) with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='c')) as logo_wrapper: logo_wrapper.append(NoEscape("Сгенерированно в СПб ГБУЗ МИАЦ")) logo_wrapper.append(NewLine()) logo_wrapper.append(NoEscape("В основе данные, предоставленные лабораториями")) pdf.preamble.append(first_page) pdf.change_document_style("firstpage") pdf.add_color(name="lightgray", model="gray", description="0.80") pdf.append(HorizontalSpace(size="500px")) with pdf.create(Section(NoEscape("Исследование на COVID-19"),numbering=False)): pdf.append(NoEscape("Наименование лаборатории: " + stroka.Name_Lab )) pdf.append(NewLine()) pdf.append(NoEscape("Дата исследования: " + stroka.Date_Test)) pdf.append(NewLine()) pdf.append(NoEscape("Ответственный за исследование: ")) pdf.append(NewLine()) pdf.append(NoEscape(stroka.lab_familia +' '+ stroka.lab_name +' '+ stroka.lab_secondname)) with pdf.create(Section(NoEscape("Пациент: ") ,numbering=False)): pdf.append(LargeText(NoEscape(stroka.Surname +' '+ stroka.Firstname +' '+ stroka.Patronymic))) pdf.append(NewLine()) pdf.append(NewLine()) pdf.append(NoEscape("Дата рождения: " + stroka.Birthday)) pdf.append(NewLine()) pdf.append(NoEscape("Паспорт: " + stroka.Passport)) pdf.append(NewLine()) pdf.append(NoEscape("СНИЛС: " + stroka.Snils)) pdf.append(NewLine()) pdf.append(NoEscape("ОМС: " + stroka.Policy_OMS)) pdf.append(NewLine()) pdf.append(NoEscape("Контактный номер: " + stroka.Phone)) pdf.append(NewLine()) with pdf.create(Section(NoEscape("Результат: "),numbering=False)): pdf.append(NoEscape("Качественное обнаружение короновируса SARS 2 в различных образцах: ")) pdf.append(NewLine()) pdf.append(NewLine()) if stroka.Result_Test == 'ND': pdf.append(TextColor('green',LargeText(NoEscape('Не обнаружено')))) if stroka.Result_Test == 'DET': pdf.append(TextColor('red',LargeText(NoEscape('Обнаружено')))) pdf.generate_pdf(clean_tex=True,compiler='pdflatex') with open(pdf_path+'.pdf', "rb") as pdf_file: encoded_pdf = base64.b64encode(pdf_file.read()).decode() return encoded_pdf
def test_position(): repr(HorizontalSpace(size='20pt', star=False)) repr(VerticalSpace(size="20pt", star=True)) # Test alignment environments center = Center() center.append("append") repr(center) right = FlushRight() right.append("append") repr(right) left = FlushLeft() left.append("append") repr(left) minipage = MiniPage(width=r"\textwidth", height="10pt", pos='t', align='r', content_pos='t', fontsize="Large") minipage.append("append") repr(minipage) textblock = TextBlock(width="200", horizontal_pos="200", vertical_pos="200", indent=True) textblock.append("append") textblock.dumps() repr(textblock)
def _add_kernel_structure_subsection( self, doc: Document, width: str, title: str = 'Kernel Structure Evolution', *args, **kwargs) -> None: """Add kernel structure sub-section to document. :param doc: :param width: :param title: :param args: :param kwargs: :return: """ with doc.create(Subsection(title)): doc.append('A summary of the structure of gp_models searched.') with doc.create(Figure(position='h!')) as plot: with doc.create( SubFigure(position='t', width=NoEscape(r'0.45\linewidth'))) as left: plot_distribution(self.experiment.median_n_hyperparameters, self.experiment.std_n_hyperparameters, self.experiment.best_n_hyperparameters, value_name='median', metric_name='# Hyperparameters') left.add_plot(width=NoEscape(width), *args, **kwargs) left.add_caption( 'A plot of the number of hyperparameters for each iteration of the best model, \ the median number of hyperparameters, and the standard deviation.' ) plot.append(HorizontalSpace("10pt")) with doc.create( SubFigure(position='t', width=NoEscape(r'0.45\linewidth'))) as right: plot_distribution(self.experiment.median_n_operands, self.experiment.std_n_operands, self.experiment.best_n_operands, value_name='median', metric_name='# Operands') right.add_plot(width=NoEscape(width), *args, **kwargs) right.add_caption( 'A plot of the number of operands (number of 1-D gp_models) over time including \ the best model, the median number of operands, and the standard deviation.' ) plot.add_caption( 'These two figures show how the structure of the compositional gp_models changed over \ time. The left figure shows the hyperparameter distribution and the right one shows operand \ distribution.')
def _add_population_subsection(self, doc: Document, width: str, title: str = 'Population Evolution', *args, **kwargs) -> None: """Add population sub-section to document. :param doc: :param width: :param title: :param args: :param kwargs: :return: """ with doc.create(Subsection(title)): doc.append('A summary of the population of gp_models searched.') with doc.create(Figure(position='h!')) as plot: with doc.create( SubFigure(position='t', width=NoEscape(r'0.45\linewidth'))) as left: plot_distribution(self.experiment.mean_cov_dists, self.experiment.std_cov_dists, metric_name='covariance distance') left.add_plot(width=NoEscape(width), *args, **kwargs) left.add_caption( 'This plot shows the mean Euclidean covariance distance over time of all \ pairs of kernel matrices. It represents the heterogeneity of the population.' ) plot.append(HorizontalSpace("10pt")) with doc.create( SubFigure(position='t', width=NoEscape(r'0.45\linewidth'))) as right: plot_distribution(self.experiment.diversity_scores, metric_name='diversity', value_name='population') right.add_plot(width=NoEscape(width), *args, **kwargs) right.add_caption( 'This plot shows the mean Euclidean distance of all pairs of kernel expressions \ in additive form. It represents the diversity/heterogeneity of the population.' ) plot.add_caption( 'Two figures showing the evolution of the population heterogeneity.' )
def format_recipe(recipe, display_opts): """ Return the recipe in a paragraph in a samepage """ recipe_page = SamepageEnvironment() name_line = LargeText(recipe.name) if display_opts.origin and 'schubar original' in recipe.origin.lower(): name_line.append(superscript('*')) #name_line.append(superscript(NoEscape('\dag'))) if display_opts.prices and recipe.max_cost: price = util.calculate_price(recipe.max_cost, display_opts.markup) name_line.append(DotFill()) name_line.append(superscript('$')) name_line.append(price) name_line.append('\n') recipe_page.append(name_line) if display_opts.prep_line: recipe_page.append( FootnoteText(recipe.prep_line(extended=True, caps=False) + '\n')) if display_opts.info and recipe.info: recipe_page.append(SmallText(italic(recipe.info + '\n'))) for item in recipe.ingredients: recipe_page.append(item.str() + '\n') if display_opts.variants: for variant in recipe.variants: recipe_page.append(HorizontalSpace('8pt')) recipe_page.append(SmallText(italic(variant + '\n'))) if display_opts.examples and recipe.examples: # and recipe.name != 'The Cocktail': for e in recipe.examples: recipe_page.append( FootnoteText( "${cost:.2f} | {abv:.2f}% | {std_drinks:.2f} | {kinds}\n". format(**e._asdict()))) recipe_page.append(Command('par')) return recipe_page
def _add_model_scores(self, doc: Document, width: str, title: str = 'Model Score Evolution', *args, **kwargs) -> \ None: """Add model scores sub-section to document. :param doc: :param width: :param title: :param args: :param kwargs: :return: """ with doc.create(Subsection(title)): doc.append('A summary of the distribution of model scores.') with doc.create(Figure(position='h!')) as plot: with doc.create( SubFigure(position='t', width=NoEscape(r'0.45\linewidth'))) as left: plot_best_so_far(self.experiment.best_scores) left.add_plot(width=NoEscape(width), *args, **kwargs) left.add_caption( 'A plot of the maximum score over each iteration.') plot.append(HorizontalSpace("10pt")) with doc.create( SubFigure(position='t', width=NoEscape(r'0.45\linewidth'))) as right: plot_distribution(self.experiment.mean_scores, self.experiment.std_scores, self.experiment.best_scores) right.add_plot(width=NoEscape(width), *args, **kwargs) right.add_caption( 'A distribution of the maximum model score, the mean model score, and standard \ deviation of models scores per iteration.') plot.add_caption( 'These two figures show the model scores. The left shows a best-so-far curve and the \ right one shows a distribution of scores.')
def setup_header_footer(doc, pdf_opts, display_opts): # Header with title, tagline, page number right, date left # Footer with key to denote someting about drinks title = pdf_opts.title or '@Schubar' if display_opts.prices: tagline = 'Tips never required, always appreciated' tagline = pdf_opts.tagline or 'Tips for your drinks never required, always appreciated' else: tagline = 'Get Fubar at Schubar on the good stuff' tagline = pdf_opts.tagline or 'Get Fubar at Schubar, but, like, in a classy way' hf = PageStyle("schubarheaderfooter", header_thickness=0.4, footer_thickness=0.4) with hf.create(Head('L')): hf.append(TitleText(title)) hf.append(Command('\\')) hf.append(FootnoteText(italic(tagline))) with hf.create(Head('R')): hf.append(FootnoteText(time.strftime("%b %d, %Y"))) if display_opts.origin: with hf.create(Foot('L')): hf.append(superscript("*")) #hf.append(superscript(NoEscape("\dag"))) hf.append(FootnoteText(r"Schubar Original")) with hf.create(Foot('C')): if display_opts.prices: hf.append(HorizontalSpace('12pt')) hf.append( FootnoteText( NoEscape( r"\$ amount shown is recommended tip, calculated from cost of ingredients" ))) with hf.create(Foot('R')): hf.append(FootnoteText(Command('thepage'))) doc.preamble.append(hf) doc.change_document_style("schubarheaderfooter")
def generate_results_file(self, title, xml_file, csv_file, outputfile, clean_tex=False): structure = SurveyXML(xml_file).get_survey_structure() results = ResultsCSV(csv_file) self.add_title(title) for question_group in structure: section_name = question_group['group_name'] with self.doc.create(Section(section_name)): for parent_question in question_group['questions']: parent_question_name = parent_question['question_name'] question_responses = parent_question['question_responses'] question_type = parent_question['question_type'] sub_questions = parent_question['sub_questions'] if question_type == 'matrix': if parent_question_name not in exclude_question_names: self.doc.append(parent_question_name) self.doc.append('\n\n') for sub_question in sub_questions: coords = results.get_coords( parent_question_name, sub_question, question_responses) if sub_question in with_xticks: xtick_empty = False else: xtick_empty = True question = MatrixQuestion(sub_question, coords, xtick_empty) latex_question = self.get_latex_question(question) self.doc.append(latex_question) self.doc.append('\n\n') elif question_type == 'matrix_five_points': if '-->' in sub_questions[0]: self.doc.append(parent_question_name) self.doc.append('\n\n') for sub_question in sub_questions: responses = [ int(response) for response in question_responses ] coords = results.get_coords( parent_question_name, sub_question, responses) if '-->' in sub_question: question_title, details = sub_question.split( '-->') text_left, text_right = details.split('|') else: question_title = parent_question_name text_left, text_right = sub_question.split('|') question = MatrixFivePointsQuestion( question_title, coords, text_left, text_right) latex_question = self.get_latex_question(question) self.doc.append(latex_question) self.doc.append('\n\n') elif question_type == 'multiple_choice': coords, sonstiges = results.get_coords_and_sonstiges_multiple_choice( parent_question_name, question_responses) question = MultipleChoiceQuestion( parent_question_name, coords) latex_question = self.get_latex_question(question) self.doc.append(latex_question) self.doc.append('\n') self.doc.append(HorizontalSpace('7cm')) self.doc.append( NoEscape(r'Sonstiges: %s' % r'; '.join(sonstiges))) self.doc.append('\n\n') elif question_type == 'text': if not section_name == 'Freitext': self.doc.append(bold(parent_question_name)) self.doc.append('\n\n') text = results.get_text_responses( parent_question_name) else: text = results.get_text_responses( freitext_question) self.doc.append(' \n\n '.join(text)) self.doc.append('\n\n') elif question_type == 'yes_no': num_yes, num_no = results.get_num_yes_num_no( parent_question_name) question = YesNoQuestion(parent_question_name, num_yes, num_no) latex_question = self.get_latex_question(question) self.doc.append(latex_question) self.doc.append('\n\n') elif question_type == 'single_choice': coords = results.get_coords_single_choice( parent_question_name, question_responses) question = MultipleChoiceQuestion( parent_question_name, coords) latex_question = self.get_latex_question(question) self.doc.append(latex_question) self.doc.append('\n\n') elif question_type == 'gesamtnote': responses = [ int(response) for response in question_responses ] coords = results.get_coords(parent_question_name, None, responses) question = MatrixFivePointsQuestion( parent_question_name, coords, text_left='', text_right='') latex_question = self.get_latex_question(question) self.doc.append(latex_question) self.doc.generate_pdf(outputfile, clean_tex=clean_tex)
def gerar_pdf_certificado(certificado): # Configurações da classe geometry_options = {'landscape': True, 'left': '2cm', 'right': '1cm'} doc = Document(geometry_options=geometry_options, lmodern=False, document_options=['a4paper', 'brazil'], inputenc=None, fontenc=None, font_size='footnotesize') # Pacotes doc.packages.add(Package('microtype')) doc.packages.add(Package('indentfirst')) doc.packages.add(Package('graphicx')) doc.packages.add(Package('calc')) doc.packages.add(Package('fontspec')) options_background = ['scale=1', 'opacity=1', 'angle=0'] doc.packages.add(Package('background', options=options_background)) doc.packages.add(Package('csquotes')) # Configurações (preâmbulo) doc.preamble.append(Command('MakeOuterQuote', '\"')) # coverte aspas automaticamente, sem precisar de `` e '' doc.preamble.append(Command('renewcommand', arguments=[Command('baselinestretch'), '1.5'])) doc.preamble.append(Command('setlength', arguments=[Command('parindent'), NoEscape(r'.35\textwidth')])) doc.preamble.append(Command('setlength', arguments=[Command('parskip'), '0.2cm'])) doc.preamble.append(Command('setlength', arguments=[Command('emergencystretch'), '5pt'])) # Imagem de fundo doc.preamble.append(NoEscape(r'\backgroundsetup{ contents=\includegraphics{modelo-certificado-20.pdf} }')) # Diretório das imagens img_dir = '{}/base/static/img/'.format(BASE_DIR) # necessário barra no final doc.preamble.append(UnsafeCommand('graphicspath', '{{{}}}'.format(img_dir))) # Início do documento doc.append(UnsafeCommand('setmainfont', 'Latin Modern Sans', ['SizeFeatures={Size=16}', 'Ligatures=TeX'])) doc.append(Command('pagestyle', 'empty')) doc.append(Command('BgThispage')) doc.append(VerticalSpace(size='2cm', star=True)) with doc.create(FlushRight()) as fr: fr.append(StandAloneGraphic('titulo-certificado.pdf', 'width=6.5cm')) fr.append(LineBreak()) doc.append(VerticalSpace(size=NoEscape('-1cm'), star=True)) doc.append(Command('Large')) # Usado para o nome dos meses ('%B') locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8') inicio = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower() fim = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower() # TODO: tá faltando coisa texto_principal = r''' Certificamos que \textbf{{{nome}}} atuou como {funcao}, {sob_coordenacao}no período de {inicio} a {fim}, na cidade de Foz do Iguaçu -- Paraná, com a atividade de extensão: "\textbf{{{titulo}}}", com carga horária de {carga_horaria_total} horas. ''' if certificado.funcao.nome == 'Coordenador(a)': sob_coordenacao = '' else: nome_coordenador = certificado.relatorio.projeto_extensao.coordenador.nome_completo sob_coordenacao = r'sob a coordenação de \textbf{{{}}}, '.format(escape_latex(nome_coordenador)) texto_principal = texto_principal.format(nome=escape_latex(certificado.nome), funcao=certificado.funcao.nome.lower(), sob_coordenacao=sob_coordenacao, inicio=inicio, fim=fim, titulo=escape_latex(certificado.relatorio.projeto_extensao.titulo), carga_horaria_total=str(certificado.carga_horaria_total).split('.')[0]) # texto_principal = NoEscape(r''' # Certificamos que \textbf{Adriana de Oliveira Gomes} participou como bolsista do Programa de Apoio a Inclusão Social em Atividades de Extensão -- Convênio No 750/2014 -- Fundação Araucária, Edital 05/2014-PROEX, sob a orientação do (a) professor (a) \textbf{Fernando Amâncio Aragão}, no período de outubro/2014 a setembro/2015, com a atividade de extensão: \textbf{''Atendimento fisioterapêutico para pacientes com sequelas neurológicas baseada em tarefas funcionais.''}, com carga horária de 960 (novecentas e sessenta) horas. # ''') doc.append(NoEscape(texto_principal)) doc.append(VerticalSpace(size='1.5cm', star=True)) doc.append(HorizontalSpace(size='7cm', star=True)) dia = timezone.now().strftime('%d') mes = timezone.now().strftime('%B') ano = timezone.now().strftime('%Y') data = NoEscape(r'Foz do Iguaçu, {} de {} de {}'.format(dia, mes, ano)) largura = Command('widthof', data).dumps() with doc.create(MiniPage(width=largura)) as mini: with mini.create(Center()) as center: center.append(data) center.append(NewLine()) center.append(NewLine()) center.append(NewLine()) center.append('Coordenador do Projeto de Extensão') center.append(NewLine()) center.append(NewLine()) center.append(NewLine()) center.append('Diretor de Centro') os.system('mkdir -p ' + PDF_DIR) filepath = '{}/certificado_{}'.format(PDF_DIR, str(certificado.id)) doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS) return filepath
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
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/