def parse(self): # CRIA DIRETORIO E ARQUIVO DE SAIDA timeStart = time.time() self.outPutCsvFilePath = Path( str(self.file.parent) + '\\' + str(self.file.stem)) self.outPutFileName = Path( str(self.outPutCsvFilePath) + '\\' + str(self.file.stem) + '.csv') logger.debug('Iniciando arquivo no diretorio de saida ' + str(self.outPutCsvFilePath)) try: self.parseDocument() if not self.outPutCsvFilePath.exists(): self.outPutCsvFilePath.mkdir() self.saveAndGetHash(self.final_df) # SETTANDO O PARSER RESULT self.result.setParserHealth(True) self.result.setElapsedTime(timeStart) self.result.setStatus(ParserStatus.PARSED) #-----------------------------------# logger.debug('Arquivo parseado com sucesso!!') result = self.result.getParserResult() return result except Exception as e: # ERRO GENERICO self.result.setMessage(str(e)) self.result.setStatus(ParserStatus.ERROR) result = self.result.getParserResult() return result
def __remove_bad_lines(self): logger.debug( 'Entrando no metodo para remocao de possiveis linhas erradas') try: self.df = self.df.replace(to_replace='None', value=pd.np.nan).dropna() except Exception: logger.error('Erro na remocao de linhas')
def checkDocumento(self): try: # CHECK DOCUMENTO SIMPLES SEM CRIAR DATAFRAME fileString = self.file.read_text(self.enc) if 'Unimed Seguros' in fileString: logger.debug('Operadora encontrada: Unimed Seguros - DCM') return True except Exception as e: return False
def checkDocumento(self): try: # CHECK DOCUMENTO SIMPLES SEM CRIAR DATAFRAME # Pode ser feito tambem com dataframe fileString = self.file.read_text(self.enc) # Condição para verificar presença de identificador único do doc dessa operadora if '' in fileString: logger.debug('Operadora encontrada: <ic_operadora> - <tipo documento>') return True except Exception as e: return False
def _set_header(self): logger.debug('Atribuindo cabecalho ao dataframe') self.df.columns = [ 'Conta', 'Associado', 'Servico', 'Realizacao', 'Qtde', 'Val_Informado', 'Val_Glosado', 'Val_Aprovado', 'Glosa', 'Observacao' ] self.__remove_bad_lines() self.df['Numero_Credenciado'] = self.header_df.iloc[0, 0].split(": ")[1] self.df['Total_Informado'] = self.header_df.iloc[1, 0].split(": ")[1] self.df['Total_Glosado'] = self.header_df.iloc[2, 0].split(": ")[1] self.df['Total_Aprovado'] = self.header_df.iloc[3, 0].split(": ")[1] self.df['NR'] = self.header_df.iloc[4, 0].split(";")[0].split(": ")[1] self.df['Fatura'] = self.header_df.iloc[4, 0].split(";")[1].split(": ")[1] logger.debug('Cabecalho atribuido ao dataframe com sucesso')
def run(self,file): try: parser = ParserFactory(file).getConstructor() if parser is not None: result = parser.parse() logger.debug(str(result)) return result except EmptyDocumentException as e: logger.exception(e) result = ParserResult(config=ParserConfig(file=file),message=e.args[0],status=ParserStatus.EMPTY_DOCUMENT.name).getParserResult() logger.error(str(result)) return result except TipoDocumentoNaoIdentificadoException as e: logger.exception(e) result = ParserResult(config=ParserConfig(file=file),message=e.args[0],status=ParserStatus.ERROR_IDENTIFYING_OPERATOR.name).getParserResult() logger.error(str(result)) return result
import os import random import string import sys import time from io import StringIO from multiprocessing.pool import ThreadPool from pathlib import Path from src.parserCSV.api import ParserAPI from src.utils import ParserConfig, ParserResult import pandas as pd from src.loggerConfig import logger # # PEGANDO ARQUIVOS DE UM DIRETORIO TESTE # filepath = Path('C:\\Users\\ianin\\Desktop\\IC\\PARSER\\testeParserCSV') filesToParse = [] # Preenchendo lista de filesToParse for file in filepath.iterdir(): if file.is_file() and file.suffix in ['.csv', '.txt', '.tsv']: logger.debug('NOVO ARQUIVO PARA SER PARSEADO: ' + file.name) filesToParse.append(file.absolute()) if len(filesToParse) > 0: parserResults = ParserAPI(filesToParse).runAll() else: logger.error('NÃO HÁ ARQUIVOS A SEREM PARSEADOS!!') parserResults = ParserResult(config=None) logger.fatal