Пример #1
0
 def carregar_arq_controle(self):
     try:
         with open('arquivos/data/lsa/arq_controle_lsa.json', 'r', encoding='utf8') as json_file:
             self.arquivo_controle = json.load(json_file)
         terminal.Mensagem('arquivo_controle_lsa carregado com sucesso!', 'ok')
     except Exception as identifier:
         terminal.Mensagem('Erro %s ao carregar o arquivo.'%(identifier), 'e')
Пример #2
0
    def Run(self):
        resposta = ''
        self.Carregar_atualizacao()
        if self.arq_controle == None:
            self.Inicializar_arq_controle()
        else:
            terminal.Mensagem(
                'Arquivos Atualizados em %s às %s:\nTotal de Tweets: %i\nTotal de Vocábulos: %i\nDeseja atualizar o Bag Of Words?[S/N]'
                % (self.arq_controle['atualizacao_data'],
                   self.arq_controle['atualizacao_hora'],
                   self.arq_controle['total_tweets'],
                   self.arq_controle['total_vocabulos']), 'w')
            resposta = str(input()).upper()

        if resposta == 'S':
            self.tweets_limpos.clear()
            self.__BOW()
        elif resposta == 'N':
            terminal.Mensagem(
                'Deseja gerar WordCloud com o arquivo existente?[S/N]', 'w')
            option = str(input()).upper()
            if option == 'S':
                self.__WordCloud()
            else:
                return False
        else:
            terminal.Mensagem('Resposta Inválida! Informe [S/N].', 'w')
            return False
Пример #3
0
 def feature_tweet_(lista, id_inicial):
     try:
         self.carregar_feature_tweet()
     except Exception as identifier:
         terminal.Mensagem('Erro %s Não foi possível acessar o arquivo.'%(identifier), 'e')
     try:
         contador = 0
         pos = id_inicial -1
         for tweet in lista:
             contador += 1
             pos += 1
             _palavras = len(tweet.split())
             _id = pos
             _term = Verifica_Termos_Especiais_(tweet)
             _aux = Identificar_Topico_Tweet(_id)
             _topico = _aux[0]
             _word_dicionary = Verifica_Dicionario(tweet)
             _freq = _aux[1]
             self.feature_tweet.update({_id:{'words': _palavras, 'special_terms': _term, 'words_dicionary': _word_dicionary, 'topic': _topico, 'score': _freq}})  
             terminal.printProgressBar(contador,len(lista),length=50)
         
         self.Atualiza_arquivo_controle('has_lsa_tweet', True)
         self.gravar_feature_tweet('w')
         self.Atualiza_arquivo_controle('has_feature_tweet', True)
     except Exception as identifier:
         fim = time.time()
         duracao = fim - inicio
         terminal.Mensagem('Erro %s identificado na posição %i.'%(identifier, pos), 'e')
         terminal.Mensagem('Programa finalizado!\tDuração: %.3f seg'%(duracao),'ok')
Пример #4
0
 def on_error(self, status):
     if status == 420:
         # Retorna Falso quando on_data exceder o limite da API
         print(status)
         terminal.Mensagem('TOTAL TWEETS: %s' % self.contador, 'w')
         return False
     print(status)
     terminal.Mensagem('TOTAL TWEETS: %s' % self.contador, 'w')
Пример #5
0
    def Run(self):
        def Executar_tfidf():
            aux = []
            aux = self.Carregar_PKL(
                'arquivos/data/bow/lista_tweets_limpos.pkl')
            self.tweets = self.__agregarlistas(aux)
            self.tfidf.Gerar_Dados(self.tweets)

            self.Atualiza_arq_JSON('has_vetor_tfidf', True)
            self.Atualiza_arq_JSON('vetor_tfidf_nome',
                                   'arquivos/data/tf-idf/vetor_tfidf.pkl')
            self.Atualiza_arq_JSON('has_feature_names', True)
            self.Atualiza_arq_JSON('feature_names_nome',
                                   'arquivos/data/tf-idf/feature_names.txt')

            fim = time.time()
            data = time.strftime("%d-%m-%Y", time.localtime(fim))
            hora = time.strftime("%H:%M:%S", time.localtime(fim))
            self.Atualiza_arq_JSON('atualizacao_data', data)
            self.Atualiza_arq_JSON('atualizacao_hora', hora)

        resposta = ''
        res = ''
        self.Carregar_atualizacao()
        if self.arq_controle == None:
            self.Inicializar_arq_controle()
        elif not self.arq_controle['has_vetor_tfidf'] and not self.arq_controle[
                'has_feature_names']:
            Executar_tfidf()
        else:
            terminal.Mensagem(
                'Arquivos Atualizados em %s às %s:\nDeseja atualizar o TF-IDF?[S/N]'
                % (self.arq_controle['atualizacao_data'],
                   self.arq_controle['atualizacao_hora']), 'w')
            resposta = str(input()).upper()
        if resposta == 'S':
            Executar_tfidf()
        elif resposta == 'N':
            terminal.Mensagem('Deseja Visualizar o arquivo existente?[S/N]',
                              'w')
            res = str(input()).upper()
            if res == 'S':
                if self.arq_controle['has_vetor_tfidf'] and self.arq_controle[
                        'has_feature_names']:
                    row_label = [
                        'Tweet %i' % i for i in range(len(self.tweets))
                    ]
                    col_label = self.feature_names
                    self.tfidf.Gerar_tabela(45, 5, 8, row_label, col_label,
                                            self.vetor_tfidf)
                else:
                    Executar_tfidf()
            else:
                return False
        else:
            return False
