Skip to content

Commit

Permalink
chore: mergy merge
Browse files Browse the repository at this point in the history
  • Loading branch information
naomi-lgbt committed Sep 16, 2024
2 parents 54c9085 + 630387d commit b6669ea
Show file tree
Hide file tree
Showing 19 changed files with 347 additions and 14 deletions.
20 changes: 16 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"@flydotio/dockerfile": "^0.4.10",
"@types/chai": "^4.3.5",
"@types/mocha": "^9.1.1",
"@types/node": "^18.19.39",
"@types/sinon": "^17.0.3",
"@types/ws": "^8.5.10",
"chai": "^4.3.7",
Expand Down
10 changes: 10 additions & 0 deletions src/DeepgramClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
OnPremClient,
SelfHostedRestClient,
SpeakClient,
ModelsRestClient,
} from "./packages";

/**
Expand All @@ -33,6 +34,15 @@ export default class DeepgramClient extends AbstractClient {
return new ManageClient(this.options);
}

/**
* Returns a new instance of the ModelsRestClient, which provides access to the Deepgram API's model functionality.
*
* @returns {ModelsRestClient} A new instance of the ModelsRestClient.
*/
get models(): ModelsRestClient {
return new ModelsRestClient(this.options);
}

/**
* Returns a new instance of the SelfHostedRestClient, which provides access to the Deepgram API's self-hosted functionality.
*
Expand Down
23 changes: 19 additions & 4 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { convertProtocolToWs, isBrowser } from "./helpers";
import { convertProtocolToWs, isBrowser, isBun, isNode } from "./helpers";
import { version } from "./version";
import type { DefaultNamespaceOptions, DefaultClientOptions } from "./types";

Expand All @@ -7,17 +7,32 @@ export const NODE_VERSION =
? process.versions.node
: "unknown";

export const BUN_VERSION =
typeof process !== "undefined" && process.versions && process.versions.bun
? process.versions.bun
: "unknown";

export const BROWSER_AGENT =
typeof window !== "undefined" && window.navigator && window.navigator.userAgent
? window.navigator.userAgent
: "unknown";

const getAgent = () => {
if (isNode()) {
return `node/${NODE_VERSION}`;
} else if (isBun()) {
return `bun/${BUN_VERSION}`;
} else if (isBrowser()) {
return `javascript ${BROWSER_AGENT}`;
} else {
return `unknown`;
}
};

export const DEFAULT_HEADERS = {
"Content-Type": `application/json`,
"X-Client-Info": `@deepgram/sdk; ${isBrowser() ? "browser" : "server"}; v${version}`,
"User-Agent": `@deepgram/sdk/${version} ${
isBrowser() ? `javascript ${BROWSER_AGENT}` : `node/${NODE_VERSION}`
}`,
"User-Agent": `@deepgram/sdk/${version} ${getAgent()}`,
};

export const DEFAULT_URL = "https://api.deepgram.com";
Expand Down
9 changes: 6 additions & 3 deletions src/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ import {
import { Headers as CrossFetchHeaders } from "cross-fetch";
import { Readable } from "stream";
import merge from "deepmerge";
import { BROWSER_AGENT, BUN_VERSION, NODE_VERSION } from "./constants";

export function stripTrailingSlash(url: string): string {
return url.replace(/\/$/, "");
}

export function isBrowser() {
return typeof window !== "undefined" && typeof window.document !== "undefined";
}
export const isBrowser = () => BROWSER_AGENT !== "unknown";

export const isNode = () => NODE_VERSION !== "unknown";

export const isBun = () => BUN_VERSION !== "unknown";

export function applyDefaults<O, S>(options: Partial<O> = {}, subordinate: Partial<S> = {}): S {
return merge(subordinate, options);
Expand Down
24 changes: 24 additions & 0 deletions src/lib/types/GetModelsResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
type Model = {
name: string;
canonical_name: string;
architecture: string;
languages?: string[];
version: string;
uuid: string;
batch?: boolean;
streaming?: boolean;
formatted_output?: boolean;
metadata?: {
accent: string;
color: string;
image: string;
sample: string;
};
};

export type GetModelResponse = Model;

export type GetModelsResponse = {
stt: Model[];
tts: Model[];
};
3 changes: 3 additions & 0 deletions src/lib/types/GetModelsSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface GetModelsSchema extends Record<string, unknown> {
include_outdated?: boolean;
}
2 changes: 2 additions & 0 deletions src/lib/types/LiveTranscriptionEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ export interface LiveTranscriptionEvent {
alternatives: {
transcript: string;
confidence: number;
languages: string[];
words: {
word: string;
start: number;
end: number;
confidence: number;
language: string;
punctuated_word: string;
}[];
}[];
Expand Down
2 changes: 2 additions & 0 deletions src/lib/types/SyncPrerecordedResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ interface Alternative {
entities?: Entity[];
translations?: Translation[];
topics?: TopicGroup[];
languages?: string[];
}

interface Channel {
Expand Down Expand Up @@ -208,4 +209,5 @@ interface WordBase {
punctuated_word?: string;
speaker?: number;
speaker_confidence?: number;
language?: string;
}
7 changes: 6 additions & 1 deletion src/lib/types/TranscriptionSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ interface PrerecordedSchema extends TranscriptionSchema {
/**
* @see https://developers.deepgram.com/docs/language-detection
*/
detect_language?: boolean;
detect_language?: boolean | string[];

/**
* @see https://developers.deepgram.com/docs/topic-detection
Expand Down Expand Up @@ -222,6 +222,11 @@ interface LiveSchema extends TranscriptionSchema {
*/
interim_results?: boolean;

