client_api2.py 31.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import cgi
import ssl
import slicer
import requests

try:
    # Python3
    # noinspection PyUnresolvedReferences
    import http.client as httplib
    # noinspection PyUnresolvedReferences,PyCompatibility
    from urllib.parse import quote_plus
    # noinspection PyUnresolvedReferences,PyCompatibility
    from urllib.parse import urlparse
except ImportError as e:
    # Python2
    # noinspection PyUnresolvedReferences
    import httplib
    # noinspection PyUnresolvedReferences
    from urllib import quote_plus
    # noinspection PyUnresolvedReferences
    from urlparse import urlparse

import json
import logging
import mimetypes
import os
import sys
import tempfile

import SimpleITK
import numpy as np


class AIAAClient:
    """
    The AIAAClient object is constructed with the server information

    :param server_url: AIAA Server URL (example: 'http://0.0.0.0:5000')
    """

    def __init__(self, server_url='http://0.0.0.0:5000'):
        self._server_url = server_url

    def get_server_url(self):
        """
        Get AIAA Server URL

        :return: returns AIAA Server URL
        """
        return self._server_url

    def set_server_url(self, server_url):
        """
        Update AIAA Server URL

        :param: server_url: valid url for AIAA server (example: 'http://0.0.0.0:5000')
        """
        self._server_url = server_url

    def create_session(self, image_in, expiry=0):
        """
        Create New Session

        :param image_in: valid image which will be stored as part of the new session
        :param expiry: expiry in seconds.  min(AIAASessionExpiry, expiry) will be selected by AIAA
        :return: returns json containing **session_id** and any other details from server

        valid *session_id* from result can be used for future reference
        """
        logger = logging.getLogger(__name__)
        logger.debug('Preparing for Create Session Action')

        selector = '/session/?expiry=' + str(expiry)
        fields = {}
        files = {'image': image_in}

        status, response, _ = AIAAUtils.http_multipart('PUT', self._server_url, selector, fields, files)
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, response))

        response = response.decode('utf-8') if isinstance(response, bytes) else response
        logger.debug('Response: {}'.format(response))
        return json.loads(response)

    def get_session(self, session_id):
        """
        Get Session Info

        :param session_id: valid session id
        :return: returns json containing session details if session is valid; otherwise None
        """
        logger = logging.getLogger(__name__)
        logger.debug('Fetching Session Details')

        if session_id is None:
            return None

        selector = '/session/' + AIAAUtils.urllib_quote_plus(session_id)
        status, response = AIAAUtils.http_method('GET', self._server_url, selector)
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, response))

        response = response.decode('utf-8') if isinstance(response, bytes) else response
        logger.debug('Response: {}'.format(response))
        return json.loads(response)

    def close_session(self, session_id):
        """
        Close an existing session

        :param session_id: valid session id
        :return: returns True if a session is closed, else False
        """
        logger = logging.getLogger(__name__)
        logger.debug('Fetching Session Details')

        if session_id is None:
            return False

        selector = '/session/' + AIAAUtils.urllib_quote_plus(session_id)

        status, response = AIAAUtils.http_method('DELETE', self._server_url, selector)
        logger.debug('Response: {}'.format(response))
        return status == 200

    def model(self, model):
        """
        Get the model details

        :param model: A valid Model Name which exists in AIAA Server
        :return: returns json containing the model details
        """
        logger = logging.getLogger(__name__)
        logger.debug('Fetching Model Details')

        selector = '/v1/models'
        if model:
            selector += '?model=' + AIAAUtils.urllib_quote_plus(model)

        status, response = AIAAUtils.http_method('GET', self._server_url, selector)
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, response))

        response = response.decode('utf-8') if isinstance(response, bytes) else response
        logger.debug('Response: {}'.format(response))
        return json.loads(response)

    def model_list(self, label=None):
        """
        Get the current supported model list

        :param label: Filter models which are matching the label
        :return: returns json containing list of models and details
        """
        logger = logging.getLogger(__name__)
        logger.debug('Fetching Model Details')

        selector = '/v1/models'
        if label is not None and len(label) > 0:
            selector += '?label=' + AIAAUtils.urllib_quote_plus(label)

        status, response = AIAAUtils.http_method('GET', self._server_url, selector)
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, response))

        response = response.decode('utf-8') if isinstance(response, bytes) else response

        logger.debug('Response: {}'.format(response))
        return json.loads(response)

    def segmentation(self, model, image_in, image_out, session_id=None):
        """
        2D/3D image segmentation using segmentation method

        :param model: model name according to the output of model_list()
        :param image_in: input 2D/3D image file name
        :param image_out: output mask will be stored
        :param session_id: if session id is provided (not None) then *image_in* will be ignored
        :return: returns json containing extreme points for the segmentation mask and other info

        Output 2D/3D binary mask will be saved to the specified file;  Throws AIAAException in case of Error
        """
        logger = logging.getLogger(__name__)
        logger.debug('Preparing for Segmentation Action')

        selector = '/v1/segmentation?model=' + AIAAUtils.urllib_quote_plus(model)
        if session_id:
            selector += '&session_id=' + AIAAUtils.urllib_quote_plus(session_id)

        in_fields = {'params': '{}'}
        in_files = {'datapoint': image_in} if not session_id else {}

        logger.debug('Using Selector: {}'.format(selector))
        logger.debug('Using Fields: {}'.format(in_fields))
        logger.debug('Using Files: {}'.format(in_files))

        status, form, files = AIAAUtils.http_multipart('POST', self._server_url, selector, in_fields, in_files)
        if status == 440:
            raise AIAAException(AIAAError.SESSION_EXPIRED, 'Session Expired')
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, form))

        form = json.loads(form) if isinstance(form, str) else form
        params = form.get('params')
        if params is None:  # v1 backward compatibility
            points = json.loads(form.get('points'))
            params = {'points': (json.loads(points) if isinstance(points, str) else points)}
        params = json.loads(params) if isinstance(params, str) else params

        AIAAUtils.save_result(files, image_out)
        return params

    def dextr3d(self, model, point_set, image_in, image_out, pad=20, roi_size='128x128x128',
                pre_process=True,
                session_id=None):
        """
        3D image annotation using DEXTR3D method

        :param model: model name according to the output of model_list()
        :param point_set: point set json containing the extreme points' indices
        :param image_in: input 3D image file name
        :param image_out: output mask will be stored
        :param pad: padding size (default is 20)
        :param roi_size:  image resize value (default is 128x128x128)
        :param pre_process: pre-process (crop) input volume at client side for DEXTR3D action
        :param session_id: if *session_id* is not None and *pre_process* is False then *image_in* will be ignored


        Output 3D binary mask will be saved to the specified file;  Throws AIAAException in case of Error
        """
        logger = logging.getLogger(__name__)
        logger.debug('Preparing for Annotation/Dextr3D Action')

        # Pre Process
        if pre_process:
            cropped_file = tempfile.NamedTemporaryFile(suffix='.nii.gz').name
            points, crop = AIAAUtils.image_pre_process(image_in, cropped_file, point_set, pad, roi_size)
        else:
            cropped_file = image_in
            points = point_set
            crop = None

        selector = '/v1/dextr3d?model=' + AIAAUtils.urllib_quote_plus(model)
        use_session_input = session_id and pre_process is False
        if use_session_input:
            selector += '&session_id=' + AIAAUtils.urllib_quote_plus(session_id)

        in_fields = {'params': json.dumps({'points': points})}
        in_files = {'datapoint': cropped_file} if not use_session_input else {}

        logger.debug('Using Selector: {}'.format(selector))
        logger.debug('Using Fields: {}'.format(in_fields))
        logger.debug('Using Files: {}'.format(in_files))

        status, form, files = AIAAUtils.http_multipart('POST', self._server_url, selector, in_fields, in_files)
        if status == 440:
            raise AIAAException(AIAAError.SESSION_EXPIRED, 'Session Expired')
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, form))

        form = json.loads(form) if isinstance(form, str) else form
        params = form.get('params')
        params = json.loads(params) if isinstance(params, str) else params

        # Post Process
        if pre_process:
            os.unlink(cropped_file)

            cropped_out_file = tempfile.NamedTemporaryFile(suffix='.nii.gz').name
            AIAAUtils.save_result(files, cropped_out_file)
            AIAAUtils.image_post_processing(cropped_out_file, image_out, crop, image_in)

            os.unlink(cropped_out_file)
        else:
            AIAAUtils.save_result(files, image_out)
        return params

    def deepgrow(self, model, foreground, background, image_in, image_out, current_point=None, spatial_size=None,
                 session_id=None):
        """
        2D/3D image annotation using DeepGrow method

        :param model: model name according to the output of model_list()
        :param foreground: foreground (+ve) clicks/points
        :param background: background (-ve) clicks/points
        :param image_in: input 2D/3D image file name
        :param image_out: output mask will be stored
        :param session_id: if session id is provided (not None) then *image_in* will be ignored
        :param current_point: newest click
        :param spatial_size: spatial size if supported by model

        Output 2D/3D binary mask will be saved to the specified file;  Throws AIAAException in case of Error
        """
        logger = logging.getLogger(__name__)
        logger.debug('Preparing for DeepGrow Action')

        selector = '/v1/deepgrow?model=' + AIAAUtils.urllib_quote_plus(model)
        if session_id:
            selector += '&session_id=' + AIAAUtils.urllib_quote_plus(session_id)

        params = {
            'foreground': foreground,
            'background': background,
        }
        if current_point and len(current_point):
            params['current_point'] = current_point
        if spatial_size and len(spatial_size):
            params['spatial_size'] = spatial_size
        in_fields = {'params': json.dumps(params)}
        in_files = {'datapoint': image_in} if not session_id else {}

        logger.debug('Using Selector: {}'.format(selector))
        logger.debug('Using Fields: {}'.format(in_fields))
        logger.debug('Using Files: {}'.format(in_files))

        status, form, files = AIAAUtils.http_multipart('POST', self._server_url, selector, in_fields, in_files)
        if status == 440:
            raise AIAAException(AIAAError.SESSION_EXPIRED, 'Session Expired')
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, form))

        form = json.loads(form) if isinstance(form, str) else form
        params = form.get('params')
        params = json.loads(params) if isinstance(params, str) else params

        AIAAUtils.save_result(files, image_out)
        return params

    def inference(self, params, images_in, image_out, reportProgress, client_id, session_id=""):
        """
        Generic Inference for given input image and model

        :param model: model name according to the output of model_list()
        :param params: json input consumed by model
        :param image_in: input 2D/3D image file name
        :param image_out: output mask will be stored
        :param session_id: if session id is provided (not None) then *image_in* will be ignored
        :return: returns json produced by the model inference

        Output 2D/3D binary mask will be saved to the specified file;  JSON results will be returned;
        Throws AIAAException in case of Error
        """
        logger = logging.getLogger(__name__)
        logger.debug('Preparing for Inference Action')
        import urllib
        selector = '/v1/inference?' + urllib.parse.urlencode(params)
        if session_id:
            selector += '&session_id=' + AIAAUtils.urllib_quote_plus(session_id)

        in_files = dict()
        import os
        for file in images_in:
            in_files[os.path.basename(file)] = file

        print(selector)
        logger.info('Using Selector: {}'.format(selector))
        logger.info('Using Params: {}'.format(params))
        logger.info('Using Files: {}'.format(in_files))

        status, content = AIAAUtils.http_multipart_chunk(self._server_url, selector, in_files, client_id, reportProgress)
        if status == 440:
            raise AIAAException(AIAAError.SESSION_EXPIRED, 'Session Expired')
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, content))

        AIAAUtils.save_one_result(content, image_out)
        return image_out

    def mask2polygon(self, image_in, point_ratio):
        """
        3D binary mask to polygon representation conversion

        :param image_in: input 3D binary mask image file name
        :param point_ratio: point ratio controlling how many polygon vertices will be generated

        :return: A json containing the indices of all polygon vertices slice by slice.
        """
        logger = logging.getLogger(__name__)
        logger.debug('Preparing for Mask2Polygon Action')

        selector = '/v1/mask2polygon'
        params = dict()
        params['more_points'] = point_ratio

        fields = {'params': json.dumps(params)}
        files = {'datapoint': image_in}

        status, response, _ = AIAAUtils.http_multipart('POST', self._server_url, selector, fields, files)
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, response))

        response = response.decode('utf-8') if isinstance(response, bytes) else response
        return json.loads(response)

    def fixpolygon(self, image_in, image_out, polygons, index, vertex_offset, propagate_neighbor):
        """
        2D/3D polygon update with single point edit

        :param image_in: input 2D/3D image file name
        :param image_out: output 2D/3D mask image file name
        :param polygons: list of polygons 2D/3D
        :param index: index of vertex which needs to be updated
                      1) for 2D [polygon_index, vertex_index]
                      2) for 3D [slice_index, polygon_index, vertex_index]
        :param vertex_offset: offset (2D/3D) needs to be added to get the updated vertex in [x,y] format
        :param propagate_neighbor: neighborhood size
                      1) for 2D: single value (polygon_neighborhood_size)
                      2) for 3D: [slice_neighborhood_size, polygon_neighborhood_size]
        :return: A json containing the indices of updated polygon vertices


        Output binary mask will be saved to the specified name
        """
        logger = logging.getLogger(__name__)
        logger.debug('Preparing for FixPolygon Action')

        selector = '/v1/fixpolygon'

        dimension = len(index)

        params = dict()
        params['poly'] = polygons
        params['vertex_offset'] = vertex_offset
        params['dimension'] = dimension

        if dimension == 3:
            params['slice_index'] = index[0]
            params['polygon_index'] = index[1]
            params['vertex_index'] = index[2]
            params['propagate_neighbor_3d'] = propagate_neighbor[0]
            params['propagate_neighbor'] = propagate_neighbor[1]
        else:
            params['polygon_index'] = index[0]
            params['vertex_index'] = index[1]
            params['propagate_neighbor'] = propagate_neighbor

        fields = {'params': json.dumps(params)}
        files = {'datapoint': image_in}

        status, form, files = AIAAUtils.http_multipart('POST', self._server_url, selector, fields, files)
        if status != 200:
            raise AIAAException(AIAAError.SERVER_ERROR, 'Status: {}; Response: {}'.format(status, form))

        form = json.loads(form) if isinstance(form, str) else form
        params = form.get('params')
        params = json.loads(params) if isinstance(params, str) else params

        AIAAUtils.save_result(files, image_out)
        return params


