0
|
1 # rgToolFactoryMultIn.py
|
|
2 # see https://bitbucket.org/fubar/galaxytoolfactory/wiki/Home
|
|
3 #
|
|
4 # copyright ross lazarus (ross stop lazarus at gmail stop com) May 2012
|
|
5 #
|
|
6 # all rights reserved
|
|
7 # Licensed under the LGPL
|
|
8 # suggestions for improvement and bug fixes welcome at https://bitbucket.org/fubar/galaxytoolfactory/wiki/Home
|
|
9 #
|
|
10 # sept 2014 added additional params from
|
|
11 # https://bitbucket.org/mvdbeek/dockertoolfactory/src/d4863bcf7b521532c7e8c61b6333840ba5393f73/DockerToolFactory.py?at=default
|
|
12 # passing them is complex
|
|
13 # and they are restricted to NOT contain commas or double quotes to ensure that they can be safely passed together on
|
|
14 # the toolfactory command line as a comma delimited double quoted string for parsing and passing to the script
|
|
15 # see examples on this tool form
|
|
16
|
|
17 # august 2014
|
|
18
|
|
19 # Allows arbitrary number of input files
|
|
20 # NOTE positional parameters are now passed to script
|
|
21 # and output (may be "None") is *before* arbitrary number of inputs
|
|
22 #
|
|
23 # march 2014
|
|
24 # had to remove dependencies because cross toolshed dependencies are not possible - can't pre-specify a toolshed url for graphicsmagick and ghostscript
|
|
25 # grrrrr - night before a demo
|
|
26 # added dependencies to a tool_dependencies.xml if html page generated so generated tool is properly portable
|
|
27 #
|
|
28 # added ghostscript and graphicsmagick as dependencies
|
|
29 # fixed a wierd problem where gs was trying to use the new_files_path from universe (database/tmp) as ./database/tmp
|
|
30 # errors ensued
|
|
31 #
|
|
32 # august 2013
|
|
33 # found a problem with GS if $TMP or $TEMP missing - now inject /tmp and warn
|
|
34 #
|
|
35 # july 2013
|
|
36 # added ability to combine images and individual log files into html output
|
|
37 # just make sure there's a log file foo.log and it will be output
|
|
38 # together with all images named like "foo_*.pdf
|
|
39 # otherwise old format for html
|
|
40 #
|
|
41 # January 2013
|
|
42 # problem pointed out by Carlos Borroto
|
|
43 # added escaping for <>$ - thought I did that ages ago...
|
|
44 #
|
|
45 # August 11 2012
|
|
46 # changed to use shell=False and cl as a sequence
|
|
47
|
|
48 # This is a Galaxy tool factory for simple scripts in python, R or whatever ails ye.
|
|
49 # It also serves as the wrapper for the new tool.
|
|
50 #
|
|
51 # you paste and run your script
|
|
52 # Only works for simple scripts that read one input from the history.
|
|
53 # Optionally can write one new history dataset,
|
|
54 # and optionally collect any number of outputs into links on an autogenerated HTML page.
|
|
55
|
|
56 # DO NOT install on a public or important site - please.
|
|
57
|
|
58 # installed generated tools are fine if the script is safe.
|
|
59 # They just run normally and their user cannot do anything unusually insecure
|
|
60 # but please, practice safe toolshed.
|
|
61 # Read the fucking code before you install any tool
|
|
62 # especially this one
|
|
63
|
|
64 # After you get the script working on some test data, you can
|
|
65 # optionally generate a toolshed compatible gzip file
|
|
66 # containing your script safely wrapped as an ordinary Galaxy script in your local toolshed for
|
|
67 # safe and largely automated installation in a production Galaxy.
|
|
68
|
|
69 # If you opt for an HTML output, you get all the script outputs arranged
|
|
70 # as a single Html history item - all output files are linked, thumbnails for all the pdfs.
|
|
71 # Ugly but really inexpensive.
|
|
72 #
|
|
73 # Patches appreciated please.
|
|
74 #
|
|
75 #
|
|
76 # long route to June 2012 product
|
|
77 # Behold the awesome power of Galaxy and the toolshed with the tool factory to bind them
|
|
78 # derived from an integrated script model
|
|
79 # called rgBaseScriptWrapper.py
|
|
80 # Note to the unwary:
|
|
81 # This tool allows arbitrary scripting on your Galaxy as the Galaxy user
|
|
82 # There is nothing stopping a malicious user doing whatever they choose
|
|
83 # Extremely dangerous!!
|
|
84 # Totally insecure. So, trusted users only
|
|
85 #
|
|
86 # preferred model is a developer using their throw away workstation instance - ie a private site.
|
|
87 # no real risk. The universe_wsgi.ini admin_users string is checked - only admin users are permitted to run this tool.
|
|
88 #
|
|
89
|
|
90 import sys
|
|
91 import shutil
|
|
92 import subprocess
|
|
93 import os
|
|
94 import time
|
|
95 import tempfile
|
|
96 import optparse
|
|
97 import tarfile
|
|
98 import re
|
|
99 import shutil
|
|
100 import math
|
|
101
|
|
102 progname = os.path.split(sys.argv[0])[1]
|
|
103 myversion = 'V001.1 March 2014'
|
|
104 verbose = False
|
|
105 debug = False
|
|
106 toolFactoryURL = 'https://bitbucket.org/fubar/galaxytoolfactory'
|
|
107
|
|
108 # if we do html we need these dependencies specified in a tool_dependencies.xml file and referred to in the generated
|
|
109 # tool xml
|
|
110 toolhtmldepskel = """<?xml version="1.0"?>
|
|
111 <tool_dependency>
|
|
112 <package name="ghostscript" version="9.10">
|
|
113 <repository name="package_ghostscript_9_10" owner="devteam" prior_installation_required="True" />
|
|
114 </package>
|
|
115 <package name="graphicsmagick" version="1.3.18">
|
|
116 <repository name="package_graphicsmagick_1_3" owner="iuc" prior_installation_required="True" />
|
|
117 </package>
|
|
118 <readme>
|
|
119 %s
|
|
120 </readme>
|
|
121 </tool_dependency>
|
|
122 """
|
|
123
|
2
|
124 emptytoolhtmldepskel = """<?xml version="1.0"?>
|
0
|
125 <tool_dependency>
|
|
126 <readme>
|
|
127 %s
|
|
128 </readme>
|
|
129 </tool_dependency>
|
|
130 """
|
|
131
|
|
132 protorequirements = """<requirements>
|
|
133 <requirement type="package" version="9.10">ghostscript</requirement>
|
|
134 <requirement type="package" version="1.3.18">graphicsmagick</requirement>
|
|
135 </requirements>"""
|
|
136
|
|
137 def timenow():
|
|
138 """return current time as a string
|
|
139 """
|
|
140 return time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(time.time()))
|
|
141
|
|
142 html_escape_table = {
|
|
143 "&": "&",
|
|
144 ">": ">",
|
|
145 "<": "<",
|
|
146 "$": "\$"
|
|
147 }
|
8
|
148
|
0
|
149 def html_escape(text):
|
|
150 """Produce entities within text."""
|
|
151 return "".join(html_escape_table.get(c,c) for c in text)
|
|
152
|
7
|
153
|
|
154 def html_unescape(text):
|
|
155 """Revert entities within text."""
|
8
|
156 t = text.replace('&','&').replace('>','>').replace('<','<').replace('\$','$')
|
|
157 return t
|
7
|
158
|
0
|
159 def cmd_exists(cmd):
|
|
160 return subprocess.call("type " + cmd, shell=True,
|
|
161 stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
|
|
162
|
|
163 def parse_citations(citations_text):
|
|
164 """
|
|
165 """
|
|
166 citations = [c for c in citations_text.split("**ENTRY**") if c.strip()]
|
|
167 citation_tuples = []
|
|
168 for citation in citations:
|
|
169 if citation.startswith("doi"):
|
|
170 citation_tuples.append( ("doi", citation[len("doi"):].strip() ) )
|
|
171 else:
|
|
172 citation_tuples.append( ("bibtex", citation[len("bibtex"):].strip() ) )
|
|
173 return citation_tuples
|
|
174
|
|
175
|
|
176 class ScriptRunner:
|
|
177 """class is a wrapper for an arbitrary script
|
|
178 """
|
|
179
|
|
180 def __init__(self,opts=None,treatbashSpecial=True):
|
|
181 """
|
|
182 cleanup inputs, setup some outputs
|
|
183
|
|
184 """
|
|
185 self.useGM = cmd_exists('gm')
|
|
186 self.useIM = cmd_exists('convert')
|
|
187 self.useGS = cmd_exists('gs')
|
|
188 self.temp_warned = False # we want only one warning if $TMP not set
|
|
189 self.treatbashSpecial = treatbashSpecial
|
|
190 if opts.output_dir: # simplify for the tool tarball
|
|
191 os.chdir(opts.output_dir)
|
|
192 self.thumbformat = 'png'
|
|
193 self.opts = opts
|
|
194 self.toolname = re.sub('[^a-zA-Z0-9_]+', '', opts.tool_name) # a sanitizer now does this but..
|
|
195 self.toolid = self.toolname
|
|
196 self.myname = sys.argv[0] # get our name because we write ourselves out as a tool later
|
|
197 self.pyfile = self.myname # crude but efficient - the cruft won't hurt much
|
|
198 self.xmlfile = '%s.xml' % self.toolname
|
4
|
199 rx = open(self.opts.script_path,'r').readlines()
|
|
200 rx = [x.rstrip() for x in rx] # remove pesky dos line endings if needed
|
|
201 self.script = '\n'.join(rx)
|
0
|
202 fhandle,self.sfile = tempfile.mkstemp(prefix=self.toolname,suffix=".%s" % (opts.interpreter))
|
|
203 tscript = open(self.sfile,'w') # use self.sfile as script source for Popen
|
|
204 tscript.write(self.script)
|
|
205 tscript.close()
|
6
|
206 self.indentedScript = " %s" % '\n'.join([' %s' % html_escape(x) for x in rx]) # for restructured text in help
|
|
207 self.escapedScript = "%s" % '\n'.join([' %s' % html_escape(x) for x in rx])
|
0
|
208 self.elog = os.path.join(self.opts.output_dir,"%s_error.log" % self.toolname)
|
|
209 if opts.output_dir: # may not want these complexities
|
|
210 self.tlog = os.path.join(self.opts.output_dir,"%s_runner.log" % self.toolname)
|
|
211 art = '%s.%s' % (self.toolname,opts.interpreter)
|
|
212 artpath = os.path.join(self.opts.output_dir,art) # need full path
|
|
213 artifact = open(artpath,'w') # use self.sfile as script source for Popen
|
|
214 artifact.write(self.script)
|
|
215 artifact.close()
|
|
216 self.cl = []
|
|
217 self.html = []
|
|
218 self.test1Inputs = [] # now a list
|
|
219 a = self.cl.append
|
|
220 a(opts.interpreter)
|
|
221 if self.treatbashSpecial and opts.interpreter in ['bash','sh']:
|
|
222 a(self.sfile)
|
|
223 else:
|
|
224 a('-') # stdin
|
|
225 # if multiple inputs - positional or need to distinguish them with cl params
|
|
226 if opts.input_tab:
|
|
227 tests = []
|
|
228 for i,intab in enumerate(opts.input_tab): # if multiple, make tests
|
|
229 if intab.find(',') <> -1:
|
|
230 (gpath,uname) = intab.split(',')
|
|
231 else:
|
|
232 gpath = uname = intab
|
|
233 tests.append(os.path.basename(gpath))
|
|
234 self.test1Inputs = '<param name="input_tab" value="%s" />' % (','.join(tests))
|
|
235 else:
|
|
236 self.test1Inputs = ''
|
|
237 # we always pass path,name pairs in using python optparse append
|
|
238 # but the command line has to be different
|
2
|
239 self.infile_paths = ''
|
|
240 self.infile_names = ''
|
|
241 if self.opts.input_tab:
|
|
242 self.infile_paths = ','.join([x.split(',')[0].strip() for x in self.opts.input_tab])
|
|
243 self.infile_names = ','.join([x.split(',')[1].strip() for x in self.opts.input_tab])
|
0
|
244 if self.opts.interpreter == 'python':
|
|
245 # yes, this is how additional parameters are always passed in python - to the TF itself and to
|
|
246 # scripts to avoid having unknown parameter names (yes, they can be parsed but...) on the command line
|
2
|
247 if self.opts.input_tab:
|
|
248 a('--INPATHS "%s"' % (self.infile_paths))
|
|
249 a('--INNAMES "%s"' % (self.infile_names))
|
0
|
250 if self.opts.output_tab:
|
|
251 a('--OUTPATH "%s"' % self.opts.output_tab)
|
|
252 for p in opts.additional_parameters:
|
|
253 p = p.replace('"','')
|
7
|
254 psplit = p.split(',')
|
|
255 param = html_unescape(psplit[0])
|
|
256 value = html_unescape(psplit[1])
|
|
257 a('%s="%s"' % (param,value))
|
0
|
258 if (self.opts.interpreter == 'Rscript'):
|
|
259 # pass params on command line
|
2
|
260 if self.opts.input_tab:
|
|
261 a('INPATHS="%s"' % self.infile_paths)
|
|
262 a('INNAMES="%s"' % self.infile_names)
|
0
|
263 if self.opts.output_tab:
|
2
|
264 a('OUTPATH="%s"' % self.opts.output_tab)
|
|
265 for p in opts.additional_parameters:
|
|
266 p = p.replace('"','')
|
7
|
267 psplit = p.split(',')
|
|
268 param = html_unescape(psplit[0])
|
|
269 value = html_unescape(psplit[1])
|
|
270 a('%s="%s"' % (param,value))
|
0
|
271 if (self.opts.interpreter == 'perl'):
|
|
272 # pass params on command line
|
2
|
273 if self.opts.input_tab:
|
|
274 a('%s' % self.infile_paths)
|
|
275 a('%s' % self.infile_names)
|
0
|
276 if self.opts.output_tab:
|
|
277 a('%s' % self.opts.output_tab)
|
2
|
278 for p in opts.additional_parameters:
|
|
279 p = p.replace('"','')
|
7
|
280 psplit = p.split(',')
|
|
281 param = html_unescape(psplit[0])
|
|
282 value = html_unescape(psplit[1])
|
0
|
283 if (value.find(' ') <> -1):
|
|
284 a('%s="%s"' % (param,value))
|
|
285 else:
|
|
286 a('%s=%s' % (param,value))
|
|
287 if self.opts.interpreter == 'sh' or self.opts.interpreter == 'bash':
|
|
288 # more is better - now move all params into environment AND drop on to command line.
|
|
289 self.cl.insert(0,'env')
|
2
|
290 if self.opts.input_tab:
|
|
291 self.cl.insert(1,'INPATHS=%s' % (self.infile_paths))
|
|
292 self.cl.insert(2,'INNAMES=%s' % (self.infile_names))
|
0
|
293 if self.opts.output_tab:
|
|
294 self.cl.insert(3,'OUTPATH=%s' % (self.opts.output_tab))
|
|
295 a('OUTPATH=%s' % (self.opts.output_tab))
|
|
296 # sets those environment variables for the script
|
|
297 # additional params appear in CL - yes, it's confusing
|
7
|
298 for i,p in enumerate(opts.additional_parameters):
|
|
299 psplit = p.split(',')
|
|
300 param = html_unescape(psplit[0])
|
|
301 value = html_unescape(psplit[1])
|
|
302 if (value.find(' ') <> -1):
|
|
303 a('%s="%s"' % (param,value))
|
|
304 self.cl.insert(4+i,'%s="%s"' % (param,value))
|
0
|
305 else:
|
7
|
306 a('%s=%s' % (param,value))
|
|
307 self.cl.insert(4+i,'%s=%s' % (param,value))
|
0
|
308
|
|
309
|
|
310 self.outFormats = opts.output_format
|
|
311 self.inputFormats = opts.input_formats
|
|
312 self.test1Output = '%s_test1_output.xls' % self.toolname
|
|
313 self.test1HTML = '%s_test1_output.html' % self.toolname
|
|
314
|
|
315 def makeXML(self):
|
|
316 """
|
|
317 Create a Galaxy xml tool wrapper for the new script as a string to write out
|
|
318 fixme - use templating or something less fugly than this example of what we produce
|
|
319
|
|
320 <tool id="reverse" name="reverse" version="0.01">
|
|
321 <description>a tabular file</description>
|
|
322 <command interpreter="python">
|
|
323 reverse.py --script_path "$runMe" --interpreter "python"
|
3
|
324 --tool_name "reverse" --input_tab "$input1" --output_tab "$output1"
|
0
|
325 </command>
|
|
326 <inputs>
|
|
327 <param name="input1" type="data" format="tabular" label="Select one or more input files from your history"/>
|
|
328 <param name="job_name" type="text" label="Supply a name for the outputs to remind you what they contain" value="reverse"/>
|
|
329 </inputs>
|
|
330 <outputs>
|
3
|
331 <data format="tabular" name="output1q" label="${job_name}"/>
|
0
|
332
|
|
333 </outputs>
|
|
334 <help>
|
|
335
|
|
336 **What it Does**
|
|
337
|
|
338 Reverse the columns in a tabular file
|
|
339
|
|
340 </help>
|
|
341 <configfiles>
|
|
342 <configfile name="runMe">
|
|
343
|
|
344 # reverse order of columns in a tabular file
|
|
345 import sys
|
|
346 inp = sys.argv[1]
|
|
347 outp = sys.argv[2]
|
|
348 i = open(inp,'r')
|
|
349 o = open(outp,'w')
|
|
350 for row in i:
|
|
351 rs = row.rstrip().split('\t')
|
|
352 rs.reverse()
|
|
353 o.write('\t'.join(rs))
|
|
354 o.write('\n')
|
|
355 i.close()
|
|
356 o.close()
|
|
357
|
|
358
|
|
359 </configfile>
|
|
360 </configfiles>
|
|
361 </tool>
|
|
362
|
|
363 """
|
|
364 newXML="""<tool id="%(toolid)s" name="%(toolname)s" version="%(tool_version)s">
|
|
365 %(tooldesc)s
|
|
366 %(requirements)s
|
|
367 <command interpreter="python">
|
|
368 %(command)s
|
|
369 </command>
|
|
370 <inputs>
|
|
371 %(inputs)s
|
|
372 %(additionalInputs)s
|
|
373 </inputs>
|
|
374 <outputs>
|
|
375 %(outputs)s
|
|
376 </outputs>
|
|
377 <configfiles>
|
|
378 <configfile name="runMe">
|
|
379 %(script)s
|
|
380 </configfile>
|
|
381 </configfiles>
|
|
382 <tests>
|
|
383 %(tooltests)s
|
|
384 </tests>
|
|
385 <help>
|
|
386
|
|
387 %(help)s
|
|
388
|
|
389 </help>
|
|
390 <citations>
|
|
391 %(citations)s
|
|
392 <citation type="doi">10.1093/bioinformatics/bts573</citation>
|
|
393 </citations>
|
|
394 </tool>""" # needs a dict with toolname, toolid, interpreter, scriptname, command, inputs as a multi line string ready to write, outputs ditto, help ditto
|
|
395
|
|
396 newCommand="""
|
|
397 %(toolname)s.py --script_path "$runMe" --interpreter "%(interpreter)s"
|
|
398 --tool_name "%(toolname)s"
|
|
399 %(command_inputs)s
|
|
400 %(command_outputs)s
|
|
401 """
|
|
402 # may NOT be an input or htmlout - appended later
|
|
403 tooltestsTabOnly = """
|
|
404 <test>
|
|
405 %(test1Inputs)s
|
|
406 <param name="job_name" value="test1"/>
|
|
407 <param name="runMe" value="$runMe"/>
|
|
408 <output name="output1="%(test1Output)s" ftype="tabular"/>
|
|
409 %(additionalParams)s
|
|
410 </test>
|
|
411 """
|
|
412 tooltestsHTMLOnly = """
|
|
413 <test>
|
|
414 %(test1Inputs)s
|
|
415 <param name="job_name" value="test1"/>
|
|
416 <param name="runMe" value="$runMe"/>
|
|
417 %(additionalParams)s
|
|
418 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="5"/>
|
|
419 </test>
|
|
420 """
|
|
421 tooltestsBoth = """
|
|
422 <test>
|
|
423 %(test1Inputs)s
|
|
424 <param name="job_name" value="test1"/>
|
|
425 <param name="runMe" value="$runMe"/>
|
|
426 %(additionalParams)s
|
|
427 <output name="output1" file="%(test1Output)s" ftype="tabular" />
|
|
428 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="10"/>
|
|
429 </test>
|
|
430 """
|
|
431 xdict = {}
|
|
432 xdict['additionalParams'] = ''
|
|
433 xdict['additionalInputs'] = ''
|
|
434 if self.opts.additional_parameters:
|
|
435 if self.opts.edit_additional_parameters: # add to new tool form with default value set to original value
|
2
|
436 xdict['additionalInputs'] = '\n'.join(['<param name="%s" value="%s" label="%s" help="%s" type="%s"/>' % (x.split(',')[0],html_escape(x.split(',')[1]),html_escape(x.split(',')[2]),
|
|
437 html_escape(x.split(',')[3]), x.split(',')[4]) for x in self.opts.additional_parameters])
|
|
438 xdict['additionalParams'] = '\n'.join(['<param name="%s" value="%s" />' % (x.split(',')[0],html_escape(x.split(',')[1])) for x in self.opts.additional_parameters])
|
0
|
439 xdict['requirements'] = ''
|
|
440 if self.opts.make_HTML:
|
|
441 if self.opts.include_dependencies == "yes":
|
|
442 xdict['requirements'] = protorequirements
|
|
443 xdict['tool_version'] = self.opts.tool_version
|
|
444 xdict['test1HTML'] = self.test1HTML
|
|
445 xdict['test1Output'] = self.test1Output
|
|
446 xdict['test1Inputs'] = self.test1Inputs
|
|
447 if self.opts.make_HTML and self.opts.output_tab:
|
|
448 xdict['tooltests'] = tooltestsBoth % xdict
|
|
449 elif self.opts.make_HTML:
|
|
450 xdict['tooltests'] = tooltestsHTMLOnly % xdict
|
|
451 else:
|
|
452 xdict['tooltests'] = tooltestsTabOnly % xdict
|
|
453 xdict['script'] = self.escapedScript
|
|
454 # configfile is least painful way to embed script to avoid external dependencies
|
|
455 # but requires escaping of <, > and $ to avoid Mako parsing
|
|
456 if self.opts.help_text:
|
|
457 helptext = open(self.opts.help_text,'r').readlines()
|
|
458 helptext = [html_escape(x) for x in helptext] # must html escape here too - thanks to Marius van den Beek
|
|
459 xdict['help'] = ''.join([x for x in helptext])
|
|
460 else:
|
|
461 xdict['help'] = 'Please ask the tool author (%s) for help as none was supplied at tool generation\n' % (self.opts.user_email)
|
|
462 coda = ['**Script**','Pressing execute will run the following code over your input file and generate some outputs in your history::']
|
|
463 coda.append('\n')
|
|
464 coda.append(self.indentedScript)
|
|
465 coda.append('\n**Attribution**\nThis Galaxy tool was created by %s at %s\nusing the Galaxy Tool Factory.\n' % (self.opts.user_email,timenow()))
|
|
466 coda.append('See %s for details of that project' % (toolFactoryURL))
|
|
467 coda.append('Please cite: Creating re-usable tools from scripts: The Galaxy Tool Factory. Ross Lazarus; Antony Kaspi; Mark Ziemann; The Galaxy Team. ')
|
|
468 coda.append('Bioinformatics 2012; doi: 10.1093/bioinformatics/bts573\n')
|
|
469 xdict['help'] = '%s\n%s' % (xdict['help'],'\n'.join(coda))
|
|
470 if self.opts.tool_desc:
|
|
471 xdict['tooldesc'] = '<description>%s</description>' % self.opts.tool_desc
|
|
472 else:
|
|
473 xdict['tooldesc'] = ''
|
|
474 xdict['command_outputs'] = ''
|
|
475 xdict['outputs'] = ''
|
2
|
476 if self.opts.input_tab:
|
0
|
477 cins = ['\n',]
|
2
|
478 cins.append('--input_formats %s' % self.opts.input_formats)
|
0
|
479 cins.append('#for intab in $input1:')
|
2
|
480 cins.append('--input_tab "${intab},${intab.name}"')
|
0
|
481 cins.append('#end for\n')
|
|
482 xdict['command_inputs'] = '\n'.join(cins)
|
|
483 xdict['inputs'] = '''<param name="input_tab" multiple="true" type="data" format="%s" label="Select one or more %s input files from your history"
|
|
484 help="Multiple inputs may be selected assuming the script can deal with them..."/> \n''' % (self.inputFormats,self.inputFormats)
|
|
485 else:
|
|
486 xdict['command_inputs'] = '' # assume no input - eg a random data generator
|
|
487 xdict['inputs'] = ''
|
|
488 if (len(self.opts.additional_parameters) > 0):
|
|
489 cins = ['\n',]
|
|
490 for params in self.opts.additional_parameters:
|
|
491 psplit = params.split(',') # name,value...
|
2
|
492 psplit[3] = html_escape(psplit[3])
|
|
493 if self.opts.edit_additional_parameters:
|
|
494 psplit[1] = '$%s' % psplit[0] # replace with form value
|
|
495 else:
|
|
496 psplit[1] = html_escape(psplit[1]) # leave prespecified value
|
|
497 cins.append('--additional_parameters """%s"""' % ','.join(psplit))
|
0
|
498 xdict['command_inputs'] = '%s\n%s' % (xdict['command_inputs'],'\n'.join(cins))
|
|
499 xdict['inputs'] += '<param name="job_name" type="text" size="60" label="Supply a name for the outputs to remind you what they contain" value="%s"/> \n' % self.toolname
|
|
500 xdict['toolname'] = self.toolname
|
|
501 xdict['toolid'] = self.toolid
|
|
502 xdict['interpreter'] = self.opts.interpreter
|
|
503 xdict['scriptname'] = self.sfile
|
|
504 if self.opts.make_HTML:
|
|
505 xdict['command_outputs'] += ' --output_dir "$html_file.files_path" --output_html "$html_file" --make_HTML "yes"'
|
|
506 xdict['outputs'] += ' <data format="html" name="html_file" label="${job_name}.html"/>\n'
|
|
507 else:
|
|
508 xdict['command_outputs'] += ' --output_dir "./"'
|
|
509 if self.opts.output_tab:
|
3
|
510 xdict['command_outputs'] += ' --output_tab "$output1"'
|
0
|
511 xdict['outputs'] += ' <data format="%s" name="output1" label="${job_name}"/>\n' % self.outFormats
|
|
512 xdict['command'] = newCommand % xdict
|
|
513 if self.opts.citations:
|
|
514 citationstext = open(self.opts.citations,'r').read()
|
|
515 citation_tuples = parse_citations(citationstext)
|
|
516 citations_xml = ""
|
|
517 for citation_type, citation_content in citation_tuples:
|
|
518 citation_xml = """<citation type="%s">%s</citation>""" % (citation_type, html_escape(citation_content))
|
|
519 citations_xml += citation_xml
|
|
520 xdict['citations'] = citations_xml
|
|
521 else:
|
|
522 xdict['citations'] = ""
|
|
523 xmls = newXML % xdict
|
|
524 xf = open(self.xmlfile,'w')
|
|
525 xf.write(xmls)
|
|
526 xf.write('\n')
|
|
527 xf.close()
|
|
528 # ready for the tarball
|
|
529
|
|
530
|
|
531 def makeTooltar(self):
|
|
532 """
|
|
533 a tool is a gz tarball with eg
|
|
534 /toolname/tool.xml /toolname/tool.py /toolname/test-data/test1_in.foo ...
|
|
535 """
|
|
536 retval = self.run()
|
|
537 if retval:
|
|
538 print >> sys.stderr,'## Run failed. Cannot build yet. Please fix and retry'
|
|
539 sys.exit(1)
|
|
540 tdir = self.toolname
|
|
541 os.mkdir(tdir)
|
|
542 self.makeXML()
|
2
|
543 if self.opts.help_text:
|
|
544 hlp = open(self.opts.help_text,'r').read()
|
|
545 else:
|
|
546 hlp = 'Please ask the tool author for help as none was supplied at tool generation\n'
|
|
547 if self.opts.include_dependencies == "yes":
|
|
548 tooldepcontent = toolhtmldepskel % hlp
|
|
549 else:
|
|
550 tooldepcontent = emptytoolhtmldepskel % hlp
|
|
551 depf = open(os.path.join(tdir,'tool_dependencies.xml'),'w')
|
|
552 depf.write(tooldepcontent)
|
|
553 depf.write('\n')
|
|
554 depf.close()
|
|
555 if self.opts.input_tab: # no reproducible test otherwise? TODO: maybe..
|
0
|
556 testdir = os.path.join(tdir,'test-data')
|
|
557 os.mkdir(testdir) # make tests directory
|
|
558 for i,intab in enumerate(self.opts.input_tab):
|
|
559 si = self.opts.input_tab[i]
|
|
560 if si.find(',') <> -1:
|
|
561 s = si.split(',')[0]
|
|
562 si = s
|
|
563 dest = os.path.join(testdir,os.path.basename(si))
|
|
564 if si <> dest:
|
|
565 shutil.copyfile(si,dest)
|
2
|
566 if self.opts.output_tab:
|
0
|
567 shutil.copyfile(self.opts.output_tab,os.path.join(testdir,self.test1Output))
|
|
568 if self.opts.make_HTML:
|
|
569 shutil.copyfile(self.opts.output_html,os.path.join(testdir,self.test1HTML))
|
|
570 if self.opts.output_dir:
|
|
571 shutil.copyfile(self.tlog,os.path.join(testdir,'test1_out.log'))
|
|
572 outpif = '%s.py' % self.toolname # new name
|
|
573 outpiname = os.path.join(tdir,outpif) # path for the tool tarball
|
|
574 pyin = os.path.basename(self.pyfile) # our name - we rewrite ourselves (TM)
|
|
575 notes = ['# %s - a self annotated version of %s generated by running %s\n' % (outpiname,pyin,pyin),]
|
|
576 notes.append('# to make a new Galaxy tool called %s\n' % self.toolname)
|
|
577 notes.append('# User %s at %s\n' % (self.opts.user_email,timenow()))
|
|
578 pi = open(self.pyfile,'r').readlines() # our code becomes new tool wrapper (!) - first Galaxy worm
|
|
579 notes += pi
|
|
580 outpi = open(outpiname,'w')
|
|
581 outpi.write(''.join(notes))
|
|
582 outpi.write('\n')
|
|
583 outpi.close()
|
|
584 stname = os.path.join(tdir,self.sfile)
|
|
585 if not os.path.exists(stname):
|
|
586 shutil.copyfile(self.sfile, stname)
|
|
587 xtname = os.path.join(tdir,self.xmlfile)
|
|
588 if not os.path.exists(xtname):
|
|
589 shutil.copyfile(self.xmlfile,xtname)
|
|
590 tarpath = "%s.tar.gz" % self.toolname
|
|
591 tar = tarfile.open(tarpath, "w:gz")
|
|
592 tar.add(tdir,arcname='%s' % self.toolname)
|
|
593 tar.close()
|
|
594 shutil.copyfile(tarpath,self.opts.new_tool)
|
|
595 shutil.rmtree(tdir)
|
|
596 ## TODO: replace with optional direct upload to local toolshed?
|
|
597 return retval
|
|
598
|
|
599
|
|
600 def compressPDF(self,inpdf=None,thumbformat='png'):
|
|
601 """need absolute path to pdf
|
|
602 note that GS gets confoozled if no $TMP or $TEMP
|
|
603 so we set it
|
|
604 """
|
|
605 assert os.path.isfile(inpdf), "## Input %s supplied to %s compressPDF not found" % (inpdf,self.myName)
|
|
606 hlog = os.path.join(self.opts.output_dir,"compress_%s.txt" % os.path.basename(inpdf))
|
|
607 sto = open(hlog,'a')
|
|
608 our_env = os.environ.copy()
|
|
609 our_tmp = our_env.get('TMP',None)
|
|
610 if not our_tmp:
|
|
611 our_tmp = our_env.get('TEMP',None)
|
|
612 if not (our_tmp and os.path.exists(our_tmp)):
|
|
613 newtmp = os.path.join(self.opts.output_dir,'tmp')
|
|
614 try:
|
|
615 os.mkdir(newtmp)
|
|
616 except:
|
|
617 sto.write('## WARNING - cannot make %s - it may exist or permissions need fixing\n' % newtmp)
|
|
618 our_env['TEMP'] = newtmp
|
|
619 if not self.temp_warned:
|
|
620 sto.write('## WARNING - no $TMP or $TEMP!!! Please fix - using %s temporarily\n' % newtmp)
|
|
621 self.temp_warned = True
|
|
622 outpdf = '%s_compressed' % inpdf
|
|
623 cl = ["gs", "-sDEVICE=pdfwrite", "-dNOPAUSE", "-dUseCIEColor", "-dBATCH","-dPDFSETTINGS=/printer", "-sOutputFile=%s" % outpdf,inpdf]
|
|
624 x = subprocess.Popen(cl,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
|
|
625 retval1 = x.wait()
|
|
626 sto.close()
|
|
627 if retval1 == 0:
|
|
628 os.unlink(inpdf)
|
|
629 shutil.move(outpdf,inpdf)
|
|
630 os.unlink(hlog)
|
|
631 hlog = os.path.join(self.opts.output_dir,"thumbnail_%s.txt" % os.path.basename(inpdf))
|
|
632 sto = open(hlog,'w')
|
|
633 outpng = '%s.%s' % (os.path.splitext(inpdf)[0],thumbformat)
|
|
634 if self.useGM:
|
|
635 cl2 = ['gm', 'convert', inpdf, outpng]
|
|
636 else: # assume imagemagick
|
|
637 cl2 = ['convert', inpdf, outpng]
|
|
638 x = subprocess.Popen(cl2,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
|
|
639 retval2 = x.wait()
|
|
640 sto.close()
|
|
641 if retval2 == 0:
|
|
642 os.unlink(hlog)
|
|
643 retval = retval1 or retval2
|
|
644 return retval
|
|
645
|
|
646
|
|
647 def getfSize(self,fpath,outpath):
|
|
648 """
|
|
649 format a nice file size string
|
|
650 """
|
|
651 size = ''
|
|
652 fp = os.path.join(outpath,fpath)
|
|
653 if os.path.isfile(fp):
|
|
654 size = '0 B'
|
|
655 n = float(os.path.getsize(fp))
|
|
656 if n > 2**20:
|
|
657 size = '%1.1f MB' % (n/2**20)
|
|
658 elif n > 2**10:
|
|
659 size = '%1.1f KB' % (n/2**10)
|
|
660 elif n > 0:
|
|
661 size = '%d B' % (int(n))
|
|
662 return size
|
|
663
|
|
664 def makeHtml(self):
|
|
665 """ Create an HTML file content to list all the artifacts found in the output_dir
|
|
666 """
|
|
667
|
|
668 galhtmlprefix = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
669 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
|
670 <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
|
671 <meta name="generator" content="Galaxy %s tool output - see http://g2.trac.bx.psu.edu/" />
|
|
672 <title></title>
|
|
673 <link rel="stylesheet" href="/static/style/base.css" type="text/css" />
|
|
674 </head>
|
|
675 <body>
|
|
676 <div class="toolFormBody">
|
|
677 """
|
|
678 galhtmlattr = """<hr/><div class="infomessage">This tool (%s) was generated by the <a href="https://bitbucket.org/fubar/galaxytoolfactory/overview">Galaxy Tool Factory</a></div><br/>"""
|
|
679 galhtmlpostfix = """</div></body></html>\n"""
|
|
680
|
|
681 flist = os.listdir(self.opts.output_dir)
|
|
682 flist = [x for x in flist if x <> 'Rplots.pdf']
|
|
683 flist.sort()
|
|
684 html = []
|
|
685 html.append(galhtmlprefix % progname)
|
|
686 html.append('<div class="infomessage">Galaxy Tool "%s" run at %s</div><br/>' % (self.toolname,timenow()))
|
|
687 fhtml = []
|
|
688 if len(flist) > 0:
|
|
689 logfiles = [x for x in flist if x.lower().endswith('.log')] # log file names determine sections
|
|
690 logfiles.sort()
|
|
691 logfiles = [x for x in logfiles if os.path.abspath(x) <> os.path.abspath(self.tlog)]
|
|
692 logfiles.append(os.path.abspath(self.tlog)) # make it the last one
|
|
693 pdflist = []
|
|
694 npdf = len([x for x in flist if os.path.splitext(x)[-1].lower() == '.pdf'])
|
|
695 for rownum,fname in enumerate(flist):
|
|
696 dname,e = os.path.splitext(fname)
|
|
697 sfsize = self.getfSize(fname,self.opts.output_dir)
|
|
698 if e.lower() == '.pdf' : # compress and make a thumbnail
|
|
699 thumb = '%s.%s' % (dname,self.thumbformat)
|
|
700 pdff = os.path.join(self.opts.output_dir,fname)
|
|
701 retval = self.compressPDF(inpdf=pdff,thumbformat=self.thumbformat)
|
|
702 if retval == 0:
|
|
703 pdflist.append((fname,thumb))
|
|
704 else:
|
|
705 pdflist.append((fname,fname))
|
|
706 if (rownum+1) % 2 == 0:
|
|
707 fhtml.append('<tr class="odd_row"><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname,fname,sfsize))
|
|
708 else:
|
|
709 fhtml.append('<tr><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname,fname,sfsize))
|
|
710 for logfname in logfiles: # expect at least tlog - if more
|
|
711 if os.path.abspath(logfname) == os.path.abspath(self.tlog): # handled later
|
|
712 sectionname = 'All tool run'
|
|
713 if (len(logfiles) > 1):
|
|
714 sectionname = 'Other'
|
|
715 ourpdfs = pdflist
|
|
716 else:
|
|
717 realname = os.path.basename(logfname)
|
|
718 sectionname = os.path.splitext(realname)[0].split('_')[0] # break in case _ added to log
|
|
719 ourpdfs = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] == sectionname]
|
|
720 pdflist = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] <> sectionname] # remove
|
|
721 nacross = 1
|
|
722 npdf = len(ourpdfs)
|
|
723
|
|
724 if npdf > 0:
|
|
725 nacross = math.sqrt(npdf) ## int(round(math.log(npdf,2)))
|
|
726 if int(nacross)**2 != npdf:
|
|
727 nacross += 1
|
|
728 nacross = int(nacross)
|
|
729 width = min(400,int(1200/nacross))
|
|
730 html.append('<div class="toolFormTitle">%s images and outputs</div>' % sectionname)
|
|
731 html.append('(Click on a thumbnail image to download the corresponding original PDF image)<br/>')
|
|
732 ntogo = nacross # counter for table row padding with empty cells
|
|
733 html.append('<div><table class="simple" cellpadding="2" cellspacing="2">\n<tr>')
|
|
734 for i,paths in enumerate(ourpdfs):
|
|
735 fname,thumb = paths
|
|
736 s= """<td><a href="%s"><img src="%s" title="Click to download a PDF of %s" hspace="5" width="%d"
|
|
737 alt="Image called %s"/></a></td>\n""" % (fname,thumb,fname,width,fname)
|
|
738 if ((i+1) % nacross == 0):
|
|
739 s += '</tr>\n'
|
|
740 ntogo = 0
|
|
741 if i < (npdf - 1): # more to come
|
|
742 s += '<tr>'
|
|
743 ntogo = nacross
|
|
744 else:
|
|
745 ntogo -= 1
|
|
746 html.append(s)
|
|
747 if html[-1].strip().endswith('</tr>'):
|
|
748 html.append('</table></div>\n')
|
|
749 else:
|
|
750 if ntogo > 0: # pad
|
|
751 html.append('<td> </td>'*ntogo)
|
|
752 html.append('</tr></table></div>\n')
|
|
753 logt = open(logfname,'r').readlines()
|
|
754 logtext = [x for x in logt if x.strip() > '']
|
|
755 html.append('<div class="toolFormTitle">%s log output</div>' % sectionname)
|
|
756 if len(logtext) > 1:
|
|
757 html.append('\n<pre>\n')
|
|
758 html += logtext
|
|
759 html.append('\n</pre>\n')
|
|
760 else:
|
|
761 html.append('%s is empty<br/>' % logfname)
|
|
762 if len(fhtml) > 0:
|
|
763 fhtml.insert(0,'<div><table class="colored" cellpadding="3" cellspacing="3"><tr><th>Output File Name (click to view)</th><th>Size</th></tr>\n')
|
|
764 fhtml.append('</table></div><br/>')
|
|
765 html.append('<div class="toolFormTitle">All output files available for downloading</div>\n')
|
|
766 html += fhtml # add all non-pdf files to the end of the display
|
|
767 else:
|
|
768 html.append('<div class="warningmessagelarge">### Error - %s returned no files - please confirm that parameters are sane</div>' % self.opts.interpreter)
|
|
769 html.append(galhtmlpostfix)
|
|
770 htmlf = file(self.opts.output_html,'w')
|
|
771 htmlf.write('\n'.join(html))
|
|
772 htmlf.write('\n')
|
|
773 htmlf.close()
|
|
774 self.html = html
|
|
775
|
|
776
|
|
777 def run(self):
|
|
778 """
|
|
779 scripts must be small enough not to fill the pipe!
|
|
780 """
|
|
781 if self.treatbashSpecial and self.opts.interpreter in ['bash','sh']:
|
|
782 retval = self.runBash()
|
|
783 else:
|
|
784 if self.opts.output_dir:
|
|
785 ste = open(self.elog,'w')
|
|
786 sto = open(self.tlog,'w')
|
|
787 sto.write('## Toolfactory generated command line = %s\n' % ' '.join(self.cl))
|
|
788 sto.flush()
|
|
789 p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=ste,stdin=subprocess.PIPE,cwd=self.opts.output_dir)
|
|
790 else:
|
|
791 p = subprocess.Popen(self.cl,shell=False,stdin=subprocess.PIPE)
|
|
792 p.stdin.write(self.script)
|
|
793 p.stdin.close()
|
|
794 retval = p.wait()
|
|
795 if self.opts.output_dir:
|
|
796 sto.close()
|
|
797 ste.close()
|
|
798 err = open(self.elog,'r').readlines()
|
|
799 if retval <> 0 and err: # problem
|
|
800 print >> sys.stderr,err
|
|
801 if self.opts.make_HTML:
|
|
802 self.makeHtml()
|
|
803 return retval
|
|
804
|
|
805 def runBash(self):
|
|
806 """
|
|
807 cannot use - for bash so use self.sfile
|
|
808 """
|
|
809 if self.opts.output_dir:
|
|
810 s = '## Toolfactory generated command line = %s\n' % ' '.join(self.cl)
|
|
811 sto = open(self.tlog,'w')
|
|
812 sto.write(s)
|
|
813 sto.flush()
|
|
814 p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=sto,cwd=self.opts.output_dir)
|
|
815 else:
|
|
816 p = subprocess.Popen(self.cl,shell=False)
|
|
817 retval = p.wait()
|
|
818 if self.opts.output_dir:
|
|
819 sto.close()
|
|
820 if self.opts.make_HTML:
|
|
821 self.makeHtml()
|
|
822 return retval
|
|
823
|
|
824
|
|
825 def main():
|
|
826 u = """
|
|
827 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
|
|
828 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath" --tool_name "foo" --interpreter "Rscript"
|
|
829 </command>
|
|
830 """
|
|
831 op = optparse.OptionParser()
|
|
832 a = op.add_option
|
|
833 a('--script_path',default=None)
|
|
834 a('--tool_name',default=None)
|
|
835 a('--interpreter',default=None)
|
|
836 a('--output_dir',default='./')
|
|
837 a('--output_html',default=None)
|
|
838 a('--input_tab',default=[], action="append") # these are "galaxypath,metadataname" pairs
|
|
839 a("--input_formats",default="tabular")
|
|
840 a('--output_tab',default=None)
|
|
841 a('--output_format',default='tabular')
|
|
842 a('--user_email',default='Unknown')
|
|
843 a('--bad_user',default=None)
|
|
844 a('--make_Tool',default=None)
|
|
845 a('--make_HTML',default=None)
|
|
846 a('--help_text',default=None)
|
|
847 a('--tool_desc',default=None)
|
|
848 a('--new_tool',default=None)
|
|
849 a('--tool_version',default=None)
|
|
850 a('--include_dependencies',default="yes")
|
|
851 a('--citations',default=None)
|
|
852 a('--additional_parameters', dest='additional_parameters', action='append', default=[])
|
|
853 a('--edit_additional_parameters', action="store_true", default=False)
|
|
854 opts, args = op.parse_args()
|
|
855 assert not opts.bad_user,'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to admin_users in universe_wsgi.ini' % (opts.bad_user,opts.bad_user)
|
|
856 assert opts.tool_name,'## Tool Factory expects a tool name - eg --tool_name=DESeq'
|
|
857 assert opts.interpreter,'## Tool Factory wrapper expects an interpreter - eg --interpreter=Rscript'
|
|
858 assert os.path.isfile(opts.script_path),'## Tool Factory wrapper expects a script path - eg --script_path=foo.R'
|
|
859 if opts.output_dir:
|
|
860 try:
|
|
861 os.makedirs(opts.output_dir)
|
|
862 except:
|
|
863 pass
|
|
864 opts.input_tab = [x.replace('"','').replace("'",'') for x in opts.input_tab]
|
|
865 for i,x in enumerate(opts.additional_parameters): # remove quotes we need to deal with spaces in CL params
|
|
866 opts.additional_parameters[i] = opts.additional_parameters[i].replace('"','')
|
|
867 r = ScriptRunner(opts)
|
|
868 if opts.make_Tool:
|
|
869 retcode = r.makeTooltar()
|
|
870 else:
|
|
871 retcode = r.run()
|
|
872 os.unlink(r.sfile)
|
|
873 if retcode:
|
|
874 sys.exit(retcode) # indicate failure to job runner
|
|
875
|
|
876
|
|
877 if __name__ == "__main__":
|
|
878 main()
|
|
879
|
|
880
|