The analyzer starts

This commit is contained in:
Adrien Bourmault 2019-07-12 10:57:03 +02:00 committed by GitHub
parent 75e0a85a86
commit da2a00e3ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 614 additions and 572 deletions

View File

@ -34,17 +34,19 @@ import launcher # launcher.py
import updater # updater.py
import globs # globs.py
import pytesseract # pytesseract.py
import logger # logger.py
import logger # logger.py
from main import * # main.py
# Global handler
logfile = logger.logCur
## MAIN FUNCTION OF CNIREVELATOR
def main():
logfile.printdbg('*** CNIRevelator LOGFILE. Hello World ! ***')
mainw = mainWindow(logfile.logger)
try:
os.environ['PATH'] = globs.CNIRFolder + '\\Tesseract-OCR4\\'
os.environ['TESSDATA_PREFIX'] = globs.CNIRFolder + '\\Tesseract-OCR4\\tessdata'
@ -53,15 +55,15 @@ def main():
logfile.printerr('ERROR WITH TESSERACT MODULE ' + str(e))
else:
text = 'Tesseract version ' + str(tesser_version) + ' Licensed Apache 2004 successfully initiated\n'
main_w.montext(text)
mainw.logOnTerm(text)
main_w.montext('\n\nEntrez la première ligne de MRZ svp \n')
mainw.logOnTerm('\n\nEntrez la première ligne de MRZ svp \n')
if globs.CNIRNewVersion:
showinfo('Changelog : résumé de mise à jour', ('Version du logiciel : CNIRevelator ' + globs.verstring_full + '\n\n' + globs.changelog), parent=main_w)
logger.info('main() : **** Launching App_main() ****')
main_w.mainloop()
logger.info('main() : **** Ending App_main() ****')
showinfo('Changelog : résumé de mise à jour', ('Version du logiciel : CNIRevelator ' + globs.verstring_full + '\n\n' + globs.changelog), parent=mainWindow)
logfile.printdbg('main() : **** Launching App_main() ****')
mainw.mainloop()
logfile.printdbg('main() : **** Ending App_main() ****')
logfile.printdbg('*** CNIRevelator LOGFILE. Goodbye World ! ***')
logfile.close()
@ -91,5 +93,6 @@ if updater.UPDATE_IS_MADE:
# Here we go !
try:
main()
except Exception:
except Exception as e:
traceback.print_exc(file=sys.stdout)
updater.exitProcess(1)

View File

@ -43,4 +43,4 @@ CNIRErrLog = CNIRFolder + '\\logs\\error.log'
CNIRMainLog = CNIRFolder + '\\logs\\main.log'
CNIRUrlConfig = CNIRFolder + '\\config\\urlconf.ig'
CNIRVerStock = CNIRFolder + '\\downloads\\versions.lst'
CNIREnv = os.getenv('APPDATA') + '/CNIRevelator/'
CNIREnv = CNIRFolder + '\\Data\\'

View File

