Ejemplo n.º 1
0
def main(arquivoUD,
         criterio,
         parametros,
         limit=0,
         sent_id="",
         fastSearch=False,
         separate=False):
    parametros = parametros.strip()
    pesquisa = ""

    if criterio in [1]:
        import estrutura_ud
        if isinstance(arquivoUD, str):
            with open(arquivoUD) as f:
                arquivoUD = f.read()
        else:
            arquivoUD = arquivoUD.to_str()

    #Lê o arquivo UD
    if criterio in [3, 4]:
        import estrutura_dados
        import estrutura_ud
        qualquercoisa = estrutura_dados.LerUD(arquivoUD)

    if criterio in [2]:
        import estrutura_ud
        if isinstance(arquivoUD, str):
            if "head_token" in parametros or "next_token" in parametros or "previous_token" in parametros:
                corpus = estrutura_ud.Corpus(recursivo=True, sent_id=sent_id)
            else:
                corpus = estrutura_ud.Corpus(recursivo=False, sent_id=sent_id)
            start = time.time()
            corpus.load(arquivoUD)
            sys.stderr.write("\ncorpus.build: " + str(time.time() - start))
        else:
            corpus = arquivoUD

    #Cria a lista que vai ser enviada seja ao terminal ou ao HTML
    output = list()
    casos = 0

    #Regex
    tabela = ['@YELLOW/', '@PURPLE/', '@BLUE/', '@RED/', '@CYAN/']

    if criterio == 1:
        start = time.time()
        sentence = ""
        f = arquivoUD.splitlines(keepends=True)
        for line in f:
            if line.strip():
                sentence += line
            else:
                if limit and len(output) == limit:
                    break
                regex = re.findall('(' + parametros + ')',
                                   sentence,
                                   flags=re.I)
                if regex:
                    casos += len(regex)
                    new_sentence = re.sub('(' + parametros + ')',
                                          r'<b>\1</b>',
                                          sentence,
                                          flags=re.I)
                    tokens = list()
                    header = '!@#' if not '# text = ' in new_sentence else '# text = ' + new_sentence.split(
                        "# text = ")[1].split("\n")[0]
                    for linha in new_sentence.splitlines():
                        if 'b>' in linha and '\t' in linha:
                            if '\\' in linha:
                                linha = re.sub(r"\\(\d+)",
                                               r"\\\\\1",
                                               linha,
                                               flags=re.I)
                            tokens.append(
                                linha.split('\t')[1].replace('<b>',
                                                             '').replace(
                                                                 '</b>', ''))
                    header2 = header
                    for token in tokens:
                        header2 = re.sub(r'\b' + re.escape(token) + r'\b',
                                         '<b>' + token + '</b>',
                                         header2,
                                         flags=re.I)
                    for reg in regex:
                        if not isinstance(reg, str):
                            for i, grupo in enumerate(reg):
                                if i != 0:
                                    if grupo and i - 1 < len(tabela):
                                        token = ""
                                        if '\t' in grupo:
                                            token = grupo.split('\t')[1]
                                        if token:
                                            header2 = re.sub(
                                                r'\b' + re.escape(token) +
                                                r'\b',
                                                tabela[i - 1] + token +
                                                '/FONT',
                                                header2,
                                                flags=re.I)
                    new_sentence = new_sentence.replace(header, header2)
                    output.append(new_sentence)
                sentence = ""
        sys.stderr.write(f"\ncriterio 1: {time.time() - start}")

    #If critério 2
    if criterio == 2:

        #Variáveis
        y = parametros.split('#')[0].strip()
        z = int(parametros.split('#')[1].strip())
        k = parametros.split('#')[2].strip()
        w = int(parametros.split('#')[3].strip())
        for sentence in corpus.sentences.values():
            for token in sentence.tokens:
                colunas = token.to_str().split("\t")
                if any(colunas[z - 1] == x for x in y.split("|")):
                    descarta = False
                    for _token in sentence.tokens:
                        _colunas = _token.to_str().split("\t")
                        if any(_colunas[w - 1] == x for x in k.split(
                                "|")) and _token.dephead == token.id:
                            descarta = True
                    if not descarta:
                        output.append(
                            re.sub(r"\b" + re.escape(token.word) + r"\b",
                                   "<b>" + re.escape(token.word) + "</b>",
                                   sentence.to_str()))
                        casos += 1

    #Regex Independentes
    if criterio == 3:
        regras = [x.strip() for x in parametros.split('::')]

        for a, sentence in enumerate(qualquercoisa):
            sentence2 = sentence
            for b, linha in enumerate(sentence):
                linha2 = linha
                if isinstance(linha2, list):
                    sentence2[b] = "\t".join(sentence2[b])
            sentence2 = "\n".join(sentence2)
            descarta = False
            for regranum, regra in enumerate(regras):
                if regra[0] == '!':
                    regex = re.search(regra[1:],
                                      sentence2,
                                      flags=re.IGNORECASE | re.MULTILINE)
                    casos += len(
                        re.findall(regra[1:], sentence2, flags=re.I | re.M))
                else:
                    regex = re.search(regra,
                                      sentence2,
                                      flags=re.IGNORECASE | re.MULTILINE)
                    casos += len(
                        re.findall(regra, sentence2, flags=re.I | re.M))
                if (regra[0] == '!' and regex) or (regra[0] != '!'
                                                   and not regex):
                    descarta = True
                    break
                sentence2 = re.sub('(' + regra + ')',
                                   tabela[regranum] + r'<b>\1</b>/FONT',
                                   sentence2,
                                   flags=re.IGNORECASE | re.MULTILINE)
            if not descarta:
                tokens = list()
                header = '!@#'
                for linha in sentence2.splitlines():
                    if '# text = ' in linha:
                        header = linha
                    if 'b>' in linha and '\t' in linha:
                        if '@' in linha:
                            tokens.append((linha.split('\t')[1].replace(
                                '<b>', '').replace('</b>', '').replace(
                                    '@' + linha.split('@')[1].split('/')[0] +
                                    '/', ''), '@' +
                                           linha.split('@')[1].split('/')[0] +
                                           '/'))
                            lastcolor = '@' + linha.split('@')[1].split(
                                '/')[0] + '/'
                        else:
                            tokens.append((linha.split('\t')[1].replace(
                                '<b>', '').replace('</b>', ''), lastcolor))
                header2 = header
                for token in tokens:
                    header2 = re.sub(r'\b' + re.escape(token[0]) + r'\b',
                                     token[1] + '<b>' + token[0] + '</b>/FONT',
                                     header2)
                sentence2 = sentence2.replace(header, header2)
                output.append(sentence2.splitlines())

    #pais e filhos
    if criterio == 4:
        filho = parametros.split('::')[0].strip()
        pai = parametros.split('::')[1].strip()

        negativo_filho = False
        negativo_pai = False
        if filho[0] == '!':
            negativo_filho = True
            filho = ''.join(filho[1:])
        if pai[0] == '!':
            negativo_pai = True
            pai = ''.join(pai[1:])

        for a, sentenca in enumerate(qualquercoisa):
            acheifilho = 'não'
            acheipai = 'não'
            descarta = False
            for b, linha in enumerate(sentenca):
                if isinstance(linha, list):
                    if re.search(filho,
                                 '\t'.join(linha),
                                 flags=re.IGNORECASE | re.MULTILINE):
                        acheifilho = (linha, b)
                if isinstance(linha, list):
                    if re.search(pai,
                                 '\t'.join(linha),
                                 flags=re.IGNORECASE | re.MULTILINE):
                        acheipai = (linha, b)

                if not negativo_filho and not negativo_pai and acheipai != 'não' and acheifilho != 'não' and acheipai[
                        0][0] == acheifilho[0][6]:
                    for c, linha in enumerate(sentenca):
                        if '# text' in linha:
                            qualquercoisa[a][c] = re.sub(
                                r'\b' + re.escape(acheipai[0][1]) + r'\b',
                                '<b>@BLUE/' + acheipai[0][1] + '/FONT</b>',
                                qualquercoisa[a][c],
                                flags=re.IGNORECASE | re.MULTILINE)
                            qualquercoisa[a][c] = re.sub(
                                r'\b' + re.escape(acheifilho[0][1]) + r'\b',
                                '<b>@RED/' + acheifilho[0][1] + '/FONT</b>',
                                qualquercoisa[a][c],
                                flags=re.IGNORECASE | re.MULTILINE)
                            break
                    qualquercoisa[a][acheipai[1]] = (
                        '<b>@BLUE/' +
                        '\t'.join(qualquercoisa[a][acheipai[1]]) +
                        '/FONT</b>').split('\t')
                    qualquercoisa[a][acheifilho[1]] = (
                        '<b>@RED/' +
                        '\t'.join(qualquercoisa[a][acheifilho[1]]) +
                        '/FONT</b>').split('\t')
                    output.append(qualquercoisa[a])
                    break

                elif negativo_filho and acheipai != 'não' and acheifilho != 'não' and acheipai[
                        0][0] == acheifilho[0][6]:
                    descarta = True
                    break

                elif negativo_pai and acheifilho != 'não' and acheipai != 'não' and acheipai[
                        0][0] == acheifilho[0][6]:
                    descarta = True
                    break

            if negativo_filho and acheipai != 'não' and acheifilho != 'não' and not descarta:
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheipai[0][1]) + r'\b',
                            '<b>@BLUE/' + acheipai[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheipai[1]] = (
                    '<b>@BLUE/' + '\t'.join(qualquercoisa[a][acheipai[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

            elif negativo_pai and acheipai != 'não' and acheifilho != 'não' and not descarta:
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheifilho[0][1]) + r'\b',
                            '<b>@BLUE/' + acheifilho[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheifilho[1]] = (
                    '<b>@BLUE/' + '\t'.join(qualquercoisa[a][acheifilho[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

            elif negativo_filho and acheipai != 'não' and acheifilho == 'não':
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheipai[0][1]) + r'\b',
                            '<b>@BLUE/' + acheipai[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheipai[1]] = (
                    '<b>@BLUE/' + '\t'.join(qualquercoisa[a][acheipai[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

            elif negativo_pai and acheifilho != 'não' and acheipai == 'não':
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheifilho[0][1]) + r'\b',
                            '<b>@RED/' + acheifilho[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheifilho[1]] = (
                    '<b>@RED/' + '\t'.join(qualquercoisa[a][acheifilho[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

    #Python

    if criterio == 5:

        parametros = parametros.split(" and ")
        for t, parametro in enumerate(parametros):
            if not any(x in parametros[t]
                       for x in [' = ', '==', '!=', ' < ', ' > ']):
                parametros[t] = re.findall(r'@?"[^"]+?"',
                                           parametros[t].replace(" ", ""))
                parametros[t] = [
                    ("@" if "@" in x else "") + ("next_token." * i) +
                    "word = " + x.replace("@", "")
                    for i, x in enumerate(parametros[t]) if x
                ]
                parametros[t] = " and ".join(parametros[t])
        parametros = " and ".join(parametros)
        pesquisa = parametros

        pesquisa = pesquisa.replace(" = ", " == ")
        pesquisa = pesquisa.replace(" @", " ")
        if pesquisa[0] == "@": pesquisa = pesquisa[1:]
        pesquisa = pesquisa.replace("  ", " ").strip()
        pesquisa = pesquisa.replace(" == ", " == token.")
        pesquisa = pesquisa.replace(" === ", " === token.")
        pesquisa = pesquisa.replace(" != ", " != token.")
        pesquisa = pesquisa.replace(" !== ", " !== token.")
        pesquisa = pesquisa.replace(" > ", " > token.")
        pesquisa = pesquisa.replace(" < ", " < token.")
        pesquisa = pesquisa.replace(" >= ", " >= token.")
        pesquisa = pesquisa.replace(" <= ", " <= token.")
        pesquisa = "token." + pesquisa
        pesquisa = pesquisa.replace(" and ", " and token.")
        pesquisa = pesquisa.replace(" or ", " or token.")
        pesquisa = pesquisa.replace(" in ", " in token.")
        pesquisa = pesquisa.replace(" text ", " sentence.text ")
        pesquisa = pesquisa.replace(" sent_id ", " sentence.sent_id ")
        pesquisa = pesquisa.replace('token."', '"')
        pesquisa = pesquisa.replace('token.[', '[')
        pesquisa = pesquisa.replace('token.(', '(')

        pesquisa = pesquisa.replace('token.not', 'not')
        pesquisa = pesquisa.replace('token.token.', 'token.')
        pesquisa = pesquisa.replace('token.sentence.', 'sentence.')
        pesquisa = pesquisa.replace("token.text", "sentence.text")
        pesquisa = pesquisa.replace("token.sent_id", "sentence.sent_id")
        pesquisa = pesquisa.replace('token.int(', 'int(')
        #pesquisa = pesquisa.replace("token.and", "and")
        #		pesquisa = pesquisa.replace("== int(", "==int(")
        pesquisa = re.sub(r'token\.([1234567890])', r'\1', pesquisa)

        indexed_conditions = {
            x.split(" == ")[0].strip().split("token.", 1)[1]:
            x.split(" == ")[1].strip().replace('"', '')
            for x in pesquisa.split(" and ")
            if ' == ' in x and 'token.' in x and not any(
                y in x for y in ["head_token", "previous_token", "next_token"])
        }  #["head_token.head", "head_token.next", "head_token.previous", "next_token.head", "next_token.next", "next_token.previous", "previous_token.head", "previous_token.next", "previous_token.previous"])}
        pesquisa = re.sub(r"token\.([^. ]+?)(\s|$)", r"token.__dict__['\1']\2",
                          pesquisa)

        pesquisa = re.sub(
            r'(\S+)\s==\s(\".*?\")',
            r'any( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("ddd") )',
            pesquisa
        )  #ddd provisório enquanto split na barra em pé não funciona
        pesquisa = re.sub(
            r'(\S+)\s===\s(\".*?\")',
            r'all( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("|") )',
            pesquisa)
        pesquisa = re.sub(
            r'(\S+)\s!=\s(\".*?\")',
            r'not any( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("ddd") )',
            pesquisa)
        pesquisa = re.sub(
            r'(\S+)\s!==\s(\".*?\")',
            r'not all( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("|") )',
            pesquisa)
        pesquisa = pesquisa.strip()

        if (".__dict__['id']" in pesquisa or ".__dict__['dephead']" in pesquisa
            ) and (not "int(" in pesquisa) and (" < " in pesquisa
                                                or " > " in pesquisa):
            pesquisa = re.sub(r"(\S+\.__dict__\['(id|dephead)'\])", r"int(\1)",
                              pesquisa)

        identificador = "token"

        if parametros[0] == "@":
            parametros = parametros[1:]

        arroba = parametros.split(
            " ")[0] if not ' @' in parametros else parametros.rsplit(
                " @", 1)[1].replace(
                    "int(", "").split(")")[0].split(" ")[0].replace("(", "")
        arroba = "token." + arroba
        arroba = arroba.replace("token.token", "token")
        arroba = arroba.rsplit(".", 1)[0]

        agilizar = re.findall(r'"([^"]*)"', parametros)

        import estrutura_ud
        if isinstance(arquivoUD, str):
            if "head_token" in parametros or "next_token" in parametros or "previous_token" in parametros:
                corpus = estrutura_ud.Corpus(recursivo=True,
                                             sent_id=sent_id,
                                             keywords=agilizar)
            else:
                corpus = estrutura_ud.Corpus(recursivo=False,
                                             sent_id=sent_id,
                                             keywords=agilizar)
            start = time.time()
            corpus.load(arquivoUD)
            sys.stderr.write("\ncorpus.build: " + str(time.time() - start))
        else:
            corpus = arquivoUD

        start = time.time()
        casos = []

        t1 = time.time()
        if indexed_conditions:
            sentences = defaultdict(list)
            tokens = defaultdict(list)
            values = {}
            for sent_id in corpus.sentences:
                for col in indexed_conditions:
                    if col in corpus.sentences[sent_id].processed:
                        values = re.findall(
                            r"\n(" + indexed_conditions[col] + r")\n",
                            "\n" + "\n\n".join(
                                list(corpus.sentences[sent_id].processed[col]))
                            + "\n")
                        for value in values:
                            if value:
                                if not isinstance(value, str):
                                    value = value[0]
                                tokens[col].extend(
                                    corpus.sentences[sent_id].processed[col]
                                    [value])
            for col in tokens:
                tokens[col] = set(tokens[col])
            tokens_filtered = []
            if tokens.values():
                tokens_filtered = set.intersection(*list(tokens.values()))
            '''
			priority = ['lemma', 'word', 'deprel', 'upos']
			priority_possible = []
			for col in indexed_conditions:
				if col in priority:
					priority_possible.append(priority.index(col))
			if priority_possible:
				col = priority[min(priority_possible)]
			else:
				col = list(indexed_conditions)[0]
			cols = list(indexed_conditions)
			cols.remove(col)
			'''
            for token in tokens_filtered:
                sent_id = token.split("<tok>")[0]
                t = int(token.split("<tok>")[1])
                sentences[sent_id].append(t)
        else:
            sentences = corpus.sentences
        sys.stderr.write(f"\nindexing: {time.time() - t1}")

        t1 = time.time()
        for sent_id in sentences:
            sentence = corpus.sentences[sent_id]
            sentence2 = sentence
            clean_text = [
                x.word for x in sentence2.tokens
                if not '-' in x.id and not '.' in x.id
            ]
            clean_id = [
                x.id for x in sentence2.tokens
                if not '-' in x.id and not '.' in x.id
            ]
            corresponde = 0
            tokens = sentence2.tokens_to_str()
            map_id = {x: t for t, x in enumerate(clean_id)}
            if limit and limit == len(output):
                break
            condition = "global sim; sim = 0"

            condition += '''
if not indexed_conditions:
	available_tokens = list(range(len(sentence.tokens)))
else:
	available_tokens = sentences[sent_id]
for token_t in available_tokens:
	token = sentence.tokens[token_t]
	try:
		if (not "-" in token.id and not '.' in token.id and (''' + pesquisa + ''')) :
			corresponde = 1
			clean_text[map_id[token.id]] = "@BLUE/" + clean_text[map_id[token.id]] + "/FONT"
			tokens = tokens.replace(token.string, "@BLUE/" + token.string + "/FONT")
	'''#try por causa de não ter um next_token no fim de sentença, por ex.
            if "token.head_token" in pesquisa:
                condition += '''
			clean_text[map_id[token.head_token.id]] = "@RED/" + clean_text[map_id[token.head_token.id]] + "/FONT"
			tokens = tokens.replace(token.head_token.string, "@RED/" + token.head_token.string + "/FONT")'''
            if "token.next_token" in pesquisa:
                condition += '''
			clean_text[map_id[token.next_token.id]] = "@BLUE/" + clean_text[map_id[token.next_token.id]] + "/FONT"
			tokens = tokens.replace(token.next_token.string, "@BLUE/" + token.next_token.string + "/FONT")'''
            if "token.previous_token" in pesquisa:
                condition += '''
			clean_text[map_id[token.previous_token.id]] = "@BLUE/" + clean_text[map_id[token.previous_token.id]] + "/FONT"
			tokens = tokens.replace(token.previous_token.string, "@BLUE/" + token.previous_token.string + "/FONT")'''
            condition += '''
			clean_text[map_id[''' + arroba + '''.id]] = "<b>" + clean_text[map_id[''' + arroba + '''.id]] + "</b>"'''

            exec(condition + '''
			casos.append(1)
			arroba_id = ''' + arroba + '''.id
			tokens = tokens.splitlines()
			for l, linha in enumerate(tokens):
				if linha.split("\\t")[0] == arroba_id or ("/" in linha.split("\\t")[0] and linha.split("\\t")[0].split("/")[1] == arroba_id):
					tokens[l] = "<b>" + tokens[l] + "</b>"
			tokens = "\\n".join(tokens)

			if separate:
				corresponde = 0
				final = "# clean_text = " + " ".join(clean_text) + "\\n" + sentence2.metadados_to_str() + "\\n" + tokens
				output.append(final)
			
	except Exception as e:
		print(str(e))
		print(token.to_str())
		pass
if corresponde and not separate:
	corresponde = 0
	final = "# clean_text = " + " ".join(clean_text) + "\\n" + sentence2.metadados_to_str() + "\\n" + tokens
	output.append(final)''')
        sys.stderr.write("\ncritério 5: " + str(time.time() - start))
        casos = len(casos)
        sys.stderr.write(f"\nfor each sentence: {time.time() - t1}")
    #Transforma o output em lista de sentenças (sem splitlines e sem split no \t)
    if criterio not in [5, 2, 1]:
        for a, sentence in enumerate(output):
            for b, linha in enumerate(sentence):
                if isinstance(linha, list):
                    sentence[b] = "\t".join(sentence[b])
            output[a] = "\n".join(sentence)

    start = time.time()
    for i, final in enumerate(output):
        if not fastSearch:
            anotado = estrutura_ud.Sentence(recursivo=False)
            estruturado = estrutura_ud.Sentence(recursivo=False)
            anotado.build(
                web.escape(
                    final.replace('<b>', '@BOLD').replace(
                        '</b>', '/BOLD').replace(
                            '<font color=' + tabelaf['yellow'] + '>',
                            '@YELLOW/').replace(
                                '<font color=' + tabelaf['red'] + '>',
                                '@RED/').replace(
                                    '<font color=' + tabelaf['cyan'] + '>',
                                    '@CYAN/').replace(
                                        '<font color=' + tabelaf['blue'] + '>',
                                        '@BLUE/').replace(
                                            '<font color=' +
                                            tabelaf['purple'] + '>',
                                            '@PURPLE/').replace(
                                                '</font>', '/FONT')))
            estruturado.build(
                web.unescape(final).replace('<b>', '@BOLD').replace(
                    '</b>', '/BOLD').replace(
                        '<font color=' + tabelaf['yellow'] + '>',
                        '@YELLOW/').replace(
                            '<font color=' + tabelaf['red'] + '>',
                            '@RED/').replace(
                                '<font color=' + tabelaf['cyan'] + '">',
                                '@CYAN/').replace(
                                    '<font color=' + tabelaf['blue'] + '>',
                                    '@BLUE/').
                replace('<font color=' + tabelaf['purple'] + '>',
                        '@PURPLE/').replace('</font>', '/FONT').replace(
                            '@BOLD', '').replace('/BOLD', '').replace(
                                '@YELLOW/', '').replace('@RED/', '').replace(
                                    '@CYAN/',
                                    '').replace('@BLUE/',
                                                '').replace('@PURPLE/',
                                                            '').replace(
                                                                '/FONT', ''))
        else:
            anotado = ""
            estruturado = ""
        output[i] = {
            'resultado': final,
            'resultadoAnotado': anotado,
            'resultadoEstruturado': estruturado,
        }
    #sys.stderr.write("\nbuscaDicionarios: " + str(time.time() - start))

    sentences = {}
    if not fastSearch:
        sentences = {
            x['resultadoEstruturado'].sent_id: i
            for i, x in enumerate(output)
        }

    return {
        'output': output,
        'casos': casos,
        'sentences': sentences,
        'parameters': pesquisa if pesquisa else parametros
    }
Ejemplo n.º 2
0
def getDistribution(arquivoUD,
                    parametros,
                    coluna="lemma",
                    filtros=[],
                    sent_id="",
                    criterio=0):
    import estrutura_ud

    if not criterio:
        if re.search(r"^\d+\s", parametros):
            criterio = int(parametros.split(" ", 1)[0])
            parametros = parametros.split(" ", 1)[1]
        elif len(parametros.split('"')) > 2:
            criterio = 5
        else:
            criterio = 1

    if not isinstance(arquivoUD, dict):
        sentences = main(arquivoUD,
                         criterio,
                         parametros,
                         sent_id=sent_id,
                         fastSearch=True)['output']
    else:
        sentences = arquivoUD['output']

    corpus = list()
    for sentence in sentences:
        if sentence:
            if coluna in different_distribution:
                sent = estrutura_ud.Sentence()
                sent.build(sentence['resultado'].replace(
                    f"@YELLOW/",
                    "").replace(f"@RED/", "").replace(f"@CYAN/", "").replace(
                        f"@BLUE/", "").replace(f"@PURPLE/",
                                               "").replace("/FONT", ""))
                sent_id = sent.sent_id
            else:
                sent = sentence['resultado']
                sent_id = re.findall(r"# sent_id = (.*?)\n",
                                     re.sub(r'<.*?>', '', sent))[0]
            if sent_id not in filtros:
                corpus.append(sent)

    dist = list()
    all_children = {}
    lista = {}
    dispersion_files = {}
    for sentence in corpus:
        sent_id = ""
        if not coluna in different_distribution:
            for t, token in enumerate(sentence.splitlines()):
                if not sent_id:
                    if token.startswith("# sent_id = "):
                        sent_id = token.split("# sent_id = ")[1]
                elif ('<b>' in token
                      or '</b>' in token) and len(token.split("\t")) > 5:
                    entrada = re.sub(
                        r'@.*?/', '',
                        re.sub(
                            r'<.*?>', '',
                            token.split("\t")[coluna_tab[coluna]].replace(
                                "/FONT", "")))
                    dist.append(entrada)
                    if not entrada in lista:
                        lista[entrada] = 0
                    lista[entrada] += 1
                    if '-' in sent_id:
                        if not entrada in dispersion_files:
                            dispersion_files[entrada] = []
                        filename = sent_id.rsplit("-", 1)[0]
                        if not filename in dispersion_files[entrada]:
                            dispersion_files[entrada].append(filename)
        if coluna in different_distribution:
            for t, token in enumerate(sentence.tokens):
                if '<b>' in token.to_str() or "</b>" in token.to_str():
                    if not coluna in different_distribution:
                        dist.append(
                            re.sub(r'<.*?>', '', token.__dict__[coluna]))
                    elif coluna in ["dependentes", "children"]:
                        children = [t]
                        children_already_seen = []
                        children_future = []
                        while children_already_seen != children:
                            for child in children:
                                if not child in children_already_seen:
                                    children_already_seen.append(child)
                                for _t, _token in enumerate(sentence.tokens):
                                    if cleanEstruturaUD(
                                            _token.dephead
                                    ) == cleanEstruturaUD(
                                            sentence.tokens[child].id):
                                        children_future.append(_t)
                            [
                                children.append(x) for x in children_future
                                if x not in children
                            ]
                            children_future = []
                        children_list = [
                            cleanEstruturaUD(sentence.tokens[x].word)
                            if x != t else "<b>" +
                            cleanEstruturaUD(sentence.tokens[x].word) + "</b>"
                            for x in sorted(children)
                        ]
                        if len(children_list) > 1:
                            entrada = " ".join(children_list)
                            dist.append(entrada)
                            if not entrada in lista:
                                lista[entrada] = 0
                            lista[entrada] += 1
                            if '-' in sentence.sent_id:
                                filename = sentence.sent_id.rsplit("-", 1)[0]
                                if not entrada in dispersion_files:
                                    dispersion_files[entrada] = []
                                if not filename in dispersion_files[entrada]:
                                    dispersion_files[entrada].append(filename)
                            if children_list:
                                if not entrada in all_children:
                                    all_children[entrada] = []
                                all_children[entrada].append(sentence.sent_id)

    #dicionario = dict()
    #for entrada in dist:
    #entrada = entrada.replace("<b>", "").replace("</b>", "")
    #if not entrada in dicionario: dicionario[entrada] = 1
    #else: dicionario[entrada] += 1

    #lista = list()
    #for entrada in dicionario:
    #lista.append((entrada, dicionario[entrada]))

    #freq = dict()
    #for entrada in dicionario:
    #if not dicionario[entrada] in freq: freq[dicionario[entrada]] = 1
    #else: freq[dicionario[entrada]] += 1
    #lista_freq = list()
    #for entrada in freq:
    #lista_freq.append((entrada, freq[entrada]))

    return {
        "all_children": all_children,
        "lista": lista,
        "dist": len(dist),
        "dispersion_files": dispersion_files
    }
Ejemplo n.º 3
0
def gerar_HTML(matriz, ud1, ud2, col, output, codificação):
		script = 'yes "\n" | python3 conll18_ud_eval.py -v "' + matriz.split('\n\n')[0].splitlines()[1].split(': ' ,1)[1] + '" "' + matriz.split('\n\n')[0].splitlines()[2].split(': ' ,1)[1] + '" > metrica.txt'
		call(script, shell=True)
		metrics = open("metrica.txt", 'r').read()
		with open(output + "_results.txt", "r") as f:
			resultados_cru = f.read()
		with open(output + "_sentence.txt", "r") as f:
			sentence_accuracy = f.read()

		resultados = "<table><tr><th colspan='4'>Acurácia por categoria gramatical</th></tr>"
		for linha in resultados_cru.splitlines():
			resultados += "<tr>"
			for n, item in enumerate(linha.split()):
				if n == 0:
					deprel = item
				if n + 1 == len(linha.split()) and deprel != "DEPREL":
					item = "<a href='UAS/" + deprel + ".html'>" + item + "</a>"
				resultados += "<td>" + item + "</td>"
			resultados += "</tr>"
		resultados += "</table>"

		html = ['<html><head><meta charset="'+codificação+'" name="viewport" content="width=device-width, initial-scale=1.0" ><link href="style.css" rel="stylesheet" type="text/css"><link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css"></head><body><div class="header">']
		html.append('<h1>'+output+'</h1><br><span id="topo"><h3>' + "\n".join(matriz.split('\n\n')[0].splitlines()[1:]) + '''</h3></span></div><div class="content"><center><table><th>Métricas oficiais</th><tr><td><pre>'''+metrics+'''</pre></td></tr></table><br>''' + sentence_accuracy + '''<br>''' + resultados + '''</center></div><!--div class="tab"><button class="tablinks" onclick="openCity(event, 'Dados')">Métricas oficiais</button><button class="tablinks" onclick="openCity(event, 'Matriz')">Matriz de confusão</button></div><div class="tabcontent" id="Matriz"--><pre><table id="t01">''')

		tiposy = dict()
		tiposx = dict()
		for i, linha in enumerate("\n".join(matriz.split('\n\n')[1:]).split('#!$$')[0].split('\n')[2:-1]):
				tiposy[i+2] = linha.split(' ')[0]
		for i, coluna in enumerate("\n".join(matriz.split('\n\n')[1:]).split('#!$$')[0].split('\n')[0].split()[1:-1]):
				tiposx[i+1] = coluna
		y = 0

		linha_html = ""
		for linha in "\n".join(matriz.split('\n\n')[1:]).split('#!$$')[0].split('\n'):
				if linha.strip() != '':
						linha_html += '<tr><td>' + linha.split(' ')[0] + '</td>'
						if y == 0 or y == 1:
								for x, coluna in enumerate(linha.split()[1:]):
										#linha_html += '&#09;' + coluna
										linha_html += '<td>' + coluna + '</td>'
								y += 1
						elif y < len(tiposy):
								for x, coluna in enumerate(linha.split()[1:-1]):
										#linha_html += '&#09;' + '<a href="' + output + '_html/' + tiposy[y] + '-' + tiposx[x+1] + '.html">' + coluna + '</a>'
										linha_html += '<td>' + '<a href="' + output + '_html/' + tiposy[y] + '-' + tiposx[x+1] + '.html">' + coluna + '</a>' + '</td>'
								y += 1
								#linha_html += '&#09;' + linha.split()[-1]
								linha_html += '<td>' + linha.split()[-1] + '</td>'
						elif y == len(tiposy):
								for x, coluna in enumerate(linha.split()[1:]):
										#linha_html += '&#09;' + coluna
										linha_html += '<td>' + coluna + '</td>'
						linha_html += '</tr>'

		html.append(linha_html + '</table></pre>')

		solitários = dict()
		for i, grupo in enumerate(matriz.split('#!$$')[1:]):
				grupo = [x for x in grupo.splitlines() if x]
				html.append('<div class="container"><b>' + grupo[0] + ' (' + str(len(grupo[1:])) + ''')</b> <input type="button" id="botao''' + str(i) + '''" value="Mostrar" onClick="ativa('solitary''' + str(i) + '''', 'botao''' + str(i) + '''')" class="btn-gradient blue mini"><br>''')
				html.append("<div id='solitary" + str(i) + "' style='display:none'>")
				for linha in grupo[1:]:
						if linha.strip() != '':
								html.append(linha)
				html.append("</div></div>")

		sentenças = dict()
		for sentença in ud1:
				sentença_id = ''
				tamanho_sentença = 0
				for linha in sentença:
						if '# text = ' in linha:
								sentença_header = linha
						if '# sent_id = ' in linha:
								sentença_id = linha
						if isinstance(linha, list):
								tamanho_sentença += 1
				for subsentença in ud2:
						subsentença_correta = False
						tamanho_subsentença = 0
						for sublinha in subsentença:
								if '# text = ' in sublinha and sublinha == sentença_header:
										subsentença_correta = True
								if sentença_id == '' and '# sent_id = ' in sublinha:
										sentença_id = sublinha
								if isinstance(sublinha, list):
										tamanho_subsentença += 1
						if subsentença_correta and tamanho_sentença == tamanho_subsentença:
								sentença_limpo = [x for x in sentença if isinstance(x, list)]
								subsentença_limpo = [x for x in subsentença if isinstance(x, list)]
								sentença_limpo_string = [x for x in sentença if isinstance(x, list)]
								subsentença_limpo_string = [x for x in subsentença if isinstance(x, list)]
								for l, linha in enumerate(sentença_limpo_string):
										if isinstance(linha, list):
												sentença_limpo_string[l] = "&#09;".join(sentença_limpo_string[l])
								sentença_limpo_string = "\n".join(sentença_limpo_string)
								for l, linha in enumerate(subsentença_limpo_string):
										if isinstance(linha, list):
												subsentença_limpo_string[l] = "&#09;".join(subsentença_limpo_string[l])
								subsentença_limpo_string = "\n".join(subsentença_limpo_string)
								for k in range(len(sentença_limpo)):
										coluna1 = sentença_limpo[k][col-1]
										coluna2 = subsentença_limpo[k][col-1]
										palavra = sentença_limpo[k][1]
										if not coluna1 + '-' + coluna2 in sentenças:
												sentenças[coluna1 + '-' + coluna2] = [(sentença_id, re.sub(r'\b(' + re.escape(palavra) + r')\b', '<b>' + palavra +'</b>', sentença_header), sentença_limpo_string.replace("&#09;".join(sentença_limpo[k]), '<b>' + "&#09;".join(sentença_limpo[k]) + '</b>'), subsentença_limpo_string.replace("&#09;".join(subsentença_limpo[k]), '<b>' + "&#09;".join(subsentença_limpo[k]) + '</b>'))]
										else: sentenças[coluna1+'-'+coluna2].append((sentença_id, re.sub(r'\b(' + re.escape(palavra) + r')\b', '<b>' + palavra + '</b>', sentença_header), sentença_limpo_string.replace("&#09;".join(sentença_limpo[k]), '<b>' + "&#09;".join(sentença_limpo[k]) + '</b>'), subsentença_limpo_string.replace("&#09;".join(subsentença_limpo[k]), '<b>' + "&#09;".join(subsentença_limpo[k]) + '</b>')))

		open(output + '.html', 'w', encoding=codificação).write("<br>".join(html).replace('\n','<br>') + '''</div></div></body></html>

<script>
function ativa(nome, botao){
var div = document.getElementById(nome)
if (div.style.display == 'none') {
document.getElementById(botao).value='Esconder'
div.style.display = 'block'
} else {
div.style.display = 'none'
document.getElementById(botao).value='Mostrar'
}
}
function carregar_version(){
var link_combination = document.getElementById("carregar_edit").value.split("/")
window.location = window.location.href.split(".html")[0] + "_html/" + link_combination[link_combination.length-1].split("?")[0] + "?" + document.getElementById("carregar_edit").value.split("?")[1]
}
function openCity(evt, cityName) {
	// Declare all variables
	var i, tabcontent, tablinks;

	// Get all elements with class="tabcontent" and hide them
	tabcontent = document.getElementsByClassName("tabcontent");
	for (i = 0; i < tabcontent.length; i++) {
		tabcontent[i].style.display = "none";
	}

	// Get all elements with class="tablinks" and remove the class "active"
	tablinks = document.getElementsByClassName("tablinks");
	for (i = 0; i < tablinks.length; i++) {
		tablinks[i].className = tablinks[i].className.replace(" active", "");
	}

	// Show the current tab, and add an "active" class to the button that opened the tab
	document.getElementById(cityName).style.display = "block";
	evt.currentTarget.className += " active";
}
</script>''')

		#Páginas independentes
		for combinação in sentenças:
				html = ['<html><form><head><meta charset="'+codificação+'" name="viewport" content="width=device-width, initial-scale=1.0" /><style>input[name=maior] { width: 400; }</style><link href="../style.css" rel="stylesheet" type="text/css"><link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css"></head><body onLoad="carregar()"><div class="header">'] #<form action="../matriz_cgi.py?output='+output+'&combination='+combinação+'&encoding='+codificação+'" method="post">
				html.append('<h1>'+output+'</h1><br><span id="topo"><h3>' + matriz.split('\n\n')[0] + '</span></h3></div><div class="content"><h3><a href="../' + output + '.html">Voltar</a></h3>')
				if not os.path.isdir(output + '_html'):
						os.mkdir(output + '_html')
				html.append('<h1><span id="combination">' + combinação + '</span> (' + str(len(sentenças[combinação])) + ')</h1><!--hr--><br>' + ''' <!--input type="button" onclick="enviar('2')" id="salvar_btn" class="btn-gradient orange mini" style="margin-left:0px" value="Gerar link para a versão atual"--> <input type="button" class="btn-gradient green mini" onclick="copiar_frases()" id="copiar_btn" value="Copiar sent_id das frases" style="margin-left:0px"> <input id="link_edit2" type="text" style="display:none"> <div id="gerado2" style="display:none"><b>Link gerado!</b></div><br><br>''')

				carregamento_comment = list()
				carregamento_check = list()
				for i, sentença in enumerate(sentenças[combinação]):
						for word in sentença[1].split():
							if "<b>" in sentença[1]:
								negrito = sentença[1].split("<b>")[1].split("</b>")[0]
							else:
								negrito = ".*"
								#print(negrito)
								#exit()

						#checar pai
						pais = ""
						#if combinação.split("-")[0] == combinação.split("-")[1]:
						pre_1 = estrutura_ud.Sentence()
						pre_1.build(wb.unescape(sentença[2]))
						pre_2 = estrutura_ud.Sentence()
						pre_2.build(wb.unescape(sentença[3]))
						caixa = sentença[1]
						for t, token in enumerate(pre_1.tokens):
							if "<b>" in token.to_str():
								if token.dephead != pre_2.tokens[t].dephead:
									caixa = re.sub(r"\b" + re.escape(token.head_token.word) + r"\b", "<font color=green>" + token.head_token.word + "</font>", caixa)
									caixa = re.sub(r"\b" + re.escape(pre_2.tokens[t].head_token.word) + r"\b", "<font color=red>" + pre_2.tokens[t].head_token.word + "</font>", caixa)
									pais = '<h3><font color="red">PAIS DIFERENTES</font></h3>'
								break

						carregamento_check.append('check1_'+str(i))
						carregamento_check.append('check2_'+str(i))
						carregamento_comment.append('comment'+str(i))
						html.append('<div class="container"><input type="hidden" name="negrito" value="' + negrito + '">' + str(i+1) + ' / ' + str(len(sentenças[combinação])) + '<br><br>' + sentença[0] + '<br><br>' + '''<input type="hidden" name="copiar_id" id="''' + str(i) + '''" value="''' + sentença[0].replace('/BOLD','').replace('@BOLD','').replace('@YELLOW/', '').replace('@PURPLE/', '').replace('@BLUE/', '').replace('@RED/', '').replace('@CYAN/', '').replace('/FONT', '') + '''">''' + caixa + '<!--br><br><input type="checkbox" style="margin-left:0px" id="check1_'+str(i)+'" >' + combinação.split('-')[0] + ' <input type="checkbox" id="check2_'+str(i)+'" >' + combinação.split('-')[1] + ' - Comentários: <input type="text" id="comment'+str(i)+'" name="maior" -->')
						html.append('''<br><input type="button" id="botao1''' + combinação + str(i) + '''" style="margin-left:0px" value="Mostrar GOLDEN" onClick="ativa1('sentence1''' + combinação + str(i) + '''', 'botao1''' + combinação + str(i) + '''')" > <input type="button" id="botao2''' + combinação + str(i) + '''" value="Mostrar PREVISTO" onClick="ativa2('sentence2''' + combinação + str(i) + '''', 'botao2''' + combinação + str(i) + '''')">''' + pais)
						html.append("<div id='sentence1" + combinação + str(i) + "' style='display:none'><b><br>GOLDEN:</b>")
						html.append("<pre>" + sentença[2].replace('<','&lt;').replace('>','&gt;').replace("&lt;b&gt;", "<b>").replace("&lt;/b&gt;", "</b>") + "</pre></div><div id='sentence2" + combinação + str(i) + "' style='display:none'><br><b>PREVISTO:</b>")
						html.append("<pre>" + sentença[3].replace('<','&lt;').replace('>','&gt;').replace("&lt;b&gt;", "<b>").replace("&lt;/b&gt;", "</b>") + '</pre></div></div>')

				html = "<br>".join(html).replace('\n','<br>') + '''<br><!--input type="button" class="btn-gradient orange" onclick="enviar('1')" id="salvar_btn" value="Gerar link para a versão atual" style="margin-left:0px"--> <input id="link_edit1" type="text" style="display:none"> <div id="gerado1" style="display:none"><b>Link gerado!</b></div><br><h3><a href="../''' + output + '''.html">Voltar</a></h3></div></body></form></html>

<script>
function escapeRegExp(string) {
	return string.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&').replace('&amp;', '.'); // $& means the whole matched string
}
String.prototype.rsplit = function(sep, maxsplit) {
	var split = this.split(sep);
	return maxsplit ? [ split.slice(0, -maxsplit).join(sep) ].concat(split.slice(-maxsplit)) : split;
}
function copiar_frases(){
	document.getElementById("link_edit2").value = "";
	document.getElementById("link_edit2").style.display = "inline";
	
	var sentids, i, negritos;
	sentids = document.getElementsByName("copiar_id");
	negritos = document.getElementsByName("negrito");
	for (i = 0; i < sentids.length; i++) {
		document.getElementById("link_edit2").value = document.getElementById("link_edit2").value + "^" + sentids[i].value + "$(.*\\\\n)*.*\\\\t" + negritos[i].value + "\\\\t|";
	}
	document.getElementById("link_edit2").value = document.getElementById("link_edit2").value.rsplit('|',1)[0];
}
function carregar_version(){
window.location = window.location.href.split("?")[0] + "?" + document.getElementById("carregar_edit").value.split("?")[1]
}
function ativa1(nome, botao){
var div = document.getElementById(nome)
if (div.style.display == 'none') {
document.getElementById(botao).value='Esconder GOLDEN'
div.style.display = 'block'
} else {
div.style.display = 'none'
document.getElementById(botao).value='Mostrar GOLDEN'
}
}
function ativa2(nome, botao){
var div = document.getElementById(nome)
if (div.style.display == 'none') {
document.getElementById(botao).value='Esconder PREVISTO'
div.style.display = 'block'
} else {
div.style.display = 'none'
document.getElementById(botao).value='Mostrar PREVISTO'
}
}
function gerado_false(id) {
document.getElementById("gerado"+id).style.display = "none"
}
'''
				script_onload = ['function carregar() {','let url_href = window.location.href','let url = new URL(url_href)']
				for item in carregamento_comment:
						script_onload.append('document.getElementById("'+item+'").value = url.searchParams.get("'+item+'")')
				for item in carregamento_check:
						script_onload.append('if (url.searchParams.get("'+item+'") == "true") { document.getElementById("'+item+'").checked = url.searchParams.get("'+item+'") }')
				script_onload.append('}')

				link = '?'
				script_enviar = ['''
function enviar(id) {
document.getElementById("gerado"+id).style.display = "inline"
setTimeout("gerado_false("+id+")", 1000)
document.getElementById("link_edit"+id).style.display = "inline"''']

				link = '?'
				for item in carregamento_comment:
						link += item + '=" + document.getElementById("' + item + '").value.replace(/\?/g, "~").replace(/\&/g, "~").replace(/\//g,"~") + "&'
				for item in carregamento_check:
						link += item + '=" + document.getElementById("' + item + '").checked + "&'

				script_enviar.append('document.getElementById("link_edit"+id).value = window.location.href.split("?")[0] + "' + link + '"')
				script_enviar.append('}')


				html += "\n".join(script_onload) + "\n".join(script_enviar) + '\n</script>'

				open(output + '_html/' + combinação + '.html', 'w', encoding=codificação).write(html)
Ejemplo n.º 4
0
def validate(conllu,
             sent_id=None,
             errorList="validar_UD.txt",
             noMissingToken=False):

    errorDictionary = {}

    if isinstance(conllu, str):
        corpus = estrutura_ud.Corpus(recursivo=True, sent_id=sent_id)
        corpus.load(conllu)
    else:
        corpus = conllu

    for sentence in corpus.sentences.values():
        if not sentence.text.endswith(sentence.tokens[-1].word):
            if not '1 - Sentença não termina com o último token' in errorDictionary:
                errorDictionary[
                    '1 - Sentença não termina com o último token'] = []
            errorDictionary[
                '1 - Sentença não termina com o último token'].append({
                    "sentence":
                    "",
                    "sent_id":
                    sentence.sent_id,
                    "t":
                    sentence.map_token_id["1"],
                    "attribute":
                    "id",
                })

        temRoot = False
        tem2Root = False
        for token in sentence.tokens:
            if token.deprel == "root" and not temRoot:
                temRoot = True
            elif token.deprel == "root" and temRoot:
                tem2Root = True
        if tem2Root:
            if not '1 - Tem 2 root' in errorDictionary:
                errorDictionary['1 - Tem 2 root'] = []
            errorDictionary['1 - Tem 2 root'].append({
                "sentence":
                sentence,
                "sent_id":
                sentence.sent_id,
                "t":
                sentence.map_token_id["1"],
                "attribute":
                "id",
            })
        if not temRoot:
            if not '1 - Não tem root' in errorDictionary:
                errorDictionary['1 - Não tem root'] = []
            errorDictionary['1 - Não tem root'].append({
                "sentence":
                sentence,
                "sent_id":
                sentence.sent_id,
                "t":
                sentence.map_token_id["1"],
                "attribute":
                "id",
            })

    if not noMissingToken:
        missingToken = re.findall(r"\n\n(?!#|$).*", corpus.to_str())
        if missingToken:
            if not '1 - Há tokens faltando no corpus' in errorDictionary:
                errorDictionary['1 - Há tokens faltando no corpus'] = []
            for missing in missingToken:
                errorDictionary['1 - Há tokens faltando no corpus'].append({
                    "sentence":
                    "",
                    "sent_id":
                    "<pre>" + missing + "</pre>",
                })

    with open(errorList) as f:
        errorListFile = f.read().splitlines()
        errorList = []
        [errorList.append(x) for x in errorListFile]

    for error in errorList:
        if error and error[0] != "#":
            if "erro: " in error:
                comment = error.split("erro: ")[1]
                comment = comment.strip()
                coluna = error.split(
                    "|", 1)[0] if "|" in error.split("erro: ")[0] else ""
                continue

            parameters = error.strip()
            for sentString in interrogar_UD.main(corpus,
                                                 5,
                                                 parameters,
                                                 0,
                                                 sent_id,
                                                 separate=True)['output']:
                if not comment in errorDictionary:
                    errorDictionary[comment] = []
                sentence = estrutura_ud.Sentence(recursivo=True)
                sentence.build(fromInterrogarToHtml(sentString['resultado']))
                tokenT = 0
                for t, token in enumerate(sentence.tokens):
                    if "<b>" in token.to_str():
                        tokenT = t
                        break

                errorDictionary[comment].append({
                    "t": tokenT,
                    "sentence": sentence,
                    "attribute": coluna,
                })

    return errorDictionary
Ejemplo n.º 5
0
def main(arquivoUD,
         criterio,
         parametros,
         limit=0,
         sent_id="",
         fastSearch=False):
    parametros = parametros.strip()

    #Lê o arquivo UD
    if criterio in [1, 2, 3, 4]:
        import estrutura_dados
        import estrutura_ud
        qualquercoisa = estrutura_dados.LerUD(arquivoUD)

    if criterio in [5]:
        import estrutura_ud
        if isinstance(arquivoUD, str):
            with open(arquivoUD, "r") as f:
                if "head_token" in parametros or "next_token" in parametros or "previous_token" in parametros:
                    #qtd = len(parametros.split("head_token")) -1 + len(parametros.split("previous_token")) -1 + len(parametros.split("next_token")) -1
                    corpus = estrutura_ud.Corpus(recursivo=True,
                                                 sent_id=sent_id)
                else:
                    corpus = estrutura_ud.Corpus(recursivo=False,
                                                 sent_id=sent_id)
                start = time.time()
                corpus.build(f.read())
                sys.stderr.write("\ncorpus.build: " + str(time.time() - start))
        else:
            corpus = arquivoUD

    #Cria a lista que vai ser enviada seja ao terminal ou ao HTML
    output = list()
    casos = 0

    #Regex
    tabela = ['@YELLOW/', '@PURPLE/', '@BLUE/', '@RED/', '@CYAN/']

    if criterio == 1:
        for a, sentence in enumerate(qualquercoisa):
            if limit and len(output) == limit:
                break
            sentence2 = sentence
            for b, linha in enumerate(sentence):
                linha2 = linha
                if isinstance(linha2, list):
                    sentence2[b] = "\t".join(sentence2[b])
            sentence2 = "\n".join(sentence2)
            regex = re.search(parametros,
                              sentence2,
                              flags=re.IGNORECASE | re.MULTILINE)
            if regex:
                casos += len(
                    re.findall(parametros,
                               sentence2,
                               flags=re.IGNORECASE | re.MULTILINE))
                cores = len(regex.groups())
                new_sentence = re.sub('(' + parametros + ')',
                                      r'<b>\1</b>',
                                      sentence2,
                                      flags=re.IGNORECASE | re.MULTILINE)
                tokens = list()
                header = '!@#'
                for linha in new_sentence.splitlines():
                    if '# text = ' in linha:
                        header = linha
                    if 'b>' in linha and '\t' in linha:
                        tokens.append(
                            linha.split('\t')[1].replace('<b>', '').replace(
                                '</b>', ''))
                header2 = header
                for token in tokens:
                    header2 = re.sub(r'\b' + re.escape(token) + r'\b',
                                     '<b>' + token + '</b>', header2)
                for i in range(cores):
                    if regex[i + 1] != None and i < len(tabela):
                        token = regex[i + 1]
                        if '\t' in regex[i + 1]:
                            token = regex[i + 1].split('\t')[1]
                            header2 = re.sub(r'\b' + re.escape(token) + r'\b',
                                             tabela[i] + token + '/FONT',
                                             header2)
                new_sentence = new_sentence.replace(header, header2)
                output.append(new_sentence.splitlines())

    #If critério 2
    if criterio == 2:

        #Variáveis
        y = parametros.split('#')[0].strip()
        z = int(parametros.split('#')[1])
        k = [x.strip() for x in parametros.split('#')[2].split('|')]
        w = int(parametros.split('#')[3])
        for sentence in qualquercoisa:
            achei = 'nãoachei'
            descarta = False
            for i, linha in enumerate(sentence):
                if isinstance(linha, list):
                    #print(linha)
                    if y == linha[z - 1]:
                        achei = linha[0]
                        token = linha[1]
                        sentence[i] = '<b>' + '\t'.join(sentence[i]) + '</b>'
                        sentence[i] = sentence[i].split('\t')
                        #break
            if achei != 'nãoachei':
                for i, linha in enumerate(sentence):
                    if '# text' in linha:
                        sentence[i] = re.sub(r'\b' + re.escape(token) + r'\b',
                                             '<b>' + token + '</b>',
                                             sentence[i])

            if achei != 'nãoachei':
                for linha in sentence:
                    if isinstance(linha, list):
                        for k_subitem in k:
                            if achei == linha[6] and k_subitem == linha[z - 1]:
                                descarta = True
                if descarta == False:
                    output.append(sentence)
                    casos += 1

    #Regex Independentes
    if criterio == 3:
        regras = [x.strip() for x in parametros.split('::')]

        for a, sentence in enumerate(qualquercoisa):
            sentence2 = sentence
            for b, linha in enumerate(sentence):
                linha2 = linha
                if isinstance(linha2, list):
                    sentence2[b] = "\t".join(sentence2[b])
            sentence2 = "\n".join(sentence2)
            descarta = False
            for regranum, regra in enumerate(regras):
                if regra[0] == '!':
                    regex = re.search(regra[1:],
                                      sentence2,
                                      flags=re.IGNORECASE | re.MULTILINE)
                    casos += len(
                        re.findall(regra[1:], sentence2, flags=re.I | re.M))
                else:
                    regex = re.search(regra,
                                      sentence2,
                                      flags=re.IGNORECASE | re.MULTILINE)
                    casos += len(
                        re.findall(regra, sentence2, flags=re.I | re.M))
                if (regra[0] == '!' and regex) or (regra[0] != '!'
                                                   and not regex):
                    descarta = True
                    break
                sentence2 = re.sub('(' + regra + ')',
                                   tabela[regranum] + r'<b>\1</b>/FONT',
                                   sentence2,
                                   flags=re.IGNORECASE | re.MULTILINE)
            if not descarta:
                tokens = list()
                header = '!@#'
                for linha in sentence2.splitlines():
                    if '# text = ' in linha:
                        header = linha
                    if 'b>' in linha and '\t' in linha:
                        if '@' in linha:
                            tokens.append((linha.split('\t')[1].replace(
                                '<b>', '').replace('</b>', '').replace(
                                    '@' + linha.split('@')[1].split('/')[0] +
                                    '/', ''), '@' +
                                           linha.split('@')[1].split('/')[0] +
                                           '/'))
                            lastcolor = '@' + linha.split('@')[1].split(
                                '/')[0] + '/'
                        else:
                            tokens.append((linha.split('\t')[1].replace(
                                '<b>', '').replace('</b>', ''), lastcolor))
                header2 = header
                for token in tokens:
                    header2 = re.sub(r'\b' + re.escape(token[0]) + r'\b',
                                     token[1] + '<b>' + token[0] + '</b>/FONT',
                                     header2)
                sentence2 = sentence2.replace(header, header2)
                output.append(sentence2.splitlines())

    #pais e filhos
    if criterio == 4:
        filho = parametros.split('::')[0].strip()
        pai = parametros.split('::')[1].strip()

        negativo_filho = False
        negativo_pai = False
        if filho[0] == '!':
            negativo_filho = True
            filho = ''.join(filho[1:])
        if pai[0] == '!':
            negativo_pai = True
            pai = ''.join(pai[1:])

        for a, sentenca in enumerate(qualquercoisa):
            acheifilho = 'não'
            acheipai = 'não'
            descarta = False
            for b, linha in enumerate(sentenca):
                if isinstance(linha, list):
                    if re.search(filho,
                                 '\t'.join(linha),
                                 flags=re.IGNORECASE | re.MULTILINE):
                        acheifilho = (linha, b)
                if isinstance(linha, list):
                    if re.search(pai,
                                 '\t'.join(linha),
                                 flags=re.IGNORECASE | re.MULTILINE):
                        acheipai = (linha, b)

                if not negativo_filho and not negativo_pai and acheipai != 'não' and acheifilho != 'não' and acheipai[
                        0][0] == acheifilho[0][6]:
                    for c, linha in enumerate(sentenca):
                        if '# text' in linha:
                            qualquercoisa[a][c] = re.sub(
                                r'\b' + re.escape(acheipai[0][1]) + r'\b',
                                '<b>@BLUE/' + acheipai[0][1] + '/FONT</b>',
                                qualquercoisa[a][c],
                                flags=re.IGNORECASE | re.MULTILINE)
                            qualquercoisa[a][c] = re.sub(
                                r'\b' + re.escape(acheifilho[0][1]) + r'\b',
                                '<b>@RED/' + acheifilho[0][1] + '/FONT</b>',
                                qualquercoisa[a][c],
                                flags=re.IGNORECASE | re.MULTILINE)
                            break
                    qualquercoisa[a][acheipai[1]] = (
                        '<b>@BLUE/' +
                        '\t'.join(qualquercoisa[a][acheipai[1]]) +
                        '/FONT</b>').split('\t')
                    qualquercoisa[a][acheifilho[1]] = (
                        '<b>@RED/' +
                        '\t'.join(qualquercoisa[a][acheifilho[1]]) +
                        '/FONT</b>').split('\t')
                    output.append(qualquercoisa[a])
                    break

                elif negativo_filho and acheipai != 'não' and acheifilho != 'não' and acheipai[
                        0][0] == acheifilho[0][6]:
                    descarta = True
                    break

                elif negativo_pai and acheifilho != 'não' and acheipai != 'não' and acheipai[
                        0][0] == acheifilho[0][6]:
                    descarta = True
                    break

            if negativo_filho and acheipai != 'não' and acheifilho != 'não' and not descarta:
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheipai[0][1]) + r'\b',
                            '<b>@BLUE/' + acheipai[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheipai[1]] = (
                    '<b>@BLUE/' + '\t'.join(qualquercoisa[a][acheipai[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

            elif negativo_pai and acheipai != 'não' and acheifilho != 'não' and not descarta:
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheifilho[0][1]) + r'\b',
                            '<b>@BLUE/' + acheifilho[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheifilho[1]] = (
                    '<b>@BLUE/' + '\t'.join(qualquercoisa[a][acheifilho[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

            elif negativo_filho and acheipai != 'não' and acheifilho == 'não':
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheipai[0][1]) + r'\b',
                            '<b>@BLUE/' + acheipai[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheipai[1]] = (
                    '<b>@BLUE/' + '\t'.join(qualquercoisa[a][acheipai[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

            elif negativo_pai and acheifilho != 'não' and acheipai == 'não':
                for c, linha in enumerate(sentenca):
                    if '# text' in linha:
                        qualquercoisa[a][c] = re.sub(
                            r'\b' + re.escape(acheifilho[0][1]) + r'\b',
                            '<b>@RED/' + acheifilho[0][1] + '/FONT</b>',
                            qualquercoisa[a][c],
                            flags=re.IGNORECASE | re.MULTILINE)
                        break
                qualquercoisa[a][acheifilho[1]] = (
                    '<b>@RED/' + '\t'.join(qualquercoisa[a][acheifilho[1]]) +
                    '/FONT</b>').split('\t')
                output.append(qualquercoisa[a])

    #Python
    start = time.time()
    if criterio == 5:
        pesquisa = parametros
        casos = 0

        pesquisa = pesquisa.replace(" = ", " == ")
        pesquisa = pesquisa.replace(" @", " ")
        if pesquisa[0] == "@": pesquisa = pesquisa[1:]
        pesquisa = pesquisa.replace("  ", " ").strip()
        pesquisa = pesquisa.replace(" == ", " == token.")
        pesquisa = pesquisa.replace(" === ", " === token.")
        pesquisa = pesquisa.replace(" != ", " != token.")
        pesquisa = pesquisa.replace(" !== ", " !== token.")
        pesquisa = pesquisa.replace(" > ", " > token.")
        pesquisa = pesquisa.replace(" < ", " < token.")
        pesquisa = pesquisa.replace(" >= ", " >= token.")
        pesquisa = pesquisa.replace(" <= ", " <= token.")
        pesquisa = "token." + pesquisa
        pesquisa = pesquisa.replace(" and ", " and token.")
        pesquisa = pesquisa.replace(" or ", " or token.")
        pesquisa = pesquisa.replace(" in ", " in token.")
        pesquisa = pesquisa.replace('token."', '"')
        pesquisa = pesquisa.replace('token.[', '[')
        pesquisa = pesquisa.replace('token.(', '(')

        pesquisa = pesquisa.replace('token.not', 'not')
        pesquisa = pesquisa.replace('token.token.', 'token.')
        pesquisa = re.sub(r'token\.([1234567890])', r'\1', pesquisa)

        pesquisa = re.sub(
            r'(\S+)\s==\s(\".*?\")',
            r'any( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("|") )',
            pesquisa)
        pesquisa = re.sub(
            r'(\S+)\s===\s(\".*?\")',
            r'all( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("|") )',
            pesquisa)
        pesquisa = re.sub(
            r'(\S+)\s!=\s(\".*?\")',
            r'not any( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("|") )',
            pesquisa)
        pesquisa = re.sub(
            r'(\S+)\s!==\s(\".*?\")',
            r'not all( re.search( r"^" + r\2 + r"$", x ) for x in \1.split("|") )',
            pesquisa)
        pesquisa = pesquisa.strip()

        if (".id" in pesquisa or ".dephead" in pesquisa) and (
                not "int(" in pesquisa) and ("<" in pesquisa
                                             or ">" in pesquisa):
            pesquisa = re.sub(r"(\b\S+\.(id|dephead)\b)", r"int(\1)", pesquisa)

        identificador = "token"

        if parametros[0] == "@":
            parametros = parametros[1:]

        arroba = parametros.split(
            " ")[0] if not ' @' in parametros else parametros.rsplit(
                " @", 1)[1].replace(
                    "int(", "").split(")")[0].split(" ")[0].replace("(", "")
        arroba = "token." + arroba
        arroba = arroba.replace("token.token", "token")
        arroba = arroba.rsplit(".", 1)[0]
        #if " in " in arroba: arroba = arroba.split(" in ")[1]

        #with open("expressao_busca.txt", "w") as f:
        #f.write(f"parametro: {parametros}\npesquisa: {pesquisa}\narroba: {arroba}")

        agilizar = re.findall(r'"([^"]*)"', parametros)
        #print(agilizar)
        #agilizado = [x for x in corpus.sentences.values() if all(re.search(y, x.to_str()) for y in agilizar)]
        #agilizado = corpus.sentences.values()
        agilizado = filter(
            lambda x: all(re.search(y, x.to_str()) for y in agilizar),
            corpus.sentences.values())
        #print(agilizado)

        for sentence in agilizado:
            if limit and limit == len(output):
                break
            condition = "global sim; global sentence2; sim = 0; sentence2 = copy.copy(sentence); sentence2.print = sentence2.tokens_to_str()"

            condition += '''
for ''' + identificador + ''' in sentence.tokens:
	try:
		if not "-" in '''+identificador+'''.id and (''' + pesquisa + ''') :
			sentence2.metadados['text'] = re.sub(r'\\b(' + re.escape('''+ identificador +'''.word) + r')\\b', r"@RED/\\1/FONT", sentence2.metadados['text'], flags=re.IGNORECASE|re.MULTILINE)
			sentence2.print = sentence2.print.replace('''+ identificador +'''.to_str(), "@RED/" + '''+ identificador +'''.to_str() + "/FONT")
	'''#try por causa de não ter um next_token no fim de sentença, por ex.
            if identificador + ".head_token" in pesquisa:
                condition += '''
			sentence2.metadados['text'] = re.sub(r'\\b(' + re.escape(''' + identificador + '''.head_token.word) + r')\\b', r"@BLUE/\\1/FONT", sentence2.metadados['text'], flags=re.IGNORECASE|re.MULTILINE)
			sentence2.print = sentence2.print.replace(''' + identificador + '''.head_token.to_str(), "@BLUE/" + ''' + identificador + '''.head_token.to_str() + "/FONT")'''

            condition += '''
			sentence2.metadados['text'] = re.sub(r'\\b(' + re.escape(''' + arroba + '''.word) + r')\\b', r"<b>\\1</b>", sentence2.metadados['text'], flags=re.IGNORECASE|re.MULTILINE)
			final = sentence2.metadados_to_str() + "\\n" + sentence2.print
			final = final.splitlines()
			arroba = ''' + arroba + '''.id
			for l, linha in enumerate(final):
				if linha.split("\\t")[0] == arroba or ("/" in linha.split("\\t")[0] and linha.split("\\t")[0].split("/")[1] == arroba):
					final[l] = "<b>" + final[l] + "</b>"
			final = "\\n".join(final)'''

            exec(condition + '''
			output.append(final)
	except Exception as e:
		print(e)
		pass''')
        sys.stderr.write("\ncritério 5: " + str(time.time() - start))
    #Transforma o output em lista de sentenças (sem splitlines e sem split no \t)
    if criterio not in [5]:
        for a, sentence in enumerate(output):
            for b, linha in enumerate(sentence):
                if isinstance(linha, list):
                    sentence[b] = "\t".join(sentence[b])
            output[a] = "\n".join(sentence)

    start = time.time()
    for i, final in enumerate(output):
        if not fastSearch:
            anotado = estrutura_ud.Sentence(recursivo=False)
            estruturado = estrutura_ud.Sentence(recursivo=False)
            anotado.build(
                cgi.escape(
                    final.replace('<b>', '@BOLD').replace(
                        '</b>', '/BOLD').replace(
                            '<font color=' + tabelaf['yellow'] + '>',
                            '@YELLOW/').replace(
                                '<font color=' + tabelaf['red'] + '>',
                                '@RED/').replace(
                                    '<font color=' + tabelaf['cyan'] + '>',
                                    '@CYAN/').replace(
                                        '<font color=' + tabelaf['blue'] + '>',
                                        '@BLUE/').replace(
                                            '<font color=' +
                                            tabelaf['purple'] + '>',
                                            '@PURPLE/').replace(
                                                '</font>', '/FONT')))
            estruturado.build(
                web.unescape(final).replace('<b>', '@BOLD').replace(
                    '</b>', '/BOLD').replace(
                        '<font color=' + tabelaf['yellow'] + '>',
                        '@YELLOW/').replace(
                            '<font color=' + tabelaf['red'] + '>',
                            '@RED/').replace(
                                '<font color=' + tabelaf['cyan'] + '">',
                                '@CYAN/').replace(
                                    '<font color=' + tabelaf['blue'] + '>',
                                    '@BLUE/').
                replace('<font color=' + tabelaf['purple'] + '>',
                        '@PURPLE/').replace('</font>', '/FONT').replace(
                            '@BOLD', '').replace('/BOLD', '').replace(
                                '@YELLOW/', '').replace('@RED/', '').replace(
                                    '@CYAN/',
                                    '').replace('@BLUE/',
                                                '').replace('@PURPLE/',
                                                            '').replace(
                                                                '/FONT', ''))
        else:
            anotado = ""
            estruturado = ""
        output[i] = {
            'resultado': final,
            'resultadoAnotado': anotado,
            'resultadoEstruturado': estruturado,
        }
    #sys.stderr.write("\nbuscaDicionarios: " + str(time.time() - start))

    return {'output': output, 'casos': casos}
Ejemplo n.º 6
0
def splitSentence(conllu, sent_id, sameSentenceId, newSentenceId, sameText, newText, token_id, conllu_completo="", form=False):

    if form:
        if not os.path.isfile("../cgi-bin/tokenization.json"):
            tokenization = {}
            with open("../cgi-bin/tokenization.json", "w") as f:
                json.dump(tokenization, f)

        with open("../cgi-bin/tokenization.json") as f:
            tokenization = json.load(f)

    if not isinstance(conllu, estrutura_ud.Corpus):
        corpus = estrutura_ud.Corpus(recursivo=False, any_of_keywords=[re.escape("# sent_id = " + sent_id + "\n"), re.escape("# sent_id = " + mergeSentencesId + "\n")])
        corpus.load(conllu if not conllu_completo else conllu_completo)
    else:
        corpus = conllu

    new_sentence = estrutura_ud.Sentence(recursivo=True)
    new_sentence.build(corpus.sentences[sent_id].to_str())

    new_sentence.sent_id = newSentenceId
    new_sentence.metadados['sent_id'] = newSentenceId

    new_token = False
    new_sentence_tokens = []
    old_sentence_tokens = []
    removed_tokens = 0
    for token in corpus.sentences[sent_id].tokens:
        if new_token:
            new_sentence_tokens.append(token)
        else:
            old_sentence_tokens.append(token)
        if not '-' in token.id and not new_token:
            removed_tokens += 1
        if token.id == token_id:
            new_token = True
        
    new_sentence.tokens = new_sentence_tokens
    corpus.sentences[sent_id].tokens = old_sentence_tokens
    corpus.sentences[sent_id].metadados['text'] = sameText
    corpus.sentences[sent_id].text = sameText
    corpus.sentences[new_sentence.sent_id] = new_sentence
    corpus.sentences[new_sentence.sent_id].refresh_map_token_id()
    corpus.sentences[new_sentence.sent_id].metadados['text'] = newText
    corpus.sentences[new_sentence.sent_id].text = newText
    corpus.sent_id = sameSentenceId
    corpus.sentences[sameSentenceId] = corpus.sentences.pop(sent_id)
    corpus.sentences[sameSentenceId].metadados['sent_id'] = sameSentenceId
    corpus.sentences[sameSentenceId].sent_id = sameSentenceId

    for t, token in enumerate(corpus.sentences[new_sentence.sent_id].tokens):
        token.id = str(int(token.id)-removed_tokens) if not '-' in token.id else str(int(token.id.split("-")[0])-removed_tokens) + "-" + str(int(token.id.split("-")[1])-removed_tokens)
        if token.dephead not in ["_", "0"]:
            token.dephead = str(int(token.dephead)-removed_tokens)
            if int(token.dephead) < 0:
                token.dephead = "0"

    if form:
        with open("../cgi-bin/tokenization.json", "w") as f:
            json.dump(tokenization, f)
        corpus.save(conllu + "_tokenization" if not conllu_completo else conllu_completo + "_tokenization")
        os.remove(conllu if not conllu_completo else conllu_completo)
        os.rename(conllu + "_tokenization" if not conllu_completo else conllu_completo + "_tokenization", conllu if not conllu_completo else conllu_completo)
        return new_sentence.sent_id
    else:
        return corpus
Ejemplo n.º 7
0
def renderSentences(script=""):

    conllu = form['conllu'].value
    corpus = conllu
    caminhoCompletoConllu = './interrogar-ud/conllu/' + conllu
    caminhoCompletoHtml = form['html'].value

    parametros = form['parametros'].value.split(" ", 1)[1]
    criterio = int(form['parametros'].value.split(" ", 1)[0])

    if "script" in form:
        script = form['script'].value

    startPoint = int(form['indexSentences'].value)
    filtradoPrevious = int(form['filtrado'].value) if 'filtrado' in form else 0
    nomePesquisa = form['nomePesquisa'].value

    filtros = []
    filtrar_filtros = ""
    pagina_filtros = ""
    if nomePesquisa not in fastSearch:
        pagina_html = caminhoCompletoHtml.rsplit("/", 1)[1].rsplit(".", 1)[0]
        if os.path.isfile("./cgi-bin/filtros.json"):
            with open("./cgi-bin/filtros.json") as f:
                filtros_json = json.load(f)
            filtrar_filtros = "<h4 class='translateHtml'>Filtros já aplicados:</h4>" if pagina_html in filtros_json and filtros_json[
                pagina_html]['filtros'] else ""
            if pagina_html in filtros_json:
                filtros = [
                    x for nome in filtros_json[pagina_html]['filtros'] for x in
                    filtros_json[pagina_html]['filtros'][nome]['sentences']
                ]
                for pagina in [[
                        x,
                        len(filtros_json[pagina_html]['filtros'][x]
                            ['sentences'])
                ] for x in filtros_json[pagina_html]['filtros']]:
                    filtrar_filtros += f'<li><a style="cursor:pointer;" class="translateTitle" title="Clique para adicionar ao mesmo filtro" onclick="$(\'#nome_pesquisa,#nome_pesquisa_sel\').val($(this).children(nome).text());"><span id="nome">{pagina[0]}</a> ({pagina[1]})</li>'
                    pagina_filtros += f'<li><a style="cursor:pointer;" target="_blank" href=\'../../cgi-bin/filtrar.py?action=view&html={pagina_html}&filtro=' + encodeUrl(
                        pagina[0]) + f'\'>{pagina[0]} ({pagina[1]})</li>'
            else:
                filtros = []

    if os.path.isfile('./cgi-bin/json/' +
                      slugify(conllu + "_" + parametros + ".json")):
        with open(
                "./cgi-bin/json/" +
                slugify(conllu + "_" + parametros + ".json"), "r") as f:
            resultadosBusca = json.load(f)
    else:
        if not script:
            resultadosBusca = interrogar_UD.main(caminhoCompletoConllu,
                                                 criterio, parametros)
        else:
            shutil.copy("./cgi-bin/scripts/" + script,
                        './cgi-bin/queryScript.py')
            with open("./cgi-bin/queryScript.py", 'r') as f:
                scriptFile = f.read().replace("<!--corpus-->",
                                              caminhoCompletoConllu)
            with open("./cgi-bin/queryScript.py", "w") as f:
                f.write(scriptFile)
            import queryScript
            resultadosBusca = queryScript.getResultadosBusca()

    sent_id_list = []
    if 'sent_id_list' in form and form['sent_id_list'].value:
        sent_id_list = [
            re.sub(r'<.*?>', '',
                   re.findall(r'# sent_id = (.*?)\n', x['resultado'])[0])
            for x in resultadosBusca['output']
        ]
        sent_id_list = [x for x in sent_id_list if x not in filtros]

    numeroOcorrencias = len(resultadosBusca['output']) - len(filtros)
    #numeroOcorrenciasMenosFiltro = numeroOcorrencias - len(filtros)
    if numeroOcorrencias > startPoint + 21 and numeroOcorrencias >= 1:
        finalPoint = startPoint + 20
        noMore = False
    else:
        finalPoint = len(
            resultadosBusca['output']) - len(filtros) + len(filtros)
        noMore = True

    arquivoHtml = ""
    resultados = []
    quantos = 0
    filtrado = int(form['filtrado'].value)
    for ocorrencia in resultadosBusca['output'][startPoint:]:
        anotado = estrutura_ud.Sentence(recursivo=False)
        estruturado = estrutura_ud.Sentence(recursivo=False)
        anotado.build(
            web.escape(ocorrencia['resultado'].replace('<b>', '@BOLD').replace(
                '</b>', '/BOLD').replace(
                    '<font color=' + tabela['yellow'] + '>',
                    '@YELLOW/').replace(
                        '<font color=' + tabela['red'] + '>', '@RED/').replace(
                            '<font color=' + tabela['cyan'] + '>',
                            '@CYAN/').replace(
                                '<font color=' + tabela['blue'] + '>',
                                '@BLUE/').replace(
                                    '<font color=' + tabela['purple'] + '>',
                                    '@PURPLE/').replace('</font>', '/FONT')))
        estruturado.build(
            web.unescape(ocorrencia['resultado']).replace(
                '<b>', '@BOLD').replace('</b>', '/BOLD').replace(
                    '<font color=' + tabela['yellow'] + '>',
                    '@YELLOW/').replace(
                        '<font color=' + tabela['red'] + '>', '@RED/').replace(
                            '<font color=' + tabela['cyan'] + '">',
                            '@CYAN/').replace(
                                '<font color=' + tabela['blue'] + '>',
                                '@BLUE/').replace(
                                    '<font color=' + tabela['purple'] + '>',
                                    '@PURPLE/').replace(
                                        '</font>', '/FONT').replace(
                                            '@BOLD',
                                            '').replace('/BOLD', '').replace(
                                                '@YELLOW/', '').replace(
                                                    '@RED/', '').replace(
                                                        '@CYAN/', '').replace(
                                                            '@BLUE/',
                                                            '').replace(
                                                                '@PURPLE/',
                                                                '').replace(
                                                                    '/FONT',
                                                                    ''))

        if not estruturado.sent_id in filtros and not estruturado.text in filtros:
            resultados.append({'anotado': anotado, 'estruturado': estruturado})
            quantos += 1
        else:
            quantos += 1
            filtrado += 1
            if finalPoint + 1 < len(resultadosBusca['output']):
                finalPoint += 1

        if quantos == finalPoint - startPoint:
            break

    for i, ocorrencia in enumerate(resultados):
        anotado = ocorrencia['anotado']
        estruturado = ocorrencia['estruturado']

        arquivoHtml += '<div class="container sentence-container">\n'
        arquivoHtml += f'<p>{str(startPoint+i+1-filtradoPrevious)}/{numeroOcorrencias}</p>' + '\n'
        if estruturado.sent_id:
            arquivoHtml += '<p {} class="metadados_sentence">'.format(
                'onmouseover="$(this).css(\'text-decoration\', \'underline\');" onmouseleave="$(this).css(\'text-decoration\', \'none\');"'
                if nomePesquisa not in fastSearch else "")
            arquivoHtml += f'''<input class="cb translateTitle" id=checkbox_{str(startPoint+i+1)} style="margin-left:0px;" title="Selecionar sentença para filtragem" sent_id="{estruturado.sent_id}" type=checkbox>''' if nomePesquisa not in fastSearch else ""
            arquivoHtml += f'''{estruturado.sent_id}</p>''' + '\n'
        arquivoHtml += f"<p><span id=text_{str(startPoint+i+1)}>{(anotado.metadados['clean_text'] if 'clean_text' in anotado.metadados else anotado.text).replace('/BOLD', '</b>').replace('@BOLD', '<b>').replace('@YELLOW/', '<font color=' + tabela['yellow'] + '>').replace('@PURPLE/', '<font color=' + tabela['purple'] + '>').replace('@BLUE/', '<font color=' + tabela['blue'] + '>').replace('@RED/', '<font color=' + tabela['red'] + '>').replace('@CYAN/', '<font color=' + tabela['cyan'] + '>').replace('/FONT', '</font>')}</span></p>" + '\n'
        if ((estruturado.sent_id and
             ('-' in estruturado.sent_id
              or re.search(r'^\d+$', estruturado.sent_id)))
                or estruturado.id) and estruturado.text:
            arquivoHtml += f"<p class='toolbar' style='display:none;'><button class='translateHtml sentence-control' id=contexto_{str(startPoint+i+1)} onclick=\"contexto('{estruturado.sent_id}', '{estruturado.id}', '{corpus}')\" style=\"margin-left:0px\">Mostrar contexto</button> <button class='translateHtml anotacao sentence-control' id=mostrar_{str(startPoint+i+1)} onclick=\"mostrar('div_{str(startPoint+i+1)}', 'mostrar_{str(startPoint+i+1)}')\" style=\"margin-left:0px\">Mostrar anotação</button> <button class='translateHtml opt sentence-control' id=opt_{str(startPoint+i+1)} onclick=\"mostraropt('optdiv_{str(startPoint+i+1)}', 'opt_{str(startPoint+i+1)}')\" style=\"margin-left:0px\">Mostrar opções</button> <button class=\"abrirInquerito translateHtml sentence-control\" onclick='inquerito(\"form_{str(startPoint+i+1)}\");'>Abrir inquérito</button></p>" + "\n"
        else:
            arquivoHtml += f"<p class='toolbar' style='display:none;'><button id=mostrar_{str(startPoint+i+1)} class=\"translateHtml anotacao sentence-control\" onclick=\"mostrar('div_{str(startPoint+i+1)}', 'mostrar_{str(startPoint+i+1)}')\" style=\"margin-left:0px\">Mostrar anotação</button> <button id=opt_{str(startPoint+i+1)} class=\"translateHtml sentence-control opt\" onclick=\"mostraropt('optdiv_{str(startPoint+i+1)}', 'opt_{str(startPoint+i+1)}')\" style=\"margin-left:0px\">Mostrar opções</button> <button class='translateHtml abrirInquerito sentence-control' onclick='inquerito(\"form_{str(startPoint+i+1)}\")'>Abrir inquérito</button></p>" + '\n'
        arquivoHtml += f"<span style=\"display:none; padding-left:20px;\" id=\"optdiv_{str(startPoint+i+1)}\">"
        arquivoHtml += f"<form action=\"../../cgi-bin/inquerito.py?conllu={conllu}\" target=\"_blank\" method=POST id=form_{str(startPoint+i+1)}><input type=hidden name=sentid value=\"{estruturado.sent_id}\"><input type=hidden name=occ value=\"{numeroOcorrencias}\"><input type=hidden name=textheader value=\"{estruturado.sent_id}\"><input type=hidden name=nome_interrogatorio value=\"{web.escape(nomePesquisa)}\"><input type=hidden name=link_interrogatorio value=\"{caminhoCompletoHtml}\"><input type=hidden name=text value=\"{estruturado.text}\">"
        if "@BOLD" in anotado.to_str():
            arquivoHtml += f"<input type=hidden name=tokenId value=\"" + ",".join(
                [
                    functions.cleanEstruturaUD(x.id)
                    for x in anotado.tokens if '@BOLD' in x.to_str()
                ]) + "\">"
        arquivoHtml += "</form><br>"
        if nomePesquisa not in fastSearch:
            arquivoHtml += f"<a style=\"cursor:pointer\" onclick='selectAbove({str(startPoint+i+1)})' class='translateHtml'>Selecionar todas as frases acima</a><br>"
        if nomePesquisa not in fastSearch:
            arquivoHtml += f"<!--a style=\"cursor:pointer\" onclick='filtraragora(\"{str(startPoint+i+1)}\")'>Separar sentença</a-->"
        #arquivoHtml += '<br>'
        if nomePesquisa in fastSearch:
            arquivoHtml += "<span class='translateHtml'>Salve a busca para liberar mais opções</span>"
        arquivoHtml += f"<form action=\"../../cgi-bin/udpipe.py?conllu={conllu}\" target=\"_blank\" method=POST id=udpipe_{str(startPoint+i+1)}><input type=hidden name=textheader value=\"{estruturado.text}\"></form><!--a style=\"cursor:pointer\" onclick='anotarudpipe(\"udpipe_{str(startPoint+i+1)}\")' class='translateHtml'>Anotar frase com o UDPipe</a!-->"
        arquivoHtml += ''
        arquivoHtml += f"<form action=\"../../cgi-bin/draw_tree.py?conllu={conllu}\" target=\"_blank\" method=POST id=tree_{str(startPoint+i+1)}><input type=hidden name=sent_id value=\"{estruturado.sent_id}\"><input type=hidden name=text value=\"{estruturado.text}\"></form><!--a style=\"cursor:pointer\" onclick='drawtree(\"tree_{str(startPoint+i+1)}\")' class='translateHtml'>Visualizar árvore de dependências</a-->"
        arquivoHtml += '</p></span>\n'
        arquivoHtml += f"<pre id=div_{str(startPoint+i+1)} style=\"display:none\">{anotado.to_str().replace('/BOLD', '</b>').replace('@BOLD', '<b>').replace('@YELLOW/', '<font color=' + tabela['yellow'] + '>').replace('@PURPLE/', '<font color=' + tabela['purple'] + '>').replace('@BLUE/', '<font color=' + tabela['blue'] + '>').replace('@RED/', '<font color=' + tabela['red'] + '>').replace('@CYAN/', '<font color=' + tabela['cyan'] + '>').replace('/FONT', '</font>')}</pre>" + '\n'
        arquivoHtml += '</div>\n'

    print(json.JSONEncoder().encode({
        'success': True,
        'html': arquivoHtml,
        'noMore': noMore,
        'indexSentences': finalPoint,
        'filtrado': filtrado,
        'filtrar_filtros': filtrar_filtros,
        'pagina_filtros': pagina_filtros,
        'filtros': len(filtros),
        'sent_id_list': "|".join(sent_id_list),
        'sent_id_count': str(len(sent_id_list))
    }))