mirror of
https://gitlab.os-k.eu/neox/CNIRevelator.git
synced 2023-08-25 14:03:10 +02:00
Begin reorganization
This commit is contained in:
parent
a4ec7b945e
commit
cac10bacc6
@ -1,10 +1,9 @@
|
|||||||
@echo off
|
@echo off
|
||||||
set /p version=Numero de version:
|
title Compilation de CNIRevelator
|
||||||
|
|
||||||
|
call pyinstaller -w -D --exclude-module PyQt5 --bootloader-ignore-signals --add-data "C:\users\adrie\Anaconda3\Lib\site-packages\tld\res\effective_tld_names.dat.txt";"tld\res" --add-data "id-card.ico";"id-card.ico" -i "id-card.ico" -n CNIRevelator src\analyzer\CNI_Revelator.py
|
||||||
|
|
||||||
title Compilation du programme final
|
copy LICENSE dist\CNIRevelator\
|
||||||
|
|
||||||
call pyinstaller -w -D --exclude-module PyQt5 --bootloader-ignore-signals --add-data "C:\users\adrie\Anaconda3\Lib\site-packages\tld\res\effective_tld_names.dat.txt";"tld\res" --add-data "id-card.ico";"id-card.ico" -i "id-card.ico" -n CNIRevelator_%version%.exe CNI_Revelator.py
|
|
||||||
|
|
||||||
pause
|
pause
|
||||||
|
|
@ -1,47 +1,59 @@
|
|||||||
"""
|
"""
|
||||||
********************************************************************************
|
********************************************************************************
|
||||||
*** Projet CNI_Revelator ***
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
GNU GPL * 07/2018
|
* Desc: Application launcher & updater *
|
||||||
|
* *
|
||||||
Adrien Bourmault
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
VARIABLES
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
********************************************************************************
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
"""
|
* it under the terms of the GNU General Public License as published by *
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
class changelog:
|
* any later version. *
|
||||||
|
* *
|
||||||
def __init__(self):
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
self.isOn = False
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
self.text = "Mise-à-jour de sécurité avec corrections suivantes :\n- ajout de la signature numérique de l'exécutable\n- ajout d'une clé de cryptage plus performante pour le stockage des identifiants\n- passage à la méthode de cryptage AES256\n\nAjout/correction des fonctionnalités suivantes :\n- somme de contrôle des téléchargements pour une meilleure fiabilité\n- amélioration de présentation du log en cas d'erreur\n- correction d'un bug affectant l'analyse des MRZ après la correction manuelle\n\nEt un petit bonjour à tout le monde! ;)"
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
|
* GNU General Public License for more details. *
|
||||||
|
* *
|
||||||
CST_REV = '0'
|
* You should have received a copy of the GNU General Public License *
|
||||||
CST_VERTITLE = '2.2'
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
CST_TAB_VER = ['2', '2', '5']
|
********************************************************************************
|
||||||
CST_VER = '{0}.{1}.{2}'.format(CST_TAB_VER[0], CST_TAB_VER[1], CST_TAB_VER[2])
|
"""
|
||||||
CST_TYPE = 'Final Release'
|
|
||||||
CST_NAME = 'CNIRevelator'
|
class changelog:
|
||||||
CST_TITLE = CST_NAME + ' ' + CST_VER + ' - GNU/GPL Licensing 2018'
|
|
||||||
CST_MARK = CST_NAME + ' ' + CST_TYPE + ' ' + CST_VER + ' - by NeoX, GNU/GPL Licensing 2018'
|
def __init__(self):
|
||||||
CST_SUM_VER = int(CST_TAB_VER[0]) * 100 + int(CST_TAB_VER[1]) * 10 + int(CST_TAB_VER[2])
|
self.isOn = False
|
||||||
CST_LINK = 'http://neoxgroup.eu/ftpaccess/Applicatifs/CNIRevelator/'
|
self.text = "Mise-à-jour de sécurité avec corrections suivantes :\n- ajout de la signature numérique de l'exécutable\n- ajout d'une clé de cryptage plus performante pour le stockage des identifiants\n- passage à la méthode de cryptage AES256\n\nAjout/correction des fonctionnalités suivantes :\n- somme de contrôle des téléchargements pour une meilleure fiabilité\n- amélioration de présentation du log en cas d'erreur\n- correction d'un bug affectant l'analyse des MRZ après la correction manuelle\n\nEt un petit bonjour à tout le monde! ;)"
|
||||||
CST_COLOR = '#003380'
|
|
||||||
CST_TesserHash = '5b58db27f7bc08c58a2cb33d01533b034b067cf8'
|
|
||||||
|
CST_REV = '0'
|
||||||
|
CST_VERTITLE = '2.2'
|
||||||
import base64, hashlib
|
CST_TAB_VER = ['2', '2', '5']
|
||||||
from Crypto import Random
|
CST_VER = '{0}.{1}.{2}'.format(CST_TAB_VER[0], CST_TAB_VER[1], CST_TAB_VER[2])
|
||||||
from Crypto.Cipher import AES
|
CST_TYPE = 'Final Release'
|
||||||
from tkinter import *
|
CST_NAME = 'CNIRevelator'
|
||||||
from tkinter.messagebox import *
|
CST_TITLE = CST_NAME + ' ' + CST_VER + ' - GNU/GPL Licensing 2018'
|
||||||
from tkinter import filedialog
|
CST_MARK = CST_NAME + ' ' + CST_TYPE + ' ' + CST_VER + ' - by NeoX, GNU/GPL Licensing 2018'
|
||||||
from tkinter import ttk
|
CST_SUM_VER = int(CST_TAB_VER[0]) * 100 + int(CST_TAB_VER[1]) * 10 + int(CST_TAB_VER[2])
|
||||||
import os, time, threading, sys, urllib.request as urllib2, urllib.error as URLExcept, random
|
CST_LINK = 'http://neoxgroup.eu/ftpaccess/Applicatifs/CNIRevelator/'
|
||||||
from datetime import datetime
|
CST_COLOR = '#003380'
|
||||||
|
CST_TesserHash = '5b58db27f7bc08c58a2cb33d01533b034b067cf8'
|
||||||
CST_FOLDER = os.getenv('APPDATA') + '/CNIRevelator/'
|
|
||||||
CST_CRYPTOKEY = '82Xh!efX3#@P~2eG'
|
|
||||||
|
import base64, hashlib
|
||||||
|
from Crypto import Random
|
||||||
|
from Crypto.Cipher import AES
|
||||||
|
from tkinter import *
|
||||||
|
from tkinter.messagebox import *
|
||||||
|
from tkinter import filedialog
|
||||||
|
from tkinter import ttk
|
||||||
|
import os, time, threading, sys, urllib.request as urllib2, urllib.error as URLExcept, random
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
CST_FOLDER = os.getenv('APPDATA') + '/CNIRevelator/'
|
||||||
|
CST_CRYPTOKEY = '82Xh!efX3#@P~2eG'
|
||||||
CST_CHANGELOG = changelog()
|
CST_CHANGELOG = changelog()
|
@ -1,107 +1,120 @@
|
|||||||
"""
|
"""
|
||||||
********************************************************************************
|
********************************************************************************
|
||||||
*** Projet CNI_Revelator ***
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
GNU GPL * 07/2018
|
* Desc: Application launcher & updater *
|
||||||
|
* *
|
||||||
Adrien Bourmault
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
main
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
********************************************************************************
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
"""
|
* it under the terms of the GNU General Public License as published by *
|
||||||
from CNI_GLOBALVAR import *
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
try:
|
* any later version. *
|
||||||
os.remove('error.log')
|
* *
|
||||||
os.remove('conf.ig')
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
except:
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
print("pass log deletion")
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
pass
|
* GNU General Public License for more details. *
|
||||||
|
* *
|
||||||
if not os.path.exists(CST_FOLDER):
|
* You should have received a copy of the GNU General Public License *
|
||||||
try:
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
os.makedirs(CST_FOLDER)
|
********************************************************************************
|
||||||
except IOError:
|
"""
|
||||||
print("pass IO ERROR")
|
|
||||||
pass
|
from CNI_GLOBALVAR import *
|
||||||
|
try:
|
||||||
print("debug")
|
os.remove('error.log')
|
||||||
import logging
|
os.remove('conf.ig')
|
||||||
from logging import FileHandler
|
except:
|
||||||
logger = logging.getLogger()
|
print("pass log deletion")
|
||||||
logger.setLevel(logging.INFO)
|
pass
|
||||||
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
|
|
||||||
error_handler = FileHandler((CST_FOLDER + '\\error.log'), mode='w', encoding='utf-8', delay=True)
|
if not os.path.exists(CST_FOLDER):
|
||||||
info_handler = FileHandler((CST_FOLDER + '\\cnirevelator.log'), mode='w', encoding='utf-8')
|
try:
|
||||||
error_handler.setLevel(logging.ERROR)
|
os.makedirs(CST_FOLDER)
|
||||||
logger.addHandler(error_handler)
|
except IOError:
|
||||||
info_handler.setLevel(logging.DEBUG)
|
print("pass IO ERROR")
|
||||||
info_handler.setFormatter(formatter)
|
pass
|
||||||
logger.addHandler(info_handler)
|
|
||||||
from CNI_classes import *
|
print("debug")
|
||||||
from CNI_Update import *
|
import logging
|
||||||
|
from logging import FileHandler
|
||||||
def main(logger):
|
logger = logging.getLogger()
|
||||||
logger.error('')
|
logger.setLevel(logging.INFO)
|
||||||
logger.info('main() : **** Creating App_main() ****')
|
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
|
||||||
main_w = App_main(logger)
|
error_handler = FileHandler((CST_FOLDER + '\\error.log'), mode='w', encoding='utf-8', delay=True)
|
||||||
main_w.montext('* ' + CST_NAME + ' ' + CST_VER + ' ' + CST_TYPE + ' Revision ' + CST_REV + ' *\n')
|
info_handler = FileHandler((CST_FOLDER + '\\cnirevelator.log'), mode='w', encoding='utf-8')
|
||||||
import CNI_pytesseract as pytesseract
|
error_handler.setLevel(logging.ERROR)
|
||||||
try:
|
logger.addHandler(error_handler)
|
||||||
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
info_handler.setLevel(logging.DEBUG)
|
||||||
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
info_handler.setFormatter(formatter)
|
||||||
tesser_version = pytesseract.get_tesseract_version()
|
logger.addHandler(info_handler)
|
||||||
except Exception as e:
|
from CNI_classes import *
|
||||||
logger.error('main() : **** ERROR WITH TESSERACT MODULE ' + str(e) + ' ****')
|
from CNI_Update import *
|
||||||
else:
|
|
||||||
text = 'Tesseract version ' + str(tesser_version) + ' Licensed Apache 2004 successfully initiated\n'
|
def main(logger):
|
||||||
main_w.montext(text)
|
logger.error('')
|
||||||
main_w.montext('\n\nEntrez la première ligne de MRZ svp \n')
|
logger.info('main() : **** Creating App_main() ****')
|
||||||
if CST_CHANGELOG.isOn:
|
main_w = App_main(logger)
|
||||||
showinfo('Changelog : résumé de mise à jour', ('Version du logiciel : ' + CST_VER + ' ' + CST_TYPE + ' Revision ' + CST_REV + '\n\n' + CST_CHANGELOG.text), parent=main_w)
|
main_w.montext('* ' + CST_NAME + ' ' + CST_VER + ' ' + CST_TYPE + ' Revision ' + CST_REV + ' *\n')
|
||||||
logger.info('main() : **** Launching App_main() ****')
|
import CNI_pytesseract as pytesseract
|
||||||
main_w.mainloop()
|
try:
|
||||||
logger.info('main() : **** Ending App_main() ****')
|
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
||||||
|
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
||||||
|
tesser_version = pytesseract.get_tesseract_version()
|
||||||
logger.info('launcher : ' + CST_NAME + ' ' + CST_VER)
|
except Exception as e:
|
||||||
logger.info('launcher : *****Hello World*****')
|
logger.error('main() : **** ERROR WITH TESSERACT MODULE ' + str(e) + ' ****')
|
||||||
logger.info('launcher : *****Launching SoftUpdate()*****')
|
else:
|
||||||
try:
|
text = 'Tesseract version ' + str(tesser_version) + ' Licensed Apache 2004 successfully initiated\n'
|
||||||
Answer = SoftUpdate(logger)
|
main_w.montext(text)
|
||||||
except Exception as e:
|
main_w.montext('\n\nEntrez la première ligne de MRZ svp \n')
|
||||||
logger.info('launcher : *****FATAL ERROR*****' + str(e))
|
if CST_CHANGELOG.isOn:
|
||||||
os.abort()
|
showinfo('Changelog : résumé de mise à jour', ('Version du logiciel : ' + CST_VER + ' ' + CST_TYPE + ' Revision ' + CST_REV + '\n\n' + CST_CHANGELOG.text), parent=main_w)
|
||||||
|
logger.info('main() : **** Launching App_main() ****')
|
||||||
logger.info('launcher : *****Ending SoftUpdate()*****')
|
main_w.mainloop()
|
||||||
try:
|
logger.info('main() : **** Ending App_main() ****')
|
||||||
if Answer == True:
|
|
||||||
logger.info('launcher : *****Launching main()*****')
|
|
||||||
State = main(logger)
|
logger.info('launcher : ' + CST_NAME + ' ' + CST_VER)
|
||||||
except Exception as e:
|
logger.info('launcher : *****Hello World*****')
|
||||||
logger.info('launcher : *****FATAL ERROR*****' + str(e))
|
logger.info('launcher : *****Launching SoftUpdate()*****')
|
||||||
os.abort()
|
try:
|
||||||
|
Answer = SoftUpdate(logger)
|
||||||
logger.info('launcher : *****Ending main()*****')
|
except Exception as e:
|
||||||
logger.info('launcher : *****Goodbye!*****')
|
logger.info('launcher : *****FATAL ERROR*****' + str(e))
|
||||||
handlers = logger.handlers[:]
|
os.abort()
|
||||||
for handler in handlers:
|
|
||||||
handler.close()
|
logger.info('launcher : *****Ending SoftUpdate()*****')
|
||||||
logger.removeHandler(handler)
|
try:
|
||||||
|
if Answer == True:
|
||||||
try:
|
logger.info('launcher : *****Launching main()*****')
|
||||||
with open(CST_FOLDER + '\\error.log') as (echo):
|
State = main(logger)
|
||||||
try:
|
except Exception as e:
|
||||||
os.remove('error.log')
|
logger.info('launcher : *****FATAL ERROR*****' + str(e))
|
||||||
except OSError:
|
os.abort()
|
||||||
pass
|
|
||||||
|
logger.info('launcher : *****Ending main()*****')
|
||||||
from shutil import copyfile
|
logger.info('launcher : *****Goodbye!*****')
|
||||||
temptwo = str(echo.read())
|
handlers = logger.handlers[:]
|
||||||
if len(temptwo) != 1:
|
for handler in handlers:
|
||||||
copyfile(CST_FOLDER + '\\cnirevelator.log', 'error.log')
|
handler.close()
|
||||||
except IOError:
|
logger.removeHandler(handler)
|
||||||
pass
|
|
||||||
|
try:
|
||||||
print("exit")
|
with open(CST_FOLDER + '\\error.log') as (echo):
|
||||||
|
try:
|
||||||
|
os.remove('error.log')
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
from shutil import copyfile
|
||||||
|
temptwo = str(echo.read())
|
||||||
|
if len(temptwo) != 1:
|
||||||
|
copyfile(CST_FOLDER + '\\cnirevelator.log', 'error.log')
|
||||||
|
except IOError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
print("exit")
|
||||||
sys.exit(0)
|
sys.exit(0)
|
@ -1,493 +1,506 @@
|
|||||||
"""
|
"""
|
||||||
********************************************************************************
|
********************************************************************************
|
||||||
*** Projet CNI_Revelator ***
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
GNU GPL * 07/2018
|
* Desc: Application launcher & updater *
|
||||||
|
* *
|
||||||
Adrien Bourmault
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
UPDATE
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
********************************************************************************
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
"""
|
* it under the terms of the GNU General Public License as published by *
|
||||||
from CNI_GLOBALVAR import *
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
from CNI_classes import *
|
* any later version. *
|
||||||
import hashlib
|
* *
|
||||||
from pypac import PACSession
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
from requests.auth import HTTPProxyAuth
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
import subprocess
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
|
* GNU General Public License for more details. *
|
||||||
def SoftUpdate(logger):
|
* *
|
||||||
global ret
|
* You should have received a copy of the GNU General Public License *
|
||||||
global upwin
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
import zipfile
|
********************************************************************************
|
||||||
for f in os.listdir(CST_FOLDER):
|
"""
|
||||||
if f[-4:] == '.tif':
|
|
||||||
try:
|
from CNI_GLOBALVAR import *
|
||||||
os.remove(CST_FOLDER + '\\' + f)
|
from CNI_classes import *
|
||||||
except PermissionError as e:
|
import hashlib
|
||||||
logger.info('SoftUpdate() : Failing to purge : ' + str(e))
|
from pypac import PACSession
|
||||||
|
from requests.auth import HTTPProxyAuth
|
||||||
logger.info('SoftUpdate() : Looking for older version in dir...')
|
import subprocess
|
||||||
list = os.listdir('.')
|
|
||||||
for file in list:
|
def SoftUpdate(logger):
|
||||||
if file.startswith('CNIRevelator_'):
|
global ret
|
||||||
temp = ['0', '0', '0']
|
global upwin
|
||||||
ver = file[13:].split('.')
|
import zipfile
|
||||||
for i in range(len(ver)):
|
for f in os.listdir(CST_FOLDER):
|
||||||
if ver[i] != 'exe':
|
if f[-4:] == '.tif':
|
||||||
try:
|
try:
|
||||||
temp[i] = ver[i]
|
os.remove(CST_FOLDER + '\\' + f)
|
||||||
except:
|
except PermissionError as e:
|
||||||
pass
|
logger.info('SoftUpdate() : Failing to purge : ' + str(e))
|
||||||
|
|
||||||
ver = temp.copy()
|
logger.info('SoftUpdate() : Looking for older version in dir...')
|
||||||
try:
|
list = os.listdir('.')
|
||||||
sum_ver = int(ver[0]) * 100 + int(ver[1]) * 10 + int(ver[2])
|
for file in list:
|
||||||
if sum_ver < CST_SUM_VER:
|
if file.startswith('CNIRevelator_'):
|
||||||
if file[-3:] == 'exe':
|
temp = ['0', '0', '0']
|
||||||
os.remove(file)
|
ver = file[13:].split('.')
|
||||||
logger.info('SoftUpdate() : Removed old version : ' + str(file))
|
for i in range(len(ver)):
|
||||||
CST_CHANGELOG.isOn = True
|
if ver[i] != 'exe':
|
||||||
except Exception as e:
|
try:
|
||||||
logger.error('SoftUpdate() : Failing to remove old version ' + str(file) + ' : ' + str(e))
|
temp[i] = ver[i]
|
||||||
|
except:
|
||||||
def updating():
|
pass
|
||||||
|
|
||||||
def updator():
|
ver = temp.copy()
|
||||||
global ret
|
try:
|
||||||
logger.info('[updator() thread] : Welcome !')
|
sum_ver = int(ver[0]) * 100 + int(ver[1]) * 10 + int(ver[2])
|
||||||
ret = 11
|
if sum_ver < CST_SUM_VER:
|
||||||
canvas.itemconfigure(message, text='Recherche de mises-à-jour...')
|
if file[-3:] == 'exe':
|
||||||
p.configure(mode='indeterminate', value=0, maximum=20)
|
os.remove(file)
|
||||||
p.start()
|
logger.info('SoftUpdate() : Removed old version : ' + str(file))
|
||||||
upwin.update()
|
CST_CHANGELOG.isOn = True
|
||||||
logger.info('[updator() thread] : Looking for updates...')
|
except Exception as e:
|
||||||
try:
|
logger.error('SoftUpdate() : Failing to remove old version ' + str(file) + ' : ' + str(e))
|
||||||
|
|
||||||
def download(url, filename):
|
def updating():
|
||||||
global key
|
|
||||||
global login
|
def updator():
|
||||||
try:
|
global ret
|
||||||
logger.info('[download() thread] : Trying getting credentials in the config file')
|
logger.info('[updator() thread] : Welcome !')
|
||||||
with open(CST_FOLDER + 'conf.ig', 'rb') as (config):
|
ret = 11
|
||||||
AESObj = AESCipher(CST_CRYPTOKEY)
|
canvas.itemconfigure(message, text='Recherche de mises-à-jour...')
|
||||||
try:
|
p.configure(mode='indeterminate', value=0, maximum=20)
|
||||||
tempone = AESObj.decrypt(config.read())
|
p.start()
|
||||||
if tempone != '||':
|
upwin.update()
|
||||||
if tempone.find('||') != -1:
|
logger.info('[updator() thread] : Looking for updates...')
|
||||||
IPN, IPN_PASS = tempone.split('||')[0:2]
|
try:
|
||||||
else:
|
|
||||||
raise ValueError('Cryptokey is bad !')
|
def download(url, filename):
|
||||||
else:
|
global key
|
||||||
IPN = ''
|
global login
|
||||||
IPN_PASS = ''
|
try:
|
||||||
except Exception as e:
|
logger.info('[download() thread] : Trying getting credentials in the config file')
|
||||||
raise IOError(str(e))
|
with open(CST_FOLDER + 'conf.ig', 'rb') as (config):
|
||||||
else:
|
AESObj = AESCipher(CST_CRYPTOKEY)
|
||||||
logger.info('[download() thread] : Got credentials !')
|
try:
|
||||||
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
tempone = AESObj.decrypt(config.read())
|
||||||
logger.info('[download() thread] : Authenticated to proxy successfully')
|
if tempone != '||':
|
||||||
except IOError as e:
|
if tempone.find('||') != -1:
|
||||||
logger.error('[download() thread] : False or absent credentials in the config file : ' + str(e))
|
IPN, IPN_PASS = tempone.split('||')[0:2]
|
||||||
NoConnect = True
|
else:
|
||||||
while NoConnect:
|
raise ValueError('Cryptokey is bad !')
|
||||||
|
else:
|
||||||
class LoginDialog(Toplevel):
|
IPN = ''
|
||||||
|
IPN_PASS = ''
|
||||||
def __init__(self, parent):
|
except Exception as e:
|
||||||
super().__init__(parent)
|
raise IOError(str(e))
|
||||||
self.title('Connexion')
|
else:
|
||||||
Label(self, text='IPN : ').pack()
|
logger.info('[download() thread] : Got credentials !')
|
||||||
self.entry_login = Entry(self)
|
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
||||||
self.entry_login.insert(0, '')
|
logger.info('[download() thread] : Authenticated to proxy successfully')
|
||||||
self.entry_login.pack()
|
except IOError as e:
|
||||||
Label(self, text='Mot de passe : ').pack()
|
logger.error('[download() thread] : False or absent credentials in the config file : ' + str(e))
|
||||||
self.entry_pass = Entry(self, show='*')
|
NoConnect = True
|
||||||
self.entry_pass.insert(0, '')
|
while NoConnect:
|
||||||
self.entry_pass.pack()
|
|
||||||
Button(self, text='Connexion', command=(self.connecti)).pack()
|
class LoginDialog(Toplevel):
|
||||||
self.resizable(width=False, height=False)
|
|
||||||
w = 150
|
def __init__(self, parent):
|
||||||
h = 110
|
super().__init__(parent)
|
||||||
self.update()
|
self.title('Connexion')
|
||||||
ws = self.winfo_screenwidth()
|
Label(self, text='IPN : ').pack()
|
||||||
hs = self.winfo_screenheight()
|
self.entry_login = Entry(self)
|
||||||
if getattr(sys, 'frozen', False):
|
self.entry_login.insert(0, '')
|
||||||
self.iconbitmap(sys._MEIPASS + '\\id-card.ico\\id-card.ico')
|
self.entry_login.pack()
|
||||||
else:
|
Label(self, text='Mot de passe : ').pack()
|
||||||
self.iconbitmap('id-card.ico')
|
self.entry_pass = Entry(self, show='*')
|
||||||
upwin.update()
|
self.entry_pass.insert(0, '')
|
||||||
x = ws / 2 - w / 2
|
self.entry_pass.pack()
|
||||||
y = hs / 2 - h / 2
|
Button(self, text='Connexion', command=(self.connecti)).pack()
|
||||||
self.geometry('%dx%d+%d+%d' % (w, h, x, y))
|
self.resizable(width=False, height=False)
|
||||||
|
w = 150
|
||||||
def connecti(self):
|
h = 110
|
||||||
global key
|
self.update()
|
||||||
global login
|
ws = self.winfo_screenwidth()
|
||||||
login = self.entry_login.get().strip()
|
hs = self.winfo_screenheight()
|
||||||
key = self.entry_pass.get().strip()
|
if getattr(sys, 'frozen', False):
|
||||||
self.destroy()
|
self.iconbitmap(sys._MEIPASS + '\\id-card.ico\\id-card.ico')
|
||||||
|
else:
|
||||||
session = PACSession()
|
self.iconbitmap('id-card.ico')
|
||||||
if session.get_pac() == None:
|
upwin.update()
|
||||||
IPN = ''
|
x = ws / 2 - w / 2
|
||||||
IPN_PASS = ''
|
y = hs / 2 - h / 2
|
||||||
NoConnect = False
|
self.geometry('%dx%d+%d+%d' % (w, h, x, y))
|
||||||
break
|
|
||||||
canvas.itemconfigure(message, text='En attente de connexion au serveur proxy...')
|
def connecti(self):
|
||||||
login = ''
|
global key
|
||||||
key = ''
|
global login
|
||||||
result = LoginDialog(upwin)
|
login = self.entry_login.get().strip()
|
||||||
result.transient(upwin)
|
key = self.entry_pass.get().strip()
|
||||||
result.grab_set()
|
self.destroy()
|
||||||
upwin.wait_window(result)
|
|
||||||
IPN = login
|
session = PACSession()
|
||||||
IPN_PASS = key
|
if session.get_pac() == None:
|
||||||
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
IPN = ''
|
||||||
Ans = session.get('http://www.google.com')
|
IPN_PASS = ''
|
||||||
if str(Ans) == '<Response [407]>':
|
NoConnect = False
|
||||||
canvas.itemconfigure(message, text='Identifiants erronés, accès refusé')
|
break
|
||||||
logger.info('[download() thread] : 407 Error')
|
canvas.itemconfigure(message, text='En attente de connexion au serveur proxy...')
|
||||||
time.sleep(1)
|
login = ''
|
||||||
else:
|
key = ''
|
||||||
if str(Ans) == '<Response [200]>':
|
result = LoginDialog(upwin)
|
||||||
logger.info('[download() thread] : Connection ok !')
|
result.transient(upwin)
|
||||||
NoConnect = False
|
result.grab_set()
|
||||||
else:
|
upwin.wait_window(result)
|
||||||
raise IOError()
|
IPN = login
|
||||||
|
IPN_PASS = key
|
||||||
AESObj = AESCipher(CST_CRYPTOKEY)
|
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
||||||
with open(CST_FOLDER + 'conf.ig', 'wb+') as (f):
|
Ans = session.get('http://www.google.com')
|
||||||
logger.info('[download() thread] : Saving credentials in encrypted config file')
|
if str(Ans) == '<Response [407]>':
|
||||||
f.write(AESObj.encrypt(IPN + '||' + IPN_PASS))
|
canvas.itemconfigure(message, text='Identifiants erronés, accès refusé')
|
||||||
|
logger.info('[download() thread] : 407 Error')
|
||||||
if IPN == 'i005316':
|
time.sleep(1)
|
||||||
canvas.itemconfigure(message, text='Bienvenue Thierry !')
|
else:
|
||||||
else:
|
if str(Ans) == '<Response [200]>':
|
||||||
if IPN == 'i020251':
|
logger.info('[download() thread] : Connection ok !')
|
||||||
canvas.itemconfigure(message, text='Bienvenue Samia !')
|
NoConnect = False
|
||||||
else:
|
else:
|
||||||
if IPN == 'i018410':
|
raise IOError()
|
||||||
canvas.itemconfigure(message, text='Bienvenue Adrien !')
|
|
||||||
else:
|
AESObj = AESCipher(CST_CRYPTOKEY)
|
||||||
if IPN == 'i003067':
|
with open(CST_FOLDER + 'conf.ig', 'wb+') as (f):
|
||||||
canvas.itemconfigure(message, text='Bienvenue Remy !')
|
logger.info('[download() thread] : Saving credentials in encrypted config file')
|
||||||
else:
|
f.write(AESObj.encrypt(IPN + '||' + IPN_PASS))
|
||||||
if IPN == 'i018422':
|
|
||||||
canvas.itemconfigure(message, text='Bienvenue Eloise !')
|
if IPN == 'i005316':
|
||||||
time.sleep(1)
|
canvas.itemconfigure(message, text='Bienvenue Thierry !')
|
||||||
try:
|
else:
|
||||||
Prox_us = session.get_pac().find_proxy_for_url(CST_LINK, 'neoxgroup.eu')
|
if IPN == 'i020251':
|
||||||
PROXY_USABLE = Prox_us[6:-1].split(';')[0]
|
canvas.itemconfigure(message, text='Bienvenue Samia !')
|
||||||
proxy_server_url = IPN + ':' + IPN_PASS + '@' + PROXY_USABLE
|
else:
|
||||||
ph = urllib2.ProxyHandler({'http': proxy_server_url})
|
if IPN == 'i018410':
|
||||||
auth = urllib2.ProxyBasicAuthHandler()
|
canvas.itemconfigure(message, text='Bienvenue Adrien !')
|
||||||
server = urllib2.build_opener(ph, auth, urllib2.HTTPHandler)
|
else:
|
||||||
urllib2.install_opener(server)
|
if IPN == 'i003067':
|
||||||
logger.info('[download() thread] : Proxy connection initiated successfully')
|
canvas.itemconfigure(message, text='Bienvenue Remy !')
|
||||||
except:
|
else:
|
||||||
logger.info('[download() thread] : Proxy connection not initiated')
|
if IPN == 'i018422':
|
||||||
|
canvas.itemconfigure(message, text='Bienvenue Eloise !')
|
||||||
try:
|
time.sleep(1)
|
||||||
urllib2.urlretrieve(url, filename)
|
try:
|
||||||
return True
|
Prox_us = session.get_pac().find_proxy_for_url(CST_LINK, 'neoxgroup.eu')
|
||||||
except Exception as e:
|
PROXY_USABLE = Prox_us[6:-1].split(';')[0]
|
||||||
logger.error('[download() thread] : HTTP ERROR ')
|
proxy_server_url = IPN + ':' + IPN_PASS + '@' + PROXY_USABLE
|
||||||
return e
|
ph = urllib2.ProxyHandler({'http': proxy_server_url})
|
||||||
|
auth = urllib2.ProxyBasicAuthHandler()
|
||||||
logger.info('[updator() thread] : Prepare downloading the version recap file...')
|
server = urllib2.build_opener(ph, auth, urllib2.HTTPHandler)
|
||||||
tempfile = CST_FOLDER + 'temp' + str(random.randint(11111, 99999)) + '.cniu'
|
urllib2.install_opener(server)
|
||||||
isOk = download(CST_LINK + 'cnir.ver', tempfile)
|
logger.info('[download() thread] : Proxy connection initiated successfully')
|
||||||
if not isOk:
|
except:
|
||||||
raise isOk
|
logger.info('[download() thread] : Proxy connection not initiated')
|
||||||
urllib2.urlcleanup()
|
|
||||||
logger.info('[updator() thread] : Opening version recap file...')
|
try:
|
||||||
file_ver = open(tempfile, 'r')
|
urllib2.urlretrieve(url, filename)
|
||||||
logger.info('[updator() thread] : Reading version recap file...')
|
return True
|
||||||
version = file_ver.read()
|
except Exception as e:
|
||||||
logger.info('[updator() thread] : Closing version recap file...')
|
logger.error('[download() thread] : HTTP ERROR ')
|
||||||
repert = version.split('|')
|
return e
|
||||||
file_ver.close()
|
|
||||||
logger.info('[updator() thread] : Deleting version recap file...')
|
logger.info('[updator() thread] : Prepare downloading the version recap file...')
|
||||||
os.remove(tempfile)
|
tempfile = CST_FOLDER + 'temp' + str(random.randint(11111, 99999)) + '.cniu'
|
||||||
logger.info('[updator() thread] : Parsing informations about version...')
|
isOk = download(CST_LINK + 'cnir.ver', tempfile)
|
||||||
final_f = 'CNI_file'
|
if not isOk:
|
||||||
final_ver = ['0', '0', '0']
|
raise isOk
|
||||||
final_hash = ''
|
urllib2.urlcleanup()
|
||||||
for sentence in repert:
|
logger.info('[updator() thread] : Opening version recap file...')
|
||||||
try:
|
file_ver = open(tempfile, 'r')
|
||||||
file, hashref = sentence.split(':')
|
logger.info('[updator() thread] : Reading version recap file...')
|
||||||
except ValueError:
|
version = file_ver.read()
|
||||||
pass
|
logger.info('[updator() thread] : Closing version recap file...')
|
||||||
else:
|
repert = version.split('|')
|
||||||
if str.startswith(file, CST_NAME):
|
file_ver.close()
|
||||||
ver = file.replace(CST_NAME + '_', '').split('.')
|
logger.info('[updator() thread] : Deleting version recap file...')
|
||||||
temp = [
|
os.remove(tempfile)
|
||||||
'0', '0', '0']
|
logger.info('[updator() thread] : Parsing informations about version...')
|
||||||
for i in range(len(ver)):
|
final_f = 'CNI_file'
|
||||||
temp[i] = ver[i]
|
final_ver = ['0', '0', '0']
|
||||||
|
final_hash = ''
|
||||||
ver = temp.copy()
|
for sentence in repert:
|
||||||
sum_fver = int(final_ver[0]) * 100 + int(final_ver[1]) * 10 + int(final_ver[2])
|
try:
|
||||||
sum_ver = int(ver[0]) * 100 + int(ver[1]) * 10 + int(ver[2])
|
file, hashref = sentence.split(':')
|
||||||
if sum_ver > sum_fver:
|
except ValueError:
|
||||||
final_ver = ver.copy()
|
pass
|
||||||
final_f = file
|
else:
|
||||||
final_hash = hashref
|
if str.startswith(file, CST_NAME):
|
||||||
|
ver = file.replace(CST_NAME + '_', '').split('.')
|
||||||
sum_ver = int(final_ver[0]) * 100 + int(final_ver[1]) * 10 + int(final_ver[2])
|
temp = [
|
||||||
if final_f != 'CNI_file':
|
'0', '0', '0']
|
||||||
if sum_ver > CST_SUM_VER:
|
for i in range(len(ver)):
|
||||||
logger.info('[updator() thread] : New version of CNIRevelator found !')
|
temp[i] = ver[i]
|
||||||
canvas.itemconfigure(message, text='Mise à jour disponible ! Préparation du téléchargement...')
|
|
||||||
logger.info('[updator() thread] : Preparing download')
|
ver = temp.copy()
|
||||||
with open(CST_FOLDER + 'conf.ig', 'rb') as (config):
|
sum_fver = int(final_ver[0]) * 100 + int(final_ver[1]) * 10 + int(final_ver[2])
|
||||||
logger.info('[updator() thread] : Reading credentials for proxy in config file...')
|
sum_ver = int(ver[0]) * 100 + int(ver[1]) * 10 + int(ver[2])
|
||||||
AESObj = AESCipher(CST_CRYPTOKEY)
|
if sum_ver > sum_fver:
|
||||||
IPN, IPN_PASS = AESObj.decrypt(config.read()).split('||')[0:2]
|
final_ver = ver.copy()
|
||||||
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
final_f = file
|
||||||
try:
|
final_hash = hashref
|
||||||
Prox_us = session.get_pac().find_proxy_for_url(CST_LINK, 'neoxgroup.eu')
|
|
||||||
PROXY_USABLE = Prox_us[6:-1].split(';')[0]
|
sum_ver = int(final_ver[0]) * 100 + int(final_ver[1]) * 10 + int(final_ver[2])
|
||||||
proxy_server_url = IPN + ':' + IPN_PASS + '@' + PROXY_USABLE
|
if final_f != 'CNI_file':
|
||||||
ph = urllib2.ProxyHandler({'http': proxy_server_url})
|
if sum_ver > CST_SUM_VER:
|
||||||
auth = urllib2.ProxyBasicAuthHandler()
|
logger.info('[updator() thread] : New version of CNIRevelator found !')
|
||||||
server = urllib2.build_opener(ph, auth, urllib2.HTTPHandler)
|
canvas.itemconfigure(message, text='Mise à jour disponible ! Préparation du téléchargement...')
|
||||||
logger.info('[updator() thread] : Connection to the proxy initiated successfully !')
|
logger.info('[updator() thread] : Preparing download')
|
||||||
except:
|
with open(CST_FOLDER + 'conf.ig', 'rb') as (config):
|
||||||
canvas.itemconfigure(message, text='Téléchargement en connexion directe...')
|
logger.info('[updator() thread] : Reading credentials for proxy in config file...')
|
||||||
server = urllib2.build_opener()
|
AESObj = AESCipher(CST_CRYPTOKEY)
|
||||||
logger.info('[updator() thread] : Direct connection initiated successfully')
|
IPN, IPN_PASS = AESObj.decrypt(config.read()).split('||')[0:2]
|
||||||
|
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
||||||
logger.info('[updator() thread] : Launching download of ' + final_f)
|
try:
|
||||||
Statut = Download(CST_LINK + final_f, final_f, final_f, server, p, canvas, message, logger)
|
Prox_us = session.get_pac().find_proxy_for_url(CST_LINK, 'neoxgroup.eu')
|
||||||
BLOCKSIZE = 65536
|
PROXY_USABLE = Prox_us[6:-1].split(';')[0]
|
||||||
hasher = hashlib.sha1()
|
proxy_server_url = IPN + ':' + IPN_PASS + '@' + PROXY_USABLE
|
||||||
try:
|
ph = urllib2.ProxyHandler({'http': proxy_server_url})
|
||||||
with open(final_f, 'rb') as (afile):
|
auth = urllib2.ProxyBasicAuthHandler()
|
||||||
buf = afile.read(BLOCKSIZE)
|
server = urllib2.build_opener(ph, auth, urllib2.HTTPHandler)
|
||||||
while len(buf) > 0:
|
logger.info('[updator() thread] : Connection to the proxy initiated successfully !')
|
||||||
hasher.update(buf)
|
except:
|
||||||
buf = afile.read(BLOCKSIZE)
|
canvas.itemconfigure(message, text='Téléchargement en connexion directe...')
|
||||||
|
server = urllib2.build_opener()
|
||||||
hashcod = hasher.hexdigest()
|
logger.info('[updator() thread] : Direct connection initiated successfully')
|
||||||
if hashcod != final_hash:
|
|
||||||
Statut.success = False
|
logger.info('[updator() thread] : Launching download of ' + final_f)
|
||||||
logger.error('[updator() thread] : Hashcode Error :' + final_f)
|
Statut = Download(CST_LINK + final_f, final_f, final_f, server, p, canvas, message, logger)
|
||||||
try:
|
BLOCKSIZE = 65536
|
||||||
os.remove(final_f)
|
hasher = hashlib.sha1()
|
||||||
except IOError:
|
try:
|
||||||
pass
|
with open(final_f, 'rb') as (afile):
|
||||||
|
buf = afile.read(BLOCKSIZE)
|
||||||
else:
|
while len(buf) > 0:
|
||||||
logger.info('[updator() thread] : Hashcode pass :' + final_f)
|
hasher.update(buf)
|
||||||
except FileNotFoundError as e:
|
buf = afile.read(BLOCKSIZE)
|
||||||
logger.error('[updator() thread] : File not found ' + final_f)
|
|
||||||
|
hashcod = hasher.hexdigest()
|
||||||
if Statut.success:
|
if hashcod != final_hash:
|
||||||
try:
|
Statut.success = False
|
||||||
os.rename(final_f, final_f + '.exe')
|
logger.error('[updator() thread] : Hashcode Error :' + final_f)
|
||||||
except IOError:
|
try:
|
||||||
logger.error('[updator() thread] : Unable to rename the file ! Wait 3 sec and retry')
|
os.remove(final_f)
|
||||||
time.sleep(3)
|
except IOError:
|
||||||
try:
|
pass
|
||||||
os.rename(final_f, final_f + '.exe')
|
|
||||||
except IOError:
|
else:
|
||||||
logger.critical('[updator() thread] : Unable to rename the file !')
|
logger.info('[updator() thread] : Hashcode pass :' + final_f)
|
||||||
|
except FileNotFoundError as e:
|
||||||
else:
|
logger.error('[updator() thread] : File not found ' + final_f)
|
||||||
canvas.itemconfigure(message, text='Téléchargement terminé ! Préparation du lancement...')
|
|
||||||
logger.info('[updator() thread] : Download of ' + final_f + 'finished successfully')
|
if Statut.success:
|
||||||
p.configure(mode='indeterminate', value=0, maximum=20)
|
try:
|
||||||
p.start()
|
os.rename(final_f, final_f + '.exe')
|
||||||
time.sleep(1)
|
except IOError:
|
||||||
logger.info('[updator() thread] : Launching ' + final_f)
|
logger.error('[updator() thread] : Unable to rename the file ! Wait 3 sec and retry')
|
||||||
try:
|
time.sleep(3)
|
||||||
proc = subprocess.Popen((final_f + '.exe'), shell=False, stdin=None, stdout=None, stderr=None, close_fds=True)
|
try:
|
||||||
except:
|
os.rename(final_f, final_f + '.exe')
|
||||||
logger.error('[updator() thread] : Unable to start the new version ! Wait 3 sec and retry')
|
except IOError:
|
||||||
time.sleep(3)
|
logger.critical('[updator() thread] : Unable to rename the file !')
|
||||||
try:
|
|
||||||
proc = subprocess.Popen((final_f + '.exe'), shell=False, stdin=None, stdout=None, stderr=None, close_fds=True)
|
else:
|
||||||
except Exception as e:
|
canvas.itemconfigure(message, text='Téléchargement terminé ! Préparation du lancement...')
|
||||||
logger.critical('[updator() thread] : Unable to start the new version ! Stopping : ' + str(e))
|
logger.info('[updator() thread] : Download of ' + final_f + 'finished successfully')
|
||||||
showerror("Erreur d'appel de procédure distante", 'Le lancement du nouveau programme a échoué, vous devez le lancer manuellement une fois cette fenêtre fermée', parent=upwin)
|
p.configure(mode='indeterminate', value=0, maximum=20)
|
||||||
|
p.start()
|
||||||
ret = 12
|
time.sleep(1)
|
||||||
else:
|
logger.info('[updator() thread] : Launching ' + final_f)
|
||||||
canvas.itemconfigure(message, text='Echec de la mise à jour : Erreur HTTP. Préparation du lancement...')
|
try:
|
||||||
logger.error('[updator() thread] : Update has failed with HTTP error')
|
proc = subprocess.Popen((final_f + '.exe'), shell=False, stdin=None, stdout=None, stderr=None, close_fds=True)
|
||||||
time.sleep(1)
|
except:
|
||||||
canvas.itemconfigure(message, text='Logiciel déjà à jour. Préparation du lancement...')
|
logger.error('[updator() thread] : Unable to start the new version ! Wait 3 sec and retry')
|
||||||
logger.info('[updator() thread] : CNIRevelator is up to date !')
|
time.sleep(3)
|
||||||
time.sleep(1)
|
try:
|
||||||
ret = 11
|
proc = subprocess.Popen((final_f + '.exe'), shell=False, stdin=None, stdout=None, stderr=None, close_fds=True)
|
||||||
if os.path.exists(CST_FOLDER + 'Tesseract-OCR4\\tesseract.exe'):
|
except Exception as e:
|
||||||
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
logger.critical('[updator() thread] : Unable to start the new version ! Stopping : ' + str(e))
|
||||||
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
showerror("Erreur d'appel de procédure distante", 'Le lancement du nouveau programme a échoué, vous devez le lancer manuellement une fois cette fenêtre fermée', parent=upwin)
|
||||||
else:
|
|
||||||
final_f = 'tesseract_4'
|
ret = 12
|
||||||
logger.info('[updator() thread] : Downloading tesseract 4 !')
|
else:
|
||||||
canvas.itemconfigure(message, text='Mise à jour du module OCR ! Préparation du téléchargement...')
|
canvas.itemconfigure(message, text='Echec de la mise à jour : Erreur HTTP. Préparation du lancement...')
|
||||||
logger.info('[updator() thread] : Preparing download')
|
logger.error('[updator() thread] : Update has failed with HTTP error')
|
||||||
with open(CST_FOLDER + 'conf.ig', 'rb') as (config):
|
time.sleep(1)
|
||||||
logger.info('[updator() thread] : Reading credentials for proxy in config file...')
|
canvas.itemconfigure(message, text='Logiciel déjà à jour. Préparation du lancement...')
|
||||||
AESObj = AESCipher(CST_CRYPTOKEY)
|
logger.info('[updator() thread] : CNIRevelator is up to date !')
|
||||||
IPN, IPN_PASS = AESObj.decrypt(config.read()).split('||')[0:2]
|
time.sleep(1)
|
||||||
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
ret = 11
|
||||||
try:
|
if os.path.exists(CST_FOLDER + 'Tesseract-OCR4\\tesseract.exe'):
|
||||||
Prox_us = session.get_pac().find_proxy_for_url(CST_LINK, 'neoxgroup.eu')
|
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
||||||
PROXY_USABLE = Prox_us[6:-1].split(';')[0]
|
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
||||||
proxy_server_url = IPN + ':' + IPN_PASS + '@' + PROXY_USABLE
|
else:
|
||||||
ph = urllib2.ProxyHandler({'http': proxy_server_url})
|
final_f = 'tesseract_4'
|
||||||
auth = urllib2.ProxyBasicAuthHandler()
|
logger.info('[updator() thread] : Downloading tesseract 4 !')
|
||||||
server = urllib2.build_opener(ph, auth, urllib2.HTTPHandler)
|
canvas.itemconfigure(message, text='Mise à jour du module OCR ! Préparation du téléchargement...')
|
||||||
logger.info('[updator() thread] : Connection to the proxy initiated successfully !')
|
logger.info('[updator() thread] : Preparing download')
|
||||||
except:
|
with open(CST_FOLDER + 'conf.ig', 'rb') as (config):
|
||||||
canvas.itemconfigure(message, text='Téléchargement en connexion directe...')
|
logger.info('[updator() thread] : Reading credentials for proxy in config file...')
|
||||||
server = urllib2.build_opener()
|
AESObj = AESCipher(CST_CRYPTOKEY)
|
||||||
logger.info('[updator() thread] : Direct connection initiated successfully')
|
IPN, IPN_PASS = AESObj.decrypt(config.read()).split('||')[0:2]
|
||||||
|
session = PACSession(proxy_auth=(HTTPProxyAuth(IPN, IPN_PASS)))
|
||||||
logger.info('[updator() thread] : Launching download of ' + final_f)
|
try:
|
||||||
Statut = Download(CST_LINK + final_f, CST_FOLDER + final_f, final_f, server, p, canvas, message, logger)
|
Prox_us = session.get_pac().find_proxy_for_url(CST_LINK, 'neoxgroup.eu')
|
||||||
hashcod = ''
|
PROXY_USABLE = Prox_us[6:-1].split(';')[0]
|
||||||
logger.info('[updator() thread] : Verifying hashcode of ' + final_f)
|
proxy_server_url = IPN + ':' + IPN_PASS + '@' + PROXY_USABLE
|
||||||
BLOCKSIZE = 65536
|
ph = urllib2.ProxyHandler({'http': proxy_server_url})
|
||||||
hasher = hashlib.sha1()
|
auth = urllib2.ProxyBasicAuthHandler()
|
||||||
try:
|
server = urllib2.build_opener(ph, auth, urllib2.HTTPHandler)
|
||||||
with open(CST_FOLDER + final_f, 'rb') as (afile):
|
logger.info('[updator() thread] : Connection to the proxy initiated successfully !')
|
||||||
buf = afile.read(BLOCKSIZE)
|
except:
|
||||||
while len(buf) > 0:
|
canvas.itemconfigure(message, text='Téléchargement en connexion directe...')
|
||||||
hasher.update(buf)
|
server = urllib2.build_opener()
|
||||||
buf = afile.read(BLOCKSIZE)
|
logger.info('[updator() thread] : Direct connection initiated successfully')
|
||||||
|
|
||||||
hashcod = hasher.hexdigest()
|
logger.info('[updator() thread] : Launching download of ' + final_f)
|
||||||
if hashcod != CST_TesserHash:
|
Statut = Download(CST_LINK + final_f, CST_FOLDER + final_f, final_f, server, p, canvas, message, logger)
|
||||||
Statut.success = False
|
hashcod = ''
|
||||||
logger.error('[updator() thread] : Hashcode Error : ' + final_f)
|
logger.info('[updator() thread] : Verifying hashcode of ' + final_f)
|
||||||
try:
|
BLOCKSIZE = 65536
|
||||||
os.remove(CST_FOLDER + final_f)
|
hasher = hashlib.sha1()
|
||||||
except IOError:
|
try:
|
||||||
pass
|
with open(CST_FOLDER + final_f, 'rb') as (afile):
|
||||||
|
buf = afile.read(BLOCKSIZE)
|
||||||
else:
|
while len(buf) > 0:
|
||||||
logger.info('[updator() thread] : Hashcode pass : ' + final_f)
|
hasher.update(buf)
|
||||||
except FileNotFoundError as e:
|
buf = afile.read(BLOCKSIZE)
|
||||||
logger.error('[updator() thread] : File not found ' + final_f)
|
|
||||||
|
hashcod = hasher.hexdigest()
|
||||||
if Statut.success:
|
if hashcod != CST_TesserHash:
|
||||||
canvas.itemconfigure(message, text='Téléchargement terminé ! Installation...')
|
Statut.success = False
|
||||||
logger.info('[updator() thread] : Download of ' + final_f + 'finished successfully')
|
logger.error('[updator() thread] : Hashcode Error : ' + final_f)
|
||||||
p.configure(mode='indeterminate', value=0, maximum=20)
|
try:
|
||||||
p.start()
|
os.remove(CST_FOLDER + final_f)
|
||||||
try:
|
except IOError:
|
||||||
zip_ref = zipfile.ZipFile(CST_FOLDER + final_f, 'r')
|
pass
|
||||||
zip_ref.extractall(CST_FOLDER)
|
|
||||||
zip_ref.close()
|
else:
|
||||||
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
logger.info('[updator() thread] : Hashcode pass : ' + final_f)
|
||||||
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
except FileNotFoundError as e:
|
||||||
canvas.itemconfigure(message, text='Installation terminée !')
|
logger.error('[updator() thread] : File not found ' + final_f)
|
||||||
except:
|
|
||||||
logger.error('[updator() thread] : Unable to install the module. Wait and retry')
|
if Statut.success:
|
||||||
time.sleep(3)
|
canvas.itemconfigure(message, text='Téléchargement terminé ! Installation...')
|
||||||
try:
|
logger.info('[updator() thread] : Download of ' + final_f + 'finished successfully')
|
||||||
zip_ref = zipfile.ZipFile(CST_FOLDER + final_f, 'r')
|
p.configure(mode='indeterminate', value=0, maximum=20)
|
||||||
zip_ref.extractall(CST_FOLDER)
|
p.start()
|
||||||
zip_ref.close()
|
try:
|
||||||
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
zip_ref = zipfile.ZipFile(CST_FOLDER + final_f, 'r')
|
||||||
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
zip_ref.extractall(CST_FOLDER)
|
||||||
canvas.itemconfigure(message, text='Installation terminée !')
|
zip_ref.close()
|
||||||
except Exception as e:
|
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
||||||
logger.critical('[updator() thread] : Unable to install the module ! Stopping : ' + str(e))
|
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
||||||
showerror("Erreur d'appel de procédure distante", "L'installation du module OCR a échoué, contactez le développeur.")
|
canvas.itemconfigure(message, text='Installation terminée !')
|
||||||
|
except:
|
||||||
ret = 11
|
logger.error('[updator() thread] : Unable to install the module. Wait and retry')
|
||||||
else:
|
time.sleep(3)
|
||||||
logger.critical('[updator() thread] : Unable to download the module ! ')
|
try:
|
||||||
showerror('Erreur de téléchargement', "L'installation du module OCR a échoué, merci d'indiquer le chemin d'accès au fichier tesseract_4 dans la fenêtre suivante")
|
zip_ref = zipfile.ZipFile(CST_FOLDER + final_f, 'r')
|
||||||
path = filedialog.askopenfilename(title="Indiquez le chemin d'accès à tesseract_4...", filetypes=(('Tesseract_4', '*.cni4'),
|
zip_ref.extractall(CST_FOLDER)
|
||||||
('Tesseract_4', '*.cni4')))
|
zip_ref.close()
|
||||||
if path != '':
|
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
||||||
try:
|
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
||||||
canvas.itemconfigure(message, text='Installation...')
|
canvas.itemconfigure(message, text='Installation terminée !')
|
||||||
zip_ref = zipfile.ZipFile(path, 'r')
|
except Exception as e:
|
||||||
zip_ref.extractall(CST_FOLDER)
|
logger.critical('[updator() thread] : Unable to install the module ! Stopping : ' + str(e))
|
||||||
zip_ref.close()
|
showerror("Erreur d'appel de procédure distante", "L'installation du module OCR a échoué, contactez le développeur.")
|
||||||
logger.error('[updator() thread] : Manual installation successed')
|
|
||||||
canvas.itemconfigure(message, text='Installation terminée !')
|
ret = 11
|
||||||
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
else:
|
||||||
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
logger.critical('[updator() thread] : Unable to download the module ! ')
|
||||||
except Exception as e:
|
showerror('Erreur de téléchargement', "L'installation du module OCR a échoué, merci d'indiquer le chemin d'accès au fichier tesseract_4 dans la fenêtre suivante")
|
||||||
logger.error('[updator() thread] : Manual installation has failed' + str(e))
|
path = filedialog.askopenfilename(title="Indiquez le chemin d'accès à tesseract_4...", filetypes=(('Tesseract_4', '*.cni4'),
|
||||||
showerror('Erreur de lecture', "Le module OCR n'a pas pu être installé, la saisie automatique de scans ne pourra donc fonctionner")
|
('Tesseract_4', '*.cni4')))
|
||||||
|
if path != '':
|
||||||
else:
|
try:
|
||||||
showerror('Opération annulée', "Le module OCR n'a été installé, la saisie automatique de scans ne pourra donc fonctionner")
|
canvas.itemconfigure(message, text='Installation...')
|
||||||
except URLExcept.HTTPError as e:
|
zip_ref = zipfile.ZipFile(path, 'r')
|
||||||
canvas.itemconfigure(message, text=('Echec de la mise à jour : Erreur HTTP ' + str(e.code) + ' . Préparation du lancement...'))
|
zip_ref.extractall(CST_FOLDER)
|
||||||
logger.error('[updator() thread] : Update has failed with HTTP error' + str(e.code))
|
zip_ref.close()
|
||||||
if int(e.code) == 407:
|
logger.error('[updator() thread] : Manual installation successed')
|
||||||
showerror('Erreur 407', 'Attention : le système de mise à jour automatique a fait face à une erreur 407, signifiant que la connexion au serveur proxy a été refusée. Vos identifiants vous seront redemandés au prochain démarrage. La mise à jour a échoué.')
|
canvas.itemconfigure(message, text='Installation terminée !')
|
||||||
logger.info('[updator() thread] : Credential error. Deleting the config file...')
|
os.environ['PATH'] = CST_FOLDER + 'Tesseract-OCR4\\'
|
||||||
os.remove(CST_FOLDER + 'conf.ig')
|
os.environ['TESSDATA_PREFIX'] = CST_FOLDER + 'Tesseract-OCR4\\tessdata'
|
||||||
p.configure(mode='indeterminate', value=0, maximum=20)
|
except Exception as e:
|
||||||
p.start()
|
logger.error('[updator() thread] : Manual installation has failed' + str(e))
|
||||||
time.sleep(3)
|
showerror('Erreur de lecture', "Le module OCR n'a pas pu être installé, la saisie automatique de scans ne pourra donc fonctionner")
|
||||||
except Exception as e:
|
|
||||||
canvas.itemconfigure(message, text='Echec de la mise à jour. Préparation du lancement...')
|
else:
|
||||||
logger.error('[updator() thread] : Error from the updating system : ' + str(e))
|
showerror('Opération annulée', "Le module OCR n'a été installé, la saisie automatique de scans ne pourra donc fonctionner")
|
||||||
p.configure(mode='indeterminate', value=0, maximum=20)
|
except URLExcept.HTTPError as e:
|
||||||
p.start()
|
canvas.itemconfigure(message, text=('Echec de la mise à jour : Erreur HTTP ' + str(e.code) + ' . Préparation du lancement...'))
|
||||||
time.sleep(2)
|
logger.error('[updator() thread] : Update has failed with HTTP error' + str(e.code))
|
||||||
|
if int(e.code) == 407:
|
||||||
p.stop()
|
showerror('Erreur 407', 'Attention : le système de mise à jour automatique a fait face à une erreur 407, signifiant que la connexion au serveur proxy a été refusée. Vos identifiants vous seront redemandés au prochain démarrage. La mise à jour a échoué.')
|
||||||
upwin.destroy()
|
logger.info('[updator() thread] : Credential error. Deleting the config file...')
|
||||||
root.destroy()
|
os.remove(CST_FOLDER + 'conf.ig')
|
||||||
return ret
|
p.configure(mode='indeterminate', value=0, maximum=20)
|
||||||
|
p.start()
|
||||||
logger.info('updating() : Launching updator() thread...')
|
time.sleep(3)
|
||||||
threading.Thread(target=updator, daemon=True).start()
|
except Exception as e:
|
||||||
logger.info('updating() [Thread] : Ending updator() thread')
|
canvas.itemconfigure(message, text='Echec de la mise à jour. Préparation du lancement...')
|
||||||
|
logger.error('[updator() thread] : Error from the updating system : ' + str(e))
|
||||||
ret = 11
|
p.configure(mode='indeterminate', value=0, maximum=20)
|
||||||
root = Tk()
|
p.start()
|
||||||
root.attributes('-alpha', 0.0)
|
time.sleep(2)
|
||||||
root.iconify()
|
|
||||||
upwin = Toplevel(root)
|
p.stop()
|
||||||
upwin.overrideredirect(1)
|
upwin.destroy()
|
||||||
upwin.configure(bg=CST_COLOR)
|
root.destroy()
|
||||||
upwin.resizable(width=False, height=False)
|
return ret
|
||||||
w = 600
|
|
||||||
h = 300
|
logger.info('updating() : Launching updator() thread...')
|
||||||
upwin.update()
|
threading.Thread(target=updator, daemon=True).start()
|
||||||
canvas = Canvas(upwin, width=600, height=270, bg=CST_COLOR, highlightthickness=0)
|
logger.info('updating() [Thread] : Ending updator() thread')
|
||||||
pbar = Canvas(upwin, width=600, height=30, bg=CST_COLOR)
|
|
||||||
p = ttk.Progressbar(pbar, orient=HORIZONTAL, length=590, mode='determinate')
|
ret = 11
|
||||||
upwin.update()
|
root = Tk()
|
||||||
ws = upwin.winfo_screenwidth()
|
root.attributes('-alpha', 0.0)
|
||||||
hs = upwin.winfo_screenheight()
|
root.iconify()
|
||||||
canvas.create_text((w / 2), (h / 3), text=(CST_NAME + ' ' + CST_VERTITLE), font='Calibri 30 bold', fill='white')
|
upwin = Toplevel(root)
|
||||||
message = canvas.create_text((w / 2), (h / 1.15), text=' ', font='Calibri 9', fill='white')
|
upwin.overrideredirect(1)
|
||||||
upwin.update()
|
upwin.configure(bg=CST_COLOR)
|
||||||
x = ws / 2 - w / 2
|
upwin.resizable(width=False, height=False)
|
||||||
y = hs / 2 - h / 2
|
w = 600
|
||||||
upwin.geometry('%dx%d+%d+%d' % (w, h, x, y))
|
h = 300
|
||||||
canvas.grid()
|
upwin.update()
|
||||||
pbar.grid()
|
canvas = Canvas(upwin, width=600, height=270, bg=CST_COLOR, highlightthickness=0)
|
||||||
p.grid()
|
pbar = Canvas(upwin, width=600, height=30, bg=CST_COLOR)
|
||||||
upwin.after(2000, updating)
|
p = ttk.Progressbar(pbar, orient=HORIZONTAL, length=590, mode='determinate')
|
||||||
if getattr(sys, 'frozen', False):
|
upwin.update()
|
||||||
root.iconbitmap(sys._MEIPASS + '\\id-card.ico\\id-card.ico')
|
ws = upwin.winfo_screenwidth()
|
||||||
else:
|
hs = upwin.winfo_screenheight()
|
||||||
root.iconbitmap('id-card.ico')
|
canvas.create_text((w / 2), (h / 3), text=(CST_NAME + ' ' + CST_VERTITLE), font='Calibri 30 bold', fill='white')
|
||||||
logger.info('SoftUpdate() : Entering upwin mainloop()')
|
message = canvas.create_text((w / 2), (h / 1.15), text=' ', font='Calibri 9', fill='white')
|
||||||
upwin.protocol('WM_DELETE_WINDOW', lambda : root.destroy())
|
upwin.update()
|
||||||
upwin.mainloop()
|
x = ws / 2 - w / 2
|
||||||
logger.info('SoftUpdate() : Exiting upwin mainloop()')
|
y = hs / 2 - h / 2
|
||||||
if ret == 11:
|
upwin.geometry('%dx%d+%d+%d' % (w, h, x, y))
|
||||||
logger.info('SoftUpdate() : OK to start to main() normally !')
|
canvas.grid()
|
||||||
return True
|
pbar.grid()
|
||||||
else:
|
p.grid()
|
||||||
logger.info('SoftUpdate() : Program will stop !')
|
upwin.after(2000, updating)
|
||||||
|
if getattr(sys, 'frozen', False):
|
||||||
|
root.iconbitmap(sys._MEIPASS + '\\id-card.ico\\id-card.ico')
|
||||||
|
else:
|
||||||
|
root.iconbitmap('id-card.ico')
|
||||||
|
logger.info('SoftUpdate() : Entering upwin mainloop()')
|
||||||
|
upwin.protocol('WM_DELETE_WINDOW', lambda : root.destroy())
|
||||||
|
upwin.mainloop()
|
||||||
|
logger.info('SoftUpdate() : Exiting upwin mainloop()')
|
||||||
|
if ret == 11:
|
||||||
|
logger.info('SoftUpdate() : OK to start to main() normally !')
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
logger.info('SoftUpdate() : Program will stop !')
|
||||||
return False
|
return False
|
@ -1,15 +1,28 @@
|
|||||||
"""
|
"""
|
||||||
********************************************************************************
|
********************************************************************************
|
||||||
*** Projet CNI_Revelator ***
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
GNU GPL * 07/2018
|
* Desc: Application launcher & updater *
|
||||||
|
* *
|
||||||
Adrien Bourmault
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
CLASSES
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
|
* it under the terms of the GNU General Public License as published by *
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
|
* any later version. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
|
* GNU General Public License for more details. *
|
||||||
|
* *
|
||||||
|
* You should have received a copy of the GNU General Public License *
|
||||||
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
********************************************************************************
|
********************************************************************************
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from CNI_GLOBALVAR import *
|
from CNI_GLOBALVAR import *
|
||||||
from PIL import Image, ImageFont, ImageDraw, ImageTk, ImageEnhance, ImageFilter
|
from PIL import Image, ImageFont, ImageDraw, ImageTk, ImageEnhance, ImageFilter
|
||||||
import math, warnings, string
|
import math, warnings, string
|
@ -1,311 +1,326 @@
|
|||||||
"""
|
"""
|
||||||
********************************************************************************
|
********************************************************************************
|
||||||
*** Projet CNI_Revelator ***
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
GNU GPL * 07/2018
|
* Desc: Pytesseract modification to comply with Pyinstaller *
|
||||||
|
* *
|
||||||
Adrien Bourmault
|
* Copyright © 2017-2018 Matthias A. Lee (madmaze) *
|
||||||
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
Pytesseract modification to comply with Pyinstaller
|
* *
|
||||||
|
* This file is part of CNIRevelator. *
|
||||||
*****
|
* *
|
||||||
"""
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
try:
|
* it under the terms of the GNU General Public License as published by *
|
||||||
import Image
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
except ImportError:
|
* any later version. *
|
||||||
from PIL import Image
|
* *
|
||||||
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
import os, sys, subprocess, tempfile, shlex, string
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
from glob import iglob
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
from pkgutil import find_loader
|
* GNU General Public License for more details. *
|
||||||
from distutils.version import LooseVersion
|
* *
|
||||||
from os.path import realpath, normpath, normcase
|
* You should have received a copy of the GNU General Public License *
|
||||||
numpy_installed = find_loader('numpy') is not None
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
if numpy_installed:
|
********************************************************************************
|
||||||
from numpy import ndarray
|
"""
|
||||||
tesseract_cmd = 'tesseract'
|
|
||||||
RGB_MODE = 'RGB'
|
|
||||||
OSD_KEYS = {'Page number':(
|
try:
|
||||||
'page_num', int),
|
import Image
|
||||||
'Orientation in degrees':(
|
except ImportError:
|
||||||
'orientation', int),
|
from PIL import Image
|
||||||
'Rotate':(
|
|
||||||
'rotate', int),
|
import os, sys, subprocess, tempfile, shlex, string
|
||||||
'Orientation confidence':(
|
from glob import iglob
|
||||||
'orientation_conf', float),
|
from pkgutil import find_loader
|
||||||
'Script':(
|
from distutils.version import LooseVersion
|
||||||
'script', str),
|
from os.path import realpath, normpath, normcase
|
||||||
'Script confidence':(
|
numpy_installed = find_loader('numpy') is not None
|
||||||
'script_conf', float)}
|
if numpy_installed:
|
||||||
|
from numpy import ndarray
|
||||||
class Output:
|
tesseract_cmd = 'tesseract'
|
||||||
STRING = 'string'
|
RGB_MODE = 'RGB'
|
||||||
BYTES = 'bytes'
|
OSD_KEYS = {'Page number':(
|
||||||
DICT = 'dict'
|
'page_num', int),
|
||||||
|
'Orientation in degrees':(
|
||||||
|
'orientation', int),
|
||||||
class TesseractError(RuntimeError):
|
'Rotate':(
|
||||||
|
'rotate', int),
|
||||||
def __init__(self, status, message):
|
'Orientation confidence':(
|
||||||
self.status = status
|
'orientation_conf', float),
|
||||||
self.message = message
|
'Script':(
|
||||||
self.args = (status, message)
|
'script', str),
|
||||||
|
'Script confidence':(
|
||||||
|
'script_conf', float)}
|
||||||
class TesseractNotFoundError(EnvironmentError):
|
|
||||||
|
class Output:
|
||||||
def __init__(self):
|
STRING = 'string'
|
||||||
super(TesseractNotFoundError, self).__init__(tesseract_cmd + " is not installed or it's not in your path")
|
BYTES = 'bytes'
|
||||||
|
DICT = 'dict'
|
||||||
|
|
||||||
class TSVNotSupported(EnvironmentError):
|
|
||||||
|
class TesseractError(RuntimeError):
|
||||||
def __init__(self):
|
|
||||||
super(TSVNotSupported, self).__init__('TSV output not supported. Tesseract >= 3.05 required')
|
def __init__(self, status, message):
|
||||||
|
self.status = status
|
||||||
|
self.message = message
|
||||||
def run_once(func):
|
self.args = (status, message)
|
||||||
|
|
||||||
def wrapper(*args, **kwargs):
|
|
||||||
if wrapper._result is wrapper:
|
class TesseractNotFoundError(EnvironmentError):
|
||||||
wrapper._result = func(*args, **kwargs)
|
|
||||||
return wrapper._result
|
def __init__(self):
|
||||||
|
super(TesseractNotFoundError, self).__init__(tesseract_cmd + " is not installed or it's not in your path")
|
||||||
wrapper._result = wrapper
|
|
||||||
return wrapper
|
|
||||||
|
class TSVNotSupported(EnvironmentError):
|
||||||
|
|
||||||
def get_errors(error_string):
|
def __init__(self):
|
||||||
return ' '.join(line for line in error_string.decode('utf-8').splitlines()).strip()
|
super(TSVNotSupported, self).__init__('TSV output not supported. Tesseract >= 3.05 required')
|
||||||
|
|
||||||
|
|
||||||
def cleanup(temp_name):
|
def run_once(func):
|
||||||
""" Tries to remove files by filename wildcard path. """
|
|
||||||
for filename in iglob(temp_name + '*' if temp_name else temp_name):
|
def wrapper(*args, **kwargs):
|
||||||
try:
|
if wrapper._result is wrapper:
|
||||||
os.remove(filename)
|
wrapper._result = func(*args, **kwargs)
|
||||||
except OSError:
|
return wrapper._result
|
||||||
pass
|
|
||||||
|
wrapper._result = wrapper
|
||||||
|
return wrapper
|
||||||
def prepare(image):
|
|
||||||
if isinstance(image, Image.Image):
|
|
||||||
return image
|
def get_errors(error_string):
|
||||||
if numpy_installed:
|
return ' '.join(line for line in error_string.decode('utf-8').splitlines()).strip()
|
||||||
if isinstance(image, ndarray):
|
|
||||||
pass
|
|
||||||
return Image.fromarray(image)
|
def cleanup(temp_name):
|
||||||
raise TypeError('Unsupported image object')
|
""" Tries to remove files by filename wildcard path. """
|
||||||
|
for filename in iglob(temp_name + '*' if temp_name else temp_name):
|
||||||
|
try:
|
||||||
def save_image(image):
|
os.remove(filename)
|
||||||
temp_name = tempfile.mktemp(prefix='tess_')
|
except OSError:
|
||||||
if isinstance(image, str):
|
pass
|
||||||
return (temp_name, realpath(normpath(normcase(image))))
|
|
||||||
else:
|
|
||||||
image = prepare(image)
|
def prepare(image):
|
||||||
img_extension = image.format
|
if isinstance(image, Image.Image):
|
||||||
if image.format not in frozenset({'BMP', 'JPEG', 'GIF', 'TIFF', 'PNG'}):
|
return image
|
||||||
img_extension = 'PNG'
|
if numpy_installed:
|
||||||
if not image.mode.startswith(RGB_MODE):
|
if isinstance(image, ndarray):
|
||||||
image = image.convert(RGB_MODE)
|
pass
|
||||||
if 'A' in image.getbands():
|
return Image.fromarray(image)
|
||||||
background = Image.new(RGB_MODE, image.size, (255, 255, 255))
|
raise TypeError('Unsupported image object')
|
||||||
background.paste(image, (0, 0), image)
|
|
||||||
image = background
|
|
||||||
input_file_name = temp_name + os.extsep + img_extension
|
def save_image(image):
|
||||||
(image.save)(input_file_name, format=img_extension, **image.info)
|
temp_name = tempfile.mktemp(prefix='tess_')
|
||||||
return (
|
if isinstance(image, str):
|
||||||
temp_name, input_file_name)
|
return (temp_name, realpath(normpath(normcase(image))))
|
||||||
|
else:
|
||||||
|
image = prepare(image)
|
||||||
def subprocess_args(include_stdout=True):
|
img_extension = image.format
|
||||||
if hasattr(subprocess, 'STARTUPINFO'):
|
if image.format not in frozenset({'BMP', 'JPEG', 'GIF', 'TIFF', 'PNG'}):
|
||||||
si = subprocess.STARTUPINFO()
|
img_extension = 'PNG'
|
||||||
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
if not image.mode.startswith(RGB_MODE):
|
||||||
env = os.environ
|
image = image.convert(RGB_MODE)
|
||||||
else:
|
if 'A' in image.getbands():
|
||||||
si = None
|
background = Image.new(RGB_MODE, image.size, (255, 255, 255))
|
||||||
env = None
|
background.paste(image, (0, 0), image)
|
||||||
if include_stdout:
|
image = background
|
||||||
ret = {'stdout': subprocess.PIPE}
|
input_file_name = temp_name + os.extsep + img_extension
|
||||||
else:
|
(image.save)(input_file_name, format=img_extension, **image.info)
|
||||||
ret = {}
|
return (
|
||||||
ret.update({'stdin':subprocess.PIPE, 'stderr':subprocess.PIPE,
|
temp_name, input_file_name)
|
||||||
'startupinfo':si,
|
|
||||||
'env':env})
|
|
||||||
return ret
|
def subprocess_args(include_stdout=True):
|
||||||
|
if hasattr(subprocess, 'STARTUPINFO'):
|
||||||
|
si = subprocess.STARTUPINFO()
|
||||||
def run_tesseract(input_filename, output_filename_base, extension, lang, config='', nice=0):
|
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||||||
cmd_args = []
|
env = os.environ
|
||||||
if not sys.platform.startswith('win32'):
|
else:
|
||||||
if nice != 0:
|
si = None
|
||||||
cmd_args += ('nice', '-n', str(nice))
|
env = None
|
||||||
cmd_args += (tesseract_cmd, input_filename, output_filename_base)
|
if include_stdout:
|
||||||
if lang is not None:
|
ret = {'stdout': subprocess.PIPE}
|
||||||
cmd_args += ('-l', lang)
|
else:
|
||||||
cmd_args += shlex.split(config)
|
ret = {}
|
||||||
if extension not in ('box', 'osd', 'tsv'):
|
ret.update({'stdin':subprocess.PIPE, 'stderr':subprocess.PIPE,
|
||||||
cmd_args.append(extension)
|
'startupinfo':si,
|
||||||
try:
|
'env':env})
|
||||||
proc = (subprocess.Popen)(cmd_args, **subprocess_args())
|
return ret
|
||||||
except OSError:
|
|
||||||
raise TesseractNotFoundError()
|
|
||||||
|
def run_tesseract(input_filename, output_filename_base, extension, lang, config='', nice=0):
|
||||||
status_code, error_string = proc.wait(), proc.stderr.read()
|
cmd_args = []
|
||||||
proc.stderr.close()
|
if not sys.platform.startswith('win32'):
|
||||||
if status_code:
|
if nice != 0:
|
||||||
raise TesseractError(status_code, get_errors(error_string))
|
cmd_args += ('nice', '-n', str(nice))
|
||||||
return True
|
cmd_args += (tesseract_cmd, input_filename, output_filename_base)
|
||||||
|
if lang is not None:
|
||||||
|
cmd_args += ('-l', lang)
|
||||||
def run_and_get_output(image, extension, lang=None, config='', nice=0, return_bytes=False):
|
cmd_args += shlex.split(config)
|
||||||
temp_name, input_filename = ('', '')
|
if extension not in ('box', 'osd', 'tsv'):
|
||||||
try:
|
cmd_args.append(extension)
|
||||||
temp_name, input_filename = save_image(image)
|
try:
|
||||||
kwargs = {'input_filename':input_filename,
|
proc = (subprocess.Popen)(cmd_args, **subprocess_args())
|
||||||
'output_filename_base':temp_name + '_out',
|
except OSError:
|
||||||
'extension':extension,
|
raise TesseractNotFoundError()
|
||||||
'lang':lang,
|
|
||||||
'config':config,
|
status_code, error_string = proc.wait(), proc.stderr.read()
|
||||||
'nice':nice}
|
proc.stderr.close()
|
||||||
run_tesseract(**kwargs)
|
if status_code:
|
||||||
filename = kwargs['output_filename_base'] + os.extsep + extension
|
raise TesseractError(status_code, get_errors(error_string))
|
||||||
with open(filename, 'rb') as (output_file):
|
return True
|
||||||
if return_bytes:
|
|
||||||
return output_file.read()
|
|
||||||
return output_file.read().decode('utf-8').strip()
|
def run_and_get_output(image, extension, lang=None, config='', nice=0, return_bytes=False):
|
||||||
finally:
|
temp_name, input_filename = ('', '')
|
||||||
cleanup(temp_name)
|
try:
|
||||||
|
temp_name, input_filename = save_image(image)
|
||||||
|
kwargs = {'input_filename':input_filename,
|
||||||
def file_to_dict(tsv, cell_delimiter, str_col_idx):
|
'output_filename_base':temp_name + '_out',
|
||||||
result = {}
|
'extension':extension,
|
||||||
rows = [row.split(cell_delimiter) for row in tsv.split('\n')]
|
'lang':lang,
|
||||||
if not rows:
|
'config':config,
|
||||||
return result
|
'nice':nice}
|
||||||
else:
|
run_tesseract(**kwargs)
|
||||||
header = rows.pop(0)
|
filename = kwargs['output_filename_base'] + os.extsep + extension
|
||||||
if len(rows[(-1)]) < len(header):
|
with open(filename, 'rb') as (output_file):
|
||||||
rows[(-1)].append('')
|
if return_bytes:
|
||||||
if str_col_idx < 0:
|
return output_file.read()
|
||||||
str_col_idx += len(header)
|
return output_file.read().decode('utf-8').strip()
|
||||||
for i, head in enumerate(header):
|
finally:
|
||||||
result[head] = [int(row[i]) if i != str_col_idx else row[i] for row in rows]
|
cleanup(temp_name)
|
||||||
|
|
||||||
return result
|
|
||||||
|
def file_to_dict(tsv, cell_delimiter, str_col_idx):
|
||||||
|
result = {}
|
||||||
def is_valid(val, _type):
|
rows = [row.split(cell_delimiter) for row in tsv.split('\n')]
|
||||||
if _type is int:
|
if not rows:
|
||||||
return val.isdigit()
|
return result
|
||||||
else:
|
else:
|
||||||
if _type is float:
|
header = rows.pop(0)
|
||||||
pass
|
if len(rows[(-1)]) < len(header):
|
||||||
try:
|
rows[(-1)].append('')
|
||||||
float(val)
|
if str_col_idx < 0:
|
||||||
return True
|
str_col_idx += len(header)
|
||||||
except ValueError:
|
for i, head in enumerate(header):
|
||||||
return False
|
result[head] = [int(row[i]) if i != str_col_idx else row[i] for row in rows]
|
||||||
|
|
||||||
return True
|
return result
|
||||||
|
|
||||||
|
|
||||||
def osd_to_dict(osd):
|
def is_valid(val, _type):
|
||||||
return {OSD_KEYS[kv[0]][0]:OSD_KEYS[kv[0]][1](kv[1]) for kv in (line.split(': ') for line in osd.split('\n')) if len(kv) == 2 if is_valid(kv[1], OSD_KEYS[kv[0]][1])}
|
if _type is int:
|
||||||
|
return val.isdigit()
|
||||||
|
else:
|
||||||
@run_once
|
if _type is float:
|
||||||
def get_tesseract_version():
|
pass
|
||||||
"""
|
try:
|
||||||
Returns LooseVersion object of the Tesseract version
|
float(val)
|
||||||
"""
|
return True
|
||||||
try:
|
except ValueError:
|
||||||
return LooseVersion((subprocess.check_output)([tesseract_cmd, '--version'], **subprocess_args(False)).decode('utf-8').split()[1].lstrip(string.printable[10:]))
|
return False
|
||||||
except OSError:
|
|
||||||
raise TesseractNotFoundError()
|
return True
|
||||||
|
|
||||||
|
|
||||||
def image_to_string(image, lang=None, config='', nice=0, boxes=False, output_type=Output.STRING):
|
def osd_to_dict(osd):
|
||||||
"""
|
return {OSD_KEYS[kv[0]][0]:OSD_KEYS[kv[0]][1](kv[1]) for kv in (line.split(': ') for line in osd.split('\n')) if len(kv) == 2 if is_valid(kv[1], OSD_KEYS[kv[0]][1])}
|
||||||
Returns the result of a Tesseract OCR run on the provided image to string
|
|
||||||
"""
|
|
||||||
if boxes:
|
@run_once
|
||||||
print("\nWarning: Argument 'boxes' is deprecated and will be removed in future versions. Use function image_to_boxes instead.\n")
|
def get_tesseract_version():
|
||||||
return image_to_boxes(image, lang, config, nice, output_type)
|
"""
|
||||||
else:
|
Returns LooseVersion object of the Tesseract version
|
||||||
args = [
|
"""
|
||||||
image, 'txt', lang, config, nice]
|
try:
|
||||||
if output_type == Output.DICT:
|
return LooseVersion((subprocess.check_output)([tesseract_cmd, '--version'], **subprocess_args(False)).decode('utf-8').split()[1].lstrip(string.printable[10:]))
|
||||||
return {'text': run_and_get_output(*args)}
|
except OSError:
|
||||||
if output_type == Output.BYTES:
|
raise TesseractNotFoundError()
|
||||||
args.append(True)
|
|
||||||
return run_and_get_output(*args)
|
|
||||||
|
def image_to_string(image, lang=None, config='', nice=0, boxes=False, output_type=Output.STRING):
|
||||||
|
"""
|
||||||
def image_to_boxes(image, lang=None, config='', nice=0, output_type=Output.STRING):
|
Returns the result of a Tesseract OCR run on the provided image to string
|
||||||
"""
|
"""
|
||||||
Returns string containing recognized characters and their box boundaries
|
if boxes:
|
||||||
"""
|
print("\nWarning: Argument 'boxes' is deprecated and will be removed in future versions. Use function image_to_boxes instead.\n")
|
||||||
config += ' batch.nochop makebox'
|
return image_to_boxes(image, lang, config, nice, output_type)
|
||||||
args = [image, 'box', lang, config, nice]
|
else:
|
||||||
if output_type == Output.DICT:
|
args = [
|
||||||
box_header = 'char left bottom right top page\n'
|
image, 'txt', lang, config, nice]
|
||||||
return file_to_dict(box_header + run_and_get_output(*args), ' ', 0)
|
if output_type == Output.DICT:
|
||||||
else:
|
return {'text': run_and_get_output(*args)}
|
||||||
if output_type == Output.BYTES:
|
if output_type == Output.BYTES:
|
||||||
args.append(True)
|
args.append(True)
|
||||||
return run_and_get_output(*args)
|
return run_and_get_output(*args)
|
||||||
|
|
||||||
|
|
||||||
def image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING):
|
def image_to_boxes(image, lang=None, config='', nice=0, output_type=Output.STRING):
|
||||||
"""
|
"""
|
||||||
Returns string containing box boundaries, confidences,
|
Returns string containing recognized characters and their box boundaries
|
||||||
and other information. Requires Tesseract 3.05+
|
"""
|
||||||
"""
|
config += ' batch.nochop makebox'
|
||||||
if get_tesseract_version() < '3.05':
|
args = [image, 'box', lang, config, nice]
|
||||||
raise TSVNotSupported()
|
if output_type == Output.DICT:
|
||||||
config = '{} {}'.format('-c tessedit_create_tsv=1', config.strip()).strip()
|
box_header = 'char left bottom right top page\n'
|
||||||
args = [image, 'tsv', lang, config, nice]
|
return file_to_dict(box_header + run_and_get_output(*args), ' ', 0)
|
||||||
if output_type == Output.DICT:
|
else:
|
||||||
return file_to_dict(run_and_get_output(*args), '\t', -1)
|
if output_type == Output.BYTES:
|
||||||
else:
|
args.append(True)
|
||||||
if output_type == Output.BYTES:
|
return run_and_get_output(*args)
|
||||||
args.append(True)
|
|
||||||
return run_and_get_output(*args)
|
|
||||||
|
def image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING):
|
||||||
|
"""
|
||||||
def image_to_osd(image, lang='osd', config='', nice=0, output_type=Output.STRING):
|
Returns string containing box boundaries, confidences,
|
||||||
"""
|
and other information. Requires Tesseract 3.05+
|
||||||
Returns string containing the orientation and script detection (OSD)
|
"""
|
||||||
"""
|
if get_tesseract_version() < '3.05':
|
||||||
config = '{}-psm 0 {}'.format('' if get_tesseract_version() < '3.05' else '-', config.strip()).strip()
|
raise TSVNotSupported()
|
||||||
args = [
|
config = '{} {}'.format('-c tessedit_create_tsv=1', config.strip()).strip()
|
||||||
image, 'osd', lang, config, nice]
|
args = [image, 'tsv', lang, config, nice]
|
||||||
if output_type == Output.DICT:
|
if output_type == Output.DICT:
|
||||||
return osd_to_dict(run_and_get_output(*args))
|
return file_to_dict(run_and_get_output(*args), '\t', -1)
|
||||||
else:
|
else:
|
||||||
if output_type == Output.BYTES:
|
if output_type == Output.BYTES:
|
||||||
args.append(True)
|
args.append(True)
|
||||||
return run_and_get_output(*args)
|
return run_and_get_output(*args)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def image_to_osd(image, lang='osd', config='', nice=0, output_type=Output.STRING):
|
||||||
if len(sys.argv) == 2:
|
"""
|
||||||
filename, lang = sys.argv[1], None
|
Returns string containing the orientation and script detection (OSD)
|
||||||
else:
|
"""
|
||||||
if len(sys.argv) == 4:
|
config = '{}-psm 0 {}'.format('' if get_tesseract_version() < '3.05' else '-', config.strip()).strip()
|
||||||
if sys.argv[1] == '-l':
|
args = [
|
||||||
filename, lang = sys.argv[3], sys.argv[2]
|
image, 'osd', lang, config, nice]
|
||||||
sys.stderr.write('Usage: python pytesseract.py [-l lang] input_file\n')
|
if output_type == Output.DICT:
|
||||||
exit(2)
|
return osd_to_dict(run_and_get_output(*args))
|
||||||
try:
|
else:
|
||||||
print(image_to_string((Image.open(filename)), lang=lang))
|
if output_type == Output.BYTES:
|
||||||
except IOError:
|
args.append(True)
|
||||||
sys.stderr.write('ERROR: Could not open file "%s"\n' % filename)
|
return run_and_get_output(*args)
|
||||||
exit(1)
|
|
||||||
|
|
||||||
|
def main():
|
||||||
if __name__ == '__main__':
|
if len(sys.argv) == 2:
|
||||||
|
filename, lang = sys.argv[1], None
|
||||||
|
else:
|
||||||
|
if len(sys.argv) == 4:
|
||||||
|
if sys.argv[1] == '-l':
|
||||||
|
filename, lang = sys.argv[3], sys.argv[2]
|
||||||
|
sys.stderr.write('Usage: python pytesseract.py [-l lang] input_file\n')
|
||||||
|
exit(2)
|
||||||
|
try:
|
||||||
|
print(image_to_string((Image.open(filename)), lang=lang))
|
||||||
|
except IOError:
|
||||||
|
sys.stderr.write('ERROR: Could not open file "%s"\n' % filename)
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
34
src/launcher/CNIRLauncher.py
Normal file
34
src/launcher/CNIRLauncher.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
"""
|
||||||
|
********************************************************************************
|
||||||
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
|
* Desc: Application launcher & updater main file *
|
||||||
|
* *
|
||||||
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
|
* it under the terms of the GNU General Public License as published by *
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
|
* any later version. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
|
* GNU General Public License for more details. *
|
||||||
|
* *
|
||||||
|
* You should have received a copy of the GNU General Public License *
|
||||||
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
|
********************************************************************************
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logger
|
||||||
|
|
||||||
|
## Launching the launcher
|
||||||
|
|
||||||
|
# Creating a log file
|
||||||
|
logfile = logger.NewLoggingSystem()
|
||||||
|
|
||||||
|
# Hello world
|
||||||
|
logfile.printdbg('*** CNIRLauncher LOGFILE. Hello World ! ***')
|
24
src/launcher/downloader.py
Normal file
24
src/launcher/downloader.py
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
"""
|
||||||
|
********************************************************************************
|
||||||
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
|
* Desc: Application launcher download stuff *
|
||||||
|
* *
|
||||||
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
|
* it under the terms of the GNU General Public License as published by *
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
|
* any later version. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
|
* GNU General Public License for more details. *
|
||||||
|
* *
|
||||||
|
* You should have received a copy of the GNU General Public License *
|
||||||
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
|
********************************************************************************
|
||||||
|
"""
|
29
src/launcher/globs.py
Normal file
29
src/launcher/globs.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
"""
|
||||||
|
********************************************************************************
|
||||||
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
|
* Desc: Application launcher global variables *
|
||||||
|
* *
|
||||||
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
|
* it under the terms of the GNU General Public License as published by *
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
|
* any later version. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
|
* GNU General Public License for more details. *
|
||||||
|
* *
|
||||||
|
* You should have received a copy of the GNU General Public License *
|
||||||
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
|
********************************************************************************
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
|
||||||
|
CNIRTesserHash = '5b58db27f7bc08c58a2cb33d01533b034b067cf8'
|
||||||
|
#CNIRFolder = os.getenv('APPDATA') + '/CNIRevelator/'
|
||||||
|
CNIRFolder = '.'
|
59
src/launcher/logger.py
Normal file
59
src/launcher/logger.py
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
"""
|
||||||
|
********************************************************************************
|
||||||
|
* CNIRevelator *
|
||||||
|
* *
|
||||||
|
* Desc: Application launcher logging stuff *
|
||||||
|
* *
|
||||||
|
* Copyright © 2018-2019 Adrien Bourmault (neox95) *
|
||||||
|
* *
|
||||||
|
* This file is part of CNIRevelator. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is free software: you can redistribute it and/or modify *
|
||||||
|
* it under the terms of the GNU General Public License as published by *
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or *
|
||||||
|
* any later version. *
|
||||||
|
* *
|
||||||
|
* CNIRevelator is distributed in the hope that it will be useful, *
|
||||||
|
* but WITHOUT ANY WARRANTY*without even the implied warranty of *
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||||
|
* GNU General Public License for more details. *
|
||||||
|
* *
|
||||||
|
* You should have received a copy of the GNU General Public License *
|
||||||
|
* along with CNIRevelator. If not, see <https:*www.gnu.org/licenses/>. *
|
||||||
|
********************************************************************************
|
||||||
|
"""
|
||||||
|
## The logging class
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import globs
|
||||||
|
|
||||||
|
class NewLoggingSystem:
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
|
||||||
|
# Deleting the error log
|
||||||
|
try:
|
||||||
|
os.remove(globs.CNIRFolder + '\\error.log') # The deletion does not working
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Create new logging handle
|
||||||
|
logger = logging.getLogger()
|
||||||
|
logger.setLevel(logging.INFO) # To make sure we can have a debug channel
|
||||||
|
|
||||||
|
# Create channels
|
||||||
|
formatter = logging.Formatter('[ %(module)s/%(funcName)s ] %(asctime)s :: %(levelname)s :: %(message)s')
|
||||||
|
error_handler = logging.FileHandler((globs.CNIRFolder + '\\error.log'), mode='w', encoding='utf-8', delay=True)
|
||||||
|
info_handler = logging.FileHandler((globs.CNIRFolder + '\\launcher.log'), mode='w', encoding='utf-8')
|
||||||
|
|
||||||
|
error_handler.setLevel(logging.ERROR)
|
||||||
|
error_handler.setFormatter(formatter)
|
||||||
|
logger.addHandler(error_handler)
|
||||||
|
|
||||||
|
info_handler.setLevel(logging.DEBUG)
|
||||||
|
info_handler.setFormatter(formatter)
|
||||||
|
logger.addHandler(info_handler)
|
||||||
|
|
||||||
|
self.logger = logger
|
||||||
|
self.printerr = logger.error
|
||||||
|
self.printdbg = logger.info
|
Loading…
Reference in New Issue
Block a user