File size: 12,101 Bytes
92c7ec3
192e7a4
 
 
 
 
92c7ec3
9152447
92c7ec3
f896425
 
d290cd6
92c7ec3
 
 
 
dbcd902
f896425
 
92c7ec3
d290cd6
92c7ec3
 
 
 
4099f5c
92c7ec3
 
14a0b87
92c7ec3
14a0b87
860712a
92c7ec3
 
 
 
0d9e5d5
 
0ff15a5
 
0d9e5d5
 
 
 
 
 
 
92c7ec3
 
 
4099f5c
 
 
92c7ec3
 
0d9e5d5
4099f5c
0d9e5d5
afc247c
4099f5c
 
0d9e5d5
4099f5c
 
 
0d9e5d5
4099f5c
0ff15a5
 
4099f5c
 
0d9e5d5
 
4099f5c
 
92c7ec3
 
 
192e7a4
92c7ec3
 
d290cd6
 
 
26221aa
86504e3
92c7ec3
 
d290cd6
14a0b87
d290cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c7ec3
14a0b87
92c7ec3
 
 
 
 
751d49e
 
 
 
 
c004bcb
8d62920
92c7ec3
 
 
751d49e
86504e3
92c7ec3
c004bcb
8d62920
92c7ec3
 
 
 
14a0b87
92c7ec3
14a0b87
92c7ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14a0b87
 
92c7ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
14a0b87
 
92c7ec3
 
 
14a0b87
 
92c7ec3
14a0b87
92c7ec3
14a0b87
92c7ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3e2f7d
37bd4dd
ceec937
4099f5c
 
ff48602
 
 
 
4099f5c
 
 
 
 
 
 
0d9e5d5
92c7ec3
192e7a4
ff48602
192e7a4
d50ac58
192e7a4
c004bcb
d50ac58
192e7a4
8d62920
d290cd6
 
14a0b87
d290cd6
 
92c7ec3
 
14a0b87
92c7ec3
14a0b87
 
92c7ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14a0b87
ff48602
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
from openai import OpenAI
import pandas as pd
import psycopg2
import time
import gradio as gr
import sqlparse
import re
import os
import warnings


from persistStorage import saveLog, getAllLogFilesPaths, getNewCsvFilePath, removeAllCsvFiles
from config import *
from constants import *
from utils import *
from gptManager import ChatgptManager
from queryHelperManagerCoT import QueryHelperChainOfThought


pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

# Filter out all warning messages
warnings.filterwarnings("ignore")

LOGGED_IN_USERS = []
dbCreds = DataWrapper(DB_CREDS_DATA)
dbEngine = DbEngine(dbCreds)
print("getting tablesAndCols..")
tablesAndCols = getAllTablesInfo(dbEngine, SCHEMA_NAME)
print("Done.")

metadataLayout = MetaDataLayout(schemaName=SCHEMA_NAME, allTablesAndCols=tablesAndCols)
metadataLayout.setSelection(DEFAULT_TABLES_COLS)

selectedTablesAndCols = metadataLayout.getSelectedTablesAndCols()

openAIClient2 = OpenAI(api_key=OPENAI_API_KEY)
gptInstanceForCoT = ChatgptManager(openAIClient2, model=GPT_MODEL)
queryHelperCot = QueryHelperChainOfThought(gptInstanceForCoT=gptInstanceForCoT,
                          schemaName=SCHEMA_NAME,platform=PLATFORM, 
                          metadataLayout=metadataLayout, 
                          sampleDataRows=SAMPLE_ROW_MAX, 
                          gptSampleRows=GPT_SAMPLE_ROWS,
                         dbEngine=dbEngine,
                         getSampleDataForTablesAndCols=getSampleDataForTablesAndCols)

def checkAuth(username, password):
  global ADMIN, PASSWD
  if username == ADMIN and password == PASSWD:
    LOGGED_IN_USERS.append(username)
    print("user logged in...",username)
    return True
  return False

# Function to save history of chat
def respondCoT(message, chatHistory, verboseChatHistory, loggedUser):
  """gpt response handler for gradio ui"""
  global queryHelperCot
  if len(loggedUser)==0:
    loggedUser.append(LOGGED_IN_USERS[-1])
  try:
    # botMessage  = queryHelperCot.getQueryForUserInputCoT(message)
    botMessage, verboseBotMessage  = queryHelperCot.getQueryForUserInputWithHistory(verboseChatHistory, message)

  except Exception as e:
    errorMessage = {"function":"queryHelperCot.getQueryForUserInputWithHistory","error":str(e), "userInput":message}
    saveLog(errorMessage, 'error')
    raise ValueError(str(e))
  logMessage = {"userInput":message, "completeGptResponse":verboseBotMessage, 
                "parsedResponse":botMessage, "function":"queryHelperCot.getQueryForUserInputWithHistory"}
  saveLog(logMessage)
  chatHistory.append((message, botMessage))
  verboseChatHistory.append((message, verboseBotMessage))
  return "", chatHistory, verboseChatHistory, loggedUser


