Beispiel #1
0
        private static ImagePredictionResultModel ProcessImagePredictions(string imageUrl, Guid projectId)
        {
            string predictionKey = "6c9f96aa9a574ab8b3aa18f5e0ec4c1c";
            var    shouldAlert   = false;

            // 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
            var result = endpoint.PredictImageUrl(projectId, new Microsoft.Cognitive.CustomVision.Models.ImageUrl(imageUrl));

            // Need to throttle the requests as to not upset it into throwing the dreaded 429 too many requests in a given period of time
            Thread.Sleep(200);

            //check for any probabilities greater than 90%
            shouldAlert = result.Predictions.Any(x => x.Probability > .9);

            if (shouldAlert)
            {
                return(result);
            }
            else
            {
                return(null);
            }
        }
Beispiel #2
0
        static void EfetuarTesteImagem(string caminho, bool eURL)
        {
            string chaveAPI     = "0c91a890892d40a0ba9f9e22a5e358de";
            string chaveProjeto = "4a1a0670-7689-4d01-ac59-fc56227cc3ed";

            // Crio o client do Custom View Service.
            PredictionEndpoint endpoint = new PredictionEndpoint()
            {
                ApiKey = chaveAPI
            };
            ImagePrediction resultado = null;

            // Verifico se o projeto é uma URL ou um arquivo local para usar o método correto.
            if (eURL)
            {
                resultado = endpoint.PredictImageUrl(new Guid(chaveProjeto), new ImageUrl(caminho));
            }
            else
            {
                resultado = endpoint.PredictImage(new Guid(chaveProjeto), File.OpenRead(caminho));
            }

            // Percorro as analises.
            foreach (var possibilidade in resultado.Predictions)
            {
                Console.WriteLine($"Tag: {possibilidade.TagName}");
                Console.WriteLine($"Possibilidade: {possibilidade.Probability:P1}");
            }
        }
Beispiel #3
0
        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));
            }
        }
Beispiel #4
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
        {
            #region Preparation
            var imageUrl = req.Query["imageUrl"];

            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var predictionSubscriptionKey = config["predictionSubscriptionKey"];
            var predictionProjectId       = config["predictionProjectId"];

            #endregion

            PredictionEndpoint endpoint = new PredictionEndpoint()
            {
                ApiKey = predictionSubscriptionKey
            };

            var result = endpoint.PredictImageUrl(Guid.Parse(predictionProjectId), new ImageUrl(imageUrl));

            #region Output
            return(new OkObjectResult(result));

            #endregion
        }
Beispiel #5
0
 private void InvokeCognitive(string photoUrl)
 {
     PredictionEndpoint endpoint = new PredictionEndpoint()
     {
         ApiKey = PREDICTION_KEY
     };
     ImageUrl url    = new ImageUrl(photoUrl);
     var      result = endpoint.PredictImageUrl(new Guid("152a2f03-5840-46b4-acfe-987a8342b47e"), url);
 }
Beispiel #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            // 変数定義
            bool   food = false;                        // "food" タグの有無
            string tag  = "";                           // カテゴリタグ

            ImageUrl url = new ImageUrl(textBox1.Text); //TextBoxからURLを取得

            var cvEp = new PredictionEndpoint {
                ApiKey = "PREDICTION_KEY"
            };
            var cvGuid      = new Guid("PROJECT_ID");
            var iterationId = new Guid("iterationId");

            try
            {
                // 画像を判定
                var cvResult = cvEp.PredictImageUrl(cvGuid, url, iterationId);
                foreach (var item in cvResult.Predictions)
                {
                    if (item.Probability > 0.8)
                    {
                        if (item.Tag == "食べ物")
                        {
                            food = true;
                        }
                        else
                        {
                            tag = item.Tag;
                            break;
                        }
                    }
                }

                if (tag != "")
                {
                    // タグに応じてメッセージをセット
                    label1.Text = "この写真は " + tag + " です。";
                }
                else if (food == true)
                {
                    //msg = "I'm not sure what it is ...";
                    label1.Text = "これは食べ物ってことしか分からないです。";
                }
                else
                {
                    //msg = "Send me food photo you are eating!";
                    label1.Text = "食べ物の写真を送ってください。";
                }
            }
            catch (Exception)
            {
                label1.Text = "エラー";
            }
        }
Beispiel #7
0
        public static List <PredictionModel> PredictionImageByUrl(string url)
        {
            string predictionKey = "c5bda34631dc4e399c3114f35fc7f980";
            var    projectId     = new Guid("9ad813c1-4f29-432a-9c9e-e0c53d51a1e9");

            // Create a prediction endpoint, passing in the obtained prediction key
            PredictionEndpoint endpoint = new PredictionEndpoint()
            {
                ApiKey = predictionKey
            };
            var result = endpoint.PredictImageUrl(projectId, new ImageUrl()
            {
                Url = url
            });
            List <PredictionModel> predictions = new List <PredictionModel>();
            // Loop over each prediction and write out the results
            var filterResult = result.Predictions.Where(p => p.Probability > 0.7).ToList();

            foreach (var p in filterResult)
            {
                predictions.Add(p);
            }
            return(predictions);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            var keys = GetApiKeys();

            var trainingApi = new TrainingApi {
                ApiKey = keys.TrainingKey
            };
            var predictionEndpoint = new PredictionEndpoint {
                ApiKey = keys.PredictionKey
            };

            var projects    = trainingApi.GetProjects();
            var herbProject = projects.FirstOrDefault(p => p.Name == "Herbs");

            Console.WriteLine("Press 1 to predict and 2 to train:");
            var pathChoice = Console.ReadLine();

            if ("1".Equals(pathChoice))
            {
                Console.WriteLine("Press 1 to predict on a URL or 2 to predict on a local file:");
                var predictType = Console.ReadLine();

                if ("1".Equals(predictType))
                {
                    Console.WriteLine("Input the URL to an image to test:");
                    var imageUrl = Console.ReadLine();

                    if (herbProject != null)
                    {
                        var result = predictionEndpoint.PredictImageUrl(herbProject.Id, new Microsoft.Cognitive.CustomVision.Prediction.Models.ImageUrl(imageUrl));

                        PrintResults(result);
                    }
                }
                else
                {
                    Console.WriteLine("Input path to image to test:");
                    var imagePath = Console.ReadLine();

                    if (!File.Exists(imagePath))
                    {
                        Console.WriteLine("File does not exist. Press enter to exit.");
                        Console.ReadLine();
                        return;
                    }

                    Console.WriteLine("Image predictions:");

                    var imageFile = File.OpenRead(imagePath);

                    if (herbProject != null)
                    {
                        var result = predictionEndpoint.PredictImage(herbProject.Id, imageFile);

                        PrintResults(result);
                    }
                    else
                    {
                        Console.WriteLine("Project doesn't exist.");
                    }
                }

                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Input path to image to train model with:");
                var imagePath = Console.ReadLine();

                Console.WriteLine("What tag would you give this image? Rosemary, cilantro, or basil?");
                var imageTag = Console.ReadLine();

                var capitilizedTag = char.ToUpper(imageTag.First()) + imageTag.Substring(1).ToLower();

                if (!File.Exists(imagePath))
                {
                    Console.WriteLine("File does not exist. Press enter to exit.");
                    Console.ReadLine();
                    return;
                }

                var imageFile = File.OpenRead(imagePath);

                var tags = trainingApi.GetTags(herbProject.Id);

                var matchedTag = tags.Tags.FirstOrDefault(t => t.Name == capitilizedTag);

                var memoryStream = new MemoryStream();
                imageFile.CopyTo(memoryStream);

                var fileCreateEntry = new ImageFileCreateEntry(imageFile.Name, memoryStream.ToArray());
                var fileCreateBatch = new ImageFileCreateBatch {
                    Images = new List <ImageFileCreateEntry> {
                        fileCreateEntry
                    }, TagIds = new List <Guid> {
                        matchedTag.Id
                    }
                };

                var result = trainingApi.CreateImagesFromFiles(herbProject.Id, fileCreateBatch);

                var resultImage = result.Images.FirstOrDefault();

                switch (resultImage.Status)
                {
                case "OKDuplicate":
                    Console.WriteLine("Image is already used for training. Please use another to train with");
                    Console.ReadLine();
                    break;

                default:
                    break;
                }

                var iteration = trainingApi.TrainProject(herbProject.Id);

                while (iteration.Status != "Completed")
                {
                    System.Threading.Thread.Sleep(1000);

                    iteration = trainingApi.GetIteration(herbProject.Id, iteration.Id);
                }

                iteration.IsDefault = true;
                trainingApi.UpdateIteration(herbProject.Id, iteration.Id, iteration);
                Console.WriteLine("Done training!");

                Console.ReadLine();
            }
        }
Beispiel #9
0
        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());
            }
        }
