Exemple #1
0
        public AzureDescriptionModel GetAzureDescriptionImage(byte[] imageBytes, string base64ImageString)
        {
            AzureDescriptionModel imageDescribe = null;

            Logger.Info($"AzureBLogic START - GetAzureDescriptionImage Action from image: '{base64ImageString}'");

            try
            {
                DateTime currentDateTime = DateTime.Now;

                if (!dateTimeInitAzureRequest.HasValue)
                {
                    dateTimeInitAzureRequest = currentDateTime;
                }
                else
                {
                    TimeSpan intervalToEvaluate = currentDateTime - dateTimeInitAzureRequest.Value;

                    if (intervalToEvaluate.Seconds > 60)
                    {
                        dateTimeInitAzureRequest = currentDateTime;
                        currentRequestAzure      = 1;
                    }
                }

                if (currentRequestAzure <= maxRequestAzure)
                {
                    currentRequestAzure++;
                    ReadAzureAppConfiguration();

                    imageDescribe = Task.Run(async() => await CallAzureDescribe(imageBytes)).Result;

                    if (useAzureTranslate)
                    {
                        imageDescribe = Task.Run(async() => await CallAzureTranslate(imageDescribe)).Result;
                    }
                }
                else
                {
                    Logger.Error($"AzureBLogic ERROR - GetAzureDescriptionImage Action Maximum requests per minute have been exhausted.");
                    imageDescribe = new AzureDescriptionModel()
                    {
                        ErrorMessage = $"Alcanzado el limite de peticiones por minuto, actualmente son: '{maxRequestAzure}' por minuto."
                    };
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc, "AzureBLogic ERROR - GetAzureDescriptionImage Action");
            }
            finally
            {
                Logger.Info($"AzureBLogic FINISH - GetAzureDescriptionImage Action from image: '{base64ImageString}' with response: '{imageDescribe}'");
            }

            return(imageDescribe);
        }
Exemple #2
0
        private async Task <AzureDescriptionModel> CallAzureDescribe(byte[] imageBytes)
        {
            Logger.Error($"AzureBLogic START - CallAzureDescribe Action");

            HttpClient                 client = new HttpClient();
            HttpResponseMessage        response;
            AzureDescribeResponseModel imageDescribeResponse;
            AzureDescriptionModel      imageDescribe = null;

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

            // Add the byte array as an octet stream to the request body.
            using (ByteArrayContent content = new ByteArrayContent(imageBytes))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                // Asynchronously call the REST API method.
                response = await client.PostAsync(urlDescribe, content);
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                // Asynchronously get the JSON response.
                string contentString = await response.Content.ReadAsStringAsync();

                imageDescribeResponse = JsonConvert.DeserializeObject <AzureDescribeResponseModel>(contentString);

                if (imageDescribeResponse != null)
                {
                    imageDescribe = imageDescribeResponse.Description;
                }
                else
                {
                    Logger.Error($"AzureBLogic ERROR - CallAzureDescribe Action response OK but NOT mapped object result");
                }
            }
            else
            {
                Logger.Error($"AzureBLogic ERROR - CallAzureDescribe Action response: '{response.RequestMessage}'");
            }

            return(imageDescribe);
        }
