Пример #1
0
        public void sentimentAnalysisExample(ITextAnalyticsClient client)
        {
            var result = client.Sentiment(txt_Feedback.Text, "en");

            //var result = client.Sentiment("I hate you", "en");  -- Debugging purposes --
            txt_Score.Text = $"{result.Score:0.00}";
        }
Пример #2
0
        /// <summary>
        /// Initializes the static members of the EchoWithCounterBot class
        /// </summary>
        static EchoWithCounterBot()
        {
            var config = Startup.Configuration;

            var textAnalyticsKey      = config.GetSection("textAnalyticsKey")?.Value;
            var textAnalyticsEndpoint = config.GetSection("textAnalyticsEndpoint")?.Value;

            textAnalyticsClient = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(textAnalyticsKey))
            {
                Endpoint = config.GetSection("textAnalyticsEndpoint")?.Value,
            };

            var searchName  = config.GetSection("searchName")?.Value;
            var searchIndex = config.GetSection("searchIndex")?.Value;
            var searchKey   = config.GetSection("searchKey")?.Value;

            searchClient = new SearchIndexClient(searchName, searchIndex, new SearchCredentials(searchKey));

            stopset = new HashSet <string>(stopwords.Split());
            greeted = new HashSet <string>()
            {
                "default-user"
            };

            cryptonyms = JsonConvert.DeserializeObject <Dictionary <string, string> >
                             (File.ReadAllText("cia-cryptonyms.json"));

            searchUrl = config.GetSection("searchUrl")?.Value;
        }
Пример #3
0
 static NLPService()
 {
     _client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
     {
         Endpoint = "https://westus.api.cognitive.microsoft.com/"
     };
 }
Пример #4
0
        public async Task Entities()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "Entities");
                ITextAnalyticsClient client = GetClient(HttpMockServer.CreateInstance());
                EntitiesBatchResult  result = await client.EntitiesAsync(
                    null,
                    new MultiLanguageBatchInput(
                        new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput()
                    {
                        Id = "id",
                        Text = "Microsoft released Windows 10",
                        Language = "en"
                    }
                }));

                Assert.Equal("Microsoft", result.Documents[0].Entities[0].Name);
                Assert.Equal("a093e9b9-90f5-a3d5-c4b8-5855e1b01f85", result.Documents[0].Entities[0].BingId);
                Assert.Equal("Microsoft", result.Documents[0].Entities[0].Matches[0].Text);
                Assert.Equal(0.12508682244047509, result.Documents[0].Entities[0].Matches[0].WikipediaScore);
                Assert.Equal(0.99999618530273438, result.Documents[0].Entities[0].Matches[0].EntityTypeScore);
                context.Stop();
            }
        }
Пример #5
0
 public LanguageController()
 {
     _taClient = new TextAnalyticsClient(new MockCredentials())
     {
         Endpoint = ServiceEndpoint
     };
 }
Пример #6
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}");
                }
            }
        }
