public async Task <(bool Success, string?Message)> Execute(Stream input, string blobName, string outputBlobName)
        {
            // Validate max width of the image
            using (Image image = Image.Load(input))
            {
                if (image.Width > _settings.MaxMediaSize)
                {
                    return(false, $"Image is too big. Requesting resize.");
                }
            }

            var blockBlob = Helpers.BlobHelper.GetBlobReference(outputBlobName) ?? throw new ArgumentException($"Blob '{blobName}' not found");

            input.Position = 0;

            // Get smart thumbnail
            var credentials = new ApiKeyServiceClientCredentials(_settings.CognitiveServices.Key);

            using (var visionClient = new ComputerVisionClient(credentials)
            {
                Endpoint = _settings.CognitiveServices.Endpoint
            })
                using (var result = await visionClient.GenerateThumbnailInStreamAsync(_settings.ThumbnailSize, _settings.ThumbnailSize, input, true))
                    using (var output = new MemoryStream())
                    {
                        await result.CopyToAsync(output);

                        output.Position = 0;
                        await blockBlob.UploadFromStreamAsync(output);
                    }

            return(true, null);
        }
Exemple #2
0
        public static async Task Main()
        {
            string text = "SQLSaturday is Awesome!";

            string[] endpoints = new string[] {
                "<endpointGoesHere>",
                "http://localhost:5000"
            };
            string key = "<apiKeyGoesHere>";

            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(key);

            foreach (string endpoint in endpoints)
            {
                using (TextAnalyticsClient client = new TextAnalyticsClient(credentials)
                {
                    Endpoint = endpoint
                })
                {
                    SentimentResult sentiment = await client.SentimentAsync(text);

                    Console.WriteLine($"Sentiment for text: '{text}'\n On endpoint: '{endpoint}'\n is: {sentiment.Score}\n");
                }
            }

            Console.ReadLine();
        }
Exemple #3
0
        public AzureHelper(string subscriptionKey, string apiEndpoint)
        {
            ApiKeyServiceClientCredentials Credentials = new ApiKeyServiceClientCredentials(subscriptionKey);

            client          = new ComputerVisionClient(Credentials);
            client.Endpoint = apiEndpoint;
        }
Exemple #4
0
        static async Task <LuisResult> GetPrediction()
        {
            // Use Language Understanding or Cognitive Services key
            // to create authentication credentials
            var endpointPredictionkey = "<REPLACE-WITH-YOUR-KEY>";
            var credentials           = new ApiKeyServiceClientCredentials(endpointPredictionkey);

            // Create Luis client and set endpoint
            // region of endpoint must match key's region
            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { });

            luisClient.Endpoint = "https://<REPLACE-WITH-YOUR-KEY-REGION>.api.cognitive.microsoft.com";

            // Set query values

            // public Language Understanding Home Automation app
            var appId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2";

            // query specific to home automation app
            var query = "turn on the bedroom light";

            // common settings for remaining parameters
            Double?timezoneOffset    = null;
            var    verbose           = true;
            var    staging           = false;
            var    spellCheck        = false;
            String bingSpellCheckKey = null;
            var    log = false;

            // Create prediction client
            var prediction = new Prediction(luisClient);

            // get prediction
            return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None));
        }
Exemple #5
0
        static async Task <LuisResult> GetPrediction()
        {
            var endpointPredictionkey = "5cfeca8bb6734baf81b8c65f71635515";
            var credentials           = new ApiKeyServiceClientCredentials(endpointPredictionkey);

            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { });

            luisClient.Endpoint = "https://westus.api.cognitive.microsoft.com";

            // public Language Understanding Home Automation app
            var appId = "344b9f85-5975-4edc-9e66-56cdc7013b9a";

            // query specific to home automation app
            var query = "probando";

            // common settings for remaining parameters
            Double?timezoneOffset    = 0;
            var    verbose           = true;
            var    staging           = true;
            var    spellCheck        = false;
            String bingSpellCheckKey = null;
            var    log = true;

            // Create prediction client
            var prediction = new Prediction(luisClient);

            // get prediction
            return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None));
        }
