예제 #1
0
run.font.color.rgb = RGBColor(255, 255, 255)
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="000000"/>'.format(nsdecls('w')))
table.rows[0].cells[2]._tc.get_or_add_tcPr().append(shading_elm_1)
#hdr_cells[3].text = 'Translation'
cell3 = hdr_cells[3]
cell3.text = 'Audio Translation'
run = cell2.paragraphs[0].runs[0]
run.font.color.rgb = RGBColor(255, 255, 255)
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="000000"/>'.format(nsdecls('w')))
table.rows[0].cells[3]._tc.get_or_add_tcPr().append(shading_elm_1)

r = 1
for StartTime, subtitle in sorted(dictionary.items()):
    row_cells = table.add_row().cells
    row_cells[0].text = str(r)
    row_cells[1].text = str(StartTime)
    row_cells[2].text = str(subtitle)
    row_cells[3].text = str(subtitles_target[r - 1])
    r += 1

hdr_cells[0].width = Cm(0)
hdr_cells[2].width = Inches(5)
hdr_cells[3].width = Inches(10)

document.save(target + '.docx')

for file in os.listdir('.'):
    filename = os.path.join(os.getcwd(), file)
    newname = filename.replace('.srt.docx', '.docx')
    os.rename(filename, newname)
예제 #2
0
def set_table_width(table, data):
    i = 0
    for w in data:
        set_column_width(table.columns[i], Cm(data[i]))
        i += 1
예제 #3
0
def compila_parte_2(request, id):
    moduli_input_path = os.path.join(settings.STATIC_ROOT, 'RimborsiApp', 'moduli')
    moduli_output_path = os.path.join(settings.MEDIA_ROOT, 'moduli')

    input_file = os.path.join(moduli_input_path, 'ModuloMissione_Part2.docx')
    document = Document(input_file)
    missione = Missione.objects.get(user=request.user, id=id)
    date_richiesta = ModuliMissione.objects.get(missione=missione)
    profile = Profile.objects.get(user=request.user)
    trasporto = Trasporto.objects.filter(missione=missione)
    km_totali = trasporto.filter(mezzo='AUTO').aggregate(Sum('km'))['km__sum'] or 0

    # Remove trasporti that has 0 km
    trasporto = trasporto.filter(costo__gt=0).order_by("data")

    class ParConfig:
        def __init__(self):
            self.config = []
            self.counter = 0

        def append(self, index, values, excludes=[]):
            self.config.append([index, values, excludes])

        def __getitem__(self, index):
            return self.config[index]

    config = ParConfig()
    sottoscritto_gender_friendly = 'Il sottoscritto' if profile.sesso == 'M' else 'La sottoscritta'
    config.append(sottoscritto_gender_friendly, [f'{profile.user.first_name} {profile.user.last_name}'])
    config.append('DICHIARA di aver compiuto la missione a', [
        f'{missione.citta_destinazione} - {missione.stato_destinazione.nome}',
        missione.inizio_ora.strftime('%H:%M'),
        missione.inizio.strftime('%d/%m/%Y'),
        missione.fine_ora.strftime('%H:%M'),
        missione.fine.strftime('%d/%m/%Y')])
    # config.append('DICHIARA di aver ricevuto', ['TODO'])
    config.append('nel caso di utilizzo di mezzo proprio', [f'{km_totali}'])
    # config.append('che il costo del biglietto', ['cosa ci va?'])
    # config.append('che l’originale del fattura/ricevuta cumulativa', ['aaa', 'aaa', 'aaa'])
    # config.append('che il costo della fattura/ricevuta _', ['aa'])
    # config.append('che l’originale del fattura/ricevuta cumulativa, relativo a ___', ['aaa', 'aaa', 'aaa'])
    # config.append('che l’originale del fattura/ricevuta cumulativa, relativo a __________________________ ',
    #               ['aaa', 'aaa', 'aaa'])
    # config.append('che il costo della fattura/ricevuta __________________________ ', ['aa'])
    config.append('Data richiesta', [date_richiesta.parte_2.strftime('%d/%m/%Y')])

    for k, values, excludes in config:
        str = ''
        for par in document.paragraphs:
            if k in par.text:
                for s1, s2 in zip_longest(re.sub('_+', '_', par.text).split('_'), values, fillvalue=''):
                    if s2 != '':
                        str += f'{s1}__{s2}__'
                    else:
                        str += f'{s1}'
                for r in par.runs:
                    if len(r.text) > 0:
                        r.text = ''
                par.add_run(text=str)
                break

    # Tabella `VIAGGIO E TRASPORTO`
    table = document.tables[0]

    while len(table.rows) <= len(trasporto):
        row = table.add_row()

    for i, t in enumerate(trasporto, start=1):
        costo_str = f'{t.costo:.2f} {t.valuta}'
        if t.valuta != 'EUR':
            costo_in_euro = money_exchange(t.data, t.valuta, t.costo)
            costo_str += f' ({costo_in_euro:.2f} EUR)'

        table.cell(i, 0).text = t.data.strftime('%d/%m/%Y')
        table.cell(i, 1).text = f'da {t.da or ""}'
        table.cell(i, 2).text = f'a {t.a or ""}'
        table.cell(i, 3).text = t.mezzo
        table.cell(i, 4).text = t.tipo_costo or ''
        table.cell(i, 5).text = costo_str
        table.rows[i].height = Cm(0.61)

    db_dict = {
        'pernottamento': [],
        'scontrino': [],  # pasti
        'convegno': [],
        'altrespese': [],
    }

    # Load the default values for each field in db_dict
    for k, _ in db_dict.items():
        db_dict[k] = load_json(missione, k)

    # TODO Scontrino dovrebbe essere ordinato per data. Potrebbe essere un pacco.
    r_scontrino = []
    for row in db_dict['scontrino']:
        if row['s1'] is not None:
            r_scontrino.append({'data': row['data'], 's1': row['s1'], 'd1': row['d1'], 'v1': row['v1']})
        if row['s2'] is not None:
            r_scontrino.append({'data': row['data'], 's1': row['s2'], 'd1': row['d2'], 'v1': row['v2']})
        if row['s3'] is not None:
            r_scontrino.append({'data': row['data'], 's1': row['s3'], 'd1': row['d3'], 'v1': row['v3']})
    db_dict['scontrino'] = r_scontrino

    # Fill all the remaining tables
    for index, (key, value) in enumerate(db_dict.items(), start=1):
        table = document.tables[index]

        while len(table.rows) <= len(value):
            row = table.add_row()
            # row.height = Cm(0.61)

        for i, t in enumerate(value, start=1):
            s1 = float(t['s1'])
            valuta = t['v1']
            data = t['data']  #.strftime('%Y-%m-%d')
            costo_str = f'{s1:.2f} {valuta}'
            if valuta != 'EUR':
                costo_in_euro = money_exchange(data, valuta, s1)
                costo_str += f' ({costo_in_euro:.2f} EUR)'

            table.cell(i, 0).text = t['data'].strftime('%d/%m/%Y')
            table.cell(i, 1).text = t['d1'] if t['d1'] is not None else ''
            table.cell(i, 2).text = costo_str
            table.rows[i].height = Cm(0.61)

    output_name_tmp = os.path.join(moduli_output_path, f'Missione_{missione.id}_parte_2_tmp.docx')
    output_name = f'Missione_{missione.id}_parte_2.docx'
    document.save(os.path.join(moduli_output_path, output_name_tmp))
    # Salvo il docx appena creato dentro a un FileField
    moduli_missione = ModuliMissione.objects.get(missione=missione)
    outputStream = open(output_name_tmp, "rb")
    moduli_missione.parte_2_file.save(output_name, outputStream)

    # Elimino il file temporaneo
    os.remove(output_name_tmp)
예제 #4
0
meu_word.add_paragraph('Formatação "No Spacing"', style='No Spacing')
meu_word.add_paragraph('Formatação "Heading 1"', style='Heading 1')
meu_word.add_paragraph('Formatação "Heading 2"', style='Heading 2')
meu_word.add_paragraph('Formatação "Heading 3"', style='Heading 3')
meu_word.add_paragraph('Formatação "Title"', style='Title')
meu_word.add_paragraph('Formatação "Subtitle"', style='Subtitle')
meu_word.add_paragraph('Formatação "Quote"', style='Quote')
meu_word.add_paragraph('Formatação "Intense Quote"', style='Intense Quote')
meu_word.add_paragraph('Formatação "List Paragraph"', style='List Paragraph')
meu_word.add_paragraph('Primeiro item em uma lista com pontos ',
                       style='List Bullet')
meu_word.add_paragraph('Primeiro item em uma lista numerada ',
                       style='List Number')

meu_word.add_picture('russian_skull.jpg', width=Cm(5.25))

# tabela = meu_word.add_table(rows=3, cols=2)
# celula = tabela.cell(0,0)
# celula.text = 'Nome'

registros = (
    (3, '101', 'Maça'),
    (7, '422', 'Ovos'),
    (4, '631', 'Banana'),
)

meu_word.add_page_break()

tabela = meu_word.add_table(rows=1, cols=3)
def printing(quarter_output):
    '''function that compiles the summary sheet'''

    master_list = list_of_masters_all[0:4]

    milestone_master = all_milestone_data_bulk(list_of_masters_all[0].projects, list_of_masters_all[0])

    for project_name in list_of_masters_all[0].projects:
        doc = Document()
        print(project_name)
        heading = str(project_name)
        name = str(project_name)
        # TODO: change heading font size
        # todo be able to change text size and font
        intro = doc.add_heading(str(heading), 0)
        intro.alignment = 1
        intro.bold = True

        y = doc.add_paragraph()
        a = list_of_masters_all[0].data[project_name]['Senior Responsible Owner (SRO)']
        if a == None:
            a = 'TBC'
        else:
            a = a

        b = list_of_masters_all[0].data[project_name]['SRO Phone No.']
        if b == None:
            b = 'TBC'
        else:
            b = b

        y.add_run('SRO name:  ' + str(a) + ',   Tele:  ' + str(b))

        y = doc.add_paragraph()
        a = list_of_masters_all[0].data[project_name]['Project Director (PD)']
        if a == None:
            a = 'TBC'
        else:
            a = a
            b = list_of_masters_all[0].data[project_name]['PD Phone No.']
            if b == None:
                b = 'TBC'
            else:
                b = b

        y.add_run('PD name:  ' + str(a) + ',   Tele:  ' + str(b))

        '''Start of table with DCA confidence ratings'''
        table1 = doc.add_table(rows=1, cols=5)
        table1.cell(0, 0).width = Cm(7)

        '''quarter information in top row of table is here'''
        for i, quarter in enumerate(quarter_list):
            table1.cell(0, i+1).text = quarter

        # '''setting row height - partially working'''
        # # todo understand row height better
        # row = table1.rows[0]
        # tr = row._tr
        # trPr = tr.get_or_add_trPr()
        # trHeight = OxmlElement('w:trHeight')
        # trHeight.set(qn('w:val'), str(200))
        # trHeight.set(qn('w:hRule'), 'atLeast')
        # trPr.append(trHeight)

        SRO_conf_table_list = ['SRO DCA', 'Finance DCA', 'Benefits DCA', 'Resourcing DCA', 'Schedule DCA']
        SRO_conf_key_list = ['Departmental DCA', 'SRO Finance confidence', 'SRO Benefits RAG', 'Overall Resource DCA - Now',
                             'SRO Schedule Confidence']

        '''All SRO RAG rating placed in table'''
        for i in range(0, len(master_list)+1):
            table = doc.add_table(rows=1, cols=5)
            table.cell(0, 0).width = Cm(7)
            table.cell(0, 0).text = SRO_conf_table_list[i]
            for x, master in enumerate(master_list):
                try:
                    rating = convert_rag_text(master.data[project_name][SRO_conf_key_list[i]])
                    table.cell(0, x + 1).text = rating
                    cell_colouring(table.cell(0, x + 1), rating)
                except (KeyError, TypeError):
                    table.cell(0, x + 1).text = 'N/A'

        '''DCA Narrative text'''
        doc.add_paragraph()
        y = doc.add_paragraph()
        heading = 'SRO Overall DCA Narrative'
        y.add_run(str(heading)).bold = True

        dca_a = list_of_masters_all[0].data[project_name]['Departmental DCA Narrative']
        try:
            dca_b = list_of_masters_all[1].data[project_name]['Departmental DCA Narrative']
        except KeyError:
            dca_b = dca_a

        '''comparing text options'''
        # compare_text_showall(dca_a, dca_b, doc)
        compare_text_newandold(dca_a, dca_b, doc)

        '''Finance section'''
        y = doc.add_paragraph()
        heading = 'Financial information'
        y.add_run(str(heading)).bold = True

        '''Financial Meta data'''
        table1 = doc.add_table(rows=2, cols=5)
        table1.cell(0, 0).text = 'Forecast Whole Life Cost (£m):'
        table1.cell(0, 1).text = 'Percentage Spent:'
        table1.cell(0, 2).text = 'Source of Funding:'
        table1.cell(0, 3).text = 'Nominal or Real figures:'
        table1.cell(0, 4).text = 'Full profile reported:'

        wlc = round(list_of_masters_all[0].data[project_name]['Total Forecast'], 1)
        table1.cell(1, 0).text = str(wlc)
        # str(list_of_masters_all[0].data[project_name]['Total Forecast'])
        #a = list_of_masters_all[0].data[project_name]['Total Forecast']
        b = list_of_masters_all[0].data[project_name]['Pre 19-20 RDEL Forecast Total']
        if b == None:
            b = 0
        c = list_of_masters_all[0].data[project_name]['Pre 19-20 CDEL Forecast Total']
        if c == None:
            c = 0
        d = list_of_masters_all[0].data[project_name]['Pre 19-20 Forecast Non-Gov']
        if d == None:
            d = 0
        e = b + c + d
        try:
            c = round(e / wlc * 100, 1)
        except (ZeroDivisionError, TypeError):
            c = 0
        table1.cell(1, 1).text = str(c) + '%'
        a = str(list_of_masters_all[0].data[project_name]['Source of Finance'])
        b = list_of_masters_all[0].data[project_name]['Other Finance type Description']
        if b == None:
            table1.cell(1, 2).text = a
        else:
            table1.cell(1, 2).text = a + ' ' + str(b)
        table1.cell(1, 3).text = str(list_of_masters_all[0].data[project_name]['Real or Nominal - Actual/Forecast'])
        table1.cell(1, 4).text = ''

        '''Finance DCA Narrative text'''
        doc.add_paragraph()
        y = doc.add_paragraph()
        heading = 'SRO Finance Narrative'
        y.add_run(str(heading)).bold = True

        #TODO further testing on code down to 308. current hard code solution not ideal, plus not sure working properly yet

        gmpp_narrative_keys = ['Project Costs Narrative', 'Cost comparison with last quarters cost narrative',
                               'Cost comparison within this quarters cost narrative']

        fin_text_1 = combine_narrtives(project_name, list_of_masters_all[0], gmpp_narrative_keys)
        try:
            fin_text_2 = combine_narrtives(project_name, list_of_masters_all[1], gmpp_narrative_keys)
        except KeyError:
            fin_text_2 = fin_text_1

        # if narrative == 'NoneNoneNone':
        #     fin_text = combine_narrtives(name, dictionary_1, bicc_narrative_keys)
        # else:
        #     fin_text = narrative

        compare_text_newandold(fin_text_1, fin_text_2, doc)
        #compare_text_showall()

        '''financial chart heading'''
        y = doc.add_paragraph()
        heading = 'Financial Analysis - Cost Profile'
        y.add_run(str(heading)).bold = True
        y = doc.add_paragraph()
        y.add_run('{insert chart}')

        '''milestone section'''
        y = doc.add_paragraph()
        heading = 'Planning information'
        y.add_run(str(heading)).bold = True

        '''Milestone Meta data'''
        table1 = doc.add_table(rows=2, cols=4)
        table1.cell(0, 0).text = 'Project Start Date:'
        table1.cell(0, 1).text = 'Latest Approved Business Case:'
        table1.cell(0, 2).text = 'Start of Operations:'
        table1.cell(0, 3).text = 'Project End Date:'

        key_dates = milestone_master[project_name]

        #c = key_dates['Start of Project']
        try:
            c = tuple(key_dates['Start of Project'])[0]
            c = datetime.datetime.strptime(c.isoformat(), '%Y-%M-%d').strftime('%d/%M/%Y')
        except (KeyError, AttributeError):
            c = 'Not reported'

        table1.cell(1, 0).text = str(c)

        table1.cell(1, 1).text = str(list_of_masters_all[0].data[project_name]['IPDC approval point'])

        try:
            a = tuple(key_dates['Start of Operation'])[0]
            a = datetime.datetime.strptime(a.isoformat(), '%Y-%M-%d').strftime('%d/%M/%Y')
            table1.cell(1, 2).text = str(a)
        except (KeyError, AttributeError):
            table1.cell(1, 2).text = 'Not reported'

        #b = key_dates['Project End Date']
        try:
            b = tuple(key_dates['Project End Date'])[0]
            b = datetime.datetime.strptime(b.isoformat(), '%Y-%M-%d').strftime('%d/%M/%Y')
        except (KeyError, AttributeError):
            b = 'Not reported'
        table1.cell(1, 3).text = str(b)

        # TODO: workout generally styling options for doc, paragraphs and tables

        '''milestone narrative text'''
        doc.add_paragraph()
        y = doc.add_paragraph()
        heading = 'SRO Milestone Narrative'
        y.add_run(str(heading)).bold = True

        mile_dca_a = list_of_masters_all[0].data[project_name]['Milestone Commentary']
        if mile_dca_a == None:
            mile_dca_a = 'None'

        try:
            mile_dca_b = list_of_masters_all[1].data[project_name]['Milestone Commentary']
            if mile_dca_b == None:
                mile_dca_b = 'None'
        except KeyError:
            mile_dca_b = mile_dca_a

        # compare_text_showall()
        compare_text_newandold(mile_dca_a, mile_dca_b, doc)

        '''milestone chart heading'''
        y = doc.add_paragraph()
        heading = 'Project reported high-level milestones and schedule changes'
        y.add_run(str(heading)).bold = True
        y = doc.add_paragraph()
        some_text = 'The below table presents all project reported remaining high-level milestones, with six months grace ' \
                    'from close of the current quarter. Milestones are sorted in chronological order. Changes in milestones' \
                    ' dates in comparison to last quarter and baseline have been calculated and are provided.'
        y.add_run(str(some_text)).italic = True
        y = doc.add_paragraph()
        y.add_run('{insert chart}')

        doc.save(root_path/'output/{}_summary.docx'.format(project_name + quarter_output))
예제 #6
0

document = Document('form.docx')

fontn = document.styles['Normal'].font
fontn.size = Pt(9)
fontn.name = 'Frutiger LT 45 Light'
fontn.color.rgb = RGBColor(31, 73, 125)

# document.add_heading('PHAST Analysis - ' + folder, level=0)

ISs = []
for e in lEvent:
    pvis, hole, weather = e.Key.split("\\")
    if not (pvis in ISs):
        ISs.append(pvis)

for IS in ISs:
    document.add_heading(IS, level=1)
    for e in lEvent:
        pvis, hole, weather = e.Key.split("\\")
        if IS == pvis:
            fn = 'C\\' + folder + '\\C_' + slugify(e.Key) + '_2.png'
            document.add_picture(fn, width=Cm(15))

            p = document.add_paragraph('Figure', style='FigureCaption')
            Figure(p)
            p.add_run(" " + pvis + " Hole: " + hole + " Weather: " + weather)
    document.add_page_break()
document.save('C_' + folder + '_Rev.2.docx')
def usage_of_style_doc():
    document = Document()
    styles = document.styles
    table_styles = [s for s in styles if s.type == WD_STYLE_TYPE.TABLE]
    for style in table_styles:
        print(style.name)


    # 准备一些数据
    document = Document()
    vmem = psutil.virtual_memory()
    vmem_dict = vmem._asdict()
    trow = 2
    tcol = len(vmem_dict.keys())
    # 指定样式修饰表格
    table = document.add_table(rows=trow, cols=tcol, style='Colorful Grid Accent 4')
    for col, info in enumerate(vmem_dict.keys()):
        table.cell(0, col).text = info
        if info == 'percent':
            table.cell(1, col).text = str(vmem_dict[info]) + '%'
        else:
            table.cell(1, col).text = str(vmem_dict[info] / (1024 * 1024)) + 'M'
    document.save(PROJECT_PATH + "/file_location/table-style.docx")

    # 创建样式和设置字体
    doc = Document()
    for i in range(10):
        p = doc.add_paragraph(u'段落 % d' % i)
        style = doc.styles.add_style('UserStyle%d' % i, WD_STYLE_TYPE.PARAGRAPH)
        style.font.size = Pt(i + 20)
        p.style = style
    doc.save(PROJECT_PATH + '/file_location/style-1.docx')

    # 设置字体样式
    doc = Document()
    p = doc.add_paragraph()
    text_str = u'好好学习Python,努力做开发专家,成为最牛的程序员。'
    for i, ch in enumerate(text_str):
        run = p.add_run(ch)
        font = run.font
        font.name = u'微软雅黑'
        # bug of python-docx
        run._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
        font.bold = (i % 2 == 0)
        font.italic = (i % 3 == 0)
        color = font.color
        color.rgb = RGBColor(i * 10 % 200 + 55, i * 20 % 200 + 55, i * 30 % 200 + 55)
    doc.save(PROJECT_PATH + '/file_location/style-2.docx')

    # 设置段落格式
    doc = Document()
    for i in range(10):
        p = doc.add_paragraph(u'段落 % d' % i)
        style = doc.styles.add_style('UserStyle%d' % i, WD_STYLE_TYPE.PARAGRAPH)
        style.paragraph_format.left_indent = Cm(i)
        p.style = style

    doc.save(PROJECT_PATH + '/file_location/style-3.docx')


    # 样式管理器
    doc = Document()
    for i in range(10):
        p = doc.add_paragraph(u'段落 % d' % i)
        style = doc.styles.add_style('UserStyle%d' % i, WD_STYLE_TYPE.PARAGRAPH)
        style.paragraph_format.left_indent = Cm(i)
        p.style = style
        if i == 7:
            style.hidden = False
            style.quick_style = True

    for style in doc.styles:
        print(style.name, style.builtin)

    doc.paragraphs[3].style = doc.styles['Subtitle']
    doc.save(PROJECT_PATH + '/file_location/style-4.docx')
예제 #8
0
def df2docx(df, output_folder, tar_folder, row_switch: bool):

    docx_name = tar_folder + u"缺陷匯總表.docx"

    # get basic info from df
    if row_switch:
        wtf = df.shape[0]
    else:
        wtf = 100

    row_length = wtf
    col_length = df.shape[1]

    print("-> Total Row: {}".format(row_length))

    # open temp docx file
    doc = docx.Document()

    # adjust border
    section_0 = doc.sections[0]
    section_0.left_margin = Cm(1.27)
    section_0.right_margin = Cm(1.27)
    section_0.top_margin = Cm(1.27)
    section_0.bottom_margin = Cm(1.27)

    table_0 = doc.add_table(rows=2, cols=col_length, style='Table Grid')
    table_0.alignment = WD_TABLE_ALIGNMENT.CENTER
    # deal with heading
    table_0.cell(0, 0).merge(table_0.cell(1, 0))
    table_0.cell(0, 1).merge(table_0.cell(1, 1))
    table_0.cell(0, 2).merge(table_0.cell(1, 2))
    table_0.cell(0, 3).merge(table_0.cell(1, 3))
    table_0.cell(0, 4).merge(table_0.cell(1, 4))
    table_0.cell(0, 5).merge(table_0.cell(1, 5))
    table_0.cell(0, 6).merge(table_0.cell(0, 8))
    table_0.cell(0, 9).merge(table_0.cell(0, 11))
    table_0.cell(0, 12).merge(table_0.cell(1, 12))

    table_0.cell(0, 0).text = u"序號"
    table_0.cell(0, 1).text = u"區間"
    table_0.cell(0, 2).text = u"距小號塔距離(m)"
    table_0.cell(0, 3).text = u"地物危險點座標"
    table_0.cell(0, 4).text = u"缺陷類型"
    table_0.cell(0, 5).text = u"缺陷級別"
    table_0.cell(0, 6).text = u"實測距離(m)"
    table_0.cell(0, 9).text = u"規範要求安全距離(m)"
    table_0.cell(0, 12).text = u"圖示"

    table_0.cell(1, 6).text = u"平距"
    table_0.cell(1, 7).text = u"垂距"
    table_0.cell(1, 8).text = u"直線距離"
    table_0.cell(1, 9).text = u"平距"
    table_0.cell(1, 10).text = u"垂距"
    table_0.cell(1, 11).text = u"直線距離"

    print("---> table header ok.")

    table_1 = doc.add_table(rows=row_length,
                            cols=col_length,
                            style='Table Grid')
    table_cells_1 = table_1._cells

    table_1.alignment = WD_TABLE_ALIGNMENT.CENTER
    print("---> table added.")

    for i in range(row_length):
        print("-> Row Processing: {} / {}".format(i + 1, row_length))
        row_cells = table_cells_1[i * col_length:(i + 1) * col_length]
        for j in range(len(row_cells)):
            insert_value = df.iloc[i, j]
            if j == 0:
                insert_value = str(int(insert_value))
            if j >= 6 and j <= 11:
                insert_value = "{:.3f}".format(insert_value)
            if str(insert_value) == "nan":
                insert_value = ""
            row_cells[j].text = str(insert_value)

        #Add text to row_cells

    doc.save(output_folder + "/" + tar_folder + "/" + docx_name)
    print("---> docx saved.")
예제 #9
0
from docx import Document
from docx.shared import Cm
import json

if __name__ == '__main__':
    with open('../ms_wiki_data/relations.json', 'r', encoding='utf-8') as f:
        rel = json.load(f)
    style = 'Table Grid'

    document = Document()

    table = document.add_table(len(rel) + 1, 3)
    table.style = style
    table.rows[0].cells[0].text = '关系名(en)'
    table.rows[0].cells[0].width = Cm(5)
    table.rows[0].cells[1].text = '关系名(zh)'
    table.rows[0].cells[1].width = Cm(5)
    table.rows[0].cells[2].text = '内部关系'
    table.rows[0].cells[2].width = Cm(15)

    for i, j in enumerate(rel):
        table.rows[i + 1].cells[0].text = j
        table.rows[i + 1].cells[0].width = Cm(5)
        table.rows[i + 1].cells[1].text = rel[j]['zh']
        table.rows[i + 1].cells[1].width = Cm(5)
        table.rows[i + 1].cells[2].width = Cm(15)
        if j.__contains__('multi'):
            i_rel = rel[j]['inner_relation']
            i_table = table.rows[i + 1].cells[2].add_table(len(i_rel) + 1, 2)
            i_table.style = style