Пример #7
0
        public async void GivenAnyMessageActivity_WhenGetSentimentIsInvoked_ThenScoreIsBeingReturned(
            ITextAnalyticsClient textAnalyticsClient,
            IMessageActivity activity,
            double sentiment)
        {
            // Arrange
            var instrumentation = new SentimentClient(textAnalyticsClient);
            var response        = new HttpOperationResponse <SentimentBatchResult>
            {
                Body = new SentimentBatchResult(new[] { new SentimentBatchResultItem(sentiment) })
            };

            Mock.Get(textAnalyticsClient)
            .Setup(tac => tac.SentimentWithHttpMessagesAsync(
                       It.IsAny <MultiLanguageBatchInput>(),
                       It.IsAny <Dictionary <string, List <string> > >(),
                       It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(response));

            // Act
            var score = await instrumentation.GetSentiment(activity)
                        .ConfigureAwait(false);

            // Assert
            score.Should().Be(sentiment);
        }
Пример #8
0
        static void sentimentAnalysisExample(ITextAnalyticsClient client)
        {
            var result = client.Sentiment("I had the best day of my life.", "en");

            Console.WriteLine("I had the best day of my life.");
            Console.WriteLine($"Sentiment Score: {result.Score:0.00}");
        }
 /// <summary>
 /// The API returns a list of recognized entities in a given document.
 /// </summary>
 /// <remarks>
 /// To get even more information on each recognized entity we recommend using
 /// the Bing Entity Search API by querying for the recognized entities names.
 /// See the &lt;a
 /// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages"&gt;Supported
 /// languages in Text Analytics API&lt;/a&gt; for the list of enabled
 /// languages.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='showStats'>
 /// (optional) if set to true, response will contain input and document level
 /// statistics.
 /// </param>
 /// <param name='multiLanguageBatchInput'>
 /// Collection of documents to analyze.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<EntitiesBatchResult> EntitiesAsync(this ITextAnalyticsClient operations, bool? showStats = default(bool?), MultiLanguageBatchInput multiLanguageBatchInput = default(MultiLanguageBatchInput), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.EntitiesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
Пример #10
0
 /// <summary>
 /// The API returns a numeric score between 0 and 1.
 /// </summary>
 /// <remarks>
 /// Scores close to 1 indicate positive sentiment, while scores close to 0
 /// indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
 /// (e.g. a factoid statement). See the &lt;a
 /// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages"&gt;Text
 /// Analytics Documentation&lt;/a&gt; for details about the languages that are
 /// supported by sentiment analysis.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='showStats'>
 /// (optional) if set to true, response will contain input and document level
 /// statistics.
 /// </param>
 /// <param name='multiLanguageBatchInput'>
 /// Collection of documents to analyze.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <SentimentBatchResult> SentimentBatchAsync(this ITextAnalyticsClient operations, MultiLanguageBatchInput multiLanguageBatchInput = default, bool?showStats = default, CancellationToken cancellationToken = default)
 {
     using (var _result = await operations.SentimentWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 public TextAnalyzer()
 {
     _client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(SubscriptionKey))
     {
         Endpoint = ApiEndpoint
     };
 }
Пример #12
0
        public static async Task <IActionResult> GetTextSentimentAzure(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "text/sentiment/azure")]
            HttpRequest request,
            TraceWriter traceWriter,
            ExecutionContext executionContext
            )
        {
            var appsettings = new AppSettings(executionContext);
            var azureCognitiveServicesConfig = appsettings.AzureCognitiveServicesConfig;

            _textAnalyticsClient = _textAnalyticsClient ?? GetTextAnalyticsClient(azureCognitiveServicesConfig);

            var documentBatch = JsonConvert.DeserializeObject <DocumentBatch>(await GetBodyAsString(request));

            var documents = documentBatch.Documents.Select((Models.Document doc) => new MultiLanguageInput
            {
                Id       = doc.Id,
                Language = doc.LanguageCode,
                Text     = doc.Text
            }).ToList();

            try
            {
                var sentimentBatchResult = await _textAnalyticsClient.SentimentAsync(new MultiLanguageBatchInput(documents));

                var result = DocumentBatchSentimentUtil.FromSentimentBatchResult(sentimentBatchResult);
                return(new OkObjectResult(result));
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + ex.InnerException?.ToString();
                traceWriter.Error(error, ex);
                return(new BadRequestObjectResult(error));
            }
        }
 /// <summary>
 /// The API returns the detected language and a numeric score between 0 and 1.
 /// </summary>
 /// <remarks>
 /// Scores close to 1 indicate 100% certainty that the identified language is
 /// true. A total of 120 languages are supported.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='showStats'>
 /// (optional) if set to true, response will contain input and document level
 /// statistics.
 /// </param>
 /// <param name='languageBatchInput'>
 /// Collection of documents to analyze.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task<LanguageBatchResult> DetectLanguageAsync(this ITextAnalyticsClient operations, bool? showStats = default(bool?), LanguageBatchInput languageBatchInput = default(LanguageBatchInput), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.DetectLanguageWithHttpMessagesAsync(showStats, languageBatchInput, null, cancellationToken).ConfigureAwait(false))
     {
         return _result.Body;
     }
 }
 /// <summary>
 /// The API returns the detected language and a numeric score between 0 and 1.
 /// </summary>
 /// <remarks>
 /// Scores close to 1 indicate 100% certainty that the identified language is
 /// true. A total of 120 languages are supported.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='input'>
 /// Collection of documents to analyze.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <LanguageBatchResult> DetectLanguageAsync(this ITextAnalyticsClient operations, BatchInput input, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.DetectLanguageWithHttpMessagesAsync(input, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 public LanguageController()
 {
     _taClient = new TextAnalyticsClient(new MockCredentials())
     {
         // Ensure the sdk client makes requests to your cognitive service containers instead of the cloud API
         Endpoint = ServiceEndpoint
     };
 }
Пример #16
0
        //For TextAnalytics
        static double sentimentAnalysisExample(ITextAnalyticsClient client, string message) //戻り値をvoidからdouble型に変更
        {
            var result = client.Sentiment(message, "ja");                                   //引数messageを分析対象にし、言語は日本語に設定

            Debug.WriteLine($"User Message: {message}");                                    //引数messageの内容を出力
            Debug.WriteLine($"Sentiment Score1: {result.Score:0.00}");                      //出力確認1
            return((double)result.Score);                                                   //分析スコアを返す
        }
Пример #17
0
 public TextAnalytics(string meetingMinutesFilePath, string fullTranscribeSpeechPath)
 {
     _meetingMinutesFilePath   = meetingMinutesFilePath;
     _fullTranscribeSpeechPath = fullTranscribeSpeechPath;
     _client = new TextAnalyticsClient(new TextAnalyticsApiKeyServiceClientCredentials())
     {
         Endpoint = "https://eastus.api.cognitive.microsoft.com"
     };
 }
