-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregister.py
More file actions
805 lines (685 loc) · 27.8 KB
/
Copy pathregister.py
File metadata and controls
805 lines (685 loc) · 27.8 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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2025 University of Dundee & Open Microscopy Environment.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from urllib.parse import urlsplit
import zarr
from zarr.core.buffer import default_buffer_prototype
from zarr.core.sync import sync
import argparse
import locale
import platform
import sys
import tempfile
from numpy import iinfo, finfo
# from getpass import getpass
from omero.cli import cli_login
from omero.gateway import BlitzGateway
import omero
from omero.model.enums import PixelsTypeint8, PixelsTypeuint8, PixelsTypeint16
from omero.model.enums import PixelsTypeuint16, PixelsTypeint32
from omero.model.enums import PixelsTypeuint32, PixelsTypefloat
from omero.model.enums import PixelsTypecomplex, PixelsTypedouble
from omero.model.enums import UnitsLength
from omero.model import ExternalInfoI
from omero.rtypes import rbool, rdouble, rint, rlong, rstring, rtime
from omero.model import ChecksumAlgorithmI
from omero.model import LengthI
from omero.model import NamedValue
from omero.model.enums import ChecksumAlgorithmSHA1160
from omero_version import omero_version
from omero.callbacks import CmdCallbackI
AWS_DEFAULT_ENDPOINT = "s3.us-east-1.amazonaws.com"
PIXELS_TYPE = {'int8': PixelsTypeint8,
'int16': PixelsTypeint16,
'uint8': PixelsTypeuint8,
'uint16': PixelsTypeuint16,
'int32': PixelsTypeint32,
'uint32': PixelsTypeuint32,
'float_': PixelsTypefloat,
'float8': PixelsTypefloat,
'float16': PixelsTypefloat,
'float32': PixelsTypefloat,
'float64': PixelsTypedouble,
'complex_': PixelsTypecomplex,
'complex64': PixelsTypecomplex}
UL = sorted(UnitsLength._enumerators.values())
def get_omexml_bytes(store):
# get() is async. Need to sync to get the bytes
rsp = store.get("OME/METADATA.ome.xml", prototype=default_buffer_prototype())
result = sync(rsp)
if result is None:
return None
return result.to_bytes()
def create_fileset():
"""Create a new Fileset with single OME XML file."""
fileset = omero.model.FilesetI()
entry = omero.model.FilesetEntryI()
# NB: If the clientPath includes .zarr, Bio-Formats tries to import zarr group
entry.setClientPath(rstring("OME/METADATA.ome.xml"))
fileset.addFilesetEntry(entry)
# Fill version info
system, node, release, version, machine, processor = platform.uname()
client_version_info = [
NamedValue('omero.version', omero_version),
NamedValue('os.name', system),
NamedValue('os.version', release),
NamedValue('os.architecture', machine)
]
try:
client_version_info.append(
NamedValue('locale', locale.getlocale()[0]))
except:
pass
upload = omero.model.UploadJobI()
upload.setVersionInfo(client_version_info)
fileset.linkJob(upload)
return fileset
def create_settings():
"""Create ImportSettings and set some values."""
settings = omero.grid.ImportSettings()
# can't create thumbnails on import since ExternalInfo is not set yet
settings.doThumbnails = rbool(False)
settings.noStatsInfo = rbool(False)
settings.userSpecifiedTarget = None
settings.userSpecifiedName = None
settings.userSpecifiedDescription = None
settings.userSpecifiedAnnotationList = None
settings.userSpecifiedPixels = None
settings.checksumAlgorithm = ChecksumAlgorithmI()
s = rstring(ChecksumAlgorithmSHA1160)
settings.checksumAlgorithm.value = s
return settings
def upload_file(proc, omexml_bytes, client):
"""Upload files to OMERO from local filesystem."""
ret_val = []
i = 0
rfs = proc.getUploader(i)
try:
offset = 0
# rfs.write([], offset, 0) # Touch
# Write the OME XML file
rfs.write(omexml_bytes, offset, len(omexml_bytes))
# create temp file for sha1
with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:
fp.write(omexml_bytes)
fp.close()
ret_val.append(client.sha1(fp.name))
finally:
rfs.close()
return ret_val
def assert_import(client, proc, omexml_bytes, wait):
"""Wait and check that we imported an image."""
hashes = upload_file(proc, omexml_bytes, client)
# print ('Hashes:\n %s' % '\n '.join(hashes))
handle = proc.verifyUpload(hashes)
cb = CmdCallbackI(client, handle)
# https://github.com/openmicroscopy/openmicroscopy/blob/v5.4.9/components/blitz/src/ome/formats/importer/ImportLibrary.java#L631
if wait == 0:
cb.close(False)
return None
if wait < 0:
while not cb.block(2000):
sys.stdout.write('.')
sys.stdout.flush()
sys.stdout.write('\n')
else:
cb.loop(wait, 1000)
rsp = cb.getResponse()
if isinstance(rsp, omero.cmd.ERR):
raise Exception(rsp)
assert len(rsp.pixels) > 0
return rsp
def full_import(client, omexml_bytes, wait=-1):
"""Re-usable method for a basic import."""
mrepo = client.getManagedRepository()
fileset = create_fileset()
settings = create_settings()
proc = mrepo.importFileset(fileset, settings)
try:
# do the upload and trigger the import
return assert_import(client, proc, omexml_bytes, wait)
finally:
proc.close()
def format_s3_uri(uri, endpoint):
'''
Combine endpoint and uri
'''
parsed_uri = urlsplit(uri)
url = "{0.netloc}".format(parsed_uri)
if endpoint:
parsed_endpoint = urlsplit(endpoint)
endpoint = "{0.netloc}".format(parsed_endpoint)
else:
endpoint = AWS_DEFAULT_ENDPOINT
return "{0.scheme}".format(parsed_uri) + "://" + endpoint + "/" + url + "{0.path}".format(parsed_uri)
def load_array(store, path=None):
arr = zarr.open(store=store, mode="r", path=path)
return arr
def load_attrs(store, path=None):
"""
Load the attrs from the root group or path subgroup
"""
root = zarr.open(store=store, mode="r", path=path)
attrs = root.attrs.asdict()
if "ome" in attrs:
attrs = attrs["ome"]
return attrs
def parse_image_metadata(store, img_attrs, image_path=None):
"""
Parse the image metadata
"""
multiscale_attrs = img_attrs['multiscales'][0]
array_path = multiscale_attrs["datasets"][0]["path"]
if image_path is not None:
array_path = image_path.rstrip("/") + "/" + array_path
# load .zarray from path to know the dimension
array_data = load_array(store, array_path)
sizes = {}
shape = array_data.shape
axes = multiscale_attrs.get("axes")
# Need to check the older version
if axes:
for axis, size in zip(axes, shape):
if isinstance(axis, str):
sizes[axis] = size # v0.3
else:
sizes[axis["name"]] = size
pixel_size = {}
transforms = multiscale_attrs["datasets"][0]["coordinateTransformations"]
for transform in transforms:
if transform["type"] == "scale":
scale = transform["scale"]
pixel_size = {axis["name"]: (pixel_size, axis.get("unit", "")) for axis, pixel_size
in zip(axes, scale) if axis["name"] in "xyz"}
break
pixels_type = array_data.dtype.name
return sizes, pixel_size, pixels_type
def create_image(conn, store, image_attrs, object_name, families, models, args, image_path=None):
'''
Create an Image/Pixels object
'''
query_service = conn.getQueryService()
pixels_service = conn.getPixelsService()
sizes, pixel_size, pixels_type = parse_image_metadata(store, image_attrs, image_path)
size_t = sizes.get("t", 1)
size_z = sizes.get("z", 1)
size_x = sizes.get("x", 1)
size_y = sizes.get("y", 1)
size_c = sizes.get("c", 1)
# if channels is None or len(channels) != size_c:
channels = list(range(sizes.get("c", 1)))
omero_pixels_type = query_service.findByQuery("from PixelsType as p where p.value='%s'" % PIXELS_TYPE[pixels_type], None)
iid = pixels_service.createImage(size_x, size_y, size_z, size_t, channels, omero_pixels_type, object_name, "", conn.SERVICE_OPTS)
iid = iid.getValue()
rnd_def = None
image = conn.getObject("Image", iid)
# Set rendering settings and channel names if omero_attrs is provided
rnd_def = set_rendering_settings(conn, image, image_attrs, pixels_type, families, models)
set_pixel_size(image, pixel_size)
img_obj = image._obj
set_external_info(img_obj, args, image_path)
return img_obj, rnd_def
def hex_to_rgba(hex_color):
"""
Converts a hex color code to an RGB array.
"""
if len(hex_color) == 3:
hex_color = hex_color[0]*2 + hex_color[1]*2 + hex_color[2]*2
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
return [r, g, b]
def get_channels(omero_info):
'''
Find the name of the channels if specified
'''
channel_names = []
if omero_info is None:
return channel_names
for index, entry in enumerate(omero_info.get('channels', [])):
channel_names.append(entry.get('label', index))
return channel_names
def set_channel_names(conn, iid, omero_attrs):
channel_names = get_channels(omero_attrs)
nameDict = dict((i + 1, name) for i, name in enumerate(channel_names))
conn.setChannelNames("Image", [iid], nameDict)
def set_rendering_settings(conn, image, image_attrs, pixels_type, families=None, models=None):
'''
Extract the rendering settings and the channels information
'''
omero_info = image_attrs.get('omero', None)
if omero_info is None:
return None
set_channel_names(conn, image.id, omero_info)
if families is None:
families = load_families(conn.getQueryService())
if models is None:
models = load_models(conn.getQueryService())
pixels_id = image.getPrimaryPixels().getId()
if omero_info is None:
return
rdefs = omero_info.get('rdefs', None)
if rdefs is None:
rdefs = dict()
rnd_def = omero.model.RenderingDefI()
rnd_def.version = rint(0)
rnd_def.defaultZ = rint(rdefs.get('defaultZ', 0))
rnd_def.defaultT = rint(rdefs.get('defaultT', 0))
value = rdefs.get('model', 'rgb')
if value == 'color':
value = 'rgb'
ref_model = None
for m in models:
mv = m.getValue()._val
if mv == 'rgb':
ref_model = m
if mv == value:
rnd_def.model = m
if rnd_def.model is None:
rnd_def.model = ref_model
q_def = omero.model.QuantumDefI()
q_def.cdStart = rint(0)
q_def.cdEnd = rint(255)
# Flag to select a 8-bit depth (<i>=2^8-1</i>) output interval
q_def.bitResolution = rint(255)
rnd_def.quantization = q_def
rnd_def.pixels = omero.model.PixelsI(pixels_id, False)
if pixels_type.startswith('float'):
pixels_min = finfo(pixels_type).min
pixels_max = finfo(pixels_type).max
else:
pixels_min = iinfo(pixels_type).min
pixels_max = iinfo(pixels_type).max
for entry in omero_info.get('channels', []):
cb = omero.model.ChannelBindingI()
rnd_def.addChannelBinding(cb)
cb.coefficient = rdouble(entry.get('coefficient', 1.0))
cb.active = rbool(entry.get('active', False))
value = entry.get('family', "linear")
ref_family = None
for f in families:
fv = f.getValue()._val
if fv == "linear":
ref_family = f
if fv == value:
cb.family = f
if cb.family is None:
cb.family = ref_family
# convert color to rgba
rgb = hex_to_rgba(entry.get('color', "000000").lstrip("#")) # default to black is no color set
cb.red = rint(rgb[0])
cb.green = rint(rgb[1])
cb.blue = rint(rgb[2])
cb.alpha = rint(255)
cb.noiseReduction = rbool(False)
window = entry.get("window", {})
try:
cb.inputStart = rdouble(float(window.get("start", pixels_min)))
except TypeError:
cb.inputStart = rdouble(pixels_min)
try:
cb.inputEnd = rdouble(float(window.get("end", pixels_max)))
except TypeError:
cb.inputEnd = rdouble(pixels_max)
inverted = entry.get("inverted", False)
if inverted: # add codomain
ric = omero.model.ReverseIntensityContextI()
ric.reverse = rbool(inverted)
cb.addCodomainMapContext(ric)
return rnd_def
def get_unit_length(value):
for unit in UL:
if unit.name.lower() == value:
return unit
return None
def create_length(value_unit):
if len(value_unit) > 1 and value_unit[1]:
try:
unit = get_unit_length(value_unit[1])
if unit is None:
return LengthI(value_unit[0], UnitsLength.PIXEL)
return LengthI(value_unit[0], unit)
except TypeError:
pass
return LengthI(value_unit[0], UnitsLength.PIXEL)
def set_pixel_size(image, pixel_size):
pixels = image.getPrimaryPixels()._obj
if "x" in pixel_size:
pixels.setPhysicalSizeX(create_length(pixel_size["x"]))
if "y" in pixel_size:
pixels.setPhysicalSizeY(create_length(pixel_size["y"]))
if "z" in pixel_size and pixel_size["z"] != (1, ''):
pixels.setPhysicalSizeZ(create_length(pixel_size["z"]))
def load_families(query_service):
ctx = {'omero.group': '-1'}
return query_service.findAllByQuery('select f from Family as f', None, ctx)
def load_models(query_service):
ctx = {'omero.group': '-1'}
return query_service.findAllByQuery('select f from RenderingModel as f', None, ctx)
def register_image(conn, store, args, img_attrs=None, image_path=None):
"""
Register the ome.zarr image in OMERO.
"""
update_service = conn.getUpdateService()
query_service = conn.getQueryService()
families = load_families(query_service)
models = load_models(query_service)
if img_attrs is None:
img_attrs = load_attrs(store, image_path)
if args.name:
image_name = args.name
elif "name" in img_attrs:
image_name = img_attrs["name"]
else:
image_name = args.uri.rstrip("/").split("/")[-1]
if image_path is not None:
image_name = f"{image_name} [{image_path}]"
image, rnd_def = create_image(conn, store, img_attrs, image_name, families, models, args, image_path=image_path)
update_service.saveAndReturnObject(image)
if rnd_def is not None:
update_service.saveAndReturnObject(rnd_def)
print("Created Image", image.id.val)
return image
def determine_naming(values):
'''
Determine the name of columns or rows of a plate
'''
if len(values) > 0:
value = values[0]['name']
if value.isdigit():
return "number"
return "letter"
def create_plate_acquisition(pa):
'''
Create a plate acquisition object
'''
plate_acquisition = omero.model.PlateAcquisitionI()
if pa.get("name"):
plate_acquisition.name = rstring(pa.get("name"))
else:
plate_acquisition.name = rstring(pa.get("id"))
if pa.get("maximumfieldcount"):
plate_acquisition.maximumFieldCount = rint(pa.get("maximumfieldcount"))
if pa.get("starttime"):
plate_acquisition.startTime = rtime(pa.get("starttime"))
if pa.get("endtime"):
plate_acquisition.endTime = rtime(pa.get("endtime"))
return plate_acquisition
# def register_plate(conn, uri, name=None, transport_params=None, endpoint=None, uri_parameters=None):
def register_plate(conn, store, args, attrs):
'''
Register a plate
'''
plate_attrs = attrs["plate"]
object_name = args.name
if object_name is None:
object_name = plate_attrs.get("name", None)
if object_name is None:
object_name = args.uri.rstrip("/").split("/")[-1].split(".")[0]
update_service = conn.getUpdateService()
query_service = conn.getQueryService()
families = load_families(query_service)
models = load_models(query_service)
# Create a plate
plate = omero.model.PlateI()
plate.name = rstring(object_name)
plate.columnNamingConvention = rstring(determine_naming(plate_attrs['columns']))
plate.rowNamingConvention = rstring(determine_naming(plate_attrs['rows']))
plate.rows = rint(len(plate_attrs['rows']))
plate.columns = rint(len(plate_attrs['columns']))
acquisitions = plate_attrs.get('acquisitions')
plate_acquisitions = {}
if acquisitions is not None and len(acquisitions) > 1:
for pa in acquisitions:
plate_acquisition = create_plate_acquisition(pa)
plate.addPlateAcquisition(plate_acquisition)
plate = update_service.saveAndReturnObject(plate)
print("Plate created with id:", plate.id.val)
# load the new plate acquisitions and map them to the original IDs
if acquisitions is not None and len(acquisitions) > 1:
pwrapper = conn.getObject("Plate", plate.id.val)
pas = list(pwrapper.listPlateAcquisitions())
for pa, saved in zip(acquisitions, pas):
plate_acquisitions[pa["id"]] = saved.id
print('plate_acquisitions', plate_acquisitions)
# for bug in omero-cli-zarr - need to handle dupliate Wells!
well_paths = []
well_count = len(plate_attrs["wells"])
for well_index, well_attrs in enumerate(plate_attrs["wells"]):
images_to_save = []
rnd_defs = []
# read metadata
row_index = well_attrs["rowIndex"]
column_index = well_attrs["columnIndex"]
well_path = well_attrs['path']
if well_path in well_paths:
continue
else:
well_paths.append(well_path)
print("well_path", well_path, f"({well_index}/{well_count})")
# create OMERO object
well = omero.model.WellI()
well.plate = omero.model.PlateI(plate.getId(), False)
well.column = rint(column_index)
well.row = rint(row_index)
well_attrs = load_attrs(store, well_path)
well_samples_attrs = well_attrs["well"]["images"]
for sample_attrs in well_samples_attrs:
image_path = f"{well_path}/{sample_attrs['path']}/"
img_attrs = load_attrs(store, image_path)
image_name = img_attrs.get('name', f"{well_path}/{sample_attrs['path']}")
image, rnd_def = create_image(conn, store, img_attrs, image_name, families, models, args, image_path)
images_to_save.append(image)
if rnd_def is not None:
rnd_defs.append(rnd_def)
# Link well sample and plate acquisition
ws = omero.model.WellSampleI()
if 'acquisition' in sample_attrs:
acquisition_id = sample_attrs['acquisition']
pa_id = plate_acquisitions.get(acquisition_id)
if pa is not None:
ws.plateAcquisition = omero.model.PlateAcquisitionI(pa_id, False)
ws.image = omero.model.ImageI(image.id.val, False)
ws.well = well
well.addWellSample(ws)
# Save each Well and Images as we go...
update_service.saveObject(well)
update_service.saveAndReturnArray(images_to_save)
if len(rnd_defs) > 0:
update_service.saveAndReturnIds(rnd_defs)
print("Plate created with id:", plate.id.val)
return plate
def set_external_info(image, args, image_path=None):
'''
Create the external info and link it to the image
'''
extinfo = ExternalInfoI()
# non-nullable properties
setattr(extinfo, "entityId", rlong(3))
setattr(extinfo, "entityType", rstring("com.glencoesoftware.ngff:multiscales"))
uri = args.uri
endpoint = args.endpoint
nosignrequest = args.nosignrequest
if image_path is not None:
uri = uri.rstrip("/") + "/" + image_path
parsed_uri = urlsplit(uri)
scheme = "{0.scheme}".format(parsed_uri)
if "http" in scheme:
endpoint = "https://" + "{0.netloc}".format(parsed_uri)
nosignrequest = True
path = "{0.path}".format(parsed_uri)
if path.startswith("/"):
path = path[1:]
uri = "s3://" + path
if not uri.startswith("/"):
uri = format_s3_uri(uri, endpoint)
if nosignrequest:
if not uri.endswith("/"):
uri = uri + "/"
uri = uri + "?anonymous=true"
setattr(extinfo, "lsid", rstring(uri))
print("lsid:", uri)
image.details.externalInfo = extinfo
def validate_uri(uri):
'''
Check that the protocol is valid and the URI ends with "/"
'''
parsed_uri = urlsplit(uri)
scheme = "{0.scheme}".format(parsed_uri)
if "s3" not in scheme:
raise Exception("Protocol should be s3. Protocol specified is: " + scheme)
# Check if ends with / otherwise add one
path = "{0.path}".format(parsed_uri)
if path.endswith("/"):
return uri
return uri + "/"
def validate_endpoint(endpoint):
'''
Check that the protocol is valid
'''
if endpoint is None or not endpoint:
return
parsed_endpoint = urlsplit(endpoint)
scheme = "{0.scheme}".format(parsed_endpoint)
if "https" not in scheme:
raise Exception("Protocol should be https. Protocol specified is: " + scheme)
def get_uri_parameters(transport_params, nosignrequest):
if transport_params is None:
return None
if nosignrequest:
return "?anonymous=true"
return None
def link_to_target(args, conn, obj):
is_plate = isinstance(obj, omero.model.PlateI)
if args.target:
if is_plate:
screen_id = args.target
if screen_id.startswith("Screen:"):
screen_id = screen_id.split(":")[1]
target = conn.getObject("Screen", attributes={'id': int(screen_id)})
else:
dataset_id = args.target
if dataset_id.startswith("Dataset:"):
dataset_id = dataset_id.split(":")[1]
target = conn.getObject("Dataset", attributes={'id': int(dataset_id)})
else:
if is_plate:
target = conn.getObject("Screen", attributes={'name': args.target_by_name})
else:
target = conn.getObject("Dataset", attributes={'name': args.target_by_name})
if target is None:
print("Target not found")
return
if is_plate:
link = omero.model.ScreenPlateLinkI()
link.parent = omero.model.ScreenI(target.getId(), False)
link.child = omero.model.PlateI(obj.getId(), False)
conn.getUpdateService().saveObject(link)
print("Linked to Screen", target.getId())
else:
link = omero.model.DatasetImageLinkI()
link.parent = omero.model.DatasetI(target.getId(), False)
link.child = omero.model.ImageI(obj.getId(), False)
conn.getUpdateService().saveObject(link)
print("Linked to Dataset", target.getId())
def main():
parser = argparse.ArgumentParser()
parser.add_argument("uri", type=str, help="The URI to the S3 store")
parser.add_argument("--endpoint", required=False, type=str, help="Enter the URL endpoint if applicable")
parser.add_argument("--name", required=False, type=str, help="The name of the image/plate")
parser.add_argument("--nosignrequest", required=False, action='store_true', help="Indicate to sign anonymously")
parser.add_argument("--target", required=False, type=str, help="The id of the target (dataset/screen)")
parser.add_argument("--target-by-name", required=False, type=str, help="The name of the target (dataset/screen)")
parser.add_argument('--wait', type=int, default=-1, help=(
'Wait for this number of seconds for each import to complete. '
'0: return immediately, -1: wait indefinitely (default). '
'Only applies when importing OME/METADATA.ome.xml.'))
args = parser.parse_args()
with cli_login() as cli:
conn = BlitzGateway(client_obj=cli._client)
uri = args.uri
endpoint = args.endpoint
nosignrequest = args.nosignrequest
validate_endpoint(endpoint)
store = None
if uri.startswith("/"):
store = zarr.storage.LocalStore(uri, read_only=True)
else:
storage_options={}
if nosignrequest:
storage_options['anon'] = True
if endpoint:
storage_options['client_kwargs'] = {'endpoint_url': endpoint}
store = zarr.storage.FsspecStore.from_url(uri,
read_only=True,
storage_options=storage_options
)
zattrs = load_attrs(store)
objs = []
if "plate" in zattrs:
print("Registering: Plate")
objs = [register_plate(conn, store, args, zattrs)]
else:
if "bioformats2raw.layout" in zattrs and zattrs["bioformats2raw.layout"] == 3:
print("Registering: bioformats2raw.layout")
zarr_name = args.uri.rstrip("/").split("/")[-1]
if args.name:
zarr_name = args.name
# try to load OME/METADATA.ome.xml
omexml_bytes = get_omexml_bytes(store)
if omexml_bytes is not None:
print("Importing OME/METADATA.ome.xml")
rsp = full_import(conn.c, omexml_bytes, args.wait)
for series, p in enumerate(rsp.pixels):
# set external info. NB: order of pixels MUST match the series 0, 1, 2...
image = conn.getObject("Image", p.image.id.val)
image_path = str(series)
image_attrs = load_attrs(store, image_path)
# pixels_type is only used if we have *incomplete* `omero` metadata
sizes, pixel_size, pixels_type = parse_image_metadata(store, image_attrs, image_path)
rnd_def = set_rendering_settings(conn, image, image_attrs, pixels_type)
if rnd_def is not None:
conn.getUpdateService().saveAndReturnObject(rnd_def)
set_external_info(image._obj, args, image_path=image_path)
# default name is METADATA.ome.xml [series], based on clientPath?
new_name = image.name.replace("METADATA.ome.xml", zarr_name)
print("Imported Image:", image.id, new_name)
image.setName(new_name)
image.save() # save Name and ExternalInfo
objs.append(image)
else:
print("OME/METADATA.ome.xml Not Found")
series = 0
series_exists = True
while series_exists:
try:
print("Checking for series:", series)
obj = register_image(conn, store, args, None, image_path=str(series))
objs.append(obj)
except FileNotFoundError:
series_exists = False
series += 1
else:
print("Registering: Image")
objs = [register_image(conn, store, args, zattrs)]
if args.target or args.target_by_name:
for obj in objs:
link_to_target(args, conn, obj)
if __name__ == "__main__":
main()