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); }
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); } }
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 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 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); }
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); }
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}"); } } }
/// <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 double MakeAnalysisRequest(string message) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westcentralus, SubscriptionKey = Properties.Resources.TextApiSubscriptionKey }; // Extracting sentiment SentimentBatchResult result = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("ru", "0", message), })); var score = result.Documents[0].Score; return(score.HasValue ? score.Value : 0); // score.HasValue ? score.ToString() : "Что-то пошло не так"; }
public static async Task <double?> GetSentiment(string inputText, string analyticsID) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "2763d3dab1404c1e99b75c283f9642b0"; // Extracting language LanguageBatchResult resultLanguage = client.DetectLanguage( new BatchInput( new List <Input>() { new Input(analyticsID, inputText), })); // Printing language results. LanguageBatchResultItem docItem = resultLanguage.Documents[0]; // perchè analizzo solo una frase per volta string language = string.Empty; if (docItem.DetectedLanguages[0].Name.Equals("english")) { language = "en"; } //Extracting sentiment SentimentBatchResult resultSentiment = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(language, docItem.Id, inputText), })); return(resultSentiment.Documents[0].Score); }
/// <summary> /// Gets the emotion response. /// </summary> /// <param name="phrase">phrase to calculate the sentiment of.</param> /// <returns>the score of the emotion response</returns> private double GetEmotionResponse(string phrase) { // Initiating the text analytics client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); // Setting the client region. client.AzureRegion = AzureRegions.Westeurope; // Setting the client subscription key. client.SubscriptionKey = subscriptionKey; // Sending the request to the server and getting the results. SentimentBatchResult result = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(language, DOCUMENT_ID, phrase) })); // Returning the result return(result.Documents[0].Score.Value * 100); }
private static int GetScore(string message) { ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westus; client.SubscriptionKey = _textAnalyticsApi; var results = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", message) })); if (results.Documents.Count == 0) { return(0); } var score = results.Documents[0].Score.GetValueOrDefault(); var fixedScore = (int)(score * 100); return(fixedScore); }
/// <summary> /// Sends a speech recognition request to the speech service /// </summary> /// <param name="audioFile">The audio file.</param> /// <param name="locale">The locale.</param> /// <param name="serviceUrl">The service URL.</param> /// <param name="subscriptionKey">The subscription key.</param> /// <returns> /// A task /// </returns> public async Task Run() { // create the preferences object var preferences = new Preferences("en-US", LongDictationUrl, new CognitiveServicesAuthorizationProvider("c26f94bbc00e4c98a0ee0cde5833506a")); // Create a a speech client using (var speechClient = new SpeechClient(preferences)) { //speechClient.SubscribeToPartialResult(this.OnPartialResult); speechClient.SubscribeToRecognitionResult(this.OnRecognitionResult); // create an audio content and pass it a stream. using (var audio = new FileStream(filename, FileMode.Open, FileAccess.Read)) { var deviceMetadata = new DeviceMetadata(DeviceType.Near, DeviceFamily.Desktop, NetworkType.Ethernet, OsName.Windows, "1607", "Dell", "T3600"); var applicationMetadata = new ApplicationMetadata("SampleApp", "1.0.0"); var requestMetadata = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "SampleAppService"); await speechClient.RecognizeAsync(new SpeechInput(audio, requestMetadata), this.cts.Token).ConfigureAwait(false); } } // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "922da2349b3f4d5f8d30cf175347ce7b"; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", Msg), })); // Printing sentiment results var document = result3.Documents[result3.Documents.Count() - 1]; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Sentiment Score: {0:0.00}", document.Score); //Save to DB string sql = "update [CaseConversation] set [ConversationTranscript] = '" + Msg + "',"; sql += "[SentimentScore] = " + document.Score + " where id = " + sqlInt + ";"; using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"])) { // 1. declare command object with parameter conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; // 2. define parameters used in command object //SqlParameter param = new SqlParameter(); //param.ParameterName = "@qkid"; //param.Value = "''"; // 3. add new parameter to command object //cmd.Parameters.Add(param); int sqlInt2 = cmd.ExecuteNonQuery(); cmd.Dispose(); conn.Close(); } Msg += "<br /> <br />" + sb.ToString(); }
public string Get(string textToInspect) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westeurope; client.SubscriptionKey = config["TextAnalysisKey"]; StringBuilder sb = new StringBuilder(); // Extracting language sb.AppendLine("===== LANGUAGE EXTRACTION ======"); LanguageBatchResult result = client.DetectLanguage( new BatchInput( new List <Input>() { new Input("1", textToInspect), })); // Printing language results. foreach (var document in result.Documents) { sb.AppendLine($"Document ID: {document.Id} , Language: {document.DetectedLanguages[0].Name}"); // Getting key-phrases sb.AppendLine("\n\n===== KEY-PHRASE EXTRACTION ======"); var isoLanguageName = document.DetectedLanguages[0].Iso6391Name; KeyPhraseBatchResult phraseResult = client.KeyPhrases( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(isoLanguageName, "1", textToInspect), })); var phrasesFound = phraseResult.Documents.FirstOrDefault(); if (phrasesFound == null) { throw new Exception("Failed processing message - no phrase result"); } sb.AppendLine($"Document ID: {phrasesFound.Id} "); sb.AppendLine("\t Key phrases:"); foreach (string keyphrase in phrasesFound.KeyPhrases) { sb.AppendLine("\t\t" + keyphrase); var entitySearchApi = new EntitySearchAPI(new ApiKeyServiceClientCredentials(config["EntityKey"])); var entityData = entitySearchApi.Entities.Search(keyphrase); if (entityData?.Entities?.Value?.Count > 0) { // find the entity that represents the dominant one var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault(); if (mainEntity != null) { sb.AppendLine($"Searched for {keyphrase} and found a dominant entity with this description:"); sb.AppendLine(mainEntity.Description); } else { sb.AppendLine($"Couldn't find a main entity for {keyphrase}"); } } else { sb.AppendLine($"No data returned for entity {keyphrase}"); } } // Extracting sentiment sb.AppendLine("\n\n===== SENTIMENT ANALYSIS ======"); SentimentBatchResult sentimentResult = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(isoLanguageName, "0", textToInspect), })); var sentiment = sentimentResult.Documents.FirstOrDefault(); if (sentiment == null) { throw new Exception("Failed processing message - no sentiment result"); } // Printing sentiment results sb.AppendLine($"Document ID: {sentiment.Id} , Sentiment Score: {sentiment.Score}"); } return(sb.ToString()); }
static void Main(string[] args) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI { AzureRegion = AzureRegions.Westus, SubscriptionKey = "your subscription key" }; Console.OutputEncoding = System.Text.Encoding.UTF8; // Extracting language Console.WriteLine("===== LANGUAGE EXTRACTION ======"); LanguageBatchResult result = client.DetectLanguage( new BatchInput( new List <Input>() { new Input("1", "This is a document written in English."), new Input("2", "Este es un document escrito en Español."), new Input("3", "这是一个用中文写的文件") })); // Printing language results. foreach (var document in result.Documents) { Console.WriteLine("Document ID: {0} , Language: {1}", document.Id, document.DetectedLanguages[0].Name); } // Getting key-phrases Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======"); KeyPhraseBatchResult result2 = client.KeyPhrases( 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!") })); // 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); } } // Extracting sentiment Console.WriteLine("\n\n===== SENTIMENT ANALYSIS ======"); SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", "I had the best day of my life."), 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."), })); // Printing sentiment results foreach (var document in result3.Documents) { Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); } }
public static async Task RunAsync( [CosmosDBTrigger("Tweets", "TweetsToAnalyze", CreateLeaseCollectionIfNotExists = true, LeasesCollectionThroughput = 1000)] IReadOnlyList <Document> documents, TraceWriter log) { var textAnalyticsAzureRegion = ConfigurationManager.AppSettings["AnalyticsAzureRegion"]; var textAnalyticsSubKey = ConfigurationManager.AppSettings["AnalyticsSubKey"]; var databaseName = ConfigurationManager.AppSettings["CosmosDatabase"]; var outputCollectionName = ConfigurationManager.AppSettings["CosmosCollectionOutput"]; var inputCollectionName = ConfigurationManager.AppSettings["CosmosCollectionInput"]; var endpoint = ConfigurationManager.AppSettings["CosmosEndpoint"]; var authKey = ConfigurationManager.AppSettings["CosmosKey"]; var tweetsList = new List <Tweet>(); var scoredDocuments = new List <object>(); log.Info($"Function triggered, processing {documents.Count} documents."); //Create list of Tweets foreach (var doc in documents) { Tweet tweet = (dynamic)doc; tweetsList.Add(tweet); } // Do TextAnalysis using (ITextAnalyticsAPI textAnalyzerClient = new TextAnalyticsAPI()) { AzureRegions region = (AzureRegions)Enum.Parse(typeof(AzureRegions), textAnalyticsAzureRegion); textAnalyzerClient.AzureRegion = region; textAnalyzerClient.SubscriptionKey = textAnalyticsSubKey; // Add tweets to analysis batch var mlinput = new List <MultiLanguageInput>(); foreach (var doc in documents) { Tweet tweet = JsonConvert.DeserializeObject <Tweet>(doc.ToString()); mlinput.Add(new MultiLanguageInput(tweet.Language, tweet.Id, tweet.Text)); } var mlbatchinput = new MultiLanguageBatchInput(mlinput); SentimentBatchResult result = textAnalyzerClient.Sentiment(mlbatchinput); // Add score to the original tweets and convert to documents foreach (var document in result.Documents) { var tweet = tweetsList .Where(d => d.Id == document.Id) .FirstOrDefault() .Sentiment = document.Score; scoredDocuments.Add(JsonConvert.SerializeObject(tweet)); } } var outputCollectionLink = UriFactory.CreateDocumentCollectionUri(databaseName, outputCollectionName); using (DocumentClient cosmosClient = new DocumentClient( new Uri(endpoint), authKey, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp })) { foreach (var scoredTweet in tweetsList) { await cosmosClient.CreateDocumentAsync(outputCollectionLink, scoredTweet); await cosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, inputCollectionName, scoredTweet.Id)); } } }
public static StoryLine createStory(string userInput) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westus; client.SubscriptionKey = "49bd3a3a1a244fd289aa30b7a5594b05"; Console.OutputEncoding = System.Text.Encoding.UTF8; // Extracting language Console.WriteLine("===== LANGUAGE EXTRACTION ======"); // CALLING TAMMY's FUNCTION TO GET THE USER INPUT STRING string inputString = "I live in HongKong for nine years now. After that, I went to UCSD for college. I miss food from hometown."; // Split each line according to period. Afterr the speech ends, return an empty string. string [] singleLine = inputString.Split('.'); string [] keyWordResult = new string[singleLine.Length]; double [] sentimentResult = new double[singleLine.Length]; List <Input> inputLine = new List <Input>(); int count = 0; foreach (var line in singleLine) { //Console.WriteLine($"<{line}>"); inputLine.Add(new Input(count.ToString(), line)); count++; } string[] languages = new string[inputLine.Count]; LanguageBatchResult result = client.DetectLanguage( new BatchInput( inputLine )); // Updating language results. count = 0; foreach (var document in result.Documents) { //Console.WriteLine("Document ID: {0} , Language: {1}", document.Id, document.DetectedLanguages[0].Iso6391Name); languages[count] = document.DetectedLanguages[0].Iso6391Name; count++; } // Getting key-phrases Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======"); int languageCount = 0; count = 0; List <MultiLanguageInput> inputKeywordLine = new List <MultiLanguageInput>(); foreach (var key in singleLine) { //Console.WriteLine("The language is: {0}, The count is {1}, the key is {2}", languages[languageCount], count.ToString(),key); inputKeywordLine.Add(new MultiLanguageInput(languages[languageCount], count.ToString(), key)); count++; } KeyPhraseBatchResult result2 = client.KeyPhrases( new MultiLanguageBatchInput( inputKeywordLine )); // Printing keyphrases foreach (var document in result2.Documents) { //Console.WriteLine("Document ID: {0} ", document.Id); //Console.WriteLine("\t Key phrases: {0}", document.KeyPhrases[0]); keyWordResult[Int32.Parse(document.Id)] = document.KeyPhrases[0]; //Console.WriteLine(keyWordResult[Int32.Parse(document.Id)]); /* * foreach (string keyphrase in document.KeyPhrases) * { * Console.WriteLine("\t\t" + keyphrase); * } */ } // Extracting sentiment Console.WriteLine("\n\n===== SENTIMENT ANALYSIS ======"); SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( inputKeywordLine /* * new List<MultiLanguageInput>() * { * new MultiLanguageInput("en", "1", "I live in HongKong for nine years now."), * new MultiLanguageInput("en", "2", "After that, I went to UCSD for college."), * new MultiLanguageInput("en", "3", " I miss food from hometown."), * }*/ )); // Printing sentiment results foreach (var document in result3.Documents) { sentimentResult[Int32.Parse(document.Id)] = Convert.ToDouble(document.Score); //Console.WriteLine(sentimentResult[Int32.Parse(document.Id)]); } return(new StoryLine(languages, keyWordResult, sentimentResult)); }
static void Main(string[] args) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Eastus2; client.SubscriptionKey = args[0]; Console.OutputEncoding = System.Text.Encoding.UTF8; string[] fileEntries = Directory.GetFiles(args[1]); foreach (string fileName in fileEntries) { FileStream fileStream = new FileStream(fileName, FileMode.Open); FileStream out1 = new FileStream(fileName + ".KP.TXT", FileMode.Create); FileStream out2 = new FileStream(fileName + ".SENT.TXT", FileMode.Create); try { // Open the text file using a stream reader. using (StreamReader sr = new StreamReader(fileStream)) { String fullText = ""; // Read the stream to a string, and write the string to the console. while (!sr.EndOfStream) { String line = sr.ReadLine(); if (!line.StartsWith("NOTE Confidence:") && !line.StartsWith("00:") && !line.StartsWith("WEBVTT")) { fullText = fullText + line + System.Environment.NewLine; } } //Console.Write(fullText); Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======"); KeyPhraseBatchResult result2 = client.KeyPhrases( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("", "1", fullText) })); using (StreamWriter sw1 = new StreamWriter(out1)) { // Printing keyphrases foreach (var document in result2.Documents) { foreach (string keyphrase in document.KeyPhrases) { sw1.WriteLine(keyphrase); } /* * Console.WriteLine("Document ID: {0} ", document.Id); * Console.WriteLine("\t Key phrases:"); * foreach (string keyphrase in document.KeyPhrases) * { * Console.WriteLine("\t\t" + keyphrase); * } */ } } // Extracting sentiment Console.WriteLine("\n\n===== SENTIMENT ANALYSIS ======"); SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("", "1", fullText) })); using (StreamWriter sw2 = new StreamWriter(out2)) { // Printing keyphrases foreach (var document in result3.Documents) { sw2.WriteLine("Sentiment Score: {0:0.00}", document.Score); } } // Printing sentiment results //foreach (var document in result3.Documents) //{ //Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score); //} } } catch (Exception e) { Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } }
public void RegisterAppointment(string message) { if (string.IsNullOrEmpty(message)) { return; } QueueAppointment app = null; try { app = Newtonsoft.Json.JsonConvert.DeserializeObject <QueueAppointment>(message); } catch (Exception ex) { Logger.LogError(System.Reflection.MethodBase.GetCurrentMethod(), string.Format("[RegisterAppointment] - Eroare la parsarea mesajului. Mesaj: {0}. Eroare: {1}.", message, ex.Message)); return; } SqlParameter response = new SqlParameter("@Response", System.Data.SqlDbType.NVarChar); response.Direction = System.Data.ParameterDirection.Output; response.Size = int.MaxValue; SqlParameter responseMessage = new SqlParameter("@ResponseMessage", System.Data.SqlDbType.NVarChar); responseMessage.Direction = System.Data.ParameterDirection.Output; responseMessage.Size = int.MaxValue; SqlParameter messageID = new SqlParameter("@MessageID", System.Data.SqlDbType.Int); messageID.Direction = System.Data.ParameterDirection.Output; using (SqlConnection con = AppConfiguration.DatabaseConnectionString) using (SqlCommand cmd = new SqlCommand(@"EXEC sp_RegisterAppointmentMessage @RequestedDate = @RequestedDate, @Email = @Email, @Message = @Message, @EmailID = @EmailID, @Name = @Name, @NumberOfPersons = @NumberOfPersons, @GoodCustomer = @GoodCustomer, @Response = @Response OUTPUT, @ResponseMessage = @ResponseMessage OUTPUT, @MessageID = @MessageID OUTPUT" , con)) { cmd.Parameters.Add(new SqlParameter("@RequestedDate", app.date)); cmd.Parameters.Add(new SqlParameter("@Email", app.email)); cmd.Parameters.Add(new SqlParameter("@Message", app.message)); cmd.Parameters.Add(new SqlParameter("@EmailID", DBNull.Value)); cmd.Parameters.Add(new SqlParameter("@Name", DBNull.Value)); cmd.Parameters.Add(new SqlParameter("@NumberOfPersons", DBNull.Value)); ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westeurope; client.SubscriptionKey = "fcd70fa96095470fa5c7ec05f3a56d60"; Console.OutputEncoding = System.Text.Encoding.UTF8; SentimentBatchResult result3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput("en", "0", app.message), })); try { if (result3 != null && result3.Documents.Count > 0) { cmd.Parameters.Add(new SqlParameter("@GoodCustomer", result3.Documents[0].Score > 0.5)); } else { cmd.Parameters.Add(new SqlParameter("@GoodCustomer", DBNull.Value)); } } catch { cmd.Parameters.Add(new SqlParameter("@GoodCustomer", DBNull.Value)); } cmd.Parameters.Add(response); cmd.Parameters.Add(responseMessage); cmd.Parameters.Add(messageID); try { con.Open(); cmd.ExecuteNonQuery(); if (responseMessage.Value != null) { Utils.SendEmail(responseMessage.Value.ToString(), app.email); } } catch (Exception ex) { Logger.LogError(System.Reflection.MethodBase.GetCurrentMethod(), "[RegisterAppointment] - Eroare la salvarea mesajului. Mesaj: " + ex.Message); } finally { if (con.State == System.Data.ConnectionState.Open) { con.Close(); } } } Logger.LogError(System.Reflection.MethodBase.GetCurrentMethod(), "[RegisterAppointment] - Raspuns: " + responseMessage.Value); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westeurope; client.SubscriptionKey = Environment.GetEnvironmentVariable("clientSubscriptionKey"); _inputCount++; //Luis var httpClient = new HttpClient(); var queryString = HttpUtility.ParseQueryString(string.Empty); var luisAppId = Environment.GetEnvironmentVariable("luisAppId"); var subscriptionKey = Environment.GetEnvironmentVariable("subscriptionKey"); // The request header contains your subscription key httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey); // The "q" parameter contains the utterance to send to LUIS queryString["q"] = activity.Text; // These optional request parameters are set to their default values queryString["timezoneOffset"] = "0"; queryString["verbose"] = "false"; queryString["spellCheck"] = "false"; queryString["staging"] = "false"; var uri = "https://westeurope.api.cognitive.microsoft.com/luis/v2.0/apps/" + luisAppId + "?" + queryString; var response = await httpClient.GetAsync(uri); string lang = null; var dataFromLuis = JsonConvert.DeserializeObject <LuisResponse>(response.Content.ReadAsStringAsync().Result); if (dataFromLuis.entities.Length > 0) { lang = dataFromLuis.entities[0].entity; } //Finne språket LanguageBatchResult res = client.DetectLanguage( new BatchInput( new List <Input> { new Input(_inputCount.ToString(), activity.Text) })); // calculate something for us to return int length = (activity.Text ?? string.Empty).Length; StringBuilder keyWordBuilder = new StringBuilder(); keyWordBuilder.Append(" "); // Printing language results. foreach (var document in res.Documents) { //Finne nøkkelfraser KeyPhraseBatchResult res2 = client.KeyPhrases( new MultiLanguageBatchInput( new List <MultiLanguageInput> { new MultiLanguageInput(document.DetectedLanguages[0].Iso6391Name, _inputCount.ToString(), activity.Text) })); // Printing keyphrases foreach (var doc2 in res2.Documents) { foreach (string keyphrase in doc2.KeyPhrases) { keyWordBuilder.Append(keyphrase + " "); } if (doc2.KeyPhrases.Count == 0) { keyWordBuilder.Append("Fant ingen nøkkelfraser"); } } // Extracting sentiment SentimentBatchResult res3 = client.Sentiment( new MultiLanguageBatchInput( new List <MultiLanguageInput> { new MultiLanguageInput(document.DetectedLanguages[0].Iso6391Name, _inputCount.ToString(), activity.Text) })); // Printing sentiment results foreach (var doc3 in res3.Documents) { ConsultantResponse dataFromResponsefromConsultant = null; var httpConsultant = new HttpClient(); httpConsultant .DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); //ACCEPT header if (lang != null) { var responsefromConsultant = await httpConsultant.GetAsync( $"http://37.139.15.166/consultants?skill={dataFromLuis.entities[0].entity}"); dataFromResponsefromConsultant = JsonConvert.DeserializeObject <ConsultantResponse>( responsefromConsultant.Content.ReadAsStringAsync().Result); } string returnConsultantIfData(ConsultantResponse cr) { int count = 0; if (cr != null && cr.consultants.Length > 0) { StringBuilder cnBuilder = new StringBuilder(); cnBuilder.AppendLine( $"I hear you are looking for people that know {dataFromLuis.entities[0].entity} programming language. In our resource database i found: "); foreach (var c in cr.consultants) { cnBuilder.Append(c.name); count++; if (count < cr.consultants.Length) { cnBuilder.Append(", "); } } return(cnBuilder.ToString()); } return(null); } var textInput = activity.Text; var langIs = document.DetectedLanguages[0].Name; var keyFrases = keyWordBuilder.ToString().TrimEnd(); var emotionScoreIs = $"{doc3.Score:0.00}"; bool onlyLuisApi = true; StringBuilder responsBuilder = new StringBuilder(); if (onlyLuisApi) { //Only luis fetch programming skills responsBuilder. Append(returnConsultantIfData(dataFromResponsefromConsultant)); } else { //With detect language, sentiment, key frases and luis programming skills responsBuilder. Append("Hello! You wrote "). AppendLine(textInput + "."). Append("The language is most likely: "). AppendLine(langIs + "."). Append("The key frases are: "). AppendLine(keyFrases + "."). Append("Based what you wrote i detected the sentiment score: "). AppendLine(emotionScoreIs + " On a scale between 0-1, where 0 is the most negative(sad) and 1 is most positive(happy)."). Append(returnConsultantIfData(dataFromResponsefromConsultant)); } // return our reply to the user if (responsBuilder.Length > 0) { await context.PostAsync(responsBuilder.ToString()); } } } context.Wait(MessageReceivedAsync); }
public async Task <TextAnalyticsDocumentSentimentModel> CallTextAnalytics(string utterance) { // Create a client. ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westeurope; client.SubscriptionKey = _textAnalyticsSubscriptionKey; var keysList = ""; var language = client.DetectLanguage( new BatchInput( new List <Input>() { new Input("0", utterance) })); foreach (var document in language.Documents) { Console.WriteLine("Document ID: {0} , Language: {1}", document.Id, document.DetectedLanguages[0].Name); } var lang = language.Documents.FirstOrDefault()?.DetectedLanguages.FirstOrDefault()?.Iso6391Name; var keys = client.KeyPhrases( new MultiLanguageBatchInput( new List <MultiLanguageInput>() { new MultiLanguageInput(lang, "0", utterance), })); var sentiment = client.Sentiment(new MultiLanguageBatchInput(new List <MultiLanguageInput>() { new MultiLanguageInput(lang, "0", utterance) })); //Si les sentiments sont nulls, on renvoie un objet vide if (sentiment.Documents == null) { return(new TextAnalyticsDocumentSentimentModel()); } { var document = new TextAnalyticsDocumentSentimentModel { Text = utterance, Score = sentiment.Documents.FirstOrDefault(x => x.Id == "0")?.Score, Id = sentiment.Documents.FirstOrDefault()?.Id, Language = lang }; if (keys.Documents != null) { foreach (var item in keys.Documents.SelectMany(x => x.KeyPhrases).ToList()) { document.KeyWords += item; } } if (language.Documents == null) { return(document); } { foreach (var item in language.Documents.SelectMany(x => x.DetectedLanguages).ToList()) { document.DetectedLanguage += item.Name; } } return(document); } }