Exemplo n.º 1
0
        public TextAnalytics()
        {
            TextAnalyticsApiKeyCredential credentials = new TextAnalyticsApiKeyCredential("febeb4159a3d474eaa98d81a55a70554");
            Uri endpoint = new Uri("https://cogsertextanal.cognitiveservices.azure.com/");

            client = new TextAnalyticsClient(endpoint, credentials);
            //var writeText = EntityLinkingExample(client, inputText);
            //System.IO.File.WriteAllText(path, writeText);
        }
        public TextAnalyticsClient GetClient(TextAnalyticsApiKeyCredential credential = default)
        {
            string apiKey = Recording.GetVariableFromEnvironment(ApiKeyEnvironmentVariable);

            credential ??= new TextAnalyticsApiKeyCredential(apiKey);
            return(InstrumentClient(
                       new TextAnalyticsClient(
                           new Uri(Recording.GetVariableFromEnvironment(EndpointEnvironmentVariable)),
                           credential,
                           Recording.InstrumentClientOptions(new TextAnalyticsClientOptions()))
                       ));
        }
Exemplo n.º 3
0
        public void CreateTextAnalyticsClient()
        {
            string endpoint = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string apiKey   = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_API_KEY");

            #region Snippet:CreateTextAnalyticsClient
            //@@ string endpoint = "<endpoint>";
            //@@ string apiKey = "<apiKey>";
            var credential = new TextAnalyticsApiKeyCredential(apiKey);
            var client     = new TextAnalyticsClient(new Uri(endpoint), credential);
            #endregion
        }
Exemplo n.º 4
0
        public void BadRequestSnippet()
        {
            string endpoint = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string apiKey   = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_API_KEY");

            var    credentials = new TextAnalyticsApiKeyCredential(apiKey);
            var    client      = new TextAnalyticsClient(new Uri(endpoint), credentials);
            string input       = "Este documento está en español.";

            #region Snippet:BadRequest
            try
            {
                DetectedLanguage result = client.DetectLanguage(input);
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine(e.ToString());
            }
            #endregion
        }
        public async Task RotateApiKey()
        {
            // Instantiate a client that will be used to call the service.
            string apiKey              = Recording.GetVariableFromEnvironment(ApiKeyEnvironmentVariable);
            var    credential          = new TextAnalyticsApiKeyCredential(apiKey);
            TextAnalyticsClient client = GetClient(credential);

            string input = "Este documento está en español.";

            // Verify the credential works (i.e., doesn't throw)
            await client.DetectLanguageAsync(input);

            // Rotate the API key to an invalid value and make sure it fails
            credential.UpdateCredential("Invalid");
            Assert.ThrowsAsync <RequestFailedException>(
                async() => await client.DetectLanguageAsync(input));

            // Re-rotate the API key and make sure it succeeds again
            credential.UpdateCredential(apiKey);
            await client.DetectLanguageAsync(input);
        }
Exemplo n.º 6
0
        public static async Task Run([BlobTrigger("incoming/{name}", Connection = "AudioBlobConnectionString")] Stream blobStream, string name, ILogger log, ExecutionContext context)
        {
            _logger = log;

            // grab the local config values for testing
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            _trancriptionSqlDatabaseConnectionString = config.GetConnectionString("TrancriptionSqlDatabaseConnectionString");
            _textAnalyticsApiKeyCredential           = new TextAnalyticsApiKeyCredential(Environment.GetEnvironmentVariable("TextAnalyticsApiKeyCredential"));
            _textAnalyticsEndpoint  = new Uri(Environment.GetEnvironmentVariable("TextAnalyticsEndpoint"));
            _speechApiKeyCredential = Environment.GetEnvironmentVariable("SpeechApiKeyCredential");
            _speechApiRegion        = Environment.GetEnvironmentVariable("SpeechApiRegion");

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _logger.LogInformation($"{name}: Size: {blobStream.Length} Bytes");

            await RecognizeSpeechAsync(name, blobStream);
        }
