public ActionResult <string> GetKeyPhrases(int id)
        {
            List <Models.KeyPhrase> obj     = new List <Models.KeyPhrase>();
            KeyPhraseBatchResult    result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                         new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("ja", "1", "猫は幸せ"),
                new MultiLanguageInput("de", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
                new MultiLanguageInput("en", "3", "My cat is stiff as a rock."),
                new MultiLanguageInput("es", "4", "A mi me encanta el fútbol!")
            })).Result;

            // Printing keyphrases
            foreach (var document in result2.Documents)
            {
                Models.KeyPhrase temp = new Models.KeyPhrase();
                //List<string> keys = new List<string>();
                temp.id = document.Id;

                foreach (string keyphrase in document.KeyPhrases)
                {
                    temp.KeyPhrases.Add(keyphrase);
                }
                obj.Add(temp);
            }
            return(Ok(obj));
        }
Esempio n. 2
0
        public static async Task <KeyPhrasesResult> GetKeyPhrasesAsync(string input, string language = "en")
        {
            KeyPhrasesResult keyPhrasesResult = new KeyPhrasesResult()
            {
                KeyPhrases = Enumerable.Empty <string>()
            };

            if (!string.IsNullOrEmpty(input))
            {
                KeyPhraseBatchResult result = await AnalyticsClient.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                                        new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(language, "0", input)
                }));

                if (result.Documents != null)
                {
                    List <string> phrases = new List <string>();

                    foreach (string keyPhrase in result.Documents[0].KeyPhrases)
                    {
                        phrases.Add(keyPhrase);
                    }

                    keyPhrasesResult.KeyPhrases = phrases;
                }

                if (result.Errors != null)
                {
                    // Just return the empty IEnumerable
                }
            }

            return(keyPhrasesResult);
        }
Esempio n. 3
0
        public static List <string> getAnalitcsResult(string inputText)
        {
            ITextAnalyticsAPI client = new TextAnalyticsAPI();

            client.AzureRegion     = AzureRegions.Westcentralus;
            client.SubscriptionKey = "";

            List <string> strList = new List <string>();


            KeyPhraseBatchResult result2 = client.KeyPhrases(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", inputText)
            }));

            strList.Add(result2.Documents[0].KeyPhrases[0]);

            SentimentBatchResult result3 = client.Sentiment(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", inputText)
            }));

            strList.Add(result3.Documents[0].Score.ToString());
            return(strList);
        }
 private ICollection <ImageTag> ExtractTags(KeyPhraseBatchResult result)
 {
     return(result.Documents[0].KeyPhrases.Select(k => new ImageTag()
     {
         Name = k, FromDescription = true
     }).ToList());
 }
Esempio n. 5
0
        private static void RunExperiment3(ITextAnalyticsClient client)
        {
            Console.WriteLine("\n\n===== Experiment 3. - extract keyphrases ======");

            KeyPhraseBatchResult result = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                     new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("ja", "1", "猫は幸せ"),
                new MultiLanguageInput("de", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fuß."),
                new MultiLanguageInput("en", "3", "My cat is stiff as a rock."),
                new MultiLanguageInput("es", "4", "A mi me encanta el fútbol!")
            })).Result;

            // Printing keyphrases
            foreach (var document in result.Documents)
            {
                Console.WriteLine($"Document ID: {document.Id} ");
                Console.WriteLine("\t Key phrases:");

                foreach (string keyphrase in document.KeyPhrases)
                {
                    Console.WriteLine($"\t\t{keyphrase}");
                }
            }
        }
        private async Task <IEnumerable <AnalysisResult> > GetAnalysisResultsAsync(MultiLanguageBatchInput batchInput)
        {
            KeyPhraseBatchResult keyPhraseBatchResult = await _textAnalyticsAPI.KeyPhrasesAsync(batchInput);

            SentimentBatchResult sentimentBatchResult = await _textAnalyticsAPI.SentimentAsync(batchInput);


            foreach (var keyPhrase in keyPhraseBatchResult.Documents)
            {
                string tweet = batchInput.Documents
                               .Where(d => d.Id == keyPhrase.Id)
                               .Select(t => t.Text)
                               .FirstOrDefault();

                var sentiment = sentimentBatchResult.Documents
                                .Where(s => s.Id == keyPhrase.Id)
                                .FirstOrDefault();

                if (IsSignificant(sentiment.Score) && !keyPhrase.KeyPhrases.Count().Equals(0))
                {
                    AnalysisResult analysisResult = new AnalysisResult
                    {
                        KeyPhrases = keyPhrase.KeyPhrases,
                        Attitude   = DeriveAttitude(sentiment.Score),
                        Tweet      = tweet
                    };

                    _analysisResults.Add(analysisResult);
                }
            }

            return(_analysisResults);
        }
        private static void ProcessKeyPhrases(string documentid, string text)
        {
            var credentials = new ApiKeyServiceClientCredentials("key here");

            ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials("key here"));

            client.AzureRegion = AzureRegions.Westeurope;

            KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                      new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", documentid + ":" + text, text)
            })).Result;

            foreach (var document in result2.Documents)
            {
                Console.WriteLine("Document ID: {0} ", document.Id);

                Console.WriteLine("\t Key phrases:");

                foreach (string keyphrase in document.KeyPhrases)
                {
                    Console.WriteLine("\t\t" + keyphrase);
                }
            }
        }
