corretti problemi di pylint

c'e' da renderlo meno rompicoglioni
This commit is contained in:
2020-10-12 16:00:20 +02:00
parent e195ea5532
commit 16ab928383
6 changed files with 1248 additions and 1167 deletions

29
SPEx/poetry.lock generated
View File

@@ -34,6 +34,18 @@ docs = ["sphinx", "sphinx-rtd-theme", "zope.interface"]
tests = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "zope.interface"] tests = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "zope.interface"]
tests_no_zope = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six"] tests_no_zope = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six"]
[[package]]
category = "dev"
description = "A tool that automatically formats Python code to conform to the PEP 8 style guide"
name = "autopep8"
optional = false
python-versions = "*"
version = "1.5.4"
[package.dependencies]
pycodestyle = ">=2.6.0"
toml = "*"
[[package]] [[package]]
category = "dev" category = "dev"
description = "Cross-platform colored terminal text." description = "Cross-platform colored terminal text."
@@ -119,6 +131,14 @@ optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
version = "1.9.0" version = "1.9.0"
[[package]]
category = "dev"
description = "Python style guide checker"
name = "pycodestyle"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
version = "2.6.0"
[[package]] [[package]]
category = "dev" category = "dev"
description = "python code static checker" description = "python code static checker"
@@ -238,7 +258,7 @@ python-versions = "*"
version = "1.12.1" version = "1.12.1"
[metadata] [metadata]
content-hash = "e35375126d07552fb1e200007cf6bd02991d90c71eb261f21b33919e77395a58" content-hash = "f2c0aacdec9a2b08fb05b279563096aab92c78d4b64ccc312db25de8e74a910f"
lock-version = "1.0" lock-version = "1.0"
python-versions = "^3.8" python-versions = "^3.8"
@@ -255,6 +275,9 @@ attrs = [
{file = "attrs-20.2.0-py2.py3-none-any.whl", hash = "sha256:fce7fc47dfc976152e82d53ff92fa0407700c21acd20886a13777a0d20e655dc"}, {file = "attrs-20.2.0-py2.py3-none-any.whl", hash = "sha256:fce7fc47dfc976152e82d53ff92fa0407700c21acd20886a13777a0d20e655dc"},
{file = "attrs-20.2.0.tar.gz", hash = "sha256:26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594"}, {file = "attrs-20.2.0.tar.gz", hash = "sha256:26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594"},
] ]
autopep8 = [
{file = "autopep8-1.5.4.tar.gz", hash = "sha256:d21d3901cb0da6ebd1e83fc9b0dfbde8b46afc2ede4fe32fbda0c7c6118ca094"},
]
colorama = [ colorama = [
{file = "colorama-0.4.3-py2.py3-none-any.whl", hash = "sha256:7d73d2a99753107a36ac6b455ee49046802e59d9d076ef8e47b61499fa29afff"}, {file = "colorama-0.4.3-py2.py3-none-any.whl", hash = "sha256:7d73d2a99753107a36ac6b455ee49046802e59d9d076ef8e47b61499fa29afff"},
{file = "colorama-0.4.3.tar.gz", hash = "sha256:e96da0d330793e2cb9485e9ddfd918d456036c7149416295932478192f4436a1"}, {file = "colorama-0.4.3.tar.gz", hash = "sha256:e96da0d330793e2cb9485e9ddfd918d456036c7149416295932478192f4436a1"},
@@ -309,6 +332,10 @@ py = [
{file = "py-1.9.0-py2.py3-none-any.whl", hash = "sha256:366389d1db726cd2fcfc79732e75410e5fe4d31db13692115529d34069a043c2"}, {file = "py-1.9.0-py2.py3-none-any.whl", hash = "sha256:366389d1db726cd2fcfc79732e75410e5fe4d31db13692115529d34069a043c2"},
{file = "py-1.9.0.tar.gz", hash = "sha256:9ca6883ce56b4e8da7e79ac18787889fa5206c79dcc67fb065376cd2fe03f342"}, {file = "py-1.9.0.tar.gz", hash = "sha256:9ca6883ce56b4e8da7e79ac18787889fa5206c79dcc67fb065376cd2fe03f342"},
] ]
pycodestyle = [
{file = "pycodestyle-2.6.0-py2.py3-none-any.whl", hash = "sha256:2295e7b2f6b5bd100585ebcb1f616591b652db8a741695b3d8f5d28bdc934367"},
{file = "pycodestyle-2.6.0.tar.gz", hash = "sha256:c58a7d2815e0e8d7972bf1803331fb0152f867bd89adf8a01dfd55085434192e"},
]
pylint = [ pylint = [
{file = "pylint-2.6.0-py3-none-any.whl", hash = "sha256:bfe68f020f8a0fece830a22dd4d5dddb4ecc6137db04face4c3420a46a52239f"}, {file = "pylint-2.6.0-py3-none-any.whl", hash = "sha256:bfe68f020f8a0fece830a22dd4d5dddb4ecc6137db04face4c3420a46a52239f"},
{file = "pylint-2.6.0.tar.gz", hash = "sha256:bb4a908c9dadbc3aac18860550e870f58e1a02c9f2c204fdf5693d73be061210"}, {file = "pylint-2.6.0.tar.gz", hash = "sha256:bb4a908c9dadbc3aac18860550e870f58e1a02c9f2c204fdf5693d73be061210"},

View File

@@ -13,6 +13,7 @@ parse = "*"
[tool.poetry.dev-dependencies] [tool.poetry.dev-dependencies]
pytest = "^5.2" pytest = "^5.2"
pylint = "^2.6.0" pylint = "^2.6.0"
autopep8 = "^1.5.4"
[build-system] [build-system]
requires = ["poetry>=0.12"] requires = ["poetry>=0.12"]

File diff suppressed because it is too large Load Diff

View File

@@ -7,107 +7,105 @@ import json,os,glob,copy
from PyQt5.QtCore import QObject from PyQt5.QtCore import QObject
class bananaCONF(QObject): class bananaCONF(QObject):
''' '''
Carica e Salva file di configurazione per bananaSPLITTER Carica e Salva file di configurazione per bananaSPLITTER
''' '''
def __init__(self, workdir=None, logger=None): def __init__(self, workdir=None, logger=None):
try: try:
QObject.__init__(self) QObject.__init__(self)
self.log = logger self.log = logger
self.fileList = None self.fileList = None
self.workdir = None self.workdir = None
self.inUse = None self.inUse = None
self.settingsList = dict() self.settingsList = dict()
if workdir is not None: if workdir is not None:
self.workdir = workdir self.workdir = workdir
os.chdir(workdir) os.chdir(workdir)
self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd())) self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd()))
else: else:
self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione")) self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione"))
pass pass
except Exception as e: except Exception as e:
print(f"libConfload Exception: {e}") print(f"libConfload Exception: {e}")
def open(self): def open(self):
self.log.info(self.tr("Carico i file di configurazione")) self.log.info(self.tr("Carico i file di configurazione"))
self.fileList = glob.glob(r"*.json") self.fileList = glob.glob(r"*.json")
if len(self.fileList) > 0: if len(self.fileList) > 0:
for f in self.fileList: for f in self.fileList:
try: try:
fp = open(f) fp = open(f)
tf = json.load(fp) tf = json.load(fp)
fName = f.split("\\")[-1] fName = f.split("\\")[-1]
self.settingsList[fName] = copy.deepcopy(tf) self.settingsList[fName] = copy.deepcopy(tf)
self.log.info(self.tr("Caricato correttamente: {}").format(fName)) self.log.info(self.tr("Caricato correttamente: {}").format(fName))
fp.close() fp.close()
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \ self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \
Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno)) Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno))
except IOError as ee: except IOError as ee:
self.log.error(self.tr("Impossibile aprire il file: {}").format(ee)) self.log.error(self.tr("Impossibile aprire il file: {}").format(ee))
except Exception as eee: except Exception as eee:
self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee)) self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee))
else: else:
self.log.error(self.tr("Non ho trovato alcun file di configurazione!")) self.log.error(self.tr("Non ho trovato alcun file di configurazione!"))
pass pass
def reload(self): def reload(self):
self.settingsList = None self.settingsList = None
self.fileList = None self.fileList = None
self.inUse = None self.inUse = None
self.open() self.open()
pass pass
def use(self, toUse): def use(self, toUse):
self.inUse = toUse self.inUse = toUse
return self return self
def save(self, fName=None): def save(self, fName=None):
if fName is None: if fName is None:
fName=self.inUse fName=self.inUse
self.log.info(self.tr("Salvo la configurazione: {}").format(fName)) self.log.info(self.tr("Salvo la configurazione: {}").format(fName))
try: try:
f=open(fName, 'w') f=open(fName, 'w')
json.dump(self.settingsList[self.inUse], f, indent='\t') json.dump(self.settingsList[self.inUse], f, indent='\t')
f.close() f.close()
except IOError as e: except IOError as e:
self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e)) self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e))
except Exception as ei: except Exception as ei:
self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei)) self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei))
pass pass
def getFiles(self): def getFiles(self):
return self.fileList return self.fileList
def getParam(self, *keys): def getParam(self, *keys):
rv = self.settingsList[self.inUse] rv = self.settingsList[self.inUse]
try: try:
for k in keys: for k in keys:
rv = rv[k] rv = rv[k]
return rv return rv
except ValueError as ve: except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False return False
pass pass
def setParam(self, keys=(), val=None): def setParam(self, keys=(), val=None):
sv = self.settingsList[self.inUse] sv = self.settingsList[self.inUse]
try: try:
for k in keys[:-1]: for k in keys[:-1]:
sv = sv[k] sv = sv[k]
sv[keys[-1]] = val sv[keys[-1]] = val
return True return True
except ValueError as ve: except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False return False
pass pass
def dump(self): def dump(self):
return self.settingsList[self.inUse] return self.settingsList[self.inUse]
def loads(self, conf): def loads(self, conf):
jconf = json.loads(conf) jconf = json.loads(conf)
self.settingsList[self.inUse]=jconf self.settingsList[self.inUse]=jconf

