-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqtmain_xrf.py
More file actions
203 lines (168 loc) · 8.26 KB
/
qtmain_xrf.py
File metadata and controls
203 lines (168 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# LacCore/CSDCO
# qtmain_xrf.py
# PyQt GUI wrapper of XRF processing logic
import logging, os, sys, time, traceback
from PyQt5 import QtWidgets
import common
import xrf_opencv as xrf
from gui import FileListPanel, errbox, infobox, ProgressPanel, ButtonPanel
from prefs import Preferences
class MainWindow(QtWidgets.QDialog):
def __init__(self, app):
QtWidgets.QDialog.__init__(self)
self.VERSION = "1.4"
self.app = app
self.app_path = None # init'd in self.initPrefs()
self.initAppPath()
self.initGUI()
self.installRulers()
self.initPrefs()
def initGUI(self):
self.setWindowTitle("CSD Facility XRF Image Converter v{}".format(self.VERSION))
vlayout = QtWidgets.QVBoxLayout(self)
listLabel = "Images to be converted: click Add, or drag and drop files into the list below."
self.imageList = FileListPanel(listLabel)
self.imageList.addButton.setAutoDefault(False)
self.imageList.rmButton.setAutoDefault(False)
self.saveDefaultsButton = QtWidgets.QToolButton()
self.saveDefaultsButton.setText("Save Current Settings as Default")
self.saveDefaultsButton.clicked.connect(self.saveDefaultSettings)
vlayout.addWidget(self.imageList, 1)
settingsGroupBox = QtWidgets.QGroupBox("Converter Settings")
settingsGroupLayout = QtWidgets.QVBoxLayout()
self.gamma = QtWidgets.QLineEdit()
self.gamma.setFixedWidth(50)
gammaLayout = QtWidgets.QHBoxLayout()
gammaLayout.addWidget(QtWidgets.QLabel("Gamma Correction:"))
gammaLayout.addWidget(self.gamma)
gammaLayout.addWidget(QtWidgets.QLabel("typically between 0.8 (darker) and 2.3 (brighter)"), stretch=1)
rulerLayout = QtWidgets.QHBoxLayout()
self.rulerCombo = QtWidgets.QComboBox()
self.rulerCombo.setSizePolicy(QtWidgets.QSizePolicy.Expanding, self.rulerCombo.sizePolicy().verticalPolicy())
rulerLayout.addWidget(QtWidgets.QLabel("Ruler:"))
rulerLayout.addWidget(self.rulerCombo)
outputNamingLayout = QtWidgets.QHBoxLayout()
self.outputNamingCombo = QtWidgets.QComboBox()
self.outputNamingCombo.addItems(["Use input file's name", "Use name of input file's parent directory"])
self.outputNamingCombo.setSizePolicy(QtWidgets.QSizePolicy.Expanding, self.outputNamingCombo.sizePolicy().verticalPolicy())
outputNamingLayout.addWidget(QtWidgets.QLabel("Output Naming:"))
outputNamingLayout.addWidget(self.outputNamingCombo)
settingsGroupLayout.addLayout(gammaLayout)
settingsGroupLayout.addLayout(rulerLayout)
settingsGroupLayout.addLayout(outputNamingLayout)
settingsGroupLayout.addSpacing(15)
settingsGroupLayout.addWidget(self.saveDefaultsButton)
settingsGroupBox.setLayout(settingsGroupLayout)
vlayout.addSpacing(10)
vlayout.addWidget(settingsGroupBox)
self.convertButton = QtWidgets.QPushButton("Convert Images")
self.convertButton.clicked.connect(self.processImageFiles)
self.convertButton.setAutoDefault(False)
self.buttonPanel = ButtonPanel(self.convertButton)
self.progressPanel = ProgressPanel(self, "Converting...")
self.stackedLayout = QtWidgets.QStackedLayout()
self.stackedLayout.addWidget(self.buttonPanel)
self.stackedLayout.addWidget(self.progressPanel)
self.stackedLayout.setCurrentIndex(0)
vlayout.addLayout(self.stackedLayout, stretch=0)
def showProgressLayout(self, show):
self.stackedLayout.setCurrentIndex(1 if show else 0)
def initAppPath(self):
try:
self.app_path = common.get_app_path()
except common.InvalidApplicationPathError as iape:
errbox(self, "Invalid Application Path", "Couldn't find application directory, exiting.")
raise iape # re-raise and bail
def initPrefs(self):
prefPath = os.path.join(self.app_path, "prefs.pk")
self.prefs = Preferences(prefPath)
self.installPrefs()
def installRulers(self):
rulersPath = os.path.join(self.app_path, "rulers")
if not os.path.exists(rulersPath):
os.mkdir(rulersPath)
rulerFiles = [f for f in os.listdir(rulersPath) if os.path.isfile(os.path.join(rulersPath, f))
and os.path.basename(f)[0] != '.'] # no hidden files
if len(rulerFiles) == 0:
errbox(self, message="No ruler files were found. Add one or more ruler files to the rulers folder and restart.")
else:
self.rulerCombo.addItems(rulerFiles)
def installPrefs(self):
geom = self.prefs.get("windowGeometry", None)
if geom is not None:
self.setGeometry(geom)
self.gamma.setText(self.prefs.get("gamma", "1.4"))
ruler = self.prefs.get("ruler", "")
rulerIdx = self.rulerCombo.findText(ruler)
self.rulerCombo.setCurrentIndex(rulerIdx if rulerIdx >= 0 else 0)
# default to input file name
self.outputNamingCombo.setCurrentIndex(self.prefs.get("outputNaming", 0))
def savePrefs(self):
self.prefs.set("windowGeometry", self.geometry())
self.prefs.write()
def saveDefaultSettings(self):
self.prefs.set("gamma", self.gamma.text())
self.prefs.set("ruler", self.rulerCombo.currentText())
self.prefs.set("outputNaming", self.outputNamingCombo.currentIndex())
settingsItems = [
f"Gamma: {self.gamma.text()}",
f"Ruler: {self.rulerCombo.currentText()}",
f"Output naming: {self.outputNamingCombo.currentText()}"
]
settingsStr = "Saved Default Settings.\n\n" + '\n'.join(settingsItems)
infobox(self, 'Saved Default Settings', settingsStr)
# override QWidget.closeEvent()
def closeEvent(self, event):
self.savePrefs()
event.accept() # allow window to close - event.ignore() to veto close
def getRulerPath(self):
return os.path.join(self.app_path, "rulers", str(self.rulerCombo.currentText()))
def processImageFiles(self):
imgFiles = self.imageList.getFiles()
if len(imgFiles) == 0:
infobox(self, "No Images", "Add at least one image to be converted.")
return
try:
gamma = float(self.gamma.text())
if (gamma <= 0.0):
infobox(self, "Invalid Gamma", "Gamma correction must be greater than 0.0")
return
except ValueError:
errbox(self, "Invalid Gamma", "Gamma value must be numeric and greater than 0.0")
return
success = False
self.showProgressLayout(True)
self.progressPanel.clear()
xrf.setProgressListener(self.progressPanel)
try:
parentDirBasename = self.outputNamingCombo.currentIndex() == 1
for imgPath in imgFiles:
if parentDirBasename:
outputBaseName = os.path.basename(os.path.dirname(os.path.normpath(imgPath)))
else:
outputBaseName, _ = os.path.splitext(os.path.basename(imgPath))
xrf.prepare_xrf(imgPath, self.getRulerPath(), gamma, outputBaseName, destDir=self.app_path)
success = True
except common.UnexpectedColorDepthError as e:
errbox(self, "Unexpected Color Depth", "{}".format(e.message))
except common.UnexpectedComponentCountError as e:
errbox(self, "Unexpected Component Count", "{}".format(e.message))
except common.RulerTooShortError as e:
errbox(self, "Ruler Too Short", "{}".format(e.message))
except:
err = sys.exc_info()
errbox(self, "Process failed", "{}".format("Unhandled error {}: {}".format(err[0], err[1])))
logging.error(traceback.format_exc())
finally:
self.showProgressLayout(False)
self.progressPanel.clear()
if success:
infobox(self, "Yay!", "Successfully converted {} image files.".format(len(imgFiles)))
self.imageList.clear()
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow(app)
window.setModal(False)
window.show()
sys.exit(app.exec_())