Esempio n. 8
0
        public Analyzer(string xml)
        {
            ITextAnalyticsAPI client    = Program.Client();
            string            xmlString = xml;

            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("\n\n####TEXT ANALYSIS####");
            KeyPhraseBatchResult analysis = client.KeyPhrases(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", xmlString),
            }));

            foreach (var item in analysis.Documents)
            {
                Console.WriteLine("Document ID: {0}", item.Id);
                Console.WriteLine("\t Key phrases");
                foreach (string keyphrase in item.KeyPhrases)
                {
                    Console.WriteLine(keyphrase);
                    phrases = item.KeyPhrases;
                }
            }
            Sentiment(phrases);
            Recommendations(phrases);
        }
Esempio n. 9
0
        public KeyPhraseBatchResult getKeyPhrases()
        {
            // Get keyphrases
            KeyPhraseBatchResult keyPhraseBatchResult = client.KeyPhrases(getMultiLanguageBatchInput());

            return(keyPhraseBatchResult);
        }
Esempio n. 10
0
        public static async Task <KeyPhrasesResult> GetKeyPhrasesAsync(string[] input, string language = "en")
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (!input.Any())
            {
                throw new ArgumentException("Input array is empty.");
            }

            var inputList = new List <MultiLanguageInput>();

            for (int i = 0; i < input.Length; i++)
            {
                inputList.Add(new MultiLanguageInput(language, i.ToString(), input[i]));
            }

            KeyPhraseBatchResult result = await client.KeyPhrasesAsync(multiLanguageBatchInput : new MultiLanguageBatchInput(inputList));

            IEnumerable <IList <string> > keyPhrases = result.Documents.OrderBy(x => x.Id).Select(x => x.KeyPhrases);

            return(new KeyPhrasesResult()
            {
                KeyPhrases = keyPhrases
            });
        }
Esempio n. 11
0
        public static Dictionary <string, List <KeyValuePair <string, string> > > IdentifyKeyPhrases(List <string> lstSentence)
        {
            var response = new Dictionary <string, List <KeyValuePair <string, string> > >();
            // Create a client.
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://westus.api.cognitive.microsoft.com"
            }; //Replace 'westus' with the correct region for your Text Analytics subscription

            var inputList = lstSentence.Select((l, i) => new MultiLanguageInput("en", i.ToString(), l)).ToList();

            KeyPhraseBatchResult result = client.KeyPhrasesAsync(new MultiLanguageBatchInput(inputList)).Result;

            // Printing entities results
            foreach (var document in result.Documents)
            {
                var entities = new List <KeyValuePair <string, string> >();
                foreach (string keyphrase in document.KeyPhrases)
                {
                    entities.Add(new KeyValuePair <string, string>(document.Id, keyphrase));
                }
                response.Add(document.Id, entities);
            }
            return(response);
        }
