public Analyser() { _client = new TextAnalyticsAPI(new Creds()) { AzureRegion = AzureRegions.Australiaeast }; }
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 double?ExtractSentiments(List <string> Queries) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials()); client.AzureRegion = AzureRegions.Westus; MultiLanguageBatchInput multiLanguageBatchInput = new MultiLanguageBatchInput(); multiLanguageBatchInput.Documents = new List <MultiLanguageInput>(); for (int i = 0; i < Queries.Count; i++) { multiLanguageBatchInput.Documents.Add(new MultiLanguageInput("en", i.ToString(), Queries[i])); } SentimentBatchResult sentimentBatchResult = client.SentimentAsync(multiLanguageBatchInput).Result; double?score = 0; // Printing sentiment results foreach (var document in sentimentBatchResult.Documents) { score += document.Score; } return(score / sentimentBatchResult.Documents.Count); }
public static string AnalizarTexto(string textoPDF, string numPagina) { string result = string.Empty; var json = "[\"\"]"; // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials()); client.AzureRegion = AzureRegions.Southcentralus; KeyPhraseBatchResult result2; try { // Getting key-phrases var length = textoPDF.Length; textoPDF = textoPDF.Replace(".", ""); result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("es", numPagina, textoPDF) })).Result; } catch (Exception ex) { throw ex; } if (result2.Documents.Count > 0) { json = RemoveSpecialCharacters(JsonConvert.SerializeObject(result2.Documents[0].KeyPhrases)); } return(json); }
private static ITextAnalyticsAPI InitializeTextAnalyticsClient() { ITextAnalyticsAPI textAnalyticsClient = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("CognitiveServicesKey"))); textAnalyticsClient.AzureRegion = AzureRegions.Southcentralus; // Change if it's in another region return(textAnalyticsClient); }
public static async void MainAsync(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; //// Create a client. var client = ElasticSearchFactory.GetClient(); TextAnalyticsAPI textAnalyticsClient = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials()) { AzureRegion = AzureRegions.Westcentralus }; var countResponse = client.Count <Stiftung>(); var count = countResponse.Count; var searchSize = 20; var searchStart = 0; do { await UpdateFoundationsTags(searchStart, searchSize, client, textAnalyticsClient); searchStart += searchSize; }while (searchStart < count); Console.WriteLine("You're finished. Great!"); }
/// <summary> /// Adds found key phrases to references list of keyPhrases - the most important ones first. /// </summary> /// <param name="keyPhrases"></param> /// <param name="analyzable"></param> /// <param name="log"></param> private static void RunTextAnalysis(ref List <string> keyPhrases, List <MultiLanguageInput> analyzable, TraceWriter log) { var batch = new MultiLanguageBatchInput(); batch.Documents = analyzable; ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westus; client.SubscriptionKey = key1; try { var result = client.KeyPhrases(batch); foreach (var row in result.Documents) { foreach (var kp in row.KeyPhrases) { keyPhrases.Add(kp); } } } catch (Exception ex) { log.Warning(ex.Message); } }
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); } } }
public static double GetSentiment(string msg) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "d828157edb4e4ceaa79109372f3d18c4"; Console.OutputEncoding = System.Text.Encoding.UTF8; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", msg) })); // Printing sentiment results foreach (var document in result3.Documents) { Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); } double res = 0d; var item = result3.Documents.FirstOrDefault(); if (item != null) { res = item.Score.GetValueOrDefault(); } return(res); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result; //Sentiment analysis ITextAnalyticsAPI client = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westcentralus, SubscriptionKey = "Replace with your key" }; if ((message.Text != null) && (message.Text.Trim().Length > 0)) { SentimentBatchResult sentimentResult = client.Sentiment(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", message.Text), })); double sentiment = sentimentResult.Documents.First().Score ?? 0; // Completes the dialog, remove it from the stack and return the result. context.Done(sentiment); } else { await context.PostAsync("I'm sorry, I don't understand your reply. How are you (e.g. 'Fine', 'I feel sick')?"); context.Wait(this.MessageReceivedAsync); } }
public virtual async Task DoTask(IDialogContext context, IAwaitable <IMessageActivity> activity) { var response = await activity; var responseText = response.Text; // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "af0b5df9f3e34a45b7eb149b8a911782"; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", responseText) })); // Printing language results. var score = result3.Documents.First().Score; reviewdetails review = new reviewdetails() { Review = responseText, SentimentScore = (double)score }; await AzureManager.AzureManagerInstance.PostReview(review); var message = "Thank you for reviewing our bot.\n\nWe will continue to improve this bot further."; await context.PostAsync(message); context.Done(this); }
private static Rating GetSentimentAnalysis(TraceWriter log, Rating rating) { // Handle sentiment analysis for usernotes // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westus, SubscriptionKey = Environment.GetEnvironmentVariable("COGNITIVE_SERVICES_KEY") }; Guid sentimentId = Guid.NewGuid(); SentimentBatchResult result = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", sentimentId.ToString(), rating.UserNotes), })); // Printing sentiment results foreach (var document in result.Documents) { log.Info($"Document ID: {document.Id} , Sentiment Score: {document.Score}"); rating.SentimentScore = (float)document.Score; } return(rating); }
// Pruning QnA input via Text Analytics for better responses public StringBuilder TextAnalyticsRequest(string message) { // Create client ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials()); client.AzureRegion = AzureRegions.Northeurope; // Getting key-phrases var result = client.KeyPhrasesAsync(new MultiLanguageBatchInput( new List <MultiLanguageInput> { new MultiLanguageInput("no", "1", message) })).Result; // Print / string build keyphrases var stringBuilder = new StringBuilder(); foreach (var document in result.Documents) { foreach (var keyphrase in document.KeyPhrases) { stringBuilder.Append(keyphrase + " "); } } return(stringBuilder); }
private static int GetScore(string message) { // Create and initialize an instance of the // text analytics API. ITextAnalyticsAPI client = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westus, SubscriptionKey = System.Environment.GetEnvironmentVariable("TextAnalyticsApiKey") }; // Get the sentiment var results = client.Sentiment(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", message) })); // If nothing comes back, just return 0 if (results.Documents.Count == 0) { return(0); } // Retreive the result and format it into an integer var score = results.Documents[0].Score.GetValueOrDefault(); return((int)(score * 100)); }
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); }
public async Task OnTurn(ITurnContext context, MiddlewareSet.NextDelegate next) { if (context.Activity.Type is ActivityTypes.Message) { if (string.IsNullOrEmpty(context.Activity.Text)) { context.Services.Add <string>("0.0"); } // Create a client var client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials(ApiKey)); client.AzureRegion = AzureRegions.Westeurope; // Extract the language var result = await client.DetectLanguageAsync(new BatchInput(new List <Input>() { new Input("1", context.Activity.Text) })); var language = result.Documents?[0].DetectedLanguages?[0].Name; // Get the sentiment var sentimentResult = await client.SentimentAsync( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", context.Activity.Text), })); context.Services.Add <string>(sentimentResult.Documents?[0].Score?.ToString("#.#")); } await next(); }
internal static async Task <string> Sentiment(this string text, string apiKey) { if (string.IsNullOrEmpty(text)) { return("0.0"); } // Create a client var client = new TextAnalyticsAPI(new ServiceCredentials.ApiKeyServiceClientCredentials(apiKey)); // Extract the language var result = await client.DetectLanguageAsync(new BatchInput(new List <Input>() { new Input("1", text) })); var language = result.Documents?[0].DetectedLanguages?[0].Name; // Get the sentiment var sentimentResult = await client.SentimentAsync( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(language, "0", text), })); return(sentimentResult.Documents?[0].Score?.ToString("#.#")); }
private String SentimentAnalysis(String text) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westus; client.SubscriptionKey = "0e9cc6838a504e2194eb09d155678423"; Console.OutputEncoding = System.Text.Encoding.UTF8; String result = ""; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "1", text) //new MultiLanguageInput("en", "1", "This was a waste of my time. The speaker put me to sleep."), //new MultiLanguageInput("es", "2", "No tengo dinero ni nada que dar..."), //new MultiLanguageInput("it", "3", "L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."), })); //String answer = ""; //// Printing sentiment results foreach (var document in result3.Documents) { Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); result += String.Format("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); } return(result); }
public ITextAnalyticsAPI Client() { ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westeurope; client.SubscriptionKey = "c73f4ffebd444e1189a3e41aecc2c159"; return(client); }
public FeedbackService() { _textAnalyticsAPI = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westus, SubscriptionKey = App.Secrets.TextAnalyticsKey }; }
public TextAnalysisMain(string textkey, AzureRegions region) { _TextKey = textkey; _Region = region; _Client = new TextAnalyticsAPI { SubscriptionKey = _TextKey, AzureRegion = _Region }; Results = new TextAnalysisResults(); }
public static async Task Run([CosmosDBTrigger( databaseName: "Your_database_name", collectionName: "Review", ConnectionStringSetting = "CosmosDbConnectionString", LeaseCollectionName = "leases")] IReadOnlyList <Document> documents, [DocumentDB(databaseName: "Your_database_name", collectionName: "Review", ConnectionStringSetting = "CosmosDbConnectionString", CreateIfNotExists = false)] IAsyncCollector <dynamic> results, TraceWriter log) { if (documents != null && documents.Count > 0) { log.Verbose($"Documents modified {documents.Count}"); log.Verbose($"First document Id { documents[0].Id}"); ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "<Your_Subscription_Key>"; string languageToAnalyze = "en"; int cnt = 0; foreach (var document in documents) { if (!string.IsNullOrEmpty(document.GetPropertyValue <string>("Satisfaction"))) { continue; } var content = document.GetPropertyValue <string>("Content"); SentimentBatchResult result = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput> { new MultiLanguageInput(languageToAnalyze, id: cnt.ToString(), text: content) } ) ); cnt++; var evaluationResult = result.Documents[0].Score; var newDocument = new { id = document.Id, Content = content, Satisfaction = evaluationResult }; await results.AddAsync(newDocument); log.Verbose($"Review evaluated: {content}"); log.Verbose($"Evaluation result: {evaluationResult}"); } } }
public Demo() { client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "8e539c9707c04e659d9085673f970c6b"; Console.OutputEncoding = System.Text.Encoding.UTF8; text = readTextFile(@"C:\Users\Joske\Documents\TextAnalytics.txt").Split(new char[] { '.', '?', '!' }).ToList(); text.RemoveAll(str => String.IsNullOrWhiteSpace(str)); }
private static ITextAnalyticsAPI Initializeclient() { ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = ConfigurationManager.AppSettings["Ocp-Apim-Subscription-Key"]; Console.OutputEncoding = System.Text.Encoding.UTF8; return(client); }
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 = "上一次操作中发生了异常。"; } }
/// <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 }); }
private static async Task <DetectedLanguage> DetectedMessageLanguage(Activity activity) { var client = new TextAnalyticsAPI { AzureRegion = (AzureRegions)Enum.Parse(typeof(AzureRegions), CloudConfigurationManager.GetSetting("TextAnalyticsApiRegion")), SubscriptionKey = CloudConfigurationManager.GetSetting("TextAnalyticsApiKey") }; var query = new TextAnalysisQuery(activity.Text); var language = await query.Execute(client); return(language); }
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(); }
public async Task <TextAnalyticsResult> AnalyzeTextAsync(string text) { try { // COGNITIVE SERVICE : client API REST ITextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials()) { AzureRegion = AzureRegions.Australiaeast }; var result = new TextAnalyticsResult(); // COGNITIVE SERVICE : Détection de la langue var resultLanguage = await client.DetectLanguageAsync(new BatchInput( new List <Input>() { new Input("0", text) })); var l = resultLanguage.Documents[0].DetectedLanguages[0]; result.Language = l.Name; result.LanguageIso = l.Iso6391Name; // COGNITIVE SERVICE : Détection des phrases clés var resultKeyPhrases = client.KeyPhrasesAsync(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(result.LanguageIso, "0", text) })); result.KeyPhrases = resultKeyPhrases.Result.Documents[0].KeyPhrases.ToArray(); // COGNITIVE SERVICE : Détection du score de sentiment var resultSentiment = client.SentimentAsync(new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(result.LanguageIso, "0", text) })); result.ScoreSentiment = resultSentiment.Result.Documents[0].Score; return(result); } catch (Exception ex) { _logger.LogError($"Text analyze : {ex.Message}"); return(null); } }
public LanguageBatchResult DetectLanguageServiceForAString(string text) { ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westeurope; client.SubscriptionKey = ""; LanguageBatchResult result = client.DetectLanguage(new BatchInput( new List <Input> { new Input("0", text) })); return(result); }