File size: 12,392 Bytes
ac35dc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a0e87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac35dc9
 
 
7c30d23
ac35dc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8a0e87
 
 
 
 
 
 
 
 
ac35dc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
from langchain.chains import create_sql_query_chain
from transformers import AutoModelForCausalLM, AutoTokenizer,pipeline, LlamaTokenizer, LlamaForCausalLM
from langchain_huggingface import HuggingFacePipeline
from langchain_openai import ChatOpenAI
import os
from langchain_community.utilities.sql_database import SQLDatabase
from operator import itemgetter
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder,FewShotChatMessagePromptTemplate,PromptTemplate
from langchain_community.vectorstores import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_openai import OpenAIEmbeddings
from operator import itemgetter
from langchain.chains.openai_tools import create_extraction_chain_pydantic
from langchain_core.pydantic_v1 import BaseModel, Field
from typing import List
import pandas as pd
from argparse import ArgumentParser
import json
from langchain.memory import ChatMessageHistory
from langchain_community.tools.sql_database.tool import QuerySQLDataBaseTool
import subprocess
import sys
from transformers import pipeline
import librosa
import soundfile
import datasets
import sounddevice as sd
import numpy as np
import io

model_id = "avnishkanungo/whisper-small-dv"  # update with your model id
pipe = pipeline("automatic-speech-recognition", model=model_id)

def select_table(desc_path):
    def get_table_details():
        # Read the CSV file into a DataFrame
        table_description = pd.read_csv(desc_path) ##"/teamspace/studios/this_studio/database_table_descriptions.csv"
        table_docs = []

        # Iterate over the DataFrame rows to create Document objects
        table_details = ""
        for index, row in table_description.iterrows():
            table_details = table_details + "Table Name:" + row['Table'] + "\n" + "Table Description:" + row['Description'] + "\n\n"

        return table_details
    
    class Table(BaseModel):
        """Table in SQL database."""

        name: str = Field(description="Name of table in SQL database.")
    
    table_details_prompt = f"""Return the names of ALL the SQL tables that MIGHT be relevant to the user question. \
            The tables are:

            {get_table_details()}

            Remember to include ALL POTENTIALLY RELEVANT tables, even if you're not sure that they're needed."""

    table_chain = create_extraction_chain_pydantic(Table, llm, system_message=table_details_prompt)
    
    def get_tables(tables: List[Table]) -> List[str]:
        tables  = [table.name for table in tables]
        return tables

    select_table = {"input": itemgetter("question")} | create_extraction_chain_pydantic(Table, llm, system_message=table_details_prompt) | get_tables

    return select_table


def prompt_creation(example_path):

    with open(example_path, 'r') as file: ##'/teamspace/studios/this_studio/few_shot_samples.json'
        data = json.load(file)

    examples = data["examples"]

    example_prompt = ChatPromptTemplate.from_messages(
        [
            ("human", "{input}\nSQLQuery:"),
            ("ai", "{query}"),
        ]
    )

    vectorstore = Chroma()
    vectorstore.delete_collection()
    example_selector = SemanticSimilarityExampleSelector.from_examples(
        examples,
        OpenAIEmbeddings(),
        vectorstore,
        k=2,
        input_keys=["input"],
    )
    
    few_shot_prompt = FewShotChatMessagePromptTemplate(
        example_prompt=example_prompt,
        example_selector=example_selector,
        input_variables=["input","top_k"],
    )


    final_prompt = ChatPromptTemplate.from_messages(
        [
            ("system", "You are a MySQL expert. Given an input question, create a syntactically correct MySQL query to run. Unless otherwise specificed.\n\nHere is the relevant table info: {table_info}\n\nBelow are a number of examples of questions and their corresponding SQL queries."),
            few_shot_prompt,
            MessagesPlaceholder(variable_name="messages"),
            ("human", "{input}"),
        ]
    )

    print(few_shot_prompt.format(input="How many products are there?"))
        
    return final_prompt



def rephrase_answer():
    answer_prompt = PromptTemplate.from_template(
    """Given the following user question, corresponding SQL query, and SQL result, answer the user question.

        Question: {question}
        SQL Query: {query}
        SQL Result: {result}
        Answer: """
    )

    rephrase_answer = answer_prompt | llm | StrOutputParser()

    return rephrase_answer

def is_ffmpeg_installed():
    try:
        # Run `ffmpeg -version` to check if ffmpeg is installed
        subprocess.run(['ffmpeg', '-version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False

def install_ffmpeg():
    try:
        if sys.platform.startswith('linux'):
            subprocess.run(['sudo', 'apt-get', 'update'], check=True)
            subprocess.run(['sudo', 'apt-get', 'install', '-y', 'ffmpeg'], check=True)
        elif sys.platform == 'darwin':  # macOS
            subprocess.run(['/bin/bash', '-c', 'brew install ffmpeg'], check=True)
        elif sys.platform == 'win32':
            print("Please download ffmpeg from https://ffmpeg.org/download.html and install it manually.")
            return False
        else:
            print("Unsupported OS. Please install ffmpeg manually.")
            return False
    except subprocess.CalledProcessError as e:
        print(f"Failed to install ffmpeg: {e}")
        return False
    return True

def transcribe_speech(filepath):
        output = pipe(
            filepath,
            max_new_tokens=256,
            generate_kwargs={
                "task": "transcribe",
                "language": "english",
            },  # update with the language you've fine-tuned on
            chunk_length_s=30,
            batch_size=8,
        )
        return output["text"]
    
def record_command():
        sample_rate = 16000  # Sample rate in Hz
        duration = 8  # Duration in seconds

        print("Recording...")

        # Record audio
        audio = sd.rec(int(sample_rate * duration), samplerate=sample_rate, channels=1, dtype='float32')
        sd.wait()  # Wait until recording is finished

        print("Recording finished")

        # Convert the audio to a binary stream and save it to a variable
        audio_buffer = io.BytesIO()
        soundfile.write(audio_buffer, audio, sample_rate, format='WAV')
        audio_buffer.seek(0)  # Reset buffer position to the beginning

        # The audio file is now saved in audio_buffer
        # You can read it again using soundfile or any other audio library
        audio_data, sample_rate = soundfile.read(audio_buffer)

        # Optional: Save the audio to a file for verification
        # with open('recorded_audio.wav', 'wb') as f:
        #     f.write(audio_buffer.getbuffer())

        print("Audio saved to variable")
        return audio_data

def check_libportaudio_installed():
    try:
        # Run `ffmpeg -version` to check if ffmpeg is installed
        subprocess.run(['libportaudio2', '-version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False

def install_libportaudio():
    try:
        if sys.platform.startswith('linux'):
            subprocess.run(['sudo', 'apt-get', 'update'], check=True)
            subprocess.run(['sudo', 'apt-get', 'install', '-y', 'libportaudio2'], check=True)
        elif sys.platform == 'darwin':  # macOS
            subprocess.run(['/bin/bash', '-c', 'brew install portaudio'], check=True)
        elif sys.platform == 'win32':
            print("Please download ffmpeg from https://ffmpeg.org/download.html and install it manually.")
            return False
        else:
            print("Unsupported OS. Please install ffmpeg manually.")
            return False
    except subprocess.CalledProcessError as e:
        print(f"Failed to install ffmpeg: {e}")
        return False
    return True


if __name__ == '__main__':

    # Please configure your DB credentials and paths of the files for few shot learning and fine tuning
    parser = ArgumentParser()
    parser.add_argument('--example_path', type=str, default=os.getcwd()+"/few_shot_samples.json")
    parser.add_argument('--desc_path', type=str, default=os.getcwd()+"/database_table_descriptions.csv")
    parser.add_argument('--db_user', type=str, default="root")
    parser.add_argument('--db_password', type=str, default="")
    parser.add_argument('--db_host', type=str, default="localhost")
    parser.add_argument('--db_name', type=str, default="classicmodels")
    parser.add_argument('--open_ai_key', type=str)
    args = parser.parse_args()

    db_user = args.db_user
    db_password = args.db_password
    db_host = args.db_host
    db_name = args.db_name

    db = SQLDatabase.from_uri(f"mysql+pymysql://{db_user}:{db_password}@{db_host}/{db_name}")
    # print(db.dialect)
    # print(db.get_usable_table_names())
    # print(db.table_info)
    os.environ["OPENAI_API_KEY"] =  args.open_ai_key  

    history = ChatMessageHistory()

    llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

    final_prompt = prompt_creation(args.example_path)

    generate_query = create_sql_query_chain(llm, db, final_prompt)

    execute_query = QuerySQLDataBaseTool(db=db)

    chain = (
        RunnablePassthrough.assign(table_names_to_use=select_table(args.desc_path)) |
        RunnablePassthrough.assign(query=generate_query).assign(
        result=itemgetter("query") | execute_query
        )
        | rephrase_answer()
    )

    if is_ffmpeg_installed():
        print("ffmpeg is already installed.")
    else:
        print("ffmpeg is not installed. Installing ffmpeg...")
    if install_ffmpeg():
        print("ffmpeg installation successful.")
    else:
        print("ffmpeg installation failed. Please install it manually.")
    
    if check_libportaudio_installed():
        print("libportaudio is already installed.")
    else:
        print("libportaudio is not installed. Installing ffmpeg...")
    if install_libportaudio():
        print("libportaudio installation successful.")
    else:
        print("libportaudio installation failed. Please install it manually.")

    valid_interface_type = ["audio", "text", "quit"]
    while True:
        interface_type = input("Please enter 'audio', 'text', or 'quit': ").strip().lower()
        if interface_type in valid_interface_type:
            if interface_type == "quit":
                print("Exiting the loop.")
                break
            elif interface_type == "text" :
                print(f"You selected '{interface_type}'.")
                while True:
                    user_input = input("Enter a question for the DB (or type 'quit' to exit): ")
                    if user_input.lower() == 'quit':
                        break
                    output = chain.invoke({"question": user_input, "messages":history.messages})
                    history.add_user_message(user_input)
                    history.add_ai_message(output)
                    print(output)
            elif interface_type == "audio":
                print(f"You selected '{interface_type}'.") 
                command = record_command()
                sql_query = transcribe_speech(command)
                print(sql_query)
                output = chain.invoke({"question": sql_query, "messages":history.messages})
                history.add_user_message(sql_query)
                history.add_ai_message(output)
                print(output)     

        else:
            print("Invalid input. Please try again.")


    # while True:
    #     user_input = input("Enter a question for the DB (or type 'quit' to exit): ")
    #     if user_input.lower() == 'quit':
    #         break
    #     output = chain.invoke({"question": user_input, "messages":history.messages})
    #     history.add_user_message(user_input)
    #     history.add_ai_message(output)
    #     print(output)