-
Notifications
You must be signed in to change notification settings - Fork 0
/
omeroImporter.py
2226 lines (2076 loc) · 87.1 KB
/
omeroImporter.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
from datetime import datetime
import pathlib
import os
import sys
import time
import json
import shutil
import re
import pandas as pd
import xlrd
# BACKBLAZE
import boto3 # REQUIRED! - Details here: https://pypi.org/project/boto3/
from botocore.exceptions import ClientError
from botocore.config import Config
# from dotenv import load_dotenv # Project Must install Python Package: python-dotenv
# EMAIL
import email
import smtplib
import ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# CRYPTO
from cryptography.fernet import Fernet
# OMERO
import ezomero as ezome
import omero.clients
from omero.gateway import (
ProjectWrapper,
DatasetWrapper,
ImageWrapper,
MapAnnotationWrapper,
TagAnnotationWrapper,
)
from omero.model import (
ProjectI,
DatasetI,
ImageI,
ProjectDatasetLinkI,
)
from omero.gateway import BlitzGateway
dateFormatter = "%d-%m-%Y_%H-%M-%S"
outputPreviousImportedFileName = "OmeroImporter_previousImported.txt"
outputLogFileName = "OmeroImporter_log.txt"
# outputMetadataLogFileName = "OmeroImporter_metadata_log.txt"
outputImportedFileName = "OmeroImporter_imported.txt"
# outputMetadataFileName = "OmeroImporter_metadata.txt"
configFileFolder = "OmeroImporter"
configFileName = "OmeroImporter.cfg"
keyFileName = "OmeroImporter.key"
outputLogFilePath = None
# outputMetadataLogFilePath = None
outputImportedFilePath = None
# outputMetadataFilePath = None
parameters = None
p_omeroHostname = "hostName"
p_omeroPort = "port"
p_omeroUsername = "userName"
p_omeroPSW = "userPassword"
p_target = "target"
p_dest = "destination"
# p_headless = "headless"
p_delete = "hasDelete"
p_mma = "hasMMA"
p_b2 = "hasB2"
p_b2_endpoint = "b2Endpoint"
p_b2_bucketName = "b2BucketName"
p_b2_appKeyId = "b2AppKeyId"
p_b2_appKey = "b2AppKey"
p_userEmail = "userEmail"
p_adminsEmail = "adminsEmail"
p_emailFrom = "senderEmail"
p_emailFromPSW = "sendEmailPSW"
p_startTime = "startTime"
p_endTime = "endTime"
p_key = "key"
import_status = "import"
import_status_imported = "imported"
import_status_pimported = "previously imported"
import_status_found = "found"
import_status_id = "id"
import_path = "path"
import_annotate = "annotated"
metadata_datasets = "datasets"
metadata_images = "images"
metadata_image_name = "Image_Name"
metadata_image_new_name = "New_Image_Name"
metadata_image_path = "Image_Path"
metadata_image_mma = "MMA_File_Path"
metadata_image_tags1 = "Tags"
metadata_image_tags2 = "Τags"
excel_module_ome = "OMERO specific"
excel_project = 0
excel_projectName = "Project_Name"
excel_dataset = 1
excel_datasetName = "Dataset_Name"
excel_imageList = 2
excel_module = "Module"
excel_key = "Key"
excel_value = "Value"
excel_replaceNaN = "EMPTY-PD-VALUE"
class WrappedException(Exception):
def __init__(self, info, e):
self.exception = e
super().__init__(info)
# Return a boto3 client object for B2 service
def get_b2_client(endpoint, keyID, applicationKey):
b2_client = boto3.client(
service_name="s3",
endpoint_url=endpoint,
aws_access_key_id=keyID,
aws_secret_access_key=applicationKey,
)
return b2_client
# Return a boto3 resource object for B2 service
def get_b2_resource(endpoint, keyID, applicationKey):
b2 = boto3.resource(
service_name="s3",
endpoint_url=endpoint,
aws_access_key_id=keyID,
aws_secret_access_key=applicationKey,
config=Config(
signature_version="s3v4",
),
)
return b2
def upload_file(bucketName, filePath, fileName, b2, b2path=None):
# filePath = directory + '/' + file
remotePath = b2path
if remotePath is None:
remotePath = fileName
else:
remotePath = re.sub(r"\\", "/", remotePath)
printToConsole("remotePath " + remotePath)
try:
response = b2.Bucket(bucketName).upload_file(filePath, remotePath)
except ClientError as ce:
raise
return response
def mergeDictionaries(dict1, dict2):
dict = deepCopyDictionary(dict1)
mergedDict = deepMergeDictionaries(dict, dict2)
return mergedDict
def deepCopyDictionary(dict1):
newDict = {}
for key in dict1:
if isinstance(dict1[key], dict):
newDict[key] = deepCopyDictionary(dict1[key])
else:
newDict[key] = dict1[key]
return newDict
def deepMergeDictionaries(dict1, dict2):
newDict = dict1
for key in dict2:
if isinstance(dict2[key], dict):
if key in dict1:
newDict[key] = deepMergeDictionaries(dict1[key], dict2[key])
else:
newDict[key] = deepCopyDictionary(dict2[key])
else:
newDict[key] = dict2[key]
return newDict
def writeConfigFile(path, dict):
configFilePath = os.path.join(path, configFileName)
keyFilePath = os.path.join(path, keyFileName)
try:
with open(keyFilePath, "w") as f:
try:
f.write(str(dict[p_key]))
f.close()
except (FileNotFoundError, PermissionError, OSError) as e:
printToConsole("Writing key file failed for " + keyFilePath)
printToConsole(repr(e))
except (IOError, OSError) as e:
printToConsole("Writing key file failed for " + keyFilePath)
printToConsole(repr(e))
try:
with open(configFilePath, "w") as f:
try:
for key in dict:
if key == p_key:
continue
value = dict[key]
f.write(str(key) + " = " + str(value))
f.write("\n")
f.close()
except (FileNotFoundError, PermissionError, OSError) as e:
printToConsole("Writing config file failed for " + configFilePath)
printToConsole(repr(e))
except (IOError, OSError) as e:
printToConsole("Writing config file failed for " + configFilePath)
printToConsole(repr(e))
def readConfigFile(path):
configFile = os.path.join(path, configFileName)
configFilePath = pathlib.Path(configFile).resolve()
keyFile = os.path.join(path, keyFileName)
keyFilePath = pathlib.Path(keyFile).resolve()
key = None
params = {}
if not configFilePath.exists() or not keyFilePath.exists():
return params
try:
with open(keyFilePath, "r") as f:
try:
key = f.readline().strip()
f.close()
params[p_key] = key
except (FileNotFoundError, PermissionError, OSError) as e:
message = "Opening key file failed for " + keyFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
except (IOError, OSError) as e:
message = "Reading key file failed for " + keyFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
try:
with open(configFilePath, "r") as f:
try:
while True:
line = f.readline()
if not line:
break
data = line.strip()
if data.startswith("//") or data.startswith("#"):
continue
else:
tokens = data.split(" = ")
val = tokens[1]
params[tokens[0]] = val
f.close()
return params
except (FileNotFoundError, PermissionError, OSError) as e:
message = "Opening config file failed for " + configFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
except (IOError, OSError) as e:
message = "Reading config file failed for " + configFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
def writeCurrentImported(dict):
try:
with open(outputImportedFilePath, "w") as f:
try:
json.dump(dict, f)
except (FileNotFoundError, PermissionError, OSError) as e:
message = (
"Writing current imported file failed for " + outputImportedFilePath
)
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
except (IOError, OSError) as e:
message = "Writing current imported file failed for " + outputImportedFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
def writePreviousImported(path, dict):
importedFilePath = os.path.join(path, outputPreviousImportedFileName)
try:
with open(importedFilePath, "w") as f:
try:
json.dump(dict, f)
except (FileNotFoundError, PermissionError, OSError) as e:
message = (
"Writing previous imported file failed for " + importedFilePath
)
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
except (IOError, OSError) as e:
message = "Writing previous imported file failed for " + importedFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
def readPreviousImportedFile(path):
importedFilePath = os.path.join(path, outputPreviousImportedFileName)
if not pathlib.Path(importedFilePath).resolve().exists():
return None
try:
with open(importedFilePath, "r") as f:
try:
data = json.load(f)
return data
except (FileNotFoundError, PermissionError, OSError) as e:
message = "Reading previous imported failed for " + importedFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
except (IOError, OSError) as e:
message = "Opening previous imported failed for " + importedFilePath
writeToLog("ERROR: " + message)
writeToLog(repr(e))
printToConsole(message)
printToConsole(repr(e))
def initFiles(path):
now = datetime.now()
nowFormat = now.strftime(dateFormatter)
global outputLogFilePath
outputLogFilePath = os.path.join(path, nowFormat + "_" + outputLogFileName)
try:
open(outputLogFilePath, "x")
except (IOError, OSError) as e:
printToConsole("Creating log file failed for " + outputLogFilePath)
printToConsole(repr(e))
# global outputMetadataLogFilePath
# outputMetadataLogFilePath = os.path.join(
# path, nowFormat + "_" + outputMetadataLogFileName
# )
# try:
# open(outputMetadataLogFilePath, "x")
# except (IOError, OSError) as e:
# writeToLog("Creating log file failed for " + outputMetadataLogFilePath + "\n")
# writeToLog(repr(e) + "\n")
global outputImportedFilePath
outputImportedFilePath = os.path.join(
path, nowFormat + "_" + outputImportedFileName
)
try:
open(outputImportedFilePath, "x")
except (IOError, OSError) as e:
printToConsole("Creating log file failed for " + outputImportedFilePath)
printToConsole(repr(e))
# global outputMetadataFilePath
# outputMetadataFilePath = os.path.join(
# path, nowFormat + "_" + outputMetadataFileName
# )
# try:
# open(outputMetadataFilePath, "x")
# except (IOError, OSError) as e:
# writeToLog("Creating log file failed for " + outputMetadataFilePath + "\n")
# writeToLog(repr(e) + "\n")
def printToConsole(s):
now = datetime.now()
nowFormat = now.strftime(dateFormatter)
print(nowFormat + " - " + s + "\n")
def writeToLog(s):
now = datetime.now()
nowFormat = now.strftime(dateFormatter)
try:
with open(outputLogFilePath, "a") as f:
try:
f.write(nowFormat + " : " + s)
f.write("\n")
f.close()
except (FileNotFoundError, PermissionError, OSError) as e:
printToConsole("Writing to log file failed for " + outputLogFilePath)
printToConsole(repr(e))
except (IOError, OSError) as e:
printToConsole("Opening log file failed for " + outputLogFilePath)
printToConsole(repr(e))
# def writeToMetadataLogFile(s):
# now = datetime.now()
# nowFormat = now.strftime(dateFormatter)
# try:
# with open(outputMetadataLogFilePath, "a") as f:
# try:
# f.write(nowFormat + " : " + s)
# f.write("\n")
# f.close()
# except (FileNotFoundError, PermissionError, OSError) as e:
# printToConsole(
# "Writing to log file failed for " + outputMetadataLogFilePath
# )
# printToConsole(repr(e))
# except (IOError, OSError) as e:
# printToConsole("Opening log file failed for " + outputMetadataLogFilePath)
# printToConsole(repr(e))
# def writeToPreviousMetadataFile(imported):
# now = datetime.now()
# nowFormat = now.strftime(dateFormatter)
# try:
# with open(outputMetadataFilePath, "a") as f:
# try:
# f.write("Files Metadata was written for:\n")
# for s in imported:
# f.write(s)
# f.write("\n")
# f.close()
# except (FileNotFoundError, PermissionError, OSError) as e:
# printToConsole(
# "Writing to log file failed for " + outputMetadataFilePath
# )
# printToConsole(repr(e))
# except (IOError, OSError) as e:
# printToConsole("Opening log file failed for " + outputMetadataFilePath)
# printToConsole(repr(e))
def sendErrorEmail(emailTo, adminsEmailTo, error, emailFrom, emailFromPSW):
subject = "Omero Import error report"
text = "Omero Importer job has been terminated due to the following error:\n"
text += error + "\n\n"
if emailTo != None and emailFrom != None and emailFromPSW != None:
sendEmail(emailTo, subject, text, emailFrom, emailFromPSW)
if adminsEmailTo != None and emailFrom != None and emailFromPSW != None:
# printToConsole("emailFrom " + str(emailFrom))
# printToConsole("emailFromPSW " + str(emailFromPSW))
# printToConsole("emailTo " + str(emailTo))
sendAdminEmail(adminsEmailTo, subject, text, emailFrom, emailFromPSW)
def sendCompleteEmail(
emailTo, adminsEmailTo, hasNewImport, results, emailFrom, emailFromPSW
):
subject = "Omero Importer job completion report"
text = "Omero Importer job successfully complete.\n"
if hasNewImport:
text += "The following structure has been created:\n"
for projectKey in results:
projectData = results[projectKey]
text += "Project: " + projectKey + " " + projectData[import_status]
if import_annotate in projectData:
if projectData[import_status] == import_status_pimported:
text += " , metadata updated\n"
else:
text += " , metadata written\n"
else:
text += "\n"
for datasetKey in projectData:
datasetData = projectData[datasetKey]
if not isinstance(datasetData, dict):
continue
text += "Dataset: " + datasetKey + " " + datasetData[import_status]
if import_annotate in datasetData:
if datasetData[import_status] == import_status_pimported:
text += " , metadata updated\n"
else:
text += " , metadata written\n"
else:
text += "\n"
for imageKey in datasetData:
imageData = datasetData[imageKey]
if not isinstance(imageData, dict):
continue
text += "Image: " + imageKey + " " + imageData[import_status]
if import_annotate in imageData:
if imageData[import_status] == import_status_pimported:
text += " , metadata updated\n"
else:
text += " , metadata written\n"
else:
text += "\n"
else:
text += "No new structure was created.\n"
text += "\n"
if hasNewImport:
sendEmail(emailTo, subject, text, emailFrom, emailFromPSW)
sendAdminEmail(adminsEmailTo, subject, text, emailFrom, emailFromPSW)
def sendEmail(emailTo, subject, text, emailFrom, emailFromPSW):
body = text
body += "\nThis is an automatic message from an unsupervised email address, please do not reply to this mail.\n"
body += "If you need assistance contact [email protected]"
message = MIMEMultipart("alternative")
message["Subject"] = subject
message["From"] = emailFrom
if isinstance(emailTo, str):
message["To"] = emailTo
else:
message["To"] = ", ".join(emailTo)
message.attach(MIMEText(body, "plain"))
email = message.as_string()
# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(emailFrom, emailFromPSW)
server.sendmail(emailFrom, emailTo, email)
def sendAdminEmail(emailTo, subject, text, emailFrom, emailFromPSW):
body = text
body += "\nThis is an automatic message from an unsupervised email address, please do not reply to this mail.\n"
body += "If you need assistance contact [email protected]"
message = MIMEMultipart("alternative")
message["Subject"] = subject
message["From"] = emailFrom
if isinstance(emailTo, str):
message["To"] = emailTo
else:
message["To"] = ", ".join(emailTo)
message.attach(MIMEText(body, "plain"))
f1 = outputLogFilePath
f1Path = pathlib.Path(f1)
# Open file in binary mode
with open(f1Path, "rb") as attachment:
# Add file as application/octet-stream
# Email client can usually download this automatically as attachment
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode file in ASCII characters to send by email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
"Content-Disposition",
f"attachment; filename= {f1Path.name}",
)
# Add attachment to message and convert message to string
message.attach(part)
# f2 = outputMetadataLogFilePath
# # Open file in binary mode
# with open(f2, "rb") as attachment:
# # Add file as application/octet-stream
# # Email client can usually download this automatically as attachment
# part = MIMEBase("application", "octet-stream")
# part.set_payload(attachment.read())
# # Encode file in ASCII characters to send by email
# encoders.encode_base64(part)
# # Add header as key/value pair to attachment part
# part.add_header(
# "Content-Disposition",
# f"attachment; filename= {f2}",
# )
# # Add attachment to message and convert message to string
# message.attach(part)
f3 = outputImportedFilePath
f3Path = pathlib.Path(f3)
# Open file in binary mode
with open(f3Path, "rb") as attachment:
# Add file as application/octet-stream
# Email client can usually download this automatically as attachment
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode file in ASCII characters to send by email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
"Content-Disposition",
f"attachment; filename= {f3Path.name}",
)
# Add attachment to message and convert message to string
message.attach(part)
# f4 = outputMetadataFilePath
# # Open file in binary mode
# with open(f4, "rb") as attachment:
# # Add file as application/octet-stream
# # Email client can usually download this automatically as attachment
# part = MIMEBase("application", "octet-stream")
# part.set_payload(attachment.read())
# # Encode file in ASCII characters to send by email
# encoders.encode_base64(part)
# # Add header as key/value pair to attachment part
# part.add_header(
# "Content-Disposition",
# f"attachment; filename= {f4}",
# )
# # Add attachment to message and convert message to string
# message.attach(part)
email = message.as_string()
# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(emailFrom, emailFromPSW)
server.sendmail(emailFrom, emailTo, email)
def readCSVFile(path):
try:
with open(path) as f:
try:
dataArray = []
dataDict = {}
isImageListFile = False
keys = None
imageIndex = 0
while True:
line = f.readline()
if not line:
break
data = line.strip()
if "- PROJECT" in data or "- DATASET" in data:
continue
if "- IMAGE" in data:
isImageListFile = True
continue
if "Key,Value" in data:
continue
if "Image_Name" in data:
keys = data.split(",")
continue
if not isImageListFile:
dataSplit = data.split(",")
key = dataSplit[0]
value = dataSplit[1]
dataDict[key] = value
else:
dataSplit = data.split(",")
i = 0
dataArray.append({})
for key in keys:
value = dataSplit[i]
i = i + 1
if (
key == metadata_image_tags1
or key == metadata_image_tags2
):
if value == "":
tags = []
else:
tags = value.split("#")
dataArray[imageIndex][key] = tags
else:
dataArray[imageIndex][key] = value
imageIndex = imageIndex + 1
f.close()
if isImageListFile:
return dataArray
return dataDict
except Exception as e:
raise WrappedException("Read file failed for " + repr(path), e)
except Exception as e:
raise WrappedException("Open file failed for " + repr(path), e)
def collectMetadataFromCSV(path):
data = {}
projects = {}
datasets = {}
images = {}
targetPath = pathlib.Path(path).resolve()
for path in targetPath.iterdir():
if path.is_dir():
continue
name = path.name
if ".csv" not in name:
continue
nameParts = name.split("#")
parts = len(nameParts)
if parts == 1:
# project
projectName = name.replace(".csv", "")
try:
projectData = readCSVFile(path)
except Exception as e:
raise
projects[projectName] = projectData
elif parts == 2:
# dataset
projectName = nameParts[0]
datasetName = nameParts[1].replace(".csv", "")
try:
datasetData = readCSVFile(path)
except Exception as e:
raise
if projectName not in datasets:
datasets[projectName] = {}
datasets[projectName][datasetName] = datasetData
elif parts == 3:
# image list
projectName = nameParts[0]
datasetName = nameParts[1]
try:
imageData = readCSVFile(path)
except Exception as e:
raise
if projectName not in images:
images[projectName] = {}
# images[projectName][datasetName] = []
images[projectName][datasetName] = imageData
for projectKey in projects:
data[projectKey] = projects[projectKey]
for projectKey in datasets:
if metadata_datasets not in data[projectKey]:
data[projectKey][metadata_datasets] = {}
for datasetKey in datasets[projectKey]:
data[projectKey][metadata_datasets][datasetKey] = datasets[projectKey][
datasetKey
]
for projectKey in images:
for datasetKey in images[projectKey]:
if metadata_images not in data[projectKey][metadata_datasets][datasetKey]:
data[projectKey][metadata_datasets][datasetKey][metadata_images] = {}
data[projectKey][metadata_datasets][datasetKey][metadata_images] = images[
projectKey
][datasetKey]
printToConsole("Data:")
printToConsole(str(data))
return data
def parseImageListSpreadsheetData(ssData):
data = []
keys = ssData.columns
size = len(ssData[keys[0]])
for i in range(0, size):
objectData = {}
for key in keys:
if key == excel_replaceNaN:
continue
value = ssData[key][i]
if key == metadata_image_tags1 or key == metadata_image_tags2:
if value == excel_replaceNaN:
value = []
else:
values = value.split(",")
value = values
if value == excel_replaceNaN:
continue
if isinstance(value, str):
value = value.strip()
objectData[key] = value
if objectData != None and objectData != {}:
data.append(objectData)
# data[i] = objectData
return data
def parseSpreadsheetData(ssData, objectNameKey):
data = {}
objectData = {}
module = None
objectName = None
modules = ssData[excel_module].values
keys = ssData[excel_key].values
values = ssData[excel_value].values
for i in range(0, len(keys)):
if modules[i] != excel_replaceNaN:
module = modules[i]
if not module in objectData:
objectData[module] = {}
key = keys[i]
if key == excel_replaceNaN:
continue
value = values[i]
if value == excel_replaceNaN:
continue
# value = "NA"
if isinstance(value, str):
value = value.strip()
if key == objectNameKey:
objectName = value
objectData[module][key] = value
cleanObjectData = {k: v for k, v in objectData.items() if v != None and v != {}}
data[objectName] = cleanObjectData
return data
def collectMetadataFromExcel(path):
data = {}
targetPath = pathlib.Path(path).resolve()
for path in targetPath.iterdir():
if path.is_dir():
continue
name = path.name
if ".xlsx" in name or ".xlsm" in name:
ssFileProjectData = pd.read_excel(
path, sheet_name=excel_project, header=8
).fillna(excel_replaceNaN)
ssProjectData = parseSpreadsheetData(ssFileProjectData, excel_projectName)
projectName = list(ssProjectData.keys())[0]
if projectName not in data:
# TODO IF PROJECT NAME CHANGED IN SAME PROJECT DIRECTORY IF OVERRIDE OVERRIDE IF NOT SEND ERROR EMAIL
data.update(ssProjectData)
if metadata_datasets not in data[projectName]:
data[projectName][metadata_datasets] = {}
ssFileDatasetData = pd.read_excel(
path, sheet_name=excel_dataset, header=8
).fillna(excel_replaceNaN)
ssDatasetData = parseSpreadsheetData(ssFileDatasetData, excel_datasetName)
datasetName = list(ssDatasetData.keys())[0]
if datasetName not in data[projectName][metadata_datasets]:
data[projectName][metadata_datasets].update(ssDatasetData)
if metadata_images not in data[projectName][metadata_datasets][datasetName]:
data[projectName][metadata_datasets][datasetName][metadata_images] = {}
ssFileImageListData = pd.read_excel(
path, sheet_name=excel_imageList, header=12
).fillna(excel_replaceNaN)
ssImageListData = parseImageListSpreadsheetData(ssFileImageListData)
data[projectName][metadata_datasets][datasetName][
metadata_images
] = ssImageListData
printToConsole("Data:")
printToConsole(str(data))
return data
def main(argv, argc):
if len(argv) > 1 and argv[1] == "-h":
print("Help for Omero Importer CL")
print("-cfg <options>, to create a global config file")
print("options (* required):")
print("*-H <hostname>")
print("-p <port>, default is 4064")
print("*-u <admin userName>")
print("*-psw <admin password>")
print("*-t <target>, target directory to launch the importer")
print(
"-d <destination>, destination directory where to move files after import (in this case if not specified copy does not happen)"
)
print("-del, to delete files after import and copy, default is false")
print("-mma, to add microscope and acquisition settings file, default is false")
print(
"-b2 <endpoint#bucketName#appKeyId#appKey>, to use backblaze as destination for copy (conflict with -d)"
)
print(
"-ts <hh:mm>, to specify the daily start time of the application, default is non-stop"
)
print(
"-te <hh:mm>, to specify the time limit after which the application should auto terminate, default is non-stop"
)
print("*-sml <email address> to set up automatic email sender")
print("*-smlp <password> to set up automatic email sender password")
print(
"*-aml <email address1#email address2:...> to set up automatic email to admin upon error or completion"
)
print("#####")
print(
"-ucfg <userDirectory> <options> to create a user config file in a specific directory, conflicting user options override global options"
)
print("options (* required):")
print("*-u <user userName>")
print("*-psw <user password>")
print(
"-d <destination>, destination directory where to move files after import (in this case if not specified copy does not happen)"
)
print("-del, to delete files after import and copy")
print(
"-b2 <endpoint#bucketName#appKeyId#appKey>, to use backblaze as destination for copy (conflict with -d)"
)
print("-mma, to add microscope and acquisition settings file")
print(
"*-ml <email address1:email address2:...> to set up automatic email upon error or completion"
)
quit()
localPath = None
try:
localPath = pathlib.Path(__file__).parent.resolve(strict=True)
except FileNotFoundError:
localPath = pathlib.Path().resolve()
initFiles(localPath)
printToConsole("LOG FILE INIT")
isCfg = False
isUCfg = False
# Both param
destination_g = None
hasDelete_g = False
hasMMA_g = False
hasB2_g = False
b2Endpoint_g = None
b2BucketName_g = None
b2AppKeyId_g = None
b2AppKey_g = None
# Global param
hostName = None
port = 4064
target = None
startTimeHr = None
startTimeMin = None
endTimeHr = None
endTimeMin = None
adminsEmailTo = None
emailFrom = None
emailFromPSW = None
# User param
userDirectoryPath = None
userName_g = None
userPSW_g = None
emailTo = None
isAdmin = False
for i in range(1, argc):
arg = argv[i]
if arg == "-cfg":
isCfg = True
elif arg == "-ucfg":
isUCfg = True
userDirectory = argv[i + 1]
if userDirectory == None:
error = "user directory cannot be undefined with the -ucfg option, application terminated."
writeToLog("ERROR: " + error)
printToConsole("ERROR: " + error)
quit()
try:
userDirectoryPath = pathlib.Path(userDirectory).resolve()
if not userDirectoryPath.exists():
# if not os.path.exists(tmpTarget):
error = (
"User directory "
+ userDirectory
+ " doesn't exists, application terminated."
)
writeToLog("ERROR: " + error)
printToConsole("ERROR: " + error)
quit()
if not userDirectoryPath.is_dir():
# if not os.path.isdir(tmpTarget):
error = (
"User directory "
+ userDirectory
+ " is not a directory, application terminated."
)
writeToLog("ERROR: " + error)
printToConsole("ERROR: " + error)
quit()
# target = tmpTarget
except IOError as e:
error = (
"Something went wrong trying to determine if user directory "
+ userDirectory
+ " exists and is a directory, application terminated."
)
writeToLog("ERROR: " + error)
printToConsole("ERROR: " + error)
quit()
elif arg == "-H":
hostName = argv[i + 1]
elif arg == "-p":
port = argv[i + 1]
elif arg == "-u":
userName_g = argv[i + 1]
elif arg == "-psw":
userPSW_g = argv[i + 1]
elif arg == "-t":