Esempio n. 12
0
        private static void KeyPhrases(ITextAnalyticsAPI client)
        {
            // Getting key-phrases
            Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======");

            var inputs2 = new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("zh", "1", "我的兔子花花好可爱."),
                new MultiLanguageInput("de", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
                new MultiLanguageInput("en", "3", "My cat is stiff as a rock."),
                new MultiLanguageInput("es", "4", "A mi me encanta el fútbol!")
            };

            KeyPhraseBatchResult result2 = client.KeyPhrases(new MultiLanguageBatchInput(inputs2));

            // Printing keyphrases
            foreach (var document in result2.Documents)
            {
                Console.WriteLine("Document ID: {0} ", document.Id);

                Console.WriteLine("\t Key phrases:");

                foreach (string keyphrase in document.KeyPhrases)
                {
                    Console.WriteLine("\t\t" + keyphrase);
                }

                Console.WriteLine($"Text: {inputs2.FirstOrDefault(i => i.Id == document.Id).Text}");
                Console.WriteLine();
            }
        }
Esempio n. 13
0
        public string[] getPhrases(string para)
        {
            string[] phrases = new string[100];
            // Create a client.
            TextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceMicrosoftClientCredentials())
            {
                AzureRegion = AzureRegions.Southeastasia // example
            };

            Console.OutputEncoding = System.Text.Encoding.UTF8;

            KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                      new List <MultiLanguageInput>()
            {
                //new MultiLanguageInput("en", "1", "????"),
                //new MultiLanguageInput("en", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
                //new MultiLanguageInput("en", "3", "My cat is stiff as a rock."),
                new MultiLanguageInput("en", "1", para + ".")
            })).Result;

            // Printing keyphrases
            foreach (var document in result2.Documents)
            {
                int i = 0;
                foreach (string keyphrase in document.KeyPhrases)
                {
                    phrases[i++] = keyphrase;
                }
            }
            return(phrases);
        }
Esempio n. 14
0
        private async Task <IList <IList <string> > > GetKeyPhrasesBatchAsync(IList <string> batchInputText)
        {
            KeyPhraseBatchResult result = await textAnalyticsClient.KeyPhrasesAsync(
                new MultiLanguageBatchInput(
                    batchInputText.Select((text, index) => new MultiLanguageInput("en", $"{index + 1}", text)).ToList()
                    )
                );

            return(result.Documents.Select(k => k.KeyPhrases).ToList());
        }
Esempio n. 15
0
        public IList <string> KeyPhrases(ITextAnalyticsClient client, string identity, string text)
        {
            KeyPhraseBatchResult result = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                     new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(identity, "1", text)
            })).Result;

            return(result.Documents[0].KeyPhrases);
        }
        public async Task <string[]> GetKeyPhrasesAsync(string text)
        {
            // Build our request model
            MultiLanguageBatchInput requestDocument = GetSingleInput(text);

            // Get the result
            KeyPhraseBatchResult result = await PostKeyPhrasesRequestAsync(requestDocument);

            // Return an array of all the key phrases
            return(result.Documents.SelectMany(x => x.KeyPhrases).ToArray());
        }
Esempio n. 17
0
        public void KeyPhrases()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "KeyPhrases");
                ITextAnalyticsClient client = GetClient(HttpMockServer.CreateInstance());
                KeyPhraseBatchResult result = client.KeyPhrases(
                    "I love my team mates");

                Assert.Equal("team mates", result.Documents[0].KeyPhrases[0]);
            }
        }
Esempio n. 18
0
        private async void button1_Click(object sender, EventArgs e)
        {
            textBox2.Clear();
            pictureBox1.Refresh();

            try
            {
                string imageFilePath = textBox1.Text;

                if (File.Exists(imageFilePath))
                {
                    pictureBox1.Load(imageFilePath);
                    // Make the REST API call.
                    textBox2.AppendText("\nWait a moment for the results to appear.");
                    await MakeOCRRequest(imageFilePath);
                }
                else
                {
                    textBox2.Text = "Invalid file path";
                }

                textBox2.AppendText("\n===== Poster - Key ======\n");

                // Create a client.
                ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials())
                {
                    AzureRegion = AzureRegions.Westcentralus
                };

                // Getting key-phrases
                KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(input: new MultiLanguageBatchInput(
                                                                          documents: new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(language, "0", poster),
                })
                                                                      ).Result;
                // Printing keyphrases
                foreach (var document in result2.Documents)
                {
                    textBox2.AppendText(String.Format("\nDocument ID: {0} \n", document.Id));

                    foreach (string keyphrase in document.KeyPhrases)
                    {
                        textBox2.AppendText("  " + keyphrase);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "发生异常:" + ex, "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                textBox2.Text = "上一次操作中发生了异常。";
            }
        }
