def isCompressed(self):

        # basepath = 'tmp'
        basepath = os.path.dirname(self.path)
        fileName = baseName(self.path)

        with zipfile.ZipFile(self.path, 'r') as zf:
            if len(zf.namelist()) == 1:
                singleFile = zf.namelist()[0]
                outfile = [filePath(basepath, singleFile)]
                if self.multi is False:
                    with open(outfile[0], 'wb') as f:
                        f.write(
                            zf.read(singleFile))  ## zf.read() equaly bytes  ##
                else:
                    self.internal.append(
                        zf.read(singleFile).replace(b"\r\n", b"\n"))
                outfile1 = filePath(os.path.dirname(self.path), singleFile)
                return outfile, outfile1
            elif not zf.namelist():
                logger.debug(f"{fileName} is empty")
            elif len(zf.namelist()) >= 2:
                izbor = [x for x in zf.namelist() if not x.endswith('/')]
                if len(zf.namelist()) > 9:
                    dlg = MultiChoice(None,
                                      "Pick files:",
                                      fileName,
                                      choices=izbor)
                else:
                    dlg = wx.MultiChoiceDialog(None, 'Pick files:', fileName,
                                               izbor)
                try:
                    if dlg.ShowModal() == wx.ID_OK:
                        response = dlg.GetSelections()
                        files = [izbor[x] for x in response]
                        names = [baseName(i) for i in files]
                        outfiles = [filePath(basepath, x) for x in names]
                        single = filePath(
                            os.path.dirname(self.path),
                            baseName(files[-1]),
                        )
                        if len(files) == 1:
                            with open(outfiles[0], "wb") as f:
                                f.write(zf.read(files[0]))
                        for i in files:
                            self.internal.append(
                                zf.read(i).replace(b"\r\n", b"\n"))
                        self.internPath.extend((files))
                        return outfiles, single
                    else:
                        logger.debug(f'{self.path}: Canceled.')
                        dlg.Destroy()
                finally:
                    dlg.Destroy()
예제 #2
0
def checkFile(path, newfile, text_s, multi=False):
    file1_name = path
    try:
        n_sign = text_s.count(r"\?")
        if n_sign > 0:
            poruka = re.sub(
                r"(?: ){2,14}",
                " ",
                u'!! Greška u tekstu\
            !!\n{0}\nNeispravnih znakova\ konvertovanih kao znak `?` ukupno:\
            [{1} ]',
            ).format(baseName(file1_name), n_sign)

            logger.debug(poruka)
            if multi is True:
                file1_name = newfile
            error_text = f"Greška:\n\n{baseName(file1_name)}\nBilo je neispravnih znakova u\
            tekstu\nkonvertovanih kao znak `?`\nUkupno: [{n_sign}]\nProverite tekst."

            if error_text:
                error_text = re.sub("(?: ){2,4}", " ", error_text)
            return error_text
    except UnboundLocalError as e:
        logger.debug(f"File_Check, error({e})")
    except Exception as e:
        logger.debug(f"File_Check, unexpected error: {e}")
예제 #3
0
def displayError(text, tctrl, rdir, path, new_enc, multi=False):
    """"""
    nlist = w_position(r"\?", text)
    epath = baseName(path)

    if type(rdir) is list:
        rdir = [x for rdir[0] in rdir for x in rdir[0]]
        outf = os.path.join(rdir[0], os.path.splitext(epath)[0] + "_error.log")
    else:
        outf = os.path.join(rdir, os.path.splitext(epath)[0] + "_error.log")

    showMeError(path, text, outf, new_enc)
    text = text.replace('¬', '?')

    if multi is False:
        tctrl.SetValue(text)
        for i in nlist:
            if not len(nlist) > 300:
                tctrl.SetStyle(i[0], i[1], wx.TextAttr("YELLOW", "GREEN"))
                tctrl.SetInsertionPoint(i[1])

    return text
