예제 #1
0
        public async Task <KeyValuePair <bool, string> > PostString(string sourceHttpUrl, HttpContent?httpContent, bool verbose = true)
        {
            Uri sourceUri = new Uri(sourceHttpUrl);

            if (verbose)
            {
                _logger.LogInformation("[PostString] HttpClientHelper > " + sourceUri.Host + " ~ " + sourceHttpUrl);
            }

            // // allow whitelist and https only
            if (!_allowedDomains.Contains(sourceUri.Host) || sourceUri.Scheme != "https")
            {
                return
                    (new KeyValuePair <bool, string>(false, string.Empty));
            }

            try
            {
                using (HttpResponseMessage response = await _httpProvider.PostAsync(sourceHttpUrl, httpContent))
                    using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
                    {
                        var reader = new StreamReader(streamToReadFrom, Encoding.UTF8);
                        var result = await reader.ReadToEndAsync();

                        return(new KeyValuePair <bool, string>(response.StatusCode == HttpStatusCode.OK, result));
                    }
            }
            catch (HttpRequestException exception)
            {
                return(new KeyValuePair <bool, string>(false, exception.Message));
            }
        }
        /// <summary>
        /// Handles one round of Handling images (i.e. image saving, registering in Database, getting results for each image
        /// </summary>
        /// <param name="tempFolderPath">Path where to store file</param>
        /// <param name="url">Url at which DeepLearningAPI is server</param>
        /// <param name="files">Files (images) to be processed</param>
        /// <returns></returns>
        public async Task <ResponseModel> ProcessImagesAsync(
            string tempFolderPath,
            string url,
            List <IFormFile> files)
        {
            logger.LogDebug($"{correlationId} - Getting predictions for {files.Count} images");

            // orig. file names
            List <string>            images             = new List <string>(files.Count);
            List <PredictionRequest> predictionRequests = new List <PredictionRequest>(files.Count);
            List <ImageDefinition>   imageDefinitions   = new List <ImageDefinition>(files.Count);

            DateTime   started    = DateTime.Now;
            WebRequest webRequest = dbProvider.RegisterRequest(correlationId);
            // Save files and extract their EXIF data
            List <string> newFileNames = RegisterImages(
                webRequest,
                files,
                images,
                predictionRequests,
                tempFolderPath,
                imageDefinitions
                );

            // Send actual request
            logger.LogDebug($"{correlationId} - Sending request for predictions to \"{url}\"");
            PredictionResponseModel predictionResponse = await httpProvider
                                                         .PostAsync <PredictionResponseModel>(url, new PredictionRequestModel(newFileNames));

            if (predictionResponse.Data == null)
            {
                logger.LogError($"{correlationId} - Predictions from DeepLearning API was not returned.");

                // TODO: Register metrics
                throw new HttpRequestException($"Response from {url} does not contain any data");
            }

            // TODO: Save results to DB..
            // predictionResponse.Data.ForEach();

            // collect all results (amount: images x labels)
            List <PredictionResult> allPredictionResults = predictionResponse.Data
                                                           .Select((imagePredictions, i) =>
                                                                   imagePredictions.Select(prediction => new PredictionResult
            {
                Label             = prediction.Key,
                Score             = prediction.Value,
                ImageDefinition   = imageDefinitions[i],
                PredictionRequest = predictionRequests[i]
            }).ToList())
                                                           .Aggregate((predictions1, predictions2) =>
            {
                predictions1.AddRange(predictions2);
                return(predictions1);
            });

            // save results to db
            dbProvider.RegisterPredictionResults(allPredictionResults);
            dbProvider.RegisterMetrics(new Metric
            {
                WebRequestId = webRequest.WebRequestId,
                MetricCode   = "OVERALL",
                Started      = started,
                Ended        = DateTime.Now
            });

            // map image orig. names to prediction response
            return(new ResponseModel(predictionResponse.Data.ToDictionary(predictions => images[predictionResponse.Data.IndexOf(predictions)])));
        }