diff --git a/SPEx/poetry.lock b/SPEx/poetry.lock index a52fed3..46ee25f 100644 --- a/SPEx/poetry.lock +++ b/SPEx/poetry.lock @@ -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_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]] category = "dev" description = "Cross-platform colored terminal text." @@ -119,6 +131,14 @@ optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" 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]] category = "dev" description = "python code static checker" @@ -238,7 +258,7 @@ python-versions = "*" version = "1.12.1" [metadata] -content-hash = "e35375126d07552fb1e200007cf6bd02991d90c71eb261f21b33919e77395a58" +content-hash = "f2c0aacdec9a2b08fb05b279563096aab92c78d4b64ccc312db25de8e74a910f" lock-version = "1.0" 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.tar.gz", hash = "sha256:26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594"}, ] +autopep8 = [ + {file = "autopep8-1.5.4.tar.gz", hash = "sha256:d21d3901cb0da6ebd1e83fc9b0dfbde8b46afc2ede4fe32fbda0c7c6118ca094"}, +] colorama = [ {file = "colorama-0.4.3-py2.py3-none-any.whl", hash = "sha256:7d73d2a99753107a36ac6b455ee49046802e59d9d076ef8e47b61499fa29afff"}, {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.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 = [ {file = "pylint-2.6.0-py3-none-any.whl", hash = "sha256:bfe68f020f8a0fece830a22dd4d5dddb4ecc6137db04face4c3420a46a52239f"}, {file = "pylint-2.6.0.tar.gz", hash = "sha256:bb4a908c9dadbc3aac18860550e870f58e1a02c9f2c204fdf5693d73be061210"}, diff --git a/SPEx/pyproject.toml b/SPEx/pyproject.toml index be9f399..91c8afc 100644 --- a/SPEx/pyproject.toml +++ b/SPEx/pyproject.toml @@ -13,6 +13,7 @@ parse = "*" [tool.poetry.dev-dependencies] pytest = "^5.2" pylint = "^2.6.0" +autopep8 = "^1.5.4" [build-system] requires = ["poetry>=0.12"] diff --git a/SPEx/spex/guimain.py b/SPEx/spex/guimain.py index a3bbb9e..2d4e900 100644 --- a/SPEx/spex/guimain.py +++ b/SPEx/spex/guimain.py @@ -6,615 +6,672 @@ TODO LIST 1. rendere threaded lo splitter.. tentativo colore 100.. ''' -import sys, copy, json, os -import PyQt5.QtWidgets +import sys +import copy +import json +import os + +from mainwindow import Ui_mainwin +from selezout import Ui_selezout +from titolow import Ui_titolo +from avanzatetitolo3 import Ui_advtitolo3 as Ui_advtitolo +from advopt import Ui_editconf +from about import Ui_about + +from libfancylogger import fancyLogger +from libconfload import bananaCONF +from libsplit import bananaSPLITTER + import PyQt5.QtGui - - -from userInterface.compiledUI.mainwindow import Ui_mainwin -from userInterface.compiledUI.selezout import Ui_selezout -from userInterface.compiledUI.titolow import Ui_titolo -from userInterface.compiledUI.avanzatetitolo3 import Ui_advtitolo3 as Ui_advtitolo -from userInterface.compiledUI.advopt import Ui_editconf -from userInterface.compiledUI.about import Ui_about - -from libbananasplit.libfancylogger import fancyLogger -from libbananasplit.libconfload import bananaCONF -from libbananasplit.libsplit import bananaSPLITTER - from PyQt5.QtCore import QDir, QSize, QTranslator, pyqtSlot, pyqtSignal from PyQt5.QtWidgets import QMessageBox, QSizePolicy, QInputDialog #modo brutto per mettere la lista delle lingue in un posto solo -langlist = ['it','en'] +langlist = ['it', 'en'] -class bananaMain(PyQt5.QtWidgets.QMainWindow): - def __init__(self, logger=None, confloader=None): - PyQt5.QtWidgets.QMainWindow.__init__(self) - self.logger = logger - self.conf = confloader - - # inizializzazione interfaccia - self.ui = Ui_mainwin() - self.ui.setupUi(self) - self.titolo = bananaTitolo(self.conf, self.logger) - self.titoloav = bananaTitoloAvanzate(self.conf, self.logger) - self.selezout = bananaSelezOut(self.conf, self.logger) - self.advopt = bananaAdvOpt(self.conf, self.logger) - - #popola le tab con le finestre giuste - self.ui.wgt_main.addTab(self.titolo, self.tr("Impostazioni Titolo")) - self.ui.wgt_main.addTab(self.selezout, self.tr("Selezione Output")) - - # connetti bottoni avanti - self.ui.btn_avanti.clicked.connect(self.nextTab) - self.titolo.titoloui.btn_avanti.clicked.connect(self.nextTab) - - #connetti bottoni indietro - self.titolo.titoloui.btn_indietro.clicked.connect(self.prevTab) - self.selezout.selezoutui.btn_indietro.clicked.connect(self.prevTab) - - #connetti bottoni selezione cartelle - self.ui.btn_cartellasorg.clicked.connect(self.selezSorg) - self.ui.btn_cartelladest.clicked.connect(self.selezDest) - - #connetti action tab - self.ui.actionLingua.triggered.connect(self.openLanguage) - self.ui.actionAvanzate.triggered.connect(self.openAdvOpt) - self.ui.actionCarica_Preset.triggered.connect(self.openLoadPreset) - self.ui.actionSalva_Preset.triggered.connect(self.openSavePreset) - self.ui.actionAbout_SPEx.triggered.connect(self.openAbout) - - #connetti i radbutton versione - self.ui.rad_fileNew.clicked.connect(self.selezVers) - self.ui.rad_fileOld.clicked.connect(self.selezVers) - - #connetti segnali delle sottointerfacce - self.advopt.update.connect(self.fillAllInterfaces) - self.logger.sendLog.connect(self.appendLog) - - #riempi pagine di interfaccia - self.fillAllInterfaces() - self.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed) - self.setFixedSize(QSize(self.conf.getParam('settings','winW'), self.conf.getParam('settings','winH'))) - pass - - def fillInterface(self): - #pagina principale - try: - self.ui.lbl_preset.setText(self.conf.inUse.replace('.json','')) - self.ui.lbl_sorg.setText(self.conf.getParam('paths','INworkPath')) - self.ui.lbl_dest.setText(self.conf.getParam('paths','OUTworkPath')) - self.ui.rad_fileNew.setChecked(self.conf.getParam('docStruct', 'fileVersNew')) - self.ui.rad_fileOld.setChecked(not self.conf.getParam('docStruct', 'fileVersNew')) - self.fillFileList() - except: - self.log.critical(self.tr("MainWindow: Configurazione non accettata")) - - def fillAllInterfaces(self): - self.fillInterface() - self.titolo.fillInterface() - self.titoloav.fillInterface() - self.selezout.fillInterface() - self.advopt.fillInterface() - - def fillFileList(self): - fl = QDir(self.conf.getParam('paths','INworkPath')) - fl.setNameFilters(['*.txt','*.TXT']) - fl = fl.entryList(QDir.NoDotAndDotDot | QDir.Files) - self.ui.lst_files.clear() - for f in fl: - self.ui.lst_files.addItem(PyQt5.QtWidgets.QListWidgetItem(f)) - self.conf.setParam(('paths', 'fileList'), fl) +class bananaMain(PyQt5.QtWidgets.QMainWindow): + def __init__(self, logger=None, confloader=None): + PyQt5.QtWidgets.QMainWindow.__init__(self) + self.logger = logger + self.conf = confloader + # inizializzazione interfaccia + self.ui = Ui_mainwin() + self.ui.setupUi(self) + self.titolo = bananaTitolo(self.conf, self.logger) + self.titoloav = bananaTitoloAvanzate(self.conf, self.logger) + self.selezout = bananaSelezOut(self.conf, self.logger) + self.advopt = bananaAdvOpt(self.conf, self.logger) + #popola le tab con le finestre giuste + self.ui.wgt_main.addTab(self.titolo, self.tr("Impostazioni Titolo")) + self.ui.wgt_main.addTab(self.selezout, self.tr("Selezione Output")) + # connetti bottoni avanti + self.ui.btn_avanti.clicked.connect(self.nextTab) + self.titolo.titoloui.btn_avanti.clicked.connect(self.nextTab) + #connetti bottoni indietro + self.titolo.titoloui.btn_indietro.clicked.connect(self.prevTab) + self.selezout.selezoutui.btn_indietro.clicked.connect(self.prevTab) + #connetti bottoni selezione cartelle + self.ui.btn_cartellasorg.clicked.connect(self.selezSorg) + self.ui.btn_cartelladest.clicked.connect(self.selezDest) + #connetti action tab + self.ui.actionLingua.triggered.connect(self.openLanguage) + self.ui.actionAvanzate.triggered.connect(self.openAdvOpt) + self.ui.actionCarica_Preset.triggered.connect(self.openLoadPreset) + self.ui.actionSalva_Preset.triggered.connect(self.openSavePreset) + self.ui.actionAbout_SPEx.triggered.connect(self.openAbout) + #connetti i radbutton versione + self.ui.rad_fileNew.clicked.connect(self.selezVers) + self.ui.rad_fileOld.clicked.connect(self.selezVers) + #connetti segnali delle sottointerfacce + self.advopt.update.connect(self.fillAllInterfaces) + self.logger.sendLog.connect(self.appendLog) + #riempi pagine di interfaccia + self.fillAllInterfaces() + self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + self.setFixedSize(QSize(self.conf.getParam( + 'settings', 'winW'), self.conf.getParam('settings', 'winH'))) + pass + def fillInterface(self): + #pagina principale + try: + self.ui.lbl_preset.setText(self.conf.inUse.replace('.json', '')) + self.ui.lbl_sorg.setText(self.conf.getParam('paths', 'INworkPath')) + self.ui.lbl_dest.setText(self.conf.getParam('paths', 'OUTworkPath')) + self.ui.rad_fileNew.setChecked( + self.conf.getParam('docStruct', 'fileVersNew')) + self.ui.rad_fileOld.setChecked( + not self.conf.getParam('docStruct', 'fileVersNew')) + self.fillFileList() + except: + self.log.critical(self.tr("MainWindow: Configurazione non accettata")) + def fillAllInterfaces(self): + self.fillInterface() + self.titolo.fillInterface() + self.titoloav.fillInterface() + self.selezout.fillInterface() + self.advopt.fillInterface() + def fillFileList(self): + fl = QDir(self.conf.getParam('paths', 'INworkPath')) + fl.setNameFilters(['*.txt', '*.TXT']) + fl = fl.entryList(QDir.NoDotAndDotDot | QDir.Files) + self.ui.lst_files.clear() + for f in fl: + self.ui.lst_files.addItem(PyQt5.QtWidgets.QListWidgetItem(f)) + self.conf.setParam(('paths', 'fileList'), fl) + def nextTab(self): + self.ui.wgt_main.setCurrentIndex(self.ui.wgt_main.currentIndex()+1) + self.logger.debug(self.tr("Prossima Tab")) + pass + def prevTab(self): + self.ui.wgt_main.setCurrentIndex(self.ui.wgt_main.currentIndex()-1) + self.logger.debug(self.tr("Tab Precedente")) + pass + def openLoadPreset(self): + self.logger.debug(self.tr("Apri Carica Preset")) + lf = PyQt5.QtWidgets.QFileDialog(self, self.tr( + "Carica Preset"), self.conf.getParam('paths', 'configurationPath')) + lf.setAcceptMode(PyQt5.QtWidgets.QFileDialog.AcceptOpen) + lf.setFileMode(PyQt5.QtWidgets.QFileDialog.ExistingFile) + lf.setNameFilter("bananaCONF (*.json)") + if lf.exec(): + cf = str(lf.selectedFiles()[0].split('/')[-1]) + self.logger.info(self.tr(f"Apro la configurazione: {cf}")) + self.conf.open() + self.conf.use(cf) + self.logger.debug(self.tr("Riempio tutte le tab")) + self.fillAllInterfaces() + pass + def openSavePreset(self): + self.logger.debug(self.tr("Apri Salva Preset")) + self.applicaTutto() + sf = PyQt5.QtWidgets.QFileDialog( + self, "Salva Preset", self.conf.getParam('paths', 'configurationPath')) + sf.setAcceptMode(PyQt5.QtWidgets.QFileDialog.AcceptSave) + sf.setNameFilter("bananaCONF (*.json)") + if sf.exec(): + rv = str(sf.selectedFiles()[0].split('/')[-1]) + self.conf.setParam(('paths', 'lastUsed'), rv) + #scrivi quale file e' stato usato per ultimo nel default + prev = self.conf.inUse + self.conf.use("defaults.json") + self.conf.setParam(('paths', 'lastUsed'), rv) + self.conf.save(fName="defaults.json") + self.conf.use(prev) + ## + self.logger.debug(self.tr(f"Scrivo la configurazione: {rv}")) + self.conf.save(fName=rv) + pass + def openAdvOpt(self): + self.logger.debug(self.tr("Apri Opzioni Avanzate")) + self.advopt.fillInterface() + self.advopt.show() + pass + def openLanguage(self): + global langlist + self.logger.debug(self.tr("Apri Opzioni Lingua")) + flag = False + lang, flag = QInputDialog.getItem(self, self.tr( + "Lingua"), self.tr("Disponibili"), langlist, 0, False) + if flag: + self.conf.setParam(('settings', 'uiLang'), lang) + else: + pass - def nextTab(self): - self.ui.wgt_main.setCurrentIndex(self.ui.wgt_main.currentIndex()+1) - self.logger.debug(self.tr("Prossima Tab")) - pass - - def prevTab(self): - self.ui.wgt_main.setCurrentIndex(self.ui.wgt_main.currentIndex()-1) - self.logger.debug(self.tr("Tab Precedente")) - pass - - def openLoadPreset(self): - self.logger.debug(self.tr("Apri Carica Preset")) - lf = PyQt5.QtWidgets.QFileDialog(self,self.tr("Carica Preset"),self.conf.getParam('paths', 'configurationPath')) - lf.setAcceptMode(PyQt5.QtWidgets.QFileDialog.AcceptOpen) - lf.setFileMode(PyQt5.QtWidgets.QFileDialog.ExistingFile) - lf.setNameFilter("bananaCONF (*.json)") - if lf.exec(): - cf = str(lf.selectedFiles()[0].split('/')[-1]) - self.logger.info(self.tr(f"Apro la configurazione: {cf}")) - self.conf.open() - self.conf.use(cf) - self.logger.debug(self.tr("Riempio tutte le tab")) - self.fillAllInterfaces() - pass - - def openSavePreset(self): - self.logger.debug(self.tr("Apri Salva Preset")) - self.applicaTutto() - sf = PyQt5.QtWidgets.QFileDialog(self,"Salva Preset",self.conf.getParam('paths', 'configurationPath')) - sf.setAcceptMode(PyQt5.QtWidgets.QFileDialog.AcceptSave) - sf.setNameFilter("bananaCONF (*.json)") - if sf.exec(): - rv=str(sf.selectedFiles()[0].split('/')[-1]) - self.conf.setParam(('paths','lastUsed'),rv) - #scrivi quale file e' stato usato per ultimo nel default - prev=self.conf.inUse - self.conf.use("defaults.json") - self.conf.setParam(('paths','lastUsed'),rv) - self.conf.save(fName="defaults.json") - self.conf.use(prev) - ## - self.logger.debug(self.tr(f"Scrivo la configurazione: {rv}")) - self.conf.save(fName=rv) - pass - - def openAdvOpt(self): - self.logger.debug(self.tr("Apri Opzioni Avanzate")) - self.advopt.fillInterface() - self.advopt.show() - pass - - def openLanguage(self): - global langlist - self.logger.debug(self.tr("Apri Opzioni Lingua")) - flag = False - lang,flag = QInputDialog.getItem(self, self.tr("Lingua"), self.tr("Disponibili"), langlist, 0, False) - if flag: - self.conf.setParam(('settings','uiLang'),lang) - else: - pass - - def openAbout(self): - self.logger.debug(self.tr("Apri Finestra About")) - self.spxabt=spexAbout(confloader=self.conf) - - def selezSorg(self): - rv = PyQt5.QtWidgets.QFileDialog.getExistingDirectory(self,self.tr("Seleziona Cartella Sorgente"),self.conf.getParam('paths','INworkPath')) - if rv is not "": - self.conf.setParam(keys=('paths','INworkPath',), val=rv+"/") - self.ui.lbl_sorg.setText(rv) - self.logger.info(self.tr("Selezionata Cartella Sorgente: {}").format(rv+"/")) - self.fillFileList() - pass - - def selezDest(self): - rv = PyQt5.QtWidgets.QFileDialog.getExistingDirectory(self,self.tr("Seleziona Cartella Destinazione"),self.conf.getParam('paths','OUTworkPath')) - if rv is not "": - self.conf.setParam(keys=('paths','OUTworkPath',), val=rv+"/") - self.ui.lbl_dest.setText(rv) - self.logger.info(self.tr("Selezionata Cartella Destinazione: {}").format(rv+"/")) - pass - - def selezVers(self): - self.conf.setParam(('docStruct','fileVersNew'), self.ui.rad_fileNew.isChecked()) - self.logger.debug(self.tr(f"Selezionata Versione File")) - - def openFileDialog(self, name, path): - self.log.debug(self.tr("Apro in directory: {}").format(path)) - return - - def applicaTutto(self): - self.titolo.applica() - self.selezout.applica() - - def appendLog(self, msg): - self.ui.txt_log.append(msg) + def openAbout(self): + self.logger.debug(self.tr("Apri Finestra About")) + self.spxabt = spexAbout(confloader=self.conf) + + def selezSorg(self): + rv = PyQt5.QtWidgets.QFileDialog.getExistingDirectory(self, self.tr( + "Seleziona Cartella Sorgente"), self.conf.getParam('paths', 'INworkPath')) + if rv != "": + self.conf.setParam(keys=('paths', 'INworkPath',), val=rv+"/") + self.ui.lbl_sorg.setText(rv) + self.logger.info( + self.tr("Selezionata Cartella Sorgente: {}").format(rv+"/")) + self.fillFileList() + pass + + def selezDest(self): + rv = PyQt5.QtWidgets.QFileDialog.getExistingDirectory(self, self.tr( + "Seleziona Cartella Destinazione"), self.conf.getParam('paths', 'OUTworkPath')) + if rv != "": + self.conf.setParam(keys=('paths', 'OUTworkPath',), val=rv+"/") + self.ui.lbl_dest.setText(rv) + self.logger.info( + self.tr("Selezionata Cartella Destinazione: {}").format(rv+"/")) + pass + + def selezVers(self): + self.conf.setParam(('docStruct', 'fileVersNew'), + self.ui.rad_fileNew.isChecked()) + self.logger.debug(self.tr(f"Selezionata Versione File")) + + def openFileDialog(self, name, path): + self.log.debug(self.tr("Apro in directory: {}").format(path)) + return + + def applicaTutto(self): + self.titolo.applica() + self.selezout.applica() + + def appendLog(self, msg): + self.ui.txt_log.append(msg) ############################################################# ####################### INTERFACES ########################## ############################################################# + class bananaTitolo(PyQt5.QtWidgets.QWidget): - def __init__(self, confloader=None, logger=None): - PyQt5.QtWidgets.QWidget.__init__(self) - self.titoloui = Ui_titolo() - self.titoloui.setupUi(self) - self.conf = confloader - self.log = logger - if self.conf is not None: - self.titoloui.btn_avanzate.clicked.connect(self.spawnAvanzate) - self.titoloui.btn_avanti.clicked.connect(self.applica) - self.advtitolo = bananaTitoloAvanzate(confloader, self.log) - self.fillInterface() - pass - - def fillInterface(self): - try: - # imposta predefiniti interfaccia da file - #Data (la piu complicata) - self.titoloui.chk_data.setChecked(self.conf.getParam('docStruct','outDate')) - self.titoloui.rad_datajpn.setChecked(self.conf.getParam('docStruct', 'outDateType') == 'jpn') - self.titoloui.rad_dataita.setChecked(self.conf.getParam('docStruct', 'outDateType') == 'it') - self.titoloui.rad_datausa.setChecked(self.conf.getParam('docStruct', 'outDateType') == 'usa') - #Titolo - self.titoloui.chk_titolo.setChecked(self.conf.getParam('docStruct','outTitle')) - self.titoloui.spn_ncarat.setValue(self.conf.getParam('docStruct', 'maxTitleLen')) - #Numero Documento - self.titoloui.chk_docnum.setChecked(self.conf.getParam('docStruct','outNumber')) - #Separatore - found=False - for itmn in range(self.titoloui.lyt_sep.count()): - itm=self.titoloui.lyt_sep.itemAt(itmn).widget() - if isinstance(itm, PyQt5.QtWidgets.QRadioButton): - if itm.text() == self.conf.getParam('docStruct', 'outNameSep'): - itm.setChecked(True) - found = True - if not found: - self.titoloui.rad_altro.setChecked(True) - self.titoloui.lin_altro.setText(self.conf.getParam('docStruct', 'customSep')) - #finestra avanzate - self.advtitolo.fillInterface() - except: - self.log.critical(self.tr("Titolo: Configurazione non accettata")) - - def spawnAvanzate(self): - self.log.debug(self.tr("Mostro la finestra avanzate titolo")) - self.advtitolo.show() - pass - - def applica(self): - self.log.info(self.tr("Applico impostazioni Titolo")) - self.conf.setParam(('docStruct','outDate'),self.titoloui.chk_data.isChecked()) - self.conf.setParam(('docStruct','outNumber'),self.titoloui.chk_docnum.isChecked()) - self.conf.setParam(('docStruct','outTitle'),self.titoloui.chk_titolo.isChecked()) - if self.titoloui.rad_dataita.isChecked(): - self.conf.setParam(('docStruct','outDateType'),'ita') - elif self.titoloui.rad_datajpn.isChecked(): - self.conf.setParam(('docStruct','outDateType'),'jpn') - elif self.titoloui.rad_datausa.isChecked(): - self.conf.setParam(('docStruct','outDateType'),'usa') - self.conf.setParam(('docStruct','maxTitleLen'), self.titoloui.spn_ncarat.value()) - self.conf.setParam(('docStruct', 'customSep'),self.titoloui.lin_altro.text()) - for itmn in range(self.titoloui.lyt_sep.count()): - itm=self.titoloui.lyt_sep.itemAt(itmn).widget() - if isinstance(itm, PyQt5.QtWidgets.QRadioButton): - if len(itm.text())==1 and itm.isChecked(): - self.conf.setParam(('docStruct', 'outNameSep'), itm.text()) - self.advtitolo.applica() - pass - + def __init__(self, confloader=None, logger=None): + PyQt5.QtWidgets.QWidget.__init__(self) + self.titoloui = Ui_titolo() + self.titoloui.setupUi(self) + self.conf = confloader + self.log = logger + if self.conf is not None: + self.titoloui.btn_avanzate.clicked.connect(self.spawnAvanzate) + self.titoloui.btn_avanti.clicked.connect(self.applica) + self.advtitolo = bananaTitoloAvanzate(confloader, self.log) + self.fillInterface() + pass + + def fillInterface(self): + try: + # imposta predefiniti interfaccia da file + #Data (la piu complicata) + self.titoloui.chk_data.setChecked( + self.conf.getParam('docStruct', 'outDate')) + self.titoloui.rad_datajpn.setChecked( + self.conf.getParam('docStruct', 'outDateType') == 'jpn') + self.titoloui.rad_dataita.setChecked( + self.conf.getParam('docStruct', 'outDateType') == 'it') + self.titoloui.rad_datausa.setChecked( + self.conf.getParam('docStruct', 'outDateType') == 'usa') + #Titolo + self.titoloui.chk_titolo.setChecked( + self.conf.getParam('docStruct', 'outTitle')) + self.titoloui.spn_ncarat.setValue( + self.conf.getParam('docStruct', 'maxTitleLen')) + #Numero Documento + self.titoloui.chk_docnum.setChecked( + self.conf.getParam('docStruct', 'outNumber')) + #Separatore + found = False + for itmn in range(self.titoloui.lyt_sep.count()): + itm = self.titoloui.lyt_sep.itemAt(itmn).widget() + if isinstance(itm, PyQt5.QtWidgets.QRadioButton): + if itm.text() == self.conf.getParam('docStruct', 'outNameSep'): + itm.setChecked(True) + found = True + if not found: + self.titoloui.rad_altro.setChecked(True) + self.titoloui.lin_altro.setText( + self.conf.getParam('docStruct', 'customSep')) + #finestra avanzate + self.advtitolo.fillInterface() + except: + self.log.critical(self.tr("Titolo: Configurazione non accettata")) + + def spawnAvanzate(self): + self.log.debug(self.tr("Mostro la finestra avanzate titolo")) + self.advtitolo.show() + pass + + def applica(self): + self.log.info(self.tr("Applico impostazioni Titolo")) + self.conf.setParam(('docStruct', 'outDate'), + self.titoloui.chk_data.isChecked()) + self.conf.setParam(('docStruct', 'outNumber'), + self.titoloui.chk_docnum.isChecked()) + self.conf.setParam(('docStruct', 'outTitle'), + self.titoloui.chk_titolo.isChecked()) + if self.titoloui.rad_dataita.isChecked(): + self.conf.setParam(('docStruct', 'outDateType'), 'ita') + elif self.titoloui.rad_datajpn.isChecked(): + self.conf.setParam(('docStruct', 'outDateType'), 'jpn') + elif self.titoloui.rad_datausa.isChecked(): + self.conf.setParam(('docStruct', 'outDateType'), 'usa') + self.conf.setParam(('docStruct', 'maxTitleLen'), + self.titoloui.spn_ncarat.value()) + self.conf.setParam(('docStruct', 'customSep'), + self.titoloui.lin_altro.text()) + for itmn in range(self.titoloui.lyt_sep.count()): + itm = self.titoloui.lyt_sep.itemAt(itmn).widget() + if isinstance(itm, PyQt5.QtWidgets.QRadioButton): + if len(itm.text()) == 1 and itm.isChecked(): + self.conf.setParam(('docStruct', 'outNameSep'), itm.text()) + self.advtitolo.applica() + pass + + class bananaTitoloAvanzate(PyQt5.QtWidgets.QWidget): - def __init__(self, confloader=None, logger=None): - PyQt5.QtWidgets.QWidget.__init__(self) - self.titoloavui = Ui_advtitolo() - self.titoloavui.setupUi(self) - self.titoloavui.btn_OK.clicked.connect(self.returnOk) - self.titoloavui.btn_annulla.clicked.connect(self.returnKo) - - self.titoloavui.rad_dataprimo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_datasecondo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_dataterzo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_numeroprimo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_numerosecondo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_numeroterzo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_titoloprimo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_titolosecondo.clicked.connect(self.gestisciBottoni) - self.titoloavui.rad_titoloterzo.clicked.connect(self.gestisciBottoni) - self.conf = confloader - self.log = logger - self.fillInterface() - pass + def __init__(self, confloader=None, logger=None): + PyQt5.QtWidgets.QWidget.__init__(self) + self.titoloavui = Ui_advtitolo() + self.titoloavui.setupUi(self) + self.titoloavui.btn_OK.clicked.connect(self.returnOk) + self.titoloavui.btn_annulla.clicked.connect(self.returnKo) + + self.titoloavui.rad_dataprimo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_datasecondo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_dataterzo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_numeroprimo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_numerosecondo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_numeroterzo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_titoloprimo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_titolosecondo.clicked.connect(self.gestisciBottoni) + self.titoloavui.rad_titoloterzo.clicked.connect(self.gestisciBottoni) + self.conf = confloader + self.log = logger + self.fillInterface() + pass + + def fillInterface(self): + try: + #rimepi interfaccia + self.titoloavui.rad_dataprimo.setChecked( + self.conf.getParam('docStruct', 'datePos') == 1) + self.titoloavui.rad_datasecondo.setChecked( + self.conf.getParam('docStruct', 'datePos') == 2) + self.titoloavui.rad_dataterzo.setChecked( + self.conf.getParam('docStruct', 'datePos') == 3) + self.titoloavui.rad_titoloprimo.setChecked( + self.conf.getParam('docStruct', 'titlePos') == 1) + self.titoloavui.rad_titolosecondo.setChecked( + self.conf.getParam('docStruct', 'titlePos') == 2) + self.titoloavui.rad_titoloterzo.setChecked( + self.conf.getParam('docStruct', 'titlePos') == 3) + self.titoloavui.rad_numeroprimo.setChecked( + self.conf.getParam('docStruct', 'numberPos') == 1) + self.titoloavui.rad_numerosecondo.setChecked( + self.conf.getParam('docStruct', 'numberPos') == 2) + self.titoloavui.rad_numeroterzo.setChecked( + self.conf.getParam('docStruct', 'numberPos') == 3) + self.titoloavui.txt_prefisso.setText( + self.conf.getParam('docStruct', 'outPrefix')) + self.titoloavui.txt_suffisso.setText( + self.conf.getParam('docStruct', 'outSuffix')) + except: + self.log.critical(self.tr("AvanzateTitolo: Configurazione non accettata")) + + def gestisciBottoni(self): + #PRIMO + if self.titoloavui.rad_numeroprimo.isChecked(): + self.titoloavui.rad_dataprimo.setChecked(False) + self.titoloavui.rad_titoloprimo.setChecked(False) + self.titoloavui.rad_numerosecondo.setChecked(False) + self.titoloavui.rad_numeroterzo.setChecked(False) + if self.titoloavui.rad_dataprimo.isChecked(): + self.titoloavui.rad_numeroprimo.setChecked(False) + self.titoloavui.rad_titoloprimo.setChecked(False) + self.titoloavui.rad_datasecondo.setChecked(False) + self.titoloavui.rad_dataterzo.setChecked(False) + if self.titoloavui.rad_titoloprimo.isChecked(): + self.titoloavui.rad_numeroprimo.setChecked(False) + self.titoloavui.rad_dataprimo.setChecked(False) + self.titoloavui.rad_titolosecondo.setChecked(False) + self.titoloavui.rad_titoloterzo.setChecked(False) + #secondo + if self.titoloavui.rad_numerosecondo.isChecked(): + self.titoloavui.rad_datasecondo.setChecked(False) + self.titoloavui.rad_titolosecondo.setChecked(False) + self.titoloavui.rad_numeroprimo.setChecked(False) + self.titoloavui.rad_numeroterzo.setChecked(False) + if self.titoloavui.rad_datasecondo.isChecked(): + self.titoloavui.rad_numerosecondo.setChecked(False) + self.titoloavui.rad_titolosecondo.setChecked(False) + self.titoloavui.rad_dataprimo.setChecked(False) + self.titoloavui.rad_dataterzo.setChecked(False) + if self.titoloavui.rad_titolosecondo.isChecked(): + self.titoloavui.rad_numerosecondo.setChecked(False) + self.titoloavui.rad_datasecondo.setChecked(False) + self.titoloavui.rad_titoloprimo.setChecked(False) + self.titoloavui.rad_titoloterzo.setChecked(False) + #terzo + if self.titoloavui.rad_numeroterzo.isChecked(): + self.titoloavui.rad_dataterzo.setChecked(False) + self.titoloavui.rad_titoloterzo.setChecked(False) + self.titoloavui.rad_numeroprimo.setChecked(False) + self.titoloavui.rad_numerosecondo.setChecked(False) + if self.titoloavui.rad_dataterzo.isChecked(): + self.titoloavui.rad_numeroterzo.setChecked(False) + self.titoloavui.rad_titoloterzo.setChecked(False) + self.titoloavui.rad_dataprimo.setChecked(False) + self.titoloavui.rad_datasecondo.setChecked(False) + if self.titoloavui.rad_titoloterzo.isChecked(): + self.titoloavui.rad_numeroterzo.setChecked(False) + self.titoloavui.rad_dataterzo.setChecked(False) + self.titoloavui.rad_titoloprimo.setChecked(False) + self.titoloavui.rad_titolosecondo.setChecked(False) + pass + + def returnOk(self): + self.log.info(self.tr("Avanzate Titolo Accettate")) + self.applica() + self.hide() + pass + + def returnKo(self): + self.log.info(self.tr("Avanzate Titolo Rifiutate")) + self.hide() + pass + + def applica(self): + #data + if self.titoloavui.rad_dataprimo.isChecked(): + self.conf.setParam(('docStruct', 'datePos'), 1) + elif self.titoloavui.rad_datasecondo.isChecked(): + self.conf.setParam(('docStruct', 'datePos'), 2) + elif self.titoloavui.rad_dataterzo.isChecked(): + self.conf.setParam(('docStruct', 'datePos'), 3) + else: + self.conf.setParam(('docStruct', 'datePos'), -1) + #numero + if self.titoloavui.rad_numeroprimo.isChecked(): + self.conf.setParam(('docStruct', 'numberPos'), 1) + elif self.titoloavui.rad_numerosecondo.isChecked(): + self.conf.setParam(('docStruct', 'numberPos'), 2) + elif self.titoloavui.rad_numeroterzo.isChecked(): + self.conf.setParam(('docStruct', 'numberPos'), 3) + else: + self.conf.setParam(('docStruct', 'numberPos'), -1) + #titolo + if self.titoloavui.rad_titoloprimo.isChecked(): + self.conf.setParam(('docStruct', 'titlePos'), 1) + elif self.titoloavui.rad_titolosecondo.isChecked(): + self.conf.setParam(('docStruct', 'titlePos'), 2) + elif self.titoloavui.rad_titoloterzo.isChecked(): + self.conf.setParam(('docStruct', 'titlePos'), 3) + else: + self.conf.setParam(('docStruct', 'titlePos'), -1) + #prefisso e suffisso + self.conf.setParam(('docStruct', 'outPrefix'), + self.titoloavui.txt_prefisso.text()) + self.conf.setParam(('docStruct', 'outSuffix'), + self.titoloavui.txt_suffisso.text()) - def fillInterface(self): - try: - #rimepi interfaccia - self.titoloavui.rad_dataprimo.setChecked(self.conf.getParam('docStruct','datePos')==1) - self.titoloavui.rad_datasecondo.setChecked(self.conf.getParam('docStruct','datePos')==2) - self.titoloavui.rad_dataterzo.setChecked(self.conf.getParam('docStruct','datePos')==3) - self.titoloavui.rad_titoloprimo.setChecked(self.conf.getParam('docStruct','titlePos')==1) - self.titoloavui.rad_titolosecondo.setChecked(self.conf.getParam('docStruct','titlePos')==2) - self.titoloavui.rad_titoloterzo.setChecked(self.conf.getParam('docStruct','titlePos')==3) - self.titoloavui.rad_numeroprimo.setChecked(self.conf.getParam('docStruct','numberPos')==1) - self.titoloavui.rad_numerosecondo.setChecked(self.conf.getParam('docStruct','numberPos')==2) - self.titoloavui.rad_numeroterzo.setChecked(self.conf.getParam('docStruct','numberPos')==3) - self.titoloavui.txt_prefisso.setText(self.conf.getParam('docStruct','outPrefix')) - self.titoloavui.txt_suffisso.setText(self.conf.getParam('docStruct','outSuffix')) - except: - self.log.critical(self.tr("AvanzateTitolo: Configurazione non accettata")) - def gestisciBottoni(self): - #PRIMO - if self.titoloavui.rad_numeroprimo.isChecked(): - self.titoloavui.rad_dataprimo.setChecked(False) - self.titoloavui.rad_titoloprimo.setChecked(False) - self.titoloavui.rad_numerosecondo.setChecked(False) - self.titoloavui.rad_numeroterzo.setChecked(False) - if self.titoloavui.rad_dataprimo.isChecked(): - self.titoloavui.rad_numeroprimo.setChecked(False) - self.titoloavui.rad_titoloprimo.setChecked(False) - self.titoloavui.rad_datasecondo.setChecked(False) - self.titoloavui.rad_dataterzo.setChecked(False) - if self.titoloavui.rad_titoloprimo.isChecked(): - self.titoloavui.rad_numeroprimo.setChecked(False) - self.titoloavui.rad_dataprimo.setChecked(False) - self.titoloavui.rad_titolosecondo.setChecked(False) - self.titoloavui.rad_titoloterzo.setChecked(False) - #secondo - if self.titoloavui.rad_numerosecondo.isChecked(): - self.titoloavui.rad_datasecondo.setChecked(False) - self.titoloavui.rad_titolosecondo.setChecked(False) - self.titoloavui.rad_numeroprimo.setChecked(False) - self.titoloavui.rad_numeroterzo.setChecked(False) - if self.titoloavui.rad_datasecondo.isChecked(): - self.titoloavui.rad_numerosecondo.setChecked(False) - self.titoloavui.rad_titolosecondo.setChecked(False) - self.titoloavui.rad_dataprimo.setChecked(False) - self.titoloavui.rad_dataterzo.setChecked(False) - if self.titoloavui.rad_titolosecondo.isChecked(): - self.titoloavui.rad_numerosecondo.setChecked(False) - self.titoloavui.rad_datasecondo.setChecked(False) - self.titoloavui.rad_titoloprimo.setChecked(False) - self.titoloavui.rad_titoloterzo.setChecked(False) - #terzo - if self.titoloavui.rad_numeroterzo.isChecked(): - self.titoloavui.rad_dataterzo.setChecked(False) - self.titoloavui.rad_titoloterzo.setChecked(False) - self.titoloavui.rad_numeroprimo.setChecked(False) - self.titoloavui.rad_numerosecondo.setChecked(False) - if self.titoloavui.rad_dataterzo.isChecked(): - self.titoloavui.rad_numeroterzo.setChecked(False) - self.titoloavui.rad_titoloterzo.setChecked(False) - self.titoloavui.rad_dataprimo.setChecked(False) - self.titoloavui.rad_datasecondo.setChecked(False) - if self.titoloavui.rad_titoloterzo.isChecked(): - self.titoloavui.rad_numeroterzo.setChecked(False) - self.titoloavui.rad_dataterzo.setChecked(False) - self.titoloavui.rad_titoloprimo.setChecked(False) - self.titoloavui.rad_titolosecondo.setChecked(False) - pass - - def returnOk(self): - self.log.info(self.tr("Avanzate Titolo Accettate")) - self.applica() - self.hide() - pass - - def returnKo(self): - self.log.info(self.tr("Avanzate Titolo Rifiutate")) - self.hide() - pass - - def applica(self): - #data - if self.titoloavui.rad_dataprimo.isChecked(): - self.conf.setParam(('docStruct', 'datePos'), 1) - elif self.titoloavui.rad_datasecondo.isChecked(): - self.conf.setParam(('docStruct', 'datePos'), 2) - elif self.titoloavui.rad_dataterzo.isChecked(): - self.conf.setParam(('docStruct', 'datePos'), 3) - else: - self.conf.setParam(('docStruct', 'datePos'), -1) - #numero - if self.titoloavui.rad_numeroprimo.isChecked(): - self.conf.setParam(('docStruct', 'numberPos'), 1) - elif self.titoloavui.rad_numerosecondo.isChecked(): - self.conf.setParam(('docStruct', 'numberPos'), 2) - elif self.titoloavui.rad_numeroterzo.isChecked(): - self.conf.setParam(('docStruct', 'numberPos'), 3) - else: - self.conf.setParam(('docStruct', 'numberPos'), -1) - #titolo - if self.titoloavui.rad_titoloprimo.isChecked(): - self.conf.setParam(('docStruct', 'titlePos'), 1) - elif self.titoloavui.rad_titolosecondo.isChecked(): - self.conf.setParam(('docStruct', 'titlePos'), 2) - elif self.titoloavui.rad_titoloterzo.isChecked(): - self.conf.setParam(('docStruct', 'titlePos'), 3) - else: - self.conf.setParam(('docStruct', 'titlePos'), -1) - #prefisso e suffisso - self.conf.setParam(('docStruct','outPrefix'), self.titoloavui.txt_prefisso.text()) - self.conf.setParam(('docStruct','outSuffix'), self.titoloavui.txt_suffisso.text()) - - class bananaSelezOut(PyQt5.QtWidgets.QWidget): - def __init__(self, confloader=None, logger=None): - PyQt5.QtWidgets.QWidget.__init__(self) - self.selezoutui = Ui_selezout() - self.selezoutui.setupUi(self) - self.conf = confloader - self.log = logger - if self.conf is not None: - self.selezoutui.btn_split.clicked.connect(self.applica) - self.selezoutui.btn_split.clicked.connect(self.splitta) - self.fillInterface() - pass - - def fillInterface(self): - try: - self.selezoutui.cmb_lingua.clear() - self.selezoutui.cmb_lingua.addItems(self.conf.settingsList['languageconf.json'].keys()) - self.selezoutui.cmb_lingua.setCurrentIndex(self.conf.getParam('docStruct','languageIdx')) - self.selezoutui.rad_mainbodyEFile.setChecked(self.conf.getParam('settings', 'saveBodyFile') and self.conf.getParam('settings', 'saveSeparateFiles')) - self.selezoutui.rad_file.setChecked(self.conf.getParam('settings', 'saveSeparateFiles') and not self.conf.getParam('settings', 'saveBodyFile')) - self.selezoutui.rad_mainbody.setChecked(self.conf.getParam('settings', 'saveBodyFile') and not self.conf.getParam('settings', 'saveSeparateFiles')) - self.selezoutui.chk_removeDuplicates.setChecked(self.conf.getParam('settings', 'removeDuplicates')) - self.selezoutui.chk_includeTitle.setChecked(self.conf.getParam('settings', 'includeTitle')) - self.selezoutui.chk_removeBreakWord.setChecked(self.conf.getParam('settings', 'delWordBreak')) - self.selezoutui.chk_cleaDestFolder.setChecked(self.conf.getParam('settings', 'removeOldFiles')) - self.selezoutui.lin_specialChars.setText(''.join(self.conf.getParam('settings', 'delChars'))) - pass - except: - self.log.critical(self.tr("SelezUscita: Configurazione non accettata")) - pass - - def applica(self): - self.log.info(self.tr("Applico Impostazioni File Uscita")) - self.conf.setParam(('docStruct', 'language'), self.selezoutui.cmb_lingua.currentText()) - self.conf.setParam(('docStruct', 'languageIdx'), self.selezoutui.cmb_lingua.currentIndex()) - self.conf.setParam(('settings', 'saveBodyFile'), self.selezoutui.rad_mainbody.isChecked() - | self.selezoutui.rad_mainbodyEFile.isChecked()) - self.conf.setParam(('settings', 'saveSeparateFiles'), self.selezoutui.rad_file.isChecked() - | self.selezoutui.rad_mainbodyEFile.isChecked()) - self.conf.setParam(('settings', 'removeDuplicates'), self.selezoutui.chk_removeDuplicates.isChecked()) - self.conf.setParam(('settings', 'includeTitle'), self.selezoutui.chk_removeDuplicates.isChecked()) - self.conf.setParam(('settings', 'delWordBreak'), self.selezoutui.chk_removeBreakWord.isChecked()) - self.conf.setParam(('settings', 'removeOldFiles'), self.selezoutui.chk_cleaDestFolder.isChecked()) - self.conf.setParam(('settings', 'delChars'), list(self.selezoutui.lin_specialChars.text())) - pass - - def splitta(self): - # costruisco il dizionario di configurazione - prefile = self.conf.inUse - splconf = copy.deepcopy(self.conf.dump()) - lang = copy.deepcopy(self.conf.use('languageconf.json').getParam(splconf['docStruct']['language'])) - splconf['docStruct']['language'] = lang - self.conf.use(prefile) - - #formato nome in uscita - nametemp=[] - for i in range(1,4): - if i == splconf['docStruct']['numberPos'] and splconf['docStruct']['outNumber']: - nametemp.append("{docnum}") - if i == splconf['docStruct']['datePos'] and splconf['docStruct']['outDate']: - nametemp.append(splconf['docStruct']['dateFormats'][splconf['docStruct']['outDateType']]) - if i == splconf['docStruct']['titlePos'] and splconf['docStruct']['outTitle']: - nametemp.append("{title}") - pass - if splconf['docStruct']['outPrefix'] != '': - nametemp.insert(0, splconf['docStruct']['outPrefix']) #inserisco prefisso e suffisso - if splconf['docStruct']['outSuffix'] != '': - nametemp.append(splconf['docStruct']['outSuffix']) - #unisco i pezzi - splconf['docStruct']['outNameFormat'] = splconf['docStruct']['outNameSep'].join(nametemp)+splconf['docStruct']['outExt'] - - #costruisco messageBox - msgb = QMessageBox(parent=self, icon=QMessageBox.Warning, text=self.tr("Sto SPLITTANDO, attendi..")) - msgb.setWindowTitle(self.tr("Sto Splittando..")) - msgb.show() - - @pyqtSlot() - def updateState(msg): - msgb.setText(msg) - # costruisco i thread - - tDict={} - try: - for f in splconf['paths']['fileList']: - splconf['name']=f - tDict[f] = bananaSPLITTER(fileParams=copy.deepcopy(splconf), logger=self.log) - tDict[f].sendStatus.connect(updateState) - tDict[f].run() - #QThreadPool.globalInstance().start(tDict[f]) - except Exception as e: - self.log.error(self.tr(f"Impossibile avviare lo splitter: {e}")) - - msgb.setText(self.tr("FINITO!")) - pass - + def __init__(self, confloader=None, logger=None): + PyQt5.QtWidgets.QWidget.__init__(self) + self.selezoutui = Ui_selezout() + self.selezoutui.setupUi(self) + self.conf = confloader + self.log = logger + if self.conf is not None: + self.selezoutui.btn_split.clicked.connect(self.applica) + self.selezoutui.btn_split.clicked.connect(self.splitta) + self.fillInterface() + pass + + def fillInterface(self): + try: + self.selezoutui.cmb_lingua.clear() + self.selezoutui.cmb_lingua.addItems( + self.conf.settingsList['languageconf.json'].keys()) + self.selezoutui.cmb_lingua.setCurrentIndex( + self.conf.getParam('docStruct', 'languageIdx')) + self.selezoutui.rad_mainbodyEFile.setChecked(self.conf.getParam( + 'settings', 'saveBodyFile') and self.conf.getParam('settings', 'saveSeparateFiles')) + self.selezoutui.rad_file.setChecked(self.conf.getParam( + 'settings', 'saveSeparateFiles') and not self.conf.getParam('settings', 'saveBodyFile')) + self.selezoutui.rad_mainbody.setChecked(self.conf.getParam( + 'settings', 'saveBodyFile') and not self.conf.getParam('settings', 'saveSeparateFiles')) + self.selezoutui.chk_removeDuplicates.setChecked( + self.conf.getParam('settings', 'removeDuplicates')) + self.selezoutui.chk_includeTitle.setChecked( + self.conf.getParam('settings', 'includeTitle')) + self.selezoutui.chk_removeBreakWord.setChecked( + self.conf.getParam('settings', 'delWordBreak')) + self.selezoutui.chk_cleaDestFolder.setChecked( + self.conf.getParam('settings', 'removeOldFiles')) + self.selezoutui.lin_specialChars.setText( + ''.join(self.conf.getParam('settings', 'delChars'))) + pass + except: + self.log.critical(self.tr("SelezUscita: Configurazione non accettata")) + pass + + def applica(self): + self.log.info(self.tr("Applico Impostazioni File Uscita")) + self.conf.setParam(('docStruct', 'language'), + self.selezoutui.cmb_lingua.currentText()) + self.conf.setParam(('docStruct', 'languageIdx'), + self.selezoutui.cmb_lingua.currentIndex()) + self.conf.setParam(('settings', 'saveBodyFile'), self.selezoutui.rad_mainbody.isChecked() + | self.selezoutui.rad_mainbodyEFile.isChecked()) + self.conf.setParam(('settings', 'saveSeparateFiles'), self.selezoutui.rad_file.isChecked() + | self.selezoutui.rad_mainbodyEFile.isChecked()) + self.conf.setParam(('settings', 'removeDuplicates'), + self.selezoutui.chk_removeDuplicates.isChecked()) + self.conf.setParam(('settings', 'includeTitle'), + self.selezoutui.chk_removeDuplicates.isChecked()) + self.conf.setParam(('settings', 'delWordBreak'), + self.selezoutui.chk_removeBreakWord.isChecked()) + self.conf.setParam(('settings', 'removeOldFiles'), + self.selezoutui.chk_cleaDestFolder.isChecked()) + self.conf.setParam(('settings', 'delChars'), list( + self.selezoutui.lin_specialChars.text())) + pass + + def splitta(self): + # costruisco il dizionario di configurazione + prefile = self.conf.inUse + splconf = copy.deepcopy(self.conf.dump()) + lang = copy.deepcopy(self.conf.use( + 'languageconf.json').getParam(splconf['docStruct']['language'])) + splconf['docStruct']['language'] = lang + self.conf.use(prefile) + + #formato nome in uscita + nametemp = [] + for i in range(1, 4): + if i == splconf['docStruct']['numberPos'] and splconf['docStruct']['outNumber']: + nametemp.append("{docnum}") + if i == splconf['docStruct']['datePos'] and splconf['docStruct']['outDate']: + nametemp.append(splconf['docStruct']['dateFormats'] + [splconf['docStruct']['outDateType']]) + if i == splconf['docStruct']['titlePos'] and splconf['docStruct']['outTitle']: + nametemp.append("{title}") + pass + if splconf['docStruct']['outPrefix'] != '': + # inserisco prefisso e suffisso + nametemp.insert(0, splconf['docStruct']['outPrefix']) + if splconf['docStruct']['outSuffix'] != '': + nametemp.append(splconf['docStruct']['outSuffix']) + #unisco i pezzi + splconf['docStruct']['outNameFormat'] = splconf['docStruct']['outNameSep'].join( + nametemp)+splconf['docStruct']['outExt'] + + #costruisco messageBox + msgb = QMessageBox(parent=self, icon=QMessageBox.Warning, + text=self.tr("Sto SPLITTANDO, attendi..")) + msgb.setWindowTitle(self.tr("Sto Splittando..")) + msgb.show() + + @pyqtSlot() + def updateState(msg): + msgb.setText(msg) + # costruisco i thread + + tDict = {} + try: + for f in splconf['paths']['fileList']: + splconf['name'] = f + tDict[f] = bananaSPLITTER( + fileParams=copy.deepcopy(splconf), logger=self.log) + tDict[f].sendStatus.connect(updateState) + tDict[f].run() + #QThreadPool.globalInstance().start(tDict[f]) + except Exception as e: + self.log.error(self.tr(f"Impossibile avviare lo splitter: {e}")) + + msgb.setText(self.tr("FINITO!")) + pass + + class bananaAdvOpt(PyQt5.QtWidgets.QWidget): - - update = pyqtSignal() - - def __init__(self, confloader=None, logger=None): - PyQt5.QtWidgets.QWidget.__init__(self) - self.advoptui = Ui_editconf() - self.advoptui.setupUi(self) - self.conf = confloader - self.log = logger - self.errmsg=None - if self.conf is not None: - self.advoptui.btn_ok.clicked.connect(self.accetta) - self.advoptui.btn_cancel.clicked.connect(self.rifiuta) - self.fillInterface() - pass - - def fillInterface(self): - try: - self.advoptui.txt_confFile.setPlainText(json.dumps(self.conf.dump(),indent=2)) - except: - self.log.critical(self.tr("AdvancedOptions: Configurazione non accettata")) - pass - - def accetta(self): - self.errmsg = QMessageBox() - self.errmsg.setModal(True) - self.errmsg.setWindowTitle(self.tr("Avanzate Globali")) - icon = PyQt5.QtGui.QIcon() - icon.addPixmap(PyQt5.QtGui.QPixmap(":/icons/icons8-smartphone-ram-100.png"), PyQt5.QtGui.QIcon.Normal, PyQt5.QtGui.QIcon.Off) - self.errmsg.setWindowIcon(icon) - try: - self.conf.loads(self.advoptui.txt_confFile.toPlainText()) - self.log.info(self.tr("Parametri inseriti validi, configurazione accettata")) - self.errmsg.setIcon(QMessageBox.Information) - self.errmsg.setText(self.tr("Parametri inseriti validi, configurazione accettata")) - self.errmsg.show() - self.update.emit() - self.hide() - except Exception as e: - self.log.error(self.tr(f"Errore nei parametri! {e}")) - self.errmsg.setIcon(QMessageBox.Critical) - self.errmsg.setText(self.tr(f"Errore nei parametri!\n{e}")) - self.errmsg.show() - pass - - def rifiuta(self): - self.log.info(f"AdvancedOptions: Configurazione Rifiutata") - self.hide() - pass - + + update = pyqtSignal() + + def __init__(self, confloader=None, logger=None): + PyQt5.QtWidgets.QWidget.__init__(self) + self.advoptui = Ui_editconf() + self.advoptui.setupUi(self) + self.conf = confloader + self.log = logger + self.errmsg = None + if self.conf is not None: + self.advoptui.btn_ok.clicked.connect(self.accetta) + self.advoptui.btn_cancel.clicked.connect(self.rifiuta) + self.fillInterface() + pass + + def fillInterface(self): + try: + self.advoptui.txt_confFile.setPlainText( + json.dumps(self.conf.dump(), indent=2)) + except: + self.log.critical(self.tr("AdvancedOptions: Configurazione non accettata")) + pass + + def accetta(self): + self.errmsg = QMessageBox() + self.errmsg.setModal(True) + self.errmsg.setWindowTitle(self.tr("Avanzate Globali")) + icon = PyQt5.QtGui.QIcon() + icon.addPixmap(PyQt5.QtGui.QPixmap(":/icons/icons8-smartphone-ram-100.png"), + PyQt5.QtGui.QIcon.Normal, PyQt5.QtGui.QIcon.Off) + self.errmsg.setWindowIcon(icon) + try: + self.conf.loads(self.advoptui.txt_confFile.toPlainText()) + self.log.info( + self.tr("Parametri inseriti validi, configurazione accettata")) + self.errmsg.setIcon(QMessageBox.Information) + self.errmsg.setText( + self.tr("Parametri inseriti validi, configurazione accettata")) + self.errmsg.show() + self.update.emit() + self.hide() + except Exception as e: + self.log.error(self.tr(f"Errore nei parametri! {e}")) + self.errmsg.setIcon(QMessageBox.Critical) + self.errmsg.setText(self.tr(f"Errore nei parametri!\n{e}")) + self.errmsg.show() + pass + + def rifiuta(self): + self.log.info(f"AdvancedOptions: Configurazione Rifiutata") + self.hide() + pass + + class bananaSplitterInterface(PyQt5.QtWidgets.QWidget): - def __init__(self, confloader=None, logger=None): - PyQt5.QtWidgets.QWidget.__init__(self) - pass - + def __init__(self, confloader=None, logger=None): + PyQt5.QtWidgets.QWidget.__init__(self) + pass + + class spexAbout(PyQt5.QtWidgets.QDialog): - def __init__(self, confloader=None, logger=None): - PyQt5.QtWidgets.QDialog.__init__(self) - self.abt = Ui_about() - self.abt.setupUi(self) - self.abt.lbl_info.setText(self.abt.lbl_info.text().replace('{ver}',confloader.getParam('version'))) - self.show() - pass + def __init__(self, confloader=None, logger=None): + PyQt5.QtWidgets.QDialog.__init__(self) + self.abt = Ui_about() + self.abt.setupUi(self) + self.abt.lbl_info.setText(self.abt.lbl_info.text().replace( + '{ver}', confloader.getParam('version'))) + self.show() + pass ############################################################# ####################### MAIN ################################ ############################################################# + + def except_hook(cls, exception, traceback): - sys.__excepthook__(cls, exception, traceback) + sys.__excepthook__(cls, exception, traceback) + if __name__ == '__main__': - app = PyQt5.QtWidgets.QApplication(sys.argv) - sys.excepthook = except_hook - - try: - print(os.getcwd()) - LOGGER = fancyLogger(filepath=r"./conf/loggerconf.json",fileLog=False) - conf = bananaCONF(workdir=r"./conf", logger=LOGGER) - conf.open() - conf.use("defaults.json") - conf.use(conf.getParam('paths', 'lastUsed')) - - iflan = conf.getParam('settings','uiLang') - trlist = [f":/tr/translations/guimain_{iflan}.qm", - f":/tr/translations/libconfload_{iflan}.qm", - f":/tr/translations/libsplit_{iflan}.qm", - f":/tr/translations/mainwindow_{iflan}.qm", - f":/tr/translations/avanzatetitolo3_{iflan}.qm", - f":/tr/translations/titolow_{iflan}.qm", - f":/tr/translations/selezout_{iflan}.qm", - f":/tr/translations/about_{iflan}.qm"] - qtrlist=[] - - if iflan != 'it': - LOGGER.debug("Carico Traduzioni: ") - for tr in trlist: - qtr = QTranslator() - print(qtr.load(tr),f" {tr}") - app.installTranslator(qtr) - qtrlist.append(qtr) - - except Exception as e: - print(f"Errore main: {e}") - sys.exit() - - window = bananaMain(logger=LOGGER, confloader=conf) - window.show() - rv = app.exec() - print("ExitCode: {}".format(rv)) - sys.exit(rv) - pass + app = PyQt5.QtWidgets.QApplication(sys.argv) + sys.excepthook = except_hook + + try: + print(f"Running directory {os.environ['WORKSPACELOC']}") + print(f"Pythonpath: {os.environ['PYTHONPATH']}") + LOGGER = fancyLogger(filepath=r"./conf/loggerconf.json", fileLog=False) + conf = bananaCONF(workdir=r"./conf", logger=LOGGER) + conf.open() + conf.use("defaults.json") + conf.use(conf.getParam('paths', 'lastUsed')) + + iflan = conf.getParam('settings', 'uiLang') + trlist = [f":/tr/translations/guimain_{iflan}.qm", + f":/tr/translations/libconfload_{iflan}.qm", + f":/tr/translations/libsplit_{iflan}.qm", + f":/tr/translations/mainwindow_{iflan}.qm", + f":/tr/translations/avanzatetitolo3_{iflan}.qm", + f":/tr/translations/titolow_{iflan}.qm", + f":/tr/translations/selezout_{iflan}.qm", + f":/tr/translations/about_{iflan}.qm"] + qtrlist = [] + + if iflan != 'it': + LOGGER.debug("Carico Traduzioni: ") + for tr in trlist: + qtr = QTranslator() + print(qtr.load(tr), f" {tr}") + app.installTranslator(qtr) + qtrlist.append(qtr) + + except Exception as e: + print(f"Errore main: {e}") + sys.exit() + + window = bananaMain(logger=LOGGER, confloader=conf) + window.show() + rv = app.exec() + print("ExitCode: {}".format(rv)) + sys.exit(rv) + pass diff --git a/SPEx/spex/libbananasplit/libconfload.py b/SPEx/spex/libbananasplit/libconfload.py index e9ce68e..d9098dc 100644 --- a/SPEx/spex/libbananasplit/libconfload.py +++ b/SPEx/spex/libbananasplit/libconfload.py @@ -7,107 +7,105 @@ import json,os,glob,copy from PyQt5.QtCore import QObject class bananaCONF(QObject): - ''' - Carica e Salva file di configurazione per bananaSPLITTER - ''' - def __init__(self, workdir=None, logger=None): - try: - QObject.__init__(self) - self.log = logger - self.fileList = None - self.workdir = None - self.inUse = None - self.settingsList = dict() - if workdir is not None: - self.workdir = workdir - os.chdir(workdir) - self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd())) - else: - self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione")) - pass - except Exception as e: - print(f"libConfload Exception: {e}") + ''' + Carica e Salva file di configurazione per bananaSPLITTER + ''' + def __init__(self, workdir=None, logger=None): + try: + QObject.__init__(self) + self.log = logger + self.fileList = None + self.workdir = None + self.inUse = None + self.settingsList = dict() + if workdir is not None: + self.workdir = workdir + os.chdir(workdir) + self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd())) + else: + self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione")) + pass + except Exception as e: + print(f"libConfload Exception: {e}") - def open(self): - self.log.info(self.tr("Carico i file di configurazione")) - self.fileList = glob.glob(r"*.json") - if len(self.fileList) > 0: - for f in self.fileList: - try: - fp = open(f) - tf = json.load(fp) - fName = f.split("\\")[-1] - self.settingsList[fName] = copy.deepcopy(tf) - self.log.info(self.tr("Caricato correttamente: {}").format(fName)) - fp.close() - except json.JSONDecodeError as e: - self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \ - Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno)) - except IOError as ee: - self.log.error(self.tr("Impossibile aprire il file: {}").format(ee)) - except Exception as eee: - self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee)) - else: - self.log.error(self.tr("Non ho trovato alcun file di configurazione!")) - pass - - def reload(self): - self.settingsList = None - self.fileList = None - self.inUse = None - self.open() - pass - - def use(self, toUse): - self.inUse = toUse - return self - - def save(self, fName=None): - if fName is None: - fName=self.inUse - self.log.info(self.tr("Salvo la configurazione: {}").format(fName)) - try: - f=open(fName, 'w') - json.dump(self.settingsList[self.inUse], f, indent='\t') - f.close() - except IOError as e: - self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e)) - except Exception as ei: - self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei)) - pass - - def getFiles(self): - return self.fileList - - def getParam(self, *keys): - rv = self.settingsList[self.inUse] - try: - for k in keys: - rv = rv[k] - return rv - except ValueError as ve: - self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) - return False - pass - - def setParam(self, keys=(), val=None): - sv = self.settingsList[self.inUse] - try: - for k in keys[:-1]: - sv = sv[k] - sv[keys[-1]] = val - return True - except ValueError as ve: - self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) - return False - pass - - def dump(self): - return self.settingsList[self.inUse] - - def loads(self, conf): - jconf = json.loads(conf) - self.settingsList[self.inUse]=jconf + def open(self): + self.log.info(self.tr("Carico i file di configurazione")) + self.fileList = glob.glob(r"*.json") + if len(self.fileList) > 0: + for f in self.fileList: + try: + fp = open(f) + tf = json.load(fp) + fName = f.split("\\")[-1] + self.settingsList[fName] = copy.deepcopy(tf) + self.log.info(self.tr("Caricato correttamente: {}").format(fName)) + fp.close() + except json.JSONDecodeError as e: + self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \ + Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno)) + except IOError as ee: + self.log.error(self.tr("Impossibile aprire il file: {}").format(ee)) + except Exception as eee: + self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee)) + else: + self.log.error(self.tr("Non ho trovato alcun file di configurazione!")) + pass + + def reload(self): + self.settingsList = None + self.fileList = None + self.inUse = None + self.open() + pass + + def use(self, toUse): + self.inUse = toUse + return self + + def save(self, fName=None): + if fName is None: + fName=self.inUse + self.log.info(self.tr("Salvo la configurazione: {}").format(fName)) + try: + f=open(fName, 'w') + json.dump(self.settingsList[self.inUse], f, indent='\t') + f.close() + except IOError as e: + self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e)) + except Exception as ei: + self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei)) + pass + + def getFiles(self): + return self.fileList + + def getParam(self, *keys): + rv = self.settingsList[self.inUse] + try: + for k in keys: + rv = rv[k] + return rv + except ValueError as ve: + self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) + return False + pass + + def setParam(self, keys=(), val=None): + sv = self.settingsList[self.inUse] + try: + for k in keys[:-1]: + sv = sv[k] + sv[keys[-1]] = val + return True + except ValueError as ve: + self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) + return False + pass + + def dump(self): + return self.settingsList[self.inUse] + + def loads(self, conf): + jconf = json.loads(conf) + self.settingsList[self.inUse]=jconf - - \ No newline at end of file diff --git a/SPEx/spex/libbananasplit/libfancylogger.py b/SPEx/spex/libbananasplit/libfancylogger.py index 80f57a8..cfc7424 100644 --- a/SPEx/spex/libbananasplit/libfancylogger.py +++ b/SPEx/spex/libbananasplit/libfancylogger.py @@ -10,92 +10,92 @@ import colorama from PyQt5.QtCore import QObject, pyqtSignal class fancyLogger(QObject): - ''' - Colorizza il logger di python, per un' esperienza stile willy wonka - ''' - sendLog = pyqtSignal(str) - - def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False): - QObject.__init__(self) - try: - with open(filepath, 'r') as fp: - settings = json.load(fp) - fp.close() - colorama.init(convert=True) - self.LRED = colorama.Fore.LIGHTRED_EX - self.RED = colorama.Fore.RED - self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX - self.YELLOW = colorama.Fore.YELLOW - self.LBLUE = colorama.Fore.LIGHTBLUE_EX - self.BLUE = colorama.Fore.BLUE - self.LGREEN = colorama.Fore.LIGHTGREEN_EX - self.LGREEN = colorama.Fore.GREEN - self.WHITE = colorama.Fore.LIGHTWHITE_EX - self.RST = colorama.Style.RESET_ALL - - # Setup Logger - self.LOGGER = logging.getLogger(name) - self.LOGGER.setLevel(logging.DEBUG) - self.LOGGER.propagate = False - FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"])) - if fileLog: - # File Logging - fh = logging.FileHandler((settings["logFile"])) - fh.setLevel(logging.DEBUG) - fh.setFormatter(FORMATTER) - self.LOGGER.addHandler(fh) - if consoleLog: - # Console Logging - cl= logging.StreamHandler(sys.stdout) - cl.setLevel(logging.DEBUG) - cl.setFormatter(FORMATTER) - self.LOGGER.addHandler(cl) - except IOError as e: - print("Impossibile caricare la configurazione del logger: [{}]".format(e)) - except Exception as ee: - print(f"libFancylogger error: {ee}") - pass - - def debug(self, msg="Undefined Debug"): - print(self.LBLUE, end='') - self.LOGGER.debug(msg) - print(self.RST, end='') - self.sendLog.emit(f"DEBUG | {msg}
") - pass - - def info(self, msg="Undefined Info"): - print(self.LGREEN, end='') - self.LOGGER.info(msg) - print(self.RST, end='') - self.sendLog.emit(f"INFO | {msg}
") - pass - - def warn(self, msg="Undefined Warning"): - print(self.LYELLOW, end='') - self.LOGGER.warning(msg) - print(self.RST, end='') - self.sendLog.emit(f"WARNING | {msg}
") - pass - - def error(self, msg="Undefined Error"): - print(self.LRED, end='') - self.LOGGER.error(msg) - print(self.RST, end='') - self.sendLog.emit(f"ERROR | {msg}
") - pass - - def critical(self, msg="Undefined Critical"): - print(self.RED, end='') - self.LOGGER.critical(msg) - print(self.RST, end='') - self.sendLog.emit(f"CRITICAL | {msg}
") - pass - - def testColors(self): - self.debug("Test Debug") - self.info("Test Info") - self.warn("Test Warning") - self.error("Test Error") - self.critical("Test Critical") - pass - \ No newline at end of file + ''' + Colorizza il logger di python, per un' esperienza stile willy wonka + ''' + sendLog = pyqtSignal(str) + + def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False): + QObject.__init__(self) + try: + with open(filepath, 'r') as fp: + settings = json.load(fp) + fp.close() + colorama.init(convert=True) + self.LRED = colorama.Fore.LIGHTRED_EX + self.RED = colorama.Fore.RED + self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX + self.YELLOW = colorama.Fore.YELLOW + self.LBLUE = colorama.Fore.LIGHTBLUE_EX + self.BLUE = colorama.Fore.BLUE + self.LGREEN = colorama.Fore.LIGHTGREEN_EX + self.LGREEN = colorama.Fore.GREEN + self.WHITE = colorama.Fore.LIGHTWHITE_EX + self.RST = colorama.Style.RESET_ALL + + # Setup Logger + self.LOGGER = logging.getLogger(name) + self.LOGGER.setLevel(logging.DEBUG) + self.LOGGER.propagate = False + FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"])) + if fileLog: + # File Logging + fh = logging.FileHandler((settings["logFile"])) + fh.setLevel(logging.DEBUG) + fh.setFormatter(FORMATTER) + self.LOGGER.addHandler(fh) + if consoleLog: + # Console Logging + cl= logging.StreamHandler(sys.stdout) + cl.setLevel(logging.DEBUG) + cl.setFormatter(FORMATTER) + self.LOGGER.addHandler(cl) + except IOError as e: + print("Impossibile caricare la configurazione del logger: [{}]".format(e)) + except Exception as ee: + print(f"libFancylogger error: {ee}") + pass + + def debug(self, msg="Undefined Debug"): + print(self.LBLUE, end='') + self.LOGGER.debug(msg) + print(self.RST, end='') + self.sendLog.emit(f"DEBUG | {msg}
") + pass + + def info(self, msg="Undefined Info"): + print(self.LGREEN, end='') + self.LOGGER.info(msg) + print(self.RST, end='') + self.sendLog.emit(f"INFO | {msg}
") + pass + + def warn(self, msg="Undefined Warning"): + print(self.LYELLOW, end='') + self.LOGGER.warning(msg) + print(self.RST, end='') + self.sendLog.emit(f"WARNING | {msg}
") + pass + + def error(self, msg="Undefined Error"): + print(self.LRED, end='') + self.LOGGER.error(msg) + print(self.RST, end='') + self.sendLog.emit(f"ERROR | {msg}
") + pass + + def critical(self, msg="Undefined Critical"): + print(self.RED, end='') + self.LOGGER.critical(msg) + print(self.RST, end='') + self.sendLog.emit(f"CRITICAL | {msg}
") + pass + + def testColors(self): + self.debug("Test Debug") + self.info("Test Info") + self.warn("Test Warning") + self.error("Test Error") + self.critical("Test Critical") + pass + \ No newline at end of file diff --git a/SPEx/spex/libbananasplit/libsplit.py b/SPEx/spex/libbananasplit/libsplit.py index 2470643..8b15d3c 100644 --- a/SPEx/spex/libbananasplit/libsplit.py +++ b/SPEx/spex/libbananasplit/libsplit.py @@ -10,397 +10,395 @@ import time, parse, re, copy, os, json import traceback class bananaSPLITTER(QObject): - - sendStatus = pyqtSignal(str) - - def __init__(self, fileParams=None, logger=None): - try: - QObject.__init__(self) - self.fileParams = fileParams - self.log = logger - self.rawFile = None - self.status = "first" - self.contentList = list() - self.bodyCounter=0 - self.duplicateNumber=0 - #self.log.debug(f"Configurazione: \n {json.dumps(fileParams, indent=2)}") - if fileParams is not None: - self.log.debug(self.tr("Sto operando sul file: {}..").format(self.fileParams['name'])) - self.paths = self.fileParams['paths'] - self.docStruct = self.fileParams['docStruct'] - self.settings = self.fileParams['settings'] - self.fileName = self.fileParams['name'] - self.outPath = self.paths['OUTworkPath']+slugify(self.fileName)+'/' - self.beginTime = time.time() - pass - else: - self.log.critical(self.tr("Non e' stato fornito il nome di alcun file da splittare!")) - except Exception as e: - print(f"libSplit error: {e}") - pass - - def run(self): - self.log.info(self.tr("Nuovo SPLITTER su file: {}").format(self.fileName)) - self.sendStatus.emit(self.tr(f"Inizio {self.fileName}")) - try: - self.openFile() - self.remEmptyLines() - if self.docStruct['fileVersNew']: - self.newSplitFile() - else: - self.splitFile() - - if self.settings['removeDuplicates']: - self.log.info(self.tr("Controllo se ci sono dei duplicati..")) - self.removeDuplicates() - else: - for idx, ff in enumerate(self.contentList): - ff['duplicate']=False - self.contentList[idx]=ff - self.log.warn(self.tr("Salto il controllo dei duplicati..")) - # se il parse e la rimozione dei duplicati e' andata bene - # preparo e inizio il salvataggio - if os.path.exists(self.outPath): - if self.settings['removeOldFiles']: - #os.chdir(self.outPath) - for f in os.listdir(self.outPath): - os.remove(self.outPath+f) - else: - raise FileExistsError(self.tr("Non posso sovrascrivere i vecchi file, eliminali manualmente!")) - else: - os.mkdir(self.outPath) - #os.chdir(self.outPath) - if self.settings['saveSeparateFiles']: - self.saveSeparate() - if self.settings['saveBodyFile']: - 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! [{}]") - .format(self.fileParams['name'],ee)) - except FileExistsError as fe: - self.log.critical(fe) - except Exception as ee: - traceback.print_exc() - self.log.warn(ee) - pass - - def openFile(self): - try: - #os.chdir(self.paths["INworkPath"]) - self.log.info(self.tr("Carico il contenuto..")) - fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding']) - self.rawFile = fp.readlines() - fp.close() - except IOError as e: - self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e)) - raise BaseException("OpenFile") - os.rmdir(self.outPath) - except Exception as ee: - print(ee) - pass + sendStatus = pyqtSignal(str) + def __init__(self, fileParams=None, logger=None): + try: + QObject.__init__(self) + self.fileParams = fileParams + self.log = logger + self.rawFile = None + self.status = "first" + self.contentList = list() + self.bodyCounter=0 + self.duplicateNumber=0 + #self.log.debug(f"Configurazione: \n {json.dumps(fileParams, indent=2)}") + if fileParams is not None: + self.log.debug(self.tr("Sto operando sul file: {}..").format(self.fileParams['name'])) + self.paths = self.fileParams['paths'] + self.docStruct = self.fileParams['docStruct'] + self.settings = self.fileParams['settings'] + self.fileName = self.fileParams['name'] + self.outPath = self.paths['OUTworkPath']+slugify(self.fileName)+'/' + self.beginTime = time.time() + pass + else: + self.log.critical(self.tr("Non e' stato fornito il nome di alcun file da splittare!")) + except Exception as e: + print(f"libSplit error: {e}") + pass + + def run(self): + self.log.info(self.tr("Nuovo SPLITTER su file: {}").format(self.fileName)) + self.sendStatus.emit(self.tr(f"Inizio {self.fileName}")) + try: + self.openFile() + self.remEmptyLines() + if self.docStruct['fileVersNew']: + self.newSplitFile() + else: + self.splitFile() + + if self.settings['removeDuplicates']: + self.log.info(self.tr("Controllo se ci sono dei duplicati..")) + self.removeDuplicates() + else: + for idx, ff in enumerate(self.contentList): + ff['duplicate']=False + self.contentList[idx]=ff + self.log.warn(self.tr("Salto il controllo dei duplicati..")) + # se il parse e la rimozione dei duplicati e' andata bene + # preparo e inizio il salvataggio + if os.path.exists(self.outPath): + if self.settings['removeOldFiles']: + #os.chdir(self.outPath) + for f in os.listdir(self.outPath): + os.remove(self.outPath+f) + else: + raise FileExistsError(self.tr("Non posso sovrascrivere i vecchi file, eliminali manualmente!")) + else: + os.mkdir(self.outPath) + #os.chdir(self.outPath) + if self.settings['saveSeparateFiles']: + self.saveSeparate() + if self.settings['saveBodyFile']: + 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! [{}]") + .format(self.fileParams['name'],ee)) + except FileExistsError as fe: + self.log.critical(fe) + except Exception as ee: + traceback.print_exc() + self.log.warn(ee) + pass + + def openFile(self): + try: + #os.chdir(self.paths["INworkPath"]) + self.log.info(self.tr("Carico il contenuto..")) + fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding']) + self.rawFile = fp.readlines() + fp.close() + except IOError as e: + self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e)) + raise BaseException("OpenFile") + os.rmdir(self.outPath) + except Exception as ee: + print(ee) + pass - def remEmptyLines(self): - self.log.info(self.tr("Elimino righe vuote e caratteri inutili..")) - tempContent = [] - try: - for ll in self.rawFile: - for c in self.settings['delChars']: - ll = ll.replace(c,'') - if ll not in ['\n', '\r', '\r\n']: - tempContent.append(ll) - self.rawFile = copy.deepcopy(tempContent) - self.rawFile.append('\n') #linea vuota finale per essere sicuri di parsare bene - return True - except: - self.log.error(self.tr("Errore inaspettato durante l'eliminazione delle righe vuote!")) - raise BaseException("DelLines") - del tempContent + def remEmptyLines(self): + self.log.info(self.tr("Elimino righe vuote e caratteri inutili..")) + tempContent = [] + try: + for ll in self.rawFile: + for c in self.settings['delChars']: + ll = ll.replace(c,'') + if ll not in ['\n', '\r', '\r\n']: + tempContent.append(ll) + self.rawFile = copy.deepcopy(tempContent) + self.rawFile.append('\n') #linea vuota finale per essere sicuri di parsare bene + return True + except: + self.log.error(self.tr("Errore inaspettato durante l'eliminazione delle righe vuote!")) + raise BaseException("DelLines") + del tempContent - def newSplitFile(self): #porting del codice dal programma originale - self.log.info(self.tr("Individuo il contenuto..")) - self.bodyCounter=0 - self.duplicateNumber=0 - docNumber = 0 - docSkipped = 0 - docDate = {} - title = '' - prevLine = '' - newsPaperName = '' - titleBegin = True - newsName = False - tempBody = list() - - for l in self.rawFile: #per ogni linea del file - l=l.replace('\xa0', ' ') - lineWords = l.lstrip().split(' ') #dividi la riga in parole - if self.status == 'first': - try: - # ricerco la data - if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: - try: - docDate=parse.parse(self.docStruct['dateFormat'],l).named - docDate['month']=docDate['month'].lstrip().rstrip().capitalize() - docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 - # dopo la data inizia il titolo, ma prima si cerca il nome del giornale - except: - self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]"). format(l.strip('\r\n'))) - pass - elif lineWords[0].upper() in self.docStruct['language']['headWords']: - #cambio stato e inizializzo un nuovo documento da riempire - self.status = 'head' - newDoc=dict() - newDoc['title']=title - newDoc['date']=docDate - newDoc['newsPaperName'] = newsPaperName - titleBegin = False - newsName = False - else: - if titleBegin: - title = l.strip().capitalize() - titleBegin = False - newsName = True - elif newsName: - if self.settings['getNewsPaperName']: - try: - if l.strip(): - newsPaperName = l.strip() - else: - newsPaperName = self.settings['nameNotFoundStr'] - except: - self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\ - controlla i file di uscita! [{}]").format(l.strip())) - else: - newsPaperName = self.settings['nameNotFoundStr'] - newsName = False - except IndexError: - self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!")) - pass - elif self.status == 'head': - tempContent = list() - #doppio check per trovare l'inizio del corpo documento - if re.match(self.docStruct['beginOfDocument'],l): - self.status='body' - #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 - #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 - 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())) - self.status = 'tail' - anomaly = True - elif not lineWords[0].upper() in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine - if self.settings['delLF']: - tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo - else: - tempBody.append(l) - else: - self.status = 'tail' - anomaly = False - - pass - elif self.status == 'tail': - if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None): - self.status = 'first' - anomaly = False - titleBegin = True - if self.settings['delWordBreak']: - tempContent=[ll.replace('-\n', '') for ll in tempContent] - newDoc['content']=copy.deepcopy(''.join(tempBody)) - self.contentList.append(copy.deepcopy(newDoc)) - tempBody=list() - self.bodyCounter +=1 - pass - else: - self.log.critical(self.tr("Stato Interno Sconosciuto")) - prevLine=l #salva sempre e comunque il contenuto della linea precedente - pass - #ricerca terminata, espongo i risultati - self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter)) - if docSkipped > 0: - self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped)) - pass - pass - - def splitFile(self): #porting del codice dal programma originale - self.log.info(self.tr("Individuo il contenuto..")) - self.bodyCounter=0 - self.duplicateNumber=0 - docNumber = 0 - docSkipped = 0 - docDate = {} - title = '' - prevLine = '' - newsPaperName = '' - titleBegin = False - tempBody = list() - docSep=re.compile(self.docStruct['docSep']) - - for l in self.rawFile: #per ogni linea del file - lineWords = l.lstrip().split(' ') #dividi la riga in parole - if self.status == 'first': - #prendo il numero di documento per vedere se ci sono buchi - try: - try: - nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named - if nn["current"]-docNumber==1: - pass - else: - 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"])) - docSkipped+=1 - docNumber = nn["current"] - except: - pass #non segnalare eccezione se il parse fallisce - # ricerco la data - if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: - try: - docDate=parse.parse(self.docStruct['dateFormat'],l).named - docDate['month']=docDate['month'].lstrip().rstrip().capitalize() - docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 - title = '' - titleBegin=True - # dopo la data inizia il titolo, ma prima si cerca il nome del giornale - if self.settings['getNewsPaperName']: - try: - if prevLine.split(' ')[0].strip().isalpha(): - newsPaperName = prevLine.strip() - else: - newsPaperName = self.settings['nameNotFoundStr'] - except: - self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\ - controlla i file di uscita! [{}]").format(prevLine.strip())) - else: - newsPaperName = self.settings['nameNotFoundStr'] - except: - self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]").format(l.strip('\r\n'))) - pass - elif lineWords[0] in self.docStruct['language']['headWords']: - #cambio stato e inizializzo un nuovo documento da riempire - self.status = 'head' - newDoc=dict() - newDoc['title']=title - newDoc['date']=docDate - newDoc['newsPaperName'] = newsPaperName - titleBegin=False - else: - if titleBegin: - title += l.strip().capitalize() - except IndexError: - self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!")) - pass - elif self.status == 'head': - tempContent = list() - 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 - self.status = 'body' - pass - elif self.status == 'body': - if not lineWords[0] in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine - if self.settings['delLF']: - tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo - else: - tempBody.append(l) - else: - self.status = 'tail' - anomaly = False - 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\ - L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t[{}]").format(docNumber, l.strip())) - self.status = 'tail' - anomaly = True - pass - elif self.status == 'tail': - if docSep.match(l) is not None or anomaly: - self.status = 'first' - anomaly = False - if self.settings['delWordBreak']: - tempContent=[ll.replace('-\n', '') for ll in tempContent] - newDoc['content']=copy.deepcopy(''.join(tempBody)) - self.contentList.append(copy.deepcopy(newDoc)) - tempBody=list() - self.bodyCounter +=1 - pass - else: - self.log.critical(self.tr("Stato Interno Sconosciuto")) - prevLine=l #salva sempre e comunque il contenuto della linea precedente - pass - #ricerca terminata, espongo i risultati - self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter)) - if docSkipped > 0: - self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped)) - pass - pass + def newSplitFile(self): #porting del codice dal programma originale + self.log.info(self.tr("Individuo il contenuto..")) + self.bodyCounter=0 + self.duplicateNumber=0 + docNumber = 0 + docSkipped = 0 + docDate = {} + title = '' + prevLine = '' + newsPaperName = '' + titleBegin = True + newsName = False + tempBody = list() + + for l in self.rawFile: #per ogni linea del file + l=l.replace('\xa0', ' ') + lineWords = l.lstrip().split(' ') #dividi la riga in parole + if self.status == 'first': + try: + # ricerco la data + if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: + try: + docDate=parse.parse(self.docStruct['dateFormat'],l).named + docDate['month']=docDate['month'].lstrip().rstrip().capitalize() + docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 + # dopo la data inizia il titolo, ma prima si cerca il nome del giornale + except: + self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]"). format(l.strip('\r\n'))) + pass + elif lineWords[0].upper() in self.docStruct['language']['headWords']: + #cambio stato e inizializzo un nuovo documento da riempire + self.status = 'head' + newDoc=dict() + newDoc['title']=title + newDoc['date']=docDate + newDoc['newsPaperName'] = newsPaperName + titleBegin = False + newsName = False + else: + if titleBegin: + title = l.strip().capitalize() + titleBegin = False + newsName = True + elif newsName: + if self.settings['getNewsPaperName']: + try: + if l.strip(): + newsPaperName = l.strip() + else: + newsPaperName = self.settings['nameNotFoundStr'] + except: + self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\ + controlla i file di uscita! [{}]").format(l.strip())) + else: + newsPaperName = self.settings['nameNotFoundStr'] + newsName = False + except IndexError: + self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!")) + pass + elif self.status == 'head': + tempContent = list() + #doppio check per trovare l'inizio del corpo documento + if re.match(self.docStruct['beginOfDocument'],l): + self.status='body' + #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 + #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 + 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())) + self.status = 'tail' + anomaly = True + elif not lineWords[0].upper() in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine + if self.settings['delLF']: + tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo + else: + tempBody.append(l) + else: + self.status = 'tail' + anomaly = False + + pass + elif self.status == 'tail': + if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None): + self.status = 'first' + anomaly = False + titleBegin = True + if self.settings['delWordBreak']: + tempContent=[ll.replace('-\n', '') for ll in tempContent] + newDoc['content']=copy.deepcopy(''.join(tempBody)) + self.contentList.append(copy.deepcopy(newDoc)) + tempBody=list() + self.bodyCounter +=1 + pass + else: + self.log.critical(self.tr("Stato Interno Sconosciuto")) + prevLine=l #salva sempre e comunque il contenuto della linea precedente + pass + #ricerca terminata, espongo i risultati + self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter)) + if docSkipped > 0: + self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped)) + pass + pass + + def splitFile(self): #porting del codice dal programma originale + self.log.info(self.tr("Individuo il contenuto..")) + self.bodyCounter=0 + self.duplicateNumber=0 + docNumber = 0 + docSkipped = 0 + docDate = {} + title = '' + prevLine = '' + newsPaperName = '' + titleBegin = False + tempBody = list() + docSep=re.compile(self.docStruct['docSep']) + + for l in self.rawFile: #per ogni linea del file + lineWords = l.lstrip().split(' ') #dividi la riga in parole + if self.status == 'first': + #prendo il numero di documento per vedere se ci sono buchi + try: + try: + nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named + if nn["current"]-docNumber==1: + pass + else: + 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"])) + docSkipped+=1 + docNumber = nn["current"] + except: + pass #non segnalare eccezione se il parse fallisce + # ricerco la data + if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: + try: + docDate=parse.parse(self.docStruct['dateFormat'],l).named + docDate['month']=docDate['month'].lstrip().rstrip().capitalize() + docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 + title = '' + titleBegin=True + # dopo la data inizia il titolo, ma prima si cerca il nome del giornale + if self.settings['getNewsPaperName']: + try: + if prevLine.split(' ')[0].strip().isalpha(): + newsPaperName = prevLine.strip() + else: + newsPaperName = self.settings['nameNotFoundStr'] + except: + self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\ + controlla i file di uscita! [{}]").format(prevLine.strip())) + else: + newsPaperName = self.settings['nameNotFoundStr'] + except: + self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]").format(l.strip('\r\n'))) + pass + elif lineWords[0] in self.docStruct['language']['headWords']: + #cambio stato e inizializzo un nuovo documento da riempire + self.status = 'head' + newDoc=dict() + newDoc['title']=title + newDoc['date']=docDate + newDoc['newsPaperName'] = newsPaperName + titleBegin=False + else: + if titleBegin: + title += l.strip().capitalize() + except IndexError: + self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!")) + pass + elif self.status == 'head': + tempContent = list() + 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 + self.status = 'body' + pass + elif self.status == 'body': + if not lineWords[0] in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine + if self.settings['delLF']: + tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo + else: + tempBody.append(l) + else: + self.status = 'tail' + anomaly = False + 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\ + L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t[{}]").format(docNumber, l.strip())) + self.status = 'tail' + anomaly = True + pass + elif self.status == 'tail': + if docSep.match(l) is not None or anomaly: + self.status = 'first' + anomaly = False + if self.settings['delWordBreak']: + tempContent=[ll.replace('-\n', '') for ll in tempContent] + newDoc['content']=copy.deepcopy(''.join(tempBody)) + self.contentList.append(copy.deepcopy(newDoc)) + tempBody=list() + self.bodyCounter +=1 + pass + else: + self.log.critical(self.tr("Stato Interno Sconosciuto")) + prevLine=l #salva sempre e comunque il contenuto della linea precedente + pass + #ricerca terminata, espongo i risultati + self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter)) + if docSkipped > 0: + self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped)) + pass + pass - def removeDuplicates(self): - titleList=[] - duplicateList=[] - for idx, ff in enumerate(self.contentList): - if ff['title'] not in titleList: - titleList.append(ff['title']) - ff['duplicate']=False - self.contentList[idx]=ff - pass - else: - if ff['title'] not in duplicateList: - duplicateList.append(ff['title']) - if self.settings['showRemovedDuplicates']: - self.log.info(self.tr("Duplicato: {}").format(ff['title'].strip())) - ff['duplicate'] = True - self.contentList[idx]=ff - self.duplicateNumber+=1 - self.log.info(self.tr("Ho rimosso {} duplicati di {} articoli..").format(self.duplicateNumber, len(duplicateList))) - pass - - def saveSeparate(self): - outFileCounter = 0 - self.paths['OUTworkPath']=self.paths['OUTworkPath']+slugify(self.fileName) - self.log.info(self.tr("Salvo gli articoli in file separati...")) - self.log.debug(self.tr("Persorso: {0}").format(self.outPath)) - for ff in self.contentList: - try: - if ff['duplicate'] == False: - fName=self.docStruct['outNameFormat'].format(title=slugify(ff['title'][:self.docStruct['maxTitleLen']]),\ - filename=slugify(self.fileName),\ - docnum=outFileCounter,\ - papername=ff['newsPaperName'].strip(),\ - **ff['date']) - out=open(self.outPath+'{0}'.format(fName),'wb') - if self.settings['includeTitle']: - ff['content'] = ff['title']+os.linesep+ff['content'] - out.write(ff['content'].encode(self.settings['encoding'])) - out.close() - outFileCounter+=1 - except IOError as e: - self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e)) - continue - except KeyError as ke: - self.log.error(self.tr(f"Chiave {ke} non trovata per:{outFileCounter} {ff['title']} ")) - except Exception as ee: - traceback.print_exc() - self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}")) - if outFileCounter < self.bodyCounter: - self.log.error(self.tr("Ho salvato meno file rispetto a quelli trovati!")) - pass - - def saveBody(self): - 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)) - #os.chdir(self.outPath) - try: - fName=slugify(self.fileName) - fName='BODYFILE_{0}.txt'.format(fName[:self.docStruct['maxTitleLen']]) - fileContent = os.linesep.join([cc['content'] for cc in self.contentList]) - out=open(self.outPath+'{0}'.format(fName),'wb') - out.write(fileContent.encode(self.settings['encoding'])) - out.close() - except IOError as e: - self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e)) - except Exception as ee: - self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}")) - pass + def removeDuplicates(self): + titleList=[] + duplicateList=[] + for idx, ff in enumerate(self.contentList): + if ff['title'] not in titleList: + titleList.append(ff['title']) + ff['duplicate']=False + self.contentList[idx]=ff + pass + else: + if ff['title'] not in duplicateList: + duplicateList.append(ff['title']) + if self.settings['showRemovedDuplicates']: + self.log.info(self.tr("Duplicato: {}").format(ff['title'].strip())) + ff['duplicate'] = True + self.contentList[idx]=ff + self.duplicateNumber+=1 + self.log.info(self.tr("Ho rimosso {} duplicati di {} articoli..").format(self.duplicateNumber, len(duplicateList))) + pass + + def saveSeparate(self): + outFileCounter = 0 + self.paths['OUTworkPath']=self.paths['OUTworkPath']+slugify(self.fileName) + self.log.info(self.tr("Salvo gli articoli in file separati...")) + self.log.debug(self.tr("Persorso: {0}").format(self.outPath)) + for ff in self.contentList: + try: + if ff['duplicate'] == False: + fName=self.docStruct['outNameFormat'].format(title=slugify(ff['title'][:self.docStruct['maxTitleLen']]),\ + filename=slugify(self.fileName),\ + docnum=outFileCounter,\ + papername=ff['newsPaperName'].strip(),\ + **ff['date']) + out=open(self.outPath+'{0}'.format(fName),'wb') + if self.settings['includeTitle']: + ff['content'] = ff['title']+os.linesep+ff['content'] + out.write(ff['content'].encode(self.settings['encoding'])) + out.close() + outFileCounter+=1 + except IOError as e: + self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e)) + continue + except KeyError as ke: + self.log.error(self.tr(f"Chiave {ke} non trovata per:{outFileCounter} {ff['title']} ")) + except Exception as ee: + traceback.print_exc() + self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}")) + if outFileCounter < self.bodyCounter: + self.log.error(self.tr("Ho salvato meno file rispetto a quelli trovati!")) + pass + + def saveBody(self): + 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)) + #os.chdir(self.outPath) + try: + fName=slugify(self.fileName) + fName='BODYFILE_{0}.txt'.format(fName[:self.docStruct['maxTitleLen']]) + fileContent = os.linesep.join([cc['content'] for cc in self.contentList]) + out=open(self.outPath+'{0}'.format(fName),'wb') + out.write(fileContent.encode(self.settings['encoding'])) + out.close() + except IOError as e: + self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e)) + except Exception as ee: + self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}")) + pass - - \ No newline at end of file + + \ No newline at end of file