# Confidence of each word as scatter graph
plt.scatter(stats['timestamps'], stats['accuracy'])
# Mean average as line across graph
plt.plot(
    [stats['timestamps'][0], stats['timestamps'][-1]],
    [statistics.mean(stats['accuracy']),
     statistics.mean(stats['accuracy'])], 'r')
# Formatting
plt.xlabel('Time (seconds)')
#plt.xticks(range(0, int(stats['timestamps'][-1]), 60))
plt.ylabel('Accuracy (percent)')
plt.yticks(range(0, 101, 10))
plt.title('Accuracy during video')
plt.legend(['Accuracy average (mean)', 'Individual words'], loc='lower center')
plt.savefig('chart.png')
document.add_picture('chart.png', width=Cm(14.64))
document.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER
document.add_page_break()

# Process and display transcript by speaker segments
print('Writing transcript...')
table = document.add_table(rows=1, cols=3)
table.style = document.styles['Light List Accent 1']
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Time'
hdr_cells[1].text = 'Speaker'
hdr_cells[2].text = 'Content'

for segment in data['results']['speaker_labels']['segments']:
    # If there is content in the segment
    if len(segment['items']) > 0:
 def columns_width(self, cols, width):
     # 表の列幅を変更する
     for cell in self.table.columns[cols].cells:
         cell.width = Cm(width)
예제 #12
0
# coding : utf-8

from docx import Document
from docx.shared import Cm, Pt
import io

document = Document()

p = document.add_paragraph(u'New things.呵呵呵enenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenen呵enenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenenen')

k = p.style.paragraph_format
k.line_spacing = Cm(0.5)

sections = document.sections
for section in sections:
    section.top_margin = Cm(1)
    section.bottom_margin = Cm(1)
    section.left_margin = Cm(1)
    section.right_margin = Cm(1)

new = 
document.save(new)

print(new)
예제 #13
0
 def add_img(self, path):
     self.document.add_picture(path, width=Cm(15), height=Cm(15))
예제 #14
0
    # try:
    # document.add_picture("D:\python\image\\" + pic,width=Inches(2.5),height=Inches(5))
    # except:
    #     print('暂时无法识别',pic)
    row = int(i / 2)
    col = 0
    if (i == 1 or i == 0):
        col = i
    elif (i == 3):
        col = 1
    else:
        col = i % int(i / 2)

    cell = table.cell(row, col)
    print("i = " + str(i) + "\t行:" + str(row) + "\t列:" + str(col))
    cell.width = Cm(4.5)
    if i < len(pictures):
        run = cell.paragraphs[0].add_run()  # type:Paragraph
        run.add_picture(imagePath + '\\' + pictures[i],
                        width=Cm(6.5),
                        height=Cm(11))

# 判断路径是否存在
# 存在     True
# 不存在   False
isExists = os.path.exists(savePath)

# 判断结果
if not isExists:
    # 如果不存在则创建目录
    # 创建目录操作函数
    max2 = ansys.iloc[tabindex + 2, 1]
    max2 = abs(max2)
    min2 = ansys.iloc[tabindex + 3, 1]
    min2 = abs(min2)
    outnum2 = max(max2, min2)

    max3 = ansys.iloc[tabindex + 4, 1]
    max3 = abs(max3)
    min3 = ansys.iloc[tabindex + 5, 1]
    min3 = abs(min3)
    outnum3 = max(max3, min3)
    calc_book.add_paragraph(
        f'内爬钢梁X向最大挠度{ceil(outnum1)}mm,Y向最大挠度{ceil(outnum2)}mm,Z向最大挠度{ceil(outnum3)}mm:',
        style='Normal')
    calc_book.add_paragraph('', style='No Spacing').add_run('').add_picture(
        f'{picnum}.png', height=Cm(7))
    picnum = picnum + 1
    calc_book.add_paragraph('', style='No Spacing').add_run('').add_picture(
        f'{picnum}.png', height=Cm(7))
    picnum = picnum + 1
    calc_book.add_paragraph('', style='No Spacing').add_run('').add_picture(
        f'{picnum}.png', height=Cm(7))
    picnum = picnum + 1
    max4 = ansys.iloc[tabindex + 6, 1]
    max4 = abs(max4)
    min4 = ansys.iloc[tabindex + 7, 1]
    min4 = abs(min4)
    outnum4 = max(max4, min4)
    calc_book.add_paragraph(f'内爬钢梁最大Mises应力{ceil(outnum4)}MPa:',
                            style='Normal')
    calc_book.add_paragraph('', style='No Spacing').add_run('').add_picture(
예제 #16
0
파일: exports.py 프로젝트: NHS-NGS/GeL2MDT
def write_mdt_outcome_template(report):
    """
    :param pk: GEL Interpretationreport instance
    :return: Writes a docx template file for summarising proband MDT outcomes
    """
    document = Document()
    document.add_picture(os.path.join(settings.STATIC_DIR, 'nhs_image.png'))
    header_image = document.paragraphs[-1]
    header_image.alignment = WD_ALIGN_PARAGRAPH.RIGHT 
 
    document.add_heading('Genomics MDM record', 0)

    table = document.add_table(rows=1, cols=1, style='Table Grid')
    table.rows[0].cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = table.rows[0].cells[0].paragraphs[0].add_run(
        'THIS IS NOT A DIAGNOSTIC REPORT. UNVALIDATED FINDINGS SHOULD NOT BE USED TO INFORM CLINICAL '
        'MANAGEMENT DECISIONS.\n')
    run.font.color.rgb = RGBColor(255, 0, 0)
    run = table.rows[0].cells[0].paragraphs[0].add_run(
        'This is a record of unvalidated variants identified through the 100,000 genome project. '
        'Class 3 variants are of uncertain clinical significance, future review and diagnostic confirmation '
        'may be appropriate if further evidence becomes available.\n')
    run.font.color.rgb = RGBColor(255, 0, 0)

    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.3)
    # table.rows[0].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.1)
    paragraph = document.add_paragraph()
    paragraph.add_run()

    table = document.add_table(rows=2, cols=4, style='Table Grid')
    heading_cells = table.rows[0].cells
    heading_cells[0].paragraphs[0].add_run('Patient Name').bold=True
    heading_cells[1].paragraphs[0].add_run('DOB').bold=True
    heading_cells[2].paragraphs[0].add_run('NHS number').bold=True
    heading_cells[3].paragraphs[0].add_run('Local ID').bold=True

    row = table.rows[1].cells
    row[0].text = str(report.ir_family.participant_family.proband.forename) \
                  + ' ' \
                  + str(report.ir_family.participant_family.proband.surname)
    row[1].text = str(report.ir_family.participant_family.proband.date_of_birth.date())
    try:
        row[2].text = report.ir_family.participant_family.proband.nhs_number
    except TypeError:
        row[2].text = ''
    if report.ir_family.participant_family.proband.local_id:
        row[3].text = report.ir_family.participant_family.proband.local_id

    paragraph = document.add_paragraph()
    paragraph.add_run()
    paragraph.add_run('Referring Clinician: ').bold=True
    paragraph.add_run('{}\n'.format(report.ir_family.participant_family.clinician))
    paragraph.add_run('Department/Hospital: ').bold=True
    paragraph.add_run('{}\n'.format(report.ir_family.participant_family.proband.gmc))
    paragraph.add_run('Study: ').bold=True
    paragraph.add_run('100,000 genomes (whole genome sequencing)\n')
    paragraph.add_run('OPA ID: ').bold = True
    paragraph.add_run('{}\n'.format(report.ir_family.ir_family_id))
    paragraph.add_run('Family ID: ').bold=True
    paragraph.add_run('{}\n'.format(report.ir_family.participant_family.gel_family_id))
    paragraph.add_run('Genome Build: ').bold=True
    paragraph.add_run('{}\n\n'.format(report.assembly))

    # paragraph.add_run('Phenotype summary: ').bold=True
    # if sample_info.hpo_terms:
    #    paragraph.add_run('{}\n'.format(', '.join(list(json.loads(sample_info.hpo_terms)))))

    proband_variants = list(ProbandVariant.objects.filter(interpretation_report=report))

    run = paragraph.add_run('MDT:\n')
    run.font.size = Pt(16)
    run.underline = True
    run.bold = True

    if proband_variants:
        run = paragraph.add_run('Variant Outcome Summary:\n')
        run.font.size = Pt(13)
        run.underline = True
        run.bold = True

        table = document.add_table(rows=1, cols=7, style='Table Grid')
        heading_cells = table.rows[0].cells
        run = heading_cells[0].paragraphs[0].add_run('Gene')
        run.bold=True
        run.font.size = Pt(9)
        run = heading_cells[1].paragraphs[0].add_run('HGVSg')
        run.bold = True
        run.font.size = Pt(9)
        run = heading_cells[2].paragraphs[0].add_run('HGVSc')
        run.bold = True
        run.font.size = Pt(9)
        run = heading_cells[3].paragraphs[0].add_run('HGVSp')
        run.bold = True
        run.font.size = Pt(9)
        run = heading_cells[4].paragraphs[0].add_run('Zygosity')
        run.bold = True
        run.font.size = Pt(9)
        run = heading_cells[5].paragraphs[0].add_run('Phenotype Contribution')
        run.bold = True
        run.font.size = Pt(9)
        run = heading_cells[6].paragraphs[0].add_run('Class')
        run.bold = True
        run.font.size = Pt(9)

    for proband_variant in proband_variants:
        cells = table.add_row().cells
        transcript = proband_variant.get_transcript()
        transcript_variant = proband_variant.get_transcript_variant()
        if transcript is None or transcript_variant is None:
            raise ValueError(f"Please select transcripts for all variants before exporting\n")
        rdr = proband_variant.create_rare_disease_report()
        run = cells[0].paragraphs[0].add_run(str(transcript.gene))
        run.font.size = Pt(7)
        run = cells[1].paragraphs[0].add_run(str(transcript_variant.hgvs_g))
        run.font.size = Pt(7)
        run = cells[2].paragraphs[0].add_run(str(transcript_variant.hgvs_c))
        run.font.size = Pt(7)
        run = cells[3].paragraphs[0].add_run(str(transcript_variant.hgvs_p))
        run.font.size = Pt(7)
        run = cells[4].paragraphs[0].add_run(str(proband_variant.zygosity))
        run.font.size = Pt(7)
        run = cells[5].paragraphs[0].add_run(str(rdr.get_contribution_to_phenotype_display()))
        run.font.size = Pt(7)
        run = cells[6].paragraphs[0].add_run(str(rdr.classification))
        run.font.size = Pt(7)

    mdt_linkage_list = MDTReport.objects.filter(interpretation_report=report).values('MDT')
    mdt = MDT.objects.filter(id__in=mdt_linkage_list).order_by('-date_of_mdt').first()

    paragraph = document.add_paragraph()

    paragraph.add_run('MDT Date: ').bold = True
    paragraph.add_run('{}\n'.format(mdt.date_of_mdt.date()))
    paragraph.add_run('MDT Attendees: ').bold = True
    clinicians = Clinician.objects.filter(mdt=mdt.id).values_list('name', flat=True)
    clinical_scientists = ClinicalScientist.objects.filter(mdt=mdt.id).values_list('name', flat=True)
    other_staff = OtherStaff.objects.filter(mdt=mdt.id).values_list('name', flat=True)

    attendees = list(clinicians) + list(clinical_scientists) + list(other_staff)
    paragraph.add_run('{}\n\n'.format(', '.join(attendees)))
    paragraph.add_run()
    run = paragraph.add_run('Discussion:\n')
    run.font.size = Pt(13)
    run.underline = True
    run.bold = True
    paragraph.add_run('{}\n\n'.format(report.ir_family.participant_family.proband.discussion.rstrip()))
    run = paragraph.add_run('Action:\n')
    run.font.size = Pt(13)
    run.underline = True
    run.bold = True
    paragraph.add_run('{}\n'.format(report.ir_family.participant_family.proband.action.rstrip()))
    return document, mdt
예제 #17
0
    except:
        print('請輸入五碼就好')
while True:
    password = input('progressnote密碼(預設為身份證字號):')
    try:
        if len(password) == 10:
            password = re.match(r'[a-zA-z]\d{9}', password).group(0).upper()
            break
        else:
            print('請輸入身份證字號')
    except:
        print('請輸入身份證字號')
#創建patientlist的word檔案
document = Document(location + r'\\default.docx')
section = document.sections[0]
section.left_margin = Cm(0.5)
section.right_margin = Cm(0.5)
section.top_margin = Cm(1.27)
section.bottom_margin = Cm(1.27)

today = datetime.today()
todaydate = str(today.year) + str(today.month).zfill(2) + str(
    today.day).zfill(2)

paragraph = document.add_paragraph(todaydate + '\n')
#看是要哪一個主治的patient list
atten = input('主治DOC五碼就好,不需要請直接enter:')
if atten != '':
    atten = 'DOC' + atten
