Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Subscribe Interface to Live Client #259

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 116 additions & 39 deletions Deepgram/Clients/Live/v1/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Use of this source code is governed by a MIT license that can be found in the LICENSE file.
// SPDX-License-Identifier: MIT

using System.Threading;
using Deepgram.Models.Authenticate.v1;
using Deepgram.Models.Live.v1;

Expand All @@ -17,6 +18,7 @@ public class Client : Attribute, IDisposable

private ClientWebSocket? _clientWebSocket;
private CancellationTokenSource? _cancellationTokenSource;
private readonly Mutex _mutex = new Mutex();
#endregion

/// <param name="apiKey">Required DeepgramApiKey</param>
Expand All @@ -35,18 +37,18 @@ public Client(string? apiKey = null, DeepgramWsClientOptions? options = null)
Log.Verbose("LiveClient", "LEAVE");
}

#region Subscribe Events
#region Event Handlers
/// <summary>
/// Fires when an event is received from the Deepgram API
/// </summary>
public event EventHandler<OpenResponse>? _openReceived;
public event EventHandler<MetadataResponse>? _metadataReceived;
public event EventHandler<ResultResponse>? _resultsReceived;
public event EventHandler<UtteranceEndResponse>? _utteranceEndReceived;
public event EventHandler<SpeechStartedResponse>? _speechStartedReceived;
public event EventHandler<CloseResponse>? _closeReceived;
public event EventHandler<UnhandledResponse>? _unhandledReceived;
public event EventHandler<ErrorResponse>? _errorReceived;
private event EventHandler<OpenResponse>? _openReceived;
private event EventHandler<MetadataResponse>? _metadataReceived;
private event EventHandler<ResultResponse>? _resultsReceived;
private event EventHandler<UtteranceEndResponse>? _utteranceEndReceived;
private event EventHandler<SpeechStartedResponse>? _speechStartedReceived;
private event EventHandler<CloseResponse>? _closeReceived;
private event EventHandler<UnhandledResponse>? _unhandledReceived;
private event EventHandler<ErrorResponse>? _errorReceived;
#endregion

/// <summary>
Expand Down Expand Up @@ -161,36 +163,111 @@ void StartKeepAliveBackgroundThread() => _ = Task.Factory.StartNew(
Log.Verbose("LiveClient.Connect", "LEAVE");
}

//// TODO: convienence method for subscribing to events
//public void On<T>(T e, EventHandler<T> eventHandler) {
// switch (e)
// {
// case OpenResponse open:
// OpenReceived += (sender, e) => eventHandler;
// break;
// case MetadataResponse metadata:
// MetadataReceived += (sender, e) => eventHandler;
// break;
// case ResultResponse result:
// ResultsReceived += (sender, e) => eventHandler;
// break;
// case UtteranceEndResponse utteranceEnd:
// UtteranceEndReceived += (sender, e) => eventHandler;
// break;
// case SpeechStartedResponse speechStarted:
// SpeechStartedReceived += (sender, e) => eventHandler;
// break;
// case CloseResponse close:
// CloseReceived += (sender, e) => eventHandler;
// break;
// case UnhandledResponse unhandled:
// UnhandledReceived += (sender, e) => eventHandler;
// break;
// case ErrorResponse error:
// ErrorReceived += (sender, e) => eventHandler;
// break;
// }
//}
#region Subscribe Event
/// <summary>
/// Subscribe to an Open event from the Deepgram API
/// </summary>
/// <param name="eventHandler"></param>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<OpenResponse> eventHandler)
{
lock (_mutex)
{
_openReceived += (sender, e) => eventHandler(sender, e);
}

return true;
}

/// <summary>
/// Subscribe to a Metadata event from the Deepgram API
/// </summary>
/// <param name="eventHandler"></param>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<MetadataResponse> eventHandler)
{
lock (_mutex)
{
_metadataReceived += (sender, e) => eventHandler(sender, e);
}
return true;
}

/// <summary>
/// Subscribe to a Results event from the Deepgram API
/// </summary>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<ResultResponse> eventHandler)
{
lock (_mutex)
{
_resultsReceived += (sender, e) => eventHandler(sender, e);
}
return true;
}

/// <summary>
/// Subscribe to an UtteranceEnd event from the Deepgram API
/// </summary>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<UtteranceEndResponse> eventHandler)
{
lock (_mutex)
{
_utteranceEndReceived += (sender, e) => eventHandler(sender, e);
}
return true;
}

/// <summary>
/// Subscribe to a SpeechStarted event from the Deepgram API
/// </summary>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<SpeechStartedResponse> eventHandler)
{
_speechStartedReceived += (sender, e) => eventHandler(sender, e);
return true;
}

/// <summary>
/// Subscribe to a Close event from the Deepgram API
/// </summary>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<CloseResponse> eventHandler)
{
lock (_mutex)
{
_closeReceived += (sender, e) => eventHandler(sender, e);
}
return true;
}