/**
* @see https://developers.deepgram.com/docs/smart-format#using-no-delay
*/
no_delay?: boolean;

/**
* @see https://developers.deepgram.com/docs/understanding-end-of-speech-detection
*/
Expand Down
2 changes: 2 additions & 0 deletions src/lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ export * from "./DeepgramClientOptions";
export * from "./DeepgramResponse";
export * from "./DeepgramSource";
export * from "./Fetch";
export * from "./GetModelsResponse";
export * from "./GetModelsSchema";
export * from "./GetProjectBalancesResponse";
export * from "./GetProjectInvitesResponse";
export * from "./GetProjectKeysResponse";
Expand Down
2 changes: 1 addition & 1 deletion src/packages/AbstractClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import EventEmitter from "events";
import { EventEmitter } from "events";
import { DEFAULT_OPTIONS, DEFAULT_URL } from "../lib/constants";
import { DeepgramError } from "../lib/errors";
import { appendSearchParams, applyDefaults, convertLegacyOptions } from "../lib/helpers";
Expand Down
18 changes: 18 additions & 0 deletions src/packages/AbstractLiveClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { AbstractClient, noop } from "./AbstractClient";
import { CONNECTION_STATE, SOCKET_STATES } from "../lib/constants";
import type { DeepgramClientOptions, LiveSchema } from "../lib/types";
import type { WebSocket as WSWebSocket } from "ws";
import { isBun } from "../lib/helpers";

/**
* Represents a constructor for a WebSocket-like object that can be used in the application.
Expand Down Expand Up @@ -119,6 +120,23 @@ export abstract class AbstractLiveClient extends AbstractClient {
return;
}

/**
* @summary Bun websocket transport has a bug where it's native WebSocket implementation messes up the headers
* @summary This is a workaround to use the WS package for the websocket connection instead of the native Bun WebSocket
* @summary you can track the issue here
* @link https://github.com/oven-sh/bun/issues/4529
*/
if (isBun()) {
import("ws").then(({ default: WS }) => {
this.conn = new WS(requestUrl, {
headers: this.headers,
});
console.log(`Using WS package`);
this.setupConnection();
});
return;
}

/**
* Native websocket transport (browser)
*/
Expand Down
13 changes: 12 additions & 1 deletion src/packages/ListenLiveClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,18 @@ export class ListenLiveClient extends AbstractLiveClient {
}

/**
* @deprecated Since version 3.4. Will be removed in version 4.0. Use `close` instead.
* Sends a "Finalize" message to flush any transcription sitting in the server's buffer.
*/
public finalize(): void {
this.send(
JSON.stringify({
type: "Finalize",
})
);
}

/**
* @deprecated Since version 3.4. Will be removed in version 4.0. Use `requestClose` instead.
*/
public finish(): void {
this.requestClose();
Expand Down
82 changes: 82 additions & 0 deletions src/packages/ManageRestClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ import type {
UpdateProjectSchema,
VoidResponse,
GetTokenDetailsResponse,
GetModelsResponse,
GetModelResponse,
GetModelsSchema,
} from "../lib/types";
import { AbstractRestClient } from "./AbstractRestClient";

Expand Down Expand Up @@ -755,6 +758,85 @@ export class ManageRestClient extends AbstractRestClient {
throw error;
}
}

/**
* Retrieves all models for a given project.
*
* @param projectId - The ID of the project.
* @param endpoint - (optional) The endpoint URL for retrieving models. Defaults to ":version/projects/:projectId/models".
* @returns A promise that resolves to a DeepgramResponse containing the GetModelsResponse.
* @example
* ```typescript
* import { createClient } from "@deepgram/sdk";
*
* const deepgram = createClient(DEEPGRAM_API_KEY);
* const { result: models, error } = deepgram.manage.getAllModels("projectId");
*
* if (error) {
* console.error(error);
* } else {
* console.log(models);
* }
* ```
*/
async getAllModels(
projectId: string,
options: GetModelsSchema = {},
endpoint = ":version/projects/:projectId/models"
): Promise<DeepgramResponse<GetModelsResponse>> {
try {
const requestUrl = this.getRequestUrl(endpoint, { projectId }, options);
const result: GetModelsResponse = await this.get(requestUrl).then((result) => result.json());

return { result, error: null };
} catch (error) {
if (isDeepgramError(error)) {
return { result: null, error };
}

throw error;
}
}

/**
* Retrieves a model from the specified project.
*
* @param projectId - The ID of the project.
* @param modelId - The ID of the model.
* @param endpoint - (optional) The endpoint URL for the request. Default value is ":version/projects/:projectId/models/:modelId".
* @returns A promise that resolves to a DeepgramResponse containing the GetModelResponse.
* @example
* ```typescript
* import { createClient } from "@deepgram/sdk";
*
* const deepgram = createClient(DEEPGRAM_API_KEY);
* const { result: model, error } = deepgram.models.getModel("projectId", "modelId");
*
* if (error) {
* console.error(error);
* } else {
* console.log(model);
* }
* ```
*/
async getModel(
projectId: string,
modelId: string,
endpoint = ":version/projects/:projectId/models/:modelId"
): Promise<DeepgramResponse<GetModelResponse>> {
try {
const requestUrl = this.getRequestUrl(endpoint, { projectId, modelId });
const result: GetModelResponse = await this.get(requestUrl).then((result) => result.json());

return { result, error: null };
} catch (error) {
if (isDeepgramError(error)) {
return { result: null, error };
}

throw error;
}
}
}

export { ManageRestClient as ManageClient };
Loading

0 comments on commit b6669ea

Please sign in to comment.