示例#1
0
def application(environ, start_response):
    try:
        query_body_size = int(environ.get('CONTENT_LENGTH', 0))
        body = environ['wsgi.input'].read(query_body_size).decode('utf-8')
        
    except (ValueError):
        query_body_size = 0
        body = '{"requestType":100,"contentType":100,"requestData":{"productId":1,"user_email":"miha@miha8","user_password":"******"}}'
    
    status = '200 OK'
    
    print (body)
    if len(body) > 0:
        plugin_response = RequestParser(body)
        plugin_response.distribute()
        output = plugin_response.output().encode('utf-8')
    else:
        output = "Empty result".encode('utf-8')
    
    response_headers = [('Content-type', 'application/json'),
                        ('Content-Length', str(len(output)))]

    start_response(status, response_headers)

    return [output]
示例#2
0
    def handle(self, handler):
        """
    """
        content = None

        splitted_request = handler.request.uri.split("/")
        query = "/".join(splitted_request[2:])[1:]

        if splitted_request[1] == "metainfo":

            # content = self._core.get_meta_info(path)
            content = "metainfo"
            content_type = "text/html"

        # image data request
        elif splitted_request[1] == "data":

            try:
                parser = RequestParser()
                args = parser.parse(splitted_request[2:])

                # Call the cutout method
                volume = self._core.get(*args)

                # Check if we got nothing in the case of a request outside the data with fit=True
                if volume.size == 0:
                    raise IndexError("Tile index out of bounds")

                # Color mode is equivalent to segmentation color request right now
                color = parser.optional_queries["segcolor"] and parser.optional_queries["segmentation"]
                # color = True
                # Accepted image output formats
                image_formats = settings.SUPPORTED_IMAGE_FORMATS

                # Process output
                out_dtype = np.uint8
                output_format = parser.output_format

                if output_format == "zip" and not color:
                    # Rotate out of numpy array
                    volume = volume.transpose(1, 0, 2)
                    zipped_data = zlib.compress(volume.astype(out_dtype).tostring("F"))

                    output = StringIO.StringIO()
                    output.write(zipped_data)
                    content = output.getvalue()
                    content_type = "application/octet-stream"
                elif output_format in image_formats:
                    if color:
                        volume = volume[:, :, :, [2, 1, 0]]
                        content = cv2.imencode("." + output_format, volume[:, :, 0, :].astype(out_dtype))[1].tostring()
                    else:
                        content = cv2.imencode("." + output_format, volume[:, :, 0].astype(out_dtype))[1].tostring()
                    content_type = "image/" + output_format
                else:
                    content = "Error 400: Bad request<br>Output file format not supported"
                    content_type = "text/html"

                # Show some basic statistics
                print "Total volume shape:", volume.shape

            except (KeyError, ValueError):
                print "Missing query"
                content = "Error 400: Bad request<br>Missing query"
                content_type = "text/html"
            except IndexError:
                traceback.print_exc(file=sys.stdout)
                print "Could not load image"
                content = "Error 400: Bad request<br>Could not load image"
                content_type = "text/html"
            # except Exception:
            #   traceback.print_exc(file=sys.stdout)

        # invalid request
        if not content:
            content = "Error 404: Not found"
            content_type = "text/html"

        # handler.set_header('Cache-Control','no-cache, no-store, must-revalidate')
        # handler.set_header('Pragma','no-cache')
        # handler.set_header('Expires','0')
        handler.set_header("Access-Control-Allow-Origin", "*")
        handler.set_header("Content-Type", content_type)

        # Temporary check for img output
        handler.write(content)
示例#3
0
  def handle( self, handler ):
    '''
    '''
    content = None

    splitted_request = handler.request.uri.split('/')
    query = '/'.join(splitted_request[2:])[1:]

    if splitted_request[1] == 'metainfo':

      # content = self._core.get_meta_info(path)
      content = 'metainfo'
      content_type = 'text/html'

    #image data request
    elif splitted_request[1] == 'data':

      try:
        parser = RequestParser()
        args = parser.parse(splitted_request[2:])

        #Call the cutout method
        volume = self._core.get(*args)

        #Check if we got nothing in the case of a request outside the data with fit=True
        if volume.size == 0:
          raise IndexError('Tile index out of bounds')

        #Color mode is equivalent to segmentation color request right now
        color = parser.optional_queries['segcolor'] and parser.optional_queries['segmentation']
        # color = True
        #Accepted image output formats
        image_formats = settings.SUPPORTED_IMAGE_FORMATS

        #Process output
        out_dtype = np.uint8
        output_format = parser.output_format

        if output_format == 'zip' and not color:
          #Rotate out of numpy array
          volume = volume.transpose(1, 0, 2)
          zipped_data = zlib.compress(volume.astype(out_dtype).tostring('F'))

          output = StringIO.StringIO()
          output.write(zipped_data)
          content = output.getvalue()
          content_type = 'application/octet-stream'
        elif output_format in image_formats:
          if color:
            volume = volume[:,:,:,[2,1,0]]
            content = cv2.imencode('.' + output_format, volume[:,:,0,:].astype(out_dtype))[1].tostring()
          else:
            content = cv2.imencode('.' + output_format, volume[:,:,0].astype(out_dtype))[1].tostring()
          content_type = 'image/' + output_format
        else:
          content = 'Error 400: Bad request<br>Output file format not supported'
          content_type = 'text/html'

        #Show some basic statistics
        print 'Total volume shape:', volume.shape

      except (KeyError, ValueError):
        print 'Missing query'
        content = 'Error 400: Bad request<br>Missing query'
        content_type = 'text/html'
      except IndexError:
        traceback.print_exc(file=sys.stdout)
        print 'Could not load image'
        content = 'Error 400: Bad request<br>Could not load image'
        content_type = 'text/html'
      # except Exception:
      #   traceback.print_exc(file=sys.stdout)

    # invalid request
    if not content:
      content = 'Error 404: Not found'
      content_type = 'text/html'

    # handler.set_header('Cache-Control','no-cache, no-store, must-revalidate')
    # handler.set_header('Pragma','no-cache')
    # handler.set_header('Expires','0')
    handler.set_header('Access-Control-Allow-Origin', '*')
    handler.set_header('Content-Type', content_type)
    
    #Temporary check for img output
    handler.write(content)
