forked from CFGrote/ometa
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path05-KeyVal_from_Filename.py
320 lines (271 loc) · 12.2 KB
/
05-KeyVal_from_Filename.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MIF/Key_Val_from_FileName.py
Adds key-value (kv) metadata to images in a dataset in two ways:
1. at the file level kv from parsing the filename
2. common set of kv pairs from the dataset desciption
The information is found by parsing the description text for the data set
-----------------------------------------------------------------------------
Copyright (C) 2018
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.
------------------------------------------------------------------------------
@author Christian Evenhuis
<a href="mailto:[email protected]">[email protected]</a>
@version 5.3
@since 5.3
"""
import sys, os
import re
from omero.gateway import BlitzGateway
import omero
from omero.cmd import Delete2
from omero.rtypes import rlong, rstring, robject
import omero.scripts as scripts
import copy
from collections import OrderedDict
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def GetExistingMapAnnotions( obj ):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ord_dict = OrderedDict()
for ann in obj.listAnnotations():
if( isinstance(ann, omero.gateway.MapAnnotationWrapper) ):
kvs = ann.getValue()
for k,v in kvs:
ord_dict[k] = v
return ord_dict
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def RemoveMapAnnotations(conn, dtype, Id ):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
image = conn.getObject(dtype,int(Id))
namespace = omero.constants.metadata.NSCLIENTMAPANNOTATION
filename = image.getName()
anns = list( image.listAnnotations())
mapann_ids = [ann.id for ann in anns
if isinstance(ann, omero.gateway.MapAnnotationWrapper) ]
try:
delete = Delete2(targetObjects={'MapAnnotation': mapann_ids})
handle = conn.c.sf.submit(delete)
conn.c.waitOnCmd(handle, loops=10, ms=500, failonerror=True,
failontimeout=False, closehandle=False)
except Exception as ex:
print("Failed to delete links: {}".format(ex.message))
return
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def AddMapAnnotations(conn, dtype, Id ):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
'''
* Reads information from the 'Dataset Details' field,
* constructs key-val data
* attaches it to the dataset and the images contained in it
'''
dataset = conn.getObject(dtype,int(Id))
if( not ( dataset.canAnnotate() and dataset.canLink() ) ):
message = "You don't have permission to add annotations to {}".format(dataset.getName())
client.setOutput("Message", rstring(message) )
return
description = dataset.getDescription().splitlines()
modes ={"Summary" : "default" ,
"global key-value" : "global" ,
"filename key-value" : "filename",
"end key-value" : "default" }
mode = 'default'
global_kv = OrderedDict() # stores the global key value pairs
file_keys = OrderedDict() # stores the 'slot' and key for the file keys
template = None
for line in description:
# 1. See if this is a mode string
for key,value in modes.items():
match = re.search( "^#\s+{}".format(key),line.lower())
if( match is not None ):
mode = value
print("match",mode)
continue
if( mode == 'default' ):
pass
if( mode == 'global' ):
# split the line for the kay value pair
match = re.search("^\s*(\S+)\s*:\s*(\S+)",line)
if( match is not None ):
key = match.group(1)
val = match.group(2)
global_kv[key]=val
print("Found global match")
print(key,val)
if( mode == 'filename' ):
match = re.search( "^\s*template\s+(\S+)",line)
if( match is not None ):
template = match.group(1)
print("New template {}".format(template) )
# Start line
# | /----white space
# | |full stop|
# V V V V
match = re.search("^\s*(\d)\.\s+(\S+)",line)
# ^ ^
# position key
if( match is not None ):
i = int(match.group(1))
file_keys[i] = match.group(2)
print("Global k-v's")
for k,v in global_kv.items():
print( k,v)
# convert the template to a regexp
# not white space
# or underscore
# or filesep
if( template is not None ):
print("What is the template?")
template="{}$".format(template)
print(template)
template= template.replace("*","([^\s_\/]+)")
template= template.replace("?","[^\s_\/]")
print(template)
regexp = re.compile(template)
# now add the key value pairs to the dataset
existing_kv = GetExistingMapAnnotions(dataset)
if( existing_kv != global_kv ):
RemoveMapAnnotations( conn, 'dataset', dataset.getId() )
map_ann = omero.gateway.MapAnnotationWrapper(conn)
namespace = omero.constants.metadata.NSCLIENTMAPANNOTATION
map_ann.setNs(namespace)
map_ann.setValue( [ [k,v] for k,v in global_kv.items() ] )
map_ann.save()
dataset.linkAnnotation(map_ann)
# add the metadata to the images
nimg=dataset.countChildren()
nimg_updated=0
nkv_tot=0
for image in dataset.listChildren():
if( not ( image.canAnnotate() and image.canLink() ) ):
message = "You don't have permission to add annotations to {}".format(image.getName())
client.setOutput("Message", rstring(message) )
return
existing_kv = GetExistingMapAnnotions(image)
updated_kv = copy.deepcopy(global_kv)
if( template is not None ):
# apply the template to the file name
name = image.getName()
path = os.path.dirname(image.getImportedImageFilePaths()['client_paths'][0])
filename = path+"/"+name
match = regexp.search(filename)
if( match is not None ):
for i,val in enumerate(match.groups()):
i1 = i+1
if( i1 in file_keys ):
key=file_keys[i1]
updated_kv[key] = val
print("existing_kv")
for k,v in existing_kv.items():
print(" {} : {}".format(k,v))
print("updated_kv")
for k,v in updated_kv.items():
print(" {} : {}".format(k,v))
print("Are they the same?",existing_kv == updated_kv )
if( existing_kv != updated_kv ):
print("The key-values pairs are different")
RemoveMapAnnotations( conn, 'image', image.getId() )
map_ann = omero.gateway.MapAnnotationWrapper(conn)
namespace = omero.constants.metadata.NSCLIENTMAPANNOTATION
map_ann.setNs(namespace)
# convert the ordered dict to a list of lists
map_ann.setValue([ [k,v] for k,v in updated_kv.items() ] )
map_ann.save()
image.linkAnnotation(map_ann)
nimg_updated=nimg_updated+1
nkv_tot = nkv_tot+len(updated_kv)-len(existing_kv)
return "Added a total of {} kv pairs to {}/{} files ".format(nkv_tot,nimg_updated,nimg)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getObjects(conn, scriptParams):
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"""
collect the object list from the script patameters
@param conn: Blitz Gateway connection wrapper
@param scriptParams: A map of the input parameters
"""
# we know scriptParams will have "Data_Type" and "IDs" since these
# parameters are not optional
dataType = scriptParams["Data_Type"]
ids = scriptParams["IDs"]
# dataType is 'Dataset' or 'Image' so we can use it directly in
# getObjects()
obs = conn.getObjects(dataType, ids) # generator of images or datasets
objects = list(obs)
return objects
if __name__ == "__main__":
"""
The main entry point of the script, as called by the client via the
scripting service, passing the required parameters.
"""
dataTypes = [rstring('Dataset')] # only works on datasets
# Here we define the script name and description.
# Good practice to put url here to give users more guidance on how to run
# your script.
client = scripts.client(
'Key_Val_from_FileName.py',
(" Adds key-value metadata pairs to images in a data set from "
" the description for a dataset or collections of datasets"
" k-v pairs taken from the dataset description"
" and by parsing the filename"
" Image IDs or by the Dataset IDs.\nSee"
" http://www.openmicroscopy.org/site/support/omero5.2/developers/"
"scripts/user-guide.html for the tutorial that uses this script."),
scripts.String(
"Data_Type", optional=False, grouping="1",
description="The data you want to work with.", values=dataTypes,
default="Dataset"),
scripts.List(
"IDs", optional=False, grouping="2",
description="List of Dataset IDs or Image IDs").ofType(rlong(0)),
version="5.3",
authors=["Christian Evenhuis", "MIF"],
institutions=["University of Technology Sydney"],
contact="[email protected]"
)
try:
scriptParams = {}
for key in client.getInputKeys():
if client.getInput(key):
# unwrap rtypes to String, Integer etc
scriptParams[key] = client.getInput(key, unwrap=True)
print(scriptParams) # handy to have inputs in the std-out log
# wrap client to use the Blitz Gateway
conn = BlitzGateway(client_obj=client)
## do the editing...
datasets= getObjects(conn, scriptParams)
for ds in datasets:
print(ds.getName())
message = AddMapAnnotations( conn, 'Dataset', ds.getId() )
client.setOutput("Message", rstring(message))
## now handle the result, displaying message and returning image if
## appropriate
#if editedImgIds is None:
# message = "Script failed. See 'error' or 'info' for more details"
#else:
# if len(editedImgIds) == 1:
# # image-wrapper
# img = conn.getObject("Image", editedImgIds[0])
# message = "One Image edited: %s" % img.getName()
# # omero.model object
# omeroImage = img._obj
# # Insight will display 'View' link to image
# client.setOutput("Edited Image", robject(omeroImage))
# elif len(editedImgIds) > 1:
# message = "%s Images edited" % len(editedImgIds)
# else:
# message = ("No images edited. See 'error' or 'info' for more"
# " details")
# # Insight will display the 'Message' parameter
#client.setOutput("Message", rstring(message))
finally:
client.closeSession()