class AIAAError:
    SESSION_EXPIRED = 1
    RESULT_NOT_FOUND = 2
    SERVER_ERROR = 3
    UNKNOWN = 4


class AIAAException(Exception):
    def __init__(self, error, msg):
        self.error = error
        self.msg = msg


class AIAAUtils:
    def __init__(self):
        pass

    @staticmethod
    def resample_image(itk_image, out_size, linear):
        spacing = list(itk_image.GetSpacing())
        size = list(itk_image.GetSize())

        out_spacing = []
        for i in range(len(size)):
            out_spacing.append(float(spacing[i]) * float(size[i]) / float(out_size[i]))

        resample = SimpleITK.ResampleImageFilter()
        resample.SetOutputSpacing(out_spacing)
        resample.SetSize(out_size)
        resample.SetOutputDirection(itk_image.GetDirection())
        resample.SetOutputOrigin(itk_image.GetOrigin())

        if linear:
            resample.SetInterpolator(SimpleITK.sitkLinear)
        else:
            resample.SetInterpolator(SimpleITK.sitkNearestNeighbor)
        return resample.Execute(itk_image)

    @staticmethod
    def image_pre_process(input_file, output_file, point_set, pad, roi_size):
        logger = logging.getLogger(__name__)
        logger.debug('Reading Image from: {}'.format(input_file))

        itk_image = SimpleITK.ReadImage(input_file)
        spacing = itk_image.GetSpacing()
        image_size = itk_image.GetSize()

        target_size = tuple(map(int, roi_size.split('x')))
        points = np.asanyarray(np.array(point_set).astype(int))

        logger.debug('Image Size: {}'.format(image_size))
        logger.debug('Image Spacing: {}'.format(spacing))
        logger.debug('Target Size: {}'.format(target_size))
        logger.debug('Input Points: {}'.format(json.dumps(points.tolist())))

        index_min = [sys.maxsize, sys.maxsize, sys.maxsize]
        index_max = [0, 0, 0]
        vx_pad = [0, 0, 0]
        for point in points:
            for i in range(3):
                vx_pad[i] = int((pad / spacing[i]) if spacing[i] > 0 else pad)
                index_min[i] = min(max(int(point[i] - vx_pad[i]), 0), int(index_min[i]))
                index_max[i] = max(min(int(point[i] + vx_pad[i]), int(image_size[i] - 1)), int(index_max[i]))

        logger.debug('Voxel Padding: {}'.format(vx_pad))
        logger.debug('Min Index: {}'.format(index_min))
        logger.debug('Max Index: {}'.format(index_max))

        crop_index = [0, 0, 0]
        crop_size = [0, 0, 0]
        crop = []
        for i in range(3):
            crop_index[i] = index_min[i]
            crop_size[i] = index_max[i] - index_min[i]
            crop.append([crop_index[i], crop_index[i] + crop_size[i]])
        logger.debug('crop_index: {}'.format(crop_index))
        logger.debug('crop_size: {}'.format(crop_size))
        logger.debug('crop: {}'.format(crop))

        # get bounding box
        x1 = crop[0][0]
        x2 = crop[0][1]
        y1 = crop[1][0]
        y2 = crop[1][1]
        z1 = crop[2][0]
        z2 = crop[2][1]

        # crop
        points[::, 0] = points[::, 0] - x1
        points[::, 1] = points[::, 1] - y1
        points[::, 2] = points[::, 2] - z1

        cropped_image = itk_image[x1:x2, y1:y2, z1:z2]
        cropped_size = cropped_image.GetSize()
        logger.debug('Cropped size: {}'.format(cropped_size))

        # resize
        out_image = AIAAUtils.resample_image(cropped_image, target_size, True)
        logger.debug('Cropped Image Size: {}'.format(out_image.GetSize()))
        SimpleITK.WriteImage(out_image, output_file, True)

        # pointsROI
        ratio = np.divide(np.asanyarray(target_size, dtype=np.float), np.asanyarray(cropped_size, dtype=np.float))
        points[::, 0] = points[::, 0] * ratio[0]
        points[::, 1] = points[::, 1] * ratio[1]
        points[::, 2] = points[::, 2] * ratio[2]
        return points.astype(int).tolist(), crop

    @staticmethod
    def image_post_processing(input_file, output_file, crop, orig_file):
        itk_image = SimpleITK.ReadImage(input_file)
        orig_crop_size = [crop[0][1] - crop[0][0], crop[1][1] - crop[1][0], crop[2][1] - crop[2][0]]
        resize_image = AIAAUtils.resample_image(itk_image, orig_crop_size, False)

        orig_image = SimpleITK.ReadImage(orig_file)
        orig_size = orig_image.GetSize()

        image = SimpleITK.GetArrayFromImage(resize_image)
        result = np.zeros(orig_size[::-1], np.uint8)
        result[crop[2][0]:crop[2][1], crop[1][0]:crop[1][1], crop[0][0]:crop[0][1]] = image

        itk_result = SimpleITK.GetImageFromArray(result)
        itk_result.SetDirection(orig_image.GetDirection())
        itk_result.SetSpacing(orig_image.GetSpacing())
        itk_result.SetOrigin(orig_image.GetOrigin())

        SimpleITK.WriteImage(itk_result, output_file, True)

    @staticmethod
    def http_method(method, server_url, selector):
        logger = logging.getLogger(__name__)
        logger.debug('{} {}{}'.format(method, server_url, selector))

        parsed = urlparse(server_url)
        if parsed.scheme == 'https':
            logger.debug('Using HTTPS mode')
            # noinspection PyProtectedMember
            conn = httplib.HTTPSConnection(parsed.hostname, parsed.port, context=ssl._create_unverified_context())
        else:
            conn = httplib.HTTPConnection(parsed.hostname, parsed.port)

        path = parsed.path.rstrip('/')
        selector = path + '/' + selector.lstrip('/')
        logger.debug('URI Path: {}'.format(selector))

        conn.request(method, selector)
        response = conn.getresponse()

        logger.debug('HTTP Response Code: {}'.format(response.status))
        logger.debug('HTTP Response Message: {}'.format(response.reason))
        logger.debug('HTTP Response Headers: {}'.format(response.getheaders()))
        return response.status, response.read()

    @staticmethod
    def read_in_chunks(files, limit, client_id, reportProgress, blocksize=4096):
        """Lazy function (generator) to read a file piece by piece.
        Default chunk size: 4k."""
        import os
        logger = logging.getLogger(__name__)
        read_count = 0
        total = 0
        for (key, filename) in files.items():
            total += os.path.getsize(filename)
        reportProgress(0)
        for (key, filename) in files.items():
            lines = [limit,
                     'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, client_id + "_" + key),
                     'Content-Type: %s' % AIAAUtils.get_content_type(filename),
                     ""
                     ]
            body = AIAAUtils.lines_to_bytes(lines)
            yield body
            # filename = "C:\\Users\\sibni\\OneDrive\\Desktop\\1.nii.gz"
            with open(filename, mode='rb') as f:
                logger.info('Reading {}'.format(filename))

                while True:
                    slicer.app.processEvents()
                    data = f.read(blocksize)
                    read_count += len(data)
                    reportProgress(100.0*read_count/total)
                    if not data:
                        break
                    yield data
            body = AIAAUtils.lines_to_bytes([''])
            yield body

        lines = [limit + '--']
        body = AIAAUtils.lines_to_bytes(lines)
        yield body

    @staticmethod
    def lines_to_bytes(lines):
        body = bytearray()
        for line in lines:
            body.extend(line if isinstance(line, bytes) else line.encode('utf-8'))
            body.extend(b'\r\n')
        return body

    @staticmethod
    def http_multipart_chunk(server_url, selector, files, client_id, reportProgress):
        limit = '----------lImIt_of_THE_fIle_eW_$'
        logger = logging.getLogger(__name__)
        if server_url[-1] == '/':
            server_url = server_url[:-1]
        logger.info('{}{}'.format(server_url, selector))
        response = requests.post(server_url + selector,
                                 headers={"Content-type": "multipart/form-data; boundary=" + limit},
                                 data=AIAAUtils.read_in_chunks(files, "--" + limit, client_id, reportProgress),
                                 stream=True)
        reportProgress(100)
        logger.info('HTTP Response: {}'.format(response))
        logger.info('HTTP Response: {}'.format(response.status_code))
        response_content_type = response.headers['content-type']
        logger.info('HTTP Response Content-Type: {}'.format(response_content_type))

        logger.info('Reading status/content from simple response!')
        return response.status_code, response.content

    @staticmethod
    def http_multipart(method, server_url, selector, fields, files, client_id):
        logger = logging.getLogger(__name__)
        logger.debug('{} {}{}'.format(method, server_url, selector))

        parsed = urlparse(server_url)
        if parsed.scheme == 'https':
            logger.debug('Using HTTPS mode')
            # noinspection PyProtectedMember
            conn = httplib.HTTPSConnection(parsed.hostname, parsed.port, context=ssl._create_unverified_context())
        else:
            conn = httplib.HTTPConnection(parsed.hostname, parsed.port)

        content_type, body = AIAAUtils.encode_multipart_formdata(fields, files, client_id)
        # print(body)
        headers = {'content-type': content_type, 'content-length': str(len(body)), 'client_id': client_id}

        path = parsed.path.rstrip('/')
        selector = path + '/' + selector.lstrip('/')
        logger.debug('URI Path: {}'.format(selector))

        conn.request(method, selector, body, headers)

        response = conn.getresponse()
        logger.debug('HTTP Response Code: {}'.format(response.status))
        logger.debug('HTTP Response Message: {}'.format(response.reason))
        logger.debug('HTTP Response Headers: {}'.format(response.getheaders()))

        response_content_type = response.getheader('content-type', content_type)
        logger.debug('HTTP Response Content-Type: {}'.format(response_content_type))

        if 'multipart' in response_content_type:
            if response.status == 200:
                form, files = AIAAUtils.parse_multipart(response.fp if response.fp else response, response.msg)
                logger.debug('Response FORM: {}'.format(form))
                logger.debug('Response FILES: {}'.format(files.keys()))
                return response.status, form, files
            else:
                return response.status, response.read(), None

        logger.debug('Reading status/content from simple response!')
        return response.status, response.read(), None

    @staticmethod
    def save_result(files, result_file):
        logger = logging.getLogger(__name__)

        if result_file is None:
            return

        if len(files) == 0:
            raise AIAAException(AIAAError.RESULT_NOT_FOUND, "No result files found in server response!")

        for name in files:
            data = files[name]
            logger.debug('Saving {} to {}; Size: {}'.format(name, result_file, len(data)))

            dir_path = os.path.dirname(os.path.realpath(result_file))
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)

            with open(result_file, "wb") as f:
                if isinstance(data, bytes):
                    f.write(data)
                else:
                    f.write(data.encode('utf-8'))
            break

    @staticmethod
    def save_one_result(data, result_file):
        logger = logging.getLogger(__name__)

        if result_file is None:
            return

        if len(data) == 0:
            raise AIAAException(AIAAError.RESULT_NOT_FOUND, "No result files found in server response!")

        logger.debug('Saving {}; Size: {}'.format(result_file, len(data)))

        dir_path = os.path.dirname(os.path.realpath(result_file))
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

        with open(result_file, "wb") as f:
            if isinstance(data, bytes):
                f.write(data)
            else:
                f.write(data.encode('utf-8'))

    @staticmethod
    def encode_multipart_formdata(fields, files, client_id):
        limit = '----------lImIt_of_THE_fIle_eW_$'
        lines = []
        for (key, value) in fields.items():
            lines.append('--' + limit)
            lines.append('Content-Disposition: form-data; name="%s"' % key)
            lines.append('')
            lines.append(value)
        # lines.append('--' + limit)
        # lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % ("client_id", client_id))
        # lines.append('Content-Type: %s' % AIAAUtils.get_content_type(client_id))
        for (key, filename) in files.items():
            lines.append('--' + limit)
            lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, client_id + "_" + filename))
            lines.append('Content-Type: %s' % AIAAUtils.get_content_type(filename))
            lines.append('')
            with open(filename, mode='rb') as f:
                data = f.read()
                lines.append(data)
        lines.append('--' + limit + '--')
        lines.append('')

        body = bytearray()
        for line in lines:
            body.extend(line if isinstance(line, bytes) else line.encode('utf-8'))
            body.extend(b'\r\n')

        content_type = 'multipart/form-data; boundary=%s' % limit
        return content_type, body

    @staticmethod
    def get_content_type(filename):
        return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

    @staticmethod
    def parse_multipart(fp, headers):
        logger = logging.getLogger(__name__)
        fs = cgi.FieldStorage(
            fp=fp,
            environ={'REQUEST_METHOD': 'POST'},
            headers=headers,
            keep_blank_values=True
        )
        form = {}
        files = {}
        if hasattr(fs, 'list') and isinstance(fs.list, list):
            for f in fs.list:
                logger.debug('FILE-NAME: {}; NAME: {}; SIZE: {}'.format(f.filename, f.name, len(f.value)))
                if f.filename:
                    files[f.filename] = f.value
                else:
                    form[f.name] = f.value
        return form, files

    # noinspection PyUnresolvedReferences
    @staticmethod
    def urllib_quote_plus(s):
        return quote_plus(s)