@ -32,6 +32,7 @@ from tkinter import ttk
import mrz # mrz.py
from image import CanvasImage # image.py
import globs # globs.py
class mainWindow(Tk):
@ -125,7 +126,7 @@ class mainWindow(Tk):
self.termtext = Text((self.termframe), state='disabled', width=60, height=4, wrap='none', font='Terminal 17', fg='#121f38')
self.termtext.grid(column=0, row=0, sticky='NEW', padx=5)
vcmd = (self.register(self.entryValidation), '%S', '%P', '%d')
self.termentry = Entry((self.termframe), font='Terminal 17', entryValidation='all', entryValidationcommand=vcmd, fg='#121f38', width=44)
self.termentry = Entry((self.termframe), font='Terminal 17', validate='all', validatecommand=vcmd, fg='#121f38', width=44)
self.termentry.grid(column=0, row=0, sticky='SEW', padx=5)
self.monitor = ttk.Labelframe(self, text='Moniteur')
self.monlog = Text((self.monitor), state='disabled', width=60, height=10, wrap='word')
@ -150,7 +151,7 @@ class mainWindow(Tk):
menu3.add_command(label='A propos', command=(self.infobox))
menubar.add_cascade(label='Aide', menu=menu3)
self.config(menu=menubar)
self.wm_title(CST_TITLE)
self.wm_title(globs.CNIRName)
if getattr(sys, 'frozen', False):
self.iconbitmap(sys._MEIPASS + '\\id-card.ico\\id-card.ico')
else:
@ -398,7 +399,7 @@ class mainWindow(Tk):
return
self.logger.debug('openingScan() : ' + str(self.mrzdetected))
try:
os.remove(CST_FOLDER + '\\temp.tif')
os.remove(globs.CNIREnv + '\\temp.tif')
except IOError:
pass
@ -416,7 +417,7 @@ class mainWindow(Tk):
def infobox(self):
Tk().withdraw()
showinfo('A propos du logiciel', ('Version du logiciel : \n' + CST_NAME + ' ' + CST_VER + ' ' + CST_TYPE + ' Revision ' + CST_REV + "\nLicence GNU/GPL 2018\n\nAuteur : NeoX_ ; devadmin@neoxgroup.eu\n\nTesseract 4.0 est soumis à l'Apache License 2004\n\n N'hésitez pas à faire part de vos commentaires !"), parent=self)
showinfo('A propos du logiciel', ('Version du logiciel : \n' + globs.verstring_full + ' ' + "\nLicence GNU/GPL 2018\n\nAuteur : NeoX_ ; devadmin@neoxgroup.eu\n\nTesseract 4.0 est soumis à l'Apache License 2004\n\n N'hésitez pas à faire part de vos commentaires !"), parent=self)
def calculSigma(self, MRZtxt, numtype):
CST_BACKGROUND = self['background']
@ -620,7 +621,7 @@ class OpenScan(ttk.Frame):
if self.pagenum + 1 < self.nframe:
im = Image.open(self.fileorig)
im.seek(self.pagenum + 1)
newpath = CST_FOLDER + '\\temp' + str(random.randint(11111, 99999)) + '.tif'
newpath = globs.CNIREnv + '\\temp' + str(random.randint(11111, 99999)) + '.tif'
im.save(newpath)
im.close()
self.cadre.destroy()
@ -630,7 +631,7 @@ class OpenScan(ttk.Frame):
if self.pagenum - 1 >= 0:
im = Image.open(self.fileorig)
im.seek(self.pagenum - 1)
newpath = CST_FOLDER + '\\temp' + str(random.randint(11111, 99999)) + '.tif'
newpath = globs.CNIREnv + '\\temp' + str(random.randint(11111, 99999)) + '.tif'
im.save(newpath)
im.close()
self.cadre.destroy()
@ -662,12 +663,12 @@ class OpenScan(ttk.Frame):
im = self.imtotreat
import CNI_pytesseract as pytesseract
try:
os.environ['PATH'] = CST_FOLDER + '\\Tesseract-OCR4\\'
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + '\\Tesseract-OCR4\\tessdata'
os.environ['PATH'] = globs.CNIREnv + '\\Tesseract-OCR4\\'
os.environ['TESSDATA_PREFIX'] = globs.CNIREnv + '\\Tesseract-OCR4\\tessdata'
self.text = pytesseract.image_to_string(im, lang='ocrb', boxes=False, config='--psm 6 --oem 0 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890<')
except pytesseract.TesseractNotFoundError as e:
try:
os.remove(CST_FOLDER + '\\Tesseract-OCR4\\*.*')
os.remove(globs.CNIREnv + '\\Tesseract-OCR4\\*.*')
except Exception:
pass

1045
src/mrz.py

File diff suppressed because it is too large Load Diff

View File

