-
Notifications
You must be signed in to change notification settings - Fork 0
/
CeramScan.py
1210 lines (976 loc) · 52.3 KB
/
CeramScan.py
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Standard libraries
import sys
import os
# For logging errors.
#import logging
#import time
import datetime
# For reading the excel table with the users
import pandas as pd
import numpy as np
# Import the other python files, resource files,..
from Ui_MainWindow import *
from Gui_GetSet import *
from PySide6.QtWidgets import QFileDialog
from PySide6.QtCore import QResource, QDateTime
# For the actual QR Coder
import qrcode
# For the printer connection
from brother_ql.conversion import convert
from brother_ql.backends.helpers import send
from brother_ql.raster import BrotherQLRaster
# For decoding of the QR code1
import cv2
# For writing with the API
import elabapi_python
from elabapi_python.rest import ApiException
import urllib3
import json
# For image manipulation of the QR codes
from PIL import Image, ImageDraw, ImageFont
import io
import cairosvg
import tempfile
# Global folders
## The Python folder with the main python file
global pythonfolder
pythonfolder = os.path.dirname(os.path.abspath(__file__))
## The Output folder
global outputfolder
outputfolder = os.path.join(pythonfolder, "Output")
global configdict
configdict = dict()
# Config File
try:
with open(os.path.join(pythonfolder, "config.txt")) as f:
lines = f.readlines()
for line in lines:
if len(line) != 0 and line != "\n":
# Split each line into key and value
key, value = map(str.strip, line.split('='))
configdict[key] = value
print(configdict)
except Exception as a:
errorpath = os.path.join(outputfolder, "errorlog.txt")
f = open(errorpath, "a")
f.write(str(a) + "\n")
f.close()
QResource.registerResource("Resourcefile_rc.py")
####################################################################################################################################
# Gui MainWindow
####################################################################################################################################
class Gui(QMainWindow, Ui_MainWindow, Gui_GetSet): #, MainWindow
def __init__(self):
super(Gui, self).__init__()
self.setupUi(self)
self.is_initial = False # BOOL
self.initial = "" # STR
self.shortday = "" # STR
self.shortmonth = "" # STR
self.shortyear = "" # STR
self.samplenumberlist = [1]
self.subsamplenumberlist = []
self.is_batch = False # BOOL
self.is_singlesubsample = False # BOOL
self.is_batchsubsample = False # BOOL
self.ghsdict = { # DICT
"Explosive":False,
"Flammable":False,
"Oxidizing":False,
"Corrosive":False,
"Toxic":False,
"Harmful":False,
"HealthHazard":False,
"EnvironmentalHazard":False
}
self.disposal = "NoIdea"
self.df = None # This is the Pandas dataframe with all the data.
self.savefolder = outputfolder
####################################################################################################################################
# Load the userid excel table.
userid = pd.read_excel(str(configdict["LinkID"]),"userid")
userid = userid.apply(lambda x: x.astype(str).str.upper())
####################################################################################################################################
# Start the program at home and set all tabs to the first position. And some stuff not visible.
self.Main_tab.setCurrentIndex(0)
self.Home_tab.setCurrentIndex(0)
self.SampleID_tab.setCurrentIndex(0)
self.Subsample1_spinBox.setVisible(False)
self.Subsample2_spinBox.setVisible(False)
self.Subsample3_spinBox.setVisible(False)
self.label_11.setVisible(False)
# Set the current date
self.Current_dateEdit.setDateTime(QDateTime(QDate.currentDate(), QTime.currentTime()))
date = self.Current_dateEdit.date().toPython()
year = int(date.strftime("%Y")) + 10
month = int(date.strftime("%m"))
day = int(date.strftime("%d"))
self.Current_dateEdit.setDisplayFormat("dd/MM/yyyy")
self.Expiration_dateEdit.setDateTime(QDateTime(QDate(year,month,day), QTime.currentTime()))
self.Expiration_dateEdit.setMinimumDateTime(QDateTime(QDate.currentDate(), QTime.currentTime()))
self.Expiration_dateEdit.setDisplayFormat("dd/MM/yyyy")
# Set the column width
self.AddInformation_tableWidget.setColumnWidth(3, 80)
self.AddInformation_tableWidget.setColumnWidth(4, 80)
self.AddInformation_tableWidget.setColumnWidth(5, 80)
####################################################################################################################################
# Button clicks and actions.
#### Home ####
self.HomeCreate_button.clicked.connect(lambda: self.tabchange(self.Main_tab, 1))
self.HomeSearch_button.clicked.connect(lambda: self.tabchange(self.Main_tab, 2))
self.HomeScan_button.clicked.connect(lambda: self.tabchange(self.Main_tab, 3))
self.HomeLog_button.clicked.connect(lambda: self.tabchange(self.Main_tab, 4))
self.HomeAbout_button.clicked.connect(lambda: self.tabchange(self.Main_tab, 5))
#### CreateSampleID ####
self.SampleID_tab.currentChanged.connect(self.create_sampletable) # Tabchange connect.
self.SampleidBack1_button.clicked.connect(lambda: self.tabchange(self.Main_tab, 0))
self.SampleidForward1_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 1))
self.Decrypt_button.clicked.connect(lambda: self.decrypt_abbr(userid))
self.SampleidBack2_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 0))
self.SampleidForward2_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 2))
self.FirstName_lineEdit.textChanged.connect(lambda: self.namedate_update(userid))
self.LastName_lineEdit.textChanged.connect(lambda: self.namedate_update(userid))
self.Supervisor_lineEdit.textChanged.connect(lambda: self.upper_lineedit(self.Supervisor_lineEdit))
self.Current_dateEdit.dateChanged.connect(lambda: self.namedate_update(userid))
self.SampleidBack3_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 1))
self.SampleidForward3_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 3))
self.SubSample1_checkBox.stateChanged.connect(self.subsamplesingle_change)
self.SubSample2_checkBox.stateChanged.connect(self.subsamplebatch_change)
self.Batch_radioButton.toggled.connect(self.switch_singlebatch)
self.Samplenumber1_spinBox.valueChanged.connect(self.encrypt_samplenumber)
self.Subsample1_spinBox.valueChanged.connect(self.encrypt_samplenumber)
self.Samplenumber2_spinBox.valueChanged.connect(self.encrypt_samplenumber)
self.Samplenumber3_spinBox.valueChanged.connect(self.encrypt_samplenumber)
self.Subsample2_spinBox.valueChanged.connect(self.encrypt_samplenumber)
self.Subsample3_spinBox.valueChanged.connect(self.encrypt_samplenumber)
self.SampleidBack4_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 2))
self.SampleidForward4_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 4))
self.Explos_checkBox.stateChanged.connect(lambda: self.ghs_change("Explosive", self.Explos_checkBox))
self.Flamme_checkBox.stateChanged.connect(lambda: self.ghs_change("Flammable", self.Flamme_checkBox))
self.Rondflam_checkBox.stateChanged.connect(lambda: self.ghs_change("Oxidizing", self.Rondflam_checkBox))
self.Acid_checkBox.stateChanged.connect(lambda: self.ghs_change("Corrosive", self.Acid_checkBox))
self.Skull_checkBox.stateChanged.connect(lambda: self.ghs_change("Toxic", self.Skull_checkBox))
self.Exclam_checkBox.stateChanged.connect(lambda: self.ghs_change("Harmful", self.Exclam_checkBox))
self.Silhouette_checkBox.stateChanged.connect(lambda: self.ghs_change("HealthHazard", self.Silhouette_checkBox))
self.Pollu_checkBox.stateChanged.connect(lambda: self.ghs_change("EnvironmentalHazard", self.Pollu_checkBox))
self.SampleidBack5_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 3))
self.SampleidForward5_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 5))
self.NoIdea_radioButton.toggled.connect(lambda: self.disposal_change("NoIdea"))
self.NonHarzardous_radioButton.toggled.connect(lambda: self.disposal_change("NonHazardous"))
self.ContaminatedSolids_radioButton.toggled.connect(lambda: self.disposal_change("ContaminatedSolids"))
self.HalogenatedSolvents_radioButton.toggled.connect(lambda: self.disposal_change("HalogenatedSolvents"))
self.HalogenFreeSolvents_radioButton.toggled.connect(lambda: self.disposal_change("HalogenFree"))
self.SpecialPrecautions_radioButton.toggled.connect(lambda: self.disposal_change("SpecialPrecautions"))
self.SampleidBack6_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 4))
self.SampleidForward6_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 6))
#Recursion Error
#self.AddInformation_tableWidget.itemChanged.connect(self.create_sampletable)
self.SampleidBack7_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 5))
self.SampleidForward7_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 7))
self.Foldersave_button.clicked.connect(lambda: self.save_folder())
self.Save_button.clicked.connect(lambda: self.save_qrcodes())
self.ElabFTW_button.clicked.connect(lambda: self.sampleid_to_elabftw())
self.Print_button.clicked.connect(lambda: self.print_qrcodes())
self.SampleidBack8_button.clicked.connect(lambda: self.tabchange(self.SampleID_tab, 6))
self.Reset_button.clicked.connect(lambda: self.reset_ceram())
#### SearchSampleID ####
self.SearchID_lineEdit.setEnabled(False)
self.SearchID_pushButton.setEnabled(False)
self.SearchID_textBrowser.setEnabled(False)
#### ScanQR-Code ####
self.ScanQR_button.setEnabled(False)
self.ShowQR_button.setEnabled(False)
self.ScanToCreate_button.setEnabled(False)
self.ScanResult_textBrowser.setEnabled(False)
#### ShowTheLog ####
#### About ####
####################################################################################################################################
# Other functions
####################################################################################################################################
def get_allselfs(self):
"""
Prints all the current values of instance variables (self attributes).
Attributes:
- self.is_initial (bool): Flag indicating if initials are available.
- self.initial (str): User abbreviation generated from first and last names.
- self.is_singlesubsample (bool): Flag indicating the presence of single subsamples.
- self.is_batchsubsample (bool): Flag indicating the presence of batch subsamples.
- self.is_batch (bool): Flag indicating if in batch sample mode.
- self.ghsdict (dict): Dictionary containing GHS values.
- self.disposal (str): Disposal information.
- self.shortday (str): Abbreviation of the current day.
- self.shortmonth (str): Abbreviation of the current month.
- self.shortyear (str): Abbreviation of the current year.
"""
print(
"self.is_initial", self.is_initial,
"self.initial", self.initial,
"self.is_singlesubsample", self.is_singlesubsample,
"self.is_batchsubsample", self.is_batchsubsample,
"self.is_batch", self.is_batch,
"self.ghsdict", self.ghsdict,
"self.disposal", self.disposal,
"self.shortday", self.shortday,
"self.shortmonth", self.shortmonth,
"self.shortyear", self.shortyear
)
def decrypt_abbr(self, userid):
"""
Translates an abbreviation of a user or sample ID to the lineedits.
Parameters:
- userid (pd.DataFrame): DataFrame containing user or sample ID information.
Raises:
- Exception: If the input is too short to be interpreted.
Returns:
None
"""
outputtext = ""
try:
decryptinput = self.get_lineedit(self.Decrypt_lineEdit)
if len(decryptinput) <= 1:
self.create_log("Input is too short to be interpreted.")
outputtext += "Input is too short to be interpreted; "
raise Exception("Input is too short to be interpreted.")
# Make sure that the rest of the date does not change if only a Year, i.e. a 3 character string, is given.
year, month, day = self.get_date(self.Current_dateEdit)
try:
decrypt_id = userid[userid.UserID == decryptinput[0:2]].index.values
self.set_lineedit(self.FirstName_lineEdit, userid.loc[decrypt_id,"First"].item().upper())
self.set_lineedit(self.LastName_lineEdit, userid.loc[decrypt_id,"Surname"].item().upper())
outputtext += "User ID was decrypted; "
except:
outputtext += "User ID is unknown; "
if len(decryptinput) > 2:
year_id = decryptinput[2]
try:
year = self.decrypt_year(year_id, startingyear=int(configdict["StartingYear"]))
outputtext += "Year translated; "
except TypeError:
# Log
outputtext += "Sample ID, wrong format for Year?; "
self.create_log("Sample ID, wrong format for Year?")
try:
year = int(configdict["StartingYear"])
except:
year = 2011
if len(decryptinput) > 3:
month_id = decryptinput[3]
try:
month = self.decrypt_month(month_id)
outputtext += "Month translated; "
except TypeError:
# Log
self.create_log("Sample ID too short to translate the month? Month set to 01.")
outputtext += "Month cannot be decrypted, set to 01; "
month = 1
if len(decryptinput) > 4:
day_id = decryptinput[4]
try:
day = self.decrypt_day(day_id)
outputtext += "Day translated; "
except TypeError:
# Log
self.create_log("Sample ID too short to translate the day? Day set to 01.")
outputtext += "Day cannot be decrypted, set to 01; "
day = 1
self.set_date(self.Current_dateEdit,QDate(year, month, day))
except Exception as e:
outputtext += "Error: " + str(e)+ "; "
self.create_log("Decrypt button: " + str(e))
finally:
self.set_label(self.DecryptResponse_label, outputtext)
def encrypt_abbr(self, userid):
"""
Translate the name to a user abbreviation.
This method takes the first name and last name entered by the user, looks
up the corresponding user ID in the provided 'userid' DataFrame, and returns
the user abbreviation. If the user is found in the DataFrame, it returns
the uppercase user ID. Otherwise, it generates an abbreviation using the
first letters of the first and last names.
Args:
userid (pd.DataFrame): DataFrame containing user information.
Returns:
str: User abbreviation.
"""
encrypt_firstname = self.get_lineedit(self.FirstName_lineEdit)
encrypt_secondname = self.get_lineedit(self.LastName_lineEdit)
try:
if encrypt_secondname in userid.Surname.values and encrypt_firstname in userid.First.values:
decrypt_id = userid[(userid["First"]==encrypt_firstname) & (userid["Surname"]==encrypt_secondname)].index.values
self.initial = userid.loc[decrypt_id,"UserID"].item().upper()
self.is_initial = True
else:
self.initial = "-" + encrypt_firstname[0:1].upper() + encrypt_secondname[0:1].upper()
self.is_initial = False
except:
self.initial = "-" + encrypt_firstname[0:1].upper() + encrypt_secondname[0:1].upper()
self.is_initial = False
return self.initial
def encrypt_date(self):
"""
Translate the date to its abbreviation.
This method extracts the year, month, and day from the current date and
translates each component to its corresponding abbreviation. It returns a
tuple containing the abbreviated year, month, and day.
Returns:
Tuple[str, str, str]: A tuple containing the abbreviated year, month, and day.
"""
year, month, day = self.get_date(self.Current_dateEdit)
try:
self.shortyear = self.encrypt_year(year, startingyear=int(configdict["StartingYear"]))
except:
self.shortyear = self.encrypt_year(year, startingyear=2011)
self.shortmonth = self.encrypt_month(month)
self.shortday = self.encrypt_day(day)
return (self.shortyear, self.shortmonth, self.shortday)
def namedate_update(self, userid):
"""
Update the Initial and date by any change of any of the fields.
Args:
userid (str): The user ID for encryption.
Returns:
None.
"""
initial = self.encrypt_abbr(userid)
(shortyear, shortmonth, shortday) = self.encrypt_date()
self.NameDateOutput_label.setText(str(str(initial)+ str(shortyear)+ str(shortmonth)+str(shortday)))
def subsamplesingle_change(self):
"""
Change the state of single subsamples.
This method toggles the state of single subsamples based on the visibility
of certain UI elements. It updates the 'self.is_singlesubsample' attribute
and adjusts the visibility of related UI elements accordingly.
Returns:
None.
"""
self.is_singlesubsample = self.checkbox_visibilitychange(self.SubSample1_checkBox, self.Subsample1_spinBox)
self.encrypt_samplenumber()
self.create_log("The subsamples for single samples was changed to: " + str(self.is_singlesubsample))
def subsamplebatch_change(self):
"""
Change the state of batch subsamples.
This method toggles the state of batch subsamples based on the visibility
of certain UI elements. It updates the 'self.is_batchsubsample' attribute
and adjusts the visibility of related UI elements accordingly.
Returns:
None.
"""
self.is_batchsubsample = self.checkbox_visibilitychange(self.SubSample2_checkBox, self.Subsample2_spinBox)
self.checkbox_visibilitychange(self.SubSample2_checkBox, self.Subsample3_spinBox)
self.checkbox_visibilitychange(self.SubSample2_checkBox, self.label_11)
self.checkbox_visibilitychange(self.SubSample2_checkBox, self.Samplenumber3_spinBox, inverse=True)
self.checkbox_visibilitychange(self.SubSample2_checkBox, self.label_10, inverse=True)
self.encrypt_samplenumber()
self.create_log("The subsamples for batch samples was changed to: " + str(self.is_batchsubsample))
def switch_singlebatch(self):
"""
Switch between single and batch sample modes.
This method toggles between single and batch sample modes based on the
selection of the corresponding radio button. It updates the 'self.is_batch'
attribute and logs the mode change.
Returns:
None.
"""
if self.Batch_radioButton.isChecked():
self.is_batch = True
self.create_log("Batch sample mode: " + str(self.is_batch))
else:
self.is_batch = False
self.create_log("Batch sample mode: " + str(self.is_batch))
self.encrypt_samplenumber()
def ghs_change(self, ghsdictkey, checkboxobject):
"""
Change a GHS value in the GHS dictionary.
Args:
ghsdictkey (str): The key corresponding to the GHS value.
checkboxobject (QCheckBox): The checkbox object representing the GHS value.
Returns:
None.
"""
state = self.getstate_checkbox(checkboxobject)
self.ghsdict[ghsdictkey] = state
def disposal_change(self, disposalstring):
"""
Change the disposal string.
Args:
disposalstring (str): The new disposal string.
Returns:
None.
"""
self.disposal = disposalstring
def encrypt_samplenumber(self):
"""
Get the samplenumber(s) with potentially its subsamplenumber(s).
This method retrieves sample numbers and subsample numbers based on user input.
It ensures that the entered values are within a valid range and handles batch
and single sample scenarios accordingly. The resulting sample numbers and
subsample numbers are stored in 'self.samplenumberlist' and 'self.subsamplenumberlist'.
Returns:
None.
"""
# If the first value is changed to be higher than the second.
if self.Samplenumber2_spinBox.value() > self.Samplenumber3_spinBox.value():
self.Samplenumber3_spinBox.setValue(self.Samplenumber2_spinBox.value())
# If the first value is changed to be higher than the second.
elif self.Subsample2_spinBox.value() > self.Subsample3_spinBox.value():
self.Subsample3_spinBox.setValue(self.Subsample2_spinBox.value())
# Currently, the maximum amount of samples is chosen to be 20 at a time.
elif self.Subsample3_spinBox.value() >= (self.Subsample2_spinBox.value()+19):
self.Subsample3_spinBox.setValue(self.Subsample2_spinBox.value()+19)
elif self.Samplenumber3_spinBox.value() >= (self.Samplenumber2_spinBox.value()+19):
self.Samplenumber3_spinBox.setValue(self.Samplenumber2_spinBox.value()+19)
self.samplenumberlist = []
self.subsamplenumberlist = []
# If the batch sample number is selected:
if self.is_batch:
try:
if self.is_batchsubsample:
self.subsamplenumberlist.extend(list(range(self.Subsample2_spinBox.value(), self.Subsample3_spinBox.value()+1)))
self.samplenumberlist.extend([self.Samplenumber2_spinBox.value()]*len(self.subsamplenumberlist))
else:
self.samplenumberlist.extend(list(range(self.Samplenumber2_spinBox.value(), self.Samplenumber3_spinBox.value()+1)))
except:
pass
# If the single sample number is selected:
else:
try:
self.samplenumberlist.append(self.Samplenumber1_spinBox.value())
if self.is_singlesubsample:
self.subsamplenumberlist.append(self.Subsample1_spinBox.value())
except:
pass
print("SampleNumber", self.samplenumberlist, "SubSample", self.subsamplenumberlist)
def create_sampletable(self):
"""
Create the sampleID table with buttons.
This method populates the sampleID table in the GUI with sample information.
It retrieves necessary data using 'get_allselfs()' and iterates over the sample
numbers to create labels with short names and numbers. The information is then
added to the 'AddInformation_tableWidget'.
Returns:
None.
"""
self.get_allselfs()
for i in range(len(self.samplenumberlist)):
shortname = str(self.NameDateOutput_label.text())
if len(self.subsamplenumberlist) != 0:
number = str(self.samplenumberlist[i]) + "_" + str(self.subsamplenumberlist[i])
else:
number = str(self.samplenumberlist[i])
#self.AddInformation_tableWidget.setCellWidget(i,0, QLabel(shortname+number)) #
self.AddInformation_tableWidget.setItem(i,0, QTableWidgetItem(shortname+number))
def get_pdsamples(self):
"""
Generate a pandas DataFrame for all samples.
This method collects information from the GUI elements and creates a DataFrame
containing sample-related information. It extracts data such as sample IDs,
custom sample names, additional comments, and boolean values for ElabFTW, Save PNG,
and Print. The DataFrame is then populated with this information.
Returns:
None. The method updates the 'df' attribute with the generated DataFrame.
"""
self.df = pd.DataFrame()
sampleidlist = []
customsamplelist = []
Addcommentslist = []
elablist = []
savelist = []
printlist = []
firstname = self.get_lineedit(self.FirstName_lineEdit, upper = True)
secondname = self.get_lineedit(self.LastName_lineEdit, upper = True)
supervisor = self.get_lineedit(self.Supervisor_lineEdit, upper = True)
year, month, day = self.get_date(self.Current_dateEdit)
expyear, expmonth, expday = self.get_date(self.Expiration_dateEdit)
for i in range(len(self.samplenumberlist)):
# Sample ID
if self.AddInformation_tableWidget.item(i,0):
sampleidlist.append(self.AddInformation_tableWidget.item(i,0).text())
else:
sampleidlist.append("")
# Custom Sample Name
if self.AddInformation_tableWidget.item(i,1):
customsamplelist.append(self.AddInformation_tableWidget.item(i,1).text())
else:
customsamplelist.append("")
# Additional Comments
if self.AddInformation_tableWidget.item(i,2):
Addcommentslist.append(self.AddInformation_tableWidget.item(i,2).text())
else:
Addcommentslist.append("")
# ElabFTW bool
if self.AddInformation_tableWidget.item(i,3).checkState() == Qt.Checked:
elablist.append(True)
else:
elablist.append(False)
# Save PNG bool
if self.AddInformation_tableWidget.item(i,4).checkState() == Qt.Checked:
savelist.append(True)
else:
savelist.append(False)
# Print bool
if self.AddInformation_tableWidget.item(i,5).checkState() == Qt.Checked:
printlist.append(True)
else:
printlist.append(False)
self.df["First name"] = [firstname] * len(self.samplenumberlist)
self.df["Surname"] = [secondname] * len(self.samplenumberlist)
self.df["SampleID"] = sampleidlist
self.df["Supervisor"] = [supervisor] * len(self.samplenumberlist)
self.df["Date"] = [str(year) + "-" + str(month) + "-" + str(day)] * len(self.samplenumberlist)
self.df["Expiration Date"] = [str(expyear) + "-" + str(expmonth) + "-" + str(expday)] * len(self.samplenumberlist)
self.df["Custom Sample Name"] = customsamplelist
self.df["Additional Comments"] = Addcommentslist
self.df["ElabList"] = elablist
self.df["SaveList"] = savelist
self.df["PrintList"] = printlist
self.df["GHS"] = [self.ghsdict] * len(self.samplenumberlist)
self.df["Disposal"] = [self.disposal] * len(self.samplenumberlist)
print(self.df)
def save_folder(self):
"""
Select a folder for saving the QR code images.
This method opens a dialog for selecting a folder and sets the 'savefolder' attribute
to the chosen path. It also logs the changes and updates labels in the GUI accordingly.
Raises:
- If an error occurs during the folder selection, an error message is logged,
and error labels are updated in the GUI.
Note:
- If the folder selection is canceled, the method does not change the 'savefolder' attribute.
- If the selected folder is empty, the default output folder is used.
Returns:
None. The method updates the 'savefolder' attribute based on the user's choice and logs the changes.
"""
try:
folder = QFileDialog.getExistingDirectory(self, 'Select Folder')
self.savefolder = str(folder)
# Log
self.create_log("Changed folderpath: " + str(self.savefolder) + ".")
self.set_label(self.ElabFTWOutput1_label, "Changed folderpath: ")
self.set_label(self.ElabFTWOutput2_label, str(self.savefolder) + ".")
except:
# Log
self.create_log("Did not change the folderpath.")
self.set_label(self.ElabFTWOutput1_label, "Error: ")
self.set_label(self.ElabFTWOutput2_label, "Did not change the folderpath.")
if len(self.savefolder) < 1:
self.savefolder = outputfolder
# Log
self.create_log("Default folderpath. "+ self.savefolder)
self.set_label(self.ElabFTWOutput1_label, "Changed folderpath: ")
self.set_label(self.ElabFTWOutput2_label, str(self.savefolder) + ".")
def qr_create(self):
"""
Generate QR code images with additional labels.
This method performs the following steps:
1. Retrieves sample data using the 'get_pdsamples' method.
2. Iterates through the sample data and creates a QR code for each entry.
3. Adds labels to the QR code, including Shortname, Username, and GHS symbols.
4. Combines all components into a single image and appends it to the 'qrlist' attribute.
Note:
- The Shortname and Username labels are rotated 90 degrees for better layout.
- GHS symbols are added based on the hazard information in the sample data.
Returns:
None. The method generates QR codes and updates the 'qrlist' attribute, and there is no explicit return value.
"""
self.get_pdsamples()
self.qrlist = []
qr = ""
for i in range(len(self.df["SampleID"])):
for j in self.df.columns:
# Exclude some columns.
if j not in ["GHS", "Additional Comments", "Expiration Date", "Disposal", "Custom Sample Name", "ElabList", "SaveList", "PrintList"]:
qr += str(self.df[j].iloc[i]) + ";\n"
qrmake = qrcode.QRCode(
version=None,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=0
)
qrmake.add_data(str(qr))
qrmake.make(fit=True)
img = qrmake.make_image(fill_color="black", back_color="white")
# Create icons and named QR code.
username = str(self.df["First name"].iloc[i]) + " " + str(self.df["Surname"].iloc[i])
try:
font = ImageFont.truetype("FreeMono.ttf", 40)
except:
font = ImageFont.truetype("arial.ttf", 40)
# Create the Shortname label
Shortname_im = Image.new("RGB", (img.size[0],40), color="white")
ShortnameText = ImageDraw.Draw(Shortname_im)
ShortnameText.text((0, 0), str(self.df["SampleID"].iloc[i]), fill="black", font=font)
RotatedShortname = Shortname_im.rotate(90, expand=1)
# Create the Username label
Username_im = Image.new("RGB", (img.size[0],40), color="white")
UsernameText = ImageDraw.Draw(Username_im)
UsernameText.text((0, 0), username, fill="black", font=font)
RotatedUser = Username_im.rotate(90, expand=1)
# Create the GHS symbols
harmful_xoffset = 0
new_xsize = int(np.round(np.divide(img.size[0],4))) # It is assumed that not more than 4 GHS symbols are clicked. Everything else should be unreasonable
new_ysize = int(np.round(np.divide(img.size[1],4))) # It is assumed that not more than 4 GHS symbols are clicked. Everything else should be unreasonable
hazarddict = {"Explosive":":/Images/hazard-explosive-icon.svg",
"Flammable":":/Images/hazard-flammable-icon.svg",
"Oxidizing":":/Images/hazard-oxidising-icon.svg",
"Corrosive":":/Images/hazard-corrosive-icon.svg",
"Toxic":":/Images/hazard-acute-toxicity-icon.svg",
"Harmful":":/Images/hazard-harmful-icon.svg",
"HealthHazard":":/Images/hazard-serious-health-icon.svg",
"EnvironmentalHazard":":/Images/hazard-environmental-icon.svg"
}
Hazard_im = Image.new("RGB", (img.size[0],new_ysize), color="white")
for j in hazarddict:
if (self.df["GHS"].iloc[i][j]):
# Access the image using the resource path
image_path = hazarddict[j]
# Get the image data from the resource
image_data = QResource(image_path).data()
# Convert SVG to PNG using cairosvg
png_data = cairosvg.svg2png(image_data, background_color="white")
# Convert the PNG data to a Pillow Image
pil_image = Image.open(io.BytesIO(png_data)).convert("RGBA")
resized_image = pil_image.resize((new_xsize, new_ysize))
Hazard_im.paste(resized_image,(harmful_xoffset,0))
harmful_xoffset += new_xsize
# Calculate the total width
totalwidth = img.size[0] + RotatedShortname.size[0] + RotatedUser.size[0] + 20
totalheight = img.size[1] + new_ysize + 20
# Finally combine everything to one image.
combined_im = Image.new("RGB", (totalwidth,totalheight), color="white")
x_offset = 10
y_offset = 10
combined_im.paste(RotatedShortname, (x_offset, y_offset))
x_offset += RotatedShortname.size[0]
y_offset += 0
combined_im.paste(img, (x_offset, y_offset))
x_offset += img.size[0]
y_offset += 0
combined_im.paste(RotatedUser, (x_offset, y_offset))
x_offset = 10 + RotatedShortname.size[0]
y_offset += img.size[1] + 10
combined_im.paste(Hazard_im, (x_offset, y_offset))
self.qrlist.append(combined_im)
qr = ""
def save_qrcodes(self):
"""
Save QR codes based on the 'SaveList' in the DataFrame.
This method performs the following steps:
1. Calls the 'qr_create' method to generate QR codes.
2. Iterates through the generated QR codes and saves them based on the 'SaveList' in the DataFrame.
3. Logs the saved QR codes and updates labels in the GUI.
Returns:
None. The method saves QR codes to the specified folder and updates log information.
"""
# Generate QR codes
self.qr_create()
# Iterate through QR codes and save based on 'SaveList'
for i, qr in enumerate(self.qrlist):
if self.df["SaveList"].iloc[i]:
# Construct the save file path
savefile = os.path.join(self.savefolder, str(self.df["SampleID"].iloc[i]) + ".png")
# Save the QR code
qr.save(savefile)
# Log
self.create_log("Saved QR code of "+ str(self.df["SampleID"].iloc[i]) + " at: " + self.savefolder)
self.set_label(self.ElabFTWOutput1_label, "Success: ")
self.set_label(self.ElabFTWOutput2_label, "Saved QR code of "+ str(self.df["SampleID"].iloc[i]) + ".")
def elabftwbody_create(self):
"""
Process sample data and create a list of dictionaries for eLabFTW.
This method performs the following steps:
1. Retrieves sample data using the 'get_pdsamples' method.
2. Initializes an empty list 'elablist' to store dictionaries for eLabFTW.
3. Iterates through the sample data and creates dictionaries for each sample.
4. Each dictionary contains tags, title, body, and metadata fields for eLabFTW.
5. Appends each dictionary to 'elablist'.
Note:
- The sample data is expected to be available in the global variable 'df'.
- The list of sub-sample numbers is expected to be available in the global variable 'subsamplenumberlist'.
- The list of sample numbers is expected to be available in the global variable 'samplenumberlist'.
Returns:
None. The method processes the sample data and populates the 'elablist' variable.
"""
self.get_pdsamples()
self.elablist = []
elabdict = dict()
for i in range(len(self.df["SampleID"])):
# Add tags
tags = []
if self.df["SampleID"].iloc[i] != "":
tags.append(str(self.df["SampleID"].iloc[i]))
if self.df["First name"].iloc[i] != "":
tags.append(str(self.df["First name"].iloc[i]))
if self.df["Surname"].iloc[i] != "":
tags.append(str(self.df["Surname"].iloc[i]))
elabdict["tags"] = tags
# Add the title
elabdict["title"] = str(self.df["SampleID"].iloc[i])
# Add the body
current_datetime = datetime.datetime.now()
if len(self.subsamplenumberlist) != 0:
subnumber = int(self.subsamplenumberlist[i])
else:
subnumber = "None"
# Using a lambda function and filter to get keys where the value is True
ghs = "; ".join(filter(lambda key: self.df["GHS"].iloc[i][key], self.df["GHS"].iloc[i].keys()))
body = f"""
<b>Sample ID: </b> {str(self.df["SampleID"].iloc[i])} <br>
<b>Log Time: </b> {str(current_datetime.strftime("%Y-%m-%d %H:%M:%S"))} <br>
<b>Firstname: </b> {str(self.df["First name"].iloc[i])} <br>
<b>Lastname: </b> {str(self.df["Surname"].iloc[i])} <br>
<b>Supervisor: </b> {str(self.df["Supervisor"].iloc[i])} <br>
<b>Date: </b> {str(self.df["Date"].iloc[i])} <br>
<b>Expiration: </b> {str(self.df["Expiration Date"].iloc[i])} <br>
<b>Samplenumber: </b> {int(self.samplenumberlist[i])} <br>
<b>Sub-Samplenumber: </b> {subnumber} <br>
<b>GHS: </b> {str(ghs)} <br>
<b>Disposal: </b> {str(self.df["Disposal"].iloc[i])} <br>
<b>Custom Sample Name: </b> {str(self.df["Custom Sample Name"].iloc[i])} <br><br>
{str(self.df["Additional Comments"].iloc[i])}
"""
bodystrp = body.strip()
elabdict["body"] = str(bodystrp)
# Add the metadata/extra fields
metadata = {"extra_fields":
{
"Sample_ID" :
{
"type": "text",
"value": str(self.df["SampleID"].iloc[i]),
"description":"SampleID created by CeramScan v1.618"
},
"Date" :
{
"type": "date",
"value": str(self.df["Date"].iloc[i])
},
"Expiration" :
{
"type": "date",
"value": str(self.df["Expiration Date"].iloc[i])
},
"Custom_Sample_Name" :
{
"type": "text",
"value": str(self.df["Custom Sample Name"].iloc[i])
},
"Institution" :
{
"type": "text",
"value": str(configdict["Institution"])
}
}
}
elabdict["metadata"] = metadata
# Save this entry to a list of dictionaries
self.elablist.append(elabdict)
# Empty the temporary dictionary
elabdict = dict()
print(self.elablist)
def sampleid_to_elabftw(self):
"""
Upload sample data to eLabFTW.
This method performs the following steps:
1. Generates QR codes and saves them as PNG images.
2. Creates a dictionary for eLabFTW data based on sample information.
3. Configures the eLabFTW API client using the provided API key and base URL.
4. Initializes the eLabFTW ItemsApi for working with eLabFTW items.
5. Iterates through the sample data, creates new items in eLabFTW, and modifies their properties.
Note:
- The configuration information, such as API key, base URL, and category ID, is expected to be
available in the global variable 'configdict'.
- The sample data is expected to be available in the global variable 'elablist'.
- QR codes are generated using the 'qr_create' method.
- eLabFTW data is created using the 'elabftwbody_create' method.
Returns:
None. The method performs API requests to create and modify items,
and there is no explicit return value.
Inputs:
- self: The instance of the class containing this method.
"""
# QR png-list
self.qr_create()
# elabdict create
self.elabftwbody_create()
# These lines configure the eLabFTW API client using the provided API key and base URL. It also sets additional configurations, such as disabling SSL verification and debugging.
configuration = elabapi_python.Configuration()
configuration.api_key['api_key'] = configdict["API_Key"]
configuration.api_key_prefix['api_key'] = 'Authorization'
configuration.host = configdict["ElabFTW_URL"]
configuration.debug = False
configuration.verify_ssl = False
# This creates an instance of the eLabFTW API client (api_client) with the specified configuration. It also fixes an issue related to the Authorization header not being properly set by the generated library.
api_client = elabapi_python.ApiClient(configuration)
api_client.set_default_header(header_name='Authorization', header_value=configdict["API_Key"])
# This line initializes the ItemsApi class using the configured API client. It provides an interface for working with eLabFTW items.
itemsApi = elabapi_python.ItemsApi(api_client)
# Create an instance for uploads.
uploadsApi = elabapi_python.UploadsApi(api_client)
# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)