Exemple #6
0
        private async Task <LuisResult> GetPrediction(String message)
        {
            var endpointPredictionkey = _config.GetSection("LuisConfig:endpointPredictionkey").Value;
            var credentials           = new ApiKeyServiceClientCredentials(endpointPredictionkey);

            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { });

            luisClient.Endpoint = _config.GetSection("LuisConfig:Endpoint").Value;

            // public Language Understanding Home Automation app
            var appId = _config.GetSection("LuisConfig:appId").Value;

            // query specific to home automation app
            var query = message;

            // common settings for remaining parameters
            Double?timezoneOffset    = _config.GetSection("LuisConfig").GetValue <int>("timezoneOffset");
            var    verbose           = _config.GetSection("LuisConfig").GetValue <bool>("verbose");
            var    staging           = _config.GetSection("LuisConfig").GetValue <bool>("staging");
            var    spellCheck        = _config.GetSection("LuisConfig").GetValue <bool>("spellCheck");
            var    bingSpellCheckKey = _config.GetSection("LuisConfig:bingSpellCheckKey").Value;
            var    log = _config.GetSection("LuisConfig").GetValue <bool>("log");

            // Create prediction client
            var prediction = new Prediction(luisClient);

            // get prediction
            return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None));
        }
Exemple #7
0
                    public async Task RunAsync(string endpoint, string key, string text)
                    {
                        var credentials = new ApiKeyServiceClientCredentials(key);
                        var client      = new TextAnalyticsClient(credentials)
                        {
                            Endpoint = endpoint
                        };

                        // The documents to be submitted for entity recognition. The ID can be any value.
                        var inputDocuments = new MultiLanguageBatchInput(
                            new List <MultiLanguageInput>
                        {
                            new MultiLanguageInput("en", "1", text)
                        });

                        var entitiesResult = await client.EntitiesAsync(false, inputDocuments);

                        // Printing recognized entities
                        foreach (var document in entitiesResult.Documents)
                        {
                            foreach (var entity in document.Entities)
                            {
                                Entity.Add($"{entity.Name}[{entity.Type ?? "N/A"}]");
                                //Console.WriteLine($"\t\tName: {entity.Name},\tType: {entity.Type ?? "N/A"},\tSub-Type: {entity.SubType ?? "N/A"}");
                                //foreach (var match in entity.Matches)
                                //{
                                //    Console.WriteLine($"\t\t\tOffset: {match.Offset},\tLength: {match.Length},\tScore: {match.EntityTypeScore:F3}");
                                //}
                            }
                        }
                    }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            var apiKeys = new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("NewsSearchApiKey"));

            var newsClient = new NewsSearchClient(apiKeys)
            {
                Endpoint = Environment.GetEnvironmentVariable("NewsSearchUrl")
            };

            var returnArticles = new List <PartlyNewsy.Models.Article>();

            var news = await newsClient.News.SearchAsync(query : "");

            foreach (var item in news.Value)
            {
                var article = new PartlyNewsy.Models.Article {
                    ArticleUrl           = item.Url,
                    Category             = item.Category,
                    DatePublished        = DateTime.Parse(item.DatePublished),
                    FeaturedImage        = item.Image.Thumbnail.ContentUrl,
                    Headline             = item.Name,
                    NewsProviderImageUrl = item.Provider.First().Image.Thumbnail.ContentUrl,
                    NewsProviderName     = item.Provider.First().Name
                };

                returnArticles.Add(article);
            }

            return(new OkObjectResult(returnArticles));
        }
        protected BingImageSearchService()
        {
            const string subscriptionKey = "70c508d2c10147f79d9d260042ade225";
            var          credentials     = new ApiKeyServiceClientCredentials(subscriptionKey);

            _client = new ImageSearchClient(credentials);
        }
        private async Task <LuisResult> LuisRequest(string query)
        {
            var endpointPredictionkey = "YOUR_KEY";
            var credentials           = new ApiKeyServiceClientCredentials(endpointPredictionkey);
            var luisClient            = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { });

            luisClient.Endpoint = "https://westus.api.cognitive.microsoft.com/";

            // public Language Understanding Home Automation app
            var appId = "YOUR_APP_ID";

            // query specific to home automation app


            // common settings for remaining parameters
            Double?timezoneOffset    = null;
            var    verbose           = true;
            var    staging           = false;
            var    spellCheck        = false;
            String bingSpellCheckKey = null;
            var    log = false;

            // Create prediction client
            var prediction = new Prediction(luisClient);

            // get prediction
            return(await prediction.ResolveAsync(appId, query, timezoneOffset, verbose, staging, spellCheck, bingSpellCheckKey, log, CancellationToken.None));
        }