Beispiel #10
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                if (req.Method == HttpMethod.Get)
                {
                    log.Info("C# HTTP trigger function processed a request.");

                    // parse query parameter
                    string name = req.GetQueryNameValuePairs()
                                  .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                                  .Value;

                    // Get request body
                    dynamic data = await req.Content.ReadAsAsync <object>();

                    // Set name to query string or body data
                    name = name ?? data?.name;

                    return(name == null
                        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
                        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name));
                }

                else if (req.Method == HttpMethod.Post)
                {
                    var stream = await req.Content.ReadAsStreamAsync();

                    var prediction = new Prediction
                    {
                        ProjectId     = "7dad5391-6154-4d00-81ed-be1f56964d89", //This is the custom vision project we are predicting against
                        PredictionKey = "ca5362dcc67c45748973839961f84b8a",     //This is the custom vision project's prediction key we are predicting against
                        TimeStamp     = DateTime.UtcNow,
                        UserId        = Guid.NewGuid().ToString(),
                        ImageUrl      = await UploadImageToBlobStorage(stream),
                        Results       = new Dictionary <string, decimal>()
                    };

                    var endpoint = new PredictionEndpoint {
                        ApiKey = prediction.PredictionKey
                    };
                    //This is where we run our prediction against the default iteration
                    var result = endpoint.PredictImageUrl(new Guid(prediction.ProjectId), new ImageUrl(prediction.ImageUrl));

                    // 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);
                        }
                    }

                    await CosmosDataService.Instance.InsertItemAsync(prediction);

                    return(req.CreateResponse(HttpStatusCode.OK, prediction));
                }
                else
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, "Invalid request.."));
                }
            }
            catch (Exception e)
            {
                //Catch and unwind any exceptions that might be thrown and return the reason (non-production)
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, e.GetBaseException().Message));
            }

            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 (ideally this should go in your Function's App Settings)
                    var containerName = "images";
                    var endpoint      = $"https://fishkillappacctblob.blob.core.windows.net/{containerName}?sv=2017-11-09&ss=b&srt=sco&sp=rwdlac&se=2018-09-29T00:41:11Z&st=2018-09-28T16:41:11Z&spr=https,http&sig=jwlc9vDFgxzmFqDRUqFRKTEEyBobmct0Yed0Wj7zHyA%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 Custom Vision Hackathon");

                //Upload and return the new URL associated w/ this blob content
                await blockBlob.UploadFromStreamAsync(stream);

                return(blockBlob.StorageUri.PrimaryUri.ToString());
            }
        }
Beispiel #11
0
        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));
                }
            }
        }
Beispiel #12
0
        async public static Task <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)
                    {
                        var data = new Event("Custom image analyzed for treasure failed");
                        data.Add("hint", treasure.Hint).Add("source", treasure.ImageSource).Add("sent", imageUrl);
                        await EventHubService.Instance.SendEvent(data);

                        return(req.CreateErrorResponse(HttpStatusCode.NotFound, "Treasure not found"));
                    }

                    var endpoint = new PredictionEndpoint {
                        ApiKey = ConfigManager.Instance.CustomVisionPredictionKey
                    };

                    //This is where we run our prediction against the default iteration
                    var result = endpoint.PredictImageUrl(new Guid(game.CustomVisionProjectId), new ImageUrl(imageUrl));


                    ImageTagPredictionModel goodTag = null;
                    // Loop over each prediction and write out the results

                    foreach (var prediction in result.Predictions)
                    {
                        if (treasure.Attributes.Any(a => a.Name.Equals(prediction.Tag, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            if (prediction.Probability >= ConfigManager.Instance.CustomVisionMinimumPredictionProbability)
                            {
                                goodTag = prediction;
                                break;
                            }
                        }
                    }

                    {
                        var outcome = goodTag == null ? "failed" : "succeeded";
                        var data    = new Event($"Custom image analyzed for treasure {outcome}");

                        if (goodTag != null)
                        {
                            data.Add("tags", goodTag.Tag).Add("probability", goodTag.Probability.ToString("P"));
                        }

                        data.Add("hint", treasure.Hint).Add("source", treasure.ImageSource).Add("sent", imageUrl);

                        await EventHubService.Instance.SendEvent(data);
                    }

                    return(req.CreateResponse(HttpStatusCode.OK, goodTag != null));
                }
                catch (Exception e)
                {
                    analytic.TrackException(e);

                    return(req.CreateErrorResponse(HttpStatusCode.BadRequest, e));
                }
            }
        }