def preProcessSQL(sql):
  sql=sql.replace(';', '')
  disclaimerOutputStripping = ""
  if ('limit' in sql[-15:].lower())==False:
    sql = sql + ' ' + 'limit 100'
    disclaimerOutputStripping = """Results are stripped to show only top 100 rows.
Please add your custom limit to get extended result.
eg\n select * from schema.table limit 200\n"""
  sql = sqlparse.format(sql, reindent=True, keyword_case='upper')
  return sql, disclaimerOutputStripping

def onGetResultCsvFile(sql):
  global dbEngine, queryHelperCot
  sql, disclaimerOutputStripping = preProcessSQL(sql=sql)
  if not isDataQuery(sql):
    return "Sorry not allowed to run. As the query modifies the data."
  try:
    dbEngine2 = DbEngine(dbCreds)
    dbEngine2.connect()
    conn = dbEngine2.getConnection()
    df = pd.read_sql_query(sql, con=conn)
    
    dbEngine2.disconnect()
    # return disclaimerOutputStripping + str(pd.DataFrame(df))
  except Exception as e:
    # errorMessage = {"function":"testSQL","error":str(e), "userInput":sql}
    # saveLog(errorMessage, 'error')
    dbEngine2.disconnect()
    df = pd.DataFrame()
    # print(f"Error occured during running the query {sql}.\n and the error is {str(e)}")

  removeAllCsvFiles()
  csvFilePath = getNewCsvFilePath()
  df.to_csv(csvFilePath, index=False)
  downloadableFilesPaths = getAllLogFilesPaths()
  fileComponent = gr.File(csvFilePath)
  return fileComponent

def testSQL(sql):
  global dbEngine, queryHelperCot

  sql, disclaimerOutputStripping = preProcessSQL(sql=sql)
  if not isDataQuery(sql):
    return "Sorry not allowed to run. As the query modifies the data."
  try:
    dbEngine2 = DbEngine(dbCreds)
    dbEngine2.connect()
    conn = dbEngine2.getConnection()
    df = pd.read_sql_query(sql, con=conn)  
    dbEngine2.disconnect()
    table_output = gr.Dataframe(df)
    return disclaimerOutputStripping, table_output
  except Exception as e:
      errorMessage = {"function":"testSQL","error":str(e), "userInput":sql}
      saveLog(errorMessage, 'error')
      dbEngine2.disconnect()
      
      print(f"Error occured during running the query {sql}.\n and the error is {str(e)}")
      table_output = gr.Dataframe(pd.DataFrame())
      return f"The query you entered throws some error. Here is the error.\n {str(e)}", table_output


def onSelectedTablesChange(tablesSelected):
  #Updates tables visible and allow selecting columns for them
  global queryHelperCot
  print(f"Selected tables : {tablesSelected}")
  metadataLayout = queryHelperCot.getMetadata()
  allTablesAndCols = metadataLayout.getAllTablesCols()
  selectedTablesAndCols = metadataLayout.getSelectedTablesAndCols()
  allTablesList = list(allTablesAndCols.keys())
  tableBoxes = []
  for i in range(len(allTablesList)):
    if allTablesList[i] in tablesSelected:
      dd = gr.Dropdown(
             allTablesAndCols[allTablesList[i]],visible=True,value=selectedTablesAndCols.get(allTablesList[i],None), multiselect=True, label=allTablesList[i], info="Select columns of a table"
        )
      tableBoxes.append(dd)
    else:
      dd = gr.Dropdown(
             allTablesAndCols[allTablesList[i]],visible=False,value=selectedTablesAndCols.get(allTablesList[i],None), multiselect=True, label=allTablesList[i], info="Select columns of a table"
        )
      tableBoxes.append(dd)
  return tableBoxes

def onSelectedColumnsChange(*tableBoxes):
  #update selection of columns and tables (include new tables and cols in gpts context)
  global queryHelperCot
  metadataLayout = queryHelperCot.getMetadata()
  allTablesAndCols = metadataLayout.getAllTablesCols()
  allTablesList = list(allTablesAndCols.keys())
  tablesAndCols = {}
  result = ''
  print("Getting selected tables and columns from gradio")
  for tableBox, table in zip(tableBoxes, allTablesList):
    if isinstance(tableBox, list):
      if len(tableBox)!=0:
        tablesAndCols[table] = tableBox
    else:
      pass
  
  metadataLayout.setSelection(tablesAndCols=tablesAndCols)
  print("metadata updated")
  print("Updating queryHelperCot state, and sample data")
  queryHelperCot.updateMetadata(metadataLayout)
  return "Columns udpated"