ward = input('請輸入病房號兩碼,不需要請直接enter:')
ward = ward.upper()
예제 #18
0
파일: exports.py 프로젝트: NHS-NGS/GeL2MDT
def write_gtab_template(report):
    '''
    Given a Cancer report, write a report template for GTAB
    :param report: GELInterpretation instance
    :return: docx document to be exported
    '''
    proband_variants = list(ProbandVariant.objects.filter(interpretation_report=report))

    document = Document()
    sections = document.sections
    for section in sections:
        section.left_margin = Inches(0.5)
        section.right_margin = Inches(0.5)

    style = document.styles['Normal']
    font = style.font
    font.name = 'Arial'
    font.size = Pt(10)
    document.add_picture(os.path.join(settings.STATIC_DIR, 'nhs_image.png'), height=Inches(0.63), width=Inches(2.39))
    last_paragraph = document.paragraphs[-1]
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT

    table = document.add_table(rows=1, cols=1, style='Table Grid')
    heading_cells = table.rows[0].cells
    run = heading_cells[0].paragraphs[0].add_run('GTAB SUMMARY SHEET')
    run.bold = True
    heading_cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    heading_cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.3)
    heading_cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.3)

    table = document.add_table(rows=2, cols=1, style='Table Grid')
    table.rows[0].cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = table.rows[0].cells[0].paragraphs[0].add_run(
        'FOR RESEARCH PURPOSES ONLY- THESE RESULTS HAVE NOT BEEN VALIDATED.\n')
    run.font.color.rgb = RGBColor(255, 0, 0)
    run = table.rows[0].cells[0].paragraphs[0].add_run(
        'UNVALIDATED FINDINGS MUST NOT BE ACTED UPON.\n')
    run.font.color.rgb = RGBColor(255, 0, 0)
    run = table.rows[0].cells[0].paragraphs[0].add_run(
        'PLEASE CONTACT THE LABORATORY IF VALIDATION TESTING IS REQUIRED')
    run.font.color.rgb = RGBColor(255, 0, 0)
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.3)
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.3)
    run = table.rows[1].cells[0].paragraphs[0].add_run('Specialist Integrated Haematological Malignancy '
                                                       'Diagnostic Service\n')
    run.font.size = Pt(6)
    run = table.rows[1].cells[0].paragraphs[0].add_run('Acquired Genomics (SIHMDS-AG), Camelia Botnar Laboratories, '
                                                       'Great Ormond Street Hospital NHS Trust,\n')
    run.font.size = Pt(6)
    run = table.rows[1].cells[0].paragraphs[0].add_run('London, WC1N 3JH. Tel: 020 7405 9200 Ex: 5755')
    run.font.size = Pt(6)
    table.rows[1].cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.2)
    table.rows[1].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.2)
    table.rows[1].cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

    table = document.add_table(rows=1, cols=1, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run('GENOMICS ENGLAND PARTICIPANT INFORMATION')
    run.bold = True
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.2)
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.2)

    table = document.add_table(rows=4, cols=2, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run(f'Patient Name:\t\t'
                                                       f'{report.ir_family.participant_family.proband.forename} '
                                                       f'{report.ir_family.participant_family.proband.surname}')
    run = table.rows[0].cells[1].paragraphs[0].add_run(f'GEL Participant ID:\t'
                                                       f'{report.ir_family.participant_family.proband.gel_id}')
    run = table.rows[1].cells[0].paragraphs[0].add_run(f'Gender:\t\t'
                                                       f'{report.ir_family.participant_family.proband.sex}')
    run = table.rows[1].cells[1].paragraphs[0].add_run(f'CIP ID:\t\t\t'
                                                       f'ILMN-{report.ir_family.ir_family_id}')
    run = table.rows[2].cells[0].paragraphs[0].add_run(f'Date of Birth:\t\t'
                                                       f'{report.ir_family.participant_family.proband.date_of_birth.date()}')
    run = table.rows[2].cells[1].paragraphs[0].add_run(f'NHS number:\t\t'
                                                       f'{report.ir_family.participant_family.proband.nhs_number}')
    run = table.rows[3].cells[0].paragraphs[0].add_run(f'Referring Clinician:\t'
                                                       f'{report.ir_family.participant_family.clinician.name}')
    run = table.rows[3].cells[1].paragraphs[0].add_run(f'Referring Hospital:\t'
                                                       f'{report.ir_family.participant_family.proband.gmc}')

    table = document.add_table(rows=1, cols=1, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run('GENOMICS ENGLAND REPORT DETAILS')
    run.bold = True
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.2)
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.2)

    table = document.add_table(rows=4, cols=2, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run(f'Disease Type:\t\t'
                                                       f'{report.ir_family.participant_family.proband.disease_group}')
    run = table.rows[0].cells[1].paragraphs[0].add_run(f'Tumour Content:\t\t')
    run = table.rows[1].cells[0].paragraphs[0].add_run(f'Disease Subtype:\t'
                                                       f'{report.ir_family.participant_family.proband.disease_subtype}')
    run = table.rows[1].cells[1].paragraphs[0].add_run(f'Version Number:\t\t')
    run = table.rows[2].cells[0].paragraphs[0].add_run(f'Tumour Type:\t\t')
    run = table.rows[2].cells[1].paragraphs[0].add_run(f'Total Somatic SNVs:\t\t')
    run = table.rows[3].cells[0].paragraphs[0].add_run(f'Tumour sample cross-contamination: Pass ')
    run = table.rows[3].cells[1].paragraphs[0].add_run(f'Library Prep:\t\t')
    table = document.add_table(rows=3, cols=1, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run('ADDITIONAL RECRUITMENT INFORMATION')
    run.bold=True
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.2)
    table.rows[0].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.2)
    run = table.rows[1].cells[0].paragraphs[0].add_run('Multiple samples (Yes / No):   ')
    run = table.rows[2].cells[0].paragraphs[0].add_run('GENOMICS TUMOUR ADVISORY BOARD (GTAB) SUMMARY  ')
    table.rows[2].cells[0].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run.bold = True
    table.rows[2].cells[0].paragraphs[0].paragraph_format.space_before = Cm(0.2)
    table.rows[2].cells[0].paragraphs[0].paragraph_format.space_after = Cm(0.2)

    table = document.add_table(rows=1, cols=1, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run('CLINICAL UPDATE\t\t\t\t\t\t\tGTAB date: dd/mm/yyyy\n')
    run = table.rows[0].cells[0].paragraphs[0].add_run('Include any SOC testing already performed, dates of '
                                                       'treatment, clinical trials etc.\n\n\n\n\n\n\n\n\n\n')
    run.italic = True

    table = document.add_table(rows=1, cols=2, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run('Oncologist:')
    run = table.rows[0].cells[1].paragraphs[0].add_run('Clinician in lieu of referrer: ')

    table = document.add_table(rows=1, cols=1, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run(
        "FOR RESEARCH PURPOSES ONLY- THESE RESULTS HAVE NOT BEEN VALIDATED\n")
    run.font.color.rgb = RGBColor(255, 0, 0)

    run = table.rows[0].cells[0].paragraphs[0].add_run("SOMATIC VARIANTS\n\n")
    run.underline=True
    run = table.rows[0].cells[0].paragraphs[0].add_run("Only variants with specific consequences "
                                                       "(transcript ablation, splice acceptor variant, splice donor "
                                                       "variant, stop gained, frameshift variant, stop lost, start lost,"
                                                       " transcript amplification, inframe insertion, inframe deletion, "
                                                       "inframe variant, missense variant, splice region variant) in "
                                                       "canonical transcripts are reported.Complex indels and "
                                                       "frameshift variants are only annotated at the CDS level owing "
                                                       "to problems accurately annotating the protein change with the "
                                                       "current pipeline.Small variants are classified as SNVs and "
                                                       "indels < 50bp.Classification for gene mode of action (oncogene, "
                                                       "tumour suppressor or both) was extracted from the manually "
                                                       "curated Cancer Gene Census list (Wellcome Trust Sanger "
                                                       "Institute).Reported variants are classified into Domains 1-3, "
                                                       "of which Domains 1-2 are reviewed by a clinical scientist and "
                                                       "discussed at GTAB.\n\n")
    run.font.size = Pt(5)
    run = table.rows[0].cells[0].paragraphs[0].add_run("Domain 1 (variants reported as having therapeutic, "
                                                       "prognostic or trial associations by GenomOncology "
                                                       "Knowledge Management System):\n")
    run.underline = True
    run.font.size = Pt(9)
    run = table.rows[0].cells[0].paragraphs[0].add_run("Note: Please see individual "
                                                       "variant for assessment of pathogenicity\n\n") #\t1)\n")
    count = 1
    for proband_variant in proband_variants:
        if proband_variant.max_tier == 1 and proband_variant.somatic is True:
            transcript = proband_variant.get_transcript()
            transcript_variant = proband_variant.get_transcript_variant()
            if transcript_variant.hgvs_c:
                hgvs_c = transcript_variant.hgvs_c.split(':')
                if len(hgvs_c) > 1:
                    hgvs_c = hgvs_c[1]
                else:
                    hgvs_c = hgvs_c[1]
            else:
                hgvs_c = None
            if transcript_variant.hgvs_p:
                hgvs_p = transcript_variant.hgvs_p.split(':')
                if len(hgvs_p) > 1:
                    hgvs_p = hgvs_p[1]
                else:
                    hgvs_p = hgvs_p[1]
            else:
                hgvs_p = None
            table.rows[0].cells[0].paragraphs[0].add_run(f"{count}) {transcript.gene} {hgvs_c} {hgvs_p} VAF: XX\n"
                                                         f"Transcript: {transcript.name}\n\n")
            count += 1
    table.rows[0].cells[0].paragraphs[0].add_run("\n")
    run = table.rows[0].cells[0].paragraphs[0].add_run("Domain 2 "
                                                       "(variants in genes within the Cancer Gene Census- Wellcome "
                                                       "Trust Sanger Institute):\n")
    count = 1
    for proband_variant in proband_variants:
        if proband_variant.max_tier == 2 and proband_variant.somatic is True:
            transcript = proband_variant.get_transcript()
            transcript_variant = proband_variant.get_transcript_variant()
            if transcript_variant.hgvs_c:
                hgvs_c = transcript_variant.hgvs_c.split(':')
                if len(hgvs_c) > 1:
                    hgvs_c = hgvs_c[1]
                else:
                    hgvs_c = hgvs_c[1]
            else:
                hgvs_c = None
            if transcript_variant.hgvs_p:
                hgvs_p = transcript_variant.hgvs_p.split(':')
                if len(hgvs_p) > 1:
                    hgvs_p = hgvs_p[1]
                else:
                    hgvs_p = hgvs_p[1]
            else:
                hgvs_p = None
            table.rows[0].cells[0].paragraphs[0].add_run(f"{count}) {transcript.gene} {hgvs_c} {hgvs_p} VAF: XX\n"
                                                         f"Transcript: {transcript.name}\n\n")
            count += 1
    run.underline=True
    run.font.size = Pt(9)
    run = table.rows[0].cells[0].paragraphs[0].add_run("Note: Please see individual "
                                                       "variant for assessment of pathogenicity\n\n")

    table = document.add_table(rows=1, cols=1, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run(
        "FOR RESEARCH PURPOSES ONLY- THESE RESULTS HAVE NOT BEEN VALIDATED\n")
    run.font.color.rgb = RGBColor(255, 0, 0)
    run = table.rows[0].cells[0].paragraphs[0].add_run("ADDITIONAL FINDINGS\n\n")
    run.underline=True
    run = table.rows[0].cells[0].paragraphs[0].add_run("Cancer Pertinent Germline Susceptibility\n\n")
    run.underline=True
    count = 1
    for proband_variant in proband_variants:
        if proband_variant.somatic is False:
            transcript = proband_variant.get_transcript()
            transcript_variant = proband_variant.get_transcript_variant()
            if transcript_variant.hgvs_c:
                hgvs_c = transcript_variant.hgvs_c.split(':')
                if len(hgvs_c) > 1:
                    hgvs_c = hgvs_c[1]
                else:
                    hgvs_c = hgvs_c[1]
            else:
                hgvs_c = None
            if transcript_variant.hgvs_p:
                hgvs_p = transcript_variant.hgvs_p.split(':')
                if len(hgvs_p) > 1:
                    hgvs_p = hgvs_p[1]
                else:
                    hgvs_p = hgvs_p[1]
            else:
                hgvs_p = None
            table.rows[0].cells[0].paragraphs[0].add_run(f"{count}) {transcript.gene} {hgvs_c} {hgvs_p} VAF: XX\n"
                                                         f"Transcript: {transcript.name}\n\n")
            count += 1
    run.italic=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Tier 1 includes variants deemed to be pathogenic or likely "
                                                        "pathogenic in cancer susceptibility genes relevant to "
                                                        "tumour type.\nTier 3 contains all rare variants arising across"
                                                        " a large set of cancer susceptibility genes. Review of Tier "
                                                        "3 germline variants is not required routinely but should be "
                                                        "considered in cases in which there is a high index of "
                                                        "suspicion of a germline determinant of cancer in the patient "
                                                        "and/or family. \n\n")
    run.font.size=Pt(5)
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Circos Plot (genome-wide visualisation of "
                                                        "somatic variants and sequencing depth)\n\n")
    run.underline=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Copy and paste image of circus plot\n\n")
    run.italic=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "This plot illustrates the distribution of "
                                                        "somatic variants across the genome with each concentric "
                                                        "circle (track) representing a different class of variant.\n"
                                                        "Chromosomes are arranged sequentially around the "
                                                        "circumference "
                                                        "as indicated. The information presented in each track is as "
                                                        "follows:\nTrack 1 (innermost track): chromosomes\nTrack 2 "
                                                        "(in red): number of somatic SNVs in 2Mb window; scale from"
                                                        " 0 to 100\nTrack 3 (in green): number of somatic indels in "
                                                        "2Mb window; scale from 0 to 35\nTrack 4: ratio of normalised "
                                                        "depth of coverage for tumour vs normal in log2 scale smoothed "
                                                        "over 100 kb windows. Diploid regions have value of 0. Scale is"
                                                        " between -2 and 2. Regions with coverage below 15x in "
                                                        "germline are not shown. CNV losses are indicated in red, "
                                                        "CNV gains are "
                                                        "indicated in green, copy-neutral LOH regions are indicated in "
                                                        "yellow.\nTrack 5 (outermost track, in blue): absolute depth "
                                                        "of coverage in tumour sample\nStructural variants (SVs) are "
                                                        "indicated by arcs inside the plot; translocations are "
                                                        "indicated in green, inversions are indicated in purple. SVs "
                                                        "shorter than 100 kb and insertions are not plotted.\n\n\n")
    run.font.size = Pt(4)
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Structural Variants\n")
    run.underline=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Translocations involving 2 or more "
                                                        "named genes:\n\n")
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Copy and paste structural variants table\n\n")
    run.italic=True

    run = table.rows[0].cells[0].paragraphs[0].add_run( "Searched for copy number variants:\n\n")
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Copy and paste structural "
                                                        "variants table\n\n")
    run.italic=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Somatic CNVs and SVs variants have not "
                                                        "been assigned to domains (see ‘Somatic Variants’ ‘Domain 1’ "
                                                        "and ‘Domain 2’ above) whilst the performance (recall and "
                                                        "precision) of the calling algorithm for CNVs and SVs is under"
                                                        " evaluation.\nOnly SVs overlapping breakends with introns or "
                                                        "exons are listed in the table above. Each row corresponds to "
                                                        "one structural variant. Types of structural variants called "
                                                        "by Canvas: GAIN(COPY NUMBER) = CNV gain, LOSS(COPY NUMBER) ="
                                                        " CNV loss, LOH(COPY NUMBER) = loss of heterozygosity. Types "
                                                        "of structural variants called by Manta: BND = translocation, "
                                                        "DEL = deletion, DUP = duplication, INV = inversion, "
                                                        "INS = insertion. Coordinate for the second breakend in "
                                                        "translocation event captures replacement string, position and "
                                                        "direction according to variant call format specification v4.3\n\n")
    run.font.size = Pt(5)
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Mutation Burden\n")
    run.underline=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Copy and paste mutation burden plot\n\n")
    run.italic=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Total "
                                                        "number of somatic non-synonymous small variants per megabase "
                                                        "(coding region): XXX\n")
    run = table.rows[0].cells[0].paragraphs[0].add_run( "The vertical axis (log scaled) shows "
                                                        "the number of somatic non-synonymous small variants per "
                                                        "megabase of coding sequences. The dashed horizontal red line "
                                                        "represents the total somatic mutation burden in this patients "
                                                        "genome. Each sample in the 100,000 Genomes Cancer dataset is "
                                                        "represented by a dot on the plot; different cancer types are "
                                                        "ordered on the horizontal axis based on their median numbers "
                                                        "of somatic mutations (short horizontal red line).\n\n\n")
    run.font.size = Pt(5)
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Mutational Signature\n")
    run.underline=True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Copy and paste mutational signatures\n\n")
    run.italic = True
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Further "
                                                        "details of the 30 different mutational signatures used for "
                                                        "this analysis, their prevalence in different tumour types "
                                                        "and proposed aetiology can be found at the Sanger Institute "
                                                        "Website- https://cancer.sanger.ac.uk/cosmic/signatures\n\n")
    run.font.size = Pt(5)
    run = table.rows[0].cells[0].paragraphs[0].add_run( "Pharmacogenomics\n\n")
    run.underline=True

    table = document.add_table(rows=2, cols=2, style='Table Grid')
    run = table.rows[0].cells[0].paragraphs[0].add_run('Completed by:')
    run = table.rows[0].cells[1].paragraphs[0].add_run('Date: ')
    run = table.rows[1].cells[0].paragraphs[0].add_run('Checked by:')
    run = table.rows[1].cells[1].paragraphs[0].add_run('Date: ')

    return document
