Esempio n. 1
0
def createImg(text, idnum):
    print("creating image")
    img = Image.open(str(rootPath) + "bg.jpg")
	#any square background with dimensions 1080x1080. if using other dim you have to adjust the wrap around below
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(str(rootPath) + "font.ttf", 30)
	#mess around with the numbers above and below to find perfect wrap around for text so it doesnt get cut off
    draw.text((40, 40), str(fill(text, 30)), (0, 0, 0), font)
    img.save(str(rootPath) + "images/" + str(idnum) + ".jpg")
    print("Image saved as " + str(idnum) + ".jpg")
Esempio n. 2
0
    def test_fill(self):
        # Test the fill() method

        expect = '''\
This paragraph will be filled, first
without any indentation, and then with
some (including a hanging indent).'''

        result = fill(self.text, 40)
        self.check(result, expect)
def from_xml_to_text(input_filepath,
                     output_filepath,
                     tipo_boletin,
                     legible=False):
    # Recuperar fichero de configuración
    ruta_fcs = pathlib.Path(
        __file__).absolute().parent.parent / 'ficheros_configuracion'
    ruta_fichero_conf = ruta_fcs / (tipo_boletin + '_conf.xml')
    try:
        with open(ruta_fichero_conf, 'rb') as file:
            tree_fc = ET.parse(file)
            root_fc = tree_fc.getroot()
    except:
        msg = ("\nFailed: Open {ruta_fichero_conf}").format(
            ruta_fichero_conf=ruta_fichero_conf)
        logger.exception(msg)
        return

    # Abrir el XML
    try:
        # No se usa porque se abre de forma binaria (rb)
        # tipo_codificacion = root_fc.find('./charsets/xml').text
        with open(input_filepath, 'rb') as file:
            tree = ET.parse(file)
            root = tree.getroot()
    except:
        msg = ("\nFailed: Read {path}").format(path=input_filepath)
        logger.exception(msg)
        sys.exit()

    # Obtener texto
    if tipo_boletin == 'BOE':
        texto = ''
        for parrafo in root.findall(
                root_fc.find('./etiquetas_xml/auxiliares/texto').text):
            texto += parrafo.text + '\n'
    else:
        texto = root.find(
            root_fc.find('./etiquetas_xml/auxiliares/texto').text).text

    # Escribir fichero
    try:
        fp = open(output_filepath, 'w+', encoding='utf-8')
        if legible:
            texto = textwrap3.fill(texto, width=MAX_CHARS_PER_LINE)

        fp.write(texto)
        fp.close()
    except Exception as e:
        msg = ("\nFailed: Write {path}").format(path=output_filepath)
        logger.exception(msg)
Esempio n. 4
0
    def test_subsequent_indent(self):
        # Test subsequent_indent parameter

        expect = '''\
  * This paragraph will be filled, first
    without any indentation, and then
    with some (including a hanging
    indent).'''

        result = fill(self.text,
                      40,
                      initial_indent="  * ",
                      subsequent_indent="    ")
        self.check(result, expect)
Esempio n. 5
0
    def test_initial_indent(self):
        # Test initial_indent parameter

        expect = [
            "     This paragraph will be filled,",
            "first without any indentation, and then",
            "with some (including a hanging indent)."
        ]
        result = wrap(self.text, 40, initial_indent="     ")
        self.check(result, expect)

        expect = "\n".join(expect)
        result = fill(self.text, 40, initial_indent="     ")
        self.check(result, expect)
Esempio n. 6
0
def same_behavior(text, width, **kwargs):
    """
    Comparison fixture. Did ansiwrap wrap the text to the same number
    of lines, with the same number of visible characters per line, as textwrap
    did to the text without ANSI codes?
    """
    no_ansi = strip_color(text)
    clean_wrap = textwrap.wrap(no_ansi, width, **kwargs)
    clean_fill = textwrap.fill(no_ansi, width, **kwargs)
    ansi_wrap = wrap(text, width, **kwargs)
    ansi_fill = fill(text, width, **kwargs)

    clean_wrap_lens = lengths(clean_wrap)
    ansi_wrap_lens = lengths(striplines(ansi_wrap))

    assert len(clean_wrap) == len(ansi_wrap)
    assert len(clean_fill) == len(strip_color(ansi_fill))
    assert clean_wrap_lens == ansi_wrap_lens
