-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPythonScriptWrapper.py
224 lines (168 loc) · 7.31 KB
/
PythonScriptWrapper.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
import sys
import io
from lxml import etree
import optparse
import logging
import os
# It is importing from source
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
from bqapi.util import fetch_blob
# ROOT_DIR = './'
# sys.path.append(os.path.join(ROOT_DIR, "source/"))
from GobjectAdd import gobject_core
class ScriptError(Exception):
def __init__(self, message):
self.message = "Script error: %s" % message
def __str__(self):
return self.message
class PythonScriptWrapper(object):
def preprocess(self, bq):
log.info('Options: %s' % (self.options))
"""
1. Get the resource image
"""
self.seg = bq.load(self.options.annotationURL)
self.seg_name=self.seg.__dict__['name']
log.info("process image as %s" % (self.seg_name))
log.info("image meta: %s" % (self.seg))
cwd= os.getcwd()
result = fetch_blob(bq, self.options.annotationURL, dest=os.path.join(cwd,self.seg_name))
if '.gz' in self.seg_name:
os.rename(self.seg_name,self.seg_name.replace('.gz',''))
self.seg_name=self.seg_name.replace('.gz','')
def run(self):
"""
Run Python script
"""
bq = self.bqSession
try:
## bq.update_mex('Pre-process the images')
self.preprocess(bq)
except (Exception, ScriptError) as e:
log.exception("Exception during preprocess")
bq.fail_mex(msg = "Exception during pre-process: %s" % str(e))
print('fail to preprocess')
return
#call script
meta = bq.fetchxml('%s?meta'%self.options.imageURL)
xml_new=gobject_core(self.seg_name, meta)
bq.postxml(self.options.imageURL, xml_new, method='POST')
## print('posted')
bq.update_mex( 'Returning results')
def setup(self):
"""
Pre-run initialization
"""
self.bqSession.update_mex('Initializing...')
self.mex_parameter_parser(self.bqSession.mex.xmltree)
self.output_string = "added"
def teardown(self):
## """
## Post the results to the mex xml
## """
self.bqSession.update_mex('Returning results')
outputTag = etree.Element('tag', name ='outputs')
outputTag.append(etree.fromstring('<root>'+ self.output_string))
def mex_parameter_parser(self, mex_xml):
"""
Parses input of the xml and add it to options attribute (unless already set)
@param: mex_xml
"""
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")
parser.add_option('--image_volume' , dest="imageURL")
parser.add_option('--annotation_volume', dest="annotationURL")
(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.debug('\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):
try:
self.bqSession = BQSession().init_local( self.options.user, self.options.pwd, bisque_root=self.options.root)
self.options.mexURL = self.bqSession.mex.uri
except:
## print('fail to initialize mex')
return
#initalizes if mex and mex token is provided
elif (self.options.mexURL and self.options.token):
try:
## print('get session')
self.bqSession = BQSession().init_mex(self.options.mexURL, self.options.token)
except:
return
else:
raise ScriptError('Insufficient options or arguments to start this module')
try:
## print('set up')
self.setup()
except Exception as e:
log.exception("Exception during setup")
## self.bqSession.fail_mex(msg = "Exception during setup: %s" % str(e))
return
####
try:
## print('run')
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:
## print('teardown')
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()
log.debug('Session Close')
if __name__=="__main__":
PythonScriptWrapper().main()