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