
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Comprehend;
using Amazon.Comprehend.Model;
using Amazon.SageMakerRuntime;
using Amazon.SageMakerRuntime.Model;

using System;
using System.Threading.Tasks;
using System.IO;
using ICSharpCode.SharpZipLib.GZip;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Collections.Generic;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.UI.Popups;
using System.Text;
using System.Reflection;



namespace Comprehend
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            ChargeComp();

        }

        private async void ChargeComp()
        {
            s3Clt = new AmazonS3Client(AWSCred, AWSreg);

            ListBucketsResponse response = await s3Clt.ListBucketsAsync();
            foreach (S3Bucket s3Comp in response.Buckets)
            {

                cboCompIn.Items.Add(s3Comp.BucketName);
                cboCompOut.Items.Add(s3Comp.BucketName);
            }
        }

        //*************************************************************************************************
		//Définir votre région et vos paramètres d'identification, et l'ARN du rôle qui accède à Comprehend
		//*************************************************************************************************
		private static readonly RegionEndpoint AWSreg = RegionEndpoint.EUWest1;
		private static readonly string AWSAccessKey = "";
		private static readonly string AWSSecretKey = "";
		private static string dataAccessRoleARN = "arn:aws:iam:";

		private static readonly BasicAWSCredentials AWSCred = new BasicAWSCredentials(AWSAccessKey, AWSSecretKey);

		private static AmazonS3Client s3Clt;
		AmazonComprehendClient comprehendClient = new AmazonComprehendClient(AWSCred, AWSreg);
        DetectDominantLanguageResponse languageResponse;
        DetectSentimentResponse sentimentResponse;
        DetectEntitiesResponse entitiesResponse;
        DetectKeyPhrasesResponse phrasesResponse;
        DetectSyntaxResponse syntaxResponse;
        List<Entity> list;
        List<SyntaxToken> listTokens;
        private string strOut = "";

        private async void BtnCompLangue_Click(object sender, RoutedEventArgs e)
        {
            await DetectLangue(txtInput.Text);
            txtInputLangue.Text = $"Langue du texte = {strOut}";
        }

        private async Task DetectLangue(string strIn)
        {
            DetectDominantLanguageRequest detectDominant = new DetectDominantLanguageRequest
            {
                Text = strIn
            };

            languageResponse = await comprehendClient.DetectDominantLanguageAsync(detectDominant);

            float s = languageResponse.Languages[0].Score;
            foreach (DominantLanguage lang in languageResponse.Languages)
            {
                if (lang.Score >= s)
                {
                    strOut = lang.LanguageCode;
                    s = lang.Score;
                }
            };

        }

        private async void DetectCompLangue(string strCompIn, string strCompOut)
        {
            //Création d'un nom de job unique
            Random random = new Random();
            string strJobName = "Job" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();

            //Initialisation de la requête de détection de langue dominante
            StartDominantLanguageDetectionJobRequest startDominantRequest = new StartDominantLanguageDetectionJobRequest
            {
                InputDataConfig = new InputDataConfig
                {
                    InputFormat = InputFormat.ONE_DOC_PER_FILE,
                    S3Uri = "s3://" + strCompIn

                },
                OutputDataConfig = new OutputDataConfig
                {
                    S3Uri = "s3://" + strCompOut
                },
                JobName = strJobName,
				DataAccessRoleArn = dataAccessRoleARN
			};

            //Lancement de la requête et récupération de la réponse
            StartDominantLanguageDetectionJobResponse startDominantResponse;
            startDominantResponse = await comprehendClient.StartDominantLanguageDetectionJobAsync(startDominantRequest);

            //Mise en place du suivi de la réponse
            DescribeDominantLanguageDetectionJobRequest dominantLanguageDetectionJobRequest = new DescribeDominantLanguageDetectionJobRequest
            {
                JobId = startDominantResponse.JobId
            };
            DescribeDominantLanguageDetectionJobResponse dominantLanguageDetectionJobResponse = new DescribeDominantLanguageDetectionJobResponse
            {
                DominantLanguageDetectionJobProperties = new DominantLanguageDetectionJobProperties
                {
                    JobName = strJobName,
					DataAccessRoleArn = dataAccessRoleARN
				}
            };

            //Attente que la requête soit finie (elle est asynchrone)
            do
            {
                proCompJob.Value = proCompJob.Value + 10;
                if (proCompJob.Value == 100) proCompJob.Value = 10;
                await Task.Delay(1000);
                dominantLanguageDetectionJobResponse = await comprehendClient.DescribeDominantLanguageDetectionJobAsync(dominantLanguageDetectionJobRequest);
                txtCompLangue.Text = dominantLanguageDetectionJobResponse.DominantLanguageDetectionJobProperties.JobStatus;
            }
            while (dominantLanguageDetectionJobResponse.DominantLanguageDetectionJobProperties.JobStatus == JobStatus.IN_PROGRESS || dominantLanguageDetectionJobResponse.DominantLanguageDetectionJobProperties.JobStatus == JobStatus.SUBMITTED);

            proCompJob.Value = 0;

            //Lecture du fichier de sortie stocké dans S3
            LireLangueOutput(dominantLanguageDetectionJobResponse.DominantLanguageDetectionJobProperties.OutputDataConfig.S3Uri.ToString());

        }

        private async void LireLangueOutput(string strS3Uri)
        {

            //Récupération du nom de compartiment depuis l'Uri
            strS3Uri = strS3Uri.Remove(strS3Uri.LastIndexOf("/"));
            strS3Uri = strS3Uri.Substring(5);

            GetObjectRequest objectRequest = new GetObjectRequest
            {
                BucketName = strS3Uri,
                Key = "output.tar.gz"
            };
            GetObjectResponse objectResponse = await s3Clt.GetObjectAsync(objectRequest);

            //Décompression du fichier de réponse (tar.gz)
            Stream streamIn = new GZipInputStream(objectResponse.ResponseStream);
            StreamReader streamReader = new StreamReader(streamIn);

            //Suppression des premiers octets pour ne conserver que le JSON
            string mystr = streamReader.ReadToEnd().ToString();
            mystr = mystr.Substring(mystr.IndexOf("{"));
            JObject json = JObject.Parse(mystr);

            //Interrogation en Linq des pairs language/score
            var langueScores =
                from l in json["Languages"]
                select new { LC = (string)l["LanguageCode"], SC = (float)l["Score"] };

            //Recherche du score le plus élevé
            float score = 0;
            string langue = "";
            foreach (var item in langueScores)
            {
                if (item.SC > score)
                {
                    score = item.SC;
                    langue = item.LC;
                }
            };

            //Affichage de la langue dans une zone de texte
            txtCompLangue.Text = langue;

        }

        private void BtnCompLangue1_Click(object sender, RoutedEventArgs e)
        {
            DetectCompLangue(cboCompIn.SelectedValue.ToString(), cboCompOut.SelectedValue.ToString());
        }

        private async void BtnSentiment_Click(object sender, RoutedEventArgs e)
        {
            await DetectSentiment(txtInput.Text);
            txtInputLangue.Text = $"Sentiment dominant du texte : {strOut}";
        }

        private async Task DetectSentiment(string strIn)
        {
            await DetectLangue(strIn);
            DetectSentimentRequest detectSentiment = new DetectSentimentRequest
            {
                Text = strIn,
                LanguageCode = strOut
            };

            sentimentResponse = await comprehendClient.DetectSentimentAsync(detectSentiment);

            strOut = sentimentResponse.Sentiment.ToString();
            switch (strOut)
            {
                case "POSITIVE":
                    strOut = strOut + $" à {(int)(sentimentResponse.SentimentScore.Positive * 100)}%";
                    break;
                case "NEGATIVE":
                    strOut = strOut + $" à {(int)(sentimentResponse.SentimentScore.Negative * 100)}%";
                    break;
                case "NEUTRAL":
                    strOut = strOut + $" à {(int)(sentimentResponse.SentimentScore.Neutral * 100)}%";
                    break;
                case "MIXED":
                    strOut = strOut + $" à {(int)(sentimentResponse.SentimentScore.Mixed * 100)}%";
                    break;
            };

        }

        private void BtnCompSent_Click(object sender, RoutedEventArgs e)
        {
            DetectCompSent(cboCompIn.SelectedValue.ToString(), cboCompOut.SelectedValue.ToString());
        }

        private async void DetectCompSent(string strCompIn, string strCompOut)
        {
            //Création d'un nom de job unique
            Random random = new Random();
            string strJobName = "Job" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();

            //Initialisation de la requête de détection de langue dominante
            StartSentimentDetectionJobRequest startSentimentRequest = new StartSentimentDetectionJobRequest
            {
                InputDataConfig = new InputDataConfig
                {
                    InputFormat = InputFormat.ONE_DOC_PER_FILE,
                    S3Uri = "s3://" + strCompIn

                },
                OutputDataConfig = new OutputDataConfig
                {
                    S3Uri = "s3://" + strCompOut
                },
                JobName = strJobName,
				DataAccessRoleArn = dataAccessRoleARN,
                LanguageCode = "en"
            };

            //Lancement de la requête et récupération de la réponse
            StartSentimentDetectionJobResponse startSentimentResponse;
            startSentimentResponse = await comprehendClient.StartSentimentDetectionJobAsync(startSentimentRequest);

            //Mise en place du suivi de la réponse
            DescribeSentimentDetectionJobRequest describeSentimentRequest = new DescribeSentimentDetectionJobRequest
            {
                JobId = startSentimentResponse.JobId
            };
            DescribeSentimentDetectionJobResponse describeSentimentResponse = new DescribeSentimentDetectionJobResponse
            {
                SentimentDetectionJobProperties = new SentimentDetectionJobProperties
                {
                    JobName = strJobName,
					DataAccessRoleArn = dataAccessRoleARN
				}
            };

            //Attente que la requête soit finie (elle est asynchrone)
            do
            {
                proCompJob.Value = proCompJob.Value + 10;
                if (proCompJob.Value == 100) proCompJob.Value = 10;
                await Task.Delay(1000);
                describeSentimentResponse = await comprehendClient.DescribeSentimentDetectionJobAsync(describeSentimentRequest);
                txtCompLangue.Text = describeSentimentResponse.SentimentDetectionJobProperties.JobStatus;
            }
            while (describeSentimentResponse.SentimentDetectionJobProperties.JobStatus == JobStatus.IN_PROGRESS || describeSentimentResponse.SentimentDetectionJobProperties.JobStatus == JobStatus.SUBMITTED);

            proCompJob.Value = 0;

            //Lecture du fichier de sortie stocké dans S3
            LireSentOutput(describeSentimentResponse.SentimentDetectionJobProperties.OutputDataConfig.S3Uri.ToString());

        }

        private async void LireSentOutput(string strS3Uri)
        {

            //Récupération du nom de compartiment depuis l'Uri
            strS3Uri = strS3Uri.Remove(strS3Uri.LastIndexOf("/"));
            strS3Uri = strS3Uri.Substring(5);

            GetObjectRequest objectRequest = new GetObjectRequest
            {
                BucketName = strS3Uri,
                Key = "output.tar.gz"
            };
            GetObjectResponse objectResponse = await s3Clt.GetObjectAsync(objectRequest);

            //Décompression du fichier de réponse (tar.gz)
            Stream streamIn = new GZipInputStream(objectResponse.ResponseStream);
            StreamReader streamReader = new StreamReader(streamIn);

            //Suppression des premiers octets pour ne conserver que le JSON
            string mystr = streamReader.ReadToEnd().ToString();
            mystr = mystr.Substring(mystr.IndexOf("{"));
            JObject json = JObject.Parse(mystr);

            //Affichage du sentiment dans une zone de texte
            txtCompLangue.Text = json["Sentiment"].ToString();

        }

        private async void BtnEntites_Click(object sender, RoutedEventArgs e)
        {
            await DetectEntite(txtInput.Text);
            txtInputLangue.Text = $"Langue du texte : {strOut}";
        }

        private async Task DetectEntite(string strIn)
        {
            //Détection de la langue dominante
            await DetectLangue(strIn);

            //Création de la requête de détection des entités
            DetectEntitiesRequest detectEntities = new DetectEntitiesRequest
            {
                Text = strIn,
                LanguageCode = strOut
            };

            //Detection des entités
            entitiesResponse = await comprehendClient.DetectEntitiesAsync(detectEntities);

            //Affichage des entités dans un GridView
            list = entitiesResponse.Entities;
            grdData.ItemsSource = list;
        }

        private async void btnPhrase_Click(object sender, RoutedEventArgs e)
        {
            await DetectPhrase(txtInput.Text);
            txtInputLangue.Text = strOut;
        }

        private async Task DetectPhrase(string strIn)
        {
            //Détection de la langue dominante
            await DetectLangue(strIn);

            //Détection de la requête de détection des phrases
            DetectKeyPhrasesRequest phrasesRequest = new DetectKeyPhrasesRequest
            {
                Text = strIn,
                LanguageCode = strOut
            };

            //Detection des phrases
            phrasesResponse = await comprehendClient.DetectKeyPhrasesAsync(phrasesRequest);

            float score = 0;
            //Affichage de la phrase clé
            foreach (KeyPhrase phrase in phrasesResponse.KeyPhrases)
            {
                if (phrase.Score > score)
                {
                    strOut = $"Phrase clé : {phrase.Text} - {(phrase.Score * 100).ToString()}%";
                    score = phrase.Score;
                }
            }
        }

        private async void BtnSyntaxe_Click(object sender, RoutedEventArgs e)
        {
            await DetectSyntaxe(txtInput.Text);
            txtInputLangue.Text = $"Langue du texte : {strOut}";
        }

        private async Task DetectSyntaxe(string strIn)
        {
            //Détection de la langue dominante
            await DetectLangue(strIn);

            //Création de la requête de détection des entités syntaxiques
            DetectSyntaxRequest detectSyntax = new DetectSyntaxRequest
            {
                Text = strIn,
                LanguageCode = strOut
            };

            //Detection des entités syntaxiques
            syntaxResponse = await comprehendClient.DetectSyntaxAsync(detectSyntax);

            //Affichage des entités syntaxiques dans un GridView
            listTokens = syntaxResponse.SyntaxTokens;
            grdData.ItemsSource = listTokens;

        }

        private void BtnCompEntites_Click(object sender, RoutedEventArgs e)
        {
            DetectCompEntites(cboCompIn.SelectedValue.ToString(), cboCompOut.SelectedValue.ToString());
        }

        private async void DetectCompEntites(string strCompIn, string strCompOut)
        {
            //Création d'un nom de job unique
            Random random = new Random();
            string strJobName = "Job" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();

            //Initialisation de la requête de détection de langue dominante
            StartEntitiesDetectionJobRequest startEntitiesRequest = new StartEntitiesDetectionJobRequest
            {
                InputDataConfig = new InputDataConfig
                {
                    InputFormat = InputFormat.ONE_DOC_PER_FILE,
                    S3Uri = "s3://" + strCompIn

                },
                OutputDataConfig = new OutputDataConfig
                {
                    S3Uri = "s3://" + strCompOut
                },
                JobName = strJobName,
                DataAccessRoleArn = dataAccessRoleARN,
                LanguageCode = "fr"
            };

            //Lancement de la requête et récupération de la réponse
            StartEntitiesDetectionJobResponse startEntitiesResponse;
            startEntitiesResponse = await comprehendClient.StartEntitiesDetectionJobAsync(startEntitiesRequest);

            //Mise en place du suivi de la réponse
            DescribeEntitiesDetectionJobRequest describeEntitiesRequest = new DescribeEntitiesDetectionJobRequest
            {
                JobId = startEntitiesResponse.JobId
            };
            DescribeEntitiesDetectionJobResponse describeEntitiestResponse = new DescribeEntitiesDetectionJobResponse
            {
                EntitiesDetectionJobProperties = new EntitiesDetectionJobProperties
                {
                    JobName = strJobName,
                    DataAccessRoleArn = dataAccessRoleARN
				}
            };

            //Attente que la requête soit finie (elle est asynchrone)
            do
            {
                proCompJob.Value = proCompJob.Value + 10;
                if (proCompJob.Value == 100) proCompJob.Value = 10;
                await Task.Delay(1000);
                describeEntitiestResponse = await comprehendClient.DescribeEntitiesDetectionJobAsync(describeEntitiesRequest);
                txtCompLangue.Text = describeEntitiestResponse.EntitiesDetectionJobProperties.JobStatus;
            }
            while (describeEntitiestResponse.EntitiesDetectionJobProperties.JobStatus == JobStatus.IN_PROGRESS || describeEntitiestResponse.EntitiesDetectionJobProperties.JobStatus == JobStatus.SUBMITTED);

            proCompJob.Value = 0;

            //Lecture du fichier de sortie stocké dans S3
            LireEntitesOutput(describeEntitiestResponse.EntitiesDetectionJobProperties.OutputDataConfig.S3Uri.ToString());

        }

        private async void LireEntitesOutput(string strS3Uri)
        {

            //Récupération du nom de compartiment depuis l'Uri
            strS3Uri = strS3Uri.Remove(strS3Uri.LastIndexOf("/"));
            strS3Uri = strS3Uri.Substring(5);

            GetObjectRequest objectRequest = new GetObjectRequest
            {
                BucketName = strS3Uri,
                Key = "output.tar.gz"
            };
            GetObjectResponse objectResponse = await s3Clt.GetObjectAsync(objectRequest);

            //Décompression du fichier de réponse (tar.gz)
            Stream streamIn = new GZipInputStream(objectResponse.ResponseStream);
            StreamReader streamReader = new StreamReader(streamIn);

            //Suppression des premiers octets pour ne conserver que le JSON
            string mystr = streamReader.ReadToEnd().ToString();
            mystr = mystr.Substring(mystr.IndexOf("{"));
            JObject json = JObject.Parse(mystr);

            //Lecture du fichier en LINQ
            var tabEntites =
                from l in json["Entities"]
                select new { Type = l["Type"], Text = l["Text"] };

            //Databinding dynamique
            grdCompData.ItemsSource = tabEntites;

        }

        private void BtnCompPhrases_Click(object sender, RoutedEventArgs e)
        {
            DetectCompPhrases(cboCompIn.SelectedValue.ToString(), cboCompOut.SelectedValue.ToString());
        }

        private async void DetectCompPhrases(string strCompIn, string strCompOut)
        {
            //Création d'un nom de job unique
            Random random = new Random();
            string strJobName = "Job" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();

            //Initialisation de la requête de détection de langue dominante
            StartKeyPhrasesDetectionJobRequest startPhrasesRequest = new StartKeyPhrasesDetectionJobRequest
            {
                InputDataConfig = new InputDataConfig
                {
                    InputFormat = InputFormat.ONE_DOC_PER_FILE,
                    S3Uri = "s3://" + strCompIn

                },
                OutputDataConfig = new OutputDataConfig
                {
                    S3Uri = "s3://" + strCompOut
                },
                JobName = strJobName,
                DataAccessRoleArn = dataAccessRoleARN,
                LanguageCode = "fr"
            };

            //Lancement de la requête et récupération de la réponse
            StartKeyPhrasesDetectionJobResponse startPhrasesResponse;
            startPhrasesResponse = await comprehendClient.StartKeyPhrasesDetectionJobAsync(startPhrasesRequest);

            //Mise en place du suivi de la réponse
            DescribeKeyPhrasesDetectionJobRequest describePhrasesRequest = new DescribeKeyPhrasesDetectionJobRequest
            {
                JobId = startPhrasesResponse.JobId
            };
            DescribeKeyPhrasesDetectionJobResponse describePhrasesResponse = new DescribeKeyPhrasesDetectionJobResponse
            {
                KeyPhrasesDetectionJobProperties = new KeyPhrasesDetectionJobProperties
                {
                    JobName = strJobName,
                    DataAccessRoleArn = dataAccessRoleARN
				}
            };

            //Attente que la requête soit finie (elle est asynchrone)
            do
            {
                proCompJob.Value = proCompJob.Value + 10;
                if (proCompJob.Value == 100) proCompJob.Value = 10;
                await Task.Delay(1000);
                describePhrasesResponse = await comprehendClient.DescribeKeyPhrasesDetectionJobAsync(describePhrasesRequest);
                txtCompLangue.Text = describePhrasesResponse.KeyPhrasesDetectionJobProperties.JobStatus;
            }
            while (describePhrasesResponse.KeyPhrasesDetectionJobProperties.JobStatus == JobStatus.IN_PROGRESS || describePhrasesResponse.KeyPhrasesDetectionJobProperties.JobStatus == JobStatus.SUBMITTED);

            proCompJob.Value = 0;

            //Lecture du fichier de sortie stocké dans S3
            LirePhrasesOutput(describePhrasesResponse.KeyPhrasesDetectionJobProperties.OutputDataConfig.S3Uri.ToString());

        }

        private async void LirePhrasesOutput(string strS3Uri)
        {

            //Récupération du nom de compartiment depuis l'Uri
            strS3Uri = strS3Uri.Remove(strS3Uri.LastIndexOf("/"));
            strS3Uri = strS3Uri.Substring(5);

            GetObjectRequest objectRequest = new GetObjectRequest
            {
                BucketName = strS3Uri,
                Key = "output.tar.gz"
            };
            GetObjectResponse objectResponse = await s3Clt.GetObjectAsync(objectRequest);

            //Décompression du fichier de réponse (tar.gz)
            Stream streamIn = new GZipInputStream(objectResponse.ResponseStream);
            StreamReader streamReader = new StreamReader(streamIn);

            //Suppression des premiers octets pour ne conserver que le JSON
            string mystr = streamReader.ReadToEnd().ToString();
            mystr = mystr.Substring(mystr.IndexOf("{"));
            JObject json = JObject.Parse(mystr);

            var tabEntites =
                from l in json["KeyPhrases"]
                select new { Type = "", Text = l["Text"] };

            grdCompData.ItemsSource = tabEntites;

        }

        private void BtnDetectCustomClass_Click(object sender, RoutedEventArgs e)
        {
            DetectCustomClass(cboCompIn.SelectedValue.ToString(), cboCompOut.SelectedValue.ToString());

        }

        private async void DetectCustomClass(string strCompIn, string strCompOut)
        {
            //Création d'un nom de job unique
            Random random = new Random();
            string strJobName = "Job" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();

            //Initialisation de la requête de détection de langue dominante
            StartDocumentClassificationJobRequest startClassRequest = new StartDocumentClassificationJobRequest
            {
                InputDataConfig = new InputDataConfig
                {
                    InputFormat = InputFormat.ONE_DOC_PER_FILE,
                    S3Uri = "s3://" + strCompIn

                },
                OutputDataConfig = new OutputDataConfig
                {
                    S3Uri = "s3://" + strCompOut
                },
                JobName = strJobName,
                DataAccessRoleArn = dataAccessRoleARN,
				//ARN du classificateur de document - à indiquer
                DocumentClassifierArn = "arn:aws:comprehend:"
            };

            //Lancement de la requête et récupération de la réponse
            StartDocumentClassificationJobResponse startClassResponse;
            startClassResponse = await comprehendClient.StartDocumentClassificationJobAsync(startClassRequest);

            //Mise en place du suivi de la réponse
            DescribeDocumentClassificationJobRequest describeClassRequest = new DescribeDocumentClassificationJobRequest
            {
                JobId = startClassResponse.JobId
            };
            DescribeDocumentClassificationJobResponse describeClassResponse = new DescribeDocumentClassificationJobResponse
            {
                DocumentClassificationJobProperties = new DocumentClassificationJobProperties
                {
                    JobName = strJobName,
					//ARN du rôle de classificateur
                    DataAccessRoleArn = "arn:aws:iam:"
                }
            };

            //Attente que la requête soit finie (elle est asynchrone)
            do
            {
                proCompJob.Value = proCompJob.Value + 10;
                if (proCompJob.Value == 100) proCompJob.Value = 10;
                await Task.Delay(1000);
                describeClassResponse = await comprehendClient.DescribeDocumentClassificationJobAsync(describeClassRequest);
				txtCompLangue.Text = describeClassResponse.DocumentClassificationJobProperties.JobStatus;
            }
            while (describeClassResponse.DocumentClassificationJobProperties.JobStatus == JobStatus.IN_PROGRESS || describeClassResponse.DocumentClassificationJobProperties.JobStatus == JobStatus.SUBMITTED);

            proCompJob.Value = 0;

            //Lecture du fichier de sortie stocké dans S3
            LireClassOutput(describeClassResponse.DocumentClassificationJobProperties.OutputDataConfig.S3Uri.ToString());

        }

        private async void LireClassOutput(string strS3Uri)
        {

            //Récupération du nom de compartiment depuis l'Uri
            strS3Uri = strS3Uri.Remove(strS3Uri.LastIndexOf("/"));
            strS3Uri = strS3Uri.Substring(5);

            GetObjectRequest objectRequest = new GetObjectRequest
            {
                BucketName = strS3Uri,
                Key = "output.tar.gz"
            };
            GetObjectResponse objectResponse = await s3Clt.GetObjectAsync(objectRequest);

            //Décompression du fichier de réponse (tar.gz)
            Stream streamIn = new GZipInputStream(objectResponse.ResponseStream);
            StreamReader streamReader = new StreamReader(streamIn);

            string mystr = streamReader.ReadLine().ToString().TrimEnd();
			int i = 0;

			do
			{
				if (mystr.IndexOf("{") >= 0)
				{
					mystr = mystr.Substring(mystr.IndexOf("{"));
					JObject json = JObject.Parse(mystr);

					//Lecture du fichier en LINQ
					var tabEntites =
						from l in json["Classes"]
						select new { Nom = l["Name"], Score = l["Score"] };

					foreach (var tab in tabEntites)
					{
						txtCustomClassOut.Text += $"\n{i} - {tab.Nom} - {(float)tab.Score * 100}%";
					};
				}

				mystr = streamReader.ReadLine().ToString();
				i += 1;
			}
			while (!streamReader.EndOfStream);

		 }

        private void BtnChoixImage_Click(object sender, RoutedEventArgs e)
        {
            PredictImage();
        }

        public class MemoryStreamJsonConverter : JsonConverter
        {
            public override bool CanConvert(Type objectType)
            {
                return typeof(Stream).IsAssignableFrom(objectType);
            }

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                var bytes = serializer.Deserialize<byte[]>(reader);
                return bytes != null ? new MemoryStream(bytes) : new MemoryStream();
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                var bytes = ((MemoryStream)value).ToArray();
                serializer.Serialize(writer, bytes);
            }
        }

        private async void PredictImage()
        {
            FileOpenPicker fileOpen = new FileOpenPicker();
            fileOpen.FileTypeFilter.Add(".png");
            StorageFile file = await fileOpen.PickSingleFileAsync();
            if (file != null)
            {
                
                Stream stream = await file.OpenStreamForReadAsync();
                var ms= new MemoryStream();
                stream.CopyTo(ms);
                var jsond = JsonConvert.SerializeObject(ms, Formatting.None, new MemoryStreamJsonConverter());
                MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsond));

                AmazonSageMakerRuntimeClient amazonSageMakerRuntimeClient = new AmazonSageMakerRuntimeClient(AWSCred, AWSreg);
                
                InvokeEndpointRequest endpointRequest = new InvokeEndpointRequest
                {
					//Indiquer le nom de votre point de terminaison
                    EndpointName = "",
                    Body = memoryStream,
                    ContentType = "application/json",
                    Accept= "application/json"
                };
                 

                try
                {
                    InvokeEndpointResponse endpointResponse = await amazonSageMakerRuntimeClient.InvokeEndpointAsync(endpointRequest);
                    
                    txtSageMakerResponse.Text = endpointResponse.Body.ToString();
                }
                catch (System.Threading.Tasks.TaskCanceledException e)
                {
                    MessageDialog message = new MessageDialog(e.ToString());
                    await message.ShowAsync();
                }

                
            }
        }

        private void BtnEntitePerso_Click(object sender, RoutedEventArgs e)
        {
            DetectCustomEntite(cboCompIn.SelectedValue.ToString(), cboCompOut.SelectedValue.ToString());
        }

        private async void DetectCustomEntite(string strCompIn, string strCompOut)
        {
            //Création d'un nom de job unique
            Random random = new Random();
            string strJobName = "Job" + random.Next(0, 999999999).ToString() + random.Next(0, 999999999).ToString();

            //Initialisation de la requête de détection de langue dominante
            StartEntitiesDetectionJobRequest startEntitiesRequest = new StartEntitiesDetectionJobRequest
            {
                InputDataConfig = new InputDataConfig
                {
                    InputFormat = InputFormat.ONE_DOC_PER_LINE,
                    S3Uri = "s3://" + strCompIn

                },
                OutputDataConfig = new OutputDataConfig
                {
                    S3Uri = "s3://" + strCompOut
                },
                JobName = strJobName,
                DataAccessRoleArn = dataAccessRoleARN,
                LanguageCode = "en",
				//Indiquer l'ARN de l'Entity Recognizer
                EntityRecognizerArn= "arn:aws:comprehend:"
            };

            //Lancement de la requête et récupération de la réponse
            StartEntitiesDetectionJobResponse startEntitiesResponse;
            startEntitiesResponse = await comprehendClient.StartEntitiesDetectionJobAsync(startEntitiesRequest);

            //Mise en place du suivi de la réponse
            DescribeEntitiesDetectionJobRequest describeEntitiesRequest = new DescribeEntitiesDetectionJobRequest
            {
                JobId = startEntitiesResponse.JobId
            };
            DescribeEntitiesDetectionJobResponse describeEntitiestResponse = new DescribeEntitiesDetectionJobResponse
            {
                EntitiesDetectionJobProperties = new EntitiesDetectionJobProperties
                {
                    JobName = strJobName,
                    DataAccessRoleArn = dataAccessRoleARN
				}
            };

            //Attente que la requête soit finie (elle est asynchrone)
            do
            {
                proCompJob.Value = proCompJob.Value + 10;
                if (proCompJob.Value == 100) proCompJob.Value = 10;
                await Task.Delay(1000);
                describeEntitiestResponse = await comprehendClient.DescribeEntitiesDetectionJobAsync(describeEntitiesRequest);
                txtCompLangue.Text = describeEntitiestResponse.EntitiesDetectionJobProperties.JobStatus;
            }
            while (describeEntitiestResponse.EntitiesDetectionJobProperties.JobStatus == JobStatus.IN_PROGRESS || describeEntitiestResponse.EntitiesDetectionJobProperties.JobStatus == JobStatus.SUBMITTED);

            proCompJob.Value = 0;

            //Lecture du fichier de sortie stocké dans S3
            LireCustomEntitesOutput(describeEntitiestResponse.EntitiesDetectionJobProperties.OutputDataConfig.S3Uri.ToString());

        }

        private async void LireCustomEntitesOutput(string strS3Uri)
        {

            //Récupération du nom de compartiment depuis l'Uri
            strS3Uri = strS3Uri.Remove(strS3Uri.LastIndexOf("/"));
            strS3Uri = strS3Uri.Substring(5);

            GetObjectRequest objectRequest = new GetObjectRequest
            {
                BucketName = strS3Uri,
                Key = "output.tar.gz"
            };
            GetObjectResponse objectResponse = await s3Clt.GetObjectAsync(objectRequest);

            //Décompression du fichier de réponse (tar.gz)
            Stream streamIn = new GZipInputStream(objectResponse.ResponseStream);
            StreamReader streamReader = new StreamReader(streamIn);

            //Suppression des premiers octets pour ne conserver que le JSON
            string mystr = streamReader.ReadLine().ToString().TrimEnd();
            int i = 0;

            do
            {
                if (mystr.IndexOf("{") >= 0)
                {
                    mystr = mystr.Substring(mystr.IndexOf("{"));
                    JObject json = JObject.Parse(mystr);

                    //Lecture du fichier en LINQ
                    var tabEntites =
                        from l in json["Entities"]
                        select new { Nom = l["Text"], Score = l["Score"] };

                    foreach (var tab in tabEntites)
                    {
                        txtCustomClassOut.Text += $"\n{i} - {tab.Nom} - {(float)tab.Score * 100}%";
                    };
                }

                mystr = streamReader.ReadLine().ToString();
                i += 1;
            }
            while (!streamReader.EndOfStream);

        }

 		private void CboCompOut_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (cboCompIn.SelectedValue.ToString()!="" & cboCompOut.SelectedValue.ToString()!="")
			{
				btnCompLangue1.IsEnabled = true;
				btnCompSent.IsEnabled = true;
				btnCompEntites.IsEnabled = true;
				btnCompPhrases.IsEnabled = true;
				btnEntitePerso.IsEnabled = true;
				btnDetectCustomClass.IsEnabled = true;
			}
			else
			{
				btnCompLangue1.IsEnabled = false;
				btnCompSent.IsEnabled = false;
				btnCompEntites.IsEnabled = false;
				btnCompPhrases.IsEnabled = false;
				btnEntitePerso.IsEnabled = false;
				btnDetectCustomClass.IsEnabled = false;
			}
		}

		private void CboCompIn_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			cboCompOut.IsEnabled = true;
		}


	}
}