Esempio n. 7
0
def createvid(description, image_temp_list, fps=24, duration=0.1):
    blackbg = me.ColorClip((720, 720), (0, 0, 0))

    clips = [
        me.ImageClip(m.name + ".png", duration=duration)
        for m in image_temp_list
    ]
    for img in image_temp_list:
        img.close()
    concat_clip = me.concatenate_videoclips(clips,
                                            method="compose").set_position(
                                                ('center', 'center'))
    if description == "start song":
        description = " "
    if len(description) > 35:
        description = fill(description, 35)

    txtClip = me.TextClip(description,
                          color='white',
                          fontsize=30,
                          font='Amiri-regular').set_position('center')
    txt_col = txtClip.on_color(size=(blackbg.w, txtClip.h + 10),
                               color=(0, 0, 0),
                               pos=('center', 'center'),
                               col_opacity=0.8)

    txt_mov = txt_col.set_position((0, blackbg.h - 20 - txtClip.h))
    comp_list = [blackbg, concat_clip, txt_mov]
    final = me.CompositeVideoClip(comp_list).set_duration(concat_clip.duration)

    with tempfile.NamedTemporaryFile() as video_tempfile:
        final.write_videofile(video_tempfile.name + ".mp4", fps=fps)
        video_tempfile.seek(0)

        for clip in clips:
            clip.close()
        for clip in comp_list:
            clip.close()
        return video_tempfile
Esempio n. 8
0
def test_odd_states():
    """
    Attempt to put in codes that are not often seen with ansicolors module,
    but that are legit ANSI codes and used by other text processors. These inluce
    erase to end of line (EL) common in grep output, sepecifc style turn-offs
    that aren't "turn off everything," and truncated "turn off evertying."
    """

    EL = '\x1b[K'

    text = ('textwrap\ndoes\nplain\ntext\nwell.\n' + red('But') + ' text ' +
            color('colored', fg=11, bg=55, style='bold') + yellow(' with ') +
            red('embedded ', style='underline') + blue('ANSI', bg='yellow') +
            green(' codes') + '\x1b[2;33;43m?\x1b[39;49m\x1b[m' + EL +
            green(' Not') + '\x1b[39m' + '\x1b[49m' + '\x1b[1m\x1b[21m' +
            red(' so ') + '\x1b[38;2;12;23;39;48;2;10;10;10mmgood\x1b[m ' +
            magenta('there') + cyan('.') + EL +
            color(' ansiwrap ', style='italic') + yellow('has') + red(' no') +
            green(' such ') + blue('limits.'))

    no_ansi = strip_color(text)

    for width in LINE_LENGTHS:
        assert strip_color(fill(text, width)) == textwrap.fill(no_ansi, width)
def from_html_to_text(input_filepath, output_filepath, tipo_boletin, legible):
    # Recuperar fichero de configuración
    ruta_fcs = pathlib.Path(
        __file__).absolute().parent.parent / 'ficheros_configuracion'
    ruta_fichero_conf = ruta_fcs / (tipo_boletin + '_conf.xml')
    try:
        with open(ruta_fichero_conf, 'rb') as file:
            tree_fc = ET.parse(file)
            root_fc = tree_fc.getroot()
    except:
        msg = ("\nFailed: Open {ruta_fichero_conf}").format(
            ruta_fichero_conf=ruta_fichero_conf)
        logger.exception(msg)
        return

    try:
        with codecs.open(
                input_filepath, 'r',
                root_fc.find('./charsets/html').text
        ) as file:  # LO REALIZADO ES DEL BOA Y BOPs (COMPROBAR CORRECTO FUNCIONAMIENTO)
            html = file.read()
    except:
        msg = ("\nFailed: Open {input_filepath}").format(
            input_filepath=input_filepath)
        logger.exception(msg)
        return

    # Para BOE y Aragón se coge el texto entre cadenas conocidas y para otros se cogería todo el texto.
    # En BOE, con esto se consigue coger las td fácilmente, además de los párrafos.
    # Para los de Aragón es más necesario por la dificultad de parsearlo (está bastante mal estructurado).
    soup = BeautifulSoup(html, 'html.parser')
    texto_html = soup.get_text()

    if tipo_boletin in ['BOA', 'BOPH', 'BOPZ', 'BOPT']:
        inicio_texto = 'Texto completo:'
        fin_texto = '\n\n\n\n\n\n\n\n\n\n'
    elif tipo_boletin == 'BOE':
        inicio_texto = 'TEXTO ORIGINAL'
        fin_texto = '\nsubir\n'

    if tipo_boletin in ['BOA', 'BOPH', 'BOPZ', 'BOPT', 'BOE']:
        texto_html = texto_html[texto_html.find(inicio_texto
                                                ):][len(inicio_texto):]
        texto_html = texto_html[:texto_html.find(fin_texto)]

    # Quitar primeros saltos de línea
    num_saltos = 0
    i = 0
    while (i < len(texto_html)):
        if texto_html[i] == '\n' or texto_html[i] == ' ':
            num_saltos += 1
        else:
            break
        i += 1

    texto_html = texto_html[num_saltos:]

    # Escribir fichero
    try:
        fp = open(output_filepath, 'w+', encoding='utf-8')
        if legible:
            texto_html = textwrap3.fill(texto_html, width=MAX_CHARS_PER_LINE)

        fp.write(texto_html)
        fp.close()
    except Exception as e:
        msg = ("\nFailed: Write {path}").format(path=output_filepath)
        logger.exception(msg)