@ -43,6 +43,9 @@ UPDATE_IS_MADE = False
UPATH = ' '
def createShortcut(path, target='', wDir='', icon=''):
"""
Creates a shortcut for a program or an internet link
"""
ext = path[-3:]
if ext == 'url':
shortcut = file(path, 'w')
@ -61,27 +64,30 @@ def createShortcut(path, target='', wDir='', icon=''):
shortcut.save()
def spawnProcess(args, cd):
"""
Creates a new independant process. Used to launch a new version after update
"""
subprocess.Popen(args, close_fds=True, cwd=cd, creationflags=subprocess.DETACHED_PROCESS)
def exitProcess(arg):
"""
Forcefully quits a process. Used to help deletion of an old version or to quit properly
"""
# Quit totally without remain in memory
for process in psutil.process_iter():
if process.pid == os.getpid():
process.terminate()
sys.exit(arg)
## Main Batch Function
def batch():
def getLatestVersion(credentials):
"""
Returns the latest version of the software
"""
# Global Handlers
logfile = logger.logCur
launcherWindow = ihm.launcherWindowCur
credentials = downloader.newcredentials()
if not credentials.valid:
return False
# First retrieving the urls !
while True:
try:
@ -106,7 +112,7 @@ def batch():
except:
pass
with open(globs.CNIRUrlConfig, 'w') as (configFile):
configFile.write("https://raw.githubusercontent.com/neox95/CNIRevelator/master/VERSIONS.LST\n0\n0") #XXX
configFile.write("https://raw.githubusercontent.com/neox95/CNIRevelator/master/VERSIONS.LST\n0\n0")
# Getting the list of versions of the software
logfile.printdbg('Retrieving the software versions')
@ -132,11 +138,49 @@ def batch():
finalsum = finalver[2] + finalver[1]*100 + finalver[0]*100*100
sum = ver[2] + ver[1]*100 + ver[0]*100*100
# Make a statement
if sum > finalsum:
if sum >= finalsum:
finalver = ver.copy()
finalurl = url
finalchecksum = checksum
return (finalver, finalurl, finalchecksum)
def tessInstall(PATH, credentials):
# Global Handlers
logfile = logger.logCur
launcherWindow = ihm.launcherWindowCur
# Verifying that Tesseract is installed
if not os.path.exists(PATH + '\\Tesseract-OCR4\\'):
finalver, finalurl, finalchecksum = getLatestVersion(credentials)
tesseracturl = finalurl.replace("CNIRevelator.zip", "tesseract_4.zip")
# WE ASSUME THAT THE MAIN FILE IS CNIRevelator.zip AND THAT THE TESSERACT PACKAGE IS tesseract_4.zip
logfile.printdbg('Preparing download of Tesseract OCR 4...')
getTesseract = downloader.newdownload(credentials, tesseracturl, PATH + '\\TsrtPackage.zip').download()
# Unzip Tesseract
logfile.printdbg("Unzipping the package")
launcherWindow.printmsg('Installing the updates')
zip_ref = zipfile.ZipFile(PATH + '\\TsrtPackage.zip', 'r')
zip_ref.extractall(PATH)
zip_ref.close()
# Cleanup
try:
os.remove(UPATH + '\\TsrtPackage.zip')
except:
pass
## Main Batch Function
def batch(credentials):
# Global Handlers
logfile = logger.logCur
launcherWindow = ihm.launcherWindowCur
# Get the latest version of CNIRevelator
finalver, finalurl, finalchecksum = getLatestVersion(credentials)
if finalver == globs.version:
logfile.printdbg('The software is already the newer version')
return True
@ -194,25 +238,8 @@ def batch():
launcherWindow.printmsg('Success !')
# Verifying that Tesseract is installed
if not os.path.exists(globs.CNIRFolder + '\\Tesseract-OCR4\\'):
tesseracturl = finalurl.replace("CNIRevelator.zip", "tesseract_4.zip")
# WE ASSUME THAT THE MAIN FILE IS CNIRevelator.zip AND THAT THE TESSERACT PACKAGE IS tesseract_4.zip
logfile.printdbg('Preparing download of Tesseract OCR 4...')
getTesseract = downloader.newdownload(credentials, tesseracturl, UPATH + '\\TsrtPackage.zip').download()
# Unzip Tesseract
logfile.printdbg("Unzipping the package")
launcherWindow.printmsg('Installing the updates')
zip_ref = zipfile.ZipFile(UPATH + '\\TsrtPackage.zip', 'r')
zip_ref.extractall(UPATH)
zip_ref.close()
# Cleanup
try:
os.remove(UPATH + '\\TsrtPackage.zip')
except:
pass
# Install Tesseract !
tessInstall(UPATH, credentials)
# Cleanup
try:
@ -232,6 +259,16 @@ def umain():
logfile = logger.logCur
launcherWindow = ihm.launcherWindowCur
credentials = downloader.newcredentials()
if not credentials.valid:
logfile.printerr("Credentials Error. No effective update !")
launcherWindow.printmsg('Credentials Error. No effective update !')
time.sleep(2)
launcherWindow = ihm.launcherWindowCur
launcherWindow.destroy()
return 0
# Cleaner for the old version if detected
if len(sys.argv) > 1:
globs.CNIRNewVersion = True
@ -258,11 +295,13 @@ def umain():
logfile.printerr(str(e))
launcherWindow.printmsg('Fail :{}'.format(e))
launcherWindow.printmsg('Starting...')
else:
tessInstall(globs.CNIRFolder, credentials)
try:
try:
# EXECUTING THE UPDATE BATCH
success = batch()
success = batch(credentials)
except Exception as e:
logfile.printerr("An error occured on the thread : " + str(traceback.format_exc()))
launcherWindow.printmsg('ERROR : ' + str(e))