Exemplo n.º 7
0
        public static void Run([TimerTrigger("0 30 6 * * *", RunOnStartup = true)] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            // Initialize variables from local.settings.json
            string twilioSid       = System.Environment.GetEnvironmentVariable("TwilioSid");
            string twilioAuthToken = System.Environment.GetEnvironmentVariable("TwilioAuthToken");
            string newsApiKey      = System.Environment.GetEnvironmentVariable("NewsApiKey");
            string fromNumber      = System.Environment.GetEnvironmentVariable("TwilioPhoneNumber");
            string toNumber        = System.Environment.GetEnvironmentVariable("MyPhoneNumber");
            TextAnalyticsApiKeyCredential textAnalyticsCredentials = new TextAnalyticsApiKeyCredential(System.Environment.GetEnvironmentVariable("TextAnalyticsApiKeyCredential"));
            Uri textAnalyticsEndpoint = new Uri(System.Environment.GetEnvironmentVariable("CognitiveServicesEndpoint"));

            // Incase URL of article image is null, we will use this royalty free stock photo.
            string newspaperImageURL = "https://images.unsplash.com/photo-1504711331083-9c895941bf81?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80";

            // NEWS API Search parameters and URL
            string searchKeyword  = "Covid";
            string sortBy         = "relevancy";
            string pageSize       = "100";
            string searchLanguage = "en";
            string fromDate       = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
            double imageFileSize  = 0.0;

            var newAPIEndpointURL = $"https://newsapi.org/v2/everything?from={fromDate}&sortBy={sortBy}&pageSize={pageSize}&language={searchLanguage}&q={searchKeyword}&apiKey={newsApiKey}";
            // 1. Get json

            string jsonFromAPI = GetNewsFromAPI(newAPIEndpointURL);

            // 2. Deserialize into objects

            News news = JsonConvert.DeserializeObject <News> (jsonFromAPI);

            // 3. Initialize TextAnalyticsClient for sentiment detection, TwilioClient to send the message

            TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClient(textAnalyticsEndpoint, textAnalyticsCredentials);

            TwilioClient.Init(twilioSid, twilioAuthToken);

            // 4. Perform sentiment detection on article titles

            string sentimentLabel = "negative";

            if (news.status.Equals("ok"))
            {
                foreach (var article in news.articles)
                {
                    sentimentLabel = SentimentDetection(textAnalyticsClient, article.title);
                    // 5. Once a a news article with positive sentiment is found, send via text and break out of foreach loop.
                    if (sentimentLabel.Equals("Positive"))
                    {
                        log.LogInformation("Found positive story: " + article.url);

                        // Checks if there is a url for image of article, if there isn't it will default to newspaperImageURL.
                        article.urlToImage = !String.IsNullOrEmpty(article.urlToImage) ? article.urlToImage : newspaperImageURL;

                        // If article image was changes to newspaperImageURL, no need to check size because newspaperImageURL is only 321KB
                        if (!(article.urlToImage.Equals(newspaperImageURL)))
                        {
                            // Gets image file size and logs to console.
                            imageFileSize = GetMediaFileSize(article.urlToImage);
                            log.LogInformation("The image size is: " + imageFileSize);

                            // MMS size limit is 5 MB.
                            if ((imageFileSize > 4.9))
                            {
                                article.urlToImage = newspaperImageURL;
                            }
                        }

                        SendMessage(fromNumber, toNumber, article.url, article.title, article.urlToImage);

                        break;
                    }
                }
            }
            else
            {
                log.LogInformation("Error with NEWS API call");
            }
        }
Exemplo n.º 8
0
 public static void Configure(IConfiguration configuration)
 {
     var config = configuration.GetSection("TextAnalytics");
     credentials = new TextAnalyticsApiKeyCredential(config["Key"]);
     endpoint = new Uri(config["Endpoint"]);
 }