Skip to content
This repository was archived by the owner on Nov 10, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 60 additions & 33 deletions bips/service/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
from cherrypy import expose
import numpy as np

import lg_authority

from ..workflows import get_workflows, get_workflow
from .demos.dicomconvert import unzip_and_extract

MEDIA_DIR = os.path.join(os.path.dirname(__file__), 'scripts')
FILE_DIR = os.path.join(os.getcwd(), 'files')
Expand Down Expand Up @@ -43,7 +46,10 @@ def default(self, o):
except TypeError:
return ""

@lg_authority.groups('auth')
class BIPS(object):
auth = lg_authority.AuthRoot()

def __init__(self, *args, **kwargs):
tags = []
mapper = {}
Expand Down Expand Up @@ -101,17 +107,6 @@ def tags(self, query):
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps(tags)

"""
msg = ["<h2>Welcome to BIPS</h2>"]
msg.append('<ul>')
for wf, value in get_workflows():
msg += [('<li><a href="info?uuid=%s">%s</a> <a href="configure'
'?uuid=%s">Configure</a> %s</li>') % (wf, wf, wf,
value['object'].help.split('\n')[1])]
msg.append('</li>')
return '\n'.join(msg)
"""

@expose
def info(self, uuid):
wf = get_workflow(uuid)
Expand All @@ -122,24 +117,7 @@ def info(self, uuid):
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'jsonconfig': json_str, 'workflowconfig': config_str},
cls=MyEncoder)
'''
msg = """

var str = JSON.stringify(%s, null, 2);
$(this).append('<h3>Workflow info</h3>');
console.log($(this));
/*
document.write('<pre>' + syntaxHighlight(str) +'</pre>');
var str2 = JSON.stringify(%s, null, 2);
document.write('<h3>Workflow config</h3>')
document.write('<pre>' + syntaxHighlight(str2) +'</pre>');
document.write('<h3>Workflow graph</h3>')
document.write('<img src="%s" />')
*/
</script>
""" % (json_str, config_str, img_file)
return msg
'''

@expose
def configure(self, uuid):
wf = get_workflow(uuid)
Expand All @@ -151,6 +129,12 @@ def demo(self):
msg = fp.readlines()
return msg

@expose
def demo_convert(self):
with open(os.path.join(MEDIA_DIR, 'demo_convert.html')) as fp:
msg = fp.readlines()
return msg

@expose
def uploadhandler(self, **kwargs):
if 'files[]' not in kwargs:
Expand Down Expand Up @@ -185,15 +169,53 @@ def uploadhandler(self, **kwargs):
else:
out = {}
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps([out])
return json.dumps([[out]])

@expose
def dicomuploadhandler(self, **kwargs):
cherrypy.log('dcmhandler: %s' % str(kwargs))
if 'files[]' not in kwargs:
return
myFile = kwargs['files[]']
outfile = os.path.join(FILE_DIR, myFile.filename)
with open(outfile, 'wb') as fp:
shutil.copyfileobj(myFile.file, fp)
cherrypy.log('Saved file: %s' % outfile)
if os.path.isfile(outfile):
print "getting info: %s" % outfile
info = unzip_and_extract(outfile, FILE_DIR)
os.unlink(outfile)
print info
out = []
for key, value in sorted(info.items()):
info = value
out.append({"index": info['idx'],
"name": info['name'],
"metaname": info['metapath'],
'error': info['err_status'] == 'err',
"size": ' x '.join([str(val) for val in info['size']]),
"url": "%sfiles\/%s" % (url_prefix, info['filepath']),
"metaurl": "%sfiles\/%s" % (url_prefix, info['metapath']),
"delete_url": "%sdeletehandler?file=%s" % (url_prefix, info['filepath']),
"delete_type": "DELETE"
})
out = [out]
else:
out = {}
print 'out', out
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps(out)

@expose
def deletehandler(self, file):
outfile = os.path.join(FILE_DIR, file)
if os.path.isfile(outfile):
cherrypy.log('Deleting file: %s' % outfile)
os.unlink(outfile)
os.unlink(outfile+'.png')
if os.path.exists(outfile + '.png'):
os.unlink(outfile+'.png')
if os.path.exists(outfile + '.json'):
os.unlink(outfile+'.json')