Esempio n. 19
0
        private void getKeyWords()
        {
            KeyPhraseBatchResult result2 = Client.KeyPhrases(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(Lang.Iso6391Name, Id, Text),
            }));

            KeyWords = result2.Documents[0].KeyPhrases;
            getSentiment();
        }
        /// <summary>
        /// Query the Azure congnitive analytics API for text analysis. This utilizes a nuget package and is largely the example
        /// code they provided with a few tweaks.
        /// </summary>
        /// <param name="body">Text body to be analyzed</param>
        /// <returns>an instance of the Analytics class that has the relevant parts of the analysis repackaged for ease of use</returns>
        public Analytics Analyze(string body)//Note: this was private, but that made testing the controller difficult
        {
            // Create a client.
            ITextAnalyticsAPI client = new TextAnalyticsAPI();

            client.AzureRegion = AzureRegions.Westcentralus;

            client.SubscriptionKey = Configuration["textAPIKey"];

            // initialize output vars
            List <string> keyPhrases = new List <string>();
            float         sentiment  = 0;

            Console.OutputEncoding = System.Text.Encoding.UTF8;

            // Getting key-phrases
            // this is taken almost word for word from the example code in the docs for the API
            KeyPhraseBatchResult result2 = client.KeyPhrases(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "3", body),
            }));

            // Unpack key phrases into list
            foreach (var document in result2.Documents)
            {
                foreach (string keyphrase in document.KeyPhrases)
                {
                    keyPhrases.Add(keyphrase);
                }
            }

            // Extracting sentiment
            SentimentBatchResult result3 = client.Sentiment(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "0", body)
            }));

            // Unpack sentiment results
            foreach (var document in result3.Documents)
            {
                sentiment = (float)document.Score;
            }

            // Repack analysis into analytics instance for convenience of use.
            return(new Analytics()
            {
                Keywords = keyPhrases, Sentiment = sentiment
            });
        }
        public static async Task <SentimentKeyWords> BuildSentimentKeyWordsScoreAsync(string text, string language)
        {
            try
            {
                // Create a client.
                ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
                {
                    Endpoint = WebConfiguration.TextAnalyticsEndPoint,
                }; //Replace 'westus' with the correct region for your Text Analytics subscription


                SentimentBatchResult resultSentiment = await client.SentimentAsync(false,
                                                                                   new MultiLanguageBatchInput(
                                                                                       new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(language, "0", text),
                }));

                KeyPhraseBatchResult resultKeyWords = await client.KeyPhrasesAsync(false,
                                                                                   new MultiLanguageBatchInput(
                                                                                       new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(language, "3", text),
                }));

                var           scoreResult    = resultSentiment.Documents.FirstOrDefault();
                string        keywordsResult = string.Empty;
                StringBuilder builder        = new StringBuilder();
                var           keyWords       = resultKeyWords.Documents;

                foreach (var document in keyWords)
                {
                    foreach (string keyphrase in document.KeyPhrases)
                    {
                        builder.Append(keyphrase).Append(" | ");
                    }
                }

                var result = new SentimentKeyWords()
                {
                    Score    = scoreResult != null ? scoreResult.Score : 0,
                    KeyWords = builder != null?builder.ToString() : string.Empty
                };

                return(result);
            }
            catch (Exception ex)
            {
                SharedHelper.GetFullException(ex);
                return(new SentimentKeyWords());
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            // Get the path and filename to process from the user.
            Console.WriteLine("Optical Character Recognition:");
            Console.Write("Enter the path to an image with text you wish to read: ");
            string imageFilePath = Console.ReadLine();

            if (File.Exists(imageFilePath))
            {
                // Make the REST API call.
                Console.WriteLine("\nWait a moment for the results to appear.\n");
                MakeOCRRequest(imageFilePath).Wait();
            }
            else
            {
                Console.WriteLine("\nInvalid file path");
            }

            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("\n===== Poster - Key ======\n");

            // Create a client.
            ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials())
            {
                AzureRegion = AzureRegions.Westcentralus
            };

            // Getting key-phrases
            KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(input: new MultiLanguageBatchInput(
                                                                      documents: new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(language, "0", poster),
            })
                                                                  ).Result;

            // Printing keyphrases
            foreach (var document in result2.Documents)
            {
                Console.WriteLine("Document ID: {0} ", document.Id);

                foreach (string keyphrase in document.KeyPhrases)
                {
                    Console.WriteLine("  " + keyphrase);
                }
            }

            Console.WriteLine("\nPress Enter to exit...");
            Console.ReadLine();
        }