Exemple #11
0
        private PredictionResponse GetPrediction(string utterance)
        {
            var language    = GuessLanguage(utterance);
            var appId       = GetAppId(language);
            var credentials = new ApiKeyServiceClientCredentials(Config.PredictionKey);

            using (var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = Config.Endpoint
            })
            {
                var requestOptions = new PredictionRequestOptions
                {
                    DatetimeReference      = DateTime.Now, //DateTime.Parse("2019-01-01"),
                    PreferExternalEntities = true
                };

                var predictionRequest = new PredictionRequest
                {
                    Query   = utterance,
                    Options = requestOptions
                };

                // get prediction
                return(luisClient.Prediction.GetSlotPredictionAsync(
                           Guid.Parse(appId),
                           slotName: "staging",
                           predictionRequest,
                           verbose: true,
                           showAllIntents: true,
                           log: true).Result);
            }
        }
Exemple #12
0
        public async Task <TextAnalyticsAnalyzeResponse> Analyze(string text, string languageHint)
        {
            var credentials = new ApiKeyServiceClientCredentials(_subscriptionKey);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = _endpoint
            };

            var detectedLanguageResult = await client.DetectLanguageAsync(text, languageHint, true);

            if (string.IsNullOrWhiteSpace(languageHint))
            {
                languageHint = detectedLanguageResult.DetectedLanguages.FirstOrDefault()?.Iso6391Name ?? "";
            }

            var entitiesResult   = client.EntitiesAsync(text, languageHint, true);
            var keyPhrasesResult = client.KeyPhrasesAsync(text, languageHint, true);
            var sentimentResult  = client.SentimentAsync(text, languageHint, true);

            await Task.WhenAll(entitiesResult, keyPhrasesResult, sentimentResult);

            return(new TextAnalyticsAnalyzeResponse
            {
                DetectedLanguage = detectedLanguageResult,
                KeyPhrases = keyPhrasesResult.Result,
                Sentiment = sentimentResult.Result,

                Entities = entitiesResult.Result
            });
        }
        /// <summary>
        /// Sends a URL to Cognitive Services and performs analysis.
        /// </summary>
        /// <param name="imageUrl">The URL of the image to analyze.</param>
        /// <returns>Awaitable image analysis result.</returns>
        private async Task <string> AnalyzeUrlAsync(string imageUrl, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            string key  = "<SERVICE CLIENT KEY>";
            var    test = new ApiKeyServiceClientCredentials(key);

            using (var client = new ComputerVisionClient(test)
            {
                Endpoint = "https://colourfind.cognitiveservices.azure.com/"
            })
            {
                VisualFeatureTypes[] visualFeatures = new List <VisualFeatureTypes>()
                {
                    VisualFeatureTypes.Color, VisualFeatureTypes.Description, VisualFeatureTypes.Tags
                }.ToArray();

                string        language = "en";
                ImageAnalysis analysisResult;

                analysisResult = await client.AnalyzeImageAsync(imageUrl, visualFeatures, null, language);

                string mainColour = analysisResult.Color.DominantColorForeground;

                return(mainColour);
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc();
            services.AddDbContext <HotelsContext>(options => options.UseSqlServer(GetConnectionString(),
                                                                                  sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.EnableRetryOnFailure(
                    maxRetryCount: 3,
                    maxRetryDelay: TimeSpan.FromSeconds(30),
                    errorNumbersToAdd: null);
            }));
            services.AddScoped(factory =>
            {
                var apiKey  = Configuration["TextAnalyticsApiKey"];
                var baseUrl = Configuration["TextAnalyticsBaseUrl"];

                var credentials = new ApiKeyServiceClientCredentials(apiKey);

                return(new TextAnalyticsClient(credentials)
                {
                    Endpoint = baseUrl
                });
            });
            services.AddScoped <TextAnalysisService>();
            services.AddScoped <ReviewsService>();
        }