예제 #4
0
def fileHandle(infiles, text_control, fdrop=False):
    """"""
    c = 0
    if type(infiles) != list:
        infiles = [infiles]

    def file_go(infile, rfile):
        enc = FileOpened(infile).findCode()
        text = normalizeText(enc, infile)
        text = text.replace("\r\n", "\n")
        bufferText(text, WORK_TEXT)
        text = WORK_TEXT.getvalue()
        nlist = checkErrors(text)
        text_control.SetValue(text)
        text_control.SetInsertionPoint(0)
        if fdrop is False:
            if nlist:
                for i in nlist:
                    text_control.SetStyle(i[0], i[1],
                                          wx.TextAttr("YELLOW", "BLUE"))
                    text_control.SetInsertionPoint(i[1])
        PREVIOUS.clear()
        addPrevious("Open", enc, text, "", infile, rfile)
        logger.debug(f"Opened: {baseName(infile)}, {enc}")
        if os.path.exists(droppedText): os.remove(droppedText)
        d_text = {text: enc}
        with open(filePath('resources', 'var', 'r_text0.pkl'), 'wb') as t:
            pickle.dump(d_text, t)

        return enc

    if len(infiles) > 1:
        rpath = [infiles[-1]]
        BYTES_TEXT.clear()
        text_control.SetValue('Files List:\n\n')
        if fdrop is True:
            dispatcher.send("TMP_PATH", message=infiles, msg=[rpath, "", True])
        for i in range(len(infiles)):
            if not zipfile.is_zipfile(infiles[i]):
                try:
                    if not os.path.exists(infiles[i]):
                        logger.debug(f"Skipping {baseName(infiles[i])}")
                        text_control.AppendText(
                            f"\n_SKIP_:{baseName(infiles[i])}")
                        continue
                    c += 1
                    fop = FileOpened(infiles[i])
                    enc = fop.findCode()
                    fop.addBytes(infiles[i], enc, fop.getByteText())
                    name = baseName(infiles[i])
                    text_control.AppendText(f"{c} - {name}\n")
                except Exception as e:
                    logger.debug(f'FileHandler: {e}')
            else:
                try:
                    fop = FileOpened(infiles[i], multi=True)
                    fop.internal.clear()
                    outfile, rfile = fop.isCompressed()
                except:
                    logger.debug('FileHandler: No files selected.')
                else:
                    if len(outfile) == 1:
                        c += 1
                        fop = FileOpened(outfile[0])
                        enc = fop.findByteCode(n=0)
                        fop.addBytes(fop.path, enc, fop.internal[0])
                        nam = outfile[0]
                        text = baseName(nam)
                        text_control.AppendText(f"{c} - {text}\n")
                        fop.internal.clear()
                    elif len(outfile) > 1:
                        for i in range(len(outfile)):
                            c += 1
                            fop = FileOpened(outfile[i])
                            enc = fop.findByteCode(n=i)
                            fop.addBytes(outfile[i], enc, fop.internal[i])
                            text = baseName(outfile[i])
                            text_control.AppendText(f"{c} - {text}\n")
                        fop.internal.clear()
        logger.debug('FileHandler: Ready for multiple files.')
    else:
        name = "".join(infiles)
        if zipfile.is_zipfile(name):
            logger.debug(f'ZIP archive: {baseName(name)}')
            try:
                fop = FileOpened(name)
                fop.internal.clear()
                BYTES_TEXT.clear()
                outfile, rfile = fop.isCompressed()  ## outfile in tmp
            except Exception as e:
                logger.debug(f'ZIP; {e}.')
            else:
                if len(outfile) == 1:
                    if lenZip(name):
                        ## Append if not multiple
                        FILE_HISTORY.append(lenZip(name))
                    enc = file_go(outfile[0], rfile)
                    FILE_HISTORY.append(outfile[0])
                    if fdrop is True:
                        try:
                            dispatcher.send("TMP_PATH",
                                            message=outfile,
                                            msg=[rfile, enc, False])
                        except Exception as e:
                            logger.debug(f"dispatcher: {e} {outfile} {rfile}")
                elif len(outfile) > 1:
                    text_control.SetValue('Files List:\n\n')
                    for i in range(len(outfile)):
                        c += 1
                        fop = FileOpened(outfile[i], True)
                        enc = fop.findByteCode()
                        fop.addBytes(outfile[i], enc, fop.internal[i])
                        text = baseName(outfile[i])
                        text_control.AppendText(f"{c} - {text}\n")
                    if fdrop is True:
                        dispatcher.send("TMP_PATH",
                                        message=outfile,
                                        msg=[rfile, enc, True])
                    logger.debug('FileHandler: Ready for multiple files.')
        elif not zipfile.is_zipfile(name):
            ## Single file only
            ## name = real path
            BYTES_TEXT.clear()
            FILE_HISTORY.append(name)
            tmp_path = filePath('tmp', baseName(name))
            if os.path.isfile(tmp_path):
                if os.path.dirname(name) == "tmp":
                    text = open(tmp_path, "rb").read()
                os.remove(tmp_path)
            if os.path.isfile(name):
                shutil.copy(name, tmp_path)
            else:
                open(tmp_path, "wb").write(text)
            enc = file_go(tmp_path, name)
            if fdrop is True:
                dispatcher.send("TMP_PATH",
                                message=tmp_path,
                                msg=[name, enc, False])