Пример #6
0
    def Carregar_atualizacao(self):
        try:
            self.arq_controle = self.Carregar_arq_JSON(self.nome_arq_controle)
            terminal.Mensagem('arq_controle carregado com Sucesso!', 'ok')
        except Exception as identifier:
            terminal.Mensagem(str(identifier), 'e')

        try:
            self.vocabulario = self.arq.Carregar_Arquivo_UTF8(
                self.arq_controle['lista_vocabulario_nome'])
            terminal.Mensagem('vocabulario carregado com Sucesso!', 'ok')
        except Exception as identifier:
            terminal.Mensagem(str(identifier), 'e')

        try:
            self.freq_vocabulario = self.Carregar_arq_JSON(
                self.arq_controle['dict_freq_vocabulario_nome'])
            terminal.Mensagem('freq_vocabulario carregado com Sucesso!', 'ok')
        except Exception as identifier:
            terminal.Mensagem(str(identifier), 'e')

        try:
            self.tweets_limpos = self.Carregar_PKL(
                self.arq_controle['lista_tweets_limpos_nome'])
            terminal.Mensagem('lista_tweets_limpos carregado com Sucesso!',
                              'ok')
        except Exception as identifier:
            terminal.Mensagem(str(identifier), 'e')
Пример #7
0
 def Carregar_feature_topicos(self):
     try:
         with open( 'arquivos/data/lsa/feature_topicos.json', 'r', encoding='utf8') as json_file:
             dados = json.load(json_file)
             return dados
     except Exception as identifier:
         terminal.Mensagem('Erro [%s]: Não foi possível carregar o arquivo.'%identifier, 'e')
Пример #8
0
    def Localizacoes(self):
        terminal.Mensagem('Iniciando em Análise Localização', 'd')
        lista = self._Selecionar_localizacao_tweets_banco_(
            self._ids_tweets_localizacao)
        point = []
        cidades_validadas = []
        # Verificação do user_local
        for i in lista:
            if i != None:
                point.append(i)

        teste = self.Validacao_cidades(point)

        for item in teste:
            self.EhCidade(item)
            # cidades_validadas.append(item)
        self.arq.Gravar_Arquivo(
            self.cidades_validadas,
            'arquivos/data/localizacao/arquivo_localizacao.txt')
        print('Arquivo \'arquivo_localizacao.txt\' tamanho: ',
              len(self.cidades_validadas))
        count, encontrou, cids = 0, False, []
        cids.append(self.cidades_validadas[0])
        for item in self.cidades_validadas:
            for cidade in cids:
                if cidade == item:
                    encontrou = True
            if not encontrou:
                cids.append(item)
            encontrou = False
        print('%i Cidades Brasileiras encontradas.' % len(cids))
        cids.sort()
        print(cids)
Пример #9
0
 def Carregar_PKL(self, nome_arquivo):
     try:
         Input = open(nome_arquivo, 'rb')
         dados = load(Input)
         Input.close()
         return dados
     except Exception as identifier:
         terminal.Mensagem('Erro [%s]: Não foi possível carregar o arquivo.'%identifier, 'e')
Пример #10
0
    def __init__(self, tempo_segundos):
        terminal.Mensagem('Iniciando em Extrator', 'd')
        inicio = time.time()

        futuro = (inicio + tempo_segundos)
        t = threading.Timer(3.0, self.Run(futuro))
        t.setName('Thread-Extractor')
        t.start()
        if True:
            terminal.Mensagem('Cancelando a Thread....', 'w')
            t.cancel()
            fim = time.time()
            duracao = fim - inicio
            strfim = time.strftime("\nFim: %A, %d %b %Y %H:%M:%S +0000",
                                   time.localtime(fim))
            strinicio = time.strftime("\nInício: %A, %d %b %Y %H:%M:%S +0000",
                                      time.localtime(inicio))
            texto = '%s Cancelada!%s%s\nDuração: %s' % (str(
                t.getName()), strinicio, strfim, duracao)
            terminal.Mensagem(texto, 'ok')
Пример #11
0
def Continuar():
    Sinal()
    terminal.Mensagem('Deseja continuar? (S/N) ', 's')
    term = input()
    term = term.upper()
    if term != 'S':
        clear()
        return False
    else:
        clear()
        return True
Пример #12
0
 def Run(self):
     terminal.Mensagem('Iniciando em Seletor', 'd')
     print('Informe o tipo de Consulta: C - COMPLETA | A - ATUALIZAÇÃO: \t',
           end='')
     tipo = str(input())
     print('Informe a Data INICIAL para a Consulta [YYYY-MM-DD]: \t',
           end='')
     data_inicio = str(input())
     print('Informe a Data FINAL para a Consulta [YYYY-MM-DD]: \t', end='')
     data_final = str(input())
     self.select(tipo, data_inicio, data_final)
Пример #13
0
    def Gravar_Arquivo(self, lista, nome_arquivo):
        """
        Cria um manipulador de arquivo no modo escrita ('a') e salva um arquivo com o nome escolhido no parametro com os dados da lista.
        Este modo de escrita verifica se há o arquivo no diretório: 
        Se verdadeiro sobregrava, se falso cria o arquivo.

        :parametro lista: dados em formato de lista para gravar no arquivo.
        :parametro nome_arquivo: nome do arquivo de a ser gravado / escrito.
        """
        try:
            arq = open(nome_arquivo, 'a', encoding="utf-8")
            for linha in lista:
                if type(linha) == tuple:
                    arq.write(str(linha[0]) + ',' + str(linha[1]) + ';\n')
                else:
                    arq.write(linha + '\n')
            arq.close()
            terminal.Mensagem('Arquivo Gravado com Sucesso!', 'ok')
        except Exception as identifier:
            terminal.Mensagem('Erro (' + str(identifier) + ') ao tentar gravar o Arquivo!','e')
