프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / HMBDialog.py @ 1fea31e1

이력 | 보기 | 이력해설 | 다운로드 (6.42 KB)

1
# coding: utf-8
2
"""This is HMB dialog module"""
3
import os
4
import sys
5

    
6
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Commands'))
7
import FenceCommand
8

    
9
from PyQt5.QtCore import *
10
from PyQt5.QtGui import *
11
from PyQt5.QtWidgets import *
12
import openpyxl
13
from openpyxl.styles import *
14

    
15
from AppDocData import AppDocData, Config
16

    
17
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Shapes'))
18

    
19

    
20
class QHMBDialog(QDialog):
21
    def __init__(self, parent):
22
        from HMB_UI import Ui_HMBDialog
23
        from TableWidgetEx import QTableWidgetEx
24
        from WaitingSpinnerWidget import QtWaitingSpinner
25

    
26
        QDialog.__init__(self, parent)
27
        try:
28
            self.ui = Ui_HMBDialog()
29
            self.ui.setupUi(self)
30
            self.waiting_spinner = QtWaitingSpinner(self)
31
            self.ui.horizontalLayoutSpinnerWaiting.addWidget(self.waiting_spinner)
32

    
33
            self.ui.buttonBox.button(QDialogButtonBox.Ok).setIcon(QIcon(':/newPrefix/OK.svg'))
34
            self.ui.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Import'))
35
            self.ui.buttonBox.button(QDialogButtonBox.Close).setIcon(QIcon(':/newPrefix/Remove.svg'))
36

    
37
            self.fill_hmb_data(None)
38
            self.ui.tableViewHMB.setAlternatingRowColors(True)
39
            self.ui.toolButtonHMBFilePath.clicked.connect(self.on_open_hmb_file)
40
        except Exception as ex:
41
            from App import App
42
            from AppDocData import MessageType
43

    
44
            message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
45
                      f"{sys.exc_info()[-1].tb_lineno}"
46
            App.mainWnd().addMessage.emit(MessageType.Error, message)
47

    
48
    def fill_hmb_data(self, file_path: str):
49
        """load hmb data and fill table view"""
50
        import uuid
51

    
52
        try:
53
            hmbs = AppDocData.get_hmb_data(file_path)
54
            if not hmbs:
55
                return
56

    
57
            model = QStandardItemModel()
58
            header = ['UID', 'StreamNumber']
59

    
60
            for hmb in hmbs:
61
                UID = hmb.uid
62
                STREAM_NO = hmb.stream_no
63
                items = [QStandardItem(UID), QStandardItem(STREAM_NO)]
64

    
65
                for data in sorted(hmb.data, key=lambda param: param.index):
66
                    if hmbs.index(hmb) == 0:
67
                        header.append(f"{data.name}\n({data.unit})" if data.unit else f"{data.name}")
68
                    items.append(QStandardItem(data.value))
69
                model.appendRow(items)
70

    
71
            model.setHorizontalHeaderLabels(header)
72

    
73
            self.ui.tableViewHMB.setModel(model)
74
            self.ui.tableViewHMB.resizeColumnsToContents()
75
            self.ui.tableViewHMB.setEditTriggers(QAbstractItemView.NoEditTriggers)
76
        except Exception as ex:
77
            from App import App
78
            from AppDocData import MessageType
79

    
80
            message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
81
                      f"{sys.exc_info()[-1].tb_lineno}"
82
            App.mainWnd().addMessage.emit(MessageType.Error, message)
83

    
84
    class Worker(QThread):
85
        finished = pyqtSignal()
86

    
87
        def __init__(self, file_path: str):
88
            super().__init__()
89

    
90
            self._file_path = file_path
91

    
92
        def run(self):
93
            """execute thread"""
94
            import math
95
            import pandas as pd
96
            from HMBTable import HMBData, StreamData
97

    
98
            hmb_list = []
99
            sheets = pd.read_excel(self._file_path, sheet_name=None, header=None, convert_float=False)
100
            for name, df in sheets.items():
101
                rows, cols = df.shape[0], df.shape[1]
102
                for col in range(2, cols):
103
                    stream_no = df.iloc[0, col]
104
                    from_ = df.iloc[1, col]
105
                    to_ = df.iloc[2, col]
106

    
107
                    hmb = HMBData()
108
                    hmb.stream_no = stream_no
109
                    hmb.hfrom = from_
110
                    hmb.hto = to_
111

    
112
                    data = []
113
                    for row in range(3, rows):
114
                        value_ = df.iloc[row, 0]
115
                        name = value_ if value_ else ''
116
                        value_ = df.iloc[row, 1]
117
                        unit = value_ if value_ else ''
118
                        value_ = df.iloc[row, col]
119
                        value = value_ if (type(value_) is str) or (type(value_) is float and not math.isnan(value_)) \
120
                            else ''
121

    
122
                        data.append(StreamData(name, unit, value, row))
123

    
124
                    hmb.data = data
125
                    hmb_list.append(hmb)
126
                break
127

    
128
            app_doc_data = AppDocData.instance()
129
            app_doc_data.save_hmb_data(hmb_list)
130

    
131
            self.finished.emit()
132

    
133
    def on_open_hmb_file(self):
134
        """open hmb file"""
135
        from HMBTable import HMBData, StreamData
136

    
137
        options = QFileDialog.Options()
138
        options |= QFileDialog.DontUseNativeDialog
139
        file, _ = QFileDialog.getOpenFileName(self, self.tr('Import', "Select Excel File"),
140
                                               os.getcwd(), "excel files (*.xlsx)", options=options)
141
        if file:
142
            self.ui.lineEditHMBFilePath.setText(file)
143

    
144
    def accept(self):
145
        """no more used"""
146
        """accept dialog"""
147
        from HMBTable import HMBTable, HMBData
148
        from SymbolAttr import SymbolAttr
149

    
150
        def on_finished():
151
            self.fill_hmb_data(None)
152
            self.waiting_spinner.stop()
153

    
154
        try:
155
            file_path = self.ui.lineEditHMBFilePath.text()
156
            if file_path:
157
                self.worker = QHMBDialog.Worker(file_path)
158
                self.worker.finished.connect(on_finished)
159
                self.waiting_spinner.start()
160
                self.worker.start()
161
            else:
162
                QMessageBox.warning(self, self.tr('Warning'), self.tr('Please, select a HMB excel file'))
163

    
164
                """
165
                app_doc_data = AppDocData.instance()
166
                model = self.ui.tableViewHMB.model()
167
                app_doc_data.save_hmb_model(model)
168
                QDialog.accept(self)
169
                """
170
        except Exception as ex:
171
            message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
172
                      f"{sys.exc_info()[-1].tb_lineno}"
173
            QMessageBox.warning(self, self.tr('Warning'), message)
174

    
175
    def reject(self):
176
        """reject dialog"""
177
        QDialog.reject(self)