Beispiel #13
0
        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     = "YOUR_PROJECT_ID",                 //This is the custom vision project we are predicting against
                    PredictionKey = "YOUR_PREDICTION_KEY",             //This is the prediction key we are predicting against
                    TimeStamp     = DateTime.UtcNow,
                    UserId        = Guid.NewGuid().ToString(),
                    ImageUrl      = await UploadImageToBlobStorage(stream),
                    Results       = new Dictionary <string, decimal>()
                };

                var endpoint = new PredictionEndpoint {
                    ApiKey = prediction.PredictionKey
                };
                //This is where we run our prediction against the default iteration
                var result = endpoint.PredictImageUrl(new Guid(prediction.ProjectId), new ImageUrl(prediction.ImageUrl));

                // 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);
                    }
                }

                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://YOURSTORAGEACCOUNT.blob.core.windows.net/{containerName}/?sv=2017-04-17&ss=MAKE_SURE_TO_GET_A_SAS_TOKEN-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 Custom Vision Hackathon");

                //Upload and return the new URL associated w/ this blob content
                await blockBlob.UploadFromStreamAsync(stream);

                return(blockBlob.StorageUri.PrimaryUri.ToString());
            }
        }
        public static async Task <HttpResponseMessage> RunMakePrediction([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "api/MakePrediction")] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                //VERSION 1
                ////Extract the content body of the request
                //var stream = await req.Content.ReadAsStreamAsync();

                ////Retrieve a URL for the image being stored
                //var imageUrl = await UploadImageToBlobStorage(stream);

                ////Return the URL as the response content
                //return req.CreateResponse(HttpStatusCode.OK, imageUrl);


                //VERSION 2
                //========================================================================
                // Add this within the try clause
                //========================================================================

                //var stream = await req.Content.ReadAsStreamAsync();
                //var prediction = new Prediction
                //{
                //    TimeStamp = DateTime.UtcNow,
                //    UserId = Guid.NewGuid().ToString(),
                //    ImageUrl = await UploadImageToBlobStorage(stream)
                //};

                //await CosmosDataService.Instance.InsertItemAsync(prediction);
                //return req.CreateResponse(HttpStatusCode.OK, prediction);

                //VERSION 3
                var stream = await req.Content.ReadAsStreamAsync();

                var prediction = new Prediction
                {
                    //ProjectId = "YOUR_PROJECT_ID", //This is the custom vision project we are predicting against
                    //PredictionKey = "YOUR_PREDICTION_KEY", //This is the custom vision project's prediction key we are predicting against

                    ProjectId     = "3e152a33-92ee-4326-b4c9-c8068edab9d8", //"YOUR_PROJECT_ID", //This is the custom vision project we are predicting against
                    PredictionKey = "eafbd7b247bd41c1afd6d6da352f7099",     //"YOUR_PREDICTION_KEY", //This is the custom vision project's prediction key we are predicting against

                    TimeStamp = DateTime.UtcNow,
                    UserId    = Guid.NewGuid().ToString(),
                    ImageUrl  = await UploadImageToBlobStorage(stream),
                    Results   = new Dictionary <string, decimal>()
                };

                var endpoint = new PredictionEndpoint {
                    ApiKey = prediction.PredictionKey
                };
                //This is where we run our prediction against the default iteration
                var result = endpoint.PredictImageUrl(new Guid(prediction.ProjectId), new ImageUrl(prediction.ImageUrl));

                // 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);
                    }
                }

                await CosmosDataService.Instance.InsertItemAsync(prediction);

                return(req.CreateResponse(HttpStatusCode.OK, prediction));
            }
            catch (Exception e)
            {
                //Catch and unwind any exceptions that might be thrown and return the reason (non-production)
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, e.GetBaseException().Message));
            }

            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://customvisionrdr.blob.core.windows.net/images?sv=2017-11-09&ss=b&srt=sco&sp=rwdlac&se=2018-09-01T07:03:34Z&st=2018-08-21T23:03:34Z&spr=https&sig=Tdr03QWaQ7vCiy6Ut1G%2Fs05Kaw7iZ3JbhubljsMhKXA%3D";
                    //var endpoint = $"https://YOURSTORAGEACCOUNT.blob.core.windows.net/{containerName}/?sv=2017-04-17&ss=MAKE_SURE_TO_GET_A_SAS_TOKEN-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 Custom Vision Hackathon");

                //Upload and return the new URL associated w/ this blob content
                await blockBlob.UploadFromStreamAsync(stream);

                return(blockBlob.StorageUri.PrimaryUri.ToString());
            }
        }