Пример #14
0
 def Carregar_Matriz(self, nome_matriz='matriz_termos ou matriz_topicos'):
     nome = nome_matriz.lower()
     if nome == 'matriz_termos' or nome == None:
         nome_arquivo = 'arquivos/data/lsa/matriz_termos.pkl'
     elif nome == 'matriz_topicos':
         nome_arquivo = 'arquivos/data/lsa/matriz_topicos.pkl'
     try:
         matriz_T = self.Carregar_PKL(nome_arquivo)
         return matriz_T
     except Exception as identifier:
         terminal.Mensagem('Erro [%s]: Não foi possível carregar o arquivo \'%s\'.'%(identifier, nome_arquivo), 'e')
Пример #15
0
    def on_data(self, data):
        all_data = json.loads(data)
        if ((json.dumps(all_data).startswith('{"limit":') == False)):
            self.contador += 1
            id_tweet = all_data["id"]

            source = all_data["source"]

            user_id = all_data["user"]["id"]
            username = all_data["user"]["screen_name"]
            user_url = all_data["user"]["url"]
            user_description = all_data["user"]["description"]
            user_local = all_data["user"]["location"]

            date_tweet = all_data["created_at"]

            if (all_data["geo"] != None):
                geo = json.dumps(all_data["geo"])
            elif (all_data["geo"] == None):
                geo = all_data["geo"]

            if (all_data["coordinates"] != None):
                coordinates = json.dumps(all_data["coordinates"])
            elif (all_data["coordinates"] == None):
                coordinates = all_data["coordinates"]

            tweet = all_data["text"]

            if (all_data["place"] != None):
                place = json.dumps(all_data["place"])
            elif (all_data["place"] == None):
                place = all_data["place"]

            c.execute(
                "INSERT INTO tweet_tb (id_tweet, source, user_id, username, user_url, user_description, user_local, date_tweet, geo, coordinates, tweet, place) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                (id_tweet, source, user_id, username, user_url,
                 user_description, user_local, date_tweet, geo, coordinates,
                 tweet, place))

            conn.commit()

            print(username, tweet)
            if time.time() > self.futuro:
                terminal.Mensagem('TOTAL TWEETS: %s' % self.contador, 'w')
                return False
            else:
                return True
        elif (json.dumps(all_data).startswith('{"limit":')):
            print('\n' + '*' * 30 + ' Dict Json ' + '*' * 30 + '\n')
Пример #16
0
 def select(self, tipo, data_inicio, data_final):
     '''
     parametro tipo de consulta: informe C - COMPLETA | A - ATUALIZAÇÃO
     '''
     keywords = self.arq.Carregar_Arquivo_UTF8(
         'arquivos/stem_termos.txt'
     )  #palavras chave vulnerabilidade e risco sociais
     lista_aux = self.arq.Carregar_Arquivo('arquivos/ids_selecionados.txt')
     id_final = lista_aux[-1]
     if (len(lista_aux) == 0):
         tipo = 'C'
     if tipo.upper() == 'C':
         quant_tweet = self.consulta.consulta_base(keywords, 'COMPLETA')
     else:
         quant_tweet = self.consulta.consulta_base(
             keywords,
             query=
             " AND (id > %s) AND (datetime BETWEEN '%s 00:00:00.000000' AND '%s 23:59:59.999999')"
             % (id_final, data_inicio, data_final))
     terminal.Mensagem('%i Tweets Selecionados com Sucesso!' % quant_tweet,
                       'ok')
Пример #17
0
    def Carregar_atualizacao(self):
        try:
            self.arq_controle = self.Carregar_arq_JSON(self.nome_arq_controle)
            terminal.Mensagem('arq_controle carregado com Sucesso!', 'ok')
        except Exception as identifier:
            terminal.Mensagem(str(identifier), 'e')

        try:
            self.vetor_tfidf = self.Carregar_PKL(
                self.arq_controle['vetor_tfidf_nome'])
            terminal.Mensagem('vetor_tfidf carregado com Sucesso!', 'ok')
        except Exception as identifier:
            terminal.Mensagem(str(identifier), 'e')

        try:
            self.feature_names = self.arq.Carregar_Arquivo_UTF8(
                self.arq_controle['feature_names_nome'])
            terminal.Mensagem('feature_names carregado com Sucesso!', 'ok')
        except Exception as identifier:
            terminal.Mensagem(str(identifier), 'e')
Пример #18
0
    opcao = terminal.TelaInicial(title, lista)
    opcao = opcao.upper()
    if opcao == 'AUTO':
        clear()
        Run()
        if not Continuar():
            opcao = 'S'
    elif opcao == '1':
        clear()
        Extrair()
        if not Continuar():
            opcao = 'S'
    elif opcao == '2':
        clear()
        Selecionar()
        if not Continuar():
            opcao = 'S'
    elif opcao == '3':
        clear()
        Analisar()
        if not Continuar():
            opcao = 'S'
    elif opcao == '4':
        clear()
        Avaliar()
        if not Continuar():
            opcao = 'S'

