Exemple #1
0
    def post(self):
        token = request.headers.get('X-Auth-Token')
        if not existsToken(token):
            resp = Response(status=401)
            return resp

        f = flask.request.files['tumor_image']
        # print(f)
        # content = StringIO(f.read())

        img = Image.open(f)
        print(img)
        transform = transforms.Compose([
            transforms.RandomResizedCrop(224),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])
        ])
        img = transform(img)
        img = img.unsqueeze(0)

        with torch.no_grad():
            model.eval()
            py = model(img)

        res = torch.max(py, 1)[1].data.numpy()[0]
        return classes[res], '200'
Exemple #2
0
def predict(data, samples=1):
    """
    Predict probability for different digits in incoming data and
    make a bar plot out of it.

    Args:
        data (str): Image encoded as a base64 string.
        samples (int): Number of times the network should be sampled.
            An average is then used. This is only useful if network
            is stochastic (default 1).

    Returns:
        matplotlib figure
    """
    image = preprocess(data)
    x = torch.Tensor(image).view(1, 1, 28, 28)

    figure = Figure()
    ax = figure.add_subplot(1, 1, 1)

    preds = []
    for _ in range(samples):
        pred = model(x).detach().numpy()
        pred = np.squeeze(pred)
        preds.append(pred)
    pred = np.mean(preds, axis=0)
    pred = np.exp(pred)

    return pred
def create(self, model, defaults=None, **kwargs):
    params = dict(
        (k, v) for k, v in kwargs.items() if not isinstance(v, ClauseElement))
    params.update(defaults or {})
    instance = model(**params)
    self.session.add(instance)
    self.session.flush()
    return instance
Exemple #4
0
def gen_probabilities(image):
    """Call PyTorch ResNet + Fine-tuned net.
    
    @param image: RGB face image.
    @return probability vector of size 23.
    """

    # first get the image into standard form
    image = Image.fromarray(image)
    image = image.convert('RGB')
    image = preprocessing(image).unsqueeze(0)
    image = Variable(image, volatile=True)

    # pass image through ResNet to get embedding
    embedding = embedder(image)
    embedding = embedding.squeeze(2).squeeze(2)
    # pass image through model to get prediction
    log_probas = model(embedding)
    probas = torch.exp(log_probas)  # probabilities

    return probas
Exemple #5
0
def predict(file: bytes = File(...)):

    try:
        img = Image.open(io.BytesIO(file)).convert('RGB')
        del file
    except (ValueError, AttributeError, OSError):
        raise HTTPException(
            status_code=422,
            detail=
            'You must pass binaries of jpg or png image. Your data can not be interpreted as '
            'image')

    with torch.no_grad():
        raw_preds = model(model.transforms(img).unsqueeze(0).to(model.device))

    ingr_ids = raw_preds['ingr_ids'].cpu().numpy()
    recipe_ids = raw_preds['recipe_ids'].cpu().numpy()
    del raw_preds

    outs = process_prediction(recipe_ids[0], ingr_ids[0], model.instr_vocab,
                              model.ingred_vocab)

    return dict(title=outs['title'], ingredients=outs['ingredients'])