Esempio n. 23
0
        public void printKeyPhrases(KeyPhraseBatchResult result)
        {
            // Print keyphrases
            Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======");
            foreach (var document in result.Documents)
            {
                Console.WriteLine("Document ID: {0} ", document.Id);

                Console.WriteLine("\t Key phrases:");

                foreach (string keyphrase in document.KeyPhrases)
                {
                    Console.WriteLine("\t\t" + keyphrase);
                }
            }
        }
        public string[] ExtractKeyPhrases(string text, string language)
        {
            KeyPhraseBatchResult result = _AnalyticsClient.KeyPhrases(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(language, "1", text)
            }));

            if (result.Documents.Any())
            {
                return(result.Documents.First().KeyPhrases.ToArray());
            }

            return(new string[] { "Restricted" });
        }
Esempio n. 25
0
        private static async Task UpdateFoundationsTags(int searchStart, int searchSize, Nest.ElasticClient client, TextAnalyticsAPI textAnalyticsClient)
        {
            var searchResponse = client.Search <Stiftung>(s => s
                                                          .From(searchStart)
                                                          .Size(searchSize)
                                                          );

            var stiftungen = searchResponse.Documents.Where(s => s.tags == null || s.tags.Length < 1).ToArray();

            if (stiftungen.Length >= 1)
            {
                var stiftungsZwecke = await GetPurposeDescriptionsAsMultiLanguageInput(textAnalyticsClient, stiftungen);

                if (stiftungsZwecke.Count < 1)
                {
                    return;
                }
                KeyPhraseBatchResult result = await textAnalyticsClient.KeyPhrasesAsync(
                    new MultiLanguageBatchInput(stiftungsZwecke)
                    );

                // Printing key phrases and writing phrases to stiftung.
                foreach (var document in result.Documents)
                {
                    Console.WriteLine("Document ID: {0} ", document.Id);

                    Console.WriteLine("\t Key phrases:");

                    var  tags        = new List <string>();
                    Guid stiftungsId = new Guid(document.Id);

                    foreach (string keyphrase in document.KeyPhrases)
                    {
                        Console.WriteLine("\t\t" + keyphrase);
                        tags.Add(keyphrase);
                    }

                    var stiftung = new Stiftung();
                    stiftung.id        = stiftungsId;
                    stiftung.tags      = tags.ToArray();
                    stiftung.timestamp = DateTime.Now;

                    client.Update <Stiftung>(new Nest.DocumentPath <Stiftung>(stiftungsId), u => u.Doc(stiftung));
                }
                await Task.Delay(30000);
            }
        }
Esempio n. 26
0
        private void KeyPrhaseRecognition(ITextAnalyticsClient client, string text, string language)
        {
            KeyPhraseBatchResult result = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                     new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(language, "1", text)
            })).Result;

            foreach (var document in result.Documents)
            {
                Console.WriteLine("\t Key phrases:");
                foreach (string keyphrase in document.KeyPhrases)
                {
                    Console.WriteLine($"\t\t{keyphrase}");
                }
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Analyzes all the given sentences and queries them against the different apis
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="URLsources"></param>
        /// <param name="Sources"></param>
        /// <returns></returns>
        public List <Plagiat <string> > Check(List <string> origin, List <Uri> URLsources, List <String> Sources)
        {
            //google search with custom search
            GoogleSearch googleSearch = new GoogleSearch(new Uri("https://www.googleapis.com/customsearch/v1"));

            //europa pmc search for academic literatur in life science
            EuropaPMCSearch europaPMCSearch = new EuropaPMCSearch(new Uri("https://www.ebi.ac.uk/europepmc/webservices/rest/search?"));

            //create document statistics
            DocumentStatistics documentStatistics = new DocumentStatistics(origin);

            googleSearch.Check(documentStatistics);
            europaPMCSearch.Check(documentStatistics);

            //starting azure congitive services to interpret sentence
            // Create a client
            ITextAnalyticsAPI client = new TextAnalyticsAPI();

            client.AzureRegion     = AzureRegions.Westeurope;
            client.SubscriptionKey = "<placekey>";

            // Extracting language
            LanguageBatchResult languagesDetected = client.DetectLanguage(
                new BatchInput(documentStatistics.getBatchInput())
                );

            //store results
            foreach (var document in languagesDetected.Documents)
            {
                documentStatistics.updateSentenceLanguage(document.Id, document.DetectedLanguages[0].Iso6391Name);
            }

            // Getting key-phrases
            KeyPhraseBatchResult keyPhares = client.KeyPhrases(
                new MultiLanguageBatchInput(documentStatistics.getMultiLanguageBatchInput())
                );

            // Printing keyphrases
            foreach (var document in keyPhares.Documents)
            {
                documentStatistics.updateKeyPhares(document.Id, (List <string>)document.KeyPhrases);
            }

            return(documentStatistics.getPossiblePlagiates());
        }
Esempio n. 28
0
        public static List <string> GetKeyWords(string query)
        {
            // Create a client.
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                Endpoint = "https://southeastasia.api.cognitive.microsoft.com"
            };

            KeyPhraseBatchResult Result = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                     new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", query)
            })).Result;

            List <string> keyPhrases = Result.Documents[0].KeyPhrases as List <string>;

            return(keyPhrases);
        }