Exemple #15
0
        public async Task <UserQuery> DetectIntent(string message, string sessionId)
        {
            var credentials   = new ApiKeyServiceClientCredentials(PredictionSubscriptionKey);
            var runtimeClient = new LUISRuntimeClient(credentials)
            {
                Endpoint = PredictionEndpoint
            };
            var request = new PredictionRequest {
                Query = message
            };
            var response = await runtimeClient.Prediction.GetSlotPredictionAsync(Guid.Parse(AppId), SlotName, request);

            var prediction = response.Prediction;

            var isFallback = prediction.Intents.Values.Max(i => i.Score) < 0.6 || prediction.TopIntent == "None";

            return(new UserQuery
            {
                IntentName = prediction.TopIntent,
                IsFallback = isFallback,
                Parameters = prediction.Entities.ToDictionary(
                    entity => entity.Key,
                    entity => entity.Value is Newtonsoft.Json.Linq.JArray arr ? string.Join(',', arr.Select(s => s.ToString())) : entity.Value),
                AllRequiredParamsPresent = true,
                FulfillmentText = isFallback ? FallbackMessage : null,
                Timestamp = DateTime.UtcNow.Ticks
            });
        private static async void RecognizePrintedTextWithSdkAsync(string imagePath,
                                                                   bool detectOrientation)
        {
            ServiceClientCredentials serviceClientCredentials = new ApiKeyServiceClientCredentials(key);

            Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ComputerVisionAPI computerVisionApi =
                new Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ComputerVisionAPI(
                    serviceClientCredentials)
            {
                AzureRegion = AzureRegions.Southcentralus
            };
            HttpOperationResponse <OcrResult> result;

            using (FileStream fileReader = new FileStream(imagePath, FileMode.Open))
            {
                result = await computerVisionApi.RecognizePrintedTextInStreamWithHttpMessagesAsync(detectOrientation, fileReader);
            }
            foreach (OcrRegion region in result.Body.Regions)
            {
                foreach (OcrLine line in region.Lines)
                {
                    foreach (OcrWord word in line.Words)
                    {
                        Console.WriteLine(word.Text);
                    }
                }
            }
        }
Exemple #17
0
        public async static Task <ImageAnalysis> DescribePicture(MediaFile photo)
        {
            ImageAnalysis description = null;

            try
            {
                if (photo != null)
                {
                    using (var stream = photo.GetStream())
                    {
                        var credentials = new ApiKeyServiceClientCredentials(Constants.VisionApiKey);
                        var client      = new System.Net.Http.DelegatingHandler[] { };

                        var visionClient = new ComputerVisionClient(credentials, client);
                        visionClient.Endpoint = Constants.VisionEndpoint;

                        var features = new VisualFeatureTypes[] { VisualFeatureTypes.Tags, VisualFeatureTypes.Faces, VisualFeatureTypes.Categories, VisualFeatureTypes.Description, VisualFeatureTypes.Color };
                        description = await visionClient.AnalyzeImageInStreamAsync(stream, features);
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(description);
        }
                    public async Task RunAsync(string endpoint, string key, string text)
                    {
                        var credentials = new ApiKeyServiceClientCredentials(key);
                        var client      = new TextAnalyticsClient(credentials)
                        {
                            Endpoint = endpoint
                        };

                        var inputDocuments = new MultiLanguageBatchInput(
                            new List <MultiLanguageInput>
                        {
                            new MultiLanguageInput("en", "1", text)
                        });

                        var kpResults = await client.KeyPhrasesAsync(false, inputDocuments);

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

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

                            foreach (string keyphrase in document.KeyPhrases)
                            {
                                Phrase.Add($"{keyphrase}");
                                //Console.WriteLine($"\t\t{keyphrase}");
                            }
                        }
                    }
        private static IServiceCollection AddInfrastructureClients(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddScoped <IComputerVisionClient>(factory => {
                var key  = configuration["COMPUTER_VISION_SUBSCRIPTION_KEY"];
                var host = configuration["COMPUTER_VISION_ENDPOINT"];

                var credentials = new ApiKeyServiceClientCredentials(key);
                var client      = new ComputerVisionClient(credentials);
                client.Endpoint = host;

                return(client);
            });

            services.AddHttpClient <IImageAnalysisClient, ImageAnalysisClient>()
            .AddTransientHttpErrorPolicy(builder =>
                                         builder.WaitAndRetryAsync(3, retryCount =>
                                                                   TimeSpan.FromSeconds(Math.Pow(2, retryCount))));

            services.AddHttpClient <IUkiyoApiClient, UkiyoApiClient>()
            .AddTransientHttpErrorPolicy(builder =>
                                         builder.WaitAndRetryAsync(3, retryCount =>
                                                                   TimeSpan.FromSeconds(Math.Pow(2, retryCount))));

            services.Scan(scan => scan
                          .FromAssemblyOf <ImageAnalysisClient>()
                          .AddClasses(classes =>
                                      classes.Where(c => c.Name.EndsWith("Service")))
                          .UsingRegistrationStrategy(RegistrationStrategy.Skip)
                          .AsImplementedInterfaces()
                          .WithScopedLifetime());

            return(services);
        }
        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);
                }
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddCors();
            services.AddDbContext <AssetManagementSystemDBContext>(options => options.UseSqlServer("Server = localhost; Database = AssetManagementSystemDB; Trusted_Connection = True;"));
            /*Services */
            services.AddScoped <IComputerVisionClient>(factory => {
                var key         = Configuration["ComputerVisionKey"];
                var host        = Configuration["ComputerVisionEndpoint"];
                var credentials = new ApiKeyServiceClientCredentials(key);
                var client      = new ComputerVisionClient(credentials);
                client.Endpoint = host;

                return(client);
            });
            services.AddScoped(x => { return(new BlobServiceClient(Configuration["AzureBlobStorage"])); });
            services.AddOptions();
            services.Configure <ConfigurationValues>(Configuration.GetSection("AppValue"));

            //Services
            services.AddScoped <IBlobService, BlobService>();
            services.AddScoped <ICognitiveService, CognitiveService>();
            services.AddScoped <IAssetService, AssetService>();
            //Repositories
            services.AddScoped <IMetadataRepository, MetadataRepository>();
            services.AddScoped <IImageVariantRepository, ImageVariantRepository>();
            services.AddScoped <IAssetRepository, AssetRepository>();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="LuisRecognizer"/> class.
        /// </summary>
        /// <param name="application">The LUIS application to use to recognize text.</param>
        /// <param name="predictionOptions">(Optional) The LUIS prediction options to use.</param>
        /// <param name="includeApiResults">(Optional) TRUE to include raw LUIS API response.</param>
        /// <param name="clientHandler">(Optional) Custom handler for LUIS API calls to allow mocking.</param>
        public LuisRecognizer(LuisApplication application, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, HttpClientHandler clientHandler = null)
        {
            _application       = application ?? throw new ArgumentNullException(nameof(application));
            _options           = predictionOptions ?? new LuisPredictionOptions();
            _includeApiResults = includeApiResults;

            TelemetryClient        = _options.TelemetryClient;
            LogPersonalInformation = _options.LogPersonalInformation;

            var credentials       = new ApiKeyServiceClientCredentials(application.EndpointKey);
            var delegatingHandler = new LuisDelegatingHandler();
            var httpClientHandler = clientHandler ?? CreateRootHandler();
            var currentHandler    = CreateHttpHandlerPipeline(httpClientHandler, delegatingHandler);

            DefaultHttpClient = new HttpClient(currentHandler, false)
            {
                Timeout = TimeSpan.FromMilliseconds(_options.Timeout),
            };

            // assign DefaultHttpClient to _httpClient to expose Timeout in unit tests
            // and keep HttpClient usage as a singleton
            _httpClient = DefaultHttpClient;

            _runtime = new LUISRuntimeClient(credentials, _httpClient, false)
            {
                Endpoint = application.Endpoint,
            };
        }
Exemple #23
0
        private static async Task <PredictionResponse> GetIntentAndEntities(string messageText)
        {
            var credentials = new ApiKeyServiceClientCredentials(_luisPredictionKey);
            var luisClient  = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = _luisBaseUrl
            };

            var requestOptions = new PredictionRequestOptions
            {
                DatetimeReference      = DateTime.Parse("2019-01-01"),
                PreferExternalEntities = true
            };

            var predictionRequest = new PredictionRequest
            {
                Query   = messageText,
                Options = requestOptions
            };

            // get prediction
            return(await luisClient.Prediction.GetSlotPredictionAsync(
                       Guid.Parse(_luisAppId),
                       slotName : "production",
                       predictionRequest,
                       verbose : true,
                       showAllIntents : true,
                       log : true));
        }
        public override async Task <GetThumbnailResponse> GetThumbnail(GetThumbnailRequest request)
        {
            var response = new GetThumbnailResponse();

            try
            {
                var apiKeyServiceClientCredentials = new ApiKeyServiceClientCredentials(request.EndPointKey1);
                var delegatingHandlers             = new System.Net.Http.DelegatingHandler[] { };

                IComputerVisionClient computerVision = new ComputerVisionClient(
                    credentials: apiKeyServiceClientCredentials,
                    handlers: delegatingHandlers)
                {
                    Endpoint = request.EndPoint
                };

                response.Thumbnail = await computerVision.GenerateThumbnailInStreamAsync(
                    image : request.ImageStream,
                    width : request.ThumbnailSize.Width,
                    height : request.ThumbnailSize.Height,
                    smartCropping : request.ThumbnailSize.SmartCropping);

                response.Success = true;
            }
            catch (Exception e)
            {
                response.FailureInformation = e.Message;
            }

            return(response);
        }
        private async Task <TextOperationResult> RecognizeAsync <T>(Func <ComputerVisionClient, Task <T> > GetHeadersAsyncFunc, Func <T, string> GetOperationUrlFunc) where T : new()
        {
            // -----------------------------------------------------------------------
            // KEY SAMPLE CODE STARTS HERE
            // -----------------------------------------------------------------------
            var result = default(TextOperationResult);

            OutputWriterSB.AppendLine("Create result variable for storing result");
            //
            // Create Cognitive Services Vision API Service client.
            //
            var Credentials = new ApiKeyServiceClientCredentials("d8358f4194c8447bbca7c9e1605f15b0");
            var Endpoint    = "https://sushmavisionapi.cognitiveservices.azure.com/";

            using (var client = new ComputerVisionClient(Credentials)
            {
                Endpoint = Endpoint
            })
            {
                Debug.WriteLine("ComputerVisionClient is created");
                OutputWriterSB.AppendLine("ComputerVisionClient is created");
                try
                {
                    Debug.WriteLine("Calling ComputerVisionClient.RecognizeTextAsync()...");
                    OutputWriterSB.AppendLine("Calling ComputerVisionClient.RecognizeTextAsync()...");

                    T recognizeHeaders = await GetHeadersAsyncFunc(client);

                    string operationUrl = GetOperationUrlFunc(recognizeHeaders);
                    string operationId  = operationUrl.Substring(operationUrl.LastIndexOf('/') + 1);
                    Debug.WriteLine("Calling ComputerVisionClient.GetTextOperationResultAsync()...");
                    OutputWriterSB.AppendLine("Calling ComputerVisionClient.GetTextOperationResultAsync()...");
                    result = await client.GetTextOperationResultAsync(operationId);

                    for (int attempt = 1; attempt <= 3; attempt++)
                    {
                        if (result.Status == TextOperationStatusCodes.Failed || result.Status == TextOperationStatusCodes.Succeeded)
                        {
                            break;
                        }

                        Debug.WriteLine(string.Format("Server status: {0}, wait {1} seconds...", result.Status, TimeSpan.FromSeconds(3)));
                        await Task.Delay(TimeSpan.FromSeconds(3));

                        Debug.WriteLine("Calling ComputerVisionClient.GetTextOperationResultAsync()...");
                        result = await client.GetTextOperationResultAsync(operationId);
                    }
                }
                catch (Exception ex)
                {
                    result = new TextOperationResult()
                    {
                        Status = TextOperationStatusCodes.Failed
                    };
                    Debug.WriteLine(ex.Message);
                }
                return(result);
            }
        }
 private void InitTextAnalyticsClient()
 {
     _credentials = new ApiKeyServiceClientCredentials(TextSubscriptionKey);
     _client      = new TextAnalyticsClient(_credentials)
     {
         Endpoint = TextEndPoint
     };
 }