示例#4
0
    def handle(self, handler):
        '''
        '''
        content = None

        splitted_request = handler.request.uri.split('/')

        if splitted_request[1] == 'metainfo':

            # content = self._core.get_meta_info(path)
            content = 'metainfo'
            handler.set_header("Content-type", 'text/html')
        elif splitted_request[1] == 'stop':
            import tornado
            tornado.ioloop.IOLoop.instance().stop()
            handler.set_status(200)
            handler.set_header("Content-type", "text/plain")
            handler.write("stop")
            return

        # image data request
        elif splitted_request[1] == 'data':

            try:
                parser = RequestParser()
                args = parser.parse(splitted_request[2:])

                # Call the cutout method
                volume = self._core.get(*args[0:3],**args[3])

                # Check if we got nothing in the case of a request outside the
                # data with fit=True
                if volume.size == 0:
                    raise IndexError('Tile index out of bounds')

                color = parser.optional_queries['segcolor']

                # Accepted image output formats
                image_formats = settings.SUPPORTED_IMAGE_FORMATS

                # Process output
                out_dtype = np.uint8
                output_format = parser.output_format

                if output_format == 'zip' and not color:
                    # Rotate out of numpy array
                    volume = volume.transpose(1, 0, 2)
                    zipped_data = zlib.compress(
                        volume.astype(out_dtype).tostring('F'))

                    output = StringIO.StringIO()
                    output.write(zipped_data)
                    content = output.getvalue()
                    content_type = 'application/octet-stream'
                elif output_format in image_formats:
                    if color:
                        volume = volume[:, :, :, [2, 1, 0]]
                        content = cv2.imencode(
                            '.' + output_format,
                            volume[
                                :,
                                :,
                                0,
                                :].astype(out_dtype))[1].tostring()
                    else:
                        content = cv2.imencode(
                            '.' + output_format,
                            volume[
                                :,
                                :,
                                0].astype(out_dtype))[1].tostring()
                    content_type = 'image/' + output_format
                else:
                    raise HTTPError(handler.request.uri,
                                    400,
                                    'Output file format not supported',
                                    [], None)

                # Show some basic statistics

                rh_logger.logger.report_event(
                    'Total volume shape: %s' % str(volume.shape))
                handler.set_header('Content-Type', content_type)

            except (KeyError, ValueError):
                rh_logger.logger.report_event('Missing query',
                                              log_level=logging.WARNING)
                content = 'Error 400: Bad request<br>Missing query'
                content_type = 'text/html'
                handler.set_status(400)
            except IndexError:
                rh_logger.logger.report_exception(msg='Could not load image')
                content = 'Error 400: Bad request<br>Could not load image'
                content_type = 'text/html'
                handler.set_status(400)
            except HTTPError, http_error:
                content = http_error.msg
                if len(http_error.hdrs) == 0:
                    handler.set_header('Content-Type', "text/html")
                handler.set_status(http_error.code)
示例#5
0
def getText(location):
    if location==None:
        return ''
    res=location['description']
    if location['tags']!=None:
        res+=' ' + ' '.join(location['tags'])
    if location['categories']!=None:
        res+=' ' + ' '.join(location['categories'])
    return res

readInfo=ReadInfo('../info.txt')
#print readInfo.getLocation("TRECCS-00000102-423")


requestParser=RequestParser()
requests= requestParser.getRequests('../importantlocations.txt')



def calc_greedy_similarity(host, port, dbindex):
    logger.debug('calculating similarity...');

    begin_time = datetime.now()
    logger.debug('Similarity calculation started at : '+str(begin_time))
    dur = begin_time-begin_time

    redisconn=redis.StrictRedis(host=host, port=port, db=dbindex)
    #term_weight_fetcher=TermWeightFetcher(lucene_dir_path)
    term_vector_fetcher=TermVectorFetcher(redisconn, None)
    greedy=Greedy()