private static async Task <MLResponse> makeRequest(object scoreRequest, BatteryTable dataPoint)
        {
            using (var client = new HttpClient())
            {
                const string apiKey = "9eKcgSItZYwTQTPujl42shH+QfoNhlU16vGXSrPT/B3IJGsJonA6n/qyy0I2m8XR10Ty/0xMS0XsjAZbAagi2A==";
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/subscriptions/4769386f1cdf4fb6bc3250b9336fc5bc/services/15086b35646f42c6a3ddb43193821092/execute?api-version=2.0&format=swagger");

                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();

                    MLResponse mlResponse = new MLResponse()
                    {
                        StatusCode = response.StatusCode,
                        Response   = result,
                        dateStamp  = dataPoint.DateStamp
                    };
                    return(mlResponse);
                }
                else
                {
                    string     responseBuilder = string.Format("The request failed with status code: {0}", response.StatusCode);
                    MLResponse mlResponse      = new MLResponse()
                    {
                        StatusCode = response.StatusCode,
                        Response   = responseBuilder
                    };
                    return(mlResponse);
                }
            }
        }
        public override async Task ProcessItem(dynamic eventData)
        {
            // Ensure this is a correctly-formatted event for ML; ignore it otherwise
            if (eventData == null || eventData.deviceid == null || eventData.cycle == null ||
                eventData.sensor9 == null || eventData.sensor11 == null || eventData.sensor14 == null || eventData.sensor15 == null)
            {
                return;
            }

            // The experiment theoretically supports multiple inputs at once,
            // even though we only get one value at a time, so the request
            // requires an array of inputs
            MLRequest mlRequest = new MLRequest(ML_REQUEST_COLUMNS, new string[, ]
            {
                {
                    // The id is required to be numeric, so we hash the actual device id
                    eventData.deviceid.ToString().GetHashCode().ToString(),
                    // The remaining entries are string representations of the numeric values
                    eventData.cycle.ToString(),
                    eventData.sensor9.ToString(),
                    eventData.sensor11.ToString(),
                    eventData.sensor14.ToString(),
                    eventData.sensor15.ToString()
                }
            }
                                                );

            HttpClient http = new HttpClient();

            http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _configurationProvider.GetConfigurationSettingValue("MLApiKey"));
            http.BaseAddress = new Uri(_configurationProvider.GetConfigurationSettingValue("MLApiUrl") + ML_ENDPOINT);

            HttpResponseMessage response = await http.PostAsJsonAsync("", mlRequest);

            if (response.IsSuccessStatusCode)
            {
                MLResponse result = JsonConvert.DeserializeObject <MLResponse>(await response.Content.ReadAsStringAsync());

                RulTableEntity entry = new RulTableEntity
                {
                    PartitionKey = eventData.deviceid.ToString(),
                    RowKey       = eventData.cycle.ToString(),
                    // Extract the single relevant RUL value from the JSON output
                    Rul = result.Results["data"].value.Values[0, RUL_COLUMN],
                    // Since the simulator might replay data, ensure we can overwrite table values
                    ETag = "*"
                };

                // We don't need a data model to represent the result of this operation,
                // so we use a stub table/model convertor
                await AzureTableStorageHelper.DoTableInsertOrReplaceAsync <object, RulTableEntity>(entry, (RulTableEntity e) => null,
                                                                                                   _configurationProvider.GetConfigurationSettingValue("eventHub.StorageConnectionString"),
                                                                                                   _configurationProvider.GetConfigurationSettingValue("MLResultTableName"));
            }
            else
            {
                throw new Exception(string.Format("The ML request failed with status code: {0}", response.StatusCode));
            }
        }
        public static async Task <List <MLResponse> > GetMLResponse(int seed)
        {
            SqlConnectionStringBuilder connectionString = buildConnectionString();
            List <BatteryTable>        dataPoints       = getDatabaseValue(connectionString, seed);
            List <MLResponse>          responses        = new List <MLResponse>();

            for (int i = 0; i < dataPoints.Count; i++)
            {
                BatteryTable currentPoint    = dataPoints[i];
                string       currentDateTime = currentPoint.DateStamp.ToString("yyyy-MM-dd HH:mm:ss");
                string       futureDateTime  = currentPoint.DateStamp.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
                var          scoreRequest    = new
                {
                    Inputs = new Dictionary <string, List <Dictionary <string, string> > >()
                    {
                        {
                            "input1",
                            new List <Dictionary <string, string> >()
                            {
                                new Dictionary <string, string>()
                                {
                                    {
                                        "DateTime", futureDateTime
                                    },
                                }
                            }
                        },
                        {
                            "input2",
                            new List <Dictionary <string, string> >()
                            {
                                new Dictionary <string, string>()
                                {
                                    {
                                        "DateTime", currentDateTime
                                    },
                                }
                            }
                        },
                    },
                    GlobalParameters = new Dictionary <string, string>()
                    {
                    }
                };
                MLResponse response = await makeRequest(scoreRequest, currentPoint);

                responses.Add(response);
            }
            return(responses);
        }
