richardr1126 commited on
Commit
9afbbb8
β€’
1 Parent(s): 8afc4f5
Files changed (6) hide show
  1. .gitattributes +34 -34
  2. .gitignore +3 -3
  3. README.md +51 -51
  4. app-ngrok.py +221 -221
  5. app.py +324 -324
  6. requirements.txt +12 -12
.gitattributes CHANGED
@@ -1,34 +1,34 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tflite filter=lfs diff=lfs merge=lfs -text
29
- *.tgz filter=lfs diff=lfs merge=lfs -text
30
- *.wasm filter=lfs diff=lfs merge=lfs -text
31
- *.xz filter=lfs diff=lfs merge=lfs -text
32
- *.zip filter=lfs diff=lfs merge=lfs -text
33
- *.zst filter=lfs diff=lfs merge=lfs -text
34
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore CHANGED
@@ -1,4 +1,4 @@
1
- venv/
2
- .venv/
3
- env/
4
  .env
 
1
+ venv/
2
+ .venv/
3
+ env/
4
  .env
README.md CHANGED
@@ -1,52 +1,52 @@
1
- ---
2
- title: SQL Skeleton WizardCoder Demo
3
- emoji: πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ
4
- colorFrom: gray
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 3.37.0
8
- app_file: app.py
9
- pinned: true
10
- license: bigcode-openrail-m
11
- tags:
12
- - sql
13
- - spider
14
- - text-to-sql
15
- - sql demo
16
- ---
17
-
18
- ### Spider Skeleton WizardCoder Demo
19
-
20
- A demo of [Spider Skeleton Wizard Coder](https://huggingface.co/richardr1126/spider-skeleton-wizard-coder-merged/).
21
-
22
- ## Citations
23
-
24
- ```
25
- @misc{luo2023wizardcoder,
26
- title={WizardCoder: Empowering Code Large Language Models with Evol-Instruct},
27
- author={Ziyang Luo and Can Xu and Pu Zhao and Qingfeng Sun and Xiubo Geng and Wenxiang Hu and Chongyang Tao and Jing Ma and Qingwei Lin and Daxin Jiang},
28
- year={2023},
29
- }
30
- ```
31
- ```
32
- @article{yu2018spider,
33
- title={Spider: A large-scale human-labeled dataset for complex and cross-domain semantic parsing and text-to-sql task},
34
- author={Yu, Tao and Zhang, Rui and Yang, Kai and Yasunaga, Michihiro and Wang, Dongxu and Li, Zifan and Ma, James and Li, Irene and Yao, Qingning and Roman, Shanelle and others},
35
- journal={arXiv preprint arXiv:1809.08887},
36
- year={2018}
37
- }
38
- ```
39
- ```
40
- @article{dettmers2023qlora,
41
- title={QLoRA: Efficient Finetuning of Quantized LLMs},
42
- author={Dettmers, Tim and Pagnoni, Artidoro and Holtzman, Ari and Zettlemoyer, Luke},
43
- journal={arXiv preprint arXiv:2305.14314},
44
- year={2023}
45
- }
46
- ```
47
-
48
- ## Disclaimer
49
-
50
- The resources, including code, data, and model weights, associated with this project are restricted for academic research purposes only and cannot be used for commercial purposes. The content produced by any version of WizardCoder is influenced by uncontrollable variables such as randomness, and therefore, the accuracy of the output cannot be guaranteed by this project. This project does not accept any legal liability for the content of the model output, nor does it assume responsibility for any losses incurred due to the use of associated resources and output results.
51
-
52
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: SQL Skeleton WizardCoder Demo
3
+ emoji: πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ
4
+ colorFrom: gray
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 3.37.0
8
+ app_file: app.py
9
+ pinned: true
10
+ license: bigcode-openrail-m
11
+ tags:
12
+ - sql
13
+ - spider
14
+ - text-to-sql
15
+ - sql demo
16
+ ---
17
+
18
+ ### Spider Skeleton WizardCoder Demo
19
+
20
+ A demo of [Spider Skeleton Wizard Coder](https://huggingface.co/richardr1126/spider-skeleton-wizard-coder-merged/).
21
+
22
+ ## Citations
23
+
24
+ ```
25
+ @misc{luo2023wizardcoder,
26
+ title={WizardCoder: Empowering Code Large Language Models with Evol-Instruct},
27
+ author={Ziyang Luo and Can Xu and Pu Zhao and Qingfeng Sun and Xiubo Geng and Wenxiang Hu and Chongyang Tao and Jing Ma and Qingwei Lin and Daxin Jiang},
28
+ year={2023},
29
+ }
30
+ ```
31
+ ```
32
+ @article{yu2018spider,
33
+ title={Spider: A large-scale human-labeled dataset for complex and cross-domain semantic parsing and text-to-sql task},
34
+ author={Yu, Tao and Zhang, Rui and Yang, Kai and Yasunaga, Michihiro and Wang, Dongxu and Li, Zifan and Ma, James and Li, Irene and Yao, Qingning and Roman, Shanelle and others},
35
+ journal={arXiv preprint arXiv:1809.08887},
36
+ year={2018}
37
+ }
38
+ ```
39
+ ```
40
+ @article{dettmers2023qlora,
41
+ title={QLoRA: Efficient Finetuning of Quantized LLMs},
42
+ author={Dettmers, Tim and Pagnoni, Artidoro and Holtzman, Ari and Zettlemoyer, Luke},
43
+ journal={arXiv preprint arXiv:2305.14314},
44
+ year={2023}
45
+ }
46
+ ```
47
+
48
+ ## Disclaimer
49
+
50
+ The resources, including code, data, and model weights, associated with this project are restricted for academic research purposes only and cannot be used for commercial purposes. The content produced by any version of WizardCoder is influenced by uncontrollable variables such as randomness, and therefore, the accuracy of the output cannot be guaranteed by this project. This project does not accept any legal liability for the content of the model output, nor does it assume responsibility for any losses incurred due to the use of associated resources and output results.
51
+
52
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app-ngrok.py CHANGED
@@ -1,222 +1,222 @@
1
- import os
2
- import gradio as gr
3
- import sqlparse
4
- import requests
5
- from time import sleep
6
- import re
7
- import platform
8
- # Additional Firebase imports
9
- import firebase_admin
10
- from firebase_admin import credentials, firestore
11
- import json
12
- import base64
13
-
14
- print(f"Running on {platform.system()}")
15
-
16
- if platform.system() == "Windows" or platform.system() == "Darwin":
17
- from dotenv import load_dotenv
18
- load_dotenv()
19
-
20
- quantized_model = "richardr1126/spider-skeleton-wizard-coder-ggml"
21
- merged_model = "richardr1126/spider-skeleton-wizard-coder-merged"
22
- initial_model = "WizardLM/WizardCoder-15B-V1.0"
23
- lora_model = "richardr1126/spider-skeleton-wizard-coder-qlora"
24
- dataset = "richardr1126/spider-skeleton-context-instruct"
25
-
26
- # Firebase code
27
- # Initialize Firebase
28
- base64_string = os.getenv('FIREBASE')
29
- base64_bytes = base64_string.encode('utf-8')
30
- json_bytes = base64.b64decode(base64_bytes)
31
- json_data = json_bytes.decode('utf-8')
32
-
33
- firebase_auth = json.loads(json_data)
34
-
35
- # Load credentials and initialize Firestore
36
- cred = credentials.Certificate(firebase_auth)
37
- firebase_admin.initialize_app(cred)
38
- db = firestore.client()
39
-
40
- def log_message_to_firestore(input_message, db_info, temperature, response_text):
41
- doc_ref = db.collection('logs').document()
42
- log_data = {
43
- 'timestamp': firestore.SERVER_TIMESTAMP,
44
- 'temperature': temperature,
45
- 'db_info': db_info,
46
- 'input': input_message,
47
- 'output': response_text,
48
- }
49
- doc_ref.set(log_data)
50
-
51
- rated_outputs = set() # set to store already rated outputs
52
-
53
- def log_rating_to_firestore(input_message, db_info, temperature, response_text, rating):
54
- global rated_outputs
55
- output_id = f"{input_message} {db_info} {response_text} {temperature}"
56
-
57
- if output_id in rated_outputs:
58
- gr.Warning("You've already rated this output!")
59
- return
60
- if not input_message or not response_text or not rating:
61
- gr.Info("You haven't asked a question yet!")
62
- return
63
-
64
- rated_outputs.add(output_id)
65
-
66
- doc_ref = db.collection('ratings').document()
67
- log_data = {
68
- 'timestamp': firestore.SERVER_TIMESTAMP,
69
- 'temperature': temperature,
70
- 'db_info': db_info,
71
- 'input': input_message,
72
- 'output': response_text,
73
- 'rating': rating,
74
- }
75
- doc_ref.set(log_data)
76
- gr.Info("Thanks for your feedback!")
77
- # End Firebase code
78
-
79
- def format(text):
80
- # Split the text by "|", and get the last element in the list which should be the final query
81
- try:
82
- final_query = text.split("|")[1].strip()
83
- except Exception:
84
- final_query = text
85
-
86
- try:
87
- # Attempt to format SQL query using sqlparse
88
- formatted_query = sqlparse.format(final_query, reindent=True, keyword_case='upper')
89
- except Exception:
90
- # If formatting fails, use the original, unformatted query
91
- formatted_query = final_query
92
-
93
- # Convert SQL to markdown (not required, but just to show how to use the markdown module)
94
- final_query_markdown = f"{formatted_query}"
95
-
96
- return final_query_markdown
97
-
98
- def generate(input_message: str, db_info="", temperature=0.2, top_p=0.9, top_k=0, repetition_penalty=1.08, format_sql=True, stop_sequence="###", log=False):
99
- # Format the user's input message
100
- 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"
101
-
102
- url = os.getenv("KOBOLDCPP_API_URL")
103
- stop_sequence = stop_sequence.split(",")
104
- stop = ["###"] + stop_sequence
105
- payload = {
106
- "prompt": messages,
107
- "temperature": temperature,
108
- "top_p": top_p,
109
- "top_k": top_k,
110
- "top_a": 0,
111
- "n": 1,
112
- "max_context_length": 2048,
113
- "max_length": 512,
114
- "rep_pen": repetition_penalty,
115
- "sampler_order": [6,0,1,3,4,2,5],
116
- "stop_sequence": stop,
117
- }
118
- headers = {
119
- "Content-Type": "application/json",
120
- "ngrok-skip-browser-warning": "1" # added this line
121
- }
122
-
123
- for _ in range(3): # Try 3 times
124
- try:
125
- response = requests.post(url, json=payload, headers=headers)
126
- response_text = response.json()["results"][0]["text"]
127
- response_text = response_text.replace("\n", "").replace("\t", " ")
128
- if response_text and response_text[-1] == ".":
129
- response_text = response_text[:-1]
130
-
131
- output = format(response_text) if format_sql else response_text
132
-
133
- if log:
134
- # Log the request to Firestore
135
- log_message_to_firestore(input_message, db_info, temperature, output if format_sql else response_text)
136
-
137
- return output
138
-
139
-
140
- except Exception as e:
141
- print(f'Error occurred: {str(e)}')
142
- print('Waiting for 10 seconds before retrying...')
143
- gr.Warning("Error occurred, retrying, the sever may be down...")
144
- sleep(10)
145
-
146
- # Gradio UI Code
147
- with gr.Blocks(theme='gradio/soft') as demo:
148
- # Elements stack vertically by default just define elements in order you want them to stack
149
- header = gr.HTML("""
150
- <h1 style="text-align: center">SQL Skeleton WizardCoder Demo</h1>
151
- <h3 style="text-align: center">πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ Generate SQL queries from Natural Language πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ</h3>
152
- <div style="max-width: 450px; margin: auto; text-align: center">
153
- <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>
154
- </div>
155
- """)
156
-
157
- output_box = gr.Code(label="Generated SQL", lines=2, interactive=False)
158
-
159
- with gr.Row():
160
- rate_up = gr.Button("πŸ‘", variant="secondary")
161
- rate_down = gr.Button("πŸ‘Ž", variant="secondary")
162
-
163
- input_text = gr.Textbox(lines=3, placeholder='Write your question here...', label='NL Input')
164
- 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')
165
- format_sql = gr.Checkbox(label="Format SQL + Remove Skeleton", value=True, interactive=True)
166
-
167
- with gr.Row():
168
- run_button = gr.Button("Generate SQL", variant="primary")
169
- clear_button = gr.ClearButton(variant="secondary")
170
-
171
- with gr.Accordion("Options", open=False):
172
- temperature = gr.Slider(label="Temperature", minimum=0.0, maximum=1.0, value=0.2, step=0.1)
173
- top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.0, maximum=1.0, value=0.9, step=0.01)
174
- top_k = gr.Slider(label="Top-k", minimum=0, maximum=200, value=0, step=1)
175
- repetition_penalty = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.08, step=0.01)
176
- stop_sequence = gr.Textbox(lines=1, value="Explanation,Note", label='Extra Stop Sequence')
177
-
178
- info = gr.HTML(f"""
179
- <p>🌐 Leveraging the <a href='https://huggingface.co/{quantized_model}'><strong>4-bit GGML version</strong></a> of <a href='https://huggingface.co/{merged_model}'><strong>{merged_model}</strong></a> model.</p>
180
- <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>
181
- <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>
182
- <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>
183
- """)
184
-
185
- examples = gr.Examples([
186
- ["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 |"],
187
- ["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' |"],
188
- ], inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql, stop_sequence], fn=generate, cache_examples=False if platform.system() == "Windows" or platform.system() == "Darwin" else True, outputs=output_box)
189
-
190
- with gr.Accordion("More Examples", open=False):
191
- examples = gr.Examples([
192
- ["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 |"],
193
- ["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 |"],
194
- ["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 |"],
195
- ["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 |"],
196
- ["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 |"],
197
- ["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 |"],
198
- ["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 |"],
199
- ["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 |"],
200
- ], inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql, stop_sequence], fn=generate, cache_examples=False, outputs=output_box)
201
-
202
-
203
- readme_content = requests.get(f"https://huggingface.co/{merged_model}/raw/main/README.md").text
204
- readme_content = re.sub('---.*?---', '', readme_content, flags=re.DOTALL) #Remove YAML front matter
205
-
206
- with gr.Accordion("πŸ“– Model Readme", open=True):
207
- readme = gr.Markdown(
208
- readme_content,
209
- )
210
-
211
- with gr.Accordion("Disabled Options:", open=False):
212
- log = gr.Checkbox(label="Log to Firebase", value=True, interactive=False)
213
-
214
- # When the button is clicked, call the generate function, inputs are taken from the UI elements, outputs are sent to outputs elements
215
- run_button.click(fn=generate, inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql, stop_sequence, log], outputs=output_box, api_name="txt2sql")
216
- clear_button.add([input_text, db_info, output_box])
217
-
218
- # Firebase code - for rating the generated SQL (remove if you don't want to use Firebase)
219
- rate_up.click(fn=log_rating_to_firestore, inputs=[input_text, db_info, temperature, output_box, rate_up])
220
- rate_down.click(fn=log_rating_to_firestore, inputs=[input_text, db_info, temperature, output_box, rate_down])
221
-
222
  demo.queue(concurrency_count=1, max_size=20).launch(debug=True)
 
