aboutsummaryrefslogtreecommitdiff
path: root/scripts/ow-dictate.sh
blob: db7e9e449cdbeab144e71367556e110fa11a4d6e (plain)
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
#!/bin/bash
# ~/.mycfg/scripts/ow-dictate.sh — OpenAI Whisper API version

PIDFILE="/tmp/dictate.pid"
AUDIO="/tmp/dictate.wav"
NOTIFFILE="/tmp/dictate.notif_id"

NID=""
[ -f "$NOTIFFILE" ] && NID=$(cat "$NOTIFFILE")
notify() {
    local args=()
    [ -n "$NID" ] && args+=(-r "$NID")
    NID=$(notify-send -p "${args[@]}" "$@")
    echo "$NID" > "$NOTIFFILE"
}

if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
    # ── STOP recording, send to API, type ──
    kill "$(cat "$PIDFILE")"
    rm "$PIDFILE"

    notify -t 2000 "Dictation" "Sending to OpenAI..."

    API_KEY=$(pass show openai.com/api.openai.com/apikey)

    RESPONSE=$(curl -s https://api.openai.com/v1/audio/transcriptions \
        -H "Authorization: Bearer $API_KEY" \
        -F "file=@$AUDIO" \
        -F "model=whisper-1" \
        -F "language=en" \
        -F "response_format=json")

    TEXT=$(echo "$RESPONSE" | jq -r '.text // empty')

    if [ -n "$TEXT" ]; then
        xdotool type --clearmodifiers -- "$TEXT"
        notify -t 1000 "Dictation" "Done"
    else
        ERROR=$(echo "$RESPONSE" | jq -r '.error.message // "Unknown error"')
        notify -t 3000 "Dictation" "Failed: $ERROR"
    fi

    rm -f "$AUDIO"
else
    # ── START recording ──
    notify -t 0 -u low "Dictation" "Recording..."

    arecord -f S16_LE -r 16000 -c 1 -t wav "$AUDIO" &
    echo $! > "$PIDFILE"
fi