View File

@@ -10,92 +10,92 @@ import colorama
from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtCore import QObject, pyqtSignal
class fancyLogger(QObject): class fancyLogger(QObject):
''' '''
Colorizza il logger di python, per un' esperienza stile willy wonka Colorizza il logger di python, per un' esperienza stile willy wonka
''' '''
sendLog = pyqtSignal(str) sendLog = pyqtSignal(str)
def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False): def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False):
QObject.__init__(self) QObject.__init__(self)
try: try:
with open(filepath, 'r') as fp: with open(filepath, 'r') as fp:
settings = json.load(fp) settings = json.load(fp)
fp.close() fp.close()
colorama.init(convert=True) colorama.init(convert=True)
self.LRED = colorama.Fore.LIGHTRED_EX self.LRED = colorama.Fore.LIGHTRED_EX
self.RED = colorama.Fore.RED self.RED = colorama.Fore.RED
self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX
self.YELLOW = colorama.Fore.YELLOW self.YELLOW = colorama.Fore.YELLOW
self.LBLUE = colorama.Fore.LIGHTBLUE_EX self.LBLUE = colorama.Fore.LIGHTBLUE_EX
self.BLUE = colorama.Fore.BLUE self.BLUE = colorama.Fore.BLUE
self.LGREEN = colorama.Fore.LIGHTGREEN_EX self.LGREEN = colorama.Fore.LIGHTGREEN_EX
self.LGREEN = colorama.Fore.GREEN self.LGREEN = colorama.Fore.GREEN
self.WHITE = colorama.Fore.LIGHTWHITE_EX self.WHITE = colorama.Fore.LIGHTWHITE_EX
self.RST = colorama.Style.RESET_ALL self.RST = colorama.Style.RESET_ALL
# Setup Logger # Setup Logger
self.LOGGER = logging.getLogger(name) self.LOGGER = logging.getLogger(name)
self.LOGGER.setLevel(logging.DEBUG) self.LOGGER.setLevel(logging.DEBUG)
self.LOGGER.propagate = False self.LOGGER.propagate = False
FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"])) FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"]))
if fileLog: if fileLog:
# File Logging # File Logging
fh = logging.FileHandler((settings["logFile"])) fh = logging.FileHandler((settings["logFile"]))
fh.setLevel(logging.DEBUG) fh.setLevel(logging.DEBUG)
fh.setFormatter(FORMATTER) fh.setFormatter(FORMATTER)
self.LOGGER.addHandler(fh) self.LOGGER.addHandler(fh)
if consoleLog: if consoleLog:
# Console Logging # Console Logging
cl= logging.StreamHandler(sys.stdout) cl= logging.StreamHandler(sys.stdout)
cl.setLevel(logging.DEBUG) cl.setLevel(logging.DEBUG)
cl.setFormatter(FORMATTER) cl.setFormatter(FORMATTER)
self.LOGGER.addHandler(cl) self.LOGGER.addHandler(cl)
except IOError as e: except IOError as e:
print("Impossibile caricare la configurazione del logger: [{}]".format(e)) print("Impossibile caricare la configurazione del logger: [{}]".format(e))
except Exception as ee: except Exception as ee:
print(f"libFancylogger error: {ee}") print(f"libFancylogger error: {ee}")
pass pass
def debug(self, msg="Undefined Debug"): def debug(self, msg="Undefined Debug"):
print(self.LBLUE, end='') print(self.LBLUE, end='')
self.LOGGER.debug(msg) self.LOGGER.debug(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#03c2fc'>DEBUG | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#03c2fc'>DEBUG | {msg} </br>")
pass pass
def info(self, msg="Undefined Info"): def info(self, msg="Undefined Info"):
print(self.LGREEN, end='') print(self.LGREEN, end='')
self.LOGGER.info(msg) self.LOGGER.info(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#6bfc03'>INFO | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#6bfc03'>INFO | {msg} </br>")
pass pass
def warn(self, msg="Undefined Warning"): def warn(self, msg="Undefined Warning"):
print(self.LYELLOW, end='') print(self.LYELLOW, end='')
self.LOGGER.warning(msg) self.LOGGER.warning(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc9403'>WARNING | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#fc9403'>WARNING | {msg} </br>")
pass pass
def error(self, msg="Undefined Error"): def error(self, msg="Undefined Error"):
print(self.LRED, end='') print(self.LRED, end='')
self.LOGGER.error(msg) self.LOGGER.error(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#ff0000'>ERROR | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#ff0000'>ERROR | {msg} </br>")
pass pass
def critical(self, msg="Undefined Critical"): def critical(self, msg="Undefined Critical"):
print(self.RED, end='') print(self.RED, end='')
self.LOGGER.critical(msg) self.LOGGER.critical(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc03ce'>CRITICAL | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#fc03ce'>CRITICAL | {msg} </br>")
pass pass
def testColors(self): def testColors(self):
self.debug("Test Debug") self.debug("Test Debug")
self.info("Test Info") self.info("Test Info")
self.warn("Test Warning") self.warn("Test Warning")
self.error("Test Error") self.error("Test Error")
self.critical("Test Critical") self.critical("Test Critical")
pass pass

View File

@@ -10,397 +10,395 @@ import time, parse, re, copy, os, json
import traceback import traceback
class bananaSPLITTER(QObject): class bananaSPLITTER(QObject):
sendStatus = pyqtSignal(str)
sendStatus = pyqtSignal(str) def __init__(self, fileParams=None, logger=None):
try:
def __init__(self, fileParams=None, logger=None): QObject.__init__(self)
try: self.fileParams = fileParams
QObject.__init__(self) self.log = logger
self.fileParams = fileParams self.rawFile = None
self.log = logger self.status = "first"
self.rawFile = None self.contentList = list()
self.status = "first" self.bodyCounter=0
self.contentList = list() self.duplicateNumber=0
self.bodyCounter=0 #self.log.debug(f"Configurazione: \n {json.dumps(fileParams, indent=2)}")
self.duplicateNumber=0 if fileParams is not None:
#self.log.debug(f"Configurazione: \n {json.dumps(fileParams, indent=2)}") self.log.debug(self.tr("Sto operando sul file: {}..").format(self.fileParams['name']))
if fileParams is not None: self.paths = self.fileParams['paths']
self.log.debug(self.tr("Sto operando sul file: {}..").format(self.fileParams['name'])) self.docStruct = self.fileParams['docStruct']
self.paths = self.fileParams['paths'] self.settings = self.fileParams['settings']
self.docStruct = self.fileParams['docStruct'] self.fileName = self.fileParams['name']
self.settings = self.fileParams['settings'] self.outPath = self.paths['OUTworkPath']+slugify(self.fileName)+'/'
self.fileName = self.fileParams['name'] self.beginTime = time.time()
self.outPath = self.paths['OUTworkPath']+slugify(self.fileName)+'/' pass
self.beginTime = time.time() else:
pass self.log.critical(self.tr("Non e' stato fornito il nome di alcun file da splittare!"))
else: except Exception as e:
self.log.critical(self.tr("Non e' stato fornito il nome di alcun file da splittare!")) print(f"libSplit error: {e}")
except Exception as e: pass
print(f"libSplit error: {e}")
pass def run(self):
self.log.info(self.tr("Nuovo SPLITTER su file: {}").format(self.fileName))
def run(self): self.sendStatus.emit(self.tr(f"Inizio {self.fileName}"))
self.log.info(self.tr("Nuovo SPLITTER su file: {}").format(self.fileName)) try:
self.sendStatus.emit(self.tr(f"Inizio {self.fileName}")) self.openFile()
try: self.remEmptyLines()
self.openFile() if self.docStruct['fileVersNew']:
self.remEmptyLines() self.newSplitFile()
if self.docStruct['fileVersNew']: else:
self.newSplitFile() self.splitFile()
else:
self.splitFile() if self.settings['removeDuplicates']:
self.log.info(self.tr("Controllo se ci sono dei duplicati.."))
if self.settings['removeDuplicates']: self.removeDuplicates()
self.log.info(self.tr("Controllo se ci sono dei duplicati..")) else:
self.removeDuplicates() for idx, ff in enumerate(self.contentList):
else: ff['duplicate']=False
for idx, ff in enumerate(self.contentList): self.contentList[idx]=ff
ff['duplicate']=False self.log.warn(self.tr("Salto il controllo dei duplicati.."))
self.contentList[idx]=ff # se il parse e la rimozione dei duplicati e' andata bene
self.log.warn(self.tr("Salto il controllo dei duplicati..")) # preparo e inizio il salvataggio
# se il parse e la rimozione dei duplicati e' andata bene if os.path.exists(self.outPath):
# preparo e inizio il salvataggio if self.settings['removeOldFiles']:
if os.path.exists(self.outPath): #os.chdir(self.outPath)
if self.settings['removeOldFiles']: for f in os.listdir(self.outPath):
#os.chdir(self.outPath) os.remove(self.outPath+f)
for f in os.listdir(self.outPath): else:
os.remove(self.outPath+f) raise FileExistsError(self.tr("Non posso sovrascrivere i vecchi file, eliminali manualmente!"))
else: else:
raise FileExistsError(self.tr("Non posso sovrascrivere i vecchi file, eliminali manualmente!")) os.mkdir(self.outPath)
else: #os.chdir(self.outPath)
os.mkdir(self.outPath) if self.settings['saveSeparateFiles']:
#os.chdir(self.outPath) self.saveSeparate()
if self.settings['saveSeparateFiles']: if self.settings['saveBodyFile']:
self.saveSeparate() self.saveBody()
if self.settings['saveBodyFile']: self.log.info(self.tr("L'elaborazione del file ha richiesto {:4.2f} sec").format(time.time()-self.beginTime))
self.saveBody()
self.log.info(self.tr("L'elaborazione del file ha richiesto {:4.2f} sec").format(time.time()-self.beginTime)) except UnicodeDecodeError as ee:
self.log.critical(self.tr("Il file [{}] contiene caratteri non compatibili con la codifica scelta! [{}]")
except UnicodeDecodeError as ee: .format(self.fileParams['name'],ee))
self.log.critical(self.tr("Il file [{}] contiene caratteri non compatibili con la codifica scelta! [{}]") except FileExistsError as fe:
.format(self.fileParams['name'],ee)) self.log.critical(fe)
except FileExistsError as fe: except Exception as ee:
self.log.critical(fe) traceback.print_exc()
except Exception as ee: self.log.warn(ee)
traceback.print_exc() pass
self.log.warn(ee)
pass def openFile(self):
try:
def openFile(self): #os.chdir(self.paths["INworkPath"])
try: self.log.info(self.tr("Carico il contenuto.."))
#os.chdir(self.paths["INworkPath"]) fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding'])
self.log.info(self.tr("Carico il contenuto..")) self.rawFile = fp.readlines()
fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding']) fp.close()
self.rawFile = fp.readlines() except IOError as e:
fp.close() self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e))
except IOError as e: raise BaseException("OpenFile")
self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e)) os.rmdir(self.outPath)
raise BaseException("OpenFile") except Exception as ee:
os.rmdir(self.outPath) print(ee)
except Exception as ee: pass
print(ee)
pass
def remEmptyLines(self): def remEmptyLines(self):
self.log.info(self.tr("Elimino righe vuote e caratteri inutili..")) self.log.info(self.tr("Elimino righe vuote e caratteri inutili.."))
tempContent = [] tempContent = []
try: try:
for ll in self.rawFile: for ll in self.rawFile:
for c in self.settings['delChars']: for c in self.settings['delChars']:
ll = ll.replace(c,'') ll = ll.replace(c,'')
if ll not in ['\n', '\r', '\r\n']: if ll not in ['\n', '\r', '\r\n']:
tempContent.append(ll) tempContent.append(ll)
self.rawFile = copy.deepcopy(tempContent) self.rawFile = copy.deepcopy(tempContent)
self.rawFile.append('\n') #linea vuota finale per essere sicuri di parsare bene self.rawFile.append('\n') #linea vuota finale per essere sicuri di parsare bene
return True return True
except: except:
self.log.error(self.tr("Errore inaspettato durante l'eliminazione delle righe vuote!")) self.log.error(self.tr("Errore inaspettato durante l'eliminazione delle righe vuote!"))
raise BaseException("DelLines") raise BaseException("DelLines")
del tempContent del tempContent
def newSplitFile(self): #porting del codice dal programma originale def newSplitFile(self): #porting del codice dal programma originale
self.log.info(self.tr("Individuo il contenuto..")) self.log.info(self.tr("Individuo il contenuto.."))
self.bodyCounter=0 self.bodyCounter=0
self.duplicateNumber=0 self.duplicateNumber=0
docNumber = 0 docNumber = 0
docSkipped = 0 docSkipped = 0
docDate = {} docDate = {}
title = '' title = ''
prevLine = '' prevLine = ''
newsPaperName = '' newsPaperName = ''
titleBegin = True titleBegin = True
newsName = False newsName = False
tempBody = list() tempBody = list()
for l in self.rawFile: #per ogni linea del file for l in self.rawFile: #per ogni linea del file
l=l.replace('\xa0', ' ') l=l.replace('\xa0', ' ')
lineWords = l.lstrip().split(' ') #dividi la riga in parole lineWords = l.lstrip().split(' ') #dividi la riga in parole
if self.status == 'first': if self.status == 'first':
try: try:
# ricerco la data # ricerco la data
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
try: try:
docDate=parse.parse(self.docStruct['dateFormat'],l).named docDate=parse.parse(self.docStruct['dateFormat'],l).named
docDate['month']=docDate['month'].lstrip().rstrip().capitalize() docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
# dopo la data inizia il titolo, ma prima si cerca il nome del giornale # dopo la data inizia il titolo, ma prima si cerca il nome del giornale
except: except:
self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]"). format(l.strip('\r\n'))) self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]"). format(l.strip('\r\n')))
pass pass
elif lineWords[0].upper() in self.docStruct['language']['headWords']: elif lineWords[0].upper() in self.docStruct['language']['headWords']:
#cambio stato e inizializzo un nuovo documento da riempire #cambio stato e inizializzo un nuovo documento da riempire
self.status = 'head' self.status = 'head'
newDoc=dict() newDoc=dict()
newDoc['title']=title newDoc['title']=title
newDoc['date']=docDate newDoc['date']=docDate
newDoc['newsPaperName'] = newsPaperName newDoc['newsPaperName'] = newsPaperName
titleBegin = False titleBegin = False
newsName = False newsName = False
else: else:
if titleBegin: if titleBegin:
title = l.strip().capitalize() title = l.strip().capitalize()
titleBegin = False titleBegin = False
newsName = True newsName = True
elif newsName: elif newsName:
if self.settings['getNewsPaperName']: if self.settings['getNewsPaperName']:
try: try:
if l.strip(): if l.strip():
newsPaperName = l.strip() newsPaperName = l.strip()
else: else:
newsPaperName = self.settings['nameNotFoundStr'] newsPaperName = self.settings['nameNotFoundStr']
except: except:
self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\ self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
controlla i file di uscita! [{}]").format(l.strip())) controlla i file di uscita! [{}]").format(l.strip()))
else: else:
newsPaperName = self.settings['nameNotFoundStr'] newsPaperName = self.settings['nameNotFoundStr']
newsName = False newsName = False
except IndexError: except IndexError:
self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!")) self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!"))
pass pass
elif self.status == 'head': elif self.status == 'head':
tempContent = list() tempContent = list()
#doppio check per trovare l'inizio del corpo documento #doppio check per trovare l'inizio del corpo documento
if re.match(self.docStruct['beginOfDocument'],l): if re.match(self.docStruct['beginOfDocument'],l):
self.status='body' self.status='body'
#if lineWords[0].upper() not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio #if lineWords[0].upper() not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio
#tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento #tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento
#self.status = 'body' #self.status = 'body'
elif self.status == 'body': elif self.status == 'body':
if re.match(self.docStruct['endOfDocument'],l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali if re.match(self.docStruct['endOfDocument'],l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali
self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\ self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t\t[{}]").format(docNumber, l.strip())) L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t\t[{}]").format(docNumber, l.strip()))
self.status = 'tail' self.status = 'tail'
anomaly = True anomaly = True
elif not lineWords[0].upper() in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine elif not lineWords[0].upper() in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine
if self.settings['delLF']: if self.settings['delLF']:
tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo
else: else:
tempBody.append(l) tempBody.append(l)
else: else:
self.status = 'tail' self.status = 'tail'
anomaly = False anomaly = False
pass pass
elif self.status == 'tail': elif self.status == 'tail':
if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None): if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None):
self.status = 'first' self.status = 'first'
anomaly = False anomaly = False
titleBegin = True titleBegin = True
if self.settings['delWordBreak']: if self.settings['delWordBreak']:
tempContent=[ll.replace('-\n', '') for ll in tempContent] tempContent=[ll.replace('-\n', '') for ll in tempContent]
newDoc['content']=copy.deepcopy(''.join(tempBody)) newDoc['content']=copy.deepcopy(''.join(tempBody))
self.contentList.append(copy.deepcopy(newDoc)) self.contentList.append(copy.deepcopy(newDoc))
tempBody=list() tempBody=list()
self.bodyCounter +=1 self.bodyCounter +=1
pass pass
else: else:
self.log.critical(self.tr("Stato Interno Sconosciuto")) self.log.critical(self.tr("Stato Interno Sconosciuto"))
prevLine=l #salva sempre e comunque il contenuto della linea precedente prevLine=l #salva sempre e comunque il contenuto della linea precedente
pass pass
#ricerca terminata, espongo i risultati #ricerca terminata, espongo i risultati
self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter)) self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter))
if docSkipped > 0: if docSkipped > 0:
self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped)) self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped))
pass pass
pass pass
def splitFile(self): #porting del codice dal programma originale def splitFile(self): #porting del codice dal programma originale
self.log.info(self.tr("Individuo il contenuto..")) self.log.info(self.tr("Individuo il contenuto.."))
self.bodyCounter=0 self.bodyCounter=0
self.duplicateNumber=0 self.duplicateNumber=0
docNumber = 0 docNumber = 0
docSkipped = 0 docSkipped = 0
docDate = {} docDate = {}
title = '' title = ''
prevLine = '' prevLine = ''
newsPaperName = '' newsPaperName = ''
titleBegin = False titleBegin = False
tempBody = list() tempBody = list()
docSep=re.compile(self.docStruct['docSep']) docSep=re.compile(self.docStruct['docSep'])
for l in self.rawFile: #per ogni linea del file for l in self.rawFile: #per ogni linea del file
lineWords = l.lstrip().split(' ') #dividi la riga in parole lineWords = l.lstrip().split(' ') #dividi la riga in parole
if self.status == 'first': if self.status == 'first':
#prendo il numero di documento per vedere se ci sono buchi #prendo il numero di documento per vedere se ci sono buchi
try: try:
try: try:
nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named
if nn["current"]-docNumber==1: if nn["current"]-docNumber==1:
pass pass
else: else:
if self.settings["showSkipped"]: if self.settings["showSkipped"]:
self.log.warn(self.tr("Il conto dei documenti non torna! LexisNexis ne ha saltato qualcuno!\n Precedente:{0}-Attuale:{1}").format(docNumber,nn["current"])) self.log.warn(self.tr("Il conto dei documenti non torna! LexisNexis ne ha saltato qualcuno!\n Precedente:{0}-Attuale:{1}").format(docNumber,nn["current"]))
docSkipped+=1 docSkipped+=1
docNumber = nn["current"] docNumber = nn["current"]
except: except:
pass #non segnalare eccezione se il parse fallisce pass #non segnalare eccezione se il parse fallisce
# ricerco la data # ricerco la data
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
try: try:
docDate=parse.parse(self.docStruct['dateFormat'],l).named docDate=parse.parse(self.docStruct['dateFormat'],l).named
docDate['month']=docDate['month'].lstrip().rstrip().capitalize() docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
title = '' title = ''
titleBegin=True titleBegin=True
# dopo la data inizia il titolo, ma prima si cerca il nome del giornale # dopo la data inizia il titolo, ma prima si cerca il nome del giornale
if self.settings['getNewsPaperName']: if self.settings['getNewsPaperName']:
try: try:
if prevLine.split(' ')[0].strip().isalpha(): if prevLine.split(' ')[0].strip().isalpha():
newsPaperName = prevLine.strip() newsPaperName = prevLine.strip()
else: else:
newsPaperName = self.settings['nameNotFoundStr'] newsPaperName = self.settings['nameNotFoundStr']
except: except:
self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\ self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
controlla i file di uscita! [{}]").format(prevLine.strip())) controlla i file di uscita! [{}]").format(prevLine.strip()))
else: else:
newsPaperName = self.settings['nameNotFoundStr'] newsPaperName = self.settings['nameNotFoundStr']
except: except:
self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]").format(l.strip('\r\n'))) self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]").format(l.strip('\r\n')))
pass pass
elif lineWords[0] in self.docStruct['language']['headWords']: elif lineWords[0] in self.docStruct['language']['headWords']:
#cambio stato e inizializzo un nuovo documento da riempire #cambio stato e inizializzo un nuovo documento da riempire
self.status = 'head' self.status = 'head'
newDoc=dict() newDoc=dict()
newDoc['title']=title newDoc['title']=title
newDoc['date']=docDate newDoc['date']=docDate
newDoc['newsPaperName'] = newsPaperName newDoc['newsPaperName'] = newsPaperName
titleBegin=False titleBegin=False
else: else:
if titleBegin: if titleBegin:
title += l.strip().capitalize() title += l.strip().capitalize()
except IndexError: except IndexError:
self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!")) self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!"))
pass pass
elif self.status == 'head': elif self.status == 'head':
tempContent = list() tempContent = list()
if lineWords[0] not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio if lineWords[0] not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio
tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento
self.status = 'body' self.status = 'body'
pass pass
elif self.status == 'body': elif self.status == 'body':
if not lineWords[0] in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine if not lineWords[0] in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine
if self.settings['delLF']: if self.settings['delLF']:
tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo
else: else:
tempBody.append(l) tempBody.append(l)
else: else:
self.status = 'tail' self.status = 'tail'
anomaly = False anomaly = False
if docSep.match(l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali if docSep.match(l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali
self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\ self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t[{}]").format(docNumber, l.strip())) L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t[{}]").format(docNumber, l.strip()))
self.status = 'tail' self.status = 'tail'
anomaly = True anomaly = True
pass pass
elif self.status == 'tail': elif self.status == 'tail':
if docSep.match(l) is not None or anomaly: if docSep.match(l) is not None or anomaly:
self.status = 'first' self.status = 'first'
anomaly = False anomaly = False
if self.settings['delWordBreak']: if self.settings['delWordBreak']:
tempContent=[ll.replace('-\n', '') for ll in tempContent] tempContent=[ll.replace('-\n', '') for ll in tempContent]
newDoc['content']=copy.deepcopy(''.join(tempBody)) newDoc['content']=copy.deepcopy(''.join(tempBody))
self.contentList.append(copy.deepcopy(newDoc)) self.contentList.append(copy.deepcopy(newDoc))
tempBody=list() tempBody=list()
self.bodyCounter +=1 self.bodyCounter +=1
pass pass
else: else:
self.log.critical(self.tr("Stato Interno Sconosciuto")) self.log.critical(self.tr("Stato Interno Sconosciuto"))
prevLine=l #salva sempre e comunque il contenuto della linea precedente prevLine=l #salva sempre e comunque il contenuto della linea precedente
pass pass
#ricerca terminata, espongo i risultati #ricerca terminata, espongo i risultati
self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter)) self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter))
if docSkipped > 0: if docSkipped > 0:
self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped)) self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped))
pass pass
pass pass
def removeDuplicates(self): def removeDuplicates(self):
titleList=[] titleList=[]
duplicateList=[] duplicateList=[]
for idx, ff in enumerate(self.contentList): for idx, ff in enumerate(self.contentList):
if ff['title'] not in titleList: if ff['title'] not in titleList:
titleList.append(ff['title']) titleList.append(ff['title'])
ff['duplicate']=False ff['duplicate']=False
self.contentList[idx]=ff self.contentList[idx]=ff
pass pass
else: else:
if ff['title'] not in duplicateList: if ff['title'] not in duplicateList:
duplicateList.append(ff['title']) duplicateList.append(ff['title'])
if self.settings['showRemovedDuplicates']: if self.settings['showRemovedDuplicates']:
self.log.info(self.tr("Duplicato: {}").format(ff['title'].strip())) self.log.info(self.tr("Duplicato: {}").format(ff['title'].strip()))
ff['duplicate'] = True ff['duplicate'] = True
self.contentList[idx]=ff self.contentList[idx]=ff
self.duplicateNumber+=1 self.duplicateNumber+=1
self.log.info(self.tr("Ho rimosso {} duplicati di {} articoli..").format(self.duplicateNumber, len(duplicateList))) self.log.info(self.tr("Ho rimosso {} duplicati di {} articoli..").format(self.duplicateNumber, len(duplicateList)))
pass pass
def saveSeparate(self): def saveSeparate(self):
outFileCounter = 0 outFileCounter = 0
self.paths['OUTworkPath']=self.paths['OUTworkPath']+slugify(self.fileName) self.paths['OUTworkPath']=self.paths['OUTworkPath']+slugify(self.fileName)
self.log.info(self.tr("Salvo gli articoli in file separati...")) self.log.info(self.tr("Salvo gli articoli in file separati..."))
self.log.debug(self.tr("Persorso: {0}").format(self.outPath)) self.log.debug(self.tr("Persorso: {0}").format(self.outPath))
for ff in self.contentList: for ff in self.contentList:
try: try:
if ff['duplicate'] == False: if ff['duplicate'] == False:
fName=self.docStruct['outNameFormat'].format(title=slugify(ff['title'][:self.docStruct['maxTitleLen']]),\ fName=self.docStruct['outNameFormat'].format(title=slugify(ff['title'][:self.docStruct['maxTitleLen']]),\
filename=slugify(self.fileName),\ filename=slugify(self.fileName),\
docnum=outFileCounter,\ docnum=outFileCounter,\
papername=ff['newsPaperName'].strip(),\ papername=ff['newsPaperName'].strip(),\
**ff['date']) **ff['date'])
out=open(self.outPath+'{0}'.format(fName),'wb') out=open(self.outPath+'{0}'.format(fName),'wb')
if self.settings['includeTitle']: if self.settings['includeTitle']:
ff['content'] = ff['title']+os.linesep+ff['content'] ff['content'] = ff['title']+os.linesep+ff['content']
out.write(ff['content'].encode(self.settings['encoding'])) out.write(ff['content'].encode(self.settings['encoding']))
out.close() out.close()
outFileCounter+=1 outFileCounter+=1
except IOError as e: except IOError as e:
self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e)) self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e))
continue continue
except KeyError as ke: except KeyError as ke:
self.log.error(self.tr(f"Chiave {ke} non trovata per:{outFileCounter} {ff['title']} ")) self.log.error(self.tr(f"Chiave {ke} non trovata per:{outFileCounter} {ff['title']} "))
except Exception as ee: except Exception as ee:
traceback.print_exc() traceback.print_exc()
self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}")) self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}"))
if outFileCounter < self.bodyCounter: if outFileCounter < self.bodyCounter:
self.log.error(self.tr("Ho salvato meno file rispetto a quelli trovati!")) self.log.error(self.tr("Ho salvato meno file rispetto a quelli trovati!"))
pass pass
def saveBody(self): def saveBody(self):
self.log.info(self.tr('Salvo gli articoli in un singolo file vicino agli originali...')) self.log.info(self.tr('Salvo gli articoli in un singolo file vicino agli originali...'))
self.log.debug(self.tr('Persorso: {0}').format(self.outPath)) self.log.debug(self.tr('Persorso: {0}').format(self.outPath))
#os.chdir(self.outPath) #os.chdir(self.outPath)
try: try:
fName=slugify(self.fileName) fName=slugify(self.fileName)
fName='BODYFILE_{0}.txt'.format(fName[:self.docStruct['maxTitleLen']]) fName='BODYFILE_{0}.txt'.format(fName[:self.docStruct['maxTitleLen']])
fileContent = os.linesep.join([cc['content'] for cc in self.contentList]) fileContent = os.linesep.join([cc['content'] for cc in self.contentList])
out=open(self.outPath+'{0}'.format(fName),'wb') out=open(self.outPath+'{0}'.format(fName),'wb')
out.write(fileContent.encode(self.settings['encoding'])) out.write(fileContent.encode(self.settings['encoding']))
out.close() out.close()
except IOError as e: except IOError as e:
self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e)) self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e))
except Exception as ee: except Exception as ee:
self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}")) self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}"))
pass pass