Explorar el Código

добвлен logger
пределано часть скрипта, чтоб корректно работала на windows

AlexSidorov hace 1 año
padre
commit
77f2829a58

+ 0 - 2
.env

@@ -1,2 +0,0 @@
-DB_DIR=/home/asidorov/Документы/propusk_db 
-PHOTO_DIR=/home/asidorov/Изображения/propusk 

+ 2 - 1
.gitignore

@@ -10,4 +10,5 @@ dist
 PySide6
 Propusk_linux/
 .vscode
-build
+build
+.env

+ 22 - 0
logger.py

@@ -0,0 +1,22 @@
+import logging
+# import logging.config
+import os
+from datetime import datetime
+
+
+def create_logger():
+    
+    path_dir_log = os.path.join(os.path.dirname(__file__), 'logs')
+
+    if not os.path.exists(path_dir_log):
+        os.mkdir(path_dir_log)
+
+    now = datetime.now()
+    file_log = os.path.join(path_dir_log, F'logs_{now.year}{now.month}{now.day}.log')
+    logging.basicConfig(filename=file_log,
+                        encoding='utf-8',
+                        level=logging.DEBUG,
+                        format='%(asctime)s %(name)s %(levelname)s %(message)s')
+    # logging.config.fileConfig('logger.conf')
+
+logger = logging.getLogger('PropuskLogger')

+ 2 - 2
main.py

@@ -1,7 +1,7 @@
 from init_var import *
 import os
 import sys
-
+from logger import create_logger
 from PySide6.QtWidgets import QApplication
 # from appdirs import user_data_dir 
 
@@ -9,7 +9,7 @@ from PySide6.QtWidgets import QApplication
 
 def main():
     app = QApplication(sys.argv)
-    
+    create_logger()
     load_variables()
     
     from module.WorkWithDB import init_db    

+ 5 - 2
module/CleanerImage.py

@@ -2,7 +2,7 @@ from .WorkWithDB import connect, list_propusk
 from sqlalchemy import select
 from appdirs import user_data_dir
 import os
-
+from logger import logger
 
 class CleanerImage:
     def __init__(self, path: str):
@@ -10,7 +10,9 @@ class CleanerImage:
         
         if os.path.exists(path):    
             self._files_in_db = self._get_list_files_from_db()
+            logger.info(self._files_in_db)
         else:
+            logger.error(F"Не корректный путь: {path}")
             raise ValueError(F"Не корректный путь: {path}")
 
     def _get_list_files_from_db(self) -> list:
@@ -19,6 +21,7 @@ class CleanerImage:
                 list_propusk.c.face_photo,
                 list_propusk.c.pasport_photo
             ).select_from(list_propusk)
+            
             return sum([[self._only_file(x[0]), self._only_file(x[0])]
                         for x in conn.execute(list_files).all()], [])
 
@@ -33,5 +36,5 @@ class CleanerImage:
         for file in files:
             if file not in self._files_in_db:
                 os.remove(os.path.join(self._path, file))
-                print(F"Удален файл: {os.path.join(self._path, file)}")
+                logger.info(F"Удален файл: {os.path.join(self._path, file)}")
 

+ 4 - 2
module/ImageTool.py

@@ -1,5 +1,6 @@
 from PIL import Image, UnidentifiedImageError
 import os
+from logger import logger
 
 def rotate_image(path_file: str, gradus: int = -90) -> str:
     try:
@@ -13,10 +14,11 @@ def rotate_image(path_file: str, gradus: int = -90) -> str:
         rotate_img.save(rotate_path_image)
     
         return rotate_path_image
+    
     except FileNotFoundError:
-        print(F"Файл не найден: {path_file=}")
+        logger.error(F"Файл не найден: {path_file=}")
         return None
     except UnidentifiedImageError:
-        print(F"Не правильный формат: {path_file=}")
+        logger.error(F"Не правильный формат: {path_file=}")
         return None
 

+ 2 - 2
module/ModelPropusk.py

@@ -1,14 +1,14 @@
 from datetime import datetime
 from dataclasses import dataclass
+from logger import logger
 
 
 def key_error(func):
-
     def wrapper(*args, **kwargs):
         try:
             return func(*args, **kwargs)
         except KeyError:
-            print("Ключ не правильный")
+            logger.info("ModelPropusk -> Ключ не правильный")
 
     return wrapper
 

+ 2 - 1
module/MyMessageBox.py

@@ -1,4 +1,5 @@
 from PySide6.QtWidgets import QMessageBox
+from logger import logger
 
 def show_dialog(state: QMessageBox.Icon, title: str, massage: str):
    msgBox = QMessageBox()
@@ -10,4 +11,4 @@ def show_dialog(state: QMessageBox.Icon, title: str, massage: str):
 
    returnValue = msgBox.exec()
    if returnValue == QMessageBox.Ok:
-      print('OK clicked')
+      logger.info('MyMessageBox press ok')

+ 22 - 23
module/WorkWithCam.py

@@ -7,13 +7,12 @@ from PySide6.QtGui import QImage, QPixmap
 from PySide6.QtWidgets import QLabel
 from PySide6.QtMultimedia import (
     QMediaDevices, QCamera, QImageCapture, QMediaCaptureSession)
-from appdirs import user_data_dir
 from datetime import datetime
 from itertools import groupby
+from logger import logger
 
-if os.environ.get("PHOTO_DIR"):
-    IMAGES_PATH = os.environ.get("PHOTO_DIR")
-else:
+if not os.environ.get("PHOTO_DIR"):
+    logger.error("Не задана локальная переменная PHOTO_DIR")
     raise ValueError(
         "не задана локальная переменная PHOTO_DIR"
     )
@@ -31,29 +30,29 @@ class WorkWithCam:
 
         self._camera_info = get_object_cam_by_name(name_cam)
         if not self._camera_info:
+            logger.error("Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
             raise IndexError(
-                f"Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
-
-        self._file_name = self.get_filename()
+                "Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
+        
 
     def start_cam(self):
         self._camera = QCamera(self._camera_info)
         self._camera.errorOccurred.connect(self._camera_error)
+
         self._image_capture = QImageCapture(self._camera)
         self._image_capture.imageCaptured.connect(self.image_captured)
         self._image_capture.imageSaved.connect(self.image_saved)
         self._image_capture.errorOccurred.connect(self._capture_error)
+        
         self._capture_session = QMediaCaptureSession()
         self._capture_session.setCamera(self._camera)
         self._capture_session.setImageCapture(self._image_capture)
 
         if self._camera and self._camera.error() == QCamera.NoError:
-            # print()
-            name = self._camera_info.description()
             self._capture_session.setVideoOutput(self._video_widget)
             self._camera.start()
         else:
-            print("Camera unavailable")
+            logger.debug("Camera unavailable")
 
     def stop_cam(self) -> None:
         if self._camera and self._camera.isActive():
@@ -62,28 +61,29 @@ class WorkWithCam:
     def __del__(self) -> None:
         self.stop_cam()
 
-    def cupture_image(self) -> str:
+    def cupture_image(self, label: QLabel) -> str:
+        self._label = label
         self._current_preview = QImage()
+        self._file_name = self.get_filename()
+
+        logger.info(F"Создаем файл {self._file_name}")
         self._image_capture.captureToFile(self._file_name)
         return self._file_name
 
     @Slot(int, QImageCapture.Error, str)
     def _capture_error(self, id, error, error_string):
-        print(error_string, file=sys.stderr)
-        self.show_status_message(error_string)
+        logger.error(error_string)
 
     @Slot(QCamera.Error, str)
     def _camera_error(self, error, error_string):
-        print(error_string, file=sys.stderr)
-        self.show_status_message(error_string)
+        logger.error(error_string)
 
-    @staticmethod
-    def get_filename() -> str:
-        return F"{IMAGES_PATH}/propusk_{datetime.now().timestamp()}.jpg"
+    def get_filename(self) -> str:
+        return os.path.join(os.environ.get('PHOTO_DIR'), F"propusk_{datetime.now().timestamp()}.jpg")
 
     def _create_dirs(self):
-        if not os.path.exists(IMAGES_PATH):
-            os.mkdir(IMAGES_PATH)
+        if not os.path.exists(os.environ.get('PHOTO_DIR')):
+            os.mkdir(os.environ.get('PHOTO_DIR'))
 
     @Slot(int, QImage)
     def image_captured(self, id, previewImage):
@@ -91,13 +91,12 @@ class WorkWithCam:
 
     @Slot(int, str)
     def image_saved(self, id, fileName):
-        ...
+        load_image(self._label, fileName)
 
-    def show_status_message(self, message):
-        print(message, 5000)
 
 
 def load_image(qlabel: QLabel, path_file: str) -> None:
+    logger.info(F"Set image to label: {path_file}")
     qlabel.setPixmap(QPixmap(QImage(path_file)).scaled(
         qlabel.width()-4,
         qlabel.height(),

+ 4 - 6
module/WorkWithDB.py

@@ -4,6 +4,7 @@ from sqlalchemy import (MetaData, Table, Column, Integer,
 import os
 from module.MyMessageBox import show_dialog
 from PySide6.QtWidgets import QMessageBox
+from logger import logger
 
 meta = MetaData()
 
@@ -14,14 +15,12 @@ else:
     if os.environ.get("DEFAULT_PATH"):
         FILE_NAME = os.path.join(os.environ.get("DEFAULT_PATH"), "propusk.db")
     else:
+        logger.error("Не правильно указан путь к базе данных, или вообще отсутствует")
         show_dialog(
             QMessageBox.Icon.Critical,
             "Путь к бд",
             "Не правильно указан путь к базе данных, или вообще отсутствует"
         )
-        raise ValueError(F"Не правильно указан путь к базе данных, или вообще отсутствует")
-    
-print("q", FILE_NAME)
     
 cam_setting = Table("сam_setting", meta,
                     Column('id', Integer, primary_key=True),
@@ -64,11 +63,10 @@ list_propusk = Table("list_propusk", meta,
                             onupdate=func.current_timestamp()))
 
 
-engine = create_engine(F"sqlite:///{FILE_NAME}", echo=True)
-
+engine = create_engine(F"sqlite:///{FILE_NAME}", echo=False)
+engine.logging_name = 'PropuskLogger'
 
 def init_db():
-    print(FILE_NAME)
     if not os.path.exists(os.path.dirname(FILE_NAME)):
         os.mkdir(os.path.dirname(FILE_NAME))
 

+ 3 - 3
window/DialogCustomVariables.py

@@ -24,15 +24,15 @@ class DialogCustomVariables(Ui_DialogCustomVariables, QDialog):
         )
 
     def _show_path_photo(self) -> None:
-        dir = str(QFileDialog.getExistingDirectory(None, "Selected Directory"))
+        dir = str(QFileDialog.getExistingDirectory(None, "Выбрать директорию где будут храниться фоотографии"))
         self.path_photo.setText(dir)
 
     def _show_path_database(self) -> None:
-        dir = str(QFileDialog.getExistingDirectory(None, "Selected Directory"))
+        dir = str(QFileDialog.getExistingDirectory(None, "Выбрать директорию где будет храниться база данных"))
         self.path_db.setText(dir)
 
     def _save(self) -> None:
-        with open(self.path_env, 'w+') as file:
+        with open(self.path_env, 'w+', encoding="utf-8") as file:
             file.write(F"DB_DIR={self.path_db.text()} \n")
             file.write(F"PHOTO_DIR={self.path_photo.text()} \n")
 

+ 8 - 6
window/DialogHistory.py

@@ -7,7 +7,7 @@ from module.ModelPropusk import PropuskDataMethods
 from module.TemplatePropusk import TemplatePropusk
 import os
 from module.ImageTool import rotate_image
-# from PySide6.QtGui import QStandardItemModel
+from logger import logger
 
 
 class DialogHistory(Ui_DialogHistory, QDialog):
@@ -29,8 +29,11 @@ class DialogHistory(Ui_DialogHistory, QDialog):
         try:
             id_propusk = self.list_propusk.selectedItems()[0].text()
             self.load_page(int(id_propusk))
-        except IndexError:
+        except IndexError as err:
+            logger.debug(err)
             self.browser.clear()
+        except OSError as err:
+            logger.debug(err)
 
     @Slot(str)
     def filter_items(self, text: str) -> None:
@@ -75,13 +78,12 @@ class DialogHistory(Ui_DialogHistory, QDialog):
             ).fetchone()
 
             pdm = PropuskDataMethods(*row)
-            pdm.set_value("face_photo",
-                          rotate_image(pdm.get_value("face_photo"))
-                          )
+            path_photo = os.path.join(os.environ.get('PHOTO_DIR'), pdm.get_value("face_photo"))
+            pdm.set_value("face_photo", rotate_image(path_photo))
             
             render_text = str(TemplatePropusk(pdm._propusk_data.__dict__,
                                               os.path.join(os.path.dirname(
                                                   os.path.abspath(__package__)), 'docs')
                                               ))
-
+            logger.info(render_text)
             self.browser.setText(render_text)

+ 2 - 2
window/ListPersonal.py

@@ -31,8 +31,8 @@ class ListPersonal(QDialog, Ui_DialogListPersonal):
             with connect() as conn:
                 insert_personal = list_personal.insert().values(
                  lastname=self.lastname.text(),
-                firstname=self.firstname.text(),
-                middlename=self.middlename.text()
+                 firstname=self.firstname.text(),
+                 middlename=self.middlename.text()
                 )
                 conn.execute(insert_personal)
 

+ 39 - 30
window/MainWindow.py

@@ -8,7 +8,6 @@ from module.TemplatePropusk import TemplatePropusk
 from module.Printer import Printer
 from module.lang.ru import *
 from module.ImageTool import rotate_image
-# from module.ModelPropusk import *
 
 
 from .ui_py.ui_MainWindow import Ui_MainWindow
@@ -21,6 +20,9 @@ from .DialogHistory import DialogHistory
 
 from time import sleep
 from datetime import datetime
+from logger import logger
+from pathlib import Path
+import platform
 
 
 class MainWindow(QMainWindow, Ui_MainWindow):
@@ -74,6 +76,7 @@ class MainWindow(QMainWindow, Ui_MainWindow):
 
     def _check_setting_cam(self) -> None:
         if not self._get_selected_cam():
+            logger.warning(warring_cams.get("title"))
             show_dialog(
                 QMessageBox.Warning,
                 warring_cams.get("title"),
@@ -153,24 +156,31 @@ class MainWindow(QMainWindow, Ui_MainWindow):
     def _start_cam_photo(self) -> None:
         if self._get_selected_cam():
             if self.stacked_widget_photo.currentIndex() == int(os.environ.get('INDEX_PHOTO')):
-                self.stacked_widget_photo.setCurrentIndex(int(os.environ.get('INDEX_CAMERA')))
-                self.face_wwc = WorkWithCam(
-                    q_Video_Widget=self.face_video_widget,
-                    name_cam=self._get_selected_cam()
-                )
+                self.stacked_widget_photo.setCurrentIndex(
+                    int(os.environ.get('INDEX_CAMERA')))
+                self._create_wwc()
 
                 self.face_wwc.start_cam()
             else:
-                self._del_wwc("face_wwc", 1)
-                self.stacked_widget_photo.setCurrentIndex(int(os.environ.get('INDEX_PHOTO')))
+                self.face_wwc.stop_cam()
+                self.stacked_widget_photo.setCurrentIndex(
+                    int(os.environ.get('INDEX_PHOTO')))
+
+    def _create_wwc(self) -> None:
+        if not hasattr(self, "face_wwc"):
+            self.face_wwc = WorkWithCam(
+                q_Video_Widget=self.face_video_widget,
+                name_cam=self._get_selected_cam())
 
     @Slot()
-    def _take_image_face(self):
+    def _take_image_face(self) -> None:
         if hasattr(self, "face_wwc"):
-            self.face_file_name = self.face_wwc.cupture_image()
-            self.stacked_widget_photo.setCurrentIndex(int(os.environ.get('INDEX_PHOTO')))
-            self._del_wwc("face_wwc", 1)
-            load_image(self.imagePhoto, self.face_file_name)
+            self.face_file_name = self.face_wwc.cupture_image(self.imagePhoto)
+
+            sleep(1)
+            self.stacked_widget_photo.setCurrentIndex(
+                int(os.environ.get('INDEX_PHOTO')))
+            self.face_wwc.stop_cam()
 
     @Slot()
     def _print(self) -> None:
@@ -186,15 +196,18 @@ class MainWindow(QMainWindow, Ui_MainWindow):
             'dd.MM.yyyy hh:mm')
 
         rotate_img = rotate_image(self.face_file_name, -90)
-        propusk_data["face_photo"] = F"file://{rotate_img}"
+        
+        if platform.system() in 'Linux':
+            rotate_img = F"file://{rotate_img}"
 
-        render_text = str(TemplatePropusk(propusk_data,
-                                          os.path.join(os.environ.get('ABSOLUTE_PATH'), 'docs')
-                                          ))
+        propusk_data["face_photo"] = rotate_img
 
-        Printer(
-            render_text
-        ).print()
+        render_text = TemplatePropusk(
+            propusk_data,
+            os.path.join(os.environ.get('ABSOLUTE_PATH'), 'docs')
+        )
+
+        Printer(str(render_text)).print()
 
     @Slot()
     def _clear(self) -> None:
@@ -216,8 +229,8 @@ class MainWindow(QMainWindow, Ui_MainWindow):
             "place": self.place_combobox.currentData()['id'],
             "receiving_man": self.receiving_man.toPlainText(),
             "purpose_visite": self.purpose_visite.toPlainText(),
-            "face_photo": F"file://{self.face_file_name}",
-            "pasport_photo": F"file://{self.face_file_name}"
+            "face_photo": F"{Path(self.face_file_name).name}",
+            "pasport_photo": F"{Path(self.face_file_name).name}"
         }
 
         with connect() as conn:
@@ -225,18 +238,14 @@ class MainWindow(QMainWindow, Ui_MainWindow):
                 list_propusk.insert().values(**self.data_propusk)
             )
 
-    def _set_default_data(self):
+    def _set_default_data(self) -> None:
         self.number_propusk.clear()
         self.date_from.setDate(QDate().currentDate())
         self.date_to.setDate(QDate().currentDate())
         self._init_photo()
         self.receiving_man.clear()
         self.purpose_visite.clear()
-
+        self.stacked_widget_photo.setCurrentIndex(
+            int(os.environ.get('INDEX_PHOTO')))
         if hasattr(self, "face_wwc"):
-            self._del_wwc("face_wwc", 1)
-            self.stacked_widget_photo.setCurrentIndex(int(os.environ.get('INDEX_PHOTO')))
-
-    def _del_wwc(self, attr, second: int = 0) -> None:
-        sleep(second)
-        delattr(self, attr)
+            delattr(self, "face_wwc")