def newName(path, pre_suffix, multi=False):
    ''''''
    added = name_data[0]
    value2_s = name_data[1]
    value5_s = name_data[2]
    value_m = name_data[3]
    oformat = name_data[4]
    ex = name_data[5]

    spattern = re.compile(r"(?:\.srt){2,3}", re.I)
    tpattern = re.compile(r"(?:\.txt){2,3}", re.I)
    upattern = re.compile(r"\s*" + value_m + r"\d*", re.I)

    if len(re.findall(upattern, path)) == 2:
        path = upattern.sub("", path, count=2)
    elif len(re.findall(upattern, path)) == 3:
        path = upattern.sub("", path, count=3)
    if re.findall(spattern, path):
        path = spattern.sub(r".srt", path)
    elif re.findall(tpattern, path):
        path = tpattern.sub(r".txt", path)

    fprint = baseName(path)

    n = os.path.splitext(fprint)[0]

    if not "" in list(ex.values()):
        psufix = os.path.splitext(n)[-1]  ## presufix ispred sufixa
    else:
        psufix = n

    if oformat == "txt" and pre_suffix == value5_s:
        sufix = ".txt"
    elif oformat == "txt" and pre_suffix == value2_s:
        sufix = ".txt"
    ## srt,txt ili neki drugi otvoren
    else:
        sufix = os.path.splitext(path)[-1]

    suffix_list = [
        "." + x if not x.startswith("_") else x for x in ex.values()
    ] + added
    suffix_list.append(value_m)
    suffix_list = [
        x.strip(".") if x.startswith(r".(") else x for x in suffix_list
    ]

    _d = "." + pre_suffix  ## pre_suffix je unet u funkciji koja poziva newName
    if pre_suffix.startswith("_") or pre_suffix.startswith(r"("):
        _d = pre_suffix

    if psufix in suffix_list:
        name1 = '{0}{1}'.format(os.path.splitext(n)[0], _d)  ## u tmp/ folderu
    else:
        name1 = '{0}{1}'.format(n, _d)

    if name1.endswith("."): name1 = name1[:-1]

    for i in suffix_list:
        if i == "." or not i:
            continue
        fpattern = re.compile(i, re.I)
        count_s = len(re.findall(fpattern, name1))
        if count_s >= 2:
            name1 = "".join(name1.rsplit(i, count_s))
            if not name1.endswith(i):
                name1 = name1 + i
    return name1, sufix  ## Vraca samo ime fajla bez putanje