コード例 #1
0
def generate_bill(a_family, a_cost_per_person):
    a_title = DIR_UBERSICHT + "Vorauszahlung_Ubersicht_"+a_family+".pdf"
    pdf = PDFDocument(a_title)
    pdf.init_report()
    pdf.p_markup("Automatisch generiert am: "+ str(date.today()), pdf.style.right)
    pdf.spacer(20)
    pdf.h1("Übersicht Vorauszahlung für Familie " + a_family)
    pdf.spacer(20)
    pdf.h2("Kostenaufstellung")
    pdf.hr()
    pdf.spacer(10)
    my_list = []
    q = db.query(Members).join(Familys).filter_by(f_name=a_family)
    total = 0
    for result in db.execute(q):
        my_list.append([result[2] + " " + result[3], str(a_cost_per_person) + " €"])
        total += a_cost_per_person
    try:
        pdf.table(my_list, 220)
    except Exception:
        print("No members")
    pdf.spacer(10)
    pdf.hr()
    pdf.spacer(20)
    pdf.p_markup("Total: " + str(total) + " €", pdf.style.bold)
    pdf.spacer(20)
    pdf.p(UBERWEISUNG_FOOTER)
    pdf.generate()
    return os.path.abspath(a_title)
コード例 #2
0
ファイル: Description.py プロジェクト: Eggiverse/FAE
    def Run(self, pipeline, result_folder, store_folder):

        # Data Description
        data_description_text = "    "

        all_training_result_csv_path = os.path.join(result_folder, 'all_train_result.csv')
        if not os.path.exists(all_training_result_csv_path):
            print('There is no result here')
            return False

        all_training_result_df = pd.read_csv(all_training_result_csv_path, index_col=0, header=0)
        sample_number = all_training_result_df.iloc[0, :]['sample_number']
        positive_number = all_training_result_df.iloc[0, :]['positive_number']
        negative_number = all_training_result_df.iloc[0, :]['negative_number']
        data_description_text += "We selected {:d} cases as the training data set ({:d}/{:d} = positive/negative)). ".\
            format(sample_number, positive_number, negative_number)

        testing_result_csv_path = os.path.join(result_folder, 'test_result.csv')
        if not os.path.exists(testing_result_csv_path):
            data_description_text += "Since the number of the samples were limited, there was no independent testing data. "
        else:
            testing_result_df = pd.read_csv(testing_result_csv_path, index_col=0, header=0)
            sample_number = testing_result_df.iloc[0, :]['sample_number']
            positive_number = testing_result_df.iloc[0, :]['positive_number']
            negative_number = testing_result_df.iloc[0, :]['negative_number']
            data_description_text += "We also selected another {:d} cases as the independent testing data " \
                                     "set ({:d}/{:d} = positive/negative). \n" \
                                     "".format(sample_number, positive_number, negative_number)

        # Method Description
        method_description_text = "    "
        method_description_text += pipeline.GetNormalizer().GetDescription()
        method_description_text += pipeline.GetDimensionReduction().GetDescription()
        method_description_text += pipeline.GetFeatureSelector().GetDescription()
        method_description_text += pipeline.GetClassifier().GetDescription()
        method_description_text += pipeline.GetCrossValidatiaon().GetDescription()
        method_description_text += "\n"

        statistic_description_text = "    The performance of the model was evaluated using receiver operating characteristic " \
                                     "(ROC) curve analysis. The area under the ROC curve (AUC) was calculated for quantification. " \
                                     "The accuracy, sensitivity, specificity, positive predictive value (PPV), and negative " \
                                     "predictive value (NPV) were also calculated at a cutoff value that maximized the " \
                                     "value of the Yorden index. We also boosted estimation 1000 times and applied paired " \
                                     "t-test to give the 95% confidence interval. All above processes were implemented with " \
                                     "FeAture Explorer (FAE, v0.2.5, https://github.com/salan668/FAE) on Python (3.6.8, https://www.python.org/). \n"

        # Result Description
        result_folder = os.path.join(result_folder, pipeline.GetStoreName())
        result = pd.read_csv(os.path.join(result_folder, 'result.csv'), index_col=0)

        if os.path.exists(testing_result_csv_path):
            result_description_text = "We found that the model based on {:d} features can get the highest AUC on the " \
                                      "validation data set. The AUC and the accuracy could achieve {:.3f} and {:.3f}, respectively. In this point, " \
                                      "The AUC and the accuracy of the model achieve {:.3f} and {:.3f} on testing data set. " \
                                      "The clinical statistics in the diagonsis and the selected features were shown in Table 1 and Table 2. " \
                                      "The ROC curve was shown in Figure 1. \n" \
                                      "".format(pipeline.GetFeatureSelector().GetSelectedFeatureNumber(),
                                                float(result.loc['val_auc'].values),
                                                float(result.loc['val_accuracy'].values),
                                                float(result.loc['test_auc'].values),
                                                float(result.loc['test_accuracy'].values)
                                                )

        else:
            result_description_text = "We found that the model based on {:d} features can get the highest AUC on the " \
                                      "validation data set. The AUC and the accuracy could achieve {:.3f} and {:.3f}, respectively. " \
                                      "The clinical statistics in the diagonsis and the selected features were shown in Table 1 and Table 2. " \
                                      "The ROC curve was shown in Figure 1. \n" \
                                      "".format(pipeline.GetFeatureSelector().GetSelectedFeatureNumber(),
                                                float(result.loc['val_auc'].values), float(result.loc['val_accuracy'].values))

        from reportlab.lib import colors
        table_stype = (
            ('FONT', (0, 0), (-1, -1), '%s' % 'Helvetica', 9),
            ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black),
            ('LINEABOVE', (0, 1), (-1, 1), 1, colors.black),
            ('LINEBELOW', (0, -1), (-1, -1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER')
        )
        table_1_header = "Table 1. Clinical statistics in the diagnosis. "

        if not os.path.exists(testing_result_csv_path):
            table_1 = [['Statistics', 'Value'],
                       ['Accuracy', str(result.loc['val_accuracy'].values[0])],
                       ['AUC', str(result.loc['val_auc'].values[0])],
                       ['AUC 95% CIs', str(result.loc['val_auc 95% CIs'].values[0])],
                       ['NPV', str(result.loc['val_negative predictive value'].values[0])],
                       ['PPV', str(result.loc['val_positive predictive value'].values[0])],
                       ['Sensitivity', str(result.loc['val_sensitivity'].values[0])],
                       ['Specificity', str(result.loc['val_specificity'].values[0])]]
        else:
            table_1 = [['Statistics', 'Value'],
                       ['Accuracy', str(result.loc['test_accuracy'].values[0])],
                       ['AUC', str(result.loc['test_auc'].values[0])],
                       ['AUC 95% CIs', str(result.loc['test_auc 95% CIs'].values[0])],
                       ['NPV', str(result.loc['test_negative predictive value'].values[0])],
                       ['PPV', str(result.loc['test_positive predictive value'].values[0])],
                       ['Sensitivity', str(result.loc['test_sensitivity'].values[0])],
                       ['Specificity', str(result.loc['test_specificity'].values[0])]]

        candidate_file = glob.glob(os.path.join(result_folder, '*coef.csv'))
        if len(candidate_file) > 0:
            coef = pd.read_csv(candidate_file[0], index_col=0, header=0)
            table_2_header = 'Table 2. The coefficients of features in the model. '
            table_2 = [['Features', 'Coef in model']]
            for index in coef.index:
                table_2.append([str(index), "{:.3f}".format(coef.loc[index].values[0])])

        else:
            with open(os.path.join(result_folder, 'feature_select_info.csv'), 'r', newline='') as file:
                reader = csv.reader(file)
                for row in reader:
                    if row[0] == 'selected_feature':
                        features = row[1:]
            table_2_header = 'Table 2. The selected of features. '
            table_2 = [['Features', 'Rank']]
            for index in range(len(features)):
                table_2.append([features[index], str(index + 1)])

        figure_title = "Figure 1. The ROC curve. "

        # Build PDF
        pdf = PDFDocument(os.path.join(store_folder, 'description.pdf'))
        pdf.init_report()
        pdf.h1("Materials and Methods")
        pdf.p(data_description_text)
        pdf.p(method_description_text)
        pdf.p(statistic_description_text)

        pdf.h1("Result")
        pdf.p(result_description_text)
        pdf.table_header(table_1_header)
        pdf.table(table_1, 130, style=table_stype)
        pdf.table_header(table_2_header)
        pdf.table(table_2, 200, style=table_stype)
        pdf.p("\n\n")
        pdf.image(os.path.join(store_folder, 'ROC.jpg'))
        pdf.table_header(figure_title)

        pdf.end_connect("Thanks for using FAE v.0.2.5. If you need a specific description, please connect to Yang Song ([email protected]) or Guang Yang "
              "([email protected]). Welcome any co-operation and discussion. ")
        pdf.generate()
コード例 #3
0
ファイル: reporting.py プロジェクト: matthiask/zivinetz
def assignment_pdf(request, assignment_id):
    assignment = get_object_or_404(
        Assignment.objects.select_related("drudge__user"), pk=assignment_id
    )

    if not request.user.is_staff:
        if assignment.drudge.user != request.user:
            return HttpResponseForbidden("<h1>Access forbidden</h1>")

    result_writer = PdfFileWriter()

    # Generate the first page ################################################
    first_page = BytesIO()
    pdf = PDFDocument(first_page)

    pdf.init_report()
    pdf.generate_style(font_size=10)

    scope_statement = assignment.specification.scope_statement
    address = [
        scope_statement.company_name or u"Verein Naturnetz",
        scope_statement.company_address or u"Chlosterstrasse",
        scope_statement.company_contact_location or u"8109 Kloster Fahr",
    ]

    pdf.spacer(25 * mm)
    pdf.table(list(zip(address, address)), (8.2 * cm, 8.2 * cm), pdf.style.tableBase)
    pdf.spacer(30 * mm)

    pdf.p_markup(
        u"""
Lieber Zivi<br /><br />

Vielen Dank fürs Erstellen deiner Einsatzvereinbarung! Du findest hier nun die
Einsatzvereinbarung und einige Hinweise zum Einsatz beim Naturnetz. Bitte lies
alles nochmals genau durch und überprüfe deine Daten auf Fehler. Wenn alles
korrekt ist, unterschreibe die Einsatzvereinbarung und schicke diese ans
Naturnetz. Die Naturnetz-Adresse ist oben aufgedruckt (passend für ein
Fenstercouvert). Die Blätter mit den Hinweisen solltest du bei dir behalten
und für deinen Zivildiensteinsatz aufbewahren. Mit deiner Unterschrift
bestätigst du, dass du die Bestimmungen gelesen und akzeptiert hast. Die
Adresse unten wird von uns benutzt, um die Einsatzvereinbarung an das
Regionalzentrum weiterzuleiten.<br /><br />

Bestätigung: Ich akzeptiere die internen Bestimmungen des Naturnetz (Beilagen
zur Einsatzvereinbarung).<br /><br /><br /><br />

_________________________________________<br />
%s, %s<br /><br />

Wir freuen uns auf deinen Einsatz!
"""
        % (date.today().strftime("%d.%m.%Y"), assignment.drudge.user.get_full_name())
    )
    pdf.spacer(26 * mm)

    address = u"\n".join(
        [assignment.regional_office.name, assignment.regional_office.address]
    ).replace("\r", "")

    pdf.table([(address, address)], (8.2 * cm, 8.2 * cm), pdf.style.tableBase)

    pdf.generate()

    # Add the first page to the output #######################################
    first_page_reader = PdfFileReader(first_page)
    result_writer.addPage(first_page_reader.getPage(0))

    # Generate the form ######################################################
    overlay = BytesIO()
    pdf = PDFDocument(overlay)

    # pdf.show_boundaries = True
    pdf.init_report(page_fn=create_stationery_fn(AssignmentPDFStationery(assignment)))

    pdf.pagebreak()
    pdf.pagebreak()

    pdf.generate()

    # Merge the form and the overlay, and add everything to the output #######
    eiv_reader = PdfFileReader(
        os.path.join(
            os.path.dirname(os.path.dirname(__file__)),
            "data",
            "Einsatzvereinbarung.pdf",
        )
    )
    overlay_reader = PdfFileReader(overlay)

    for idx in range(2):
        page = eiv_reader.getPage(idx)
        page.mergePage(overlay_reader.getPage(idx))
        result_writer.addPage(page)

    # Add the conditions PDF if it exists ####################################
    if assignment.specification.conditions:
        conditions_reader = PdfFileReader(
            assignment.specification.conditions.open("rb")
        )
        for page in range(conditions_reader.getNumPages()):
            result_writer.addPage(conditions_reader.getPage(page))

    # Response! ##############################################################
    response = HttpResponse(content_type="application/pdf")
    result_writer.write(response)

    response["Content-Disposition"] = "attachment; filename=eiv-%s.pdf" % (
        assignment.pk,
    )
    return response
コード例 #4
0
    def writeToPDF(self, path, data):
        pdf = PDFDocument(path)
        pdf.init_report()
        pdf.generate_style()

        pdf.style.heading1.alignment = TA_CENTER
        pdf.style.heading1.fontSize = 18
        heading_style = pdf.style.heading1

        pdf.h1('Fahrtenbuch Firma RAC', style=heading_style)

        pdf.p('\n\n\n')

        content = [[
            'Name', 'Datum', 'Anfangskilometerstand', 'Endkilometerstand',
            'gefahrene Kilometer', 'Art der Fahrt', 'Zweck der Fahrt',
            'Fahrtanfang', 'Fahrtziel'
        ]]
        for p in data['rides']:
            row = []
            for d in p:
                if (d != 'Bestaetigt'):
                    row.append(self.adjustStringLength(p.get(d)))
            content.append(row)

        # ReportLab formatting
        table_style = (
            ("FONT", (0, 0), (-1, -1), "%s" % pdf.style.fontName, 4),
            ("TOPPADDING", (0, 0), (-1, -1), 2),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 2),
            ("LEFTPADDING", (0, 0), (-1, -1), 2),
            ("RIGHTPADDING", (0, 0), (-1, -1), 2),
            ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
            ("ALIGN", (0, 0), (-1, -1), "CENTER"),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            (
                "FONT",
                (0, 0),
                (-1, 0),
                "%s-Bold" % pdf.style.fontName,
                4.5,
            ),
        )

        header = [['KFZ-Kennzeichen', 'Anfangsdatum', 'Enddatum'],
                  [
                      data['header'][0]['KFZ-Kennzeichen'],
                      data['header'][0]['Anfangsdatum'],
                      data['header'][0]['Enddatum']
                  ]]
        header2 = [['Anfangskilometerstand', 'Endkilometerstand'],
                   [
                       data['header'][0]['Anfangskilometerstand'],
                       data['header'][0]['Endkilometerstand']
                   ]]

        pdf.table(header, 80, style=table_style)
        pdf.table(header2, 80, style=table_style)
        pdf.p('\n\n\n')
        pdf.table(content, 60, style=table_style)
        pdf.generate()