richardr1126 commited on
Commit
e6db544
β€’
1 Parent(s): 9afbbb8

added local demo

Browse files
Files changed (1) hide show
  1. app-local.py +325 -0
app-local.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import sqlite3
4
+ import sqlparse
5
+ import requests
6
+ import time
7
+ import re
8
+ import platform
9
+ import openai
10
+ from transformers import (
11
+ AutoModelForCausalLM,
12
+ AutoTokenizer,
13
+ StoppingCriteria,
14
+ StoppingCriteriaList,
15
+ )
16
+ # Additional Firebase imports
17
+ import firebase_admin
18
+ from firebase_admin import credentials, firestore
19
+ import json
20
+ import base64
21
+ import torch
22
+
23
+ print(f"Running on {platform.system()}")
24
+
25
+ from dotenv import load_dotenv
26
+ load_dotenv()
27
+
28
+ quantized_model = "richardr1126/spider-skeleton-wizard-coder-8bit"
29
+ merged_model = "richardr1126/spider-skeleton-wizard-coder-merged"
30
+ initial_model = "WizardLM/WizardCoder-15B-V1.0"
31
+ lora_model = "richardr1126/spider-skeleton-wizard-coder-qlora"
32
+ dataset = "richardr1126/spider-skeleton-context-instruct"
33
+
34
+ model_name = os.getenv("HF_MODEL_NAME", None)
35
+ tok = AutoTokenizer.from_pretrained(model_name)
36
+
37
+ max_new_tokens = 1024
38
+
39
+ print(f"Starting to load the model {model_name}")
40
+
41
+ m = AutoModelForCausalLM.from_pretrained(
42
+ model_name,
43
+ #device_map="cpu",
44
+ low_cpu_mem_usage=True
45
+ #load_in_8bit=True,
46
+ )
47
+
48
+ m.config.pad_token_id = m.config.eos_token_id
49
+ m.generation_config.pad_token_id = m.config.eos_token_id
50
+
51
+ print(f"Successfully loaded the model {model_name} into memory")
52
+
53
+ ################# Firebase code #################
54
+ # Initialize Firebase
55
+ base64_string = os.getenv('FIREBASE')
56
+ base64_bytes = base64_string.encode('utf-8')
57
+ json_bytes = base64.b64decode(base64_bytes)
58
+ json_data = json_bytes.decode('utf-8')
59
+
60
+ firebase_auth = json.loads(json_data)
61
+
62
+ # Load credentials and initialize Firestore
63
+ cred = credentials.Certificate(firebase_auth)
64
+ firebase_admin.initialize_app(cred)
65
+ db = firestore.client()
66
+
67
+ def log_message_to_firestore(input_message, db_info, temperature, response_text):
68
+ doc_ref = db.collection('logs').document()
69
+ log_data = {
70
+ 'timestamp': firestore.SERVER_TIMESTAMP,
71
+ 'temperature': temperature,
72
+ 'db_info': db_info,
73
+ 'input': input_message,
74
+ 'output': response_text,
75
+ }
76
+ doc_ref.set(log_data)
77
+
78
+ rated_outputs = set() # set to store already rated outputs
79
+
80
+ def log_rating_to_firestore(input_message, db_info, temperature, response_text, rating):
81
+ global rated_outputs
82
+ output_id = f"{input_message} {db_info} {response_text} {temperature}"
83
+
84
+ if output_id in rated_outputs:
85
+ gr.Warning("You've already rated this output!")
86
+ return
87
+ if not input_message or not response_text or not rating:
88
+ gr.Info("You haven't asked a question yet!")
89
+ return
90
+
91
+ rated_outputs.add(output_id)
92
+
93
+ doc_ref = db.collection('ratings').document()
94
+ log_data = {
95
+ 'timestamp': firestore.SERVER_TIMESTAMP,
96
+ 'temperature': temperature,
97
+ 'db_info': db_info,
98
+ 'input': input_message,
99
+ 'output': response_text,
100
+ 'rating': rating,
101
+ }
102
+ doc_ref.set(log_data)
103
+ gr.Info("Thanks for your feedback!")
104
+ ############### End Firebase code ###############
105
+
106
+ def format(text):
107
+ # Split the text by "|", and get the last element in the list which should be the final query
108
+ try:
109
+ final_query = text.split("|")[1].strip()
110
+ except Exception:
111
+ final_query = text
112
+
113
+ try:
114
+ # Attempt to format SQL query using sqlparse
115
+ formatted_query = sqlparse.format(final_query, reindent=True, keyword_case='upper')
116
+ except Exception:
117
+ # If formatting fails, use the original, unformatted query
118
+ formatted_query = final_query
119
+
120
+ # Convert SQL to markdown (not required, but just to show how to use the markdown module)
121
+ final_query_markdown = f"{formatted_query}"
122
+
123
+ return final_query_markdown
124
+
125
+ def extract_db_code(text):
126
+ pattern = r'```(?:\w+)?\s?(.*?)```'
127
+ matches = re.findall(pattern, text, re.DOTALL)
128
+ return [match.strip() for match in matches]
129
+
130
+ def generate_dummy_db(db_info, question, query):
131
+ pre_prompt = "Generate a SQLite database with dummy data for this database, output the SQL code in a SQL code block. Make sure you add dummy data relevant to the question and query.\n\n"
132
+ prompt = pre_prompt + db_info + "\n\nQuestion: " + question + "\nQuery: " + query
133
+
134
+ while True:
135
+ try:
136
+ response = openai.ChatCompletion.create(
137
+ model="gpt-3.5-turbo",
138
+ messages=[
139
+ {"role": "user", "content": prompt}
140
+ ],
141
+ #temperature=0.7,
142
+ )
143
+ response_text = response['choices'][0]['message']['content']
144
+
145
+ db_code = extract_db_code(response_text)
146
+
147
+ return db_code
148
+
149
+ except Exception as e:
150
+ print(f'Error occurred: {str(e)}')
151
+ print('Waiting for 20 seconds before retrying...')
152
+ time.sleep(20)
153
+
154
+ def test_query_on_dummy_db(db_code, query):
155
+ try:
156
+ # Connect to an SQLite database in memory
157
+ conn = sqlite3.connect(':memory:')
158
+ cursor = conn.cursor()
159
+
160
+ # Iterate over each extracted SQL block and split them into individual commands
161
+ for sql_block in db_code:
162
+ statements = sqlparse.split(sql_block)
163
+
164
+ # Execute each SQL command
165
+ for statement in statements:
166
+ if statement:
167
+ cursor.execute(statement)
168
+
169
+ # Run the provided test query against the database
170
+ cursor.execute(query)
171
+ print(cursor.fetchall())
172
+
173
+ # Close the connection
174
+ conn.close()
175
+
176
+ # If everything executed without errors, return True
177
+ return True
178
+
179
+ except Exception as e:
180
+ print(f"Error encountered: {e}")
181
+ return False
182
+
183
+
184
+ def generate(input_message: str, db_info="", temperature=0.2, top_p=0.9, top_k=0, repetition_penalty=1.08, format_sql=True, log=False, num_return_sequences=1, num_beams=1, do_sample=False):
185
+ stop_token_ids = tok.convert_tokens_to_ids(["###"])
186
+ class StopOnTokens(StoppingCriteria):
187
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
188
+ for stop_id in stop_token_ids:
189
+ if input_ids[0][-1] == stop_id:
190
+ return True
191
+ return False
192
+ stop = StopOnTokens()
193
+
194
+ # Format the user's input message
195
+ messages = f"Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\n\nConvert text to sql: {input_message} {db_info}\n\n### Response:\n\n"
196
+
197
+ input_ids = tok(messages, return_tensors="pt").input_ids
198
+ input_ids = input_ids.to(m.device)
199
+ generate_kwargs = dict(
200
+ input_ids=input_ids,
201
+ max_new_tokens=max_new_tokens,
202
+ temperature=temperature,
203
+ top_p=top_p,
204
+ top_k=top_k,
205
+ repetition_penalty=repetition_penalty,
206
+ #streamer=streamer,
207
+ stopping_criteria=StoppingCriteriaList([stop]),
208
+ num_return_sequences=num_return_sequences,
209
+ num_beams=num_beams,
210
+ do_sample=do_sample,
211
+ )
212
+
213
+ tokens = m.generate(**generate_kwargs)
214
+
215
+ responses = []
216
+ for response in tokens:
217
+ response_text = tok.decode(response, skip_special_tokens=True)
218
+
219
+ # Only take what comes after ### Response:
220
+ response_text = response_text.split("### Response:")[1].strip()
221
+
222
+ query = format(response_text) if format_sql else response_text
223
+ if (num_return_sequences > 1):
224
+ query = query.replace("\n", " ").replace("\t", " ").strip()
225
+ # Test against dummy database
226
+ db_code = generate_dummy_db(db_info, input_message, query)
227
+ success = test_query_on_dummy_db(db_code, query)
228
+ # Format again
229
+ query = format(query) if format_sql else query
230
+ if success:
231
+ responses.append(query)
232
+ else:
233
+ responses.append(query)
234
+
235
+ # Choose the first response
236
+ output = responses[0] if responses else ""
237
+
238
+ if log:
239
+ # Log the request to Firestore
240
+ log_message_to_firestore(input_message, db_info, temperature, output)
241
+
242
+ return output
243
+
244
+ # Gradio UI Code
245
+ with gr.Blocks(theme='gradio/soft') as demo:
246
+ # Elements stack vertically by default just define elements in order you want them to stack
247
+ header = gr.HTML("""
248
+ <h1 style="text-align: center">SQL Skeleton WizardCoder Demo</h1>
249
+ <h3 style="text-align: center">πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ Generate SQL queries from Natural Language πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ</h3>
250
+ <div style="max-width: 450px; margin: auto; text-align: center">
251
+ <p style="font-size: 12px; text-align: center">⚠️ Should take 30-60s to generate. Please rate the response, it helps a lot. If you get a blank output, the model server is currently down, please try again another time.</p>
252
+ </div>
253
+ """)
254
+
255
+ output_box = gr.Code(label="Generated SQL", lines=2, interactive=False)
256
+
257
+ with gr.Row():
258
+ rate_up = gr.Button("πŸ‘", variant="secondary")
259
+ rate_down = gr.Button("πŸ‘Ž", variant="secondary")
260
+
261
+ input_text = gr.Textbox(lines=3, placeholder='Write your question here...', label='NL Input')
262
+ db_info = gr.Textbox(lines=4, placeholder='Make sure to place your tables information inside || for better results. Example: | table_01 : column_01 , column_02 | table_02 : column_01 , column_02 | ...', label='Database Info')
263
+ format_sql = gr.Checkbox(label="Format SQL + Remove Skeleton", value=True, interactive=True)
264
+
265
+ with gr.Row():
266
+ run_button = gr.Button("Generate SQL", variant="primary")
267
+ clear_button = gr.ClearButton(variant="secondary")
268
+
269
+ with gr.Accordion("Options", open=False):
270
+ temperature = gr.Slider(label="Temperature", minimum=0.0, maximum=1.0, value=0.2, step=0.1)
271
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.0, maximum=1.0, value=0.9, step=0.01)
272
+ top_k = gr.Slider(label="Top-k", minimum=0, maximum=200, value=0, step=1)
273
+ repetition_penalty = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.08, step=0.01)
274
+
275
+ with gr.Accordion("Generation strategies", open=False):
276
+ md_description = gr.Markdown("""Increasing num return sequences will increase the number of SQLs generated, but will still yield only the best output of the number of return sequences. SQLs are tested against the db info you provide.""")
277
+ num_return_sequences = gr.Slider(label="Number of return sequences (to generate and test)", minimum=1, maximum=5, value=1, step=1)
278
+ num_beams = gr.Slider(label="Num Beams", minimum=1, maximum=5, value=1, step=1)
279
+ do_sample = gr.Checkbox(label="Do Sample", value=False, interactive=True)
280
+
281
+ info = gr.HTML(f"""
282
+ <p>🌐 Leveraging the <a href='https://huggingface.co/{quantized_model}'><strong>bitsandbytes 8-bit version</strong></a> of <a href='https://huggingface.co/{merged_model}'><strong>{merged_model}</strong></a> model.</p>
283
+ <p>πŸ”— How it's made: <a href='https://huggingface.co/{initial_model}'><strong>{initial_model}</strong></a> was finetuned to create <a href='https://huggingface.co/{lora_model}'><strong>{lora_model}</strong></a>, then merged together to create <a href='https://huggingface.co/{merged_model}'><strong>{merged_model}</strong></a>.</p>
284
+ <p>πŸ“‰ Fine-tuning was performed using QLoRA techniques on the <a href='https://huggingface.co/datasets/{dataset}'><strong>{dataset}</strong></a> dataset. You can view training metrics on the <a href='https://huggingface.co/{lora_model}'><strong>QLoRa adapter HF Repo</strong></a>.</p>
285
+ <p>πŸ“Š All inputs/outputs are logged to Firebase to see how the model is doing. You can also leave a rating for each generated SQL the model produces, which gets sent to the database as well.</a></p>
286
+ """)
287
+
288
+ examples = gr.Examples([
289
+ ["What is the average, minimum, and maximum age of all singers from France?", "| stadium : stadium_id , location , name , capacity , highest , lowest , average | singer : singer_id , name , country , song_name , song_release_year , age , is_male | concert : concert_id , concert_name , theme , stadium_id , year | singer_in_concert : concert_id , singer_id | concert.stadium_id = stadium.stadium_id | singer_in_concert.singer_id = singer.singer_id | singer_in_concert.concert_id = concert.concert_id |"],
290
+ ["How many students have dogs?", "| student : stuid , lname , fname , age , sex , major , advisor , city_code | has_pet : stuid , petid | pets : petid , pettype , pet_age , weight | has_pet.stuid = student.stuid | has_pet.petid = pets.petid | pets.pettype = 'Dog' |"],
291
+ ], inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql], fn=generate, cache_examples=False if platform.system() == "Windows" or platform.system() == "Darwin" else True, outputs=output_box)
292
+
293
+ with gr.Accordion("More Examples", open=False):
294
+ examples = gr.Examples([
295
+ ["What is the average weight of pets of all students?", "| student : stuid , lname , fname , age , sex , major , advisor , city_code | has_pet : stuid , petid | pets : petid , pettype , pet_age , weight | has_pet.stuid = student.stuid | has_pet.petid = pets.petid |"],
296
+ ["How many male singers performed in concerts in the year 2023?", "| stadium : stadium_id , location , name , capacity , highest , lowest , average | singer : singer_id , name , country , song_name , song_release_year , age , is_male | concert : concert_id , concert_name , theme , stadium_id , year | singer_in_concert : concert_id , singer_id | concert.stadium_id = stadium.stadium_id | singer_in_concert.singer_id = singer.singer_id | singer_in_concert.concert_id = concert.concert_id |"],
297
+ ["For students who have pets, how many pets does each student have? List their ids instead of names.", "| student : stuid , lname , fname , age , sex , major , advisor , city_code | has_pet : stuid , petid | pets : petid , pettype , pet_age , weight | has_pet.stuid = student.stuid | has_pet.petid = pets.petid |"],
298
+ ["Show location and name for all stadiums with a capacity between 5000 and 10000.", "| stadium : stadium_id , location , name , capacity , highest , lowest , average | singer : singer_id , name , country , song_name , song_release_year , age , is_male | concert : concert_id , concert_name , theme , stadium_id , year | singer_in_concert : concert_id , singer_id | concert.stadium_id = stadium.stadium_id | singer_in_concert.singer_id = singer.singer_id | singer_in_concert.concert_id = concert.concert_id |"],
299
+ ["What are the number of concerts that occurred in the stadium with the largest capacity ?", "| stadium : stadium_id , location , name , capacity , highest , lowest , average | singer : singer_id , name , country , song_name , song_release_year , age , is_male | concert : concert_id , concert_name , theme , stadium_id , year | singer_in_concert : concert_id , singer_id | concert.stadium_id = stadium.stadium_id | singer_in_concert.singer_id = singer.singer_id | singer_in_concert.concert_id = concert.concert_id |"],
300
+ ["Which student has the oldest pet?", "| student : stuid , lname , fname , age , sex , major , advisor , city_code | has_pet : stuid , petid | pets : petid , pettype , pet_age , weight | has_pet.stuid = student.stuid | has_pet.petid = pets.petid |"],
301
+ ["List the names of all singers who performed in a concert with the theme 'Rock'", "| stadium : stadium_id , location , name , capacity , highest , lowest , average | singer : singer_id , name , country , song_name , song_release_year , age , is_male | concert : concert_id , concert_name , theme , stadium_id , year | singer_in_concert : concert_id , singer_id | concert.stadium_id = stadium.stadium_id | singer_in_concert.singer_id = singer.singer_id | singer_in_concert.concert_id = concert.concert_id |"],
302
+ ["List all students who don't have pets.", "| student : stuid , lname , fname , age , sex , major , advisor , city_code | has_pet : stuid , petid | pets : petid , pettype , pet_age , weight | has_pet.stuid = student.stuid | has_pet.petid = pets.petid |"],
303
+ ], inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql], fn=generate, cache_examples=False, outputs=output_box)
304
+
305
+
306
+ readme_content = requests.get(f"https://huggingface.co/{merged_model}/raw/main/README.md").text
307
+ readme_content = re.sub('---.*?---', '', readme_content, flags=re.DOTALL) #Remove YAML front matter
308
+
309
+ with gr.Accordion("πŸ“– Model Readme", open=True):
310
+ readme = gr.Markdown(
311
+ readme_content,
312
+ )
313
+
314
+ with gr.Accordion("Disabled Options:", open=False):
315
+ log = gr.Checkbox(label="Log to Firebase", value=True, interactive=False)
316
+
317
+ # When the button is clicked, call the generate function, inputs are taken from the UI elements, outputs are sent to outputs elements
318
+ run_button.click(fn=generate, inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql, log, num_return_sequences, num_beams, do_sample], outputs=output_box, api_name="txt2sql")
319
+ clear_button.add([input_text, db_info, output_box])
320
+
321
+ # Firebase code - for rating the generated SQL (remove if you don't want to use Firebase)
322
+ rate_up.click(fn=log_rating_to_firestore, inputs=[input_text, db_info, temperature, output_box, rate_up])
323
+ rate_down.click(fn=log_rating_to_firestore, inputs=[input_text, db_info, temperature, output_box, rate_down])
324
+
325
+ demo.queue(concurrency_count=1, max_size=20).launch(debug=True)