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
|
9
|
175 def shell_source(script):
|
|
176 """need a way to source a Galaxy tool interpreter env.sh so we can use that dependency
|
|
177 package
|
|
178 see http://pythonwise.blogspot.fr/2010/04/sourcing-shell-script.html
|
|
179 Sometime you want to emulate the action of "source" in bash,
|
|
180 settings some environment variables. Here is a way to do it.
|
|
181 Note that we have to finesse the automagic exports using nulls as newlines for env"""
|
|
182 pipe = subprocess.Popen("env -i ; . %s ; env -0" % script, stdout=subprocess.PIPE, shell=True)
|
|
183 output = pipe.communicate()[0]
|
|
184 outl = output.split('\0')
|
|
185 outl = [x for x in outl if len(x.split("=")) == 2]
|
|
186 newenv = dict((line.split("=", 1) for line in outl))
|
|
187 os.environ.update(newenv)
|
|
188
|
0
|
189 class ScriptRunner:
|
|
190 """class is a wrapper for an arbitrary script
|
|
191 """
|
|
192
|
|
193 def __init__(self,opts=None,treatbashSpecial=True):
|
|
194 """
|
|
195 cleanup inputs, setup some outputs
|
|
196
|
|
197 """
|
|
198 self.useGM = cmd_exists('gm')
|
|
199 self.useIM = cmd_exists('convert')
|
|
200 self.useGS = cmd_exists('gs')
|
|
201 self.temp_warned = False # we want only one warning if $TMP not set
|
|
202 self.treatbashSpecial = treatbashSpecial
|
|
203 if opts.output_dir: # simplify for the tool tarball
|
|
204 os.chdir(opts.output_dir)
|
|
205 self.thumbformat = 'png'
|
|
206 self.opts = opts
|
|
207 self.toolname = re.sub('[^a-zA-Z0-9_]+', '', opts.tool_name) # a sanitizer now does this but..
|
|
208 self.toolid = self.toolname
|
|
209 self.myname = sys.argv[0] # get our name because we write ourselves out as a tool later
|
|
210 self.pyfile = self.myname # crude but efficient - the cruft won't hurt much
|
|
211 self.xmlfile = '%s.xml' % self.toolname
|
4
|
212 rx = open(self.opts.script_path,'r').readlines()
|
|
213 rx = [x.rstrip() for x in rx] # remove pesky dos line endings if needed
|
|
214 self.script = '\n'.join(rx)
|
0
|
215 fhandle,self.sfile = tempfile.mkstemp(prefix=self.toolname,suffix=".%s" % (opts.interpreter))
|
|
216 tscript = open(self.sfile,'w') # use self.sfile as script source for Popen
|
|
217 tscript.write(self.script)
|
|
218 tscript.close()
|
6
|
219 self.indentedScript = " %s" % '\n'.join([' %s' % html_escape(x) for x in rx]) # for restructured text in help
|
|
220 self.escapedScript = "%s" % '\n'.join([' %s' % html_escape(x) for x in rx])
|
0
|
221 self.elog = os.path.join(self.opts.output_dir,"%s_error.log" % self.toolname)
|
|
222 if opts.output_dir: # may not want these complexities
|
|
223 self.tlog = os.path.join(self.opts.output_dir,"%s_runner.log" % self.toolname)
|
|
224 art = '%s.%s' % (self.toolname,opts.interpreter)
|
|
225 artpath = os.path.join(self.opts.output_dir,art) # need full path
|
|
226 artifact = open(artpath,'w') # use self.sfile as script source for Popen
|
|
227 artifact.write(self.script)
|
|
228 artifact.close()
|
|
229 self.cl = []
|
|
230 self.html = []
|
|
231 self.test1Inputs = [] # now a list
|
|
232 a = self.cl.append
|
|
233 a(opts.interpreter)
|
9
|
234 a(self.sfile)
|
0
|
235 # if multiple inputs - positional or need to distinguish them with cl params
|
|
236 if opts.input_tab:
|
|
237 tests = []
|
|
238 for i,intab in enumerate(opts.input_tab): # if multiple, make tests
|
|
239 if intab.find(',') <> -1:
|
|
240 (gpath,uname) = intab.split(',')
|
|
241 else:
|
|
242 gpath = uname = intab
|
|
243 tests.append(os.path.basename(gpath))
|
|
244 self.test1Inputs = '<param name="input_tab" value="%s" />' % (','.join(tests))
|
|
245 else:
|
|
246 self.test1Inputs = ''
|
|
247 # we always pass path,name pairs in using python optparse append
|
|
248 # but the command line has to be different
|
2
|
249 self.infile_paths = ''
|
|
250 self.infile_names = ''
|
|
251 if self.opts.input_tab:
|
|
252 self.infile_paths = ','.join([x.split(',')[0].strip() for x in self.opts.input_tab])
|
|
253 self.infile_names = ','.join([x.split(',')[1].strip() for x in self.opts.input_tab])
|
0
|
254 if self.opts.interpreter == 'python':
|
|
255 # yes, this is how additional parameters are always passed in python - to the TF itself and to
|
|
256 # scripts to avoid having unknown parameter names (yes, they can be parsed but...) on the command line
|
2
|
257 if self.opts.input_tab:
|
|
258 a('--INPATHS "%s"' % (self.infile_paths))
|
|
259 a('--INNAMES "%s"' % (self.infile_names))
|
0
|
260 if self.opts.output_tab:
|
|
261 a('--OUTPATH "%s"' % self.opts.output_tab)
|
|
262 for p in opts.additional_parameters:
|
|
263 p = p.replace('"','')
|
7
|
264 psplit = p.split(',')
|
|
265 param = html_unescape(psplit[0])
|
|
266 value = html_unescape(psplit[1])
|
|
267 a('%s="%s"' % (param,value))
|
0
|
268 if (self.opts.interpreter == 'Rscript'):
|
|
269 # pass params on command line
|
2
|
270 if self.opts.input_tab:
|
|
271 a('INPATHS="%s"' % self.infile_paths)
|
|
272 a('INNAMES="%s"' % self.infile_names)
|
0
|
273 if self.opts.output_tab:
|
2
|
274 a('OUTPATH="%s"' % self.opts.output_tab)
|
|
275 for p in opts.additional_parameters:
|
|
276 p = p.replace('"','')
|
7
|
277 psplit = p.split(',')
|
|
278 param = html_unescape(psplit[0])
|
|
279 value = html_unescape(psplit[1])
|
|
280 a('%s="%s"' % (param,value))
|
0
|
281 if (self.opts.interpreter == 'perl'):
|
|
282 # pass params on command line
|
2
|
283 if self.opts.input_tab:
|
|
284 a('%s' % self.infile_paths)
|
|
285 a('%s' % self.infile_names)
|
0
|
286 if self.opts.output_tab:
|
|
287 a('%s' % self.opts.output_tab)
|
2
|
288 for p in opts.additional_parameters:
|
|
289 p = p.replace('"','')
|
7
|
290 psplit = p.split(',')
|
|
291 param = html_unescape(psplit[0])
|
|
292 value = html_unescape(psplit[1])
|
0
|
293 if (value.find(' ') <> -1):
|
|
294 a('%s="%s"' % (param,value))
|
|
295 else:
|
|
296 a('%s=%s' % (param,value))
|
|
297 if self.opts.interpreter == 'sh' or self.opts.interpreter == 'bash':
|
|
298 # more is better - now move all params into environment AND drop on to command line.
|
|
299 self.cl.insert(0,'env')
|
2
|
300 if self.opts.input_tab:
|
|
301 self.cl.insert(1,'INPATHS=%s' % (self.infile_paths))
|
|
302 self.cl.insert(2,'INNAMES=%s' % (self.infile_names))
|
0
|
303 if self.opts.output_tab:
|
|
304 self.cl.insert(3,'OUTPATH=%s' % (self.opts.output_tab))
|
|
305 a('OUTPATH=%s' % (self.opts.output_tab))
|
|
306 # sets those environment variables for the script
|
|
307 # additional params appear in CL - yes, it's confusing
|
7
|
308 for i,p in enumerate(opts.additional_parameters):
|
|
309 psplit = p.split(',')
|
|
310 param = html_unescape(psplit[0])
|
|
311 value = html_unescape(psplit[1])
|
|
312 if (value.find(' ') <> -1):
|
|
313 a('%s="%s"' % (param,value))
|
|
314 self.cl.insert(4+i,'%s="%s"' % (param,value))
|
0
|
315 else:
|
7
|
316 a('%s=%s' % (param,value))
|
|
317 self.cl.insert(4+i,'%s=%s' % (param,value))
|
0
|
318
|
|
319
|
|
320 self.outFormats = opts.output_format
|
|
321 self.inputFormats = opts.input_formats
|
|
322 self.test1Output = '%s_test1_output.xls' % self.toolname
|
|
323 self.test1HTML = '%s_test1_output.html' % self.toolname
|
|
324
|
|
325 def makeXML(self):
|
|
326 """
|
|
327 Create a Galaxy xml tool wrapper for the new script as a string to write out
|
|
328 fixme - use templating or something less fugly than this example of what we produce
|
|
329
|
|
330 <tool id="reverse" name="reverse" version="0.01">
|
|
331 <description>a tabular file</description>
|
|
332 <command interpreter="python">
|
|
333 reverse.py --script_path "$runMe" --interpreter "python"
|
3
|
334 --tool_name "reverse" --input_tab "$input1" --output_tab "$output1"
|
0
|
335 </command>
|
|
336 <inputs>
|
|
337 <param name="input1" type="data" format="tabular" label="Select one or more input files from your history"/>
|
|
338 <param name="job_name" type="text" label="Supply a name for the outputs to remind you what they contain" value="reverse"/>
|
|
339 </inputs>
|
|
340 <outputs>
|
3
|
341 <data format="tabular" name="output1q" label="${job_name}"/>
|
0
|
342
|
|
343 </outputs>
|
|
344 <help>
|
|
345
|
|
346 **What it Does**
|
|
347
|
|
348 Reverse the columns in a tabular file
|
|
349
|
|
350 </help>
|
|
351 <configfiles>
|
|
352 <configfile name="runMe">
|
|
353
|
|
354 # reverse order of columns in a tabular file
|
|
355 import sys
|
|
356 inp = sys.argv[1]
|
|
357 outp = sys.argv[2]
|
|
358 i = open(inp,'r')
|
|
359 o = open(outp,'w')
|
|
360 for row in i:
|
|
361 rs = row.rstrip().split('\t')
|
|
362 rs.reverse()
|
|
363 o.write('\t'.join(rs))
|
|
364 o.write('\n')
|
|
365 i.close()
|
|
366 o.close()
|
|
367
|
|
368
|
|
369 </configfile>
|
|
370 </configfiles>
|
|
371 </tool>
|
|
372
|
|
373 """
|
|
374 newXML="""<tool id="%(toolid)s" name="%(toolname)s" version="%(tool_version)s">
|
|
375 %(tooldesc)s
|
|
376 %(requirements)s
|
|
377 <command interpreter="python">
|
|
378 %(command)s
|
|
379 </command>
|
|
380 <inputs>
|
|
381 %(inputs)s
|
|
382 %(additionalInputs)s
|
|
383 </inputs>
|
|
384 <outputs>
|
|
385 %(outputs)s
|
|
386 </outputs>
|
|
387 <configfiles>
|
|
388 <configfile name="runMe">
|
|
389 %(script)s
|
|
390 </configfile>
|
|
391 </configfiles>
|
|
392 <tests>
|
|
393 %(tooltests)s
|
|
394 </tests>
|
|
395 <help>
|
|
396
|
|
397 %(help)s
|
|
398
|
|
399 </help>
|
|
400 <citations>
|
|
401 %(citations)s
|
|
402 <citation type="doi">10.1093/bioinformatics/bts573</citation>
|
|
403 </citations>
|
9
|
404 </tool>"""
|
|
405 # needs a dict with toolname, toolid, interpreter, scriptname, command, inputs as a multi line string ready to write, outputs ditto, help ditto
|
0
|
406
|
|
407 newCommand="""
|
|
408 %(toolname)s.py --script_path "$runMe" --interpreter "%(interpreter)s"
|
|
409 --tool_name "%(toolname)s"
|
|
410 %(command_inputs)s
|
|
411 %(command_outputs)s
|
|
412 """
|
|
413 # may NOT be an input or htmlout - appended later
|
|
414 tooltestsTabOnly = """
|
|
415 <test>
|
|
416 %(test1Inputs)s
|
|
417 <param name="job_name" value="test1"/>
|
|
418 <param name="runMe" value="$runMe"/>
|
|
419 <output name="output1="%(test1Output)s" ftype="tabular"/>
|
|
420 %(additionalParams)s
|
|
421 </test>
|
|
422 """
|
|
423 tooltestsHTMLOnly = """
|
|
424 <test>
|
|
425 %(test1Inputs)s
|
|
426 <param name="job_name" value="test1"/>
|
|
427 <param name="runMe" value="$runMe"/>
|
|
428 %(additionalParams)s
|
|
429 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="5"/>
|
|
430 </test>
|
|
431 """
|
|
432 tooltestsBoth = """
|
|
433 <test>
|
|
434 %(test1Inputs)s
|
|
435 <param name="job_name" value="test1"/>
|
|
436 <param name="runMe" value="$runMe"/>
|
|
437 %(additionalParams)s
|
|
438 <output name="output1" file="%(test1Output)s" ftype="tabular" />
|
|
439 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="10"/>
|
|
440 </test>
|
|
441 """
|
|
442 xdict = {}
|
|
443 xdict['additionalParams'] = ''
|
|
444 xdict['additionalInputs'] = ''
|
|
445 if self.opts.additional_parameters:
|
|
446 if self.opts.edit_additional_parameters: # add to new tool form with default value set to original value
|
9
|
447 xdict['additionalInputs'] = '\n'.join(['<param name="%s" value="%s" label="%s" help="%s" type="%s"/>' % \
|
|
448 (x.split(',')[0],html_escape(x.split(',')[1]),html_escape(x.split(',')[2]),html_escape(x.split(',')[3]), x.split(',')[4]) for x in self.opts.additional_parameters])
|
2
|
449 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
|
450 xdict['requirements'] = ''
|
|
451 if self.opts.make_HTML:
|
|
452 if self.opts.include_dependencies == "yes":
|
|
453 xdict['requirements'] = protorequirements
|
|
454 xdict['tool_version'] = self.opts.tool_version
|
|
455 xdict['test1HTML'] = self.test1HTML
|
|
456 xdict['test1Output'] = self.test1Output
|
|
457 xdict['test1Inputs'] = self.test1Inputs
|
|
458 if self.opts.make_HTML and self.opts.output_tab:
|
|
459 xdict['tooltests'] = tooltestsBoth % xdict
|
|
460 elif self.opts.make_HTML:
|
|
461 xdict['tooltests'] = tooltestsHTMLOnly % xdict
|
|
462 else:
|
|
463 xdict['tooltests'] = tooltestsTabOnly % xdict
|
|
464 xdict['script'] = self.escapedScript
|
|
465 # configfile is least painful way to embed script to avoid external dependencies
|
|
466 # but requires escaping of <, > and $ to avoid Mako parsing
|
|
467 if self.opts.help_text:
|
|
468 helptext = open(self.opts.help_text,'r').readlines()
|
|
469 helptext = [html_escape(x) for x in helptext] # must html escape here too - thanks to Marius van den Beek
|
|
470 xdict['help'] = ''.join([x for x in helptext])
|
|
471 else:
|
|
472 xdict['help'] = 'Please ask the tool author (%s) for help as none was supplied at tool generation\n' % (self.opts.user_email)
|
|
473 coda = ['**Script**','Pressing execute will run the following code over your input file and generate some outputs in your history::']
|
|
474 coda.append('\n')
|
|
475 coda.append(self.indentedScript)
|
|
476 coda.append('\n**Attribution**\nThis Galaxy tool was created by %s at %s\nusing the Galaxy Tool Factory.\n' % (self.opts.user_email,timenow()))
|
|
477 coda.append('See %s for details of that project' % (toolFactoryURL))
|
|
478 coda.append('Please cite: Creating re-usable tools from scripts: The Galaxy Tool Factory. Ross Lazarus; Antony Kaspi; Mark Ziemann; The Galaxy Team. ')
|
|
479 coda.append('Bioinformatics 2012; doi: 10.1093/bioinformatics/bts573\n')
|
|
480 xdict['help'] = '%s\n%s' % (xdict['help'],'\n'.join(coda))
|
|
481 if self.opts.tool_desc:
|
|
482 xdict['tooldesc'] = '<description>%s</description>' % self.opts.tool_desc
|
|
483 else:
|
|
484 xdict['tooldesc'] = ''
|
|
485 xdict['command_outputs'] = ''
|
|
486 xdict['outputs'] = ''
|
2
|
487 if self.opts.input_tab:
|
0
|
488 cins = ['\n',]
|
2
|
489 cins.append('--input_formats %s' % self.opts.input_formats)
|
0
|
490 cins.append('#for intab in $input1:')
|
2
|
491 cins.append('--input_tab "${intab},${intab.name}"')
|
0
|
492 cins.append('#end for\n')
|
|
493 xdict['command_inputs'] = '\n'.join(cins)
|
|
494 xdict['inputs'] = '''<param name="input_tab" multiple="true" type="data" format="%s" label="Select one or more %s input files from your history"
|
|
495 help="Multiple inputs may be selected assuming the script can deal with them..."/> \n''' % (self.inputFormats,self.inputFormats)
|
|
496 else:
|
|
497 xdict['command_inputs'] = '' # assume no input - eg a random data generator
|
|
498 xdict['inputs'] = ''
|
|
499 if (len(self.opts.additional_parameters) > 0):
|
|
500 cins = ['\n',]
|
|
501 for params in self.opts.additional_parameters:
|
|
502 psplit = params.split(',') # name,value...
|
2
|
503 psplit[3] = html_escape(psplit[3])
|
|
504 if self.opts.edit_additional_parameters:
|
|
505 psplit[1] = '$%s' % psplit[0] # replace with form value
|
|
506 else:
|
|
507 psplit[1] = html_escape(psplit[1]) # leave prespecified value
|
|
508 cins.append('--additional_parameters """%s"""' % ','.join(psplit))
|
0
|
509 xdict['command_inputs'] = '%s\n%s' % (xdict['command_inputs'],'\n'.join(cins))
|
|
510 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
|
|
511 xdict['toolname'] = self.toolname
|
|
512 xdict['toolid'] = self.toolid
|
|
513 xdict['interpreter'] = self.opts.interpreter
|
|
514 xdict['scriptname'] = self.sfile
|
|
515 if self.opts.make_HTML:
|
|
516 xdict['command_outputs'] += ' --output_dir "$html_file.files_path" --output_html "$html_file" --make_HTML "yes"'
|
|
517 xdict['outputs'] += ' <data format="html" name="html_file" label="${job_name}.html"/>\n'
|
|
518 else:
|
|
519 xdict['command_outputs'] += ' --output_dir "./"'
|
|
520 if self.opts.output_tab:
|
3
|
521 xdict['command_outputs'] += ' --output_tab "$output1"'
|
0
|
522 xdict['outputs'] += ' <data format="%s" name="output1" label="${job_name}"/>\n' % self.outFormats
|
|
523 xdict['command'] = newCommand % xdict
|
|
524 if self.opts.citations:
|
|
525 citationstext = open(self.opts.citations,'r').read()
|
|
526 citation_tuples = parse_citations(citationstext)
|
|
527 citations_xml = ""
|
|
528 for citation_type, citation_content in citation_tuples:
|
|
529 citation_xml = """<citation type="%s">%s</citation>""" % (citation_type, html_escape(citation_content))
|
|
530 citations_xml += citation_xml
|
|
531 xdict['citations'] = citations_xml
|
|
532 else:
|
|
533 xdict['citations'] = ""
|
|
534 xmls = newXML % xdict
|
|
535 xf = open(self.xmlfile,'w')
|
|
536 xf.write(xmls)
|
|
537 xf.write('\n')
|
|
538 xf.close()
|
|
539 # ready for the tarball
|
|
540
|
|
541
|
|
542 def makeTooltar(self):
|
|
543 """
|
|
544 a tool is a gz tarball with eg
|
|
545 /toolname/tool.xml /toolname/tool.py /toolname/test-data/test1_in.foo ...
|
|
546 """
|
|
547 retval = self.run()
|
|
548 if retval:
|
|
549 print >> sys.stderr,'## Run failed. Cannot build yet. Please fix and retry'
|
|
550 sys.exit(1)
|
|
551 tdir = self.toolname
|
|
552 os.mkdir(tdir)
|
|
553 self.makeXML()
|
2
|
554 if self.opts.help_text:
|
|
555 hlp = open(self.opts.help_text,'r').read()
|
|
556 else:
|
|
557 hlp = 'Please ask the tool author for help as none was supplied at tool generation\n'
|
|
558 if self.opts.include_dependencies == "yes":
|
|
559 tooldepcontent = toolhtmldepskel % hlp
|
|
560 else:
|
|
561 tooldepcontent = emptytoolhtmldepskel % hlp
|
|
562 depf = open(os.path.join(tdir,'tool_dependencies.xml'),'w')
|
|
563 depf.write(tooldepcontent)
|
|
564 depf.write('\n')
|
|
565 depf.close()
|
|
566 if self.opts.input_tab: # no reproducible test otherwise? TODO: maybe..
|
0
|
567 testdir = os.path.join(tdir,'test-data')
|
|
568 os.mkdir(testdir) # make tests directory
|
|
569 for i,intab in enumerate(self.opts.input_tab):
|
|
570 si = self.opts.input_tab[i]
|
|
571 if si.find(',') <> -1:
|
|
572 s = si.split(',')[0]
|
|
573 si = s
|
|
574 dest = os.path.join(testdir,os.path.basename(si))
|
|
575 if si <> dest:
|
|
576 shutil.copyfile(si,dest)
|
2
|
577 if self.opts.output_tab:
|
0
|
578 shutil.copyfile(self.opts.output_tab,os.path.join(testdir,self.test1Output))
|
|
579 if self.opts.make_HTML:
|
|
580 shutil.copyfile(self.opts.output_html,os.path.join(testdir,self.test1HTML))
|
|
581 if self.opts.output_dir:
|
|
582 shutil.copyfile(self.tlog,os.path.join(testdir,'test1_out.log'))
|
|
583 outpif = '%s.py' % self.toolname # new name
|
|
584 outpiname = os.path.join(tdir,outpif) # path for the tool tarball
|
|
585 pyin = os.path.basename(self.pyfile) # our name - we rewrite ourselves (TM)
|
|
586 notes = ['# %s - a self annotated version of %s generated by running %s\n' % (outpiname,pyin,pyin),]
|
|
587 notes.append('# to make a new Galaxy tool called %s\n' % self.toolname)
|
|
588 notes.append('# User %s at %s\n' % (self.opts.user_email,timenow()))
|
|
589 pi = open(self.pyfile,'r').readlines() # our code becomes new tool wrapper (!) - first Galaxy worm
|
|
590 notes += pi
|
|
591 outpi = open(outpiname,'w')
|
|
592 outpi.write(''.join(notes))
|
|
593 outpi.write('\n')
|
|
594 outpi.close()
|
|
595 stname = os.path.join(tdir,self.sfile)
|
|
596 if not os.path.exists(stname):
|
|
597 shutil.copyfile(self.sfile, stname)
|
|
598 xtname = os.path.join(tdir,self.xmlfile)
|
|
599 if not os.path.exists(xtname):
|
|
600 shutil.copyfile(self.xmlfile,xtname)
|
|
601 tarpath = "%s.tar.gz" % self.toolname
|
|
602 tar = tarfile.open(tarpath, "w:gz")
|
|
603 tar.add(tdir,arcname='%s' % self.toolname)
|
|
604 tar.close()
|
|
605 shutil.copyfile(tarpath,self.opts.new_tool)
|
|
606 shutil.rmtree(tdir)
|
|
607 ## TODO: replace with optional direct upload to local toolshed?
|
|
608 return retval
|
|
609
|
|
610
|
|
611 def compressPDF(self,inpdf=None,thumbformat='png'):
|
|
612 """need absolute path to pdf
|
|
613 note that GS gets confoozled if no $TMP or $TEMP
|
|
614 so we set it
|
|
615 """
|
|
616 assert os.path.isfile(inpdf), "## Input %s supplied to %s compressPDF not found" % (inpdf,self.myName)
|
|
617 hlog = os.path.join(self.opts.output_dir,"compress_%s.txt" % os.path.basename(inpdf))
|
|
618 sto = open(hlog,'a')
|
|
619 our_env = os.environ.copy()
|
|
620 our_tmp = our_env.get('TMP',None)
|
|
621 if not our_tmp:
|
|
622 our_tmp = our_env.get('TEMP',None)
|
|
623 if not (our_tmp and os.path.exists(our_tmp)):
|
|
624 newtmp = os.path.join(self.opts.output_dir,'tmp')
|
|
625 try:
|
|
626 os.mkdir(newtmp)
|
|
627 except:
|
|
628 sto.write('## WARNING - cannot make %s - it may exist or permissions need fixing\n' % newtmp)
|
|
629 our_env['TEMP'] = newtmp
|
|
630 if not self.temp_warned:
|
|
631 sto.write('## WARNING - no $TMP or $TEMP!!! Please fix - using %s temporarily\n' % newtmp)
|
|
632 self.temp_warned = True
|
|
633 outpdf = '%s_compressed' % inpdf
|
|
634 cl = ["gs", "-sDEVICE=pdfwrite", "-dNOPAUSE", "-dUseCIEColor", "-dBATCH","-dPDFSETTINGS=/printer", "-sOutputFile=%s" % outpdf,inpdf]
|
|
635 x = subprocess.Popen(cl,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
|
|
636 retval1 = x.wait()
|
|
637 sto.close()
|
|
638 if retval1 == 0:
|
|
639 os.unlink(inpdf)
|
|
640 shutil.move(outpdf,inpdf)
|
|
641 os.unlink(hlog)
|
|
642 hlog = os.path.join(self.opts.output_dir,"thumbnail_%s.txt" % os.path.basename(inpdf))
|
|
643 sto = open(hlog,'w')
|
|
644 outpng = '%s.%s' % (os.path.splitext(inpdf)[0],thumbformat)
|
|
645 if self.useGM:
|
|
646 cl2 = ['gm', 'convert', inpdf, outpng]
|
|
647 else: # assume imagemagick
|
|
648 cl2 = ['convert', inpdf, outpng]
|
|
649 x = subprocess.Popen(cl2,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
|
|
650 retval2 = x.wait()
|
|
651 sto.close()
|
|
652 if retval2 == 0:
|
|
653 os.unlink(hlog)
|
|
654 retval = retval1 or retval2
|
|
655 return retval
|
|
656
|
|
657
|
|
658 def getfSize(self,fpath,outpath):
|
|
659 """
|
|
660 format a nice file size string
|
|
661 """
|
|
662 size = ''
|
|
663 fp = os.path.join(outpath,fpath)
|
|
664 if os.path.isfile(fp):
|
|
665 size = '0 B'
|
|
666 n = float(os.path.getsize(fp))
|
|
667 if n > 2**20:
|
|
668 size = '%1.1f MB' % (n/2**20)
|
|
669 elif n > 2**10:
|
|
670 size = '%1.1f KB' % (n/2**10)
|
|
671 elif n > 0:
|
|
672 size = '%d B' % (int(n))
|
|
673 return size
|
|
674
|
|
675 def makeHtml(self):
|
|
676 """ Create an HTML file content to list all the artifacts found in the output_dir
|
|
677 """
|
|
678
|
|
679 galhtmlprefix = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
680 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
|
681 <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
|
682 <meta name="generator" content="Galaxy %s tool output - see http://g2.trac.bx.psu.edu/" />
|
|
683 <title></title>
|
|
684 <link rel="stylesheet" href="/static/style/base.css" type="text/css" />
|
|
685 </head>
|
|
686 <body>
|
|
687 <div class="toolFormBody">
|
|
688 """
|
|
689 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/>"""
|
|
690 galhtmlpostfix = """</div></body></html>\n"""
|
|
691
|
|
692 flist = os.listdir(self.opts.output_dir)
|
|
693 flist = [x for x in flist if x <> 'Rplots.pdf']
|
|
694 flist.sort()
|
|
695 html = []
|
|
696 html.append(galhtmlprefix % progname)
|
|
697 html.append('<div class="infomessage">Galaxy Tool "%s" run at %s</div><br/>' % (self.toolname,timenow()))
|
|
698 fhtml = []
|
|
699 if len(flist) > 0:
|
|
700 logfiles = [x for x in flist if x.lower().endswith('.log')] # log file names determine sections
|
|
701 logfiles.sort()
|
|
702 logfiles = [x for x in logfiles if os.path.abspath(x) <> os.path.abspath(self.tlog)]
|
|
703 logfiles.append(os.path.abspath(self.tlog)) # make it the last one
|
|
704 pdflist = []
|
|
705 npdf = len([x for x in flist if os.path.splitext(x)[-1].lower() == '.pdf'])
|
|
706 for rownum,fname in enumerate(flist):
|
|
707 dname,e = os.path.splitext(fname)
|
|
708 sfsize = self.getfSize(fname,self.opts.output_dir)
|
|
709 if e.lower() == '.pdf' : # compress and make a thumbnail
|
|
710 thumb = '%s.%s' % (dname,self.thumbformat)
|
|
711 pdff = os.path.join(self.opts.output_dir,fname)
|
|
712 retval = self.compressPDF(inpdf=pdff,thumbformat=self.thumbformat)
|
|
713 if retval == 0:
|
|
714 pdflist.append((fname,thumb))
|
|
715 else:
|
|
716 pdflist.append((fname,fname))
|
|
717 if (rownum+1) % 2 == 0:
|
|
718 fhtml.append('<tr class="odd_row"><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname,fname,sfsize))
|
|
719 else:
|
|
720 fhtml.append('<tr><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname,fname,sfsize))
|
|
721 for logfname in logfiles: # expect at least tlog - if more
|
|
722 if os.path.abspath(logfname) == os.path.abspath(self.tlog): # handled later
|
|
723 sectionname = 'All tool run'
|
|
724 if (len(logfiles) > 1):
|
|
725 sectionname = 'Other'
|
|
726 ourpdfs = pdflist
|
|
727 else:
|
|
728 realname = os.path.basename(logfname)
|
|
729 sectionname = os.path.splitext(realname)[0].split('_')[0] # break in case _ added to log
|
|
730 ourpdfs = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] == sectionname]
|
|
731 pdflist = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] <> sectionname] # remove
|
|
732 nacross = 1
|
|
733 npdf = len(ourpdfs)
|
|
734
|
|
735 if npdf > 0:
|
|
736 nacross = math.sqrt(npdf) ## int(round(math.log(npdf,2)))
|
|
737 if int(nacross)**2 != npdf:
|
|
738 nacross += 1
|
|
739 nacross = int(nacross)
|
|
740 width = min(400,int(1200/nacross))
|
|
741 html.append('<div class="toolFormTitle">%s images and outputs</div>' % sectionname)
|
|
742 html.append('(Click on a thumbnail image to download the corresponding original PDF image)<br/>')
|
|
743 ntogo = nacross # counter for table row padding with empty cells
|
|
744 html.append('<div><table class="simple" cellpadding="2" cellspacing="2">\n<tr>')
|
|
745 for i,paths in enumerate(ourpdfs):
|
|
746 fname,thumb = paths
|
|
747 s= """<td><a href="%s"><img src="%s" title="Click to download a PDF of %s" hspace="5" width="%d"
|
|
748 alt="Image called %s"/></a></td>\n""" % (fname,thumb,fname,width,fname)
|
|
749 if ((i+1) % nacross == 0):
|
|
750 s += '</tr>\n'
|
|
751 ntogo = 0
|
|
752 if i < (npdf - 1): # more to come
|
|
753 s += '<tr>'
|
|
754 ntogo = nacross
|
|
755 else:
|
|
756 ntogo -= 1
|
|
757 html.append(s)
|
|
758 if html[-1].strip().endswith('</tr>'):
|
|
759 html.append('</table></div>\n')
|
|
760 else:
|
|
761 if ntogo > 0: # pad
|
|
762 html.append('<td> </td>'*ntogo)
|
|
763 html.append('</tr></table></div>\n')
|
|
764 logt = open(logfname,'r').readlines()
|
|
765 logtext = [x for x in logt if x.strip() > '']
|
|
766 html.append('<div class="toolFormTitle">%s log output</div>' % sectionname)
|
|
767 if len(logtext) > 1:
|
|
768 html.append('\n<pre>\n')
|
|
769 html += logtext
|
|
770 html.append('\n</pre>\n')
|
|
771 else:
|
|
772 html.append('%s is empty<br/>' % logfname)
|
|
773 if len(fhtml) > 0:
|
|
774 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')
|
|
775 fhtml.append('</table></div><br/>')
|
|
776 html.append('<div class="toolFormTitle">All output files available for downloading</div>\n')
|
|
777 html += fhtml # add all non-pdf files to the end of the display
|
|
778 else:
|
|
779 html.append('<div class="warningmessagelarge">### Error - %s returned no files - please confirm that parameters are sane</div>' % self.opts.interpreter)
|
|
780 html.append(galhtmlpostfix)
|
|
781 htmlf = file(self.opts.output_html,'w')
|
|
782 htmlf.write('\n'.join(html))
|
|
783 htmlf.write('\n')
|
|
784 htmlf.close()
|
|
785 self.html = html
|
|
786
|
|
787
|
9
|
788
|
0
|
789 def run(self):
|
|
790 """
|
|
791 scripts must be small enough not to fill the pipe!
|
|
792 """
|
9
|
793 if self.opts.envshpath <> 'system':
|
|
794 shell_source(self.opts.envshpath)
|
0
|
795 if self.treatbashSpecial and self.opts.interpreter in ['bash','sh']:
|
|
796 retval = self.runBash()
|
|
797 else:
|
|
798 if self.opts.output_dir:
|
|
799 ste = open(self.elog,'w')
|
|
800 sto = open(self.tlog,'w')
|
|
801 sto.write('## Toolfactory generated command line = %s\n' % ' '.join(self.cl))
|
|
802 sto.flush()
|
9
|
803 p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=ste,cwd=self.opts.output_dir)
|
0
|
804 else:
|
9
|
805 p = subprocess.Popen(self.cl,shell=False)
|
0
|
806 retval = p.wait()
|
|
807 if self.opts.output_dir:
|
|
808 sto.close()
|
|
809 ste.close()
|
|
810 err = open(self.elog,'r').readlines()
|
|
811 if retval <> 0 and err: # problem
|
|
812 print >> sys.stderr,err
|
|
813 if self.opts.make_HTML:
|
|
814 self.makeHtml()
|
|
815 return retval
|
|
816
|
|
817 def runBash(self):
|
|
818 """
|
|
819 cannot use - for bash so use self.sfile
|
|
820 """
|
|
821 if self.opts.output_dir:
|
|
822 s = '## Toolfactory generated command line = %s\n' % ' '.join(self.cl)
|
|
823 sto = open(self.tlog,'w')
|
|
824 sto.write(s)
|
|
825 sto.flush()
|
|
826 p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=sto,cwd=self.opts.output_dir)
|
|
827 else:
|
|
828 p = subprocess.Popen(self.cl,shell=False)
|
|
829 retval = p.wait()
|
|
830 if self.opts.output_dir:
|
|
831 sto.close()
|
|
832 if self.opts.make_HTML:
|
|
833 self.makeHtml()
|
|
834 return retval
|
|
835
|
|
836
|
|
837 def main():
|
|
838 u = """
|
|
839 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
|
|
840 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath" --tool_name "foo" --interpreter "Rscript"
|
|
841 </command>
|
|
842 """
|
|
843 op = optparse.OptionParser()
|
|
844 a = op.add_option
|
|
845 a('--script_path',default=None)
|
|
846 a('--tool_name',default=None)
|
|
847 a('--interpreter',default=None)
|
|
848 a('--output_dir',default='./')
|
|
849 a('--output_html',default=None)
|
|
850 a('--input_tab',default=[], action="append") # these are "galaxypath,metadataname" pairs
|
|
851 a("--input_formats",default="tabular")
|
|
852 a('--output_tab',default=None)
|
|
853 a('--output_format',default='tabular')
|
|
854 a('--user_email',default='Unknown')
|
|
855 a('--bad_user',default=None)
|
|
856 a('--make_Tool',default=None)
|
|
857 a('--make_HTML',default=None)
|
|
858 a('--help_text',default=None)
|
|
859 a('--tool_desc',default=None)
|
|
860 a('--new_tool',default=None)
|
|
861 a('--tool_version',default=None)
|
|
862 a('--include_dependencies',default="yes")
|
|
863 a('--citations',default=None)
|
|
864 a('--additional_parameters', dest='additional_parameters', action='append', default=[])
|
|
865 a('--edit_additional_parameters', action="store_true", default=False)
|
9
|
866 a('--envshpath',default="system")
|
0
|
867 opts, args = op.parse_args()
|
|
868 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)
|
|
869 assert opts.tool_name,'## Tool Factory expects a tool name - eg --tool_name=DESeq'
|
|
870 assert opts.interpreter,'## Tool Factory wrapper expects an interpreter - eg --interpreter=Rscript'
|
|
871 assert os.path.isfile(opts.script_path),'## Tool Factory wrapper expects a script path - eg --script_path=foo.R'
|
|
872 if opts.output_dir:
|
|
873 try:
|
|
874 os.makedirs(opts.output_dir)
|
|
875 except:
|
|
876 pass
|
|
877 opts.input_tab = [x.replace('"','').replace("'",'') for x in opts.input_tab]
|
|
878 for i,x in enumerate(opts.additional_parameters): # remove quotes we need to deal with spaces in CL params
|
|
879 opts.additional_parameters[i] = opts.additional_parameters[i].replace('"','')
|
|
880 r = ScriptRunner(opts)
|
|
881 if opts.make_Tool:
|
|
882 retcode = r.makeTooltar()
|
|
883 else:
|
|
884 retcode = r.run()
|
|
885 os.unlink(r.sfile)
|
|
886 if retcode:
|
|
887 sys.exit(retcode) # indicate failure to job runner
|
|
888
|
|
889
|
|
890 if __name__ == "__main__":
|
|
891 main()
|
|
892
|
|
893
|