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