1
+ import os
2
+ import gradio as gr
3
+ import sqlparse
4
+ import requests
5
+ from time import sleep
6
+ import re
7
+ import platform
8
+ # Additional Firebase imports
9
+ import firebase_admin
10
+ from firebase_admin import credentials, firestore
11
+ import json
12
+ import base64
13
+
14
+ print(f"Running on {platform.system()}")
15
+
16
+ if platform.system() == "Windows" or platform.system() == "Darwin":
17
+ from dotenv import load_dotenv
18
+ load_dotenv()
19
+
20
+ quantized_model = "richardr1126/spider-skeleton-wizard-coder-ggml"
21
+ merged_model = "richardr1126/spider-skeleton-wizard-coder-merged"
22
+ initial_model = "WizardLM/WizardCoder-15B-V1.0"
23
+ lora_model = "richardr1126/spider-skeleton-wizard-coder-qlora"
24
+ dataset = "richardr1126/spider-skeleton-context-instruct"
25
+
26
+ # Firebase code
27
+ # Initialize Firebase
28
+ base64_string = os.getenv('FIREBASE')
29
+ base64_bytes = base64_string.encode('utf-8')
30
+ json_bytes = base64.b64decode(base64_bytes)
31
+ json_data = json_bytes.decode('utf-8')
32
+
33
+ firebase_auth = json.loads(json_data)
34
+
35
+ # Load credentials and initialize Firestore
36
+ cred = credentials.Certificate(firebase_auth)
37
+ firebase_admin.initialize_app(cred)
38
+ db = firestore.client()
39
+
40
+ def log_message_to_firestore(input_message, db_info, temperature, response_text):
41
+ doc_ref = db.collection('logs').document()
42
+ log_data = {
43
+ 'timestamp': firestore.SERVER_TIMESTAMP,
44
+ 'temperature': temperature,
45
+ 'db_info': db_info,
46
+ 'input': input_message,
47
+ 'output': response_text,
48
+ }
49
+ doc_ref.set(log_data)
50
+
51
+ rated_outputs = set() # set to store already rated outputs
52
+
53
+ def log_rating_to_firestore(input_message, db_info, temperature, response_text, rating):
54
+ global rated_outputs
55
+ output_id = f"{input_message} {db_info} {response_text} {temperature}"
56
+
57
+ if output_id in rated_outputs:
58
+ gr.Warning("You've already rated this output!")
59
+ return
60
+ if not input_message or not response_text or not rating:
61
+ gr.Info("You haven't asked a question yet!")
62
+ return
63
+
64
+ rated_outputs.add(output_id)
65
+
66
+ doc_ref = db.collection('ratings').document()
67
+ log_data = {
68
+ 'timestamp': firestore.SERVER_TIMESTAMP,
69
+ 'temperature': temperature,
70
+ 'db_info': db_info,
71
+ 'input': input_message,
72
+ 'output': response_text,
73
+ 'rating': rating,
74
+ }
75
+ doc_ref.set(log_data)
76
+ gr.Info("Thanks for your feedback!")
77
+ # End Firebase code
78
+
79
+ def format(text):
80
+ # Split the text by "|", and get the last element in the list which should be the final query
81
+ try:
82
+ final_query = text.split("|")[1].strip()
83
+ except Exception:
84
+ final_query = text
85
+
86
+ try:
87
+ # Attempt to format SQL query using sqlparse
88
+ formatted_query = sqlparse.format(final_query, reindent=True, keyword_case='upper')
89
+ except Exception:
90
+ # If formatting fails, use the original, unformatted query
91
+ formatted_query = final_query
92
+
93
+ # Convert SQL to markdown (not required, but just to show how to use the markdown module)
94
+ final_query_markdown = f"{formatted_query}"
95
+
96
+ return final_query_markdown
97
+
98
+ def generate(input_message: str, db_info="", temperature=0.2, top_p=0.9, top_k=0, repetition_penalty=1.08, format_sql=True, stop_sequence="###", log=False):
99
+ # Format the user's input message
100
+ 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"
101
+
102
+ url = os.getenv("KOBOLDCPP_API_URL")
103
+ stop_sequence = stop_sequence.split(",")
104
+ stop = ["###"] + stop_sequence
105
+ payload = {
106
+ "prompt": messages,
107
+ "temperature": temperature,
108
+ "top_p": top_p,
109
+ "top_k": top_k,
110
+ "top_a": 0,
111
+ "n": 1,
112
+ "max_context_length": 2048,
113
+ "max_length": 512,
114
+ "rep_pen": repetition_penalty,
115
+ "sampler_order": [6,0,1,3,4,2,5],
116
+ "stop_sequence": stop,
117
+ }
118
+ headers = {
119
+ "Content-Type": "application/json",
120
+ "ngrok-skip-browser-warning": "1" # added this line
121
+ }
122
+
123
+ for _ in range(3): # Try 3 times
124
+ try:
125
+ response = requests.post(url, json=payload, headers=headers)
126
+ response_text = response.json()["results"][0]["text"]
127
+ response_text = response_text.replace("\n", "").replace("\t", " ")
128
+ if response_text and response_text[-1] == ".":
129
+ response_text = response_text[:-1]
130
+
131
+ output = format(response_text) if format_sql else response_text
132
+
133
+ if log:
134
+ # Log the request to Firestore
135
+ log_message_to_firestore(input_message, db_info, temperature, output if format_sql else response_text)
136
+
137
+ return output
138
+
139
+
140
+ except Exception as e:
141
+ print(f'Error occurred: {str(e)}')
142
+ print('Waiting for 10 seconds before retrying...')
143
+ gr.Warning("Error occurred, retrying, the sever may be down...")
144
+ sleep(10)
145
+
146
+ # Gradio UI Code
147
+ with gr.Blocks(theme='gradio/soft') as demo:
148
+ # Elements stack vertically by default just define elements in order you want them to stack
149
+ header = gr.HTML("""
150
+ <h1 style="text-align: center">SQL Skeleton WizardCoder Demo</h1>
151
+ <h3 style="text-align: center">πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ Generate SQL queries from Natural Language πŸ•·οΈβ˜ οΈπŸ§™β€β™‚οΈ</h3>
152
+ <div style="max-width: 450px; margin: auto; text-align: center">
153
+ <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>
154
+ </div>
155
+ """)
156
+
157
+ output_box = gr.Code(label="Generated SQL", lines=2, interactive=False)
158
+
159
+ with gr.Row():
160
+ rate_up = gr.Button("πŸ‘", variant="secondary")
161
+ rate_down = gr.Button("πŸ‘Ž", variant="secondary")
162
+
163
+ input_text = gr.Textbox(lines=3, placeholder='Write your question here...', label='NL Input')
164
+ 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')
165
+ format_sql = gr.Checkbox(label="Format SQL + Remove Skeleton", value=True, interactive=True)
166
+
167
+ with gr.Row():
168
+ run_button = gr.Button("Generate SQL", variant="primary")
169
+ clear_button = gr.ClearButton(variant="secondary")
170
+
171
+ with gr.Accordion("Options", open=False):
172
+ temperature = gr.Slider(label="Temperature", minimum=0.0, maximum=1.0, value=0.2, step=0.1)
173
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.0, maximum=1.0, value=0.9, step=0.01)
174
+ top_k = gr.Slider(label="Top-k", minimum=0, maximum=200, value=0, step=1)
175
+ repetition_penalty = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.08, step=0.01)
176
+ stop_sequence = gr.Textbox(lines=1, value="Explanation,Note", label='Extra Stop Sequence')
177
+
178
+ info = gr.HTML(f"""
179
+ <p>🌐 Leveraging the <a href='https://huggingface.co/{quantized_model}'><strong>4-bit GGML version</strong></a> of <a href='https://huggingface.co/{merged_model}'><strong>{merged_model}</strong></a> model.</p>
180
+ <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>
181
+ <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>
182
+ <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>
183
+ """)
184
+
185
+ examples = gr.Examples([
186
+ ["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 |"],
187
+ ["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' |"],
188
+ ], inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql, stop_sequence], fn=generate, cache_examples=False if platform.system() == "Windows" or platform.system() == "Darwin" else True, outputs=output_box)
189
+
190
+ with gr.Accordion("More Examples", open=False):
191
+ examples = gr.Examples([
192
+ ["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 |"],
193
+ ["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 |"],
194
+ ["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 |"],
195
+ ["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 |"],
196
+ ["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 |"],
197
+ ["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 |"],
198
+ ["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 |"],
199
+ ["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 |"],
200
+ ], inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql, stop_sequence], fn=generate, cache_examples=False, outputs=output_box)
201
+
202
+
203
+ readme_content = requests.get(f"https://huggingface.co/{merged_model}/raw/main/README.md").text
204
+ readme_content = re.sub('---.*?---', '', readme_content, flags=re.DOTALL) #Remove YAML front matter
205
+
206
+ with gr.Accordion("πŸ“– Model Readme", open=True):
207
+ readme = gr.Markdown(
208
+ readme_content,
209
+ )
210
+
211
+ with gr.Accordion("Disabled Options:", open=False):
212
+ log = gr.Checkbox(label="Log to Firebase", value=True, interactive=False)
213
+
214
+ # When the button is clicked, call the generate function, inputs are taken from the UI elements, outputs are sent to outputs elements
215
+ run_button.click(fn=generate, inputs=[input_text, db_info, temperature, top_p, top_k, repetition_penalty, format_sql, stop_sequence, log], outputs=output_box, api_name="txt2sql")
216
+ clear_button.add([input_text, db_info, output_box])
217
+
218
+ # Firebase code - for rating the generated SQL (remove if you don't want to use Firebase)
219
+ rate_up.click(fn=log_rating_to_firestore, inputs=[input_text, db_info, temperature, output_box, rate_up])
220
+ rate_down.click(fn=log_rating_to_firestore, inputs=[input_text, db_info, temperature, output_box, rate_down])
221
+
222
  demo.queue(concurrency_count=1, max_size=20).launch(debug=True)
