Skip to content

Commit bf6dbbb

Browse files
committed
Merge remote-tracking branch 'origin/main'
2 parents 7639fe9 + dcb979c commit bf6dbbb

File tree

5 files changed

+92
-97
lines changed

5 files changed

+92
-97
lines changed

MLH.jpg

-389 KB
Binary file not shown.

download.html

Lines changed: 0 additions & 55 deletions
This file was deleted.
Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
11
For details see the Develop with Oracle AI and Database Services: Gen, Vision, Speech, Language, and OML
2-
located here: https://livelabs.oracle.com/pls/apex/r/dbpm/livelabs/view-workshop?wid=3874
2+
located here: https://livelabs.oracle.com/pls/apex/r/dbpm/livelabs/view-workshop?wid=3874
3+
4+
Quick notes are here...
5+
- setup the database side with Select AI configured, etc.
6+
- oci session authenticate ; oci iam region list --config-file ~/.oci/config --profile MYSPEECHAIPROFILE --auth security_token
7+
- $env:COMPARTMENT_ID = "ocid1.compartment.oc1..YOURCOMPARMENTID"
8+
- python src/RealtimeSpeechSelectAI.py

python-realtimespeech-selectai/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ https://artifactory.oci.oraclecorp.com/global-dev-pypi/oci-2.129.1+preview.1.180
33
PyAudio>=0.2.14
44
websockets==11.0.3; python_version >= "3.7"
55
websockets==9.1; python_version == "3.6"
6+
aiohttp
67
oracledb

python-realtimespeech-selectai/src/RealtimeSpeechSelectAI.py

Lines changed: 84 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import asyncio
22
import getpass
3-
3+
import os
4+
import json
45
import pyaudio
56
import oracledb
7+
from datetime import datetime
68
import oci
79
from oci.config import from_file
810
from oci.auth.signers.security_token_signer import SecurityTokenSigner
@@ -11,19 +13,25 @@
1113
RealtimeClientListener,
1214
RealtimeParameters,
1315
)
14-
16+
from aiohttp import web
17+
18+
# Global variables to store the latest data
19+
latest_thetime = None
20+
latest_question = None
21+
latest_answer = None
22+
compartment_id = os.getenv('COMPARTMENT_ID')
23+
print(f"compartment_id: {compartment_id}")
1524
pw = getpass.getpass("Enter database user password:")
1625

1726
# Use this when making a connection with a wallet
1827
connection = oracledb.connect(
1928
user="moviestream",
2029
password=pw,
2130
dsn="selectaidb_high",
22-
config_dir="/Users/pparkins/Downloads/Wallet_SelectAIDB",
23-
wallet_location="/Users/pparkins/Downloads/Wallet_SelectAIDB"
31+
config_dir=r"C:\Users\paulp\Downloads\Wallet_SelectAIDB",
32+
wallet_location=r"C:\Users\paulp\Downloads\Wallet_SelectAIDB"
2433
)
25-
print("Successfully connected to Oracle Database")
26-
print(f"Connection details: {connection}")
34+
print(f"Successfully connected to Oracle Database Connection: {connection}")
2735

2836
# Create a FIFO queue
2937
queue = asyncio.Queue()
@@ -43,7 +51,7 @@
4351
last_result_time = None
4452

4553
def authenticator():
46-
config = from_file("~/.oci/config", "paulspeechai")
54+
config = from_file("~/.oci/config", "MYSPEECHAIPROFILE")
4755
with open(config["security_token_file"], "r") as f:
4856
token = f.readline()
4957
private_key = oci.signer.load_private_key_from_file(config["key_file"])
@@ -69,6 +77,7 @@ def audio_callback(in_data, frame_count, time_info, status):
6977

7078
stream.start_stream()
7179
config = from_file()
80+
isInsertResults = True
7281

7382
async def send_audio(client):
7483
while True:
@@ -85,11 +94,18 @@ def on_result(self, result):
8594
print(f"Received final results: {transcription}")
8695
print(f"Current cummulative result: {cummulativeResult}")
8796
if cummulativeResult.lower().startswith("select ai"):
97+
cummulativeResult = cummulativeResult[len("select ai"):].strip()
98+
isSelect = True
99+
elif cummulativeResult.lower().startswith("select the eye"):
100+
cummulativeResult = cummulativeResult[len("select the eye"):].strip()
88101
isSelect = True
102+
else:
103+
cummulativeResult = ""
89104
last_result_time = asyncio.get_event_loop().time()
90105
else:
91106
print(f"Received partial results: {result['transcriptions'][0]['transcription']}")
92107

108+
93109
def on_ack_message(self, ackmessage):
94110
return super().on_ack_message(ackmessage)
95111

@@ -113,54 +129,72 @@ async def check_idle():
113129
isSelect = False
114130
await asyncio.sleep(1)
115131

