-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatty.py
153 lines (116 loc) · 4.21 KB
/
chatty.py
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
import datetime
import json
import time
import cheshire_cat_api as ccat
from pprint import pprint
import base64
from bs4 import BeautifulSoup
from playsound import playsound
from recorder import record_audio
import threading
# Connection settings with default values
config = ccat.Config(
base_url="localhost",
port=1865,
user_id="user_boy",
auth_key="",
secure_connection=False,
)
def on_open():
# This is triggered when the connection is opened
print("Connection opened!")
def on_message(message: str):
# This is triggered when a new message arrives
""" Looking for the audio file in the message
{
"type" :
"chat",
"content" :
"<audio controls autoplay><source
src='/admin/assets/voice/voice_20240617_140731.wav'
type='audio/mp3'
>
Your browser does not support the audio element.</audio>"
}
"""
message = json.loads(message)
if message["type"] == "chat" and "type='audio/mp3" in message["content"]:
html_string = message["content"]
url_audio_to_play = get_audio_file_path(
html_string
)
print("The file you are looking for is at :--->" + url_audio_to_play)
thread = threading.Thread(target=playsound, args=(url_audio_to_play,))
thread.start()
#playsound(url_audio_to_play) was blocking the thread and the connection was closed by the server because of a timeout
elif message["type"] == "chat" and "type='audio/wav" not in message["content"]:
print("Your user input was :")
print(message["why"]['input'])
print("Your response :")
print(message["content"])
def on_error(exception: Exception):
# This is triggered when a WebSocket error is raised
print(str(exception))
def on_close(status_code: int, message: str):
# This is triggered when the connection is closed
print(f"Connection closed with code {status_code}: {message}")
def read_file(file_path):
"""Reads a file and returns its content."""
with open(file_path, "rb") as file:
return file.read()
def read_file_as_base64(file_path):
"""Reads a file and encodes its content to base64."""
with open(file_path, "rb") as file:
return base64.b64encode(file.read()).decode("utf-8")
def get_audio_file_path(html_string):
"""
get the audio file path from the html string
and returns the url to reach the audio file
"""
soup = BeautifulSoup(html_string, "lxml")
source_tag = soup.find("source")
src_value = source_tag["src"]
url_audio = "http://" + config.base_url + ":" + str(config.port) + src_value
return url_audio
audio_file = ""
extra_fields = {
"audio_key": "", # Base64 encoded audio file
"audio_type": "audio/ogg", # MIME type of the audio file
"audio_name": "msg45430839-160807.ogg", # final part of the audio file path , should be better use timestamp
"encodedBase64": True, # Flag to indicate that the audio is encoded in base64
}
# Cat Client
cat_client = ccat.CatClient(
config=config,
on_open=on_open,
on_close=on_close,
on_message=on_message,
on_error=on_error,
)
url_audio_to_play = ""
# Connect to the WebSocket API
cat_client.connect_ws()
while not cat_client.is_ws_connected:
# A better handling is strongly advised to avoid an infinite loop
time.sleep(1)
while True:
# Send a message to the WebSocket
print("url i'm reaching for " + config.base_url + ":" + str(config.port))
message = input("Write 'stop' to exit: \nPress Enter for recording")
if message == "stop":
break
else:
print("I'm recording for 10 seconds...")
my_audio=record_audio()
extra_fields["audio_key"] = read_file_as_base64(my_audio)
print("I'm sending the audio to the server")
try:
cat_client.send(message, **extra_fields)
except Exception as e:
print("Error sending the message because of " + str(e))
print("Closing the connection")
cat_client.close()
print("Trying to reconnecting to the server")
cat_client.connect_ws()
# Close connection
cat_client.close()