Exemple #27
0
 public LuisNLP(IConfiguration config)
 {
     this.config              = config;
     this.credentials         = new ApiKeyServiceClientCredentials(config["Luis.AuthoringKey"]);
     this.luisClient          = new LUISRuntimeClient(credentials);
     this.luisClient.Endpoint = config["Luis.Endpoint"];
     this.prediction          = new Prediction(luisClient);
 }
Exemple #28
0
        public MainCameraPageViewController(IntPtr handle) : base(handle)
        {
            httpClient = new HttpClient();
            var credentials = new ApiKeyServiceClientCredentials(Help.PrivateKeys.CognitiveServicesKey);

            computerVisionClient          = new ComputerVisionClient(credentials, httpClient, false);
            computerVisionClient.Endpoint = Help.PrivateKeys.CognitiveServicesEndpoint;
        }
Exemple #29
0
        public async Task <LuisResult> ExtractEntitiesFromLUIS(string textToAnalyze)
        {
            var method = "ExtractEntitiesFromLUIS";

            try
            {
                _logger.LogInformation(string.Format("{0} - {1}", method, "IN"));

                _logger.LogInformation(string.Format("{0} - {1}", method, "Getting credentials."));
                var subscriptionKey = Environment.GetEnvironmentVariable("LUISAPISubscriptionKey");
                if (subscriptionKey == null)
                {
                    throw new System.ArgumentNullException("subscriptionKey");
                }

                var credentials = new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("LUISAPISubscriptionKey"));

                _logger.LogInformation(string.Format("{0} - {1}", method, "Creating client."));
                var client = new LUISRuntimeClient(credentials);

                _logger.LogInformation(string.Format("{0} - {1}", method, "Setting Endpoint"));
                client.Endpoint = "https://westeurope.api.cognitive.microsoft.com/";

                _logger.LogInformation(string.Format("{0} - {1}", method, "Getting app ID."));
                var appID = Environment.GetEnvironmentVariable("LUISAPPID");
                if (appID == null)
                {
                    throw new System.ArgumentNullException("appID");
                }

                _logger.LogInformation(string.Format("{0} - {1}", method, "Getting Bing Subscription Key."));

                var bingSubcriptionKey = Environment.GetEnvironmentVariable("BingAPISubscriptionKey");
                if (bingSubcriptionKey == null)
                {
                    throw new System.ArgumentNullException("bingSubcriptionKey");
                }

                _logger.LogInformation(string.Format("{0} - {1}", method, "Predicting."));
                return(await _predictionHelperService.ResolveAsync(client.Prediction, appID, textToAnalyze,
                                                                   null, null, false, true, bingSubcriptionKey));
            }
            catch (ArgumentNullException arg)
            {
                _logger.LogError(string.Format("{0} - {1}", method, "Received a null argument."));
                _logger.LogError(string.Format("{0} - {1}", method, "Argument:"));
                _logger.LogError(string.Format("{0} - {1}", method, arg.ParamName));
                return(null);
            }
            catch (Exception ex)
            {
                _logger.LogError(string.Format("{0} - {1}", method, "Generic Exception."));
                _logger.LogError(string.Format("{0} - {1}", method, "Message:"));
                _logger.LogError(string.Format("{0} - {1}", method, ex.Message));
                return(null);
            }
        }
Exemple #30
0
        private static void InitComputer()
        {
            var credenciales = new ApiKeyServiceClientCredentials(APIKEY);

            Cliente = new ComputerVisionClient(credenciales)
            {
                Endpoint = ENDPOINT
            };
        }