def open_page():
#pass
Expand All @@ -204,7 +226,12 @@ def start_service():
if not os.path.exists(FILE_DIR):
os.mkdir(FILE_DIR)
config = {'/': {'tools.staticdir.on': True,
'tools.staticdir.dir': os.getcwd()},
'tools.staticdir.dir': os.getcwd(),
'tools.lg_authority.on': False,
'tools.lg_authority.site_storage': 'sqlite3',
'tools.lg_authority.site_storage_conf':
{ 'file': os.path.abspath('test.db') }
},
'/css': {'tools.staticdir.on': True,
'tools.staticdir.dir': os.path.join(MEDIA_DIR, 'css')},
'/js': {'tools.staticdir.on': True,
Expand All @@ -218,7 +245,7 @@ def start_service():
'/files': {'tools.staticdir.on': True,
'tools.staticdir.dir': FILE_DIR},
}
#start webservice
# #start webservice
certfile = os.path.join(os.environ['HOME'], 'certinfo')
if os.path.exists(certfile):
cherrypy.log('Loading cert info: %s' % certfile)
Expand Down
1 change: 1 addition & 0 deletions bips/service/demos/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

80 changes: 80 additions & 0 deletions bips/service/demos/dicomconvert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from glob import glob
import os
import string

from tempfile import mkdtemp
from dcmstack import parse_and_stack, NiftiWrapper

def sanitize_path_comp(path_comp):
result = []
for char in path_comp:
if not char in string.letters + string.digits + '-_.':
result.append('_')
else:
result.append(char)
return ''.join(result)

def get_dicom_info(dicom_dir, dest):
"""Return a freesurfer style dicom info generator
"""
fl = sorted(glob(os.path.join(dicom_dir, '*.dcm')))
stack = parse_and_stack(fl, force=True, warn_on_except=True)
info = {}
for key in sorted(stack):
key_fields = key.split('-')
idx = int(key_fields[0])
name = key_fields[1]
stack_object = stack[key]
if not stack_object.error:
size = list(stack_object.get_shape())
if len(size) == 3:
size.append(1)
err_status = 'ok'
out_fn = sanitize_path_comp(key) + '.nii.gz'
out_path = os.path.join(dest, out_fn)
nii = stack_object.to_nifti(embed_meta=True)
nii_wrp = NiftiWrapper(nii)
meta_fn = out_fn + '.json'
meta_path = os.path.join(dest, meta_fn)
with open(meta_path, 'w') as fp:
fp.write(nii_wrp.meta_ext.to_json())
nii.to_filename(out_path)
else:
size = [0, 0, 0, 0]
err_status = 'err'
out_fn = None
meta_fn = None
filepath = out_fn
filename = stack_object._files_info[0][2]
info[idx] = dict(idx=idx, name=name, err_status=err_status,
size=size, filename=filename,
filepath=filepath,
metapath=meta_fn)
size = [str(val) for val in size]
print '\t'.join([str(idx), name, err_status] + size + [filename])
return info

def unzip_and_extract(filename, dest):
outdir = mkdtemp()
if '.tgz' in filename or '.tar.gz' in filename:
import tarfile
bundle = tarfile.open(filename, 'r')
elif '.zip' in filename:
import zipfile
bundle = zipfile.ZipFile(filename, 'r')
else:
raise ValueError('Unknown compression format. Only zip and tar+gzip supported')
bundle.extractall(outdir)
dcmdir = None
print outdir
for r,d,f in os.walk(outdir):
print r
for files in f:
print files
if files.endswith(".dcm"):
dcmdir = r
break
print dcmdir
info = get_dicom_info(dcmdir, dest)
return info

2 changes: 1 addition & 1 deletion bips/service/scripts/cors/postmessage.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<head>
<meta charset="utf-8">
<title>jQuery File Upload Plugin postMessage API</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<script>
Expand Down
10 changes: 7 additions & 3 deletions bips/service/scripts/cors/result.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<!DOCTYPE HTML>
<!--
/*
* jQuery Iframe Transport Plugin Redirect Page 2.0
* jQuery Iframe Transport Plugin Redirect Page 2.0.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
Expand All @@ -16,5 +16,9 @@
<meta charset="utf-8">
<title>jQuery Iframe Transport Plugin Redirect Page</title>
</head>
<body><script>document.body.innerHTML=decodeURIComponent(window.location.search.slice(1));</script></body>
</html>
<body>
<script>
document.body.innerText=document.body.textContent=decodeURIComponent(window.location.search.slice(1));
</script>
</body>
</html>
Loading