-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatloop.py
More file actions
86 lines (67 loc) · 2.32 KB
/
chatloop.py
File metadata and controls
86 lines (67 loc) · 2.32 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
import queue
import sounddevice as sd
from vosk import Model, KaldiRecognizer
import json
from eliza.eliza import Eliza
import re
# --- ASR Setup ---
model = Model("./models/vosk-model-small-de-0.15")
rec = KaldiRecognizer(model, 32000)
# --- Audio Queue ---
q = queue.Queue()
audio_active = True # Flag to control audio input
def callback(indata, frames, time, status):
"""This function is called for each audio block."""
if status:
print(status, flush=True)
if audio_active: # Only queue audio if active
q.put(bytes(indata))
# --- Eliza Chatbot Setup ---
bot = Eliza()
bot.load("buddy.txt")
# --- TTS ---
def speak(text):
import subprocess
global audio_active
# Pause audio input before speaking
audio_active = False
# Run TTS
subprocess.run(["espeak-ng", "-v", "de", text])
# Resume audio input after speaking
audio_active = True
def extract_tags_and_text(text):
# Alle Tags extrahieren
tags = re.findall(r'<[^>]+>', text)
# Tags sortieren (lexikographisch)
tags_sorted = sorted(tags)
# Zu einem String verketten (mit Leerzeichen getrennt)
tag_string = " ".join(tags_sorted) or ""
# Tags aus dem Text entfernen
clean_text = re.sub(r'\s*<[^>]+>\s*', ' ', text).strip()
clean_text = re.sub(r'\s+', ' ', clean_text)
return tag_string, clean_text
# --- Loop ---
def output(response):
print("Eliza: " + response)
speak(response)
with sd.RawInputStream(samplerate=32000, blocksize=8000, dtype='int16', channels=1, callback=callback):
response = bot.initial()
output(response)
context = ""
while True:
data = q.get()
if rec.AcceptWaveform(data):
result = rec.Result()
user_input = json.loads(result).get("text", "")
if user_input:
print("You: " + user_input)
input_combined = " ".join([context, user_input]).strip()
print("[Input combined: " + input_combined + "]")
response = bot.respond(input_combined)
if response is None:
response = bot.final()
output(response)
break
print("[Raw response: " + response + "]")
context, response = extract_tags_and_text(response)
output(response)