Repository navigation
Expand file tree
/
Copy pathblahstbot
More file actions
252 lines (237 loc) · 11.4 KB
/
Copy pathblahstbot
File metadata and controls
252 lines (237 loc) · 11.4 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/zsh
# Due to advanced parsing requirements for some new features, bash in not supported in new versions of the script.
# Copyright (c) 2025 Quantius Benignus
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#-------------------------------------------------------------------------------------------
# NAME: blahstbot
# PREREQUSITES:
# - zsh shell installation
# - whisper.cpp installed (https://github.com/ggerganov/whisper.cpp) or a whisperfile
# - recent versions of 'sox', 'curl', 'xsel' or 'wl-copy' CLI tools.
# - llama.cpp or llamafile (and models) for AI chatbot functionality.
# - xdotool (X11) or ydotool (Wayland) for automatic paste after successful transcription
# - Piper neural text-to-speech engine for spoken AI assistant response
#-------------------------------------------------------------------------------------------
# Are we already running this? (prevent multiple hotkey presses)
pidof -q blahstbot && exit 0
#---USER CONFIGURATION BLOCK----------------------------------------------------------------
#The main configuration for this and all other BlahST tools is now in blahst.cfg, please, edit that file as needed.
source $HOME/.local/bin/blahst.cfg
#Local overrides:
CHATMODE=1 #temp reuse as flag variable, untill we support llamafiles.
AUTOPASTE=0
#---END USER CONFIG BLOCK-------------------------------------------------------------------
#---CHECK DEPENDENCIES.-----Run blahst_depends only if needed or requested----------
(( $blahst_deps )) || blahst_depends
#---END CHECK DEPENDENCIES.-----------------------------------------------------------------
#Hear the complaints of components and do not continue with the sequence:
set -e
set -o pipefail
clipaste() {
local str="$1"
#xsel or wl-copy:
case "$wm" in
"x11")
if (( $PRIMESEL )); then
echo $str | xsel -ip
# Simply clicking the middle mouse button. The user has to take care of: 1. Window choice. 2. Position within window.
# Thus, autopaste from the primary selection is more unpredictable and requires extra care of window focus and mouse pointer repositioning.
if (( $AUTOPASTE )); then xdotool click 2 ; fi
else
echo $str | xsel -ib
# The automatic paste option makes more sense when using the CLIPBOARD, not primary sellection.
if (( $AUTOPASTE )); then xdotool key ctrl+v ; fi
fi
;;
"wayland")
if (( $PRIMESEL )); then
echo $str | wl-copy -p
# Simply clicking the middle mouse button. The user has to take care of: 1. Window choice. 2. Position within window.
# Thus, autopaste from the primary selection is more unpredictable and requires extra care of window focus and mouse pointer repositioning.
if (( $AUTOPASTE )); then ydotool click 0xC2; fi
else
echo $str | wl-copy
# The key sym sequence may differ from the one below on a variety of systems and keyboard layouts:
if (( $AUTOPASTE )); then ydotool key 37:1 55:1 55:0 37:0 ; fi
fi
;;
*)
echo $str
;;
esac
}
tts_play() {
local text="$1"
local lc="$2"
local model="$TTSMODEL"
local rate="$rtts"
if [[ $# -eq 2 ]]; then
if [[ -n "${TTSM[$lc]}" ]]; then
local model="$PPRMDIR/${TTSM[$lc]}"
local rate="$modrate[$lc]"
else
[[ ${#lc} -gt 2 ]] || text="Warning. A text-to-speech model is not available for this language."
fi
fi
{
piper --model "$model" --output-raw <<< "$text" 2>/dev/null | \
aplay -r "$rate" -f S16_LE -t raw - 2>/dev/null
}
}
# Process command line arguments
while [ $# -gt 0 ]; do
case "$1" in
-p|--primary)
PRIMESEL=1
shift
;;
-w|--whisperfile)
whf="$WHISPERFILE"
shift
;;
-a|--llamafile)
llamf="$LLAMAFILE --cli"
CHATMODE=0 #var reuse
shift
;;
-n|--netapi)
#This uses the hostname or IP and port specified in the config block
#Can be overwritten, supplied as command line argument IP:PORT instead of this option
IPnPORT="$WHOST:$WPORT"
if [[ "$(curl -s -f -o /dev/null -w '%{http_code}' $IPnPORT)" != "200" ]]; then
#echo "Can't connect to whisper.cpp server at provided address!" >&2
#Uncomment the next line if you want to have the server start locally on a call (assuming whserver symlink is set).
pidof whserver > /dev/null 2>&1 || { whserver --host $WHOST --port $WPORT -t $NTHR -nt -fa -sns -m $WMODEL 2>/dev/null & }
desknote "No connection to whisper.cpp server" "Starting server at $IPnPORT now, please, press OK..."
fi
shift
;;
-h|--help)
echo -e "Have a spoken conversation with your Linux computer. Now with the ability to append a mouse-selected text to any spoken question/statement."
echo -e "\nUsage: $0 [-p|--primary] [-n|--netapi] [-w|--whisperfile] [-l|--llamafile]\n"
echo -e " -p, --primary: Use PRIMARY selection instead of clipboard\n"
echo -e " -n, --netapi: Use whisper.cpp/llama.cpp servers with the host:port in the blahst.cfg GONFIG block\n"
echo -e " -w, --whisperfile: Use whisperfile instead of standalone whisper.cpp. Note that the whisperfile will use the script-configured (not embedded) model.\n"
echo -e " -a, --llamafile: Use llamafile instead of standalone llama.cpp. Note that the llamafile will use the script-configured (not embedded) LLM model.\n"
echo -e "Any other non-flag command-line argument is expected to be an <IP:port> pair. Error will occur if diferent."
echo -e "\nPlease, adjust blahstbot configuration (LLM model, LLM options, prompt, TTS, etc. ) in blahst.cfg"
echo -e "\nThe AI functions are experimental and work in progress. Here is the currently selected PROMPT exposing some of blahstbot's AI functions (using zsh):"
echo -e "\n$BMPROMPT"
echo -e "To reset the context simply say 'Reset Context' and the previous conversation will be cleared, which will speed up inference."
echo -e "\nCAUTION: Transfering any AI-generated Linux commands to your command line is at your own risk. Make sure you know what you are doing."
exit 0
;;
*)
#The network address and port should have already been sanitized
IPnPORT=$1
if [[ "$(curl -s -f -o /dev/null -w '%{http_code}' $IPnPORT)" != "200" ]]; then
#echo "Can't connect to whisper.cpp server at provided address!" >&2
#Uncomment the next line if you want to have the server start locally on a call (assuming whserver symlink is set).
pidof whserver > /dev/null 2>&1 || { whserver --host $WHOST --port $WPORT -t $NTHR -nt -fa -sns -m $WMODEL 2>/dev/null & }
desknote "No connection to whisper.cpp server" "Starting server at $IPnPORT now, please, press OK..."
fi
shift
;;
esac
done
#Initialize llama-server:
(( CHATMODE )) && {
if [[ "$(curl -s -f -o /dev/null -w '%{http_code}' $LHOST:$LPORT/health)" != "200" ]]; then
pidof llamserver > /dev/null 2>&1 || { llamserver --host $LHOST --port $LPORT -t $NTHR -m $BOTMODEL ${(z)BMOPTIONS} 2>/dev/null & }
#desknote "No connection to llama.cpp server" "Starting server at $LHOST:$LPORT now, please, press OK..."
select_role
touch $TEMPD/chatfile
pidof llamserver > /dev/null 2>&1 && { tts_play $BOTGREETING; }
fi ;
}
#echo "Recording now: "
rec -q -t wav $ramf rate 16k silence 1 0.1 1% 1 2.0 3% channels 1 2>/dev/null
#Time stamps for timing the performance of the various stages (Un/Comment as needed):
#stmp=$(date +%s%N)
if [[ -n "$IPnPORT" ]] ; then
#echo "Sending to server now: "
str=$(curl -S -s $IPnPORT/inference \
-H "Content-Type: multipart/form-data" \
-F file="@$ramf" \
-F temperature="0.0" \
-F temperature_inc="0.2" \
-F response_format="text")
elif [[ "$whf" == *.llamafile ]]; then
#echo "Using $whf:"
str="$($whf -t $NTHR -nt --gpu auto -f $ramf 2>/dev/null)"
else
#A default fallback if the whisper server is offline.
#echo "Transcribing now: "
str="$(transcribe -t $NTHR -nt -fa -m $WMODEL -f $ramf 2>/dev/null)"
fi
#echo "Got text back after: "$((($(date +%s%N) - stmp)/1000000))" ms"
#stmp=$(date +%s%N)
# Whisper detected non-speech events such as (wind blowing):
str="${str/\(*\)}"
str="${str#$'\n'}"
if [[ "$wm" == "x11" ]]; then
str+=$'\n'$(xsel -op)
xsel -cp
elif [[ "$wm" == "wayland" ]]; then
str+=$'\n'$(wl-paste -p)
wl-copy -cp
fi
if [[ -n "$ZSH_VERSION" ]] ; then
str="${str# }"
str="${(C)str:0:1}${str#?}"
if [[ $str == *[Rr]eset\ context* ]]; then
: > $TEMPD/chatfile
select_role
tts_play "OK, the context was reset, let us start fresh."
exit 0
fi
if (( CHATMODE )); then
echo -e "\nUser:\n$str" >> $TEMPD/chatfile
strai="$(< $TEMPD/chatfile)"
strai="${strai//$'\n'/\n}"
strai="${strai//\"/*}"
cur_prompt="$(cat $TEMPD/chatbot_prompt)"
strr=$(curl -S -s "$LHOST:$LPORT/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer no-key" \
-d "$(jq -n \
--arg cur_prompt "$cur_prompt" \
--arg strai "$strai" \
'{slot_id: 0, temperature: 0.13, n_keep: -1, cache_prompt: true, model: "BlahstBot", messages: [
{role: "system", content: $cur_prompt},
{role: "user", content: $strai}]}')" | jq -r '.choices[0].message.content')
strr="${strr//\*/}"
strr="${strr/\[end of text\]}"
echo "Answer:\n$strr" >> $TEMPD/chatfile
str="$str\n${strr//<(?|)([A-Z][A-Z])>/}"
#We have a result (either recognized text or AI response):
#Is this a GUI desktop environment:
if [[ -n "${XDG_CURRENT_DESKTOP}" ]] || [[ -n "${DISPLAY}" ]] || [[ -n "${DESKTOP_SESSION}" ]]; then
clipaste $str
else
#"Not running in a known graphics environment. Using standard output:
echo $str ; exit 0
fi
arr=(${(s:<:)strr})
for el in $arr; do
arr2=(${(s:>:)el})
[[ ${#arr2} == 1 ]] && [[ $arr2[1] != /* ]] && { tts_play "$arr2[1]" ; } \
|| { [[ $arr2[1] != /* ]] && { tts_play "$arr2[2]" "$arr2[1]" ; } \
|| { tts_play "$arr2[2]" ; } ; }
done
else
tts_play "Llamafile support has not been implemented yet. Sorry!"
fi
else
#Not testing for AI input if shell is not zsh:
desknote "Unknown shell, assuming bash, LLM features suppressed" "Transcribed text can be pasted..."
str="${str##+([[:space:]])}"
str="${str^}"
fi