-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonScriptWrapper.py
More file actions
181 lines (140 loc) · 6.34 KB
/
PythonScriptWrapper.py
File metadata and controls
181 lines (140 loc) · 6.34 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
import sys
import io
from lxml import etree
import optparse
import logging
import nibabel as nib
import cv2
import numpy as np
# import h5py
from Segmentation import segmentation
logging.basicConfig(filename='PythonScript.log',filemode='a',level=logging.DEBUG)
log = logging.getLogger('bq.modules')
from bqapi.comm import BQCommError
from bqapi.comm import BQSession
class ScriptError(Exception):
def __init__(self, message):
self.message = "Script error: %s" % message
def __str__(self):
return self.message
class PythonScriptWrapper(object):
def run(self):
"""
Run Python script
"""
bq = self.bqSession
# call script
outputs = segmentation( bq, log, **self.options.__dict__ )
# save output back to BisQue
for output in outputs:
self.output_resources.append(output)
def setup(self):
"""
Pre-run initialization
"""
self.bqSession.update_mex('Initializing...')
self.mex_parameter_parser(self.bqSession.mex.xmltree)
self.output_resources = []
def teardown(self):
"""
Post the results to the mex xml
"""
self.bqSession.update_mex( 'Returning results')
outputTag = etree.Element('tag', name ='outputs')
for r_xml in self.output_resources:
if isinstance(r_xml, basestring):
r_xml = etree.fromstring(r_xml)
res_type = r_xml.get('type', None) or r_xml.get('resource_type', None) or r_xml.tag
# append reference to output
if res_type in ['table', 'image']:
outputTag.append(r_xml)
#etree.SubElement(outputTag, 'tag', name='output_table' if res_type=='table' else 'output_image', type=res_type, value=r_xml.get('uri',''))
else:
outputTag.append(r_xml)
#etree.SubElement(outputTag, r_xml.tag, name=r_xml.get('name', '_'), type=r_xml.get('type', 'string'), value=r_xml.get('value', ''))
self.bqSession.finish_mex(tags=[outputTag])
def mex_parameter_parser(self, mex_xml):
"""
Parses input of the xml and add it to options attribute (unless already set)
@param: mex_xml
"""
# inputs are all non-"script_params" under "inputs" and all params under "script_params"
mex_inputs = mex_xml.xpath('tag[@name="inputs"]/tag[@name!="script_params"] | tag[@name="inputs"]/tag[@name="script_params"]/tag')
if mex_inputs:
for tag in mex_inputs:
if tag.tag == 'tag' and tag.get('type', '') != 'system-input': #skip system input values
if not getattr(self.options,tag.get('name', ''), None):
log.debug('Set options with %s as %s'%(tag.get('name',''),tag.get('value','')))
setattr(self.options,tag.get('name',''),tag.get('value',''))
else:
log.debug('No Inputs Found on MEX!')
def validate_input(self):
"""
Check to see if a mex with token or user with password was provided.
@return True is returned if validation credention was provided else
False is returned
"""
if (self.options.mexURL and self.options.token): #run module through engine service
return True
if (self.options.user and self.options.pwd and self.options.root): #run module locally (note: to test module)
return True
log.debug('Insufficient options or arguments to start this module')
return False
def main(self):
parser = optparse.OptionParser()
parser.add_option('--mex_url' , dest="mexURL")
parser.add_option('--module_dir' , dest="modulePath")
parser.add_option('--staging_path' , dest="stagingPath")
parser.add_option('--bisque_token' , dest="token")
parser.add_option('--user' , dest="user")
parser.add_option('--pwd' , dest="pwd")
parser.add_option('--root' , dest="root")
(options, args) = parser.parse_args()
fh = logging.FileHandler('scriptrun.log', mode='a')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s] %(levelname)8s --- %(message)s ' +
'(%(filename)s:%(lineno)s)',datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
log.addHandler(fh)
try: #pull out the mex
if not options.mexURL:
options.mexURL = sys.argv[-2]
if not options.token:
options.token = sys.argv[-1]
except IndexError: #no argv were set
pass
if not options.stagingPath:
options.stagingPath = ''
log.info('\n\nPARAMS : %s \n\n Options: %s' % (args, options))
self.options = options
if self.validate_input():
#initalizes if user and password are provided
if (self.options.user and self.options.pwd and self.options.root):
self.bqSession = BQSession().init_local( self.options.user, self.options.pwd, bisque_root=self.options.root)
self.options.mexURL = self.bqSession.mex.uri
#initalizes if mex and mex token is provided
elif (self.options.mexURL and self.options.token):
self.bqSession = BQSession().init_mex(self.options.mexURL, self.options.token)
else:
raise ScriptError('Insufficient options or arguments to start this module')
try:
self.setup()
except Exception as e:
log.exception("Exception during setup")
self.bqSession.fail_mex(msg = "Exception during setup: %s" % str(e))
return
try:
self.run()
except (Exception, ScriptError) as e:
log.exception("Exception during run")
self.bqSession.fail_mex(msg = "Exception during run: %s" % str(e))
return
try:
self.teardown()
except (Exception, ScriptError) as e:
log.exception("Exception during teardown")
self.bqSession.fail_mex(msg = "Exception during teardown: %s" % str(e))
return
self.bqSession.close()
if __name__=="__main__":
PythonScriptWrapper().main()