Exemplo n.º 4
0
        private void storeResponseOutput(MLResponse result)
        {
            HttpHelpers.DataAccess dataAccess = new HttpHelpers.DataAccess();
            String[] resultsHolder            = result.Response.Split(':');
            double   eval = 0.0;
            double   pred = 0.0;

            for (int i = 0; i < resultsHolder.Length; i++)
            {
                string temp    = resultsHolder[i];
                string extract = Regex.Match(temp, @"-?\d+(.\d+)?").Value;

                if (!String.IsNullOrEmpty(extract))
                {
                    if (extract.Contains('-'))
                    {
                        try
                        {
                            pred = Double.Parse(extract);
                        }
                        catch (FormatException)
                        {
                        }
                        catch (OverflowException)
                        {
                        }
                    }
                    else
                    {
                        try
                        {
                            eval = Double.Parse(extract);
                        }
                        catch (FormatException)
                        {
                        }
                        catch (OverflowException)
                        {
                        }
                    }
                }
            }
            ResponseOutput responseOutput = new ResponseOutput {
                DateStamp  = result.dateStamp,
                evaluation = eval,
                prediction = pred
            };

            dataAccess.storeNewRow(responseOutput);
        }
Exemplo n.º 5
0
        public async Task <ActionResult> Index()
        {
            MLResponse result = await HelperClasses.BatteryMLService.GetMLResponse();

            storeResponseOutput(result);
            List <ResponseOutput> chartData = getPlotPoints();
            HomeViewModel         hvm       = new HomeViewModel
            {
                Response  = result,
                chartData = chartData
            };

            return(View(hvm));
        }
        public async Task <string> GetRULAsync(string deviceId, string cycle, string sensor9, string sensor11, string sensor14, string sensor15)
        {
            // The experiment theoretically supports multiple inputs at once,
            // even though we only get one value at a time, so the request
            // requires an array of inputs
            MLRequest mlRequest = new MLRequest(ML_REQUEST_COLUMNS, new string[, ]
            {
                {
                    // The id is required to be numeric, so we hash the actual device id
                    deviceId,
                    // The remaining entries are string representations of the numeric values
                    cycle,
                    sensor9,
                    sensor11,
                    sensor14,
                    sensor15
                }
            }
                                                );

            HttpClient http = new HttpClient();

            http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _configurationProvider.GetConfigurationSettingValue("MLApiKey"));
            http.BaseAddress = new Uri(_configurationProvider.GetConfigurationSettingValue("MLApiUrl") + ML_ENDPOINT);

            HttpResponseMessage response = await http.PostAsJsonAsync("", mlRequest);

            if (response.IsSuccessStatusCode)
            {
                MLResponse result = JsonConvert.DeserializeObject <MLResponse>(await response.Content.ReadAsStringAsync());
                return(result.Results["data"].value.Values[0, RUL_COLUMN]);
            }
            else
            {
                throw new Exception(string.Format("The AML request failed with status code: {0}", response.StatusCode));
            }
        }