Пример #18
0
        public void GivenEmptyTextAnalyticsClient_WhenSentimentClientIsCreated_ThenExceptionIsBeingThrown()
        {
            // Arrange
            const ITextAnalyticsClient emptyTextAnalyticsClient = null;

            // Act
            // Assert
            Assert.Throws <ArgumentNullException>(() => new SentimentClient(emptyTextAnalyticsClient));
        }
Пример #19
0
        /*
         * If the methods (Languages, KeyPhrases, Sentiments and Entities)
         * returns an error, check that the API hasn't ran out of requests
         * the current API keys supports 1k transaction at one time */

        /// <summary>
        /// Create the Text Analystic Client
        /// </summary>
        public TextAnalyticClient()
        {
            // Create a client.
            client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
            {
                // End point may change if you upgrade the API
                Endpoint = "https://uksouth.api.cognitive.microsoft.com"
            };
        }
        public void GIVENAnyTelemetryClientAnySettingsAndEmptyTextAnalyticsClient_WHENSentimentInstrumentationMiddlewareIsConstructed_THENExceptionIsBeingThrown(
            InstrumentationSettings settings)
        {
            // Arrange
            const ITextAnalyticsClient emptyTextAnalyticsClient = null;

            // Act
            // Assert
            Assert.Throws <ArgumentNullException>(() => new SentimentInstrumentationMiddleware(this.telemetryClient, emptyTextAnalyticsClient, settings));
        }
        public void GivenAnyTelemetryClientEmptySettingsAndAnyTextAnalyticsClient_WhenSentimentInstrumentationMiddlewareIsConstructed_ThenExceptionIsBeingThrown(
            ITextAnalyticsClient textAnalyticsClient)
        {
            // Arrange
            const InstrumentationSettings emptySettings = null;

            // Act
            // Assert
            Assert.Throws <ArgumentNullException>(() => new SentimentInstrumentationMiddleware(this.telemetryClient, textAnalyticsClient, emptySettings));
        }
Пример #22
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);
        }
Пример #23
0
 public SentimentInstrumentationMiddleware(
     TelemetryClient telemetryClient,
     ITextAnalyticsClient textAnalyticsClient,
     InstrumentationSettings instrumentationSettings)
     : this(
         telemetryClient,
         new SentimentClient(textAnalyticsClient),
         instrumentationSettings)
 {
 }
Пример #24
0
        public TextAnalyticsService(ITextAnalyticsClient client, IConfiguration configuration, ILogger <TextAnalyticsService> logger)
        {
            this.endpoint = configuration["TextAnalyticsEndpoint"];
            this.client   = client;
            this.logger   = logger;

            logger.LogInformation($"Text Analytics Endpoint {this.endpoint}");

            client.Endpoint = this.endpoint;
        }
Пример #25
0
        public double?SentimentText(ITextAnalyticsClient client, string identity, string text)
        {
            SentimentBatchResult result = client.SentimentAsync(
                new MultiLanguageBatchInput(
                    new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(identity, "1", text)
            })).Result;

            return(result.Documents[0].Score);
        }
Пример #26
0
        public async Task KeyPhrasesAsync()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "KeyPhrasesAsync");
                ITextAnalyticsClient client = GetClient(HttpMockServer.CreateInstance());
                KeyPhraseResult      result = await client.KeyPhrasesAsync("I love my team mates");

                Assert.Equal("team mates", result.KeyPhrases[0]);
            }
        }
Пример #27
0
        public void Sentiment()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "Sentiment");
                ITextAnalyticsClient client = GetClient(HttpMockServer.CreateInstance());
                SentimentResult      result = client.Sentiment("I love my team mates");

                Assert.True(result.Score > 0);
            }
        }
Пример #28
0
        public async Task SentimentAsync()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                HttpMockServer.Initialize(this.GetType(), "SentimentAsync");
                ITextAnalyticsClient client = GetClient(HttpMockServer.CreateInstance());
                SentimentResult      result = await client.SentimentAsync("I love my team mates");

                Assert.True(result.Score > 0);
            }
        }
Пример #29
0
        public string TextDetect(ITextAnalyticsClient client, string report)
        {
            var result = client.DetectLanguageAsync(new BatchInput(
                                                        new List <Input>()
            {
                new Input("1", report)
            })).Result;


            return(result.Documents[0].DetectedLanguages[0].Name);
        }
Пример #30
0
        public void KeyPhrases()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "KeyPhrases");
                ITextAnalyticsClient client = GetClient(HttpMockServer.CreateInstance());
                KeyPhraseResult      result = client.KeyPhrases("I love my team mates");

                Assert.Equal("team mates", result.KeyPhrases[0]);
            }
        }