Skip to content

Commit

Permalink
Merge pull request #25 from j-frei/master
Browse files Browse the repository at this point in the history
Switch from HTTP to HTTPS
  • Loading branch information
faustomilletari committed Jul 25, 2019
2 parents 1bbec3f + 7736643 commit ecb07c5
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 4 deletions.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ click
tinydb
m2r
sphinxcontrib-googleanalytics
pyOpenSSL
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@
'requests',
'click',
'tinydb',
'pyOpenSSL',
],
)
50 changes: 50 additions & 0 deletions tomaat/examples/simple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import sys, os
# We need to add "tomaat"-directory (../..) to PATH to import the tomaat package
sys.path.append( os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))

from tomaat.server import TomaatService, TomaatApp

import SimpleITK as sitk
import numpy as np

config = {
"name": "Example TOMAAT thresholding app",
"modality": "Example Modality",
"task": "Example Task",
"anatomy": "Example Anatomy",
"description":"Example Description",
"port": 9001,
"announce": False,
"api_key": "",
}

iface_in = [{'type':'volume','destination':'images'}]
iface_out = [{'type':'LabelVolume','field':'images'}]

def preprocess(input):
return {'images':[sitk.ReadImage(input['images'][0])] }

def inference(data):
itk_image = data['images'][0]
image_data = sitk.GetArrayFromImage(itk_image)
treshold = np.mean(image_data)
image_binary = image_data >= treshold
return {
'image_data': image_binary,
'image_old': itk_image,
}

def postprocess(output):
binarized_image = output['image_data'].astype(np.float)
image_new = sitk.GetImageFromArray(binarized_image)
image_new.CopyInformation(output['image_old'])
return {
'images':[image_new]
}


my_app = TomaatApp(preprocess,inference,postprocess)

my_service = TomaatService(config, my_app, iface_in, iface_out)

my_service.run()
36 changes: 36 additions & 0 deletions tomaat/server/makecert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime
from os.path import exists

def create_self_signed_cert(CERT_FILE = "./tomaat.crt",KEY_FILE = "./tomaat.key"):
if not exists(CERT_FILE) or not exists(KEY_FILE):
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096)

# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "US"
cert.get_subject().ST = "TOMAAT"
cert.get_subject().L = "TOMAAT"
cert.get_subject().O = "TOMAAT"
cert.get_subject().OU = "TOMAAT"
cert.get_subject().CN = "*"
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10*365*24*60*60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha256')
cert.sign(k, 'sha1')

# write keys
with open(CERT_FILE, "wb") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
with open(KEY_FILE, "wb") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

if __name__ == "__main__":
create_self_signed_cert(".")
33 changes: 29 additions & 4 deletions tomaat/server/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,36 @@ def __init__(self, config, app, input_interface, output_interface):

self.input_interface = input_interface
self.output_interface = output_interface
if not "cert_path" in self.config.keys():
self.config["cert_path"] = "./tomaat_cert"

cert_private = self.config["cert_path"] + ".key"
cert_public = self.config["cert_path"] + ".crt"

if not os.path.exists(cert_private) or not os.path.exists(cert_public):
from . import makecert
makecert.create_self_signed_cert(cert_public,cert_private)

# setup https
endpoint_specification = "ssl:{}".format(self.config['port'])
endpoint_specification += ":certKey="+cert_public
endpoint_specification += ":privateKey="+cert_private

self.config['endpoint_specification'] = endpoint_specification


@klein_app.route('/announcePoint', methods=['GET'])
def announcePoint(self, request):
try: ap = self.config['announcement']
except: ap = ""
return json.dumps({"announced_at":ap})

@klein_app.route('/interface', methods=['GET'])
def interface(self, request):
request.setHeader('Access-Control-Allow-Origin', '*')
request.setHeader('Access-Control-Allow-Methods', 'GET')
request.setHeader('Access-Control-Allow-Headers', '*')
request.setHeader('Access-Control-Max-Age', 2520) # 42 hours
request.setHeader('Access-Control-Max-Age', '2520') # 42 hours

return json.dumps(self.input_interface)

Expand All @@ -134,7 +157,7 @@ def predict(self, request):
request.setHeader('Access-Control-Allow-Origin', '*')
request.setHeader('Access-Control-Allow-Methods', 'POST')
request.setHeader('Access-Control-Allow-Headers', '*')
request.setHeader('Access-Control-Max-Age', 2520) # 42 hours
request.setHeader('Access-Control-Max-Age', '520') # 42 hours

logger.info('predicting...')

Expand Down Expand Up @@ -391,7 +414,9 @@ def received_data_handler(self, request):
return json.dumps(response)

def run(self):
self.klein_app.run(port=self.config['port'], host='0.0.0.0')
endpoint_specification = self.config.get("endpoint_specification",None)

self.klein_app.run(port=self.config['port'], host='0.0.0.0', endpoint_description=endpoint_specification)
reactor.run()


Expand Down Expand Up @@ -527,4 +552,4 @@ def responses_data_handler(self, request):
response = [{'type': 'DelayedResponse', 'request_id': req_id}]


return json.dumps(response)
return json.dumps(response)

0 comments on commit ecb07c5

Please sign in to comment.