terminal.Mensagem(' . . . Desconectando o VISOR . . . ', 'd')
time.sleep(4)
clear()
Пример #19
0
    def _LSA_(self):
        inicio = time.time()
        terminal.Mensagem('Iniciando em Análise Semântica Latente', 'd')
        print('0 - Análise Semântica Latente Completa\n1 - Cálculo de Relevância dos tweets\n2 - Seleção de tweets com Maior Relevância\n\t> Informe o que deseja fazer: ',end='')
        _tipo_ = str(input())
        if _tipo_ == '0':
            resposta = 'S'
            self.carregar_arq_controle()
            if self.arquivo_controle['atualizacao_data'] != None:
                terminal.Mensagem('Arquivos Atualizados em %s às %s. Deseja atualizar a LSA?[S/N]' %(self.arquivo_controle['atualizacao_data'], self.arquivo_controle['atualizacao_hora']),'w')
                resposta = str(input()).upper()

            if resposta == 'S':
                # DEFINIR STOPWORDS
                stw = []
                stopword = stopwords.words('portuguese')
                outras_palavras = self.arq.Carregar_Arquivo_UTF8('arquivos/data/lsa/limpeza_feature_names.txt')
                [stw.append(s) for s in stopword]
                [stw.append(s) for s in outras_palavras]

                # CARREGAR LISTA DE TERMOS REFERENTES A VULNERABILIDADE E RISCO
                with open('arquivos/data/lsa/termos_especiais.json', 'r', encoding='utf8') as json_file:
                    self.termos_especiais = json.load(json_file)

                pa.Atualiza_Dict_Termos_especiais(True)

                # VETOR TFIDF / BOW
                vetor = TfidfVectorizer(min_df=1,stop_words=stw)
                bag_of_words = vetor.fit_transform(self.body)
                print(bag_of_words.shape)

                
                LISTA_TRUNCADO = [x for x in range(self.TRUNCADO)]

                # DEFINIR COLUNAS E TRUNCAR O VETOR TFIDF / BOW ==> LSA - ANALISE SEMANTICA LATENTE
                svd = TruncatedSVD(n_components=self.TRUNCADO) #Truncar para X colunas
                lsa = svd.fit_transform(bag_of_words)

                def __matriz_topicos__():
                    topicos = pd.DataFrame(lsa, columns = LISTA_TRUNCADO)
                    topicos['body'] = self.body
                    print(topicos[['body', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
                                    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 
                                    34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 
                                    51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 
                                    68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 
                                    85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
                    self.Gravar_PKL(topicos, 'arquivos/data/lsa/matriz_topicos.pkl')
                    self.Atualiza_arquivo_controle('has_matriz_topicos', True)

                # DEFINIÇÃO DOS TOPICOS
                if self.arquivo_controle['has_matriz_topicos']:
                    terminal.Mensagem('Arquivos Atualizados em %s às %s. Deseja atualizar a Matriz de Tópicos?[S/N]' %(self.arquivo_controle['atualizacao_data'], self.arquivo_controle['atualizacao_hora']),'w')
                    resp = str(input()).upper()
                    if resp == 'S':
                        __matriz_topicos__()
                    else:
                        topicos = self.matriz_topicos
                else:
                    __matriz_topicos__()
            
                # DICIONÁRIO DE PALAVRAS - PRODUTO DA LSA
                dicionario = vetor.get_feature_names()
                print('Imprimir dicionário? [S/N] ', end='') 
                if input(str()).upper() == 'S':
                    print(dicionario)
                    print()

                # MATRIZ DE TERMOS - PRODUTO DA LSA
                if not self.arquivo_controle['has_matriz_termos']:
                    matriz = pd.DataFrame(svd.components_, 
                                            index=[LISTA_TRUNCADO],
                                            columns=dicionario).T
                    self.Gravar_PKL(matriz, 'arquivos/data/lsa/matriz_termos.pkl')
                    self.Atualiza_arquivo_controle('has_matriz_termos', True)
                
                print('Imprimir matriz_termos? [S/N] ', end='') 
                if input(str()).upper() == 'S':
                    print(self.Carregar_Matriz('matriz_termos'))
                    print()
                print('Imprimir matriz_topicos? [S/N] ', end='') 
                if input(str()).upper() == 'S':
                    print(self.Carregar_Matriz('matriz_topicos'))
                    print()

                self.last_id_tweet = self.arquivo_controle['last_id_tweet']

                # VETOR AUXILIAR PARA TOPICOS DOS TERMOS
                aux_topic = []
                maior, pos, aux = -1000.0, 0, 0
                for item in self.matriz_termos.values:
                    for j in item:
                        if j > maior:
                            maior = j
                            aux = pos #aux = topico
                        pos += 1
                    aux_topic.append([aux, maior])
                    pos, aux, maior = 0, 0, -1000.0
                    
                def Identificar_Topico(termo):
                    term = termo.lower()
                    achou = False
                    pos = -1
                    for item in dicionario:
                        pos += 1
                        if term == item:
                            achou = True
                            break
                    if achou:
                        return aux_topic[pos]
                    else:
                        return -1

                def Identificar_Topico_Tweet(id_tweet):
                    maior, pos, _top = -1000.0, 0, 0
                    res = []
                    for item in self.matriz_topicos.values[id_tweet]:
                        if type(item) != str:
                            if item > maior:
                                maior = item # média das freq
                                _top = pos #aux = topico
                            pos += 1
                    res.append(_top)
                    res.append(maior)
                    return res

                def Verifica_Dicionario(tweet):
                    count = 0
                    tweet = tweet.split()
                    for tw in tweet:
                        for item in dicionario:
                            if tw == item:
                                count += 1
                    return count

                def Verifica_Termos_Especiais_(tweet):
                    import re
                    caract = [r'\b\"', r'\"\b', r'\b\-', r'\b\'', r'\'\b', r'\“', r'\”', r'\.', r'\.\.\.', 
                            r'\,', r'\?', r'\!', r'\(', r'\)', r'\{', r'\}',r'\[',r'\]', r'\+', r'\*', r'\B\%'
                            r'\b\"+', r'\B\"', r'\"\B', r'\%', r'\\', r'\/', r'\|', r'\<', r'\>', r'\=', 
                            r'\B\-', r'\b\‘', r'\B\‘', r'\b\`', r'\B\`', r'\b\ñ', r'\B\ñ', r'\b\º', r'\B\º', 
                            r'\b\ª', r'\B\ª', r'\b\_', r'\B\_', r'\b\;', r'\B\;', r'\b\^', r'\~', r'\b\è', 
                            r'\_', r'\–', r'\•', r'\#', r'\b\—', r'\B\—', r'\—', r'\°', r'\b\°', r'\B\°',
                            r'\'', r'\B\'', r'\«', r'\b\«', r'\B\«', r'\&', r'\b\&', r'\B\&', r'\¬',
                            r'\b\¬', r'\B\¬', r'\¨', r'\b\¨', r'\B\¨', r'\¢', r'\b\¢', r'\B\¢', r'\£',
                            r'\b\£', r'\B\£' , r'\³', r'\b\³', r'\B\³', r'\³\b', r'\³\B', r'\²', r'\b\²', 
                            r'\B\²', r'\²\b', r'\²\B', r'\¹', r'\b\¹', r'\B\¹', r'\¹\b', r'\¹\B', r'\§', 
                            r'\b\§', r'\B\§', r'\b\·', r'\B\·', r'\·', r'\^', r'\B\^', r'\ö', r'\b\ö', 
                            r'\B\ö', r'\»', r'\b\»', r'\B\»', r'\@', r'\b\@', r'\B\@',  r'\€', r'\b\€', 
                            r'\B\€', r'\÷', r'\b\÷', r'\B\÷',r'\å', r'\b\å', r'\B\å', r'\×', r'\b\×', 
                            r'\B\×', r'\¡', r'\b\¡', r'\B\¡',  r'\¿', r'\b\¿', r'\B\¿', r'\´', r'\b\´',
                            r'\B\´', r'\$', r'\b\$', r'\B\$', r'\¥', r'\b\¥', r'\B\¥', r'\¯', r'\b\¯', 
                            r'\B\¯']
                    
                    espaco2 = re.compile(r'\b\s+')
                    for item in caract:
                            e = re.compile(item)
                            tweet = re.sub(e, ' ', tweet)
                    tweet = re.sub(espaco2, ' ', tweet)
                    
                    count = 0
                    tweet = tweet.split()
                    for word in tweet:
                        inicial = word[0]
                        if self.termos_especiais[inicial] != None:
                            for item in self.termos_especiais[inicial]:
                                if word == item:
                                    count += 1
                    return count

                def feature_tweet_(lista, id_inicial):
                    try:
                        self.carregar_feature_tweet()
                    except Exception as identifier:
                        terminal.Mensagem('Erro %s Não foi possível acessar o arquivo.'%(identifier), 'e')
                    try:
                        contador = 0
                        pos = id_inicial -1
                        for tweet in lista:
                            contador += 1
                            pos += 1
                            _palavras = len(tweet.split())
                            _id = pos
                            _term = Verifica_Termos_Especiais_(tweet)
                            _aux = Identificar_Topico_Tweet(_id)
                            _topico = _aux[0]
                            _word_dicionary = Verifica_Dicionario(tweet)
                            _freq = _aux[1]
                            self.feature_tweet.update({_id:{'words': _palavras, 'special_terms': _term, 'words_dicionary': _word_dicionary, 'topic': _topico, 'score': _freq}})  
                            terminal.printProgressBar(contador,len(lista),length=50)
                        
                        self.Atualiza_arquivo_controle('has_lsa_tweet', True)
                        self.gravar_feature_tweet('w')
                        self.Atualiza_arquivo_controle('has_feature_tweet', True)
                    except Exception as identifier:
                        fim = time.time()
                        duracao = fim - inicio
                        terminal.Mensagem('Erro %s identificado na posição %i.'%(identifier, pos), 'e')
                        terminal.Mensagem('Programa finalizado!\tDuração: %.3f seg'%(duracao),'ok')

                def Gerar_Grafico():
                    topicos = pd.DataFrame(matriz, 
                                            index=['Tweet'],
                                            columns=dicionario).T

                    print(topicos)
                    fig, ax = plt.subplots()
                    top_1 = matriz[0].values
                    top_2 = matriz[1].values

                    ax.scatter(top_1, top_2, alpha=0.3)

                    ax.set_xlabel('Primeiro Topico')
                    ax.set_ylabel('Segundo Topico')
                    ax.axvline(linewidth=0.5)
                    ax.axhline(linewidth=0.5)
                    ax.legend()

                    plt.show()
                
                # Produz Recurso de Tweets
                tamanho = self.last_id_tweet + 15000
                if tamanho > len(self.body):
                    tamanho = len(self.body)

                feature_tweet_(self.body[self.last_id_tweet: tamanho], self.last_id_tweet)
                self.Atualiza_arquivo_controle('last_id_tweet', tamanho)

                # Calcula Relevancia dos Tweets
                if self.arquivo_controle['has_lsa_tweet']:
                    self.Calcular_Relevancia_Tweet()
                else:
                    terminal.Mensagem('lsa_tweet não executado!', 'e')
                # Seleciona Tweets com maior Relevancia
                if self.arquivo_controle['has_calculo_relevancia_tweet']:
                    self.Selecionar_Tweets_Relevancia('positive',0.5)
                else:
                    terminal.Mensagem('calculo_relevancia_tweet não executado!', 'e')
                
                fim = time.time()
                data = time.strftime("%d-%m-%Y", time.localtime(fim))
                hora = time.strftime("%H:%M:%S", time.localtime(fim))
                self.Atualiza_arquivo_controle('atualizacao_data', data)
                self.Atualiza_arquivo_controle('atualizacao_hora', hora)
                duracao = fim - inicio
                terminal.Mensagem('Programa finalizado!\tDuração: %.3f seg'%(duracao),'ok')

            else:
                terminal.Mensagem('Desconectando...','d')
                return False
        
        elif _tipo_ == '1':
            self.Calcular_Relevancia_Tweet()
        elif _tipo_ == '2':
            self.Selecionar_Tweets_Relevancia('positive',0.5)
        else:
            terminal.Mensagem('Desconectando...','d')
            return False
Пример #20
0
    def Selecionar_Tweets_Relevancia(self, relevancia='POSITIVE', maior_score=0.0):
        self.carregar_feature_tweet()
        self.carregar_arq_controle()
        ''' PERGUNTAR SE DESEJA IMPRIMIR MATRIZ TERMOS E TOPICOS E DICIONARIO'''
        print('\tImprimir matriz_termos? [S/N] ', end='') 
        if input(str()).upper() == 'S':
            print(self.Carregar_Matriz('matriz_termos'))
            print()
        print('\tImprimir matriz_topicos? [S/N] ', end='') 
        if input(str()).upper() == 'S':
            print(self.Carregar_Matriz('matriz_topicos'))
            print()

        relevancia = relevancia.upper()
        encontrado = False
        status_relevancia = ['POSITIVE', 'NEGATIVE', 'NEUTRO']

        def __run__():
            score, posicao, termos, topico, palavras, dicio, importancia, tt = [], [], [], [], [], [], [], []
            for key in self.feature_tweet.keys():
                if self.feature_tweet[key]['relevance'] == relevancia and self.feature_tweet[key]['score'] >= maior_score:
                    term = self.feature_tweet[key]['special_terms']
                    dc = self.feature_tweet[key]['words_dicionary']
                    if dc != 0:
                        imp = (term / dc)
                    else:
                        imp = -1
                    score.append(self.feature_tweet[key]['score'])
                    posicao.append(key)
                    termos.append(term)
                    topico.append(self.feature_tweet[key]['topic'])
                    palavras.append(self.feature_tweet[key]['words'])
                    dicio.append(dc)
                    importancia.append(imp)

            print('\t> Tweets com Score maior que %.2f e com Relevancia \'%s\': %i / %i (%.2f)' %(maior_score, relevancia, len(posicao), len(self.feature_tweet), float(len(posicao)/len(self.feature_tweet)*100)) + '%')
            self.Atualiza_arquivo_controle('count_feature_topicos',len(posicao))

            print()
            for item in posicao: # Imprime os Tweets
                tt.append(self.body[int(item)])
            y = zip(posicao, topico, tt)
            
            topic_unique = [topico[0]]
            achou = False
            for t1 in topico:
                achou = False
                for t2 in topic_unique:
                    if t1 == t2:
                        achou = True
                if not achou:
                    topic_unique.append(t1)
            topic_unique.sort()

            topicos_dict, aux, p1 = {}, {}, 0
            for t0 in topic_unique:
                for t3 in topico:
                    if t3 == t0:
                        aux.update({posicao[p1]: self.feature_tweet[str(posicao[p1])]})
                        aux[posicao[p1]]['importancia'] = importancia[p1]
                        aux[posicao[p1]]['tweet'] = tt[p1]
                        topicos_dict.update({t3: aux.copy()})
                    p1 +=1
                aux.clear()
                p1=0

            if not self.arquivo_controle['has_feature_topicos']:
                with open('arquivos/data/lsa/feature_topicos.json', 'w', encoding='utf-8') as json_file:
                    json.dump(topicos_dict, json_file, indent=4, ensure_ascii=False)
                self.arq.Gravar_Arquivo(posicao,'arquivos/data/lsa/_ids_tweets_feature_topicos.txt')
            
            self.Atualiza_arquivo_controle('has_feature_topicos',True)

            print('\tImprimir feature_topicos? [S/N] ', end='')
            if input(str()).upper() == 'S':
                tam =0
                for t4 in topicos_dict.keys():
                    while tam < 10:
                        for t5 in topicos_dict[t4].keys():
                            print('id: {:<8} score: {:<8,.5f} terms: {:<2} topic: {:<2} words: {:<4} words_dicionary: {:<2} importancia: {:<2,.2f}'
                                    .format(t5, topicos_dict[t4][t5]['score'], topicos_dict[t4][t5]['special_terms'], topicos_dict[t4][t5]['topic'], 
                                    topicos_dict[t4][t5]['words'], topicos_dict[t4][t5]['words_dicionary'], topicos_dict[t4][t5]['importancia']))
                            tam +=1

                print('...\t\t...\t\t...\n')
                tam =0
                for t4 in topicos_dict.keys():
                    while tam < 10:
                        for t5 in topicos_dict[t4].keys():
                            print('id: {:<6} Topic: {:<2} Tweet: {:<80}'
                                    .format(t5, topicos_dict[t4][t5]['topic'], topicos_dict[t4][t5]['tweet']))
                            tam +=1
            print('\tImprimir relatorio_status_lsa_tweet? [S/N] ', end='')
            if input(str()).upper() == 'S':
                relt_topicos, tam_topic = [], 0
                for t_u in topic_unique:
                    tam_topic += len(topicos_dict[t_u])
                    relt_topicos.append([t_u, len(topicos_dict[t_u])])
                print('* * * RELATÓRIO DE STATUS LSA FEATURE * * * ')
                for item in range(0,len(relt_topicos),4):
                    if item <=len(relt_topicos)-4:
                        print('Topic: {:<2} Qtde: {:<4} Topic: {:<2} Qtde: {:<4} Topic: {:<2} Qtde: {:<4} Topic: {:<2} Qtde: {:<4}'
                                .format(relt_topicos[item][0], relt_topicos[item][1],
                                relt_topicos[item+1][0], relt_topicos[item+1][1],
                                relt_topicos[item+2][0], relt_topicos[item+2][1],
                                relt_topicos[item+3][0], relt_topicos[item+3][1]))
                    elif item == len(relt_topicos)-1:
                        print('Topic: {:<2} Qtde: {:<4}'.format(relt_topicos[item][0], relt_topicos[item][1]))
                    elif item == len(relt_topicos)-2:
                        print('Topic: {:<2} Qtde: {:<4} Topic: {:<2} Qtde: {:<4}'
                                .format(relt_topicos[item][0], relt_topicos[item][1],
                                relt_topicos[item+1][0], relt_topicos[item+1][1]))
                    else:
                        print('Topic: {:<2} Qtde: {:<4} Topic: {:<2} Qtde: {:<4} Topic: {:<2} Qtde: {:<4}'
                                .format(relt_topicos[item][0], relt_topicos[item][1],
                                relt_topicos[item+1][0], relt_topicos[item+1][1],
                                relt_topicos[item+2][0], relt_topicos[item+2][1]))
                print('\t > Total Tópicos: {:<2} Total Tweets: {:<4}'.format(len(topic_unique), tam_topic))
        
            print('\n\tRealizar Etiquetagem <Treinamento> da Base de Tweets? [S/N] ', end='')
            if input(str()).upper() == 'S':
                pos, fim = 1, False
                for i in topic_unique:
                    if i > self.arquivo_controle['topico_treinamento']:
                        print('\t> Treino da Base topic_num: \"%i\" [%i de %i tópicos]'%(i, pos, len(topic_unique)))
                        fim = self.Verifica_feature_topicos(i)
                        if fim:
                            return False
                    pos += 1
            print('\n\tImprimir Estimativa de Tweets com Vulnerabilidade TRUE? [S/N] ', end='')
            if input(str()).upper() == 'S':
                pa.Levantamento_Score_Vulnerabilidade()
            
            tweets_localizacao()

        def tweets_localizacao():
            dicts, _ids_tweets_localizacao, aux_ids = {}, [], []
            with open( 'arquivos/data/lsa/feature_topicos.json' , 'r', encoding='utf8') as json_file:
                dicts = json.load(json_file)

            for topico in dicts.keys():
                for _id in dicts[topico].keys():
                    if dicts[topico][_id]['vulnerabilidade'] == 1.0:
                        aux_ids.append(int(_id))
            aux_ids.sort()
            for item in aux_ids:
                _ids_tweets_localizacao.append(str(item))

            self.arq.Gravar_Arquivo(_ids_tweets_localizacao, 'arquivos/data/lsa/_ids_tweets_localizacao.txt')
            print('Arquivo _ids_tweets_localizacao.txt tamanho: %i'%len(_ids_tweets_localizacao))


        # __MAIN__
        for item in status_relevancia:
            if relevancia == item:
                encontrado = True
        if encontrado:
            __run__()
        else:
            terminal.Mensagem('Erro ao inserir o dado [RELEVANCE]: \'%s\'' % (relevancia), 'e')
Пример #21
0
 def carregar_feature_tweet(self):
     self.carregar_arq_controle()
     if self.arquivo_controle['has_feature_tweet']:
         with open( 'arquivos/data/lsa/feature_tweet.json' , 'r', encoding='utf8') as json_file:
             self.feature_tweet = json.load(json_file)
             terminal.Mensagem('feature_tweet carregado com sucesso!', 'ok')
Пример #22
0
 def __WordCloud(self):
     try:
         self.wc.Build_Nuvem_Palavras(self.tweets_limpos)
         terminal.Mensagem('WordClound Gerado com Sucesso!', 'ok')
     except Exception as identifier:
         terminal.Mensagem(str(identifier), 'e')
Пример #23
0
    def Seletor_Classificador(self):
        terminal.Mensagem('Iniciando em Avaliação > Classificação', 'd')
        # Variáveis
        base_tweet, vulnerabilidade, twt, loop = [], [], [], 0
        X_train, X_test, y_train, y_test = [], [], [], []
        X_treino_Holdout, X_teste_Holdout, y_treino_Holdout, y_teste_Holdout = [], [], [], []

        # Métodos
        def Seleciona_Base_tweets():
            dicts, teste = {}, {}
            with open('arquivos/data/lsa/feature_topicos.json',
                      'r',
                      encoding='utf8') as json_file:
                dicts = json.load(json_file)

            for topico in dicts.keys():
                for _id in dicts[topico].keys():
                    if dicts[topico][_id]['vulnerabilidade'] != None:
                        teste.update(dicts[topico])

            print('Tamanho  da base: %i' % len(teste))
            words, terms, wdictionary, topic, score, importancia = 0, 0, 0, 0, 0, 0

            for _id in teste.keys():
                if teste[_id]['vulnerabilidade'] != None:
                    words = (teste[_id]['words'])
                    terms = (teste[_id]['special_terms'])
                    wdictionary = (teste[_id]['words_dicionary'])
                    topic = (teste[_id]['topic'])
                    score = (teste[_id]['score'])
                    importancia = (teste[_id]['importancia'])
                    vulnerabilidade.append(teste[_id]['vulnerabilidade'])
                    twt.append([_id, teste[_id]['tweet']])
                    base_tweet.append(
                        [words, terms, wdictionary, topic, score, importancia])
                    # base_tweet.append([words, topic, score, wdictionary]) # teste 1

        Seleciona_Base_tweets()
        ''' Selecao_Amostragem_Holdout(80 - 20) '''
        parte = int(len(base_tweet) * 0.8)
        x1, x2, y1, y2 = [], [], [], []
        [x1.append(item) for item in base_tweet[:parte]]
        [x2.append(item) for item in base_tweet[parte:]]
        [y1.append(item) for item in vulnerabilidade[:parte]]
        [y2.append(item) for item in vulnerabilidade[parte:]]

        X_treino_Holdout = np.array(x1)
        X_teste_Holdout = np.array(x2)
        y_treino_Holdout = np.array(y1)
        y_teste_Holdout = np.array(y2)
        ''' Selecao_Amostragem_Stratified_Cross_Validation (80 - 20)'''
        test_size = 0.2
        train_size = 1.0 - test_size
        sss = StratifiedShuffleSplit(test_size=test_size,
                                     n_splits=12,
                                     random_state=0)
        loop = sss.get_n_splits(X_treino_Holdout, y_treino_Holdout)

        print('Parametros Stratified Cross Validation: ', sss)

        for train_index, test_index in sss.split(X_treino_Holdout,
                                                 y_treino_Holdout):
            X_train.append(X_treino_Holdout[train_index])
            X_test.append(X_treino_Holdout[test_index])
            y_train.append(y_treino_Holdout[train_index])
            y_test.append(y_treino_Holdout[test_index])
        ''' NaiveBayes '''
        clf = GaussianNB()
        predicted_CV, predicted = [], []
        for item in range(loop):
            clf.fit(X_train[item], y_train[item])
            predicted_CV.append(clf.predict(X_test[item]))

        print('>>> Resultado Teste 1 (Stratified Cross-Validation):')
        target_names = ['Não', 'Sim']
        print(
            classification_report(y_test[0],
                                  predicted_CV[0],
                                  target_names=target_names))
        # print(predicted_CV)

        #teste
        predicted = clf.predict(X_teste_Holdout)
        print('>>> Resultados Teste 2 (HOLDOUT):')
        target_names = ['Não', 'Sim']
        print(
            classification_report(y_teste_Holdout,
                                  predicted,
                                  target_names=target_names))

        met = ['HOLDOUT', 'Stratified Cross-Validation']
        tam = [[len(X_treino_Holdout),
                len(X_teste_Holdout)],
               [
                   len(X_treino_Holdout) * train_size,
                   len(X_treino_Holdout) * test_size
               ]]
        pa.Metodos_Amostragem(met, tam)
        ''' Impressão de Resultados '''
        count = parte
        contador = 0
        impressao = 10
        print('\n * * * PREDIÇÃO VULNERABILIDADE EM TWEETS * * * ')
        for item in predicted:
            if (contador < impressao) or (
                    contador >= len(vulnerabilidade[parte:]) - impressao):
                if vulnerabilidade[count] == item:
                    acerto = 'OK'
                else:
                    acerto = 'ERRO'
                print(
                    'id: {:<5} tweet: {:<30}... Vulnerabilidade: {:<2} - Class: {:<2} - {:<5}'
                    .format(twt[count][0], twt[count][1][0:30],
                            vulnerabilidade[count], item, acerto))
            elif contador == impressao:
                print(
                    '    {:<5}        {:<30}                     {:<2}          {:<2}   {:<5}'
                    .format('...', '...', '...', '...', '...'))
            count += 1
            contador += 1
        print(' > > > Tamanho teste: ', len(vulnerabilidade[parte:]))

        print('\n\tMATRIZ DE PREDIÇÃO VULNERABILIDADE EM TWEETS ')
        print(predicted)
        print(' > > > Tamanho teste: ', len(predicted))

        print('\n --- MÉTRICAS ---')
        acuracia = metrics.accuracy_score(vulnerabilidade[parte:], predicted)
        precisao = metrics.precision_score(vulnerabilidade[parte:], predicted)
        recall = metrics.recall_score(vulnerabilidade[parte:], predicted)
        v_measure = metrics.v_measure_score(vulnerabilidade[parte:], predicted)
        f1 = metrics.f1_score(vulnerabilidade[parte:], predicted)
        print(
            'acuracia:  {:<12.8f} precisao: {:<12.8f} recall: {:<12.8f}\nv_measure: {:<12.8f} f1_score: {:<12.8f}\n'
            .format(acuracia, precisao, recall, v_measure, f1))

        confusao = metrics.confusion_matrix(vulnerabilidade[parte:], predicted)
        print(confusao)
        ''' Plot Matriz de Confusão '''
        np.set_printoptions(precision=2)

        # Plot non-normalized confusion matrix
        titles_options = [("Matriz de Confusão", None),
                          ("Matriz de Confusão normalizada", 'true')]
        for title, normalize in titles_options:
            disp = plot_confusion_matrix(clf,
                                         X_teste_Holdout,
                                         y_teste_Holdout,
                                         display_labels=target_names,
                                         cmap=plt.cm.Blues,
                                         normalize=normalize)
            disp.ax_.set_title(title)

            print(title)
            print(disp.confusion_matrix)

        plt.show()