Exemple #3
0
        private async Task <AzureDescriptionModel> CallAzureTranslate(AzureDescriptionModel imageDescribe)
        {
            Logger.Error($"AzureBLogic START - CallAzureTranslate Action, imageDescribe: '{imageDescribe}'");

            HttpClient                    client = new HttpClient();
            HttpResponseMessage           response;
            List <AzureTranslateResponse> imageTranslateResponse;

            if (imageDescribe != null && imageDescribe.Captions.Count > 0 && !string.IsNullOrEmpty(imageDescribe.Captions[0].Text))
            {
                // Request headers
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", AzureTranslateSubscriptionKey);
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Region", AzureTranslateRegion);

                List <AzureTranslateRequest> azureTranslateRequestList = new List <AzureTranslateRequest>();

                foreach (AzureCaptionModel azureCaptionModel in imageDescribe.Captions)
                {
                    AzureTranslateRequest azureTranslateRequest = new AzureTranslateRequest()
                    {
                        Text = azureCaptionModel.Text
                    };

                    azureTranslateRequestList.Add(azureTranslateRequest);
                }

                var content = new StringContent(JsonConvert.SerializeObject(azureTranslateRequestList), Encoding.UTF8, "application/json");

                // Asynchronously call the REST API method.
                response = await client.PostAsync(urlTranslate, content);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // Asynchronously get the JSON response.
                    string contentString = await response.Content.ReadAsStringAsync();

                    imageTranslateResponse = JsonConvert.DeserializeObject <List <AzureTranslateResponse> >(contentString);

                    if (imageTranslateResponse != null)
                    {
                        int imageToTranslate = 0;
                        foreach (AzureTranslateResponse azureTranslateResponse in imageTranslateResponse)
                        {
                            foreach (AzureTranslateTranslation azureTranslateTranslation in azureTranslateResponse.translations)
                            {
                                if (imageToTranslate < imageDescribe.Captions.Count)
                                {
                                    imageDescribe.Captions[imageToTranslate].Text = azureTranslateTranslation.text;
                                    imageToTranslate++;
                                }
                            }
                        }
                    }
                    else
                    {
                        Logger.Error($"AzureBLogic ERROR - CallAzureTranslate Action response OK but NOT mapped object result");
                    }
                }
                else
                {
                    Logger.Error($"AzureBLogic ERROR - CallAzureTranslate Action response: '{response.RequestMessage}'");
                }
            }
            else
            {
                Logger.Error($"AzureBLogic ERROR - CallAzureTranslate Action not received imageDescribe object");
            }

            return(imageDescribe);
        }
        private bool GetAndSetDescriptionToImage(string currentImagePath, ImageModel currentImage)
        {
            Logger.Info($"MainWindow START - GetAndSetDescriptionToImage Action to path: '{currentImagePath}'");

            BitmapDecoder decoder;
            BitmapEncoder encoder;
            bool          resultGetOperation = false;

            try
            {
                using Stream fileStream = new FileStream(currentImagePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                decoder = new JpegBitmapDecoder(fileStream, BitmapCreateOptions.None, BitmapCacheOption.None);
                var frame = decoder.Frames[0];

                frame = BitmapFrame.Create(frame);
                BitmapMetadata metadata = (BitmapMetadata)frame.Metadata;

                byte[] imageBytes        = File.ReadAllBytes(currentImagePath);
                string base64ImageString = Convert.ToBase64String(imageBytes);

                Logger.Info($"MainWindow START - GetAndSetDescriptionToImage Action Get Azure Image Info from bytes[] of stringbase64: '{base64ImageString}'");

                AzureDescriptionModel azureDescribeResponseModel = azureBLogic.GetAzureDescriptionImage(imageBytes, base64ImageString);

                if (azureDescribeResponseModel != null &&
                    string.IsNullOrEmpty(azureDescribeResponseModel.ErrorMessage) &&
                    azureDescribeResponseModel.Captions != null &&
                    azureDescribeResponseModel.Captions.Count > 0)
                {
                    Logger.Info($"MainWindow START - GetAndSetDescriptionToImage Action get '{azureDescribeResponseModel.Captions.Count}' Description from Azure");

                    foreach (var caption in azureDescribeResponseModel.Captions)
                    {
                        Logger.Info($"MainWindow START - GetAndSetDescriptionToImage Action Image Caption {caption.Text} with Confidence {caption.Confidence}");
                    }

                    List <string> authors = new List <string>()
                    {
                        "Juan Manuel"
                    };

                    ReadOnlyCollection <string> authorsCollection = new ReadOnlyCollection <string>(authors);

                    metadata.Author          = authorsCollection;
                    metadata.Title           = azureDescribeResponseModel.Captions[0].Text;
                    metadata.ApplicationName = "GetDescriptionImageApp";
                    metadata.Comment         = azureDescribeResponseModel.Captions[0].Text;

                    currentImage.Alt         = metadata.Comment;
                    currentImage.Autor       = metadata.Author.ToString();
                    currentImage.Description = metadata.Comment;

                    encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(frame);

                    string newImageUri = ReplaceUri(currentImagePath);

                    using var targetStream = new FileStream(newImageUri, FileMode.Create);
                    encoder.Save(targetStream);

                    resultGetOperation = true;
                }
                else if (azureDescribeResponseModel != null && !string.IsNullOrEmpty(azureDescribeResponseModel.ErrorMessage))
                {
                    resultGetOperation = false;
                    MessageBox.Show(azureDescribeResponseModel.ErrorMessage, "Error procesando imagenes", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (azureDescribeResponseModel == null)
                {
                    resultGetOperation = false;
                    MessageBox.Show($"No se ha podido obtener información de Azure de la imaten '{currentImagePath}'", "Error procesando imagenes", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    resultGetOperation = false;
                    Logger.Info($"MainWindow START - GetAndSetDescriptionToImage Action NOT get Description from Azure");
                }
            }
            catch (Exception exc)
            {
                resultGetOperation = false;
                Logger.Error(exc, "MainWindow ERROR - GetAndSetDescriptionToImage Action");
                MessageBox.Show("Error Generico al intentar obtener la descripción de la imagen/es.", "Error procesando imagenes", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                Logger.Info("MainWindow FINISH - GetAndSetDescriptionToImage Action");
            }

            return(resultGetOperation);
        }