public async Task <IHttpActionResult> PutDeviceMetadata(string id, [FromBody] DeviceMetadata metadata) { if (metadata == null) { return(BadRequest("metadata is null")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } DeviceInfo info = await _registry.FindAsync(id); if (info == null) { info = new DeviceInfo { DeviceId = id, Status = DeviceStateConstants.RegisteredState, Metadata = metadata }; await _registry.AddOrUpdateAsync(info); return(CreatedAtRoute("DefaultApi", new { id = id }, info)); } else { info.Metadata = metadata; await _registry.AddOrUpdateAsync(info); return(Ok(info)); } }
/// <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(string audioFile, string locale, Uri serviceUrl, string subscriptionKey, string resultFile) { // create the preferences object var preferences = new Preferences(locale, serviceUrl, new CognitiveServicesAuthorizationProvider(subscriptionKey)); ResultFile = resultFile; File.CreateText(ResultFile); // 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(audioFile, 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); } } }
/// <summary> /// 通过语音数据识别语音内容 /// </summary> /// <param name="audioBytes">语音数据</param> /// <param name="locale">语种</param> /// <returns></returns> public async Task RunDiscernAsBytes(byte[] audioBytes, string locale) { Uri serviceUrl = ShortUrl; if (GetWavPlayTime(audioBytes) > 15) { serviceUrl = LongUrl; } var preferences = new Preferences(locale, serviceUrl, new AsrCheckKeyProvider(apiKey)); //参数配置类 using (var speechClient = new SpeechClient(preferences)) //创建语音客户端 { speechClient.SubscribeToPartialResult(this.OnPartialResult); speechClient.SubscribeToRecognitionResult(this.OnRecognitionResult); using (Stream stream = new MemoryStream(audioBytes)) { 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"); try { await speechClient.RecognizeAsync(new SpeechInput(stream, requestMetadata), this.cts.Token).ConfigureAwait(false); } catch (Exception ex) { } } } }
public async Task DecodeAudioAsync( Stream stream, string locale, PhraseMode mode, Func <RecognitionStep, Task> partialResult, Func <RecognitionFinalResult, Task> finalResult) { var serviceUrl = (mode == PhraseMode.LongDictation ? LongDictationUrl : ShortPhraseUrl); string subscriptionKey = configuration.GetSection("AudioToTextService.Core.AudioDecoder")["subscriptionKey"]; // create the preferences object var preferences = new Preferences(locale, serviceUrl, new CognitiveServicesAuthorizationProvider(subscriptionKey)); // Create a a speech client using (var speechClient = new SpeechClient(preferences)) { speechClient.SubscribeToPartialResult((args) => { return(partialResult(ToStep(args))); }); speechClient.SubscribeToRecognitionResult((args) => { return(finalResult(ToFinalResult(args))); }); // create an audio content and pass it a stream. 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(stream, requestMetadata), this.cts.Token).ConfigureAwait(false); } }
public void EnrichMessage(DeviceMetadata metadata) { if (metadata != null) { this.Capabilities = metadata.Capability; } }
/// <summary> /// Notifies to add a key. /// </summary> /// <param name="alias">alias alias to notify</param> /// <param name="keys">keys that need approval</param> /// <param name="deviceMetadata">device metadata of the keys</param> /// <returns>status of the notification</returns> public NotifyStatus NotifyAddKeyBlocking( Alias alias, IList <Key> keys, DeviceMetadata deviceMetadata) { return(NotifyAddKey(alias, keys, deviceMetadata).Result); }
public override IDevice createNewInstance(DeviceMetadata m, IDevice parent) { if (m.Type == NanoleafDevice.NANOLEAF_DEVICE_TYPE_NAME) { NanoleafDevice d = new NanoleafDevice(Guid.NewGuid().ToString()); d.Name = "new Nanoleaf Panel"; d.DeviceType = (EDeviceType)Enum.Parse(typeof(EDeviceType), m.Model); //Find the next ID if possible var lamps = org.dmxc.lumos.Kernel.Project.DeviceManager.getInstance() .Devices.OfType <NanoleafDevice>().Where(c => c.DeviceType.Equals(d.DeviceType)).Select(c => c.PanelID); var firstid = NanoleafPlugin.getAllPanels(d.DeviceType).Select(p => p.ID) .Except(lamps) .FirstOrDefault(); if (firstid != 0) { d.PanelID = firstid; return(d); } return(d); } throw new NotSupportedException("Unable to create a Device for Type: " + m.Type); }
private static async Task RegisterDeviceAsync(CancellationToken token) { string baseUrl = ConfigurationHelper.GetConfigValue <string>("WebApiEndpoint"); HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseUrl); var metadata = new DeviceMetadata { Building = 1, Room = 42 }; Console.WriteLine("Registering device ID = {0}", DEVICE_ID); var result = await client.PutAsJsonAsync("api/registry/" + DEVICE_ID, metadata, token); Console.WriteLine("{0} ({1})", (int)result.StatusCode, result.ReasonPhrase); if (result.IsSuccessStatusCode) { var info = await result.Content.ReadAsAsync <DeviceInfo>(token); Console.WriteLine("Device state: {0}", info.Status); } }
/// <summary> /// Notifies subscribed devices that a token should be created and endorsed. /// </summary> /// <param name="tokenRequestId">the token request ID to send</param> /// <param name="keys">keys to be added</param> /// <param name="deviceMetadata">device metadata of the keys</param> /// <param name="receiptContact">optional receipt contact to send</param> /// <returns>notify result of the notification request</returns> public NotifyResult NotifyCreateAndEndorseTokenBlocking( string tokenRequestId, IList <Key> keys, DeviceMetadata deviceMetadata, ReceiptContact receiptContact) { return(NotifyCreateAndEndorseToken(tokenRequestId, keys, deviceMetadata, receiptContact).Result); }
public DeviceMetadataViewModel(DeviceMetadata metadata) { _metadata = metadata; MappingMetadata = new ObservableCollection <Tuple <int, MappingMetadata> >(_metadata.MappingMetadata.Select(m => new Tuple <int, MappingMetadata>(m.Key, m.Value))); MappingMetadata.CollectionChanged += onMappingMetadataChanged; //ConditionDescriptions = new ObservableCollection<Tuple<ACondition, string>>(_metadata.ConditionDescriptions.Select(c => new Tuple<ACondition, string>(c.Key, c.Value))); }
public void SetupSpeechToTextImplementTest() { ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap(); exeConfigurationFileMap.ExeConfigFilename = "SpeechLicense.config"; this.config = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None); DeviceMetadata dummy = new DeviceMetadata(DeviceType.Far, DeviceFamily.Automotive, NetworkType.Cell1xRTT, OsName.Windows, "10", "whocares", "123"); var dummy2 = NAudio.Wave.WaveCallbackStrategy.Event; var dummy3 = Microsoft.VisualStudio.Threading.JoinableTaskCreationOptions.LongRunning; }
private Task <Tuple <string, string> > transcribeAudioSegement(int index, string fileName, string audioFile, TimeSpan totalTime, CancellationToken token, string user) { return(Task.Factory.StartNew <Tuple <string, string> >(() => { //var preferences = new Preferences("en-US", new Uri("wss://speech.platform.bing.com/api/service/recognition/continuous"), new CognitiveServicesAuthorizationProvider("68ecbfed77384b0badae81995a5b256b")); var preferences = new Preferences("en-US", new Uri("wss://5ba5d066af03405ba71e84ba3bc4d185.api.cris.ai/ws/cris/speech/recognize/continuous"), new CognitiveServicesAuthorizationProvider("36677b4f10da4d2a946af66da757ef0b")); DateTime lastReportTime = DateTime.Now; DateTime lastDetectionTime = DateTime.Now; int runonLength = 0; StringBuilder text = new StringBuilder(); using (var speechClient = new SpeechClient(preferences)) { speechClient.SubscribeToPartialResult((args) => { return Task.Factory.StartNew(() => { token.ThrowIfCancellationRequested(); if (DateTime.Now - lastReportTime >= mReportInterval) { var percent = (int)(args.MediaTime * 0.00001 / totalTime.TotalSeconds); percentages[index] = percent; reportProgress(fileName, Math.Min(99, percentages.Sum()), args.DisplayText.Substring(0, Math.Min(args.DisplayText.Length, 50)) + "...", user).Wait(); lastReportTime = DateTime.Now; } }); }); speechClient.SubscribeToRecognitionResult((args) => { return Task.Factory.StartNew(() => { if (args.Phrases.Count > 0) { string bestText = args.Phrases[args.Phrases.Count - 1].DisplayText; runonLength += bestText.Length; if ((DateTime.Now - lastDetectionTime >= TimeSpan.FromSeconds(5) || runonLength >= 1800) && runonLength >= 250) { text.Append("\r\n\r\n "); runonLength = 0; } text.Append(Regex.Replace(bestText, "(?<=[\\.,?])(?![$ ])", " ")); lastDetectionTime = DateTime.Now; } }); }); using (var audio = new FileStream(audioFile, FileMode.Open, FileAccess.Read)) { var deviceMetadata = new DeviceMetadata(DeviceType.Near, DeviceFamily.Desktop, NetworkType.Ethernet, OsName.Windows, "1607", "Dell", "T3600"); var applicationMetadata = new ApplicationMetadata("TranscriptionApp", "1.0.0"); var requestMetadata = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "TranscriptionService"); speechClient.RecognizeAsync(new SpeechInput(audio, requestMetadata), mTokensource.Token).Wait(); return new Tuple <string, string>(audioFile, text.ToString()); } } })); }
/// <summary> /// Notifies to add a key. /// </summary> /// <param name="alias">alias alias to notify</param> /// <param name="keys">keys that need approval</param> /// <param name="deviceMetadata">device metadata of the keys</param> /// <returns>status of the notification</returns> public Task <NotifyStatus> NotifyAddKey(Alias alias, IList <Key> keys, DeviceMetadata deviceMetadata) { var unauthenticated = ClientFactory.Unauthenticated(channel); var addKey = new AddKey { DeviceMetadata = deviceMetadata }; addKey.Keys.Add(keys); return(unauthenticated.NotifyAddKey(alias, addKey)); }
public bool TryGetDeviceMetadata(string deviceAcronym, out DeviceMetadata deviceMetadata) { deviceMetadata = new DeviceMetadata(); { bool ret = CommonPINVOKE.SubscriberInstanceBase_TryGetDeviceMetadata(swigCPtr, deviceAcronym, DeviceMetadata.getCPtr(deviceMetadata)); if (CommonPINVOKE.SWIGPendingException.Pending) { throw CommonPINVOKE.SWIGPendingException.Retrieve(); } return(ret); } }
public static async Task <string> ReconhecerFala(string contentUrl) { RecognitionStatus status = RecognitionStatus.None; string stringResult = string.Empty; WebClient wc = new WebClient(); OgaToWavConverter converter = new OgaToWavConverter(); var ogaData = await wc.DownloadDataTaskAsync(contentUrl); var wavData = converter.Convert(ogaData); var preferences = new Preferences("pt-BR", new Uri(@"wss://speech.platform.bing.com/api/service/recognition"), new CognitiveServicesAuthorizationProvider(CognitiveServicesAuthorizationProvider.API_KEY)); using (var speechClient = new SpeechClient(preferences)) { speechClient.SubscribeToPartialResult( result => { stringResult = result.DisplayText; return(Task.FromResult(true)); }); speechClient.SubscribeToRecognitionResult( result => { status = result.RecognitionStatus; return(Task.FromResult(true)); }); var deviceMetadata = new DeviceMetadata(DeviceType.Near, DeviceFamily.Unknown, NetworkType.Unknown, OsName.Windows, "10", "IBM", "ThinkCenter"); var applicationMetadata = new ApplicationMetadata("WorkshopAtentoBot", "1.0"); var requestMetada = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "ReconhecimentoFalaService"); await speechClient.RecognizeAsync(new SpeechInput(new MemoryStream(wavData), requestMetada), CancellationToken.None).ConfigureAwait(false); } while (status == RecognitionStatus.None) { await Task.Delay(200); } if (status == RecognitionStatus.Success) { return(stringResult); } else { return($"Ocorreu um erro no reconhecimento de fala. Status = {status}"); } }
public async Task NewDeviceReturnsCreated() { string id = "111"; var metadata = new DeviceMetadata(); IHttpActionResult actionResult = await _controller.PutDeviceMetadata(id, metadata); var createdResult = actionResult as CreatedAtRouteNegotiatedContentResult <DeviceInfo>; Assert.NotNull(createdResult); Assert.Equal("DefaultApi", createdResult.RouteName); Assert.Equal(id, createdResult.RouteValues["id"]); }
public async Task <bool> Add(DeviceMetadata deviceMetadata) { using (var conn = new System.Data.SqlClient.SqlConnection(_cs)) { conn.Open(); await conn.ExecuteAsync(@" INSERT INTO dbo.SensorConfiguration (DeviceId, Name, Location, Description) VALUES (@DeviceId, @Name, @Location, @Description)", deviceMetadata); return(true); } }
private void StartSpeechRecognition() { _recognitionCts = new CancellationTokenSource(); string speechSubscription = Service.Instance.Configuration.SpeechSubscription; Preferences preferences = new Preferences("en-US", LongDictationUrl, new CognitiveServicesAuthorizationProvider(speechSubscription), enableAudioBuffering: false); _recognitionStream = new SpeechRecognitionPcmStream(16000); var deviceMetadata = new DeviceMetadata(DeviceType.Far, DeviceFamily.Unknown, NetworkType.Unknown, OsName.Windows, "1607", "Dell", "T3600"); var applicationMetadata = new ApplicationMetadata("HueBot", "1.0.0"); var requestMetadata = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "HueBot"); Task.Run(async() => { do { try { //create a speech client using (_speechClient = new SpeechClient(preferences)) { _speechClient.SubscribeToRecognitionResult(this.OnRecognitionResult); await _speechClient.RecognizeAsync(new SpeechInput(_recognitionStream, requestMetadata), _recognitionCts.Token); } Log.Info(new CallerInfo(), LogContext.Media, $"[{this.Id}]: Speech recognize completed."); } catch (Exception exception) { Log.Error(new CallerInfo(), LogContext.Media, $"[{this.Id}]: Speech recognize threw exception {exception.ToString()}"); } if (_recognitionCts.IsCancellationRequested) { Log.Info(new CallerInfo(), LogContext.Media, $"[{this.Id}]:Speech recognition cancelled because it was cancelled or max exception count was hit"); break; } Stream oldStream = _recognitionStream; Log.Info(new CallerInfo(), LogContext.Media, $"[{this.Id}]: Restart speech recognition as the call is still alive. Speech recognition could have been completed because of babble/silence timeout"); _recognitionStream = new SpeechRecognitionPcmStream(16000); oldStream.Dispose(); } while (true); _speechRecoginitionFinished.Set(); } ).ForgetAndLogException(string.Format("Failed to start the SpeechRecognition Task for Id: {0}", Id)); }
/// <summary> /// Takes a passed in file that is assumed to be mono and PCM encoded, /// and sends it to the speech client. /// </summary> /// <param name="audioFile">The full path and file name of a PCM encoded MONO channel file.</param> /// <returns></returns> public async Task ExecuteRecogniseAsync(string audioFile) { FileInfo inputFileInfo = new FileInfo(audioFile); WaveStream audioStream = null; Mp3FileReader mp3Stream = null; string tempAudioFile = audioFile; switch (inputFileInfo.Extension.ToLower()) { case ".mp3": mp3Stream = new Mp3FileReader(audioFile); audioStream = WaveFormatConversionStream.CreatePcmStream(mp3Stream); // Have to send to a physical file, as the NAudio stream doesn't interact with the // Speech client nicely. tempAudioFile = System.IO.Path.GetTempFileName(); WaveFileWriter.CreateWaveFile(tempAudioFile, audioStream); break; default: // Try and send the file to the speechClient, in the hope it is a PCM encoded file. break; } //using (var inputReader = new AudioFileReader(audioFile)) //{ // var mono = inputReader.ToMono(0.5f, 0.5f); //} // Create a a speech client using (var speechClient = new SpeechClient(this._preferences)) { speechClient.SubscribeToRecognitionResult(this.OnRecognitionResultAsync); var deviceMetadata = new DeviceMetadata(DeviceType.Near, DeviceFamily.Desktop, NetworkType.Ethernet, OsName.Windows, "1607", "HyperV", "HyperV"); var applicationMetadata = new ApplicationMetadata("SSISSpeachToText", "1.0.0.0"); var requestMetadata = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "SQL Server Integration Services"); using (var audio = new FileStream(tempAudioFile, FileMode.Open, FileAccess.Read)) await speechClient.RecognizeAsync(new SpeechInput(audio, requestMetadata), this.cts.Token).ConfigureAwait(false); } if (audioStream != null) { audioStream.Dispose(); } if (mp3Stream != null) { mp3Stream.Dispose(); } }
public async Task <IActionResult> Create([FromBody] DeviceMetadata deviceMetadata) { if (deviceMetadata == null) { return(BadRequest()); } var result = await _sensorService.Add(deviceMetadata); if (result) { return(CreatedAtRoute("GetSensor", new { deviceId = deviceMetadata.DeviceId }, deviceMetadata)); } return(BadRequest()); }
public async Task <bool> Update(DeviceMetadata deviceMetadata) { using (var conn = new System.Data.SqlClient.SqlConnection(_cs)) { conn.Open(); await conn.ExecuteAsync(@" UPDATE dbo.SensorConfiguration SET Name = @Name, Location = @Location, Description = @Description WHERE DeviceId = @DeviceId", deviceMetadata); return(true); } }
public IActionResult Update(int deviceId, [FromBody] DeviceMetadata item) { if (item == null || item.DeviceId != deviceId) { return(BadRequest()); } var sensor = _sensorService.Get(deviceId); if (sensor == null) { return(NotFound()); } _sensorService.Update(item); return(new NoContentResult()); }
public async Task ExistingDeviceReturnsOk() { string id = "112"; var metadata = new DeviceMetadata(); _registry.Setup(x => x.FindAsync(id)) .ReturnsAsync(new DeviceInfo { DeviceId = id }); IHttpActionResult actionResult = await _controller.PutDeviceMetadata(id, metadata); var contentResult = actionResult as OkNegotiatedContentResult <DeviceInfo>; Assert.NotNull(contentResult); Assert.NotNull(contentResult.Content); }
/// <summary> /// Notifies subscribed devices that a token should be created and endorsed. /// </summary> /// <param name="tokenRequestId">the token request ID to send</param> /// <param name="keys">keys to be added</param> /// <param name="deviceMetadata">device metadata of the keys</param> /// <param name="receiptContact">optional receipt contact to send</param> /// <returns>notify result of the notification request</returns> public Task <NotifyResult> NotifyCreateAndEndorseToken( string tokenRequestId, IList <Key> keys, DeviceMetadata deviceMetadata, ReceiptContact receiptContact) { UnauthenticatedClient unauthenticated = ClientFactory.Unauthenticated(channel); var addKey = new AddKey { DeviceMetadata = deviceMetadata }; addKey.Keys.Add(keys); return(unauthenticated.NotifyCreateAndEndorseToken( tokenRequestId, addKey, receiptContact)); }
public async Task <List <string> > DoRequest(Stream audioFile) { CancellationTokenSource cts = new CancellationTokenSource(); var preferences = new Preferences(_locale, _serviceUrl, new CognitiveServicesAuthorizationProvider(_subscriptionKey)); using (var speechClient = new SpeechClient(preferences)) { speechClient.SubscribeToRecognitionResult(this.OnRecognitionResult); 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(audioFile, requestMetadata), cts.Token).ConfigureAwait(false); } return(_lines); }
public async Task <string> RecognizeFile(Stream audio, string stsUrl, string authKey, Uri longDictationUrl) { var cts = new CancellationTokenSource(); // create the preferences object var preferences = new Preferences("en-US", longDictationUrl, new CognitiveServicesAuthorizationProvider(stsUrl, authKey)); List <RecognitionResult> results = new List <RecognitionResult>(); using (var speechClient = new SpeechClient(preferences)) { speechClient.SubscribeToRecognitionResult(async(rr) => { await Task.Run(() => { results.Add(rr); Console.WriteLine("--------------------------------------------"); Console.WriteLine($"RecognitionStatus = ${rr.RecognitionStatus}"); foreach (var p in rr.Phrases) { Console.WriteLine($" {p.Confidence} {p.DisplayText}"); } }); }); var deviceMetadata = new DeviceMetadata(DeviceType.Near, DeviceFamily.Desktop, NetworkType.Unknown, OsName.Unknown, "1607", "Azure", "Function"); var applicationMetadata = new ApplicationMetadata("ResilientLongVtt", "1.0.0"); var requestMetadata = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "SampleAppService"); await speechClient.RecognizeAsync(new SpeechInput(audio, requestMetadata), cts.Token); Console.Write($"TOTAL RESULTS : {results.Count}"); } return("rien"); }
/// <summary> /// Sends a speech recognition request to the speech service /// </summary> /// <param name="audioFile">The audio file.</param> /// <param name="locale">The locale.</param> /// <returns> /// A task /// </returns> public async Task <string> TranslateToText(string audioFile, string locale = "en-GB") { var preferences = new Preferences(locale, _serviceUrl, new CognitiveServicesAuthorizationProvider(_subscriptionKey)); // Create a a speech client using (var speechClient = new SpeechClient(preferences)) { speechClient.SubscribeToPartialResult(this.OnPartialResult); speechClient.SubscribeToRecognitionResult(this.OnRecognitionResult); try { // create an audio content and pass it a stream. using (var downloadStream = new WebClient()) using (var audio = new MemoryStream(downloadStream.DownloadData(audioFile))) { 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); } } catch (Exception e) { if (e is PlatformNotSupportedException) { return(await TranslateToTextFallback(audioFile).ConfigureAwait(false)); //fallback for when websockets are not supported } } } return(string.Empty); }
/// <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(string audioFile, string locale, Uri serviceUrl, string subscriptionKey, string episode) { // create the preferences object var preferences = new Preferences(locale, serviceUrl, new CognitiveServicesAuthorizationProvider(subscriptionKey)); string simpleFilename = Path.GetFileNameWithoutExtension(audioFile); if (int.TryParse(episode, out int outepisode)) { episodenumber = outepisode; } else { return; } htmlOutputFilePath = Path.GetDirectoryName(audioFile) + @"\" + episodenumber.ToString() + ".html"; opmlOutputFilePath = Path.GetDirectoryName(audioFile) + @"\" + episodenumber.ToString() + ".opml"; // 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(audioFile, FileMode.Open, FileAccess.Read)) { var deviceMetadata = new DeviceMetadata(DeviceType.Near, DeviceFamily.Desktop, NetworkType.Ethernet, OsName.Windows, "1607", "Dell", "T3600"); var applicationMetadata = new ApplicationMetadata("NA Transcribe", "1.0.0"); var requestMetadata = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "NATranscriptService"); await speechClient.RecognizeAsync(new SpeechInput(audio, requestMetadata), this.cts.Token).ConfigureAwait(false); } } }
private async Task <Device> GetOrCreateSensor(int deviceId) { _logger.LogDebug("Find device with id {deviceId}", deviceId); var metadata = await _sensorService.Get(deviceId); if (metadata == null) { metadata = new DeviceMetadata { DeviceId = deviceId }; _logger.LogInformation("Saving device {deviceId}", deviceId); var result = await _sensorService.Add(metadata); if (!result) { _logger.LogError("Failed saving device {deviceId}", deviceId); throw new Exception("Unable to add sensor"); } _logger.LogInformation("Device {deviceId} saved", deviceId); } var device = new Device(metadata); return(device); }
/// <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(); }