Skip to content

Instantly share code, notes, and snippets.

@sanjeevdwivedi
Created April 20, 2018 02:59
Show Gist options
  • Save sanjeevdwivedi/6f637028ccff11094687c88eed1c6bc9 to your computer and use it in GitHub Desktop.
Save sanjeevdwivedi/6f637028ccff11094687c88eed1c6bc9 to your computer and use it in GitHub Desktop.
from azure.cognitiveservices.vision.customvision.training import training_api
from azure.cognitiveservices.vision.customvision.training.models import ImageUrlCreateEntry
from azure.cognitiveservices.vision.customvision.prediction import prediction_endpoint
from azure.cognitiveservices.vision.customvision.prediction.prediction_endpoint import models
from flask import Flask, request, jsonify
from datetime import datetime
app = Flask(__name__)
import os
import sys
import json, requests
import time
training_key = "5bd2f1fd171c427aa1009ff0304d5802" # from settings pane on customvision.ai
prediction_key = "c0bc732ba400470e936aef357942ad9c"
project_name = "blighthack"
tagname = ""
dowhat = "nothing"
# Check if the project with project_name exists and if not create ir
project_id = "a5835760-4363-47ef-b052-bbaeb06cd54d"
trainer = training_api.TrainingApi(training_key)
def upload_single_image_from_url(image_url, tag_name):
print('project id is: ' + project_id)
alltags = trainer.get_tags(project_id)
tag_id = None
for i in range(0, len(alltags.tags)):
if (alltags.tags[i].name == tag_name):
tagExists = True
tag_id = alltags.tags[i].id
break
if tag_id is not None:
trainer.create_images_from_urls(project_id, [ImageUrlCreateEntry(image_url, [tag_id])])
else:
print('No tag by name: ' + tag_name + " found")
upload_single_image_from_url('http://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg', 'boarded')
# if training is requested
def train_ml_model():
iteration_id = trainer.train_project(project_id)
while (iteration_id.status == "Training"):
iteration_id = trainer.get_iteration(project_id, iteration_id.id)
print("Training status: " + iteration_id.status)
time.sleep(1)
print('finished training the model')
#train_ml_model()
def predict(image_url):
if(image_url is None):
print('image url must be supplied')
exit(0)
iterations = trainer.get_iterations(project_id)
# we are using the first iteration but you can select any iteration as necessary
iteration_id = iterations[0].id
host = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.1/Prediction/"
path = project_id + "/url/?iterationId=" + iteration_id
predictionUrl = host + path
print('Prediction URL ' + predictionUrl)
headers = {"Prediction-key": prediction_key}
# this is the URL to the image that you want to get the prediction on
jsonObj = {"Url": image_url}
response = requests.post(predictionUrl, headers=headers, json=jsonObj)
responseJ = json.loads(response.text)
print(json.dumps(responseJ, indent=4, sort_keys=True))
predictions = responseJ['Predictions']
results = []
for prediction in predictions:
print ("Tag: " + prediction['Tag'] + " Probability: " + str(prediction['Probability']))
if prediction['Probability'] > 0.75:
results.append(prediction['Tag'])
#return results
return responseJ
#predict("https://www.cats.org.uk/uploads/images/featurebox_sidebar_kids/grief-and-loss.jpg")
@app.route('/')
def index():
return "hello, I am your webserver"
@app.route('/js')
def js():
return '''
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
alert("Your computer is awesome!");
console.log("computer is awesome");
$('#normalDiv').css('background-color', 'red');
$('#colorButton').click(toggleRedColor);
// add the code to show/hide text when button gets clicked
});
var isRedColor = true;
function toggleRedColor()
{
if(isRedColor == true)
{
$('#normalDiv').css('background-color', 'white');
isRedColor = false;
}
else
{
$('#normalDiv').css('background-color', 'red');
isRedColor = true;
}
}
var isHiddenText = false;
function toggleHide()
{
if(isHiddenText == false)
{
$('#paranormalDiv').slideUp();
isHiddenText = true;
}
else
{
$('#paranormalDiv').slideDown();
isHiddenText = false;
}
}
</script>
</head>
<body>
<h3> Welcome to my site </h3>
<p>
This is a paragraph
</p>
<div id='normalDiv'>
This is a normal div
</div>
<div id='paranormalDiv'>
This is a paranormal div
</div>
<div>
<input type='button' value='Turn Me Red and White' id='colorButton' />
<input type='button' value='Show and Hide' id='predictButton' />
</div>
</body>
</html>
'''
@app.route('/predictImageServer', methods=['POST'])
def predictImageServer():
print("entering send data")
print(request)
note = request.get_json()
result = predict(note['url'])
return jsonify(result)
@app.route('/cs')
def cs():
return '''
<html>
<head>
<style>
pre {
white-space: pre-wrap;
}
</style>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
console.log("computer is awesome");
$('#predictButton').click(getPrediction);
});
function getPrediction()
{
$('#predictImage').attr('src', $('#urlTextBox').val());
$.ajax({
type:"POST",
url: "/predictImageServer",
data: JSON.stringify({url: $('#urlTextBox').val() }),
success: function (data) {
console.log("succeeded");
console.log(data);
$("#resultsDiv").text(JSON.stringify(data));
},
dataType:"json",
contentType: "application/json; charset=utf-8"
});
}
</script>
</head>
<body>
<h3> Welcome to my Machine Learning Site </h3>
<div>
<input type='text' value='Enter url here' id='urlTextBox' />
<input type='button' value='Predict an image' id='predictButton' />
</div>
<br/>
<h3> Results are shown below: </h3>
<image src='' id='predictImage'/>
<pre id='resultsDiv'>
</pre>
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment