-
Notifications
You must be signed in to change notification settings - Fork 21
/
singlestore.py
167 lines (137 loc) · 5.55 KB
/
singlestore.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import singlestoredb as s2
import sounddevice as sd
import soundfile as sf
import numpy as np
import speech_recognition as sr
from openai import OpenAI
import os
import base64
from playsound import playsound
from io import BytesIO
# You can store user queries with SingleStore. If you do not want to use SingleStore, just use main.py.
OpenAI.api_key = os.environ["OPENAI_API_KEY"]
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
client = OpenAI()
def frame_description(base64_image, user_prompt):
return [
{
"role": "user",
"content": [
{"type": "text", "text": user_prompt},
{
"type": "image_url",
"image_url": f"data:image/jpeg;base64,{base64_image}",
},
],
},
]
def analyze_image(full_analysis, base64_image, user_prompt):
response = client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "system",
"content": """
Response should be a sentence max, maybe 2. You are a friend of someone who is watching a basketball game. The clippers are the black jersey team (with white logo on bottom). The other team is the rockets and they are in a white jersey (red logo on bottom).
They are asking you questions about what is happening in the basketball game. Talk to them naturally like a friendly conversation. Be very passionate and excited about the game and use exclamation marks.
""",
},
]
+ full_analysis
+ frame_description(base64_image, user_prompt),
max_tokens=500,
)
response_text = response.choices[0].message.content
return response_text
def play_audio(text):
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input=text,
)
response.stream_to_file("audio/output.mp3")
playsound("audio/output.mp3")
def get_prompt():
audio_file = open("audio/input.mp3", "rb")
transcript = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
response_format="text"
)
return transcript
def get_input_file(threshold=0.03, silence_duration=3, base64_image=None):
recognizer = sr.Recognizer()
with sr.Microphone() as mic:
print("Listening for speech...")
# Adjust the recognizer sensitivity to ambient noise
recognizer.adjust_for_ambient_noise(mic)
started = False
start_time = None
audio_frames = []
recording = True
def callback(indata, frames, time, status):
nonlocal started, start_time, audio_frames, recording, base64_image
if np.any(indata > threshold):
if not started:
print("Starting recording...")
# Path to your image
image_path = "frames/frame.jpg"
# Getting the base64 string
base64_image = encode_image(image_path)
started = True
start_time = time.inputBufferAdcTime
audio_frames.append(indata.copy())
elif started:
if time.inputBufferAdcTime - start_time > silence_duration:
recording = False
raise sd.CallbackAbort
with sd.InputStream(callback=callback, channels=1):
while True:
if not recording:
break
if audio_frames:
audio_data = np.concatenate(audio_frames, axis=0)
with BytesIO() as f:
sf.write(f, audio_data, samplerate=70000, format='WAV')
f.seek(0)
with sr.AudioFile(f) as source:
audio = recognizer.record(source)
with open("audio/input.mp3", "wb") as mp3_file:
mp3_file.write(audio.get_wav_data(convert_rate=16000, convert_width=2))
#print("Audio saved as input.mp3")
else:
print("No speech detected")
return base64_image
def main():
full_analysis = []
conn = s2.connect(
'admin:Testing123@svc-ca8fa339-0d39-4942-ad73-4463f4110a1c-dml.aws-virginia-5.svc.singlestore.com:3306/testing')
conn.autocommit(True)
try:
while True:
final_image = get_input_file()
user_prompt = get_prompt()
print(user_prompt)
analysis = analyze_image(full_analysis, final_image, user_prompt)
print(analysis)
play_audio(analysis)
full_analysis.append({"role": "assistant", "content": analysis})
# SQL statement for a regular INSERT
insert_stmt = 'INSERT INTO OpenAISingleStore (TextValue) VALUES (%s)'
with conn.cursor() as cur:
# Insert the data without specifying TextKey; it will auto-increment
cur.execute(insert_stmt, (user_prompt,))
# Retrieve the last inserted ID
cur.execute('SELECT LAST_INSERT_ID()')
last_id_result = cur.fetchone()
if last_id_result:
last_id = last_id_result[0]
print("Last inserted ID:", last_id)
finally:
# Ensure the connection is closed after the loop
conn.close()
if __name__ == "__main__":
main()