132+
# Function to execute AI query and optionally insert results into the table
133+
# For example Select AI I am looking for the top five selling movies for the latest month please
116134
def executeSelectAI():
117-
global cummulativeResult
135+
global cummulativeResult, isInsertResults, latest_thetime, latest_question, latest_answer
118136
print(f"executeSelectAI called cummulative result: {cummulativeResult}")
119-
# for example prompt => 'select ai I am looking for the top 5 selling movies for the latest month please',
137+
138+
# AI query - todo use openai_gpt4o
120139
query = """SELECT DBMS_CLOUD_AI.GENERATE(
121140
prompt => :prompt,
122-
profile_name => 'openai_gpt35',
141+
profile_name => 'openai_gpt35',
123142
action => 'narrate')
124143
FROM dual"""
125-
with connection.cursor() as cursor:
126-
cursor.execute(query, prompt=cummulativeResult)
127-
result = cursor.fetchone()
128-
if result and isinstance(result[0], oracledb.LOB):
129-
text_result = result[0].read()
130-
print(text_result)
131-
else:
132-
print(result)
144+
145+
try:
146+
with connection.cursor() as cursor:
147+
# Execute AI query
148+
cursor.execute(query, prompt=cummulativeResult)
149+
result = cursor.fetchone()
150+
151+
if result and isinstance(result[0], oracledb.LOB):
152+
text_result = result[0].read()
153+
print(text_result)
154+
155+
# Update the global variables
156+
latest_thetime = datetime.now()
157+
latest_question = cummulativeResult
158+
latest_answer = text_result[:3000] # Truncate if necessary
159+
cummulativeResult = ""
160+
161+
# Insert the prompt and result into the table if isInsertResults is True
162+
if isInsertResults:
163+
insert_query = """
164+
INSERT INTO selectai_data (thetime, question, answer)
165+
VALUES (:thetime, :question, :answer)
166+
"""
167+
cursor.execute(insert_query, {
168+
'thetime': latest_thetime,
169+
'question': latest_question,
170+
'answer': latest_answer
171+
})
172+
connection.commit()
173+
print("Insert successful.")
174+
else:
175+
print(result)
176+
except Exception as e:
177+
print(f"An error occurred: {e}")
178+
133179
# Reset cumulativeResult after execution
134180
cummulativeResult = ""
135181

182+
async def handle_request(request):
183+
global latest_thetime, latest_question, latest_answer
184+
data = {
185+
"thetime": latest_thetime.isoformat() if latest_thetime else None, # Convert datetime to ISO format
186+
"question": latest_question,
187+
"answer": latest_answer
188+
}
189+
return web.json_response(data)
136190

137-
# logic such as the following could be added to make the app further dynamic as far as action type...
138-
# actionValue = 'narrate'
139-
# if cummulativeResult.lower().startswith("select ai narrate"):
140-
# actionValue = "narrate"
141-
# elif cummulativeResult.lower().startswith("select ai chat"):
142-
# actionValue = "chat"
143-
# elif cummulativeResult.lower().startswith("select ai showsql"):
144-
# actionValue = "showsql"
145-
# elif cummulativeResult.lower().startswith("select ai show sql"):
146-
# actionValue = "showsql"
147-
# elif cummulativeResult.lower().startswith("select ai runsql"):
148-
# actionValue = "runsql"
149-
# elif cummulativeResult.lower().startswith("select ai run sql"):
150-
# actionValue = "runsql"
151-
# # Note that "runsql" is not currently supported as action value
152-
# query = """SELECT DBMS_CLOUD_AI.GENERATE(
153-
# prompt => :prompt,
154-
# profile_name => 'openai_gpt35',
155-
# action => :actionValue)
156-
# FROM dual"""
157191

158192
if __name__ == "__main__":
159193
# Run the event loop
160194
def message_callback(message):
161195
print(f"Received message: {message}")
162196

163-
realtime_speech_parameters: RealtimeParameters = RealtimeParameters()
197+
realtime_speech_parameters = RealtimeParameters()
164198
realtime_speech_parameters.language_code = "en-US"
165199
realtime_speech_parameters.model_domain = (
166200
realtime_speech_parameters.MODEL_DOMAIN_GENERIC
@@ -179,15 +213,24 @@ def message_callback(message):
179213
listener=SpeechListener(),
180214
service_endpoint=realtime_speech_url,
181215
signer=authenticator(),
182-
compartment_id="ocid1.compartment.oc1..MYCOMPARMENTID",
216+
compartment_id=compartment_id,
183217
)
184218

185219
loop = asyncio.get_event_loop()
186220
loop.create_task(send_audio(client))
187221
loop.create_task(check_idle())
222+
223+
# Set up the HTTP server
224+
app = web.Application()
225+
app.router.add_get('/selectai_data', handle_request)
226+
runner = web.AppRunner(app)
227+
loop.run_until_complete(runner.setup())
228+
site = web.TCPSite(runner, 'localhost', 8080)
229+
loop.run_until_complete(site.start())
230+
188231
loop.run_until_complete(client.connect())
189232

190233
if stream.is_active():
191234
stream.close()
192235

193-
print("Closed now")
236+
print("Closed now")

0 commit comments

Comments
 (0)