Exemplo n.º 7
0
        async Task ExecuteAddInvoiceCommandAsync()
        {
            try
            {
                IsBusy = true;
                // 1. Add camera logic.
                await CrossMedia.Current.Initialize();

                MediaFile photo;
                if (CrossMedia.Current.IsCameraAvailable)
                {
                    photo = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                    {
                        Directory = "Receipts",
                        Name      = "Receipt"
                    });
                }
                else
                {
                    photo = await CrossMedia.Current.PickPhotoAsync();
                }

                if (photo == null)
                {
                    PrintStatus("Photo was null :(");
                    return;
                }


                byte[] data = ReadFully(photo.GetStream());

                using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        var fileContent = new ByteArrayContent(data);
                        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") // attachment?
                        {
                            Name     = "file",                                                                  // required?
                            FileName = "test.jpg"
                        };
                        content.Add(fileContent);
                        //IsBusy = false;

                        var requestUri = "http://at-dev-vm-zxpapi-01.westus.cloudapp.azure.com/v1.0/groups/1/receipts";
                        //var requestUri = "http://requestb.in/11y6k4z1";
                        var response = await client.PostAsync(requestUri, content);

                        if (response.IsSuccessStatusCode)
                        {
                            string result = await response.Content.ReadAsStringAsync();

                            APIResponse apiResponse = JsonConvert.DeserializeObject <APIResponse>(result);

                            using (var clientML = new HttpClient())
                            {
                                string temp = apiResponse.Receipt_Url.Replace("https", "http");

                                var scoreRequest = new
                                {
                                    Inputs = new Dictionary <string, List <Dictionary <string, string> > >()
                                    {
                                        {
                                            "input1",
                                            new List <Dictionary <string, string> >()
                                            {
                                                new Dictionary <string, string>()
                                                {
                                                    //{ "Category", "" },
                                                    { "Url", temp },
                                                }
                                            }
                                        },
                                    },
                                    GlobalParameters = new Dictionary <string, string>()
                                    {
                                    }
                                };

                                var jsonToSend = JsonConvert.SerializeObject(scoreRequest);
                                var body       = new StringContent(jsonToSend, Encoding.UTF8, "application/json");

                                const string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Replace this with the API key for the web service
                                clientML.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                                clientML.BaseAddress = new Uri("https://xxx.services.azureml.net/subscriptions/xxxxxxxxx/services/xxxxxxx/execute?api-version=2.0&format=swagger");

                                var responseML = await clientML.PostAsync("", body);

                                if (responseML.IsSuccessStatusCode)
                                {
                                    string resultML = await responseML.Content.ReadAsStringAsync();

                                    // Convert JSON to object
                                    MLResponse obj = JsonConvert.DeserializeObject <MLResponse>(resultML);

                                    var outPuts = new List <MLOutputItem>(6);

                                    outPuts.Add(new MLOutputItem {
                                        Category = "Clothes and Accessories", Probability = (float)obj.Results.Output[0].ClothesAndAccessoriesProbability
                                    });
                                    outPuts.Add(new MLOutputItem {
                                        Category = "Daily Snacks", Probability = (float)obj.Results.Output[0].DailySnacksProbability
                                    });
                                    outPuts.Add(new MLOutputItem {
                                        Category = "Dining Out", Probability = (float)obj.Results.Output[0].DiningOutProbability
                                    });
                                    outPuts.Add(new MLOutputItem {
                                        Category = "Entertainment", Probability = (float)obj.Results.Output[0].EntertainmentProbability
                                    });
                                    outPuts.Add(new MLOutputItem {
                                        Category = "Fuel", Probability = (float)obj.Results.Output[0].FuelProbability
                                    });
                                    outPuts.Add(new MLOutputItem {
                                        Category = "Groceries", Probability = (float)obj.Results.Output[0].GroceriesProbability
                                    });

                                    outPuts = outPuts.OrderByDescending(x => x.Probability).ToList();

                                    Invoices.Add(new Invoice
                                    {
                                        ScoredLabel1 = outPuts[0].Category + " : " + outPuts[0].Probability,
                                        ScoredLabel2 = outPuts[1].Category + " : " + outPuts[1].Probability,
                                        ScoredLabel3 = outPuts[2].Category + " : " + outPuts[2].Probability,
                                        Photo        = photo.Path,
                                        TimeStamp    = DateTime.Now
                                    });
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                IsBusy = false;
            }
        }
        public static async Task <MLResponse> GetMLResponse()
        {
            SqlConnectionStringBuilder connectionString = buildConnectionString();
            BatteryTable dataPoint       = getDatabaseValue(connectionString);
            string       currentDateTime = dataPoint.DateStamp.ToString("yyyy-MM-dd HH:mm:ss");
            string       futureDateTime  = dataPoint.DateStamp.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
            var          scoreRequest    = new
            {
                Inputs = new Dictionary <string, List <Dictionary <string, string> > >()
                {
                    {
                        "input1",
                        new List <Dictionary <string, string> >()
                        {
                            new Dictionary <string, string>()
                            {
                                {
                                    "DateTime", futureDateTime
                                },
                            }
                        }
                    },
                    {
                        "input2",
                        new List <Dictionary <string, string> >()
                        {
                            new Dictionary <string, string>()
                            {
                                {
                                    "DateTime", currentDateTime
                                },
                            }
                        }
                    },
                },
                GlobalParameters = new Dictionary <string, string>()
                {
                }
            };

            using (var client = new HttpClient())
            {
                const string apiKey = "9eKcgSItZYwTQTPujl42shH+QfoNhlU16vGXSrPT/B3IJGsJonA6n/qyy0I2m8XR10Ty/0xMS0XsjAZbAagi2A==";
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/subscriptions/4769386f1cdf4fb6bc3250b9336fc5bc/services/15086b35646f42c6a3ddb43193821092/execute?api-version=2.0&format=swagger");

                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();

                    MLResponse mlResponse = new MLResponse()
                    {
                        StatusCode = response.StatusCode,
                        Response   = result,
                        dateStamp  = dataPoint.DateStamp
                    };
                    return(mlResponse);
                }
                else
                {
                    string     responseBuilder = string.Format("The request failed with status code: {0}", response.StatusCode);
                    MLResponse mlResponse      = new MLResponse()
                    {
                        StatusCode = response.StatusCode,
                        Response   = responseBuilder
                    };
                    return(mlResponse);
                }
            }
        }