def onResetToDefaultSelection():
  global queryHelperCot
  metadataLayout = queryHelperCot.getMetadata()
  metadataLayout.setSelection(tablesAndCols=tablesAndCols)
  queryHelperCot.updateMetadata(metadataLayout)

  metadataLayout = queryHelperCot.getMetadata()
  allTablesAndCols = metadataLayout.getAllTablesCols()
  selectedTablesAndCols = metadataLayout.getSelectedTablesAndCols()
  allTablesList = list(allTablesAndCols.keys())
  tableBoxes = []
  for i in range(len(allTablesList)):
    if allTablesList[i] in selectedTablesAndCols.keys():
      dd = gr.Dropdown(
             allTablesAndCols[allTablesList[i]],visible=True,value=selectedTablesAndCols.get(allTablesList[i],None), multiselect=True, label=allTablesList[i], info="Select columns of a table"
        )
      tableBoxes.append(dd)
    else:
      dd = gr.Dropdown(
             allTablesAndCols[allTablesList[i]],visible=False,value=selectedTablesAndCols.get(allTablesList[i],None), multiselect=True, label=allTablesList[i], info="Select columns of a table"
        )
      tableBoxes.append(dd)

  return tableBoxes

def onSyncLogsWithDataDir():
    downloadableFilesPaths = getAllLogFilesPaths()
    fileComponent = gr.File(downloadableFilesPaths, file_count='multiple')
    return fileComponent


with gr.Blocks() as demo:
    loggedUser = gr.State([])
    verboseChatHistory = gr.State([])
    with gr.Tab("Query Helper"):
        gr.Markdown("""<h1><center> Query Helper</center></h1>""")
        chatbot = gr.Chatbot()
        msg = gr.Textbox()
        def clearChatHistory():
          return []
        
        clear = gr.ClearButton([msg, chatbot, verboseChatHistory], value="Clear Chat")
        clearButton = gr.Button("Clear Context")
        clearButton.click(clearChatHistory, inputs=None, outputs=[verboseChatHistory])
        msg.submit(respondCoT, [msg, chatbot, verboseChatHistory, loggedUser], [msg, chatbot, verboseChatHistory, loggedUser])

    # screen 2 : To run sql query against database
    with gr.Tab("Run Query"):
        gr.Markdown("""<h1><center> Run Query </center></h1>""")
        text_input = gr.Textbox(label = 'Input SQL Query', placeholder="Write your SQL query here ...")
        text_button = gr.Button("RUN QUERY")
        text_output = gr.Textbox(label = 'Result')
        table_output = gr.Dataframe(pd.DataFrame())
        
        clear = gr.ClearButton([text_input, text_output])
        text_button.click(testSQL, inputs=text_input, outputs=[text_output, table_output])

        csvFileComponent = gr.File([], file_count='multiple')
        downloadCsv = gr.Button("Generate csv result file")
        downloadCsv.click(onGetResultCsvFile, inputs=text_input, outputs=csvFileComponent)
        
     # screen 3 : To set creds, schema, tables and columns
    with gr.Tab("Setup"):
        gr.Markdown("""<h1><center> Setup Tab </center></h1>""")
        text_input = gr.Textbox(label = 'schema name', value= SCHEMA_NAME)
        allTablesAndCols = queryHelperCot.getMetadata().getAllTablesCols()
        selectedTablesAndCols = queryHelperCot.getMetadata().getSelectedTablesAndCols()
        allTablesList = list(allTablesAndCols.keys()) 
        selectedTablesList = list(selectedTablesAndCols.keys())
        
        dropDown = gr.Dropdown(
             allTablesList, value=selectedTablesList, multiselect=True, label="Selected Tables", info="Select Tables from available tables of the schema"
        )

        refreshTables = gr.Button("Refresh selected tables")

        tableBoxes = []
        
        for i in range(len(allTablesList)):
            if allTablesList[i] in selectedTablesList:
              columnsDropDown = gr.Dropdown(
             allTablesAndCols[allTablesList[i]],visible=True,value=selectedTablesAndCols.get(allTablesList[i],None), multiselect=True, label=allTablesList[i], info="Select columns of a table"
        )
              #tableBoxes[allTables[i]] = columnsDropDown
              tableBoxes.append(columnsDropDown)
            else:
              columnsDropDown = gr.Dropdown(
             allTablesAndCols[allTablesList[i]], visible=False, value=None, multiselect=True, label=allTablesList[i], info="Select columns of a table"
        )
              #tableBoxes[allTables[i]] = columnsDropDown
              tableBoxes.append(columnsDropDown)

        refreshTables.click(onSelectedTablesChange, inputs=dropDown, outputs=tableBoxes)




        columnsTextBox = gr.Textbox(label = 'Result')
        refreshColumns = gr.Button("Refresh selected columns and Reload Data")
        refreshColumns.click(onSelectedColumnsChange, inputs=tableBoxes, outputs=columnsTextBox)

        resetToDefaultSelection = gr.Button("Reset to Default")
        resetToDefaultSelection.click(onResetToDefaultSelection, inputs=None, outputs=tableBoxes)
    
    #screen 4 for downloading logs
    with gr.Tab("Log-files"):
        downloadableFilesPaths = getAllLogFilesPaths()
        fileComponent = gr.File(downloadableFilesPaths, file_count='multiple')
        refreshLogs = gr.Button("Sync Log files from /data")
        refreshLogs.click(onSyncLogsWithDataDir, inputs=None, outputs=fileComponent)
print("Ready to launch...")
demo.launch(share=True, debug=True, ssl_verify=False, auth=checkAuth)