app.py CHANGED
@@ -1,325 +1,325 @@
1
- import os
2
- import gradio as gr
3
- import sqlite3
4
- import sqlparse
5
- import requests
6
- from time import sleep
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
- if platform.system() == "Windows" or platform.system() == "Darwin":
26
- from dotenv import load_dotenv
27
- load_dotenv()
28
-
29
- quantized_model = "richardr1126/spider-skeleton-wizard-coder-8bit"
30
- merged_model = "richardr1126/spider-skeleton-wizard-coder-merged"
31
- initial_model = "WizardLM/WizardCoder-15B-V1.0"
32
- lora_model = "richardr1126/spider-skeleton-wizard-coder-qlora"
33
- dataset = "richardr1126/spider-skeleton-context-instruct"
34
-
35
- model_name = os.getenv("HF_MODEL_NAME", None)
36
- tok = AutoTokenizer.from_pretrained(model_name)
37
-
38
- max_new_tokens = 1024
39
-
40
- print(f"Starting to load the model {model_name}")
41
-
42
- m = AutoModelForCausalLM.from_pretrained(
43
- model_name,
44
- device_map=0,
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)
 
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
+ if platform.system() == "Windows" or platform.system() == "Darwin":
26
+ from dotenv import load_dotenv
27
+ load_dotenv()
28
+
29
+ quantized_model = "richardr1126/spider-skeleton-wizard-coder-8bit"
30
+ merged_model = "richardr1126/spider-skeleton-wizard-coder-merged"
31
+ initial_model = "WizardLM/WizardCoder-15B-V1.0"
32
+ lora_model = "richardr1126/spider-skeleton-wizard-coder-qlora"
33
+ dataset = "richardr1126/spider-skeleton-context-instruct"
34
+
35
+ model_name = os.getenv("HF_MODEL_NAME", None)
36
+ tok = AutoTokenizer.from_pretrained(model_name)
37
+
38
+ max_new_tokens = 1024
39
+
40
+ print(f"Starting to load the model {model_name}")
41
+
42
+ m = AutoModelForCausalLM.from_pretrained(
43
+ model_name,
44
+ device_map=0,
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)
requirements.txt CHANGED
@@ -1,12 +1,12 @@
1
- einops
2
- gradio
3
- torch
4
- numpy
5
- sentencepiece
6
- bitsandbytes
7
- scipy
8
- transformers
9
- accelerate
10
- sqlparse
11
- firebase_admin
12
- openai
 
1
+ einops
2
+ gradio
3
+ numpy
4
+ sentencepiece
5
+ bitsandbytes
6
+ scipy
7
+ transformers
8
+ accelerate
9
+ sqlparse
10
+ firebase_admin
11
+ openai
12
+ python-dotenv