diff --git a/LuftmenschQt.py b/LuftmenschQt.py index 1d34d1e..5d0c1b9 100644 --- a/LuftmenschQt.py +++ b/LuftmenschQt.py @@ -1,10 +1,8 @@ -from PyQt5.QtCore import (QThread, pyqtSignal,QThreadPool,pyqtSlot,QRunnable,QObject,Qt) -from PyQt5.QtWidgets import (QApplication, QDialog, QMainWindow,QLabel,QFileDialog,QAction, - QProgressBar, QPushButton,QMessageBox,QLineEdit,QMenu, - QErrorMessage,QGraphicsOpacityEffect,QComboBox,QHBoxLayout, - QGridLayout,QSpacerItem,QSizePolicy,QFrame,QStackedLayout, - QTextEdit,QTableView,QStyle,QCheckBox,QVBoxLayout,QWidget, - QDesktopWidget,QListView,QStyleFactory) +from PyQt5.QtCore import (pyqtSignal,QThreadPool,pyqtSlot,QRunnable,QObject,Qt) +from PyQt5.QtWidgets import (QApplication, QMainWindow,QLabel,QFileDialog,QAction, + QProgressBar, QPushButton,QMessageBox,QLineEdit,QMenu,QComboBox, + QHBoxLayout,QStackedLayout,QGraphicsOpacityEffect, + QCheckBox,QVBoxLayout,QWidget,QListView) from PyQt5.QtGui import (QIcon,QFont,QPixmap,QCursor) import time @@ -16,16 +14,8 @@ from win32com import client from docx import Document from re import findall -# from selenium import webdriver -# from selenium.webdriver.support import expected_conditions as ec -# from selenium.webdriver.common.by import By -# from selenium.webdriver.support.ui import WebDriverWait -# from selenium.webdriver.support.select import Select -# from selenium.common.exceptions import TimeoutException -# from selenium.common.exceptions import WebDriverException -# import pandas as pd -# import openpyxl -# from PIL import Image, ImageOps +from webbrowser import open as op + if hasattr(Qt, 'AA_EnableHighDpiScaling'): QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) @@ -47,6 +37,13 @@ def resource_path(relative_path): username=getpass.getuser() defaultDir='D:\\Usuarios\\'+username+'\\Documents' +years=[str(i) for i in range(2010,2021)] +years.reverse() +months=[str(i) for i in range(1,13)] +for i in range(len(months)): + if len(months[i])==1: + months[i]='0'+months[i] +months.reverse() choices=['1. Convertir PDF en PDF/A', '2. Obtener PDF con páginas del mismo tamaño', '3. Unir varios archivos PDF', @@ -54,6 +51,7 @@ def resource_path(relative_path): '5. Crear archivo .zip de Requerimientos y Cartas', '6. Crear archivo .zip de Valores', '7. Generar archivo de texto para solicitar descarga de LE'] + fontOne = QFont("Helvetica", 9) fontTwo=QFont("Helvetica", 9) fontThree=QFont('Consolas', 11) #Done message font @@ -88,57 +86,57 @@ def is_opened(self): def run(self): - - if self.is_opened() == True: - self.signals.alert.emit('Error2') - else: - - - done=False - count=0 - while not done: - try: - backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') - done=True - except PermissionError: - print('Permission denied') - count+=1 - time.sleep(count) - time.sleep(1) - DestDir=os.path.abspath(os.path.join(self.SaveAs, '..')) - tempDocx='\\tempword.docx' - documento = Document() - documento.save(DestDir+tempDocx) - word = client.DispatchEx('Word.Application') - worddoc = word.Documents.Open(DestDir+tempDocx,ReadOnly = 1) - worddoc.SaveAs(self.SaveAs,FileFormat = 17) - worddoc.Close(True) - word.Quit() - os.remove(DestDir+tempDocx) - pdf=fitz.open(self.SaveAs) - opened_file=fitz.open(backup) - pdf.insertPDF(opened_file) - opened_file.close() - pdf.deletePage(0) - pdf.saveIncr() - pdf.close() - time.sleep(1) - done=False - count=0 - while not done: - try: - os.remove(backup) - done=True - except PermissionError: - print('Permission denied') - count+=1 - time.sleep(count) - if self.state==2: - from subprocess import Popen - Popen([self.SaveAs],shell=True) - time.sleep(1) - self.signals.finished.emit('Done') - + try: + if self.is_opened() == True: + self.signals.alert.emit('Error2') + else: + + done=False + count=0 + while not done: + try: + backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') + done=True + except PermissionError: + print('Permission denied') + count+=1 + time.sleep(count) + time.sleep(1) + DestDir=os.path.abspath(os.path.join(self.SaveAs, '..')) + tempDocx='\\tempword.docx' + documento = Document() + documento.save(DestDir+tempDocx) + word = client.DispatchEx('Word.Application') + worddoc = word.Documents.Open(DestDir+tempDocx,ReadOnly = 1) + worddoc.SaveAs(self.SaveAs,FileFormat = 17) + worddoc.Close(True) + word.Quit() + os.remove(DestDir+tempDocx) + pdf=fitz.open(self.SaveAs) + opened_file=fitz.open(backup) + pdf.insertPDF(opened_file) + opened_file.close() + pdf.deletePage(0) + pdf.saveIncr() + pdf.close() + time.sleep(1) + done=False + count=0 + while not done: + try: + os.remove(backup) + done=True + except PermissionError: + print('Permission denied') + count+=1 + time.sleep(count) + if self.state==2: + from subprocess import Popen + Popen([self.SaveAs],shell=True) + time.sleep(1) + self.signals.finished.emit('Done') + except Exception as e: + self.signals.alert.emit(str(type(e))) def kill(self): self.is_killed = True @@ -208,7 +206,7 @@ def initUI(self): self.h2.addStretch() self.start = QPushButton('Ejecutar', self) self.start.setStyleSheet(self.style1) - self.start.setFocus() + # self.start.setFocus() self.start.setFont(fontOne) self.start.setMinimumHeight(35) self.start.setEnabled(True) @@ -261,8 +259,8 @@ def initUI(self): self.setLayout(self.mainLayout) self.mainLayout.setAlignment(Qt.AlignCenter) - quit = QAction("Quit", self) - quit.triggered.connect(self.closeEvent) + # quit = QAction("Quit", self) + # quit.triggered.connect(self.closeEvent) def started(self): @@ -314,7 +312,8 @@ def openFileNameDialogOne(self): def alert(self, msg): if msg=='Error2': self.error('Cierra el PDF sobre el cual deseas guardar el resultado.') - + else: + self.error('Ocurrió un error inesperado: '+msg) self.clean() def finished(self, msg): if msg=='Done': @@ -329,24 +328,24 @@ def finished(self, msg): self.labelThree.show() self.progress.hide() - def closeEvent(self, event): - close = QMessageBox() - # close.setWindowTitle(self.title) - close.setWindowTitle("¿Seguro?") - close.setWindowIcon(QIcon(icon)) - close.setFont(fontTwo) - close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") - # close.setText("¿Estás seguro?") - # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') - close.setText("¿Estás seguro que deseas salir?") - close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) - close = close.exec() + # def closeEvent(self, event): + # close = QMessageBox() + # # close.setWindowTitle(self.title) + # close.setWindowTitle("¿Seguro?") + # close.setWindowIcon(QIcon(icon)) + # close.setFont(fontTwo) + # close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") + # # close.setText("¿Estás seguro?") + # # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') + # close.setText("¿Estás seguro que deseas salir?") + # close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) + # close = close.exec() - if close == QMessageBox.Yes: - event.accept() - self.clean() - else: - event.ignore() + # if close == QMessageBox.Yes: + # event.accept() + # self.clean() + # else: + # event.ignore() def error(self,errorMsg): msg = QMessageBox() @@ -418,95 +417,95 @@ def is_opened(self): return False def run(self): - if self.is_opened() == True: - self.signals.alert.emit('Error2') - else: - backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') - src= fitz.open(backup) - doc = fitz.open() - for ipage in src: - #Some pages, even though having a landscape aspect, are not actually 'landscape', - #just rotated. - #These lines of code take care of the many problems that arise when dealing with - #different page sizes. - if ipage.get_contents() != []: - if ipage.rotation==90: - ipage.setRotation(0) - if ipage.rect.width > ipage.rect.height: - fmt = fitz.PaperRect("a4-l") # landscape if input suggests - else: - fmt = fitz.PaperRect("a4") - page = doc.newPage(width = fmt.width, height = fmt.height) - page.showPDFpage(page.rect, src, ipage.number) - if page.rect.width > page.rect.height: - page.setRotation(90) - src.close() - #-----------------------------------------MINI-LOOP----------------------------------------# - done=False - count=0 - while not done: - try: - print(count) - doc.save(backup,deflate=True) - count=5 - print('sucess!') - done=True - except RuntimeError: - print('Pymupdf permission denied') - count+=0.1 - time.sleep(count) - #-----------------------------------------MINI-LOOP----------------------------------------# - doc.close() - shutil.move(backup,self.SaveAs) - - if self.PDFA==2: - from win32com import client - from docx import Document + try: + if self.is_opened() == True: + self.signals.alert.emit('Error2') + else: + backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') + src= fitz.open(backup) + doc = fitz.open() + for ipage in src: + #Some pages, even though having a landscape aspect, are not actually 'landscape', + #just rotated. + #These lines of code take care of the many problems that arise when dealing with + #different page sizes. + if ipage.get_contents() != []: + if ipage.rotation==90: + ipage.setRotation(0) + if ipage.rect.width > ipage.rect.height: + fmt = fitz.PaperRect("a4-l") # landscape if input suggests + else: + fmt = fitz.PaperRect("a4") + page = doc.newPage(width = fmt.width, height = fmt.height) + page.showPDFpage(page.rect, src, ipage.number) + if page.rect.width > page.rect.height: + page.setRotation(90) + src.close() + #-----------------------------------------MINI-LOOP----------------------------------------# done=False count=0 while not done: try: - backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') + print(count) + doc.save(backup,deflate=True) + count=5 + print('sucess!') done=True - except PermissionError: - print('Permission denied') - count+=1 - time.sleep(count) + except RuntimeError: + print('Pymupdf permission denied') + count+=0.1 + time.sleep(count) + #-----------------------------------------MINI-LOOP----------------------------------------# + doc.close() + shutil.move(backup,self.SaveAs) + + if self.PDFA==2: + done=False + count=0 + while not done: + try: + backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') + done=True + except PermissionError: + print('Permission denied') + count+=1 + time.sleep(count) + time.sleep(1) + DestDir=os.path.abspath(os.path.join(self.SaveAs, '..')) + tempDocx='\\tempword.docx' + documento = Document() + documento.save(DestDir+tempDocx) + word = client.DispatchEx('Word.Application') + worddoc = word.Documents.Open(DestDir+tempDocx,ReadOnly = 1) + worddoc.SaveAs(self.SaveAs,FileFormat = 17) + worddoc.Close(True) + word.Quit() + os.remove(DestDir+tempDocx) + pdf=fitz.open(self.SaveAs) + opened_file=fitz.open(backup) + pdf.insertPDF(opened_file) + opened_file.close() + pdf.deletePage(0) + pdf.saveIncr() + pdf.close() + time.sleep(1) + done=False + count=0 + while not done: + try: + os.remove(backup) + done=True + except PermissionError: + print('Permission denied') + count+=1 + time.sleep(count) + if self.state==2: + from subprocess import Popen + Popen([self.SaveAs],shell=True) time.sleep(1) - DestDir=os.path.abspath(os.path.join(self.SaveAs, '..')) - tempDocx='\\tempword.docx' - documento = Document() - documento.save(DestDir+tempDocx) - word = client.DispatchEx('Word.Application') - worddoc = word.Documents.Open(DestDir+tempDocx,ReadOnly = 1) - worddoc.SaveAs(self.SaveAs,FileFormat = 17) - worddoc.Close(True) - word.Quit() - os.remove(DestDir+tempDocx) - pdf=fitz.open(self.SaveAs) - opened_file=fitz.open(backup) - pdf.insertPDF(opened_file) - opened_file.close() - pdf.deletePage(0) - pdf.saveIncr() - pdf.close() - time.sleep(1) - done=False - count=0 - while not done: - try: - os.remove(backup) - done=True - except PermissionError: - print('Permission denied') - count+=1 - time.sleep(count) - if self.state==2: - from subprocess import Popen - Popen([self.SaveAs],shell=True) - time.sleep(1) - self.signals.finished.emit('Done') - + self.signals.finished.emit('Done') + except Exception as e: + self.signals.alert.emit(str(type(e))) def kill(self): self.is_killed = True @@ -582,7 +581,7 @@ def initUI(self): self.h2.addStretch() self.start = QPushButton('Ejecutar', self) self.start.setStyleSheet(self.style1) - self.start.setFocus() + # self.start.setFocus() self.start.setFont(fontOne) self.start.setMinimumHeight(35) # self.start.setMaximumWidth(200) @@ -637,8 +636,8 @@ def initUI(self): self.mainLayout.addWidget(self.labelThree) self.setLayout(self.mainLayout) - quit = QAction("Quit", self) - quit.triggered.connect(self.closeEvent) + # quit = QAction("Quit", self) + # quit.triggered.connect(self.closeEvent) def started(self): @@ -691,6 +690,8 @@ def openFileNameDialogOne(self): def alert(self, msg): if msg=='Error2': self.error('Cierra el PDF sobre el cual intentas guardar el resultado.') + else: + self.error('Ocurrió un error inesperado: '+msg) self.clean() def finished(self, msg): if msg=='Done': @@ -704,24 +705,24 @@ def finished(self, msg): self.labelThree.show() self.progress.hide() - def closeEvent(self, event): - close = QMessageBox() - # close.setWindowTitle(self.title) - close.setWindowTitle("¿Seguro?") - close.setWindowIcon(QIcon(icon)) - close.setFont(fontTwo) - close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") - # close.setText("¿Estás seguro?") - # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') - close.setText("¿Estás seguro que deseas salir?") - close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) - close = close.exec() + # def closeEvent(self, event): + # close = QMessageBox() + # # close.setWindowTitle(self.title) + # close.setWindowTitle("¿Seguro?") + # close.setWindowIcon(QIcon(icon)) + # close.setFont(fontTwo) + # close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") + # # close.setText("¿Estás seguro?") + # # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') + # close.setText("¿Estás seguro que deseas salir?") + # close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) + # close = close.exec() - if close == QMessageBox.Yes: - event.accept() - self.clean() - else: - event.ignore() + # if close == QMessageBox.Yes: + # event.accept() + # self.clean() + # else: + # event.ignore() def error(self,errorMsg): msg = QMessageBox() @@ -793,68 +794,68 @@ def is_opened(self): return False def run(self): - if len(self.documents)<2: - self.signals.alert.emit('Error3') - elif self.SaveAs in self.documents: - self.signals.alert.emit('Error1') - elif self.is_opened() == True: - self.signals.alert.emit('Error2') - else: - pdf=fitz.open() - for element in self.documents: - opened_file=fitz.open(element) - pdf.insertPDF(opened_file) - opened_file.close() - pdf.save(self.SaveAs,deflate=True) - pdf.close() - if self.PDFA==2: - from win32com import client - from docx import Document - done=False - count=0 - while not done: - try: - backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') - done=True - except PermissionError: - print('Permission denied') - count+=1 - time.sleep(count) + try: + if len(self.documents)<2: + self.signals.alert.emit('Error3') + elif self.SaveAs in self.documents: + self.signals.alert.emit('Error1') + elif self.is_opened() == True: + self.signals.alert.emit('Error2') + else: + pdf=fitz.open() + for element in self.documents: + opened_file=fitz.open(element) + pdf.insertPDF(opened_file) + opened_file.close() + pdf.save(self.SaveAs,deflate=True) + pdf.close() + if self.PDFA==2: + done=False + count=0 + while not done: + try: + backup=shutil.copy(self.SaveAs,self.SaveAs[:-4]+' sehr witzig.pdf') + done=True + except PermissionError: + print('Permission denied') + count+=1 + time.sleep(count) + time.sleep(1) + DestDir=os.path.abspath(os.path.join(self.SaveAs, '..')) + tempDocx='\\tempword.docx' + documento = Document() + documento.save(DestDir+tempDocx) + word = client.DispatchEx('Word.Application') + worddoc = word.Documents.Open(DestDir+tempDocx,ReadOnly = 1) + worddoc.SaveAs(self.SaveAs,FileFormat = 17) + worddoc.Close(True) + word.Quit() + os.remove(DestDir+tempDocx) + pdf=fitz.open(self.SaveAs) + opened_file=fitz.open(backup) + pdf.insertPDF(opened_file) + opened_file.close() + pdf.deletePage(0) + pdf.saveIncr() + pdf.close() + time.sleep(1) + done=False + count=0 + while not done: + try: + os.remove(backup) + done=True + except PermissionError: + print('Permission denied') + count+=1 + time.sleep(count) + if self.state==2: + from subprocess import Popen + Popen([self.SaveAs],shell=True) time.sleep(1) - DestDir=os.path.abspath(os.path.join(self.SaveAs, '..')) - tempDocx='\\tempword.docx' - documento = Document() - documento.save(DestDir+tempDocx) - word = client.DispatchEx('Word.Application') - worddoc = word.Documents.Open(DestDir+tempDocx,ReadOnly = 1) - worddoc.SaveAs(self.SaveAs,FileFormat = 17) - worddoc.Close(True) - word.Quit() - os.remove(DestDir+tempDocx) - pdf=fitz.open(self.SaveAs) - opened_file=fitz.open(backup) - pdf.insertPDF(opened_file) - opened_file.close() - pdf.deletePage(0) - pdf.saveIncr() - pdf.close() - time.sleep(1) - done=False - count=0 - while not done: - try: - os.remove(backup) - done=True - except PermissionError: - print('Permission denied') - count+=1 - time.sleep(count) - if self.state==2: - from subprocess import Popen - Popen([self.SaveAs],shell=True) - time.sleep(1) - self.signals.finished.emit('Done') - + self.signals.finished.emit('Done') + except Exception as e: + self.signals.alert.emit(str(type(e))) def kill(self): self.is_killed = True @@ -948,7 +949,7 @@ def initUI(self): self.h2.addStretch() self.start = QPushButton('Ejecutar', self) self.start.setStyleSheet(self.style1) - self.start.setFocus() + # self.start.setFocus() self.start.setFont(fontOne) self.start.setMinimumHeight(35) # self.start.setMaximumWidth(200) @@ -1002,8 +1003,8 @@ def initUI(self): self.mainLayout.addWidget(self.labelThree) self.setLayout(self.mainLayout) - quit = QAction("Quit", self) - quit.triggered.connect(self.closeEvent) + # quit = QAction("Quit", self) + # quit.triggered.connect(self.closeEvent) def started(self): @@ -1075,6 +1076,8 @@ def alert(self, msg): self.error('Cierra el PDF sobre el cual deseas guardar el resultado.') elif msg=='Error3': self.error('Debes seleccionar más de un PDF.') + else: + self.error('Ocurrió un error inesperado: '+msg) self.clean() def finished(self, msg): @@ -1091,24 +1094,24 @@ def finished(self, msg): self.labelThree.show() self.progress.hide() - def closeEvent(self, event): - close = QMessageBox() - # close.setWindowTitle(self.title) - close.setWindowTitle("¿Seguro?") - close.setWindowIcon(QIcon(icon)) - close.setFont(fontTwo) - close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") - # close.setText("¿Estás seguro?") - # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') - close.setText("¿Estás seguro que deseas salir?") - close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) - close = close.exec() + # def closeEvent(self, event): + # close = QMessageBox() + # # close.setWindowTitle(self.title) + # close.setWindowTitle("¿Seguro?") + # close.setWindowIcon(QIcon(icon)) + # close.setFont(fontTwo) + # close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") + # # close.setText("¿Estás seguro?") + # # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') + # close.setText("¿Estás seguro que deseas salir?") + # close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) + # close = close.exec() - if close == QMessageBox.Yes: - event.accept() - self.clean() - else: - event.ignore() + # if close == QMessageBox.Yes: + # event.accept() + # self.clean() + # else: + # event.ignore() def error(self,errorMsg): msg = QMessageBox() @@ -1179,52 +1182,49 @@ def is_opened(self): return False def run(self): - - if self.SaveAs in self.documents: - self.signals.alert.emit('Error1') - elif self.is_opened() == True: - self.signals.alert.emit('Error2') - else: - doc = fitz.open() - for file in self.documents: - img=fitz.open(file) - fmt = fitz.PaperRect("a4") - pdfbytes = img.convertToPDF() - img.close() - imgPDF = fitz.open("pdf", pdfbytes) - page = doc.newPage(width = fmt.width, height = fmt.height) - page.showPDFpage(page.rect, imgPDF, 0) - - #-----------------------------------------MINI-LOOP----------------------------------------# - done=False - count=0 - while not done: - try: - print(count) - doc.save(self.SaveAs,deflate=True) - print('sucess!') - done=True - except RuntimeError: - print('Pymupdf permission denied') - count+=0.1 - time.sleep(count) - #-----------------------------------------MINI-LOOP----------------------------------------# - doc.close() - if self.state==2: - from subprocess import Popen - Popen([self.SaveAs],shell=True) - time.sleep(1) - self.signals.finished.emit('Done') - + try: + if self.SaveAs in self.documents: + self.signals.alert.emit('Error1') + elif self.is_opened() == True: + self.signals.alert.emit('Error2') + else: + doc = fitz.open() + for file in self.documents: + img=fitz.open(file) + fmt = fitz.PaperRect("a4") + pdfbytes = img.convertToPDF() + img.close() + imgPDF = fitz.open("pdf", pdfbytes) + page = doc.newPage(width = fmt.width, height = fmt.height) + page.showPDFpage(page.rect, imgPDF, 0) + + #-----------------------------------------MINI-LOOP----------------------------------------# + done=False + count=0 + while not done: + try: + print(count) + doc.save(self.SaveAs,deflate=True) + print('sucess!') + done=True + except RuntimeError: + print('Pymupdf permission denied') + count+=0.1 + time.sleep(count) + #-----------------------------------------MINI-LOOP----------------------------------------# + doc.close() + if self.state==2: + from subprocess import Popen + Popen([self.SaveAs],shell=True) + time.sleep(1) + self.signals.finished.emit('Done') + except Exception as e: + self.signals.alert.emit(str(type(e))) def kill(self): self.is_killed = True class ActionsFour(QWidget): - """ - Simple dialog that consists of a Progress Bar and a Button. - Clicking on the button results in the start of a timer and - updates the progress bar. - """ + def __init__(self): super().__init__() @@ -1306,7 +1306,7 @@ def initUI(self): self.h2.addStretch() self.start = QPushButton('Ejecutar', self) self.start.setStyleSheet(self.style1) - self.start.setFocus() + # self.start.setFocus() self.start.setFont(fontOne) self.start.setMinimumHeight(35) # self.start.setMaximumWidth(200) @@ -1362,8 +1362,8 @@ def initUI(self): self.mainLayout.addWidget(self.labelThree) self.setLayout(self.mainLayout) - quit = QAction("Quit", self) - quit.triggered.connect(self.closeEvent) + # quit = QAction("Quit", self) + # quit.triggered.connect(self.closeEvent) def started(self): @@ -1432,6 +1432,8 @@ def alert(self, msg): self.error('No puedes guardar el resultado encima de uno de los PDFs que deseas unir.') elif msg=='Error2': self.error('Cierra el PDF sobre el cual deseas guardar el resultado.') + else: + self.error('Ocurrió un error inesperado: '+msg) self.clean() def finished(self, msg): @@ -1449,24 +1451,24 @@ def finished(self, msg): self.labelThree.show() self.progress.hide() - def closeEvent(self, event): - close = QMessageBox() - # close.setWindowTitle(self.title) - close.setWindowTitle("¿Estás seguro?") - close.setWindowIcon(QIcon(icon)) - close.setFont(fontTwo) - close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") - # close.setText("¿Estás seguro?") - # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') - close.setText("¿Estás seguro que deseas salir?") - close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) - close = close.exec() + # def closeEvent(self, event): + # close = QMessageBox() + # # close.setWindowTitle(self.title) + # close.setWindowTitle("¿Estás seguro?") + # close.setWindowIcon(QIcon(icon)) + # close.setFont(fontTwo) + # close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") + # # close.setText("¿Estás seguro?") + # # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') + # close.setText("¿Estás seguro que deseas salir?") + # close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) + # close = close.exec() - if close == QMessageBox.Yes: - event.accept() - self.clean() - else: - event.ignore() + # if close == QMessageBox.Yes: + # event.accept() + # self.clean() + # else: + # event.ignore() def error(self,errorMsg): msg = QMessageBox() @@ -1513,136 +1515,149 @@ class WorkerSignalsFive(QObject): class JobRunnerFive(QRunnable): signals = WorkerSignalsFive() - def __init__(self,SaveAs,name,choice): + def __init__(self,SaveAs,name,choice,OFcircular): super().__init__() self.is_killed = False self.SaveAs=SaveAs self.name=name self.choice=choice + self.OFcircular=OFcircular @pyqtSlot() def run(self): - - RDDir=os.path.abspath(os.path.dirname(self.SaveAs)) - if self.name in os.listdir(RDDir): - self.signals.alert.emit('Error1') - else: - if self.choice==0: - doc = fitz.open(self.SaveAs) - page = doc.loadPage(0) - text = page.getText() - nro_req=findall('(?0: + self.labelTwo.setText('') self.labelThree.hide() self.progress.show() @@ -1798,7 +1833,7 @@ def started(self): self.choice = self.combo.currentIndex() print(self.choice) self.threadpool = QThreadPool() - self.runner = JobRunnerFive(self.var1,self.name,self.choice) + self.runner = JobRunnerFive(self.var1,self.name,self.choice,self.var2) self.threadpool.start(self.runner) try: self.runner.signals.alert.disconnect(self.alert) @@ -1817,7 +1852,9 @@ def started(self): def clean(self): self.myTextBoxOne.setText(None) + self.myTextBoxThree.setText(None) self.var1=None + self.var2=None self.labelTwo.setText('') self.labelThree.hide() self.myTextBoxTwo.setText('') @@ -1845,13 +1882,19 @@ def alert(self, msg): self.error('No se encontró el número de Carta y/o OF.') elif msg=='Error4': self.error('No se encontró el número de RUC y/o OF.') + elif msg=='Error5': + self.error('El número de OF debe contener doce dígitos.') + else: + self.error('Ocurrió un error inesperado: '+msg) self.clean() def finished(self, msg): if msg=='Done': self.runner=None self.myTextBoxOne.setText(None) + self.myTextBoxThree.setText(None) self.var1=None + self.var2=None self.start.setEnabled(True) self.labelTwo.setText('¡Listo, ya puedes visualizar tus documentos!') self.labelThree.show() @@ -1860,24 +1903,24 @@ def finished(self, msg): self.labelThree.show() self.progress.hide() - def closeEvent(self, event): - close = QMessageBox() - # close.setWindowTitle(self.title) - close.setWindowTitle("¿Estás seguro?") - close.setWindowIcon(QIcon(icon)) - close.setFont(fontTwo) - close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") - # close.setText("¿Estás seguro?") - # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') - close.setText("¿Estás seguro que deseas salir?") - close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) - close = close.exec() + # def closeEvent(self, event): + # close = QMessageBox() + # # close.setWindowTitle(self.title) + # close.setWindowTitle("¿Estás seguro?") + # close.setWindowIcon(QIcon(icon)) + # close.setFont(fontTwo) + # close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") + # # close.setText("¿Estás seguro?") + # # close.setInformativeText('Se detendrá la función si se está ejecutando, pero no te preocupes ya que se guardará el avance.') + # close.setText("¿Estás seguro que deseas salir?") + # close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) + # close = close.exec() - if close == QMessageBox.Yes: - event.accept() - self.clean() - else: - event.ignore() + # if close == QMessageBox.Yes: + # event.accept() + # self.clean() + # else: + # event.ignore() def error(self,errorMsg): @@ -1901,7 +1944,11 @@ def instructions(self): info.setWindowTitle(choices[4][3:]) info.setWindowIcon(QIcon(icon)) - info.setText('''El documento resultante se guardará en la carpeta que contiene tu Requerimiento/Carta''') + info.setText('''Se creará una carpeta que contendrá el .zip resultante junto con su versión descomprimida para que puedas visualizar el contenido sin descomprimir el fichero. + +Dicha carpeta se guardará en el directorio de tu Requerimiento/Carta. + +Solo si se trata de una Carta Circular, debes ingresar el número de OF ya que éste no se suele consignar en el documento.''') info.setFont(fontTwo) info.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") info.setWindowModality(0) @@ -1924,11 +1971,11 @@ class WorkerSignalsSix(QObject): class JobRunnerSix(QRunnable): signals = WorkerSignalsSix() - def __init__(self,rd,rms,rpv): + def __init__(self,rds,rms,rpv): super().__init__() self.is_killed = False - self.rd=rd + self.rds=rds self.rms=rms self.rpv=rpv @@ -1936,38 +1983,44 @@ def __init__(self,rd,rms,rpv): def run(self): - - fatal=False - text='' - doc = fitz.open(self.rpv) - for i in range(len(doc)): - page = doc.loadPage(i) - text += page.getText() - doc.close() - - ruc=findall('[0-9]+', text) - for i in ruc: - if len(i)==11: - ruc=i - break - if len(ruc)!=11: - self.signals.alert.emit('ruc') - else: - pre=findall('\d{15}', text) - tipo=findall('RD|RM', text) - targetName='Valores '+ruc - names=[] - for p in pre: - names.append(ruc+'_'+p+'_'+'01') - - if 'RM' in tipo and self.rms is None: - print('error1') - self.signals.alert.emit('rm') - elif 'RD' in tipo and self.rd is None: - print('error2') - self.signals.alert.emit('rd') + try: + fatal=False + text='' + doc = fitz.open(self.rpv) + for i in range(len(doc)): + page = doc.loadPage(i) + text += page.getText() + doc.close() + + nums=findall('[0-9]+', text) + for i in nums: + if len(i)==11: + ruc=i + break + print(ruc) + # ruc=findall('(?=7 and i.startswith('00'): + pre.append(i) + + tipo=findall(r"\bRD\b(?!')|\bRM\b(?!')", text) + targetName='Valores '+ruc + names=[] + for p in pre: + names.append(ruc+'_'+p+'_'+'01') + + if 'RM' in tipo and self.rms is None: + print('error1') + self.signals.alert.emit('rm') + elif 'RD' in tipo and self.rds is None: + print('error2') + self.signals.alert.emit('rd') + else: + fatal2=False lines=[] text=text.replace('\n',' ').split(pre[0])[1] for p in pre[1:]: @@ -1975,73 +2028,109 @@ def run(self): text=text.replace('\n',' ').split(p)[1] lines.append(text) - codes=[] - for rm in self.rms: - doc = fitz.open(rm) - page = doc.loadPage(0) - foo = page.getText() - doc.close() - code=foo.split('\n')[3] - if code=='6091' or code=='60901': - code='060901' - else: - code='0'+code - codes.append(code) - - try: - RDDir=os.path.abspath(os.path.dirname(self.rd)) - except TypeError: - RDDir=os.path.abspath(os.path.dirname(self.rms[0])) - if targetName in os.listdir(RDDir): - self.signals.alert.emit('Error') - else: - os.mkdir(RDDir+'\\'+targetName) - targetOne=RDDir+'\\'+targetName - os.mkdir(targetOne+'\\'+targetName) - targetTwo=RDDir+'\\'+targetName+'\\'+targetName - - for i in range(len(names)): - if tipo[i]=='RD': - shutil.copy(self.rd,targetTwo+'\\'+names[i]+'.pdf') - elif tipo[i]=='RM': - idx=None - for code in codes: - if code in lines[i]: - idx=codes.index(code) - break - if idx is None: - fatal=True - break - else: - shutil.copy(self.rms[idx],targetTwo+'\\'+names[i]+'.pdf') + codesRDs=[] + codesRMs=[] - if fatal==False: - - text_RD_path=targetTwo+'\\files.txt' - with open(text_RD_path, 'w') as text_RD: + if 'RM' in tipo: + for rm in self.rms: + doc = fitz.open(rm) + page = doc.loadPage(0) + foo = page.getText() + doc.close() + code=foo.split('\n')[3] + if len(code.strip())==4: + code='0'+code[:-1]+'0'+code[-1] + else: + code='0'+code + codesRMs.append(code) + ruc2=findall('(? class MainWindow(QMainWindow): @@ -2710,7 +2797,7 @@ def __init__(self): self.window4 = ActionsFour() self.window5 = ActionsFive() self.window6 = ActionsSix() - self.window7 = ActionsSeven() + self.window7 = ActionsSeven() self.title = 'LuftMensch' self.initUI() @@ -2731,7 +2818,7 @@ def initUI(self): self.setWindowTitle(self.title) # self.setMinimumSize(750,500) - self.setMinimumSize(520,520) + self.setMinimumSize(530,530) # self.resize(500,600) # self.move(500, 2) # self.setWindowState(Qt.WindowMaximized) @@ -2743,10 +2830,16 @@ def initUI(self): self.menuBar.setStyleSheet("QMenuBar {background-color: rgb(155, 61, 61); color: rgb(255, 255, 255)}" "QMenuBar:item:selected {background-color: white ;color: black}") self.menuBar.addAction('&Acerca de', self.about) - self.menuBar.addAction('&Ir al repositorio', self.repo) self.menuBar.addAction('&Actualizar', self.update) # self.menuBar.addAction('&Ayuda', self.need_help) + self.visitRepo=QMenu("Repositorio") + self.visitRepo.setStyleSheet("QMenu {background-color: white; color: black}" + "QMenu:item:selected {background-color: white ;color: rgb(155, 61, 61)}") + self.menuBar.addMenu(self.visitRepo) + self.visitRepo.setCursor(QCursor(Qt.PointingHandCursor)) + self.visitRepo.addAction('&Ir al repositorio', self.repo) + self.help=QMenu("&Instrucciones") self.help.setStyleSheet("QMenu {background-color: white; color: black}" "QMenu:item:selected {background-color: white ;color: rgb(155, 61, 61)}") @@ -2754,7 +2847,8 @@ def initUI(self): self.help.setCursor(QCursor(Qt.PointingHandCursor)) self.help.addAction(choices[0], self.window1.instructions) self.help.addAction(choices[4], self.window5.instructions) - self.help.addAction(choices[5], self.window6.instructions) + self.help.addAction(choices[5], self.window6.instructions) + self.stackedLayout = QStackedLayout() self.mainLayout = QVBoxLayout() @@ -2804,7 +2898,8 @@ def initUI(self): self.h.setAlignment(Qt.AlignCenter) self.mainLayout.addLayout(self.h,1) - self.mainLayout.addLayout(self.v0,0) + self.mainLayout.addLayout(self.v0,0) + self.mainLayout.addLayout(self.stackedLayout,4) self.pixmap = QPixmap(icon) @@ -2821,7 +2916,7 @@ def initUI(self): self.labelFour.setAlignment(Qt.AlignCenter) self.v.addWidget(self.labelFour) - self.titleOne = QLabel('Versión 1.3.4', self) + self.titleOne = QLabel('Versión 1.3.6', self) self.titleOne.setFont(fontFive) self.titleOne.setStyleSheet("color: IndianRed") self.titleOne.setAlignment(Qt.AlignRight | Qt.AlignBottom) @@ -2834,7 +2929,7 @@ def initUI(self): self.status_label = QLabel() self.statusBar().addPermanentWidget(self.status_label) - self.status_label.setText('Estás usando la versión 1.3.4, lanzada en marzo del 2021.') + self.status_label.setText('Estás usando la versión 1.3.6 de LuftMensch.') self.w = QWidget(self) self.w.setLayout(self.mainLayout) @@ -2866,7 +2961,7 @@ def closeEvent(self, event): close.setWindowIcon(QIcon(icon)) close.setFont(fontTwo) close.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") - close.setText("Se abandonará por completo la aplicación.") + close.setText("Se abandonará por completo la aplicación.") close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) buttonYes = close.button(QMessageBox.Yes) buttonYes.setCursor(QCursor(Qt.PointingHandCursor)) @@ -2878,22 +2973,22 @@ def closeEvent(self, event): buttonCancel.setFont(fontOne) close = close.exec() - if close == QMessageBox.Yes: - + if close == QMessageBox.Yes: event.accept() else: event.ignore() def repo(self): - from webbrowser import open as op op('https://github.com/lheredias/Luftmensch') def about(self): info = QMessageBox() info.setWindowTitle("Acerca de LuftMensch") info.setWindowIcon(QIcon(icon)) - info.setText('''Luftmensch es una aplicación de productividad y de código abierto pensada en automatizar ciertas tareas administrativas. + info.setText('''LuftMensch es una aplicación de productividad y de código abierto pensada en automatizar ciertas tareas administrativas. + +En estos momentos te encuentras utilizando la versión portable de LuftMensch, la cual se puede tratar como cualquier otro archivo. -Si deseas revisar el historial de versiones, realizar consultas, dejar un comentario o hacer una sugerencia, visita el repositorio.''') +Si deseas conocer conocer más sobre LuftMensh, revisar el historial de versiones, realizar consultas, dejar un comentario o hacer una sugerencia, visita el repositorio.''') info.setFont(fontTwo) info.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") @@ -2932,7 +3027,7 @@ def update(self): info.setWindowTitle("¿Cómo actualizar LuftMensch?") info.setWindowIcon(QIcon(icon)) - info.setText('''Para actualizar la aplicación, dale click en Releases y, una vez que termine de cargar la página, descarga la versión más reciente y guárdala encima de la actual.''') + info.setText('''Para actualizar la aplicación dale click en Releases y, una vez que termine de cargar la página, descarga la versión (portable) más reciente y guárdala encima de la actual.''') info.setFont(fontTwo) info.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(69, 70, 77 )") @@ -2952,7 +3047,6 @@ def update(self): retval = info.exec_() print(retval) if retval==16384: - from webbrowser import open as op op('https://github.com/lheredias/Luftmensch/releases') if __name__ == '__main__':