Skip to content
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
6 changes: 6 additions & 0 deletions .changeset/clean-toes-melt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@livekit/components-core": patch
"@livekit/components-react": patch
---

Add useTranscription hook
1 change: 1 addition & 0 deletions packages/core/etc/components-core.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ export const cssPrefix = "lk";
// @public (undocumented)
export const DataTopic: {
readonly CHAT: "lk.chat";
readonly TRANSCRIPTION: "lk.transcription";
};

// @public (undocumented)
Expand Down
13 changes: 9 additions & 4 deletions packages/core/src/components/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
sendMessage,
setupDataMessageHandler,
} from '../observables/dataChannel';
import { log } from '../logger';

/** @public */
export type { ChatMessage };
Expand Down Expand Up @@ -165,10 +166,14 @@ export function setupChat(room: Room, options?: ChatOptions) {
...chatMsg,
ignoreLegacy: serverSupportsDataStreams(),
});
await sendMessage(room.localParticipant, encodedLegacyMsg, {
reliable: true,
topic: legacyTopic,
});
try {
await sendMessage(room.localParticipant, encodedLegacyMsg, {
reliable: true,
topic: legacyTopic,
});
} catch (error) {
log.info('could not send message in legacy chat format', error);
}
return chatMsg;
} finally {
isSending$.next(false);
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/components/textStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export function setupTextStream(room: Room, topic: string): Observable<TextStrea

// Add cleanup when room is disconnected
room.once(RoomEvent.Disconnected, () => {
room.unregisterTextStreamHandler(topic);
textStreamsSubject.complete();
getObservableCache().delete(cacheKey);
});
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/observables/dataChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ReceivedChatMessage } from '../components/chat';

export const DataTopic = {
CHAT: 'lk.chat',
TRANSCRIPTION: 'lk.transcription',
} as const;

/** @deprecated */
Expand Down
11 changes: 11 additions & 0 deletions packages/react/etc/components-react.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,17 @@ export function useTrackTranscription(trackRef: TrackReferenceOrPlaceholder_4 |
// @alpha
export function useTrackVolume(trackOrTrackReference?: LocalAudioTrack | RemoteAudioTrack | TrackReference_3, options?: AudioAnalyserOptions): number;

// @beta
export function useTranscriptions(opts?: UseTranscriptionsOptions): TextStreamData_2[];

// @beta (undocumented)
export interface UseTranscriptionsOptions {
// (undocumented)
participantIdentities?: string[];
// (undocumented)
trackSids?: string[];
}

// @public
export function useVisualStableUpdate(
trackReferences: TrackReferenceOrPlaceholder_4[], maxItemsOnPage: number, options?: UseVisualStableUpdateOptions): TrackReferenceOrPlaceholder_4[];
Expand Down
1 change: 1 addition & 0 deletions packages/react/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,4 @@ export * from './useVoiceAssistant';
export * from './useParticipantAttributes';
export * from './useIsRecording';
export * from './useTextStream';
export * from './useTranscriptions';
22 changes: 2 additions & 20 deletions packages/react/src/hooks/useTrackTranscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const TRACK_TRANSCRIPTION_DEFAULTS = {
} as const satisfies TrackTranscriptionOptions;

/**
* @returns An object consisting of `segments` with maximum length of opts.windowLength and `activeSegments` that are valid for the current track timestamp
* @returns An object consisting of `segments` with maximum length of opts.bufferSize
* @alpha
*/
export function useTrackTranscription(
Expand All @@ -44,10 +44,7 @@ export function useTrackTranscription(
) {
const opts = { ...TRACK_TRANSCRIPTION_DEFAULTS, ...options };
const [segments, setSegments] = React.useState<Array<ReceivedTranscriptionSegment>>([]);
// const [activeSegments, setActiveSegments] = React.useState<Array<ReceivedTranscriptionSegment>>(
// [],
// );
// const prevActiveSegments = React.useRef<ReceivedTranscriptionSegment[]>([]);

const syncTimestamps = useTrackSyncTime(trackRef);
const handleSegmentMessage = (newSegments: TranscriptionSegment[]) => {
opts.onTranscription?.(newSegments);
Expand All @@ -72,20 +69,5 @@ export function useTrackTranscription(
};
}, [trackRef && getTrackReferenceId(trackRef), handleSegmentMessage]);

// React.useEffect(() => {
// if (syncTimestamps) {
// const newActiveSegments = getActiveTranscriptionSegments(
// segments,
// syncTimestamps,
// opts.maxAge,
// );
// // only update active segment array if content actually changed
// if (didActiveSegmentsChange(prevActiveSegments.current, newActiveSegments)) {
// setActiveSegments(newActiveSegments);
// prevActiveSegments.current = newActiveSegments;
// }
// }
// }, [syncTimestamps, segments, opts.maxAge]);

return { segments };
}
44 changes: 44 additions & 0 deletions packages/react/src/hooks/useTranscriptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import * as React from 'react';
import { useTextStream } from './useTextStream';
import { DataTopic } from '@livekit/components-core';

/**
* @beta
*/
export interface UseTranscriptionsOptions {
participantIdentities?: string[];
trackSids?: string[];
}

/**
* @beta
* useTranscriptions is a hook that returns the transcriptions for the given participant identities and track sids,
* if no options are provided, it will return all transcriptions
* @example
* ```tsx
* const transcriptions = useTranscriptions();
* return <div>{transcriptions.map((transcription) => transcription.text)}</div>;
* ```
*/
export function useTranscriptions(opts?: UseTranscriptionsOptions) {
const { participantIdentities, trackSids } = opts ?? {};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doesn't adding these options expose an easy trap where you have

const agentTranscriptions = useTranscriptions({ participantIdentities: ['agent'] });

and

const userTranscriptions = useTranscriptions({ participantIdentities: ['user'] });

in two different locations and then they conflict on useTextStream which can only be used once?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the components implementation creates a registered handler cache that makes it possible to reuse streams across the app without running into that limitation

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah ok that works. i do still think we should just make it easy for anyone to register multiple handlers but it's not a blocker to this PR

const { textStreams } = useTextStream(DataTopic.TRANSCRIPTION);

const filteredMessages = React.useMemo(
() =>
textStreams
.filter((stream) =>
participantIdentities
? participantIdentities.includes(stream.participantInfo.identity)
: true,
)
.filter((stream) =>
trackSids
? trackSids.includes(stream.streamInfo.attributes?.['lk.transcribed_track_id'] ?? '')
: true,
),
[textStreams, participantIdentities, trackSids],
);

return filteredMessages;
}