예제 #19
0
def buildDoc(table, tableData):
    doc = Document(full_path)  # open an existing document with existing styles
    #debug print('Loaded {}'.format(tableData))
    for row in tableData:
        # print ('row {}'.format(row))
        level = row['level']
        if (level == 0):
            continue
        if (level == 1):
            levelStyle = 'style-kone-blue-heading-01'
        else:
            levelStyle = 'Heading ' + str(level)
        title = row['name']
        heading = doc.add_heading(title, level)
        heading.style = doc.styles[levelStyle]
        p = doc.add_paragraph(row['description'])
        if row['src']:
            src = doc.add_paragraph(row['src'])
            src.style = doc.styles['Body Text 3']
        if (row['formats']):
            if (not (str(row['formats']).strip() == "")):
                print("formats: " + row['formats'])
                formats = json.loads(row['formats'])
                listing_url = formats['listing-url']
                print("listing_url: " + listing_url)
                listingData, met = getTableData(listing_url)
                #for style in doc.styles:
                #print ( style )
                global ikey
                doc_table = doc.add_table(1, (len(listingData[0].keys()) - 2),
                                          doc.styles['Table Grid'])
                for lrow in listingData:
                    mikey = -1
                    ikey = 0
                    for mlrowkey in sorted(met.keys()):
                        mlrow = met[str(mlrowkey)]
                        key = mlrow['attribute_name']
                        mikey = mikey + 1
                        if (not (key in lrow.keys())):
                            continue
                        if (not (key == 'id' or key == 'guid')):
                            if (ikey == 0):
                                cells = doc_table.add_row().cells
                                thkey = 0
                                for th in sorted(
                                        met.keys()):  # this is the title row
                                    mthrow = met[str(th)]
                                    ky = mthrow['attribute_name']
                                    print("lrow.keys:")
                                    print("ky: " + str(ky))
                                    print(lrow.keys())
                                    if ((not (ky in lrow.keys())) or ky == 'id'
                                            or ky == 'guid'):
                                        continue
                                    else:
                                        cells[thkey].text = str(ky)
                                        thkey = thkey + 1
                            #print ( str(lrow[key]) ) # the value cells[0].text = lrow[key]
                            cells[ikey].text = str(lrow[key])
                            ikey = ikey + 1
        if row['img_relative_path']:
            ip = doc.add_paragraph()
            r = ip.add_run()
            r.add_text(row['img_name'])
            r.add_text("\n")
            r.add_picture(row['img_relative_path'], width=Cm(15.0))

    doc.save(full_path)
    return 0
예제 #20
0
def create_total_docx(chunks, path):
    # CONFIG
    indentation = 0.5
    tibetan_style = {'font': 'Jomolhari', 'size': 11}
    pedurma_style = {'color': (112, 128, 144), 'font': 'Jomolhari', 'size': 8}
    semantic_style = {'font': 'Free Mono', 'size': 10}
    communicative_style = {'font': 'Gentium', 'size': 12}

    document = Document()
    styles = document.styles

    # TIBETAN
    bo_style = styles.add_style('Tibetan', WD_STYLE_TYPE.CHARACTER)
    bo_font = bo_style.font
    bo_font.name = tibetan_style['font']
    bo_font.size = Pt(tibetan_style['size'])
    # PEYDURMA NOTES
    note_style = styles.add_style('Peydurma Notes', WD_STYLE_TYPE.CHARACTER)
    note_font = note_style.font
    note_font.name = pedurma_style['font']
    # note_font.size = Pt(pedurma_style['size'])
    note_font.subscript = True
    c = pedurma_style['color']
    note_font.color.rgb = RGBColor(c[0], c[1], c[2])

    # COMMUNICATIVE VERSION
    com_style = styles.add_style('Communicative', WD_STYLE_TYPE.CHARACTER)
    com_font = com_style.font
    com_font.name = communicative_style['font']
    com_font.size = Pt(communicative_style['size'])

    # SEMANTIC VERSION
    sem_style = styles.add_style('Semantic', WD_STYLE_TYPE.CHARACTER)
    sem_style.base_style = styles['Normal']
    sem_font = sem_style.font
    sem_font.name = semantic_style['font']
    sem_font.size = Pt(semantic_style['size'])

    # COMMUNICATIVE PARAGRAPH
    com_par_style = styles.add_style('Com. paragraph', WD_STYLE_TYPE.PARAGRAPH)
    com_par_style.paragraph_format.space_before = Cm(0)
    com_par_style.paragraph_format.space_after = Cm(0)

    # OTHER PARAGRAPH
    other_par_style = styles.add_style('Other paragraph',
                                       WD_STYLE_TYPE.PARAGRAPH)
    other_par_style.paragraph_format.space_before = Cm(0)
    other_par_style.paragraph_format.space_after = Cm(1)
    other_par_style.paragraph_format.left_indent = Cm(indentation)
    other_par_style.paragraph_format.line_spacing = WD_LINE_SPACING.SINGLE

    for chunk in chunks:
        com, others = chunk

        #########################
        # Communicative
        com_p = document.add_paragraph()
        com_p.style = 'Com. paragraph'
        com = re.split('(/[^/]+/)', com)
        for c in com:
            com_run = com_p.add_run('')
            com_run.style = 'Communicative'

            if c.startswith('/'):
                com_run.text = c[1:-1]
                com_run.italic = True
            else:
                com_run.text = c

        # ************************

        p = document.add_paragraph()
        p.style = 'Other paragraph'

        for pair in others:
            bo, sem = pair
            bo = re.split('(<.+?>)', bo)
            for b in bo:
                run = p.add_run(b)
                if b.startswith('<'):
                    run.style = 'Peydurma Notes'
                else:
                    run.style = 'Tibetan'
            p.add_run().add_break()

            run = p.add_run(sem)
            run.style = 'Semantic'
            run.add_break()

        # removing trailing newline
        p.runs[-1].text = p.runs[-1].text.rstrip('\n')
        # print('ok')
    out_path = path.parent / (path.stem + '.docx')
    document.save(str(out_path))
예제 #21
0
def generate_raport(network, subnets, path, answers=True, fullpage=False):
    """
    Generuje raport na podstawie dostarczonych parametrów.
    :param network: BinNetwork służący jako adres ip w poleceniu
    :param subnets: Lista obiektów Binetwork, które zawierają już wszystkie parametry
    :param answers: pokaż odpowiedzi?
    :param fullpage: Wydrukować ilość sprawdzianów tak aby zajeły one całą stronę?
    """
    subnets_list = ', '.join(str(subnet.hosts) for subnet in subnets)
    number_of_repeats = [0, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2]
    rows = len(subnets)

    if answers is False:
        # jeżeli odpowiedzi nie mają być wyświetlane, to podmień podsieci
        # na specjalnych tajnych agentów
        for i in range(len(subnets)):
            subnets[i] = FakeNetwork(subnets[i].hosts)

    document = Document()
    sections = document.sections
    for section in sections:
        # marginesy
        section.top_margin = Cm(1)
        section.bottom_margin = Cm(1)
        section.left_margin = Cm(1)
        section.right_margin = Cm(1)
    columns = "hosts allocated_size network_with_mask broadcast first_address last_address".split(
    )
    # w jakiej kolejności mają pojawiać się parametry sieci
    try:
        times = number_of_repeats[rows] if fullpage else 1
    except:
        times = 1
    for _ in range(times):
        p = document.add_paragraph('Imię i nazwisko: ')

        document.add_paragraph("Podziel sieć o adresie " + str(network) + "/" +
                               str(network.mask) + " na podsieci po " +
                               subnets_list + " hostów.")

        # tworzenie tabeli i jej nagłówków
        table = document.add_table(rows=len(subnets) + 1, cols=6)
        header = table.rows[0].cells
        header[0].text = "Hosty"
        header[1].text = "Zaalokowane hosty"
        header[2].text = "Adres podsieci"
        header[3].text = "Broadcast"
        header[4].text = "Pierwszy wolny adres"
        header[5].text = "Ostatni wolny adres"
        table.style = 'TableGrid'

        # wypełnij komórki tabeli
        for network_id, row in enumerate(table.rows[1:]):
            for id, col in enumerate(row.cells):
                col.text = str(getattr(subnets[network_id], columns[id]))
        try:
            # zapisz dokument
            document.save(path)
        except:
            print('Wystąpił problem z zapisem', file=sys.stderr)
        if _ != times - 1:
            document.add_paragraph('')
            document.add_paragraph('')
