-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlisting2.py
More file actions
150 lines (116 loc) · 3.88 KB
/
Copy pathlisting2.py
File metadata and controls
150 lines (116 loc) · 3.88 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
'''
Created on Nov 12, 2023
@author: immanueltrummer
'''
import argparse
import openai
import re
import scipy.io.wavfile
import sounddevice
import sqlite3
import time
client = openai.OpenAI()
def get_structure(data_path):
""" Extract structure from SQLite database.
Args:
data_path: path to SQLite data file.
Returns:
text description of database structure.
"""
with sqlite3.connect(data_path) as connection:
cursor = connection.cursor()
cursor.execute("select sql from sqlite_master where type = 'table';")
table_rows = cursor.fetchall()
table_ddls = [r[0] for r in table_rows]
return '\n'.join(table_ddls)
def record(output_path):
""" Record audio and store in .wav file.
Args:
output_path: store audio recording there.
"""
sample_rate = 44100
nr_frames = 5 * sample_rate
recording = sounddevice.rec(nr_frames, samplerate=sample_rate, channels=1)
sounddevice.wait()
scipy.io.wavfile.write(output_path, sample_rate, recording)
def transcribe(audio_path):
""" Transcribe audio file to text.
Args:
audio_path: path to audio file.
Returns:
transcribed text.
"""
with open(audio_path, 'rb') as audio_file:
transcription = client.audio.transcriptions.create(
file=audio_file, model='whisper-1')
return transcription.text
def create_prompt(description, question):
""" Generate prompt to translate question into SQL query.
Args:
description: text description of database structure.
question: question about data in natural language.
Returns:
prompt for question translation.
"""
parts = []
parts += ['Database:']
parts += [description]
parts += ['Translate this question into SQL query:']
parts += [question]
parts += ['SQL Query:']
return '\n'.join(parts)
def call_llm(prompt):
""" Query large language model and return answer.
Args:
prompt: input prompt for language model.
Returns:
Answer by language model.
"""
for nr_retries in range(1, 4):
try:
response = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role':'user', 'content':prompt}
]
)
return response.choices[0].message.content
except:
time.sleep(nr_retries * 2)
raise Exception('Cannot query OpenAI model!')
def process_query(data_path, query):
""" Processes SQL query and returns result.
Args:
data_path: path to SQLite data file.
query: process this query on database.
Returns:
query result.
"""
with sqlite3.connect(data_path) as connection:
cursor = connection.cursor()
cursor.execute(query)
table_rows = cursor.fetchall()
table_strings = [str(r) for r in table_rows]
return '\n'.join(table_strings)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dbpath', type=str, help='Path to SQLite data')
args = parser.parse_args()
data_structure = get_structure(args.dbpath)
while True:
user_input = input('Press enter to record (type quit to quit).')
if user_input == 'quit':
break
audio_path = 'question.wav'
record(audio_path)
question = transcribe(audio_path)
print(f'Question: {question}')
prompt = create_prompt(data_structure, question)
answer = call_llm(prompt)
query = re.findall('```sql(.*)```', answer, re.DOTALL)[0]
print(f'SQL: {query}')
try:
answer = process_query(args.dbpath, query)
print(f'Answer: {answer}')
except:
print('Error processing query! Try to reformulate.')