Exemple #6
0
def generate_models(ceesim_data, ceesim_flattened, lookup_table):
    # type: (dict, dict, dict) -> list
    '''
    Generate all non INP/PUL models

    Parameters:
     * `ceesim_data`: (dictionary) Imported CEESIM JSON data
     * `ceesim_flattened`: (dictionary, optional) Flattened CEESIM JSON data
     * `lookup_table`: (dictionary) Lookup table JSON imported
    
    **Returns**: (list) List of models
    '''
    logger.debug('Now generating all non-signal models')

    def fill_table(model, pos, value):
        # type: (model, int, str) -> None
        '''
        Fills out table from model with values

        Parameters:
         * `model`: (model class object) Model object
         * `pos`: (int) Position index
         * `value`: (str) Value to fill
        
        **Returns**: None, table is filled in-place
        '''
        if len(model.converted_data) <= pos:
            model.converted_data += [''] * \
                (pos - len(model.converted_data) + 1)
        model.converted_data[pos] = value

    def create_converted(model, opt):
        # type: (model, list) -> None
        '''
        Converts in-place model

        Parameters:
         * `model`: (model class object) Model object
         * `opt`: (list) Options from lookup table
        
        **Returns**: None, table is filled in place
        '''

        if type(opt["TABLE"]) is int:
            table_string = build_table_str(ceesim_data, lookup_table, opt[FILE_HDR], opt["SECTION"], 
                                        opt[PRI_HDR], convert_one_key, obtain_relevant_tags, opt[FILE_HDR] == "ANT")
            fill_table(model, opt[PRI_HDR], table_string)
            return None # No other conversion should occur after building table

        values = []
        for tag in opt[TAG_HDR].split('&'):
            tags = obtain_relevant_tags(ceesim_data, ceesim_flattened, tag) # removed taking the zero-index as it's done below
            if tags:
                value = tags[0]  
                logger.debug("Found tag {} for {} in {} with value: {}".format(opt[TAG_HDR],
                                                                            opt["LABEL"], opt[FILE_HDR], value))
            else:
                if opt[TAG_HDR]:
                    logger.debug('Could not find tag {}, using default value for {} in {}: {}'.format(opt[TAG_HDR],
                                                                                                    opt["LABEL"], opt[FILE_HDR], opt[DEFAULT_HDR]))
                else:
                    logger.debug('Using default value for tagless {} in {}: {}'.format(
                        opt["LABEL"], opt[FILE_HDR], opt[DEFAULT_HDR]))
                value = opt[DEFAULT_HDR]
            values.append(value)

        converted = convert_one_key(opt, values)
        fill_table(model, opt[PRI_HDR], converted) # adds to model.converted_data


    def add_headers(mfile, model):
        # type: (str, model) -> None
        '''
        Adds headers to converted model

        Parameters:
         * `mfile`: (string) Name of file
         * `model`: (model) Model class object

        **Returns**: None, data is converted in place
        '''
        with open("data/headers.csv") as head:
            headers = reader(head)
            for header in headers:
                if header[0] == mfile:
                    left = (int(header[2]) - len(header[1]) - 3) / 2
                    lleft = int(left)
                    right = lleft
                    if lleft == left:
                        left = lleft
                        right = lleft + 1
                    htext = "//" + ' '.join(
                        ['*' * lleft, header[1], '*' * right])
                    h_priority = int(header[3])
                    if determine_scan_type(ceesim_data) == "LORO" and mfile == "SIG" and (header[1] == "ANTENNA MODEL" or header[1] == "MULTIPLE SIMULTANEOUS SIGNALS"):
                        # Resolves a downstream feature displacement that occurs from the inclusion of all scan data within the .sig file's SCAN MODEL
                        h_priority += 3
                    fill_table(model, h_priority, htext)
    models = list()
    name = form_model_name(ceesim_data, ceesim_flattened)
    timestamp = obtain_relevant_tags(ceesim_data, ceesim_flattened, "LastUpdateDate")[0]
    logger.debug('Generic model generator using name: {}'.format(name))
    for mtype in AUTO_MODELS:
        next_model = model(mtype, name, timestamp)
        if mtype not in MODEL_FILES:
            logger.warn(
                'Could not find mtype {} in model files, skipping'.format(mtype))
            continue
        table_key = MODEL_FILES[mtype]
        add_headers(table_key, next_model)
        if table_key not in lookup_table:
            logger.warn(
                'Could not find key {} in lookup table, skipping'.format(table_key))
            continue
        logger.debug(
            'Now processing table key {} with mtype {}'.format(table_key, mtype))
        for cdict_key in lookup_table[table_key]:
            key_data = lookup_table[table_key][cdict_key]
            if MULTI_HDR in key_data and TABLE_DATA in key_data:
                data_opts = key_data[TABLE_DATA]
                for opt in data_opts:
                    if opt["SECTION"] == "Main":
                        continue
                    create_converted(next_model, opt)
            else:
                if key_data["SECTION"] == "Main":
                    continue
                create_converted(next_model, key_data)

        models.append(next_model)

    # Handles Intrapule here
    inp_deviations = obtain_relevant_tags(ceesim_data, ceesim_flattened, "LinearFreqDeviation")
    inp_durations = obtain_relevant_tags(ceesim_data, ceesim_flattened, "LinearFreqDuration")
    inp_info = zip(inp_deviations, inp_durations)

    for i, info in enumerate(inp_info):
        newName = "{}-{}".format(name, i + 1)
        next_model = model('INTRAPULSE', newName, timestamp)
        table_key = MODEL_FILES['INTRAPULSE']
        add_headers(table_key, next_model)
        if table_key not in lookup_table:
            logger.warn(
                'Could not find key {} in lookup table, skipping'.format(table_key))
            continue
        logger.debug(
            'Now processing table key {} with mtype {}'.format(table_key, 'INTRAPULSE'))

        for cdict_key in lookup_table[table_key]:
            key_data = lookup_table[table_key][cdict_key]
            if MULTI_HDR in key_data and TABLE_DATA in key_data:
                data_opts = key_data[TABLE_DATA]
                for opt in data_opts:
                    if opt["SECTION"] == "Main":
                        continue
                    create_converted(next_model, opt)
            else:
                if key_data["SECTION"] == "Main":
                    continue
                if not key_data["TAG"]:
                    create_converted(next_model, key_data)
                else:
                    if key_data["TAG"] == "LinearFreqDeviation":
                        fill_table(next_model, key_data[PRI_HDR], convert_one_key(key_data, [info[0]]))
                    if key_data["TAG"] == "LinearFreqDeviation&LinearFreqDuration":
                        fill_table(next_model, key_data[PRI_HDR], convert_one_key(key_data, info))

        models.append(next_model)

    return models