예제 #22
0
    def createGroupResultsDocument(self, template, headerInfo, groupData, scoreData, path):
        document = Document()
        print('Path: ' + path)

        # Change the page margins
        sections = document.sections
        for section in sections:
            section.top_margin = Cm(0.75)
            section.bottom_margin = Cm(0.5)
            section.left_margin = Cm(1.5)
            section.right_margin = Cm(2)

        # Add the date of the presentation
        date_header = document.add_paragraph()
        date_header.add_run(
            'Presentation date: ' + headerInfo['presentationDate'])
        date_header.alignment = WD_ALIGN_PARAGRAPH.RIGHT

        # Iterate through student names and marks
        for student in groupData['members']:
            user_id = str(student['id'])
            
            studentScore = scoreData[user_id]['assessmentTotalScore']

            print('---scoreData[id]---')
            print(scoreData[user_id])
            
            table = document.add_table(1, 3)
            assessment_info_cells = table.rows[0].cells
            student_name_cell = assessment_info_cells[0]
            student_name_cell.paragraphs[0].add_run("Student " + user_id + " name: ")
            student_name_cell.paragraphs[0].add_run(
                student['studentName']).bold = True
            student_id_cell = assessment_info_cells[1]
            student_id_cell.paragraphs[0].add_run("Student ID: ")
            student_id_cell.paragraphs[0].add_run(
                student['studentId']).bold = True
            student_marks_cell = assessment_info_cells[2]
            student_marks_cell.paragraphs[0].add_run("Obtained Marks: ")
            student_marks_cell.paragraphs[0].add_run(str(studentScore) + "/" + str(scoreData['perfectScore'])).bold = True

        # Add a new line
        document.add_paragraph()

        # For each group criterion, create a table
        groupCriteria = template.getGroupCriteria()
        for group in groupCriteria:
            table = document.add_table(1, 5, style='Table Grid')
            # Get the first row of the table, which contains the headers
            heading_cells = table.rows[0].cells
            # Add the group criterion's name
            heading_cells[0].paragraphs[0].add_run(group.name).bold = True
            # Add value header
            first_criterion_fields = group.getFirstCriterion().getFields()
            # group.getFirstCriterion().printFields()
            ctr = 1
            # For each field in the first criterion, add the value to header
            for field in first_criterion_fields:
                heading_cells[ctr].paragraphs[0].add_run(
                    str(field.points) + ' - ' + field.value).bold = True
                ctr += 1

            # Used to access the results object
            temp_words = group.name.split(' ')
            data_type_group = temp_words[0].lower() + '_' + str(group.id)

            criteria = group.getCriteria()
            for criterion in criteria:
                criterion_fields = criterion.getFields()

                ctr = 0
                cells = table.add_row().cells
                cells[ctr].text = criterion.name

                # Used to access the results object
                temp_words = criterion.name.split(' ')
                data_type_criterion = temp_words[0].lower(
                ) + '_' + str(criterion.id)

                for field in criterion_fields:
                    ctr += 1
                    #cells[ctr].text = field.description

                    cell_text = field.description
                   

                    # Iterate through students' results
                    for student in groupData['members']:
                        user_id = str(student['id'])
                        score = scoreData[user_id]['groupCriteria'][data_type_group]['criteria'][data_type_criterion]
                        if(str(score) == str(field.points)):
                            # Add the student index
                            cell_text = cell_text + '(' + str(student['id']) +')'
                    
                    cells[ctr].text = cell_text

            # Add a new line for every group criterion
            document.add_paragraph()

        footer = document.add_paragraph().add_run(
            'Adapted with enhancement from © 2004 National Council of Teachers of English/International Reading Association')
        font = footer.font
        font.size = Pt(8)
        font.italic = True

        document.save(path + '/' + self.document_name + '.docx')
예제 #23
0
    def handle_starttag(self, tag, attrs):
        if tag == EM:
            self.italic = True
        elif tag == P:
            if not self.list_level:
                self.paragraph = self.document.add_paragraph()
            paragraph_format = self.paragraph.paragraph_format
            paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
            paragraph_format.space_after = Pt(STANDART_PT)
            paragraph_format.first_line_indent = Cm(
                1.5)  # Inches(STANDART_INCHES + 0.3)
            #   paragraph_format.left_indent = Inches(STANDART_INCHES)
            paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
            if self.isBlockQuote:  # it's here because in html <blockquote><p></p></blockquote>
                paragraph_format.first_line_indent = Inches(0)
                paragraph_format.left_indent = Inches(STANDART_INCHES)
                paragraph_format.space_before = Pt(STANDART_PT)
                paragraph_format.space_after = Pt(STANDART_PT)
                paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
        elif tag == STRONG:
            self.bold = True
        elif tag in [H1, H2, H3, H4, H5, H6]:
            self.h = int(tag[1])
        elif tag == UL:
            self.list_level += 1
        elif tag == LI:
            self.paragraph = self.document.add_paragraph()
            self.need_dot_li = True
            self.font = self.normal_font
            self.size = self.normal_size
        elif tag == IMG:
            url = attrs[0][1]

            response = requests.get(url)
            picture = response.content
            with open(ABS_PATH.format(PICTURE_NAME), 'wb') as file:
                file.write(picture)
            try:
                self.document.add_picture(ABS_PATH.format(PICTURE_NAME),
                                          width=Inches(4),
                                          height=Inches(3))
                last_paragraph = self.document.paragraphs[-1]
                last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                last_paragraph.space_after = Pt(10)
                last_paragraph.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
                self.paragraph = self.document.add_paragraph()

                #last_paragraph.keep_with_next = False
            except Exception as e:
                print(e)
                print('ERROR WITH IMAGE {}'.format(url))
        elif tag == A:
            self.hyperlink = attrs[0][1]
        elif tag == BLOCKQUOTE:
            self.isBlockQuote = True
        # TABLE SECTION
        elif tag == TABLE:
            self.table_mode = True
        elif tag == THEAD:
            self.table_thead_mode = True
        elif tag == TH:
            pass
        elif tag == TR:
            if not self.table_thead_mode:
                self.table.add_row()
        elif tag == TD:
            pass
        # END TABLE SECTION
        elif tag == CODE:
            paragraph_format = self.paragraph.paragraph_format
            paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
            paragraph_format.line_spacing_rule = WD_LINE_SPACING.SINGLE
            paragraph_format.first_line_indent = Inches(0)
            self.italic = True
            self.size = self.code_size
            self.font = self.code_font
예제 #24
0
    def createResultsDocument(self, template, results, otherInfo, path):
        document = Document()
        print('Path: ' + path)

        # Change the page margins to match Saghir's SOFT808
        sections = document.sections
        for section in sections:
            section.top_margin = Cm(0.75)
            section.bottom_margin = Cm(0.5)
            section.left_margin = Cm(1.5)
            section.right_margin = Cm(2)

        studentScore = ''
        perfectScore = ''
        scorePercentage = str(results['scorePercentage'])
        if results['normalizedScore'] != '':
            studentScore = str(results['normalizedScore'])
            perfectScore = str(results['normalizedPerfectScore'])
        else:
            studentScore = str(results['assessmentTotalScore'])
            perfectScore = str(results['assessmentPossibleTotalScore'])

        date_header = document.add_paragraph()
        date_header.add_run(
            'Presentation date: ' + otherInfo['presentationDate'])
        date_header.alignment = WD_ALIGN_PARAGRAPH.RIGHT

        # Add presentation duration
        print(otherInfo['presentationDuration'])
        if otherInfo['presentationDuration'] != '':
            duration_header = document.add_paragraph()
            duration_header.add_run(
                'Presentation duration: ' + otherInfo['presentationDuration'])
            duration_header.alignment = WD_ALIGN_PARAGRAPH.RIGHT

        # TODO: Make this dynamic/customizable for each template
        # Add the student name, id and topic of presentation

        table = document.add_table(1, 3)

        assessment_info_cells = table.rows[0].cells
        student_name_cell = assessment_info_cells[0]
        student_name_cell.paragraphs[0].add_run("Student name: ")
        student_name_cell.paragraphs[0].add_run(
            otherInfo['studentName']).bold = True
        student_id_cell = assessment_info_cells[1]
        student_id_cell.paragraphs[0].add_run("Student ID: ")
        student_id_cell.paragraphs[0].add_run(
            otherInfo['studentId']).bold = True
        student_marks_cell = assessment_info_cells[2]
        student_marks_cell.paragraphs[0].add_run("Obtained Marks: ")
        #student_marks_cell.paragraphs[0].add_run(studentScore + "/" + perfectScore + " (" + scorePercentage + "%)").bold = True
        student_marks_cell.paragraphs[0].add_run(studentScore + "/" + perfectScore).bold = True

        table = document.add_table(1, 1)
        assessment_info_cells = table.rows[0].cells
        topic_of_presentation_cell = assessment_info_cells[0]
        topic_of_presentation_cell.paragraphs[0].add_run(
            "Topic of Presentation: ")
        topic_of_presentation_cell.paragraphs[0].add_run(
            otherInfo['presentationTopic']).bold = True

        # Add a new line
        document.add_paragraph()

        # For each group criterion, create a table
        groupCriteria = template.getGroupCriteria()
        for group in groupCriteria:
            table = document.add_table(1, 5, style='Table Grid')
            # Get the first row of the table, which contains the headers
            heading_cells = table.rows[0].cells
            # Add the group criterion's name
            heading_cells[0].paragraphs[0].add_run(group.name).bold = True
            # Add value header
            first_criterion_fields = group.getFirstCriterion().getFields()
            # group.getFirstCriterion().printFields()
            ctr = 1
            # For each field in the first criterion, add the value to header
            for field in first_criterion_fields:
                heading_cells[ctr].paragraphs[0].add_run(
                    str(field.points) + ' - ' + field.value).bold = True
                ctr += 1

            # Used to access the results object
            temp_words = group.name.split(' ')
            data_type_group = temp_words[0].lower() + '_' + str(group.id)

            criteria = group.getCriteria()
            for criterion in criteria:
                criterion_fields = criterion.getFields()

                ctr = 0
                cells = table.add_row().cells
                cells[ctr].text = criterion.name

                # Used to access the results object
                temp_words = criterion.name.split(' ')
                data_type_criterion = temp_words[0].lower(
                ) + '_' + str(criterion.id)

                for field in criterion_fields:
                    ctr += 1
                    cells[ctr].text = field.description

                    # Check if the field was selected based on the results
                    # TODO: Make a colored version of shading
                    score = results['groupCriteria'][data_type_group]['criteria'][data_type_criterion]
                    if (score == str(field.points)):
                        # Set a cell background (shading) color to RGB D9D9D9.
                        shading_elm = parse_xml(
                            r'<w:shd {} w:fill="D9D9D9"/>'.format(nsdecls('w')))
                        cells[ctr]._tc.get_or_add_tcPr().append(shading_elm)

            document.add_paragraph()

            groupTotal = document.add_paragraph('(' + group.name + ') ' + 'Total: ' + str(
                results['groupCriteria'][data_type_group]['groupTotalScore']) + ' / ' + str(results['groupCriteria'][data_type_group]['groupPossibleTotalScore']))
            groupTotal.alignment = WD_ALIGN_PARAGRAPH.RIGHT

            # Add a new line for every group criterion
            document.add_paragraph()

        footer = document.add_paragraph().add_run(
            'Adapted with enhancement from © 2004 National Council of Teachers of English/International Reading Association')
        font = footer.font
        font.size = Pt(8)
        font.italic = True

        document.save(path + '/' + self.document_name + '.docx')
예제 #25
0
def createDocShedule(group):
    columns = 26
    groupReal = 4438
    wordDocument = docx.Document()

    style = wordDocument.styles['Normal']
    font = style.font
    font.name = 'Times New Roman'

    wordDocument.add_heading(f"Журнал посещения занятий группы {groupReal}",
                             3).alignment = 1

    font.size = Pt(10)

    mod_document(wordDocument)
    table = wordDocument.add_table(rows=1, cols=columns)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '№ п.п.'
    hdr_cells[1].text = 'ФИО'
    hdr_cells[1].alignment = 1
    hdr_cells[0].alignment = 1

    table.style = 'Table Grid'

    row = table.add_row()
    row.cells[0].merge(hdr_cells[0])
    row.cells[1].merge(hdr_cells[1])

    i = 0
    users = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    k = 0

    table.cell(0, 2).merge(table.cell(0, 5)).text = "Понедельник"
    table.cell(0, 6).merge(table.cell(0, 9)).text = "Вторник"
    table.cell(0, 10).merge(table.cell(0, 13)).text = "Среда"
    table.cell(0, 14).merge(table.cell(0, 17)).text = "Четверг"
    table.cell(0, 18).merge(table.cell(0, 21)).text = "Пятница"
    table.cell(0, 22).merge(table.cell(0, 25)).text = "Суббота"

    for i in range(columns):
        table.cell(1, i).height = Cm(5)
        table.cell(1, i).height_rule = WD_ROW_HEIGHT_RULE.AUTO
        # table.cell(1, i).text=f'\n\n\n{i}'
        tr = row._tr
        trPr = tr.get_or_add_trPr()
        trHeight = OxmlElement('w:trHeight')
        trHeight.set(qn('w:val'), "2000")
        trHeight.set(qn('w:hRule'), "atLeast")
        trPr.append(trHeight)

    i = 0
    for user in users:
        row = table.add_row()
        row_cells = row.cells
        # row_cells[0].height = Cm(0.3)
        # row_cells[0].height_rule = WD_ROW_HEIGHT_RULE.AT_LEAST

        row_cells[0].text = f'{i}'
        row_cells[0].width = Cm(1.19)
        row_cells[1].text = f'Студент{i}'
        row_cells[1].width = Cm(6)
        i += 1

    for row in table.rows:
        row.height = Cm(0.5)
        row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

    row = table.add_row()
    row_cells = row.cells
    for row in row_cells:
        row.height = Cm(5)
    row_cells[0].merge(row_cells[1]).text = "Подпись старосты\n\n"
    row = table.add_row()
    row_cells = row.cells
    row_cells[0].merge(row_cells[1]).text = "Подпись преподавателя\n\n"

    wordDocument.add_heading(f"Создано через бота vk.com/botraspisanie",
                             3).alignment = 2
    wordDocument.save("starosta_blank.docx")
