aboutsummaryrefslogtreecommitdiff
path: root/apps/web/app/lib/hooks/use-live-transcript.tsx
blob: 05c3436aaaec3c79bcbc3ec3173e10776d0b6fcd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import { useState, useEffect, useCallback } from "react";
import { useQueue } from "@uidotdev/usehooks";
import { LiveClient, LiveTranscriptionEvents, createClient } from "@deepgram/sdk";

export function useLiveTranscript() {

    const { add, remove, first, size, queue } = useQueue<any>([]);
    const [apiKey, _] = useState<string | null>("");
    const [connection, setConnection] = useState<LiveClient | null>(null);
    const [isListening, setIsListening] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [isProcessing, setIsProcessing] = useState(false);
    const [micOpen, setMicOpen] = useState(false);
    const [microphone, setMicrophone] = useState<MediaRecorder | null>(null);
    const [userMedia, setUserMedia] = useState<MediaStream | null>(null);
    const [caption, setCaption] = useState<string>("");
    const [status, setStatus] = useState<string>("Not Connected");
      // Initialize Deepgram connection
  const initializeConnection = useCallback(() => {
    if (!apiKey) return null;

    const deepgram = createClient(apiKey);
    const connection = deepgram.listen.live({
      model: "nova-3",
      language: "en",
      smart_format: true,
      interim_results: true,
      punctuate: true,
      diarize: true,
      utterances: true,
    });

    connection.on(LiveTranscriptionEvents.Open, () => {
      setStatus("Connected");
      setIsListening(true);
    });

    connection.on(LiveTranscriptionEvents.Close, () => {
      setStatus("Not Connected");
      setIsListening(false);
    });

    connection.on(LiveTranscriptionEvents.Error, (error) => {
      console.error("Deepgram error:", error);
      setStatus("Error occurred");
    });

    connection.on(LiveTranscriptionEvents.Transcript, (data) => {
      const transcript = data.channel.alternatives[0].transcript;
      if (data.is_final) {
        if (transcript && transcript.trim() !== "") {
          setCaption((prev) => prev + " " + transcript);
        }
      }
    });

    return connection;
  }, [apiKey]);

  const toggleMicrophone = useCallback(async () => {
    if (microphone && userMedia) {
      setUserMedia(null);
      setMicrophone(null);
      microphone.stop();
      if (connection) {
        connection.finish();
        setConnection(null);
      }
    } else {
      const userMedia = await navigator.mediaDevices.getUserMedia({
        audio: true,
      });

      const microphone = new MediaRecorder(userMedia);
      microphone.start(250);

      microphone.onstart = () => {
        setMicOpen(true);
        // Create new connection when starting microphone
        const newConnection = initializeConnection();
        if (newConnection) {
          setConnection(newConnection);
        }
      };

      microphone.onstop = () => {
        setMicOpen(false);
      };

      microphone.ondataavailable = (e) => {
        add(e.data);
      };

      setUserMedia(userMedia);
      setMicrophone(microphone);
    }
  }, [add, microphone, userMedia, connection, initializeConnection]);

  useEffect(() => {
    setIsLoading(false);
  }, []);

  useEffect(() => {
    const processQueue = async () => {
      if (size > 0 && !isProcessing && isListening && connection) {
        setIsProcessing(true);
        try {
          const blob = first;
          if (blob) {
            connection.send(blob);
          }
          remove();
        } catch (error) {
          console.error("Error processing audio:", error);
        }
        setIsProcessing(false);
      }
    };

    const interval = setInterval(processQueue, 100);
    return () => clearInterval(interval);
  }, [connection, queue, remove, first, size, isProcessing, isListening]);

  return {
    toggleMicrophone,
    caption,
    status,
    isListening,
    isLoading,
  };
}