MainWindow.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import sys
  2. from datetime import datetime
  3. from pathlib import Path
  4. from PySide6.QtCore import QDate, QDateTime
  5. from PySide6.QtWidgets import QMainWindow, QMessageBox
  6. from sqlalchemy.exc import OperationalError
  7. from logger import logger
  8. from module import create_filename
  9. from module.cam import IPCam, USBCam, load_image
  10. from module.lang.ru import *
  11. from module.MyMessageBox import show_dialog
  12. from module.Printer import Print
  13. from module.QRCode import make as make_qr
  14. from module.TemplatePropusk import TemplatePropusk
  15. from module.WorkWithDB import *
  16. from module.wkhtmltopdf import get_path_wkhtmltopdf
  17. from module.ImageTool import rotate_image
  18. from widgets import PStackedWidget, create_widget_stacked
  19. from .DialogAbout import DialogAbout
  20. from .DialogHistory import DialogHistory
  21. from .DialogSettingCam import SettingCam
  22. from .ListPersonal import ListPersonal
  23. from .ListPlace import ListPlace
  24. from .ui_py.ui_MainWindow import Ui_MainWindow
  25. vecrot_cam_from_db = [str, str, str]
  26. class MainWindow(QMainWindow, Ui_MainWindow):
  27. def __init__(self, parent=None) -> None:
  28. super(MainWindow, self).__init__(parent)
  29. self.setupUi(self)
  30. self.__wwc = None
  31. self.data_propusk = None
  32. self.stacked_face = None
  33. self.date_from.setDateTime(QDateTime().currentDateTime())
  34. self.date_to.setDateTime(QDateTime().currentDateTime())
  35. self.__check_wkhtmltopdf()
  36. self.__init_menu_action()
  37. self.__init_btn_action()
  38. self.__update_list_combobox()
  39. self.__check_setting_cam()
  40. self.__create_widget_face_cam()
  41. self.tabWidget.currentChanged.connect(
  42. self.change_tab
  43. )
  44. def __init_menu_action(self) -> None:
  45. self.action_open_history.triggered.connect(self.open_history)
  46. self.btn_show_personal_window.triggered.connect(
  47. self.__show_personal_window
  48. )
  49. self.btn_show_place_window.triggered.connect(
  50. self.__show_place_window
  51. )
  52. self.setting_cam.triggered.connect(
  53. self.__show_setting_cam_window
  54. )
  55. self.update_list.triggered.connect(
  56. self.__update_list_combobox
  57. )
  58. self.btn_show_about.triggered.connect(
  59. self.__show_about_dialog
  60. )
  61. def __init_btn_action(self) -> None:
  62. self.btn_start_cam.clicked.connect(
  63. self.__press_btn_start_cam
  64. )
  65. self.capturePhoto.clicked.connect(
  66. self.__take_image
  67. )
  68. self.btn_save.clicked.connect(self.__save)
  69. self.btn_clear.clicked.connect(self.__clear)
  70. self.btn_print.clicked.connect(self.__print)
  71. def __show_about_dialog(self):
  72. DialogAbout(self).exec_()
  73. def __show_personal_window(self) -> None:
  74. ListPersonal(self).exec_()
  75. self.__update_list_combobox()
  76. def __show_place_window(self) -> None:
  77. ListPlace(self).exec_()
  78. self.__update_list_combobox()
  79. def __show_setting_cam_window(self) -> None:
  80. self.__stop_cam()
  81. SettingCam(self).exec_()
  82. self.__check_setting_cam()
  83. self.__create_widget_face_cam()
  84. def open_history(self) -> None:
  85. DialogHistory(self).exec_()
  86. def change_tab(self) -> None:
  87. self.__stop_cam()
  88. self.__check_setting_cam()
  89. if self.tabWidget.currentIndex() == 1:
  90. self.__mode = 'video'
  91. def __checked_rotate_document(self) -> bool:
  92. return self.rotate_image_document.isChecked()
  93. def __check_setting_cam(self) -> None:
  94. try:
  95. self.__mode, self.__cam_face, self.__cam_document = self.__get_selected_cam()
  96. except ValueError:
  97. logger.warning(warring_cams.get("title"))
  98. if show_dialog(
  99. QMessageBox.Warning,
  100. warring_cams.get("title"),
  101. warring_cams.get("body")
  102. ):
  103. self.__show_setting_cam_window()
  104. self.__check_setting_cam()
  105. else:
  106. self.close()
  107. except TypeError:
  108. logger.warning(warring_cams.get("title"))
  109. def __check_wkhtmltopdf(self) -> None:
  110. if get_path_wkhtmltopdf() is None:
  111. logger.critical('Не установлена программа wkhtmltopdf')
  112. show_dialog(QMessageBox.Icon.Critical,
  113. "Не найден wkhtmltopdf",
  114. "Не установлена программа wkhtmltopdf")
  115. sys.exit(0)
  116. def __update_list_combobox(self) -> None:
  117. self.__load_personal()
  118. self.__load_place()
  119. def __load_personal(self) -> None:
  120. self.personal_combobox.clear()
  121. with connect() as conn:
  122. for personal in conn.execute(
  123. list_personal.select()
  124. ).all():
  125. fio = F"{personal.lastname} {personal.firstname} {personal.middlename}"
  126. self.personal_combobox.addItem(
  127. fio,
  128. userData=personal.id
  129. )
  130. def __load_place(self) -> None:
  131. self.place_combobox.clear()
  132. with connect() as conn:
  133. for place in conn.execute(
  134. list_place.select()
  135. ).all():
  136. self.place_combobox.addItem(
  137. place.name_place,
  138. userData=place.id
  139. )
  140. def __get_selected_cam(self) -> vecrot_cam_from_db:
  141. '''
  142. return:
  143. str -> video, snapshot
  144. str -> ссылка для подключения к ip камеры или названия камеры (для лица)
  145. str -> названия камеры (для документа)
  146. '''
  147. with connect() as conn:
  148. cam = conn.execute(
  149. cam_setting.select()
  150. ).all()
  151. try:
  152. return cam[0].mode, cam[0].selected_cam, cam[1].selected_cam
  153. except:
  154. logger.error('Нет записи о камерах')
  155. if show_dialog(
  156. QMessageBox.Icon.Critical,
  157. 'Камера',
  158. 'Отсутствуют записи о камерах'
  159. ):
  160. self.__show_setting_cam_window()
  161. self.__check_setting_cam()
  162. else:
  163. sys.exit(0)
  164. def __press_btn_start_cam(self):
  165. match self.tabWidget.currentIndex():
  166. case 0: self.__start_cam(self.stacked_face, self.__cam_face)
  167. case 1: self.__start_cam(self.stacked_document, self.__cam_document)
  168. def __start_cam(self, widget: PStackedWidget, cam: str) -> None:
  169. if self.__wwc is None:
  170. widget.to_video()
  171. self.__create_wwc(widget, cam)
  172. self.btn_start_cam.setText(stop_cam)
  173. else:
  174. self.__stop_cam()
  175. widget.to_image()
  176. self.btn_start_cam.setText(start_cam)
  177. def __create_wwc(self, widget: PStackedWidget, cam: str) -> None:
  178. if self.__mode in 'snapshot':
  179. self.__wwc = IPCam()
  180. self.__wwc.qLabel = widget.video
  181. self.__wwc.lnk_connect = cam
  182. self.__wwc.start()
  183. else:
  184. self.__wwc = USBCam(widget.video, cam)
  185. self.__wwc.start_cam()
  186. def __take_image(self) -> None:
  187. if self.tabWidget.currentIndex() == 1:
  188. self.__file_name_document = self.__wwc.cupture_image(
  189. self.stacked_document.image)
  190. self.stacked_document.to_image()
  191. else:
  192. self.__file_name_face = self.__wwc.cupture_image(
  193. self.stacked_face.image)
  194. self.stacked_face.to_image()
  195. self.btn_start_cam.setText(start_cam)
  196. # self.__stop_cam()
  197. def __print(self) -> None:
  198. if self.data_propusk is None:
  199. self.__save()
  200. propusk_data = self.data_propusk.copy()
  201. if self.__checked_rotate_document():
  202. self.__file_name_document = rotate_image(self.__file_name_document)
  203. propusk_data.update({
  204. "personal": self.personal_combobox.currentText(),
  205. "place": self.place_combobox.currentText(),
  206. "date_from": self.date_from.dateTime().toString('dd.MM.yyyy hh:mm'),
  207. "date_to": self.date_to.dateTime().toString('dd.MM.yyyy hh:mm'),
  208. "face": self.__file_name_face,
  209. "document": self.__file_name_document,
  210. "qrcode": make_qr(propusk_data.get("id_propusk"), create_filename('qr')),
  211. "count_repeat": 2
  212. })
  213. render_text = TemplatePropusk(
  214. propusk_data,
  215. os.path.join(os.environ.get('ABSOLUTE_PATH'), 'docs')
  216. )
  217. Print(str(render_text))
  218. def __clear(self) -> None:
  219. if self.data_propusk is not None:
  220. self.data_propusk = None
  221. self.__set_default_data()
  222. def __save(self) -> None:
  223. date_from = self.date_from.dateTime().toMSecsSinceEpoch() / 1000
  224. date_to = self.date_to.dateTime().toMSecsSinceEpoch() / 1000
  225. self.data_propusk = {
  226. "id_propusk": int(self.number_propusk.text()),
  227. "date_from": datetime.fromtimestamp(date_from),
  228. "date_to": datetime.fromtimestamp(date_to),
  229. "personal": self.personal_combobox.currentData(),
  230. "place": self.place_combobox.currentData(),
  231. "receiving_man": self.receiving_man.toPlainText(),
  232. "purpose_visite": self.purpose_visite.toPlainText(),
  233. "face": F"{Path(self.__file_name_face).name}",
  234. "document": F"{Path(self.__file_name_document).name}"
  235. }
  236. with connect() as conn:
  237. try:
  238. conn.execute(
  239. list_propusk.insert().values(**self.data_propusk)
  240. )
  241. show_dialog(QMessageBox.Icon.Information, '', 'Сохранено')
  242. except OperationalError as er:
  243. logger.error(er)
  244. show_dialog(QMessageBox.Icon.Critical, 'Ошибка',
  245. 'Произошла ошибка при сохранении! \n Обратитесь к администратору')
  246. def __set_default_data(self) -> None:
  247. self.number_propusk.clear()
  248. self.date_from.setDate(QDate().currentDate())
  249. self.date_to.setDate(QDate().currentDate())
  250. if self.__wwc is not None:
  251. self.__stop_cam()
  252. self.stacked_document.to_image()
  253. self.stacked_face.to_image()
  254. load_image(self.stacked_document, os.environ.get('NO_MEDIA_IMAGE'))
  255. load_image(self.stacked_face, os.environ.get('NO_MEDIA_IMAGE'))
  256. self.receiving_man.clear()
  257. self.purpose_visite.clear()
  258. def __stop_cam(self):
  259. if self.__wwc is not None:
  260. self.__wwc.stop_cam()
  261. self.__wwc = None
  262. self.btn_start_cam.setText(start_cam)
  263. def __create_widget_face_cam(self) -> None:
  264. self.gridLayout.removeWidget(self.stacked_face)
  265. self.stacked_face = create_widget_stacked(
  266. name_object=u'stacked_face',
  267. obj=self.tab,
  268. layout=self.gridLayout,
  269. mode=self.__mode)
  270. self.stacked_face.currentChanged.connect(
  271. self.__change_text_btn
  272. )
  273. def __change_text_btn(self) -> None:
  274. if self.stacked_face.currentIndex() == 0:
  275. self.btn_start_cam.setText(stop_cam)
  276. else:
  277. self.btn_start_cam.setText(start_cam)