Esempio n. 29
0
        static public (string identifiedLanguage, string keyPhrases, double sentiment) EvaluateUtterance(TextAnalyticsClient textAnalyticsClient, string utterance)
        {
            string identifiedLanguage = null;
            string keyPhrases         = null;
            double sentiment          = Int32.MinValue;

            var detectLanguageResult = textAnalyticsClient.DetectLanguageAsync(new BatchInput(
                                                                                   new List <Input>()
            {
                new Input("1", utterance),
            })).Result;

            if (detectLanguageResult != null && detectLanguageResult.Errors.Count == 0)
            {
                identifiedLanguage = detectLanguageResult.Documents[0].DetectedLanguages[0].Name;
                string identfiedIsoLanguage = detectLanguageResult.Documents[0].DetectedLanguages[0].Iso6391Name;

                KeyPhraseBatchResult keyPhraseResult = textAnalyticsClient.KeyPhrasesAsync(new MultiLanguageBatchInput(
                                                                                               new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(identfiedIsoLanguage, "1", utterance)
                })).Result;

                if (keyPhraseResult != null && keyPhraseResult.Errors.Count == 0)
                {
                    // Collapse keyphrases into one space delimited string
                    keyPhrases = String.Join(" ", keyPhraseResult.Documents[0].KeyPhrases.Select(x => x.ToString()).ToArray());

                    SentimentBatchResult sentimentResult = textAnalyticsClient.SentimentAsync(
                        new MultiLanguageBatchInput(
                            new List <MultiLanguageInput>()
                    {
                        new MultiLanguageInput(identfiedIsoLanguage, "0", utterance)
                    })).Result;

                    if (sentimentResult != null && sentimentResult.Errors.Count == 0)
                    {
                        sentiment = sentimentResult.Documents[0].Score.Value;
                    }
                }
            }

            return(identifiedLanguage, keyPhrases, sentiment);
        }
Esempio n. 30
0
        public static async Task <List <TweetSentiment> > AnalyzeAsync(List <TweetSentiment> inputList, string incomingApiKey)
        {
            ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials(incomingApiKey));

            client.AzureRegion = AzureRegions.Westeurope;

            if (inputList.Count() >= 100)
            {
                List <MultiLanguageInput> multiLanguageInputs = ProcessToProperList(inputList);

                try
                {
                    SentimentBatchResult batchResult  = client.SentimentAsync(new MultiLanguageBatchInput(multiLanguageInputs)).Result;
                    KeyPhraseBatchResult batchResult2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(multiLanguageInputs)).Result;

                    foreach (var d in batchResult.Documents)
                    {
                        var tweet = inputList.Find(i => i.Id == d.Id);
                        tweet.Score = d.Score;
                    }

                    foreach (var d in batchResult2.Documents)
                    {
                        var tweet = inputList.Find(i => i.Id == d.Id);
                        tweet.KeyPhrases = String.Join(",", d.KeyPhrases);
                    }
                }

                catch (Exception ex)
                {
                    throw new Exception(ex.InnerException.ToString());
                }
            }

            else
            {
                inputList.ForEach(delegate(TweetSentiment action)
                {
                    action.Score = 0.5;
                });
            }

            return(inputList);
        }