public static CustomVisionViewModel Analyzed(CustomVisionRequest request, CustomVisionResponse response)
        {
            if (!string.IsNullOrWhiteSpace(response.ApiRequestErrorMessage) ||
                !string.IsNullOrWhiteSpace(response.ApiRequestErrorContent) ||
                !string.IsNullOrWhiteSpace(response.OtherErrorMessage) ||
                !string.IsNullOrWhiteSpace(response.OtherErrorContent))
            {
                return(new CustomVisionViewModel
                {
                    IsAnalyzed = false,

                    CustomVisionAnalyzeRequest = request,
                    CustomVisionAnalyzeResponse = null,

                    ApiRequestErrorMessage = response.ApiRequestErrorMessage,
                    ApiRequestErrorContent = response.ApiRequestErrorContent,
                    OtherErrorMessage = response.OtherErrorMessage,
                    OtherErrorContent = response.OtherErrorContent
                });
            }

            return(new CustomVisionViewModel
            {
                IsAnalyzed = true,

                CustomVisionAnalyzeRequest = request,
                CustomVisionAnalyzeResponse = response
            });
        }
Ejemplo n.º 2
0
        public PredictionResult Post([FromBody] CognitiveUrlRequest searchRequest)
        {
            string url = System.Configuration.ConfigurationManager.AppSettings["PredictionUrlForWebPath"];

            _client = new RestClient(url);
            if (searchRequest == null)
            {
                return new PredictionResult {
                           Errors = "Empty Search Request."
                }
            }
            ;
            if (searchRequest.ImageUrl.IsEmpty())
            {
                return new PredictionResult {
                           Errors = "Requested Url to be analysed is empty"
                }
            }
            ;

            var model = new CustomVisionRequest {
                url = searchRequest.ImageUrl
            };

            var request = new RestRequest(Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddBody(model);
            _client.AddDefaultHeader("Prediction-Key", System.Configuration.ConfigurationManager.AppSettings["PredictionKey"]);
            var res = _client.Execute <PredictionResult>(request);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                return new PredictionResult {
                           Errors = res.Content
                }
            }
            ;
            var response = res.Data;

            if (response != null && response.Predictions != null)
            {
                response.Predictions = response.Predictions.Where(p => p.Probability > 0.5).ToList();

                Utility.LogReport(response, searchRequest.Location);
                response.Predictions.ForEach(p => p.TagName = p.TagName.Replace('_', ' '));
            }

            return(response);
        }
    }
}
        public async Task <ActionResult <CustomVisionViewModel> > CustomVision([FromForm] CustomVisionRequest request)
        {
            var errorContent = "";

            if (string.IsNullOrWhiteSpace(request.CustomVisionPredictionKey))
            {
                errorContent += $"Missing or invalid Custom Vision Prediction Key (see 'Azure Settings' tab){Environment.NewLine}";
            }

            if (string.IsNullOrWhiteSpace(request.CustomVisionEndpoint))
            {
                errorContent += $"Missing or invalid Custom Vision Prediction Endpoint (see 'Azure Settings' tab){Environment.NewLine}";
            }

            if (string.IsNullOrWhiteSpace(request.ImageUrl) && (request.File == null || !_allowedFileContentType.Contains(request.File.ContentType)))
            {
                errorContent += $"Missing or invalid ImageUrl / no file provided{Environment.NewLine}";
            }

            if (request.ProjectId == null || Guid.Empty.Equals(request.ProjectId))
            {
                errorContent += $"Missing or invalid Project Id{Environment.NewLine}";
            }

            if (string.IsNullOrWhiteSpace(request.IterationPublishedName))
            {
                errorContent += $"Missing or invalid Iteration Published Name{Environment.NewLine}";
            }

            if (!string.IsNullOrWhiteSpace(errorContent))
            {
                return(View(CustomVisionViewModel.Analyzed(request,
                                                           new CustomVisionResponse
                {
                    OtherErrorMessage = "Request not processed due to the following error(s):",
                    OtherErrorContent = errorContent
                })));
            }

            Track("Vision_CustomVision");

            var imageAnalyzer = new ImageCustomVisionAnalyzer(request.CustomVisionPredictionKey, request.CustomVisionEndpoint, _httpClientFactory);
            var analyzeResult = await imageAnalyzer.AnalyzeAsync(request.ImageUrl, request.File, request.ProjectId, request.IterationPublishedName, request.ProjectType);

            return(View(CustomVisionViewModel.Analyzed(request, analyzeResult)));
        }