def from_pdf_to_text(input_filepath: str,
                     output_filepath: str,
                     tipo_boletin: dict,
                     legible: bool = False):

    try:
        pdf = pdfplumber.open(input_filepath)
    except:
        msg = ("\nFailed: Read {path}").format(path=input_filepath)
        logger.exception(msg)
        sys.exit()

    # Intentar obtener fichero de configuración del tipo_boletin.
    root_fc = recuperar_fichero_configuracion(tipo_boletin)
    if root_fc is not None:
        bounding_box = (int(root_fc.find('./puntos_corte/x0').text),
                        int(root_fc.find('./puntos_corte/top').text),
                        int(root_fc.find('./puntos_corte/x1').text),
                        int(root_fc.find('./puntos_corte/bottom').text))
        bounding_box_fecha = (
            int(root_fc.find('./puntos_corte/x0_fecha').text),
            int(root_fc.find('./puntos_corte/top_fecha').text),
            int(root_fc.find('./puntos_corte/x1_fecha').text),
            int(root_fc.find('./puntos_corte/bottom_fecha').text))
    else:  # Si el boletín no está en la configuración, se utilizan valores por defecto (similares a los del BOE)
        bounding_box = (50, 100, 500, 800)
        bounding_box_fecha = (150, 75, 400, 90)

    # Recuperar el texto necesario
    texto = ''
    for page in pdf.pages:
        # withinBBoxPage = page.within_bbox(bounding_box)		# Alternativa.
        try:
            croppedPage = page.crop(bounding_box)
            extracted_text = croppedPage.extract_text()
            if extracted_text is not None:
                texto += extracted_text + '\n'  # \n necesario por las páginas que terminan con media palabra.
        except:
            msg = ("\nWarning: Failed: Read page from {path}").format(
                path=input_filepath)
            logger.exception(msg)
            # No invalida el documento porque suele ocurrir por páginas apaisadas, que se corresponden
            # a tablas de puestos de anexos, que se tratarán independientemente del texto.

    # Dar formato correcto al texto
    if tipo_boletin == 'BOPT':
        texto = quitar_blankspaces_finales(texto)  # Preprocesamiento del BOPT

    if tipo_boletin in ['BOE', 'BOA', 'BOPZ', 'BOPT']:
        texto = quitar_guion_fin_renglon(texto)
        texto = juntar_por_parrafos(texto)
    elif tipo_boletin == 'BOPH':
        split = texto.split('\n')

        num_articulo = False
        indice_inicio_texto = 0
        for i, e in enumerate(split):
            if len(e.split(' ')) > 7 or not e.isupper():
                if num_articulo:
                    indice_inicio_texto = i
                    break
                else:
                    num_articulo = True

        string_inicial = '\n'.join(split[:i])
        string_texto = '\n'.join(split[i:])

        string_texto = juntar_por_parrafos_punto(
            quitar_guion_fin_renglon(string_texto, False))

        texto = string_inicial + '\n' + string_texto
    else:
        # Para otro tipo de boletines, se realiza esto como procesamiento único, además del corte previo.
        texto = quitar_guion_fin_renglon(texto)
        texto = juntar_por_parrafos(texto)

    ## Recuperar fecha
    page = pdf.pages[0]
    fecha = page.crop(bounding_box_fecha).extract_text()

    # Dar formato correcto a la fecha (BOA es correcto de forma predeterminada, otros boletines se dan por correctos.)
    cambio_meses = diccionario_meses()
    if tipo_boletin == 'BOE':
        fechaAux = fecha.split(' ')
        if len(fechaAux[1]) == 1:
            fechaAux[1] = '0' + fechaAux[1]
        fecha = fechaAux[1] + '/' + cambio_meses[
            fechaAux[3].lower()] + '/' + fechaAux[5]
    elif tipo_boletin == 'BOPT':
        fechaAux = fecha.split(' ')
        if len(fechaAux[0]) == 1:
            fechaAux[0] = '0' + fechaAux[0]
        fecha = fechaAux[0] + '/' + cambio_meses[
            fechaAux[2].lower()] + '/' + fechaAux[4]
    elif tipo_boletin == 'BOPH' or tipo_boletin == 'BOPZ':
        fechaAux = fecha.split(' ')
        if len(fechaAux[0]) == 1:
            fechaAux[0] = '0' + fechaAux[0]
        fecha = fechaAux[0] + '/' + cambio_meses[
            fechaAux[1].lower()] + '/' + fechaAux[2]

    # Escribir fecha y texto
    if tipo_boletin == 'BOPT':
        # Quedarse solo con el primer artículo que aparece (sin contar el incompleto), ya que los otros,
        # en caso de ser de empleo volverán a salir. Así se evitan duplicados y problemas con las info.
        texto = 'Núm. ' + texto.split('Núm. ')[1]

    try:
        fp = open(output_filepath, 'w+', encoding='utf-8')
        if legible:
            texto = textwrap3.fill(texto, width=MAX_CHARS_PER_LINE)

        fp.write(texto)
        fp.close()
    except Exception as e:
        msg = ("No se ha podido escribir el"
               f" texto en el fichero {output_filepath}.")
        raise OutputTextError(msg) from e