예제 #26
0
 def test_picture_has_correct_size(self):
     self.myapp.ui.SaveFullReportButton.click()
     doc = Document(self.reportdoc.absolute())
     shapes: InlineShapes = doc.inline_shapes
     self.assertEqual(WD_INLINE_SHAPE.PICTURE, shapes[0].type)
     self.assertEqual(Cm(7.43).emu, shapes[0].width)
예제 #27
0
    def doc5(self):
        document = Document()
        section = document.sections[-1]
        section.left_margin = Cm(1)
        section.right_margin = Cm(1)

        obj_styles = document.styles
        obj_charstyle = obj_styles.add_style('CommentsStyle',
                                             WD_STYLE_TYPE.CHARACTER)
        obj_font = obj_charstyle.font
        obj_font.size = Pt(8)
        obj_font.name = 'Times New Roman'

        obj_charstyle = obj_styles.add_style('CommentsStyle2',
                                             WD_STYLE_TYPE.CHARACTER)
        obj_font = obj_charstyle.font
        obj_font.size = Pt(10)
        obj_font.name = 'Times New Roman'

        header = document.sections[0].header
        paragraph = header.add_paragraph()
        paragraph.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
        paragraph.add_run(self.env.user.company_id.name).bold = True

        paragraph = header.add_paragraph()
        paragraph.paragraph_format.alignment = WD_TABLE_ALIGNMENT.RIGHT
        paragraph.add_run('Registration No: ')
        paragraph.add_run(self.id_number or ' ').bold = True

        # paragraph = header.add_paragraph('Transcript', style='Intense Quote')
        # paragraph.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER

        header_table = header.add_table(1, 3, width=500)
        header_table.autofit = False

        A = header_table.cell(0, 0)
        pt = A.paragraphs[0]
        t = pt.text = ''
        pt.add_run("Student's Name: ", style='CommentsStyle').bold = True
        pt.add_run(self.name, style='CommentsStyle').bold = False
        pt.paragraph_format.space_before = Pt(0)
        pt.paragraph_format.space_after = Pt(0)

        paragraph = A.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run("Program: ", style='CommentsStyle').bold = True
        paragraph.add_run(self.program_id.name,
                          style='CommentsStyle').bold = False

        paragraph = A.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run("Plan: ", style='CommentsStyle').bold = True
        paragraph.add_run(self.program_id.name + ' Major',
                          style='CommentsStyle').bold = False

        B = header_table.cell(0, 2)
        pt = B.paragraphs[0]
        t = pt.text = ''
        pt.add_run("Father's Name: ", style='CommentsStyle').bold = True
        pt.add_run(self.father_name, style='CommentsStyle').bold = False
        pt.paragraph_format.space_before = Pt(0)
        pt.paragraph_format.space_after = Pt(0)

        cells = header_table.add_row().cells
        cells[0]._element.clear_content()
        table = cells[0].add_table(rows=0, cols=4)
        table.style = 'Table Grid'
        table.autofit = False

        set_table_width(table, [1.8, 5.3, 1.0, 1.0])
        add_row(table, ['Code', 'Title', 'CH', 'Grd'])

        cells[2]._element.clear_content()
        table = cells[2].add_table(rows=0, cols=4)
        table.alignment = WD_TABLE_ALIGNMENT.RIGHT
        table.style = 'Table Grid'
        table.autofit = False

        set_table_width(table, [1.8, 5.3, 1.0, 1.0])
        add_row(table, ['Code', 'Title', 'CH', 'Grd'])

        set_table_width(header_table, [9.4, 1.0, 9.4])

        footer = document.sections[0].footer
        footer.is_linked_to_previous = False

        pt = footer.paragraphs[0]
        pt.add_run(
            '"The Official Transcript carries the embossed stamp of the University"',
            style='CommentsStyle').bold = True
        pt.paragraph_format.space_before = Pt(0)
        pt.paragraph_format.space_after = Pt(0)

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run(
            'Transcript Prepared By: ---------------------------------------------',
            style='CommentsStyle').bold = False

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run(
            'Transcript Checked By: ---------------------------------------------',
            style='CommentsStyle').bold = False

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run('Date of Issue: ' + str(fields.Date.today()),
                          style='CommentsStyle').bold = False

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run(
            '"Errors and Omissions are subject to Subsequent rectification"',
            style='CommentsStyle').bold = True
        paragraph.add_run("\t\t\tController of Examinations",
                          style='CommentsStyle2').bold = True

        big_table = document.add_table(0, 1)
        big_table.autofit = False
        set_table_width(big_table, [9.5])

        for semester in self.semester_ids:
            row = big_table.add_row()

            tag = row._tr
            child = OxmlElement('w:cantSplit')  # Create arbitrary tag
            tag.append(child)

            cells = row.cells
            cells[0]._element.clear_content()

            # label = cells[0].add_paragraph()
            # label.paragraph_format.keep_with_next = True
            # label.paragraph_format.space_before = Pt(0)
            # label.paragraph_format.space_after = Pt(0)

            table = cells[0].add_table(rows=1, cols=4)
            table.style = 'Table Grid'

            a = table.cell(0, 0)
            b = table.cell(0, 3)
            A = a.merge(b)
            A.text = semester.academic_semester_id.name
            A.paragraphs[
                0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER

            for subject in semester.student_subject_ids:
                add_row(table, [
                    subject.subject_id.subject_id.code,
                    subject.subject_id.subject_id.name,
                    subject.subject_id.weightage, subject.grade
                ])

            set_table_width(table, [1.8, 5.5, 1.0, 1.0])
            transcript_border(table)

            row = table.add_row()
            row_border(row, b=False)
            a = table.cell(len(table.rows) - 1, 0)
            b = table.cell(len(table.rows) - 1, 3)
            A = a.merge(b)

            tb_cell_run = A.paragraphs[0].add_run()
            tb_cell_run.add_text("\tSCH: " + str(semester.credits))
            tb_cell_run.add_text("\t\tSGP: " +
                                 '{0:,.2f}'.format(semester.grade_points))
            tb_cell_run.add_text("\tSGPA: " + '{0:,.2f}'.format(semester.sgpa))
            tb_cell_run.font.size = Pt(8)

            row = table.add_row()
            # row_border(table.rows[len(table.rows)-1],t=False)
            row_border(row, t=False)
            a = table.cell(len(table.rows) - 1, 0)
            b = table.cell(len(table.rows) - 1, 3)
            A = a.merge(b)

            tb_cell_run = A.paragraphs[0].add_run()
            tb_cell_run.add_text("\tCCH: " + str(semester.cch))
            tb_cell_run.add_text("\t\tCGP: " + '{0:,.2f}'.format(semester.cgp))
            tb_cell_run.add_text("\tCGPA: " + '{0:,.2f}'.format(semester.cgpa))
            tb_cell_run.font.size = Pt(8)

            for row in table.rows:
                row.height = Cm(0.4)

            label = cells[0].paragraphs[0]
            label.paragraph_format.keep_with_next = True
            label.paragraph_format.space_before = Pt(0)
            label.paragraph_format.space_after = Pt(0)

        sectPr = document.sections[-1]._sectPr
        cols = sectPr.xpath('./w:cols')[0]
        cols.set(qn('w:num'), '2')

        preventDocumentBreak(document)

        # document.save('demo.docx')

        temporary_files = []

        doc_report_fd, doc_report_path = tempfile.mkstemp(suffix='.docx',
                                                          prefix='report.tmp.')
        os.close(doc_report_fd)
        temporary_files.append(doc_report_path)

        pdf_report_fd, pdf_report_path = tempfile.mkstemp(suffix='.pdf',
                                                          prefix='report.tmp.')
        os.close(pdf_report_fd)
        temporary_files.append(pdf_report_path)

        document.save(doc_report_path)

        #send to server
        headers = {
            'Content-Type': 'multipart/form-data',
        }

        response = requests.put(endpoint,
                                files={'file': open(doc_report_path, 'rb')})
        if response.status_code == 200:
            print(response.text)

        response = requests.get(endpoint2)
        print(response.status_code)

        if response.status_code == 200:
            with open(pdf_report_path,
                      'wb') as out_file:  # change file name for PNG images
                out_file.write(response.content)

        #
        # try:
        #     # wkhtmltopdf = [_get_wkhtmltopdf_bin()] + command_args + files_command_args + paths + [pdf_report_path]
        #     wkhtmltopdf = ["/usr/bin/unoconv", "-f", "pdf", "-o", pdf_report_path, doc_report_path]
        #     process = subprocess.Popen(wkhtmltopdf, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        #     out, err = process.communicate()
        # except:
        #     raise

        with open(pdf_report_path, 'rb') as pdf_document:
            pdf_content = pdf_document.read()

        # Manual cleanup of the temporary files
        for temporary_file in temporary_files:
            try:
                os.unlink(temporary_file)
            except (OSError, IOError):
                _logger.error('Error when trying to remove file %s' %
                              temporary_file)

        return pdf_content
예제 #28
0
def generuj_rozkaz(request):
    query1 = Dane.objects.filter(typ='przepustkę jednorazową', transport__contains='kolejowym w klasie 2').order_by(
        '-stopien_id', 'nazwisko')
    query2 = Dane.objects.filter(typ='urlop', transport__contains='kolejowym w klasie 2').order_by('-stopien_id',
                                                                                                     'nazwisko')
    query3 = Dane.objects.filter(typ='przepustkę jednorazową', transport__contains='autobusowym w').order_by(
        '-stopien_id', 'nazwisko')
    query4 = Dane.objects.filter(typ='urlop', transport__contains='autobusowym w').order_by('-stopien_id',
                                                                                               'nazwisko')

    THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
    generated_rozkaz = os.path.join(THIS_FOLDER, 'demo.docx')
    document = Document()

    dodaj_naglowek(document)

    licznik = 1

    tables = []

    # tworzenie tabeli osobna funkcja
    if query1:
        p = document.add_paragraph(switch_litery(licznik) + 'na przepustkę jednorazową – środek transportu PKP:')
        # p.paragraph_format.left_indent = Inches (0.25)
        table1 = dodaj_tabele(document, query1)
        tables.append(table1)
        p.paragraph_format.space_before = Pt(12)

    if query2:
        licznik += 1
        p = document.add_paragraph(switch_litery(licznik) + 'na urlop – środek transportu PKP:')
        # p.paragraph_format.left_indent = Inches (0.25)
        table2 = dodaj_tabele(document, query2)
        tables.append(table2)
        p.paragraph_format.space_before = Pt(12)
    if query3:
        licznik += 1
        p = document.add_paragraph(switch_litery(licznik) + 'na przepustkę jednorazową – środek transportu PKS:')
        # p.paragraph_format.left_indent = Inches (0.25)
        table3 = dodaj_tabele(document, query3)
        tables.append(table3)
        p.paragraph_format.space_before = Pt(12)
    if query4:
        licznik += 1
        p = document.add_paragraph(switch_litery(licznik) + 'na urlop – środek transportu PKS:')
        # p.paragraph_format.left_indent = Inches (0.25)
        table4 = dodaj_tabele(document, query4)
        tables.append(table4)
        p.paragraph_format.space_before = Pt(12)

    # ustawianie parametrów dokumentu
    style = document.styles['Normal']
    font = style.font
    font.name = 'Times New Roman'
    font.size = Pt(12)

    # ustawianie szerokosci tabelek
    i = 1
    for tbl in tables:
        for row in tbl.rows:
            j = 1
            row.height_rule = WD_ROW_HEIGHT.EXACTLY
            row.height = Inches(0.20)
            for cell in row.cells:
                if j == 1:  # 1)
                    cell.width = Inches(0.1)
                if j == 2:  # stopien
                    cell.width = Inches(1.25)
                if j == 3:  # imie
                    cell.width = Inches(0.9)
                if j == 4:  # nazwisko
                    cell.width = Inches(1.5)
                if j == 5:
                    cell.width = Inches(2.4)
                if j == 6:
                    cell.width = Inches(0.6)
                if j == 7:
                    cell.width = Inches(1.2)
                j += 1
            i += 1

    dodaj_stopke(document)
    # ustawianie marginesow
    sections = document.sections
    for section in sections:
        section.top_margin = Cm(1.5)
        section.bottom_margin = Cm(1.59)
        section.left_margin = Cm(0.75)
        section.right_margin = Cm(1.32)

    # download
    document.save(generated_rozkaz)
    response = HttpResponse(open(generated_rozkaz, 'rb').read())
    response['Content-Type'] = 'text/plain'
    previous_month = datetime.datetime.today().month - 1
    previous_month_name = calendar.month_name[previous_month]  # ustawienie nazwy pliku z rozkazem
    response['Content-Disposition'] = 'attachment; filename= rozkaz"{}".docx'.format(previous_month_name)

    return response
예제 #29
0
    def make_puzzle(self, filename = 'puzzle'):
        difficulty = self.diff
        option = self.option
        if difficulty == 1:
            self.difficulty = 'random.choice([self.col, self.row])(word)'
        elif difficulty == 2:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev])(word)"
        elif difficulty == 3:
            self.difficulty = "random.choice([self.col, self.row, self.diagup, self.diagdown])(word)"
        elif difficulty == 4:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagup_rev, self.diagdown, self.diagdown_rev])(word)"

        self.puzzle_origin = []
        for i in range(self.height):
            self.puzzle_origin.append([])
            for j in range(self.width):
                self.puzzle_origin[i].append('0')
        print("퍼즐 만드는 중")
        words = [word[0] for word in self.word_image]
        for word in words:
            exec(self.difficulty)

        string_words = ''.join(words)
        from collections import Counter
        count_alpha = Counter(string_words)

        common_alph = ''
        for alph in count_alpha.most_common(5):
            common_alph += alph[0]

        data = ''
        if self.korean:
            f = open("random_words.txt", 'r')
            data = f.read()
            regex_f = r'[가-힣]+'
            search_target_f = data
            data = ''.join(list(set(re.findall(regex_f, search_target_f))))

        printed_words = ''
        puzzle = copy.deepcopy(self.puzzle_origin)
        for i in range(self.height):
            for j in range(self.width):
                if self.puzzle_origin[i][j] == "0":
                    fill_alph = random.choice(string.ascii_lowercase)
                    if self.korean:
                        fill_alph = random.choice(data)
                    #글자들 되도록 겹치지 않게 하기 위해서 많이 나오는 글자 한번쯤은 피할 수 있도록 한다.
                    if option == 0:
                        puzzle[i][j] = fill_alph
                    elif option == 1:
                        if fill_alph in common_alph:
                            fill_alph = random.choice(string.ascii_lowercase)
                            if self.korean:
                                fill_alph = random.choice(data)
                        puzzle[i][j] = fill_alph
                        printed_words += puzzle[i][j]
                    #글자가 겹치도록 하기 위해서 많이 나온 글자와 무작위 글자들 중에서 고르도록 한다.
                    elif option == 2:
                        common_alph_list = []
                        puzzle[i][j] = random.choice([fill_alph, random.choice(count_alpha.most_common(7))[0]])
                    printed_words += puzzle[i][j]



        # write to docx file
        # Write to docx to puzzle.docx
        document = Document()
        #changing the page margins
        sections = document.sections
        for section in sections:
            section.top_margin = Cm(1)
            section.bottom_margin = Cm(0.8)
            section.left_margin = Cm(2.3)
            section.right_margin = Cm(2.3)
        heading = 'Word Puzzle'
        if self.korean:
            heading = "낱말 찾기"
        head = document.add_heading(heading, 0)
        head.alignment = WD_ALIGN_PARAGRAPH.CENTER
        if os.path.exists('hwp_settings.json'):
            with open('hwp_settings.json') as f:
                data = json.load(f)
                para_belong = document.add_paragraph('{}학년 {}반 이름: _______'.format(data['grade'], data['class']))
        else:
            para_belong = document.add_paragraph('__학년 __반 이름: _______')
        para_belong.alignment = WD_ALIGN_PARAGRAPH.RIGHT

        puzzle_table = document.add_table(rows=self.height, cols=self.width, style='Table Grid')
        puzzle_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        self.set_height = 7200 / self.height
        for i, row in enumerate(puzzle_table.rows):
            #######################세로 길이 정하기!
            # accessing row xml and setting tr height
            tr = row._tr
            trPr = tr.get_or_add_trPr()
            trHeight = OxmlElement('w:trHeight')
            trHeight.set(qn('w:val'), str(self.set_height))
            trHeight.set(qn('w:hRule'), "atLeast")
            trPr.append(trHeight)

            for j, cell in enumerate(row.cells):
                #####가로 길이 정하기!
                cell.width = Inches(5)
                if self.uppercase and not self.korean:
                    cell.text = puzzle[i][j].upper()
                else:
                    cell.text = puzzle[i][j]
                for paragraph in cell.paragraphs:
                    #####가운데 정렬!!
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    paragraph.style.font.bold = True
                #####상하 방향에서 가운데 정렬
                tc = cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

        # 힌트 테이블 만들기
        # 사진이 들어가는 경우
        if self.pic_on:
            word_num = len(words)
            if word_num <= 15:
                size = 5
            elif word_num <= 21:
                size = (word_num+2)//3
            else:
                size = 7
            hint_table = document.add_table(rows = (len(words)+size-1)//size * 2, cols = size, style = 'Table Grid')
            hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER

            for i, row in enumerate(hint_table.rows):
                #######################세로 길이 정하기!
                if i%2 == 0:
                    # accessing row xml and setting tr height
                    tr = row._tr
                    trPr = tr.get_or_add_trPr()
                    trHeight = OxmlElement('w:trHeight')
                    trHeight.set(qn('w:val'), '1000')
                    trHeight.set(qn('w:hRule'), "atLeast")
                    trPr.append(trHeight)
                elif i%2 == 1:
                    # accessing row xml and setting tr height
                    tr = row._tr
                    trPr = tr.get_or_add_trPr()
                    trHeight = OxmlElement('w:trHeight')
                    trHeight.set(qn('w:val'), '60')
                    trHeight.set(qn('w:hRule'), "atLeast")
                    trPr.append(trHeight)

                for j, cell in enumerate(row.cells):
                    index = i//2*size + j

                    #단어 수 만큼 반복하기
                    if index < len(words):
                        for paragraph in cell.paragraphs:
                            if i % 2 == 1:
                                # 초성 또는 scramble이 켜져 있는 경우
                                if self.chosung_scramable:
                                    word = words[index]
                                    if self.korean:
                                        cho_word = ''
                                        for chr in word:
                                            chosung_scramable = hgtk.letter.decompose(chr)[0]
                                            cho_word += chosung_scramable
                                        run = paragraph.add_run(cho_word)
                                    else:
                                        # 사진 있고 영어고 scramble인 경우
                                        spelling = [i for i in word]
                                        shuffle(spelling)
                                        scrambled_word = ''.join(spelling)
                                        if self.uppercase:
                                            run = paragraph.add_run(scrambled_word.upper())
                                        else:
                                            run = paragraph.add_run(scrambled_word)
                                else:
                                    if self.uppercase and not self.korean:
                                        run = paragraph.add_run(words[index].upper())
                                    else:
                                        run = paragraph.add_run(words[index])
                                font = run.font
                                font.name = 'Arial'
                                font.size = Pt(15)

                            elif i % 2 == 0:
                                try:
                                    run = paragraph.add_run()
                                    run.add_picture(self.word_image[index][1], width=cell.width *95/100,
                                                    height=cell.width)
                                except:
                                    paragraph.add_run("에러 발생. 다른 사진 선택해주세요.")


                            #####가운데 정렬!!
                            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                            paragraph.style.font.bold = True
                    #####상하 방향에서 가운데 정렬
                    tc = cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)

        # 사진이 들어가지 않는 경우
        else:
            # 사진이 안 들어가고 영어인 경우
            if not self.korean:
                hint_table = document.add_table(rows=1, cols=1, style='Table Grid')
                hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                hint_table_row = hint_table.rows[0]
                hint_tr = hint_table_row._tr
                hint_trPr = hint_tr.get_or_add_trPr()
                hint_trHeight = OxmlElement('w:trHeight')
                hint_trHeight.set(qn('w:val'), '1000')
                hint_trHeight.set(qn('w:hRule'), "atLeast")
                hint_trPr.append(hint_trHeight)
                hint_table_cell = hint_table_row.cells[0]
                hint = ''
                parenthesis = re.compile(r'(\s)?\(.*\)(\s)?')
                bracket = re.compile(r'(\s)?\[.*\](\s)?')
                for word in words:
                    print("사전에 찾는중... " + word)
                    req = requests.get('http://endic.naver.com/small_search.nhn?query=' + word)
                    # 국어사전은 'http://ko.dict.naver.com/small_search.nhn?query='
                    html = req.text
                    soup = BeautifulSoup(html, 'html.parser')
                    meanings = soup.select('span.fnt_k05')
                    if self.uppercase:
                        word = word.upper()
                    if self.chosung_scramable:
                        spelling = [i for i in word]
                        shuffle(spelling)
                        word = ''.join(spelling)
                    if meanings:
                        text = meanings[0].text
                        text = re.sub(parenthesis, '', text)
                        text = re.sub(bracket, '', text)
                        print(text)
                        hint += word + "({})".format(text) + ', '
                hint_table_cell.width = Inches(100)
                for paragraph in hint_table_cell.paragraphs:
                    paragraph.add_run(hint.strip(', '))
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                tc = hint_table_cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

            else:
                # 사진이 안 들어가고 한글인 경우
                if self.chosung_scramable:
                    hint_table = document.add_table(rows=1, cols=1, style='Table Grid')
                    hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                    hint_table_row = hint_table.rows[0]
                    hint_tr = hint_table_row._tr
                    hint_trPr = hint_tr.get_or_add_trPr()
                    hint_trHeight = OxmlElement('w:trHeight')
                    hint_trHeight.set(qn('w:val'), '1000')
                    hint_trHeight.set(qn('w:hRule'), "atLeast")
                    hint_trPr.append(hint_trHeight)
                    hint_table_cell = hint_table_row.cells[0]
                    hint = ''
                    for word in words:
                        cho_word = ''
                        for chr in word:
                            chosung_scramable = hgtk.letter.decompose(chr)[0]
                            cho_word += chosung_scramable
                        hint += cho_word + ', '
                    hint_table_cell.width = Inches(100)
                    for paragraph in hint_table_cell.paragraphs:
                        paragraph.add_run(hint.strip(', '))
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                    tc = hint_table_cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)
                else:
                    hint_table = document.add_table(rows=1, cols=1, style='Table Grid')
                    hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                    hint_table_row = hint_table.rows[0]
                    hint_tr = hint_table_row._tr
                    hint_trPr = hint_tr.get_or_add_trPr()
                    hint_trHeight = OxmlElement('w:trHeight')
                    hint_trHeight.set(qn('w:val'), '1000')
                    hint_trHeight.set(qn('w:hRule'), "atLeast")
                    hint_trPr.append(hint_trHeight)
                    hint_table_cell = hint_table_row.cells[0]
                    hint = ''
                    for word in words:
                        hint += word + ', '
                    hint_table_cell.width = Inches(100)
                    for paragraph in hint_table_cell.paragraphs:
                        paragraph.add_run(hint.strip(', '))
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                    tc = hint_table_cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)





        # 정답 파일 쓰기
        answ_doc = Document()
        answer_table = answ_doc.add_table(rows=self.height, cols=self.width, style='Table Grid')
        answer_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        for i, row in enumerate(answer_table.rows):
            #######################세로 길이 정하기!
            # accessing row xml and setting tr height
            tr = row._tr
            trPr = tr.get_or_add_trPr()
            trHeight = OxmlElement('w:trHeight')
            trHeight.set(qn('w:val'), str(self.set_height))
            trHeight.set(qn('w:hRule'), "atLeast")
            trPr.append(trHeight)

            for j, cell in enumerate(row.cells):
                #####가로 길이 정하기!
                cell.width = Inches(8)
                cell.text = self.puzzle_origin[i][j]
                for paragraph in cell.paragraphs:
                    #####가운데 정렬!!
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    paragraph.style.font.bold = True
                    if cell.text == '0':
                        for run in paragraph.runs:
                            run.font.color.rgb = RGBColor(255, 255, 255)
                    else:
                        for run in paragraph.runs:
                            run.font.color.rgb = RGBColor(255, 0, 0)
                #####상하 방향에서 가운데 정렬
                tc = cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

        answ_doc.save(str(self.desktop) + '\{}_정답.hwp'.format(filename))
        document.save(str(self.desktop) +'\{}.hwp'.format(filename))
        print("바탕화면에 puzzle.docx와 puzzle.hwp 로 저장")
예제 #30
0
fontn = document.styles['Normal'].font
fontn.size = Pt(9)
fontn.name = 'Frutiger LT 45'
fontn.color.rgb = RGBColor(31, 73, 125)

document.add_heading('PHAST Discharge Analysis - ' + folder, level=0)

ISs = []
for e in lEvent:
    pvis,hole,weather = e.Key.split("\\")
    if not (pvis in ISs):
        ISs.append(pvis)

nbr=1
pfn = None
for IS in ISs:
    document.add_heading(IS, level=1)
    for e in lEvent:
        pvis,hole,weather = e.Key.split("\\")
        pngfilename = "TVD-"+pvis+"_"+hole
        if (IS == pvis) and (pfn != pngfilename):                        
            pfn = pngfilename #to prevent tvd... is duplicate for different weather
            # fn = 'C\\'+folder+'\\C_'+slugify(e.Key)+'.png'
            fn = slugify(pngfilename)
            document.add_picture(".\\tvd_rev.B\\"+fn+".png", width=Cm(13))            
            p = document.add_paragraph('Figure '+str(nbr) + " - " + pvis + " Hole: " + hole)
            nbr = nbr +1
    document.add_page_break()
document.save('tvd_'+folder+'_rev2.docx')