/// <summary>
/// Subscribe to an Unhandled event from the Deepgram API
/// </summary>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<UnhandledResponse> eventHandler)
{
lock (_mutex)
{
_unhandledReceived += (sender, e) => eventHandler(sender, e);
}
return true;
}

/// <summary>
/// Subscribe to an Error event from the Deepgram API
/// </summary>
/// <returns>True if successful</returns>
public bool Subscribe(EventHandler<ErrorResponse> eventHandler)
{
lock (_mutex)
{
_errorReceived += (sender, e) => eventHandler(sender, e);
}
return true;
}
#endregion

/// <summary>
/// Sends a binary message over the WebSocket connection.
Expand Down
1 change: 1 addition & 0 deletions Deepgram/LiveClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using Deepgram.Clients.Live.v1;
using Deepgram.Models.Authenticate.v1;
using Deepgram.Models.Live.v1;

namespace Deepgram;

Expand Down
16 changes: 0 additions & 16 deletions clean-up.ps1

This file was deleted.

12 changes: 3 additions & 9 deletions clean-up.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,7 @@ set -o xtrace

rm -rf ./.vs
rm -rf ./dist
rm -rf ./Deepgram/obj
rm -rf ./Deepgram/bin

# Deepgram.Tests
rm -rf ./Deepgram.Tests/bin
rm -rf ./Deepgram.Tests/obj

# Deepgram.Microphone
rm -rf ./Deepgram.Microphone/bin
rm -rf ./Deepgram.Microphone/obj
# delete all compile actifacts
find ./ -type d -iname obj -print0 | xargs -0 rm -rf
find ./ -type d -iname bin -print0 | xargs -0 rm -rf
22 changes: 22 additions & 0 deletions examples/manage/balances/Manage.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\Deepgram\Deepgram.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="Deepgram" />
</ItemGroup>

</Project>
79 changes: 79 additions & 0 deletions examples/manage/balances/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2024 Deepgram .NET SDK contributors. All Rights Reserved.
// Use of this source code is governed by a MIT license that can be found in the LICENSE file.
// SPDX-License-Identifier: MIT

using System.Text.Json;

using Deepgram.Logger;
using Deepgram.Models.Manage.v1;

namespace SampleApp
{
class Program
{
static async Task Main(string[] args)
{
// Initialize Library with default logging
// Normal logging is "Info" level
Library.Initialize();
// OR very chatty logging
//Library.Initialize(LogLevel.Debug); // LogLevel.Default, LogLevel.Debug, LogLevel.Verbose

// Set "DEEPGRAM_API_KEY" environment variable to your Deepgram API Key
var deepgramClient = new ManageClient();

var response = await deepgramClient.GetProjects();
if (response == null)
{
Console.WriteLine("No projects found.");
return;
}

Console.WriteLine(JsonSerializer.Serialize(response));

//var projectId = "";
//foreach (var project in response.Projects)
//{
// Console.WriteLine($"Project ID: {project.ProjectId}");
// projectId = project.ProjectId;
// break;
//}

//var balanacesResponse = deepgramClient.GetBalances(projectId);
//if (balanacesResponse == null || balanacesResponse.Balances == null)
//{
// Console.WriteLine("No balance found.");
// return;
//}

//Console.WriteLine("\n\nBalances:");
//Console.WriteLine(JsonSerializer.Serialize(balanacesResponse));
//Console.WriteLine("\n\n");

//string balanceId = "";
//foreach (var balance in balanacesResponse.Balances)
//{
// Console.WriteLine($"Balance ID: {balance.BalanceId}");
// balanceId = balance.BalanceId;
// break;
//}

//var balanaceResponse = deepgramClient.GetBalance(projectId, balanceId);
//if (balanaceResponse == null)
//{
// Console.WriteLine("No balance found.");
// return;
//}

//Console.WriteLine("\n\nBalances:");
//Console.WriteLine(JsonSerializer.Serialize(balanacesResponse));
//Console.WriteLine("\n\n");

Console.WriteLine("Press any key to exit.");
Console.ReadKey();

// Teardown Library
Library.Terminate();
}
}
}
8 changes: 4 additions & 4 deletions examples/streaming/file/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ static async Task Main(string[] args)
var liveClient = new LiveClient();

// Subscribe to the EventResponseReceived event
liveClient._resultsReceived += (sender, e) =>
liveClient.Subscribe(new EventHandler<ResultResponse>((sender, e) =>
{
if (e.Channel.Alternatives[0].Transcript == "")
{
return;
}

// Console.WriteLine("Transcription received: " + JsonSerializer.Serialize(e.Response.Transcription));
Console.WriteLine($"Speaker: {e.Channel.Alternatives[0].Transcript}");
};
// Console.WriteLine("Transcription received: " + JsonSerializer.Serialize(e.Transcription));
Console.WriteLine($"\n\n\n----> Speaker: {e.Channel.Alternatives[0].Transcript}\n\n\n");
}));

// Start the connection
var liveSchema = new LiveSchema()
Expand Down
Loading
Loading