Ejemplo n.º 4
0
        public async Task <ActionResult> StoreFiles(int id, [FromForm] List <IFormFile> files)
        {
            try
            {
                if (files == null || files.Count == 0)
                {
                    return(BadRequest("Se deben incluir archivos"));
                }
                BlobStorageService blobStorageService = new BlobStorageService(this.configuration);
                bool negative = false;
                foreach (IFormFile formFile in files)
                {
                    var    fileName = Path.GetFileName(formFile.FileName);
                    string mimeType = formFile.ContentType;
                    byte[] fileData;
                    using (var target = new MemoryStream())
                    {
                        formFile.CopyTo(target);
                        fileData = target.ToArray();
                    }
                    string filePath = blobStorageService.UploadFileToBlob(formFile.FileName, fileData, mimeType);

                    if (mimeType == "image/png" || mimeType == "image/jpeg" || mimeType == "image/jpg")
                    {
                        DataRepresentationApi dataRepresentationApi = new DataRepresentationApi();
                        dataRepresentationApi.DataRepresentation = "URL";
                        dataRepresentationApi.Value = filePath;
                        var jsonString  = JsonConvert.SerializeObject(dataRepresentationApi);
                        var client      = new HttpClient();
                        var queryString = HttpUtility.ParseQueryString(string.Empty);

                        // Request headers
                        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "399faba124ec4fbfbef082c9f76267e3");
                        // Request parameters
                        queryString["enhanced"] = "true";
                        var uri = "https://miactlan.cognitiveservices.azure.com/contentmoderator/moderate/v1.0/ProcessImage/Evaluate?" + queryString;

                        HttpResponseMessage response;

                        response = await client.PostAsync(uri, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                        var responseImagenText = await response.Content.ReadAsStringAsync();

                        var resultImagen = JsonConvert.DeserializeObject <ImageApiResponse>(responseImagenText);
                        if (resultImagen.IsImageAdultClassified == true ||
                            resultImagen.AdultClassificationScore >= 0.9 ||
                            resultImagen.IsImageRacyClassified == true ||
                            resultImagen.RacyClassificationScore >= 0.9)
                        {
                            blobStorageService.DeleteBlobData(filePath);
                            filePath = null;
                            negative = true;
                        }


                        if (filePath != null)
                        {
                            Archivo archivo = new Archivo()
                            {
                                IdEntrada  = id,
                                UrlArchivo = filePath,
                                MimeType   = mimeType
                            };
                            _context.Archivos.Add(archivo);

                            await _context.SaveChangesAsync();

                            var customVisionClient = new HttpClient();
                            customVisionClient.DefaultRequestHeaders.Add("Prediction-Key", "fa249ba3cc844f2287c23e5bf874d4ac");

                            var uriCustomVision = "https://southcentralus.api.cognitive.microsoft.com/customvision/v3.0/Prediction/85352c53-ff84-4fd0-b3ff-b6212f5257c3/classify/iterations/mIActlanCV/url";

                            CustomVisionRequest customVisionRequest = new CustomVisionRequest();
                            customVisionRequest.Url = filePath;
                            var jsonStringCV = JsonConvert.SerializeObject(customVisionRequest);

                            HttpResponseMessage responseCustom;

                            responseCustom = await customVisionClient.PostAsync(uriCustomVision, new StringContent(jsonStringCV, Encoding.UTF8, "application/json"));

                            var resultCustom = await responseCustom.Content.ReadAsStringAsync();

                            var resultadoCV = JsonConvert.DeserializeObject <CustomVisionResponse>(resultCustom);
                            foreach (Prediction prediction in resultadoCV.predictions)
                            {
                                if (prediction.probability >= 0.9)
                                {
                                    var categoria = await _context.CategoriaArchivos.Where(x => x.CategoriaTagId == prediction.tagId).FirstOrDefaultAsync();

                                    if (categoria != null)
                                    {
                                        ArchivoCategoriaArchivo archivoCategoriaArchivo = new ArchivoCategoriaArchivo()
                                        {
                                            IdArchivo          = archivo.IdArchivo,
                                            IdCategoriaArchivo = categoria.IdCategoriaArchivo
                                        };
                                        _context.ArchivoCategoriaArchivos.Add(archivoCategoriaArchivo);
                                        await _context.SaveChangesAsync();
                                    }
                                }
                            }
                        }
                    }
                }

                if (negative == true)
                {
                    return(Ok("Se encontraron archivos con contenido inadecuado. No se registraron"));
                }

                return(Ok("Los archivos han sido registrados"));
            } catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }