public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); try { string requestBody = new StreamReader(req.Body).ReadToEnd(); var prediction = JsonConvert.DeserializeObject <Prediction>(requestBody); var api = new TrainingApi(new TrainingApiCredentials(prediction.TrainingId)); var account = api.GetAccountInfo(); var predictionKey = account.Keys.PredictionKeys.PrimaryKey; var creds = new PredictionEndpointCredentials(predictionKey); var endpoint = new PredictionEndpoint(creds); //This is where we run our prediction against the default iteration var result = endpoint.PredictImageUrl(new Guid(prediction.ProjectId), new ImageUrl(prediction.ImageUrl)); prediction.Results = new Dictionary <string, decimal>(); // Loop over each prediction and write out the results foreach (var outcome in result.Predictions) { if (outcome.Probability > .70) { prediction.Results.Add(outcome.Tag, (decimal)outcome.Probability); } } return((ActionResult) new OkObjectResult(prediction)); } catch (Exception e) { return(new BadRequestObjectResult(e.GetBaseException().Message)); } }
public IList <Prediction> PredictImage(Stream imageStream) { var account = TrainingApi.GetAccountInfo(); var predictionKey = account.Keys.PredictionKeys.PrimaryKey; var predictionEndpointCredentials = new PredictionEndpointCredentials(predictionKey); var endpoint = new PredictionEndpoint(predictionEndpointCredentials); var result = endpoint.PredictImage(ProjectGuid, imageStream); return(result.Predictions.Select(p => new Prediction { Tag = Enum.Parse <Models.Training.Tag>(p.Tag), Probability = p.Probability }).ToList()); }
public static bool IsValidCard(string url) { try { string trainingKey = Constants.CustomVisionTrainingAPIKey; // Create the Api, passing in a credentials object that contains the training key TrainingApiCredentials trainingCredentials = new TrainingApiCredentials(trainingKey); TrainingApi trainingApi = new TrainingApi(trainingCredentials); var projects = trainingApi.GetProjects(); ProjectModel project = projects.FirstOrDefault(e => e.Name == "IDVision"); // Get the prediction key, which is used in place of the training key when making predictions var account = trainingApi.GetAccountInfo(); var predictionKey = account.Keys.PredictionKeys.PrimaryKey; // Create a prediction endpoint, passing in a prediction credentials object that contains the obtained prediction key PredictionEndpointCredentials predictionEndpointCredentials = new PredictionEndpointCredentials(predictionKey); PredictionEndpoint endpoint = new PredictionEndpoint(predictionEndpointCredentials); byte[] byteData = Utilities.Utilities.GetImagesAsByteArrayFromUri(url); MemoryStream stream = new MemoryStream(byteData); // Make a prediction against the new project var predictionResult = endpoint.PredictImage(project.Id, stream); // Loop over each prediction and write out the results foreach (var c in predictionResult.Predictions) { if ((c.Probability * 100) > 80) { return(true); } else { return(false); } } } catch (Exception ex) { throw ex; } return(false); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "api/MakePrediction")] HttpRequestMessage req, TraceWriter log) { try { var stream = await req.Content.ReadAsStreamAsync(); var prediction = new Prediction { ProjectId = "36f167d1-82e0-45f4-8ddc-ffc6d3fe3a41", //36f167d1-82e0-45f4-8ddc-... TrainingKey = "c63201c1e627428fb5c5d603430b5f62", //c63201c1e627428fb5c5d6... TimeStamp = DateTime.UtcNow, UserId = Guid.NewGuid().ToString(), ImageUrl = await UploadImageToBlobStorage(stream) }; var api = new TrainingApi(new TrainingApiCredentials(prediction.TrainingKey)); var account = api.GetAccountInfo(); var predictionKey = account.Keys.PredictionKeys.PrimaryKey; var creds = new PredictionEndpointCredentials(predictionKey); var endpoint = new PredictionEndpoint(creds); //This is where we run our prediction against the default iteration var result = endpoint.PredictImageUrl(new Guid(prediction.ProjectId), new ImageUrl(prediction.ImageUrl)); prediction.Results = new Dictionary <string, decimal>(); // Loop over each prediction and write out the results foreach (var outcome in result.Predictions) { if (outcome.Probability >= 0.0010) { prediction.Results.Add(outcome.Tag, (decimal)outcome.Probability); } } await CosmosDataService.Instance.InsertItemAsync(prediction); return(req.CreateResponse(HttpStatusCode.OK, prediction)); } catch (Exception e) { var baseException = e.GetBaseException(); var operationException = baseException as HttpOperationException; var reason = baseException.Message; if (operationException != null) { var jobj = JObject.Parse(operationException.Response.Content); var code = jobj.GetValue("Code"); if (code != null && !string.IsNullOrWhiteSpace(code.ToString())) { reason = code.ToString(); } } return(req.CreateErrorResponse(HttpStatusCode.BadRequest, reason)); } async Task <string> UploadImageToBlobStorage(Stream stream) { //Create a new blob block Id var blobId = Guid.NewGuid().ToString() + ".jpg"; if (_blobContainer == null) { //You can set your endpoint here as a string in code or just set it to pull from your App Settings var containerName = "images"; var endpoint = $"https://mynewstorageaccountblob.blob.core.windows.net/{containerName}/?sv=2017-04-17&ss=b&srt=sco&sp=rwdlac&se=2019-01-06T04:57:40Z&st=2018-01-05T20:57:40Z&spr=https&sig=YE2ZWYTvRax4jRUmBpZSzaCFDd8ZwM3pxSDHYWVn0dY%3D"; _blobContainer = new CloudBlobContainer(new Uri(endpoint)); } //Create a new block to store this uploaded image data var blockBlob = _blobContainer.GetBlockBlobReference(blobId); blockBlob.Properties.ContentType = "image/jpg"; //You can even store metadata with the content blockBlob.Metadata.Add("createdFor", "This Awesome Hackathon"); //Upload and return the new URL associated w/ this blob content await blockBlob.UploadFromStreamAsync(stream); return(blockBlob.StorageUri.PrimaryUri.ToString()); } }
static void Main(string[] args) { // You can either add your training key here, pass it on the command line, or type it in when the program runs string trainingKey = GetTrainingKey("<your key here>", args); // Create the Api, passing in a credentials object that contains the training key TrainingApiCredentials trainingCredentials = new TrainingApiCredentials(trainingKey); TrainingApi trainingApi = new TrainingApi(trainingCredentials); // Create a new project Console.WriteLine("Creating new project:"); var project = trainingApi.CreateProject("Car Assessment"); // Make two tags in the new project var WriteOffTag = trainingApi.CreateTag(project.Id, "WriteOff"); var DentTag = trainingApi.CreateTag(project.Id, "Dent"); // Add some images to the tags Console.WriteLine("\\tUploading images"); LoadImagesFromDisk(); // Images can be uploaded one at a time foreach (var image in WriteOffImages) { trainingApi.CreateImagesFromData(project.Id, image, new List <string> () { WriteOffTag.Id.ToString() }); } // Or uploaded in a single batch trainingApi.CreateImagesFromData(project.Id, DentImages, new List <Guid> () { DentTag.Id }); // Now there are images with tags start training the project Console.WriteLine("\\tTraining"); var iteration = trainingApi.TrainProject(project.Id); // The returned iteration will be in progress, and can be queried periodically to see when it has completed while (iteration.Status == "Training") { Thread.Sleep(1000); // Re-query the iteration to get it's updated status iteration = trainingApi.GetIteration(project.Id, iteration.Id); } // The iteration is now trained. Make it the default project endpoint iteration.IsDefault = true; trainingApi.UpdateIteration(project.Id, iteration.Id, iteration); Console.WriteLine("Done!\\n"); // Now there is a trained endpoint, it can be used to make a prediction // Get the prediction key, which is used in place of the training key when making predictions var account = trainingApi.GetAccountInfo(); var predictionKey = account.Keys.PredictionKeys.PrimaryKey; // Create a prediction endpoint, passing in a prediction credentials object that contains the obtained prediction key PredictionEndpointCredentials predictionEndpointCredentials = new PredictionEndpointCredentials(predictionKey); PredictionEndpoint endpoint = new PredictionEndpoint(predictionEndpointCredentials); // Make a prediction against the new project Console.WriteLine("Making a prediction:"); var result = endpoint.PredictImage(project.Id, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\\t{c.Tag}: {c.Probability:P1}"); } Console.ReadKey(); }
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = nameof(AnalyseCustomImage))] HttpRequestMessage req, TraceWriter log) { using (var analytic = new AnalyticService(new RequestTelemetry { Name = nameof(AnalyseCustomImage) })) { try { var allTags = new List <string>(); var j = JObject.Parse(req.Content.ReadAsStringAsync().Result); var imageUrl = (string)j["imageUrl"]; var treasureId = (string)j["treasureId"]; var gameId = (string)j["gameId"]; var game = CosmosDataService.Instance.GetItemAsync <Game>(gameId).Result; if (game == null) { return(req.CreateErrorResponse(HttpStatusCode.NotFound, "Game not found")); } var treasure = game.Treasures.SingleOrDefault(t => t.Id == treasureId); if (treasure == null) { return(req.CreateErrorResponse(HttpStatusCode.NotFound, "Treasure not found")); } var api = new TrainingApi(new TrainingApiCredentials(ConfigManager.Instance.CustomVisionTrainingKey)); var account = api.GetAccountInfo(); var predictionKey = account.Keys.PredictionKeys.PrimaryKey; var creds = new PredictionEndpointCredentials(predictionKey); var endpoint = new PredictionEndpoint(creds); //This is where we run our prediction against the default iteration var result = endpoint.PredictImageUrl(new Guid(game.CustomVisionProjectId), new ImageUrl(imageUrl)); bool toReturn = false; // Loop over each prediction and write out the results foreach (var outcome in result.Predictions) { if (treasure.Attributes.Any(a => a.Name.Equals(outcome.Tag, StringComparison.InvariantCultureIgnoreCase))) { if (outcome.Probability >= ConfigManager.Instance.CustomVisionMinimumPredictionProbability) { toReturn = true; break; } } } return(req.CreateResponse(HttpStatusCode.OK, toReturn)); } catch (Exception e) { analytic.TrackException(e); return(req.CreateErrorResponse(HttpStatusCode.BadRequest, e)); } } }
/// <summary> /// 获取PredictionKey /// </summary> /// <returns></returns> public string GetPredictionKey() { return(trainingApi.GetAccountInfo().Keys.PredictionKeys.PrimaryKey); }
static void Main(string[] args) { // You can either add your training key here, pass it on the command line, or type it in when the program runs string trainingKey = GetTrainingKey("<your key here>", args); // Create the Api, passing in the training key TrainingApi trainingApi = new TrainingApi() { ApiKey = trainingKey }; // Create a new project Console.WriteLine("Creating new project:"); var project = trainingApi.CreateProject("My New Project"); // Make two tags in the new project var hemlockTag = trainingApi.CreateTag(project.Id, "Hemlock"); var japaneseCherryTag = trainingApi.CreateTag(project.Id, "Japanese Cherry"); // Add some images to the tags Console.WriteLine("\tUploading images"); LoadImagesFromDisk(); // Images can be uploaded one at a time foreach (var image in hemlockImages) { using (var stream = new MemoryStream(File.ReadAllBytes(image))) { trainingApi.CreateImagesFromData(project.Id, stream, new List <string>() { hemlockTag.Id.ToString() }); } } // Or uploaded in a single batch var imageFiles = japaneseCherryImages.Select(img => new ImageFileCreateEntry(Path.GetFileName(img), File.ReadAllBytes(img))).ToList(); trainingApi.CreateImagesFromFiles(project.Id, new ImageFileCreateBatch(imageFiles, new List <Guid>() { japaneseCherryTag.Id })); // Now there are images with tags start training the project Console.WriteLine("\tTraining"); var iteration = trainingApi.TrainProject(project.Id); // The returned iteration will be in progress, and can be queried periodically to see when it has completed while (iteration.Status == "Training") { Thread.Sleep(1000); // Re-query the iteration to get it's updated status iteration = trainingApi.GetIteration(project.Id, iteration.Id); } // The iteration is now trained. Make it the default project endpoint iteration.IsDefault = true; trainingApi.UpdateIteration(project.Id, iteration.Id, iteration); Console.WriteLine("Done!\n"); // Now there is a trained endpoint, it can be used to make a prediction // Get the prediction key, which is used in place of the training key when making predictions var account = trainingApi.GetAccountInfo(); var predictionKey = account.Keys.PredictionKeys.PrimaryKey; // Create a prediction endpoint, passing in obtained prediction key PredictionEndpoint endpoint = new PredictionEndpoint() { ApiKey = predictionKey }; // Make a prediction against the new project Console.WriteLine("Making a prediction:"); var result = endpoint.PredictImage(project.Id, testImage); // Loop over each prediction and write out the results foreach (var c in result.Predictions) { Console.WriteLine($"\t{c.Tag}: {c.Probability:P1}"); } Console.ReadKey(); }