Ejemplo n.º 1
0
def submit_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        if file:
            filename = secure_filename(file.filename)
            print(filename)
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            print(file)
            result = get_prediction(str(os.path.join(UPLOAD_FOLDER, filename)))
            print(result)

            final_class = []
            final_score = []
            
            for r in result:
                final_class.append(str(r.display_name))
            for s in result:
                final_score.append(round(s.classification.score, 6))
            res = {final_class[i]: final_score[i] for i in range(len(final_class))}
            print(res)
            return jsonify(res)
Ejemplo n.º 2
0
def predict():
    if request.method == 'POST':
        # Remove existing images in directory
        files_in_dir = os.listdir(app.config['UPLOAD_FOLDER'])
        filtered_files = [
            file for file in files_in_dir
            if file.endswith(".jpg") or file.endswith(".jpeg")
        ]
        for file in filtered_files:
            path = os.path.join(app.config['UPLOAD_FOLDER'], file)
            os.remove(path)
            print("File remove")

        # Upload new file
        if 'file' not in request.files:
            print("not in file")
            return redirect(request.url)
        file = request.files['file']

        if not file:
            print("not file")
            return

        print("Getting Prediction")
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        prediction, density = get_prediction(file)
        originalimage = 'static/' + filename
        return jsonify(prediction, density, originalimage)
Ejemplo n.º 3
0
def result():
    score = get_prediction(
        '/home/rmb571/Documents/flask-video-streaming/capture.jpeg').tolist()
    if score[1] > 0.5:
        return jsonify({'Predict': 'Tails'})
    else:
        return jsonify({'Predict': 'Tails'})
Ejemplo n.º 4
0
def predict():
    # for external API calls
    if request.method == 'POST':
        file = request.files['file']
        file = Image.open(file).convert('L')
        class_pred = get_prediction(file)
        return jsonify(class_pred)
Ejemplo n.º 5
0
def details():
	# 1. Get the campaign link
	# 2. Collect the data based on the given link
	# 3. Predict the donation
	# 4. Display the graph, result, stats, etc.

	campaign = request.args.get('campaign', None)
	response = get_data(campaign)
	data = json.loads(response)

	# Remove collected_amt from our data
	# because we don't need it for the model
	df_input = pd.DataFrame([data]).drop(['collected_amt'], axis=1)
	prediction = get_prediction(df_input)

	data['campaign'] = campaign
	data['prediction'] = prediction

	# Add is funded
	if (int(data['prediction']) < int(data['donation_target_amt']) ):
		data['is_funded'] = False
	else:
		data['is_funded'] = True

	# Get graph
	target = int(data['donation_target_amt'])
	fb_shares = display_fb_shares(target)

	return render_template('details.html',
						campaign=campaign,
						data=data,
						fb_shares=fb_shares
						)
			
Ejemplo n.º 6
0
def predict():
    if request.method == 'POST':
        file = request.files['file']
        img_bytes = file.read()
        print("POST!!")
        class_name = get_prediction(image_bytes=img_bytes)

        # print(f"classname is {class_name} class_id is {class_id}")
        return jsonify({'class_name': class_name})
Ejemplo n.º 7
0
def index():
    pred = predict.get_prediction(model,mongo)
    description = pred['description']
    return '''
<h1>Current Time: ''' + time.asctime() + '''</h1>
<h1>Current prediction: ''' + str(pred['fraud_risk']) + '''</h1>
    </br>
    <h2> Description from current datapoint:</h2>
    <p> ''' + description + '''</p>
Ejemplo n.º 8
0
async def query_result(user_request: UserRequest):
    if user_request.process_type == "sentiment":
        request_content = [user_request.content, '']
        return {"result":predict.get_prediction(request_content, estimator)[0][2]}
        pass
    elif user_request.process_type == "word_vec":
        bc = BertClient(ip='localhost', port=23333)
        return {"result": np.array2string(bc.encode([user_request.content]))}
        pass
    else:
        raise HTTPException(status_code=400, detail="Unsupported processing method")
Ejemplo n.º 9
0
def callAutoml():
    print "automl"
    print(request.json)
    data = request.json
    print(data["result"])
    project_id = "extreme-tribute-220411"
    model_id = "TRL2058776748956521335"
    ans = get_prediction(data["result"], project_id, model_id)
    ans = "{" + ans + "}"
    #print(ans)
    return json.dumps(ans)
Ejemplo n.º 10
0
def predict(audusd, nzdusd):
    prediction = get_prediction(audusd, nzdusd)
    result = {
        'fisrst_class': repr(prediction[0]),
        'second_class': repr(prediction[1])
    }

    # simplejson.dumps(result)
    logging.error(prediction[0])
    logging.error(prediction[1])

    return result
Ejemplo n.º 11
0
def processImage(input_filename):
    global s1_time, s2_time, s3_time, s4_time, s5_time, s6_time
    print "starting processing"
    # step 1: remove background
    s1_start = time.clock()
    remove_background(input_filename)
    # output will be saved to removed_bg.png
    s1_time = time.clock() - s1_start

    # step 2: extract sub-image
    s2_start = time.clock()
    sub_img = get_sub_image('removed_bg.png')
    s2_time = time.clock() - s2_start

    # step 3: identify colour
    s3_start = time.clock()
    #colour = identify_colour('sharpened.png')
    colour = identify_colour('removed_bg.png')
    #colour = identify_colour('cropped.png')
    print colour
    s3_time = time.clock() - s3_start

    # step 4: get material
    s4_start = time.clock()
    material = get_prediction('cropped.png', "material")
    print material
    s4_time = time.clock() - s4_start

    # step 5: get type of clothing
    s5_start = time.clock()
    clothing_type = get_prediction('removed_bg.png', "clothing_type")
    print clothing_type
    s5_time = time.clock() - s5_start

    # step 6: web search
    s6_start = time.clock()
    query = colour + " " + material + " " + clothing_type
    print query
    do_search(query)
    s6_time = time.clock() - s6_start
Ejemplo n.º 12
0
def url_input():
    # for URL inputs
    select = request.form.get('url_select')
    response = requests.get(select)
    file = BytesIO(response.content)
    class_pred = get_prediction(Image.open(file).convert('L'))
    model_output = [(key, class_pred[key], '?') for key in class_pred.keys()]
    listStatus = [(id, filename) for id, filename in enumerate(files)]
    default = 201
    return render_template('index.html',
                           listStatus=listStatus,
                           default=default,
                           img1=select,
                           model_output=model_output)
Ejemplo n.º 13
0
def test():
    # for test images
    listStatus = [(id, filename) for id, filename in enumerate(files)]
    select = request.form.get('image_select')
    select = int(select)
    file = os.path.join('static', files[select])
    class_pred = get_prediction(Image.open(file).convert('L'))
    true_label = df_valid.iloc[select].drop(['NewPath']).to_dict()
    model_output = [(key, class_pred[key], true_label[key])
                    for key in class_pred.keys()]
    return render_template('index.html',
                           listStatus=listStatus,
                           default=select,
                           img1=file,
                           model_output=model_output)
Ejemplo n.º 14
0
def prediction_page(date, location, direction='Southbound', lane='Car'):
    # Get chart data
    start = datetime.datetime.strptime(date, '%Y-%m-%d')
    predict = get_prediction(start, location, direction, lane)
    baseline = get_baseline(start, location, direction, lane)
    actual = get_actual(start, location, direction, lane)

    # Create labels by hour
    labels = []
    time = datetime.datetime(2008, 4, 11)      # Actual date is immaterial
    end = time + datetime.timedelta(hours=24)
    while time < end:
        if time.minute == 0 and time.hour % 2 == 0:
            labels.append(str(time.time())[:-3])
        else:
            labels.append("")
        time += datetime.timedelta(minutes=30)

    # Date formatting for calendar control
    date_formatted = datetime.datetime \
        .strptime(date, '%Y-%m-%d').strftime('%m/%d/%Y')

    # Dates for arrow buttons
    next_week = start + datetime.timedelta(days=7)
    next_week = next_week.strftime('%Y-%m-%d')
    last_week = start - datetime.timedelta(days=7)
    last_week = last_week.strftime('%Y-%m-%d')
    tomorrow = start + datetime.timedelta(days=1)
    tomorrow = tomorrow.strftime('%Y-%m-%d')
    yesterday = start - datetime.timedelta(days=1)
    yesterday = yesterday.strftime('%Y-%m-%d')

    return render_template('chart.html',
                           date=date,
                           default_date=date_formatted,
                           dow=start.strftime("%A"),
                           location=location,
                           direction=direction,
                           lane=lane,
                           predict=list(predict.waittime),
                           baseline=list(baseline.waittime),
                           actual=list(actual.waittime),
                           labels=labels,
                           next_week=next_week,
                           last_week=last_week,
                           tomorrow=tomorrow,
                           yesterday=yesterday
                           )
Ejemplo n.º 15
0
def file_input():
    # for file inputs

    file = request.files['file_select']
    file.save(os.path.join(application.config['UPLOAD_FOLDER'], 'tmp.jpg'))
    class_pred = get_prediction(Image.open(file).convert('L'))
    select2 = os.path.join(application.config['UPLOAD_FOLDER'], 'tmp.jpg')

    model_output = [(key, class_pred[key], '?') for key in class_pred.keys()]
    listStatus = [(id, filename) for id, filename in enumerate(files)]
    default = 201
    return render_template('index.html',
                           listStatus=listStatus,
                           default=default,
                           img1=select2,
                           model_output=model_output)
Ejemplo n.º 16
0
def get_all_predictions():
    """
    Gets predicted price of Airbnb unit given selected inputs.

    Inputs:
        1. Zipcode
        2. Property Type
        3. Room Type
        4. How many people the unit accommadates
        5. Number of Bathrooms
        6. Number of Bedrooms
        7. Number of Beds
        8. Type of Bed

    Outputs:
        1. Predicted Price
        2. Dollar value bins
        3. Amount of units from the requested zip code in each bin
    """
    data = request.get_json(force=True)

    zipcode = data['zipcode']
    property_type = data['property_type']
    room_type = data['room_type']
    accommodates = data['accommodates']
    bathrooms = data['bathrooms']
    bedrooms = data['bedrooms']
    beds = data['beds']
    bed_type = data['bed_type']

    with dataLock:
        result = get_prediction(zipcode=zipcode,
                                property_type=property_type,
                                room_type=room_type,
                                accommodates=accommodates,
                                bathrooms=bathrooms,
                                bedrooms=bedrooms,
                                beds=beds,
                                bed_type=bed_type)

        plot_values, bins = zip_list(zipcode=zipcode)

        plot_values = [int(i) for i in plot_values]

    return json_response(prediction=result,
                         plot_values=plot_values,
                         bins=bins)
Ejemplo n.º 17
0
def get_prediction(model, category_label_to_name, image_path):
    '''
    Get the prediction probability for the image given in input

    Arguments:
        model (object): model to make predictions
        category_label_to_name (dict): dictionary for mapping category label to name
        image_path: path of the image to classify

    Returns:
        probability_category (dict): dictonary with predicted category and probability
    '''
    top_probabilities, top_classes = predict.get_prediction(
        image_path, model, top_k_probabilities=DEFAULT_TOP_K)
    probability_category = []
    for i in range(len(top_probabilities)):
        probability_category.append(
            (top_probabilities[i], category_label_to_name[top_classes[i]]))
    return dict((category, probability)
                for probability, category in probability_category)
Ejemplo n.º 18
0
def predict_single(path):
    """
    Classification of a single meme
    Note: the labels, objects and text are hard-coded but are in the right format
    Note: it might work with multiple memes if labels are list of lists, objects are list of lists and text a list of text.
    :return: A str that says if the meme is hatefull or not.
    """

    dicti = pg.get_all(path=path)
    d = pp.preprocess(dicti)
    labels = d['labels']
    objects = d['objects']
    text = d['text']

    input = predict.vectorize(labels, objects, text)
    probas = predict.get_probabilities(input)
    pred = predict.get_prediction(probas)

    if pred == 1:
        return 'This is a hateful meme', labels, objects, text
    else:
        return 'This is a safe meme', labels, objects, text
Ejemplo n.º 19
0
def index():
    if request.method == "GET":
        return render_template('index.html',
                               image_segmented=None,
                               real_image=None)
    elif request.method == "POST":
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print("full path is ", filename)
            url_for_mask = get_prediction(
                model, os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print("image_segmented is True")
            return render_template('index.html',
                                   image_segmented=url_for_mask,
                                   real_image=filename)
Ejemplo n.º 20
0
    def test_get_prediction(self):
        '''
        Verify that minimum number of points have been predicted on each day
        '''
        minimum_points = 8
        begin = dt.date(2014, 1, 1)
        end = dt.date(2017, 1, 1)

        lane = 'Car'
        errorcount = 0

        for location in ['Peace Arch', 'Pacific Highway']:
            for direction in ['Southbound', 'Northbound']:
                start = begin
                while start <= end:
                    df = get_prediction(start, location, direction, lane)
                    if pd.isnull(df.waittime).sum() > minimum_points:
                        print '{0},{1},{2}'.format(start, location, direction)

                        errorcount += 1

                    start += dt.timedelta(1)

        self.assertEqual(errorcount, 0)
Ejemplo n.º 21
0
def predict(uid):
    return jsonify({'prediction': get_prediction(datetime.now())})
import streamlit as st
from PIL import Image
import predict
import numpy as np

from tempfile import NamedTemporaryFile

st.set_option('deprecation.showfileUploaderEncoding', False)

#app title
st.title('CapBot')

#uploaded_image

file = st.file_uploader("Choose and image ...", type="jpg")
temp_file = NamedTemporaryFile(delete=False)

if file is not None:
    image = Image.open(file)
    st.image(image, caption='Uploaded Image', width=100)
    st.write("")

    if st.button("generate captions"):
        st.write("CapBot generates your caption")
        image = Image.open(file)

        caption = predict.get_prediction(image)
        st.markdown(caption)
Ejemplo n.º 23
0
def pred():
    predict.get_prediction(model,mongo)
    return 'Prediction done \n'
Ejemplo n.º 24
0
        response = requests.get(url, auth=auth, params=params)
        tweets += response.json()['statuses']

    return tweets


with open(config('TWITTER_CREDENTIALS'), 'r') as f:
    secrets = json.load(f)

auth = OAuth1(secrets['api_key'], secrets['api_secret_key'],
              secrets['access_token'], secrets['access_token_secret'])

if __name__ == "__main__":
    # prompt a user for search terms
    search_terms = input("Enter search terms separated by commas: ")
    search_terms = search_terms.split(',')
    tweets = get_tweets(search_terms)

    # save the tweets to a local file for analysis
    with open('tweets.json', 'w') as f:
        json.dump(tweets, f, indent=4, separators=(",", ":"))

    # output sentiment predictions of tweets
    for tweet in tweets:
        prediction_response = get_prediction(tweet['text'])
        if prediction_response.status_code == 200:
            print('TWEET:\n  {} \n'.format(tweet['text']))
            print(prediction_response.text, '\n')
        else:
            print('An error occured')
Ejemplo n.º 25
0
def prediction(filepath):
    with open(filepath, 'rb') as ff:
        content = ff.read()
    return predict.get_prediction(content, PROJECT_ID, DATA_ID)
Ejemplo n.º 26
0
from amazon_search import do_search
from slic_dir import remove_background

input_filename = 'yellowjacket.jpg'

# step 1: remove background
remove_background(input_filename)
# output will be saved to removed_bg.png

# step 2: extract sub-image
sub_img = get_sub_image('removed_bg.png')

# step 3: identify colour
#colour = identify_colour('sharpened.png')
colour = identify_colour('removed_bg.png')
#colour = identify_colour('cropped.png')
print colour

#step 4: get material
material = get_prediction('cropped.png', "material")
print material

# step 5: get type of clothing
clothing_type = get_prediction('removed_bg.png', "clothing_type")
print clothing_type

# step 6: web search
query = colour + " " + material + " " + clothing_type
print query
do_search(query)