Skip to content

Commit

Permalink
Sync from internal repo (2024-04-15) (#17)
Browse files Browse the repository at this point in the history
* refactor(sdk/go): improve real-time example (#4320)

GitOrigin-RevId: c7fd146c1764cc678f1388f61a9ac81423e1b128

* feat(sdk/go): support for extra session information and disabling partial transcripts (#4417)

GitOrigin-RevId: 83135c07089fc4503e0bc5d8dba7622789664325

* Update realtime_test.go
  • Loading branch information
marcusolsson committed Apr 15, 2024
1 parent 1c156e7 commit 805fcc6
Show file tree
Hide file tree
Showing 13 changed files with 554 additions and 194 deletions.
21 changes: 15 additions & 6 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,31 @@ on:
pull_request:
branches: ["main"]

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
go: ['1.18', 'stable']
name: Go ${{ matrix.go }}
steps:
- uses: actions/checkout@v3

- name: Install PortAudio
run: sudo apt-get install -y portaudio19-dev
- uses: actions/checkout@v4

- name: Set up Go
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version: "1.18"
go-version: ${{ matrix.go }}

- name: Build
run: go build -v ./...

- name: Test
run: go test -v ./...

- name: golangci-lint
uses: golangci/golangci-lint-action@v4
with:
version: latest
15 changes: 8 additions & 7 deletions assemblyai.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

const (
version = "1.4.1"
version = "1.5.0"
defaultBaseURLScheme = "https"
defaultBaseURLHost = "api.assemblyai.com"
defaultUserAgent = "assemblyai-go/" + version
Expand Down Expand Up @@ -95,7 +95,7 @@ func WithAPIKey(key string) ClientOption {
}
}

func (c *Client) newJSONRequest(method, path string, body interface{}) (*http.Request, error) {
func (c *Client) newJSONRequest(ctx context.Context, method, path string, body interface{}) (*http.Request, error) {
var buf io.ReadWriter

if body != nil {
Expand All @@ -106,7 +106,7 @@ func (c *Client) newJSONRequest(method, path string, body interface{}) (*http.Re
}
}

req, err := c.newRequest(method, path, buf)
req, err := c.newRequest(ctx, method, path, buf)
if err != nil {
return nil, err
}
Expand All @@ -118,15 +118,15 @@ func (c *Client) newJSONRequest(method, path string, body interface{}) (*http.Re
return req, nil
}

func (c *Client) newRequest(method, path string, body io.Reader) (*http.Request, error) {
func (c *Client) newRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
rel, err := url.Parse(path)
if err != nil {
return nil, err
}

rawurl := c.baseURL.ResolveReference(rel).String()

req, err := http.NewRequest(method, rawurl, body)
req, err := http.NewRequestWithContext(ctx, method, rawurl, body)
if err != nil {
return nil, err
}
Expand All @@ -137,11 +137,12 @@ func (c *Client) newRequest(method, path string, body io.Reader) (*http.Request,
return req, err
}

func (c *Client) do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.httpClient.Do(req.WithContext(ctx))
func (c *Client) do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
var apierr APIError
Expand Down
6 changes: 4 additions & 2 deletions constants_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package assemblyai

const fakeAudioURL = "https://example.com/wildfires.mp3"
const fakeTranscriptID = "TRANSCRIPT_ID"
const (
fakeAudioURL = "https://example.com/wildfires.mp3"
fakeTranscriptID = "TRANSCRIPT_ID"
)

const (
lemurSummaryWildfires = "Wildfires in Canada are causing poor air quality and health issues in parts of the US. Weather systems are channeling smoke into the Mid-Atlantic and Northeast. The smoke contains high levels of particulate matter, microscopic particles that can harm health. Concentrations of particulate matter have reached up to 10 times the annual average and 4 times the 24-hour limit. Exposure can lead to respiratory, cardiovascular and neurological issues, especially in vulnerable groups like children, the elderly, and those with preexisting conditions. \n\nThe impacts will shift over the next few days as weather changes. The fires may continue for some time but the smoke should move away from the current affected areas. Climate change is projected to lead to longer fire seasons, more frequent fires, and more widespread air quality issues, though the Eastern US has been less affected historically."
Expand Down
4 changes: 2 additions & 2 deletions examples/realtime/go.mod
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
module github.com/AssemblyAI/DeepLearning/assemblyai/developer_tools/go/examples/realtime

go 1.18
go 1.21

require (
github.com/AssemblyAI/assemblyai-go-sdk v1.3.0
github.com/AssemblyAI/assemblyai-go-sdk v1.4.1
github.com/gordonklaus/portaudio v0.0.0-20230709114228-aafa478834f5
)

Expand Down
88 changes: 48 additions & 40 deletions examples/realtime/realtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,24 @@ package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"

"log/slog"

"github.com/AssemblyAI/assemblyai-go-sdk"
"github.com/gordonklaus/portaudio"
)

type realtimeHandler struct{}

func (h *realtimeHandler) SessionBegins(event assemblyai.SessionBegins) {
fmt.Println("session begins")
slog.Info("session begins")
}

func (h *realtimeHandler) SessionTerminated(event assemblyai.SessionTerminated) {
fmt.Println("session terminated")
slog.Info("session terminated")
}

func (h *realtimeHandler) FinalTranscript(transcript assemblyai.FinalTranscript) {
Expand All @@ -31,74 +32,81 @@ func (h *realtimeHandler) PartialTranscript(transcript assemblyai.PartialTranscr
}

func (h *realtimeHandler) Error(err error) {
fmt.Println(err)
slog.Error("Something bad happened", "err", err)
}

func main() {
logger := log.New(os.Stderr, "", log.Lshortfile)

var (
apiKey = os.Getenv("ASSEMBLYAI_API_KEY")
sigs := make(chan os.Signal, 1)

signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

// We need portaudio to record the microphone.
err := portaudio.Initialize()
checkErr(err)
defer portaudio.Terminate()

var (
// Number of samples per seconds.
sampleRate = 16000
sampleRate = 16_000

// Number of samples to send at once.
framesPerBuffer = 3200
framesPerBuffer = 3_200
)

sigs := make(chan os.Signal, 1)

signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

var h realtimeHandler

client := assemblyai.NewRealTimeClient(apiKey, &h)
apiKey := os.Getenv("ASSEMBLYAI_API_KEY")

client := assemblyai.NewRealTimeClientWithOptions(
assemblyai.WithRealTimeAPIKey(apiKey),
assemblyai.WithRealTimeSampleRate(int(sampleRate)),
assemblyai.WithHandler(&h),
)

ctx := context.Background()

if err := client.Connect(ctx); err != nil {
logger.Fatal(err)
}
err = client.Connect(ctx)
checkErr(err)

// We need portaudio to record the microphone.
portaudio.Initialize()
defer portaudio.Terminate()
slog.Info("connected to real-time API", "sample_rate", sampleRate, "frames_per_buffer", framesPerBuffer)

rec, err := newRecorder(sampleRate, framesPerBuffer)
if err != nil {
logger.Fatal(err)
}
checkErr(err)

if err := rec.Start(); err != nil {
logger.Fatal(err)
}
err = rec.Start()
checkErr(err)

for {
slog.Info("recording...")

for {
select {
case <-sigs:
fmt.Println("stopping recording...")
slog.Info("stopping recording...")

if err := rec.Stop(); err != nil {
log.Fatal(err)
}
var err error

if err := client.Disconnect(ctx, true); err != nil {
log.Fatal(err)
}
err = rec.Stop()
checkErr(err)

err = client.Disconnect(ctx, true)
checkErr(err)

os.Exit(0)
default:
b, err := rec.Read()
if err != nil {
logger.Fatal(err)
}
checkErr(err)

// Send partial audio samples.
if err := client.Send(ctx, b); err != nil {
logger.Fatal(err)
}
err = client.Send(ctx, b)
checkErr(err)
}
}
}

func checkErr(err error) {
if err != nil {
slog.Error("Something bad happened", "err", err)
os.Exit(1)
}
}

0 comments on commit 805fcc6

Please sign in to comment.