LeonceNsh commited on
Commit
281c128
·
verified ·
1 Parent(s): 11d6a16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -62
app.py CHANGED
@@ -55,7 +55,7 @@ def parse_query(nl_query):
55
  ]
56
 
57
  try:
58
- response = openai.chat.completions.create(
59
  model="gpt-4",
60
  messages=messages,
61
  temperature=0,
@@ -84,115 +84,222 @@ def execute_sql_query(sql_query):
84
  # Gradio Application UI
85
  # =========================
86
 
87
- with gr.Blocks() as demo:
88
- gr.Markdown("""
89
- # Use Text to SQL to analyze US Government contract data
 
 
 
90
 
91
- ## Instructions
 
 
 
 
 
 
92
 
93
- ### 1. **Describe the data you want**: e.g., `Show awards over 1M in CA`
94
- ### 2. **Use Example Queries**: Click on any example query button below to execute.
95
- ### 3. **Generate SQL**: Or, enter your own query and click "Generate SQL" to see the SQL query.
 
96
 
97
- ## Example Queries
98
- """)
 
 
 
 
 
 
 
 
 
99
 
 
 
100
  with gr.Row():
101
- with gr.Column(scale=1):
102
-
103
- gr.Markdown("### Click on an example query:")
104
- with gr.Row():
105
- btn_example1 = gr.Button("Retrieve the top 15 records from contract_data where basetype is Award Notice, awardee has at least 12 characters, and popcity has more than 5 characters. Exclude the fields sub_tier, popzip, awardnumber, basetype, popstate, active, popcountry, type, countrycode, and popstreetaddress")
106
- btn_example2 = gr.Button("Show top 10 departments by award amount")
107
- btn_example3 = gr.Button("SELECT department_ind_agency, CONCAT('$', ROUND(SUM(award), 0)) AS sum_award FROM contract_data GROUP BY department_ind_agency ORDER BY SUM(award) DESC LIMIT 25")
108
- btn_example4 = gr.Button("Retrieve the top 15 records from contract_data where basetype is Award Notice, awardee has at least 12 characters, and popcity has more than 5 characters. Exclude the fields sub_tier, popzip, awardnumber, basetype, popstate, active, popcountry, type, countrycode, and popstreetaddress")
109
- btn_example5 = gr.Button("SELECT awardnumber,awarddate,award, office, department_ind_agency,awardee from contract_data WHERE awardee IS NOT NULL AND award IS NOT NULL AND popcity IS NOT NULL AND award > 100000000 LIMIT 10;")
110
- btn_example6 = gr.Button("SELECT awardee, CONCAT('$', ROUND(SUM(award), 0)) AS sum_award FROM contract_data GROUP BY awardee ORDER BY SUM(award) DESC LIMIT 25")
 
 
 
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
 
 
 
 
 
 
113
  query_input = gr.Textbox(
114
  label="Your Query",
115
  placeholder='e.g., "What are the total awards over 1M in California?"',
116
- lines=1
117
  )
118
 
119
- btn_generate_sql = gr.Button("Generate SQL Query")
120
- sql_query_out = gr.Code(label="Generated SQL Query", language="sql")
121
- btn_execute_query = gr.Button("Execute Query")
122
- error_out = gr.Markdown("", visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  with gr.Column(scale=2):
124
- results_out = gr.Dataframe(label="Query Results", interactive=False)
 
125
 
 
126
  with gr.Tab("Dataset Schema"):
127
- gr.Markdown("### Dataset Schema")
128
- schema_display = gr.JSON(label="Schema", value=get_schema())
 
 
 
 
 
 
 
129
 
130
  # =========================
131
  # Event Functions
132
  # =========================
133
 
134
  def generate_sql(nl_query):
 
 
135
  sql_query, error = parse_query(nl_query)
136
- return sql_query, error
 
 
137
 
138
  def execute_query(sql_query):
 
 
139
  result_df, error = execute_sql_query(sql_query)
140
- return result_df, error
 
 
141
 
142
- def handle_example_click(example_query):
143
  if example_query.strip().upper().startswith("SELECT"):
144
  sql_query = example_query
145
  result_df, error = execute_sql_query(sql_query)
146
- return sql_query, "", result_df, error
 
 
147
  else:
148
  sql_query, error = parse_query(example_query)
149
  if error:
150
- return sql_query, error, None, error
151
  result_df, exec_error = execute_sql_query(sql_query)
152
- return sql_query, exec_error, result_df, exec_error
 
 
 
 
 
153
 
154
  # =========================
155
  # Button Click Event Handlers
156
  # =========================
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  btn_generate_sql.click(
159
  fn=generate_sql,
160
  inputs=query_input,
161
- outputs=[sql_query_out, error_out]
 
162
  )
163
 
 
164
  btn_execute_query.click(
165
  fn=execute_query,
166
  inputs=sql_query_out,
167
- outputs=[results_out, error_out]
 
168
  )
169
 
170
- btn_example1.click(
171
- fn=lambda: handle_example_click("Retrieve the top 15 records from contract_data where basetype is Award Notice, awardee has at least 12 characters, and popcity has more than 5 characters. Exclude the fields sub_tier, popzip, awardnumber, basetype, popstate, active, popcountry, type, countrycode, and popstreetaddress"),
172
- outputs=[sql_query_out, error_out, results_out, error_out]
173
- )
174
- btn_example2.click(
175
- fn=lambda: handle_example_click("Show top 10 departments by award amount. Round to zero decimal places."),
176
- outputs=[sql_query_out, error_out, results_out, error_out]
177
- )
178
- btn_example3.click(
179
- fn=lambda: handle_example_click("SELECT department_ind_agency, CONCAT('$', ROUND(SUM(award), 0)) AS sum_award FROM contract_data GROUP BY department_ind_agency ORDER BY SUM(award) DESC LIMIT 25"),
180
- outputs=[sql_query_out, error_out, results_out, error_out]
181
- )
182
- btn_example4.click(
183
- fn=lambda: handle_example_click("Retrieve the top 15 records from contract_data where basetype is Award Notice, awardee has at least 12 characters, and popcity has more than 5 characters. Exclude the fields sub_tier, popzip, awardnumber, basetype, popstate, active, popcountry, type, countrycode, and popstreetaddress"),
184
- outputs=[sql_query_out, error_out, results_out, error_out]
185
- )
186
- btn_example5.click(
187
- fn=lambda: handle_example_click("SELECT award, office, department_ind_agency,awardee from contract_data WHERE awardee IS NOT NULL AND award IS NOT NULL AND award > 100000000 LIMIT 10;"),
188
- outputs=[sql_query_out, error_out, results_out, error_out]
189
- )
190
- btn_example6.click(
191
- fn=lambda: handle_example_click("SELECT awardee, CONCAT('$', ROUND(SUM(award), 0)) AS sum_award FROM contract_data GROUP BY awardee ORDER BY SUM(award) DESC LIMIT 25"),
192
- outputs=[sql_query_out, error_out, results_out, error_out]
193
  )
194
 
195
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
- # Launch the Gradio App
198
- demo.launch()
 
55
  ]
56
 
57
  try:
58
+ response = openai.ChatCompletion.create(
59
  model="gpt-4",
60
  messages=messages,
61
  temperature=0,
 
84
  # Gradio Application UI
85
  # =========================
86
 
87
+ # Custom CSS for enhanced styling
88
+ custom_css = """
89
+ .gradio-container {
90
+ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
91
+ background-color: #f9f9f9;
92
+ }
93
 
94
+ .header {
95
+ background-color: #ff5a5f;
96
+ color: white;
97
+ padding: 20px;
98
+ text-align: center;
99
+ border-radius: 8px;
100
+ }
101
 
102
+ .button-primary {
103
+ background-color: #ff5a5f;
104
+ color: white;
105
+ }
106
 
107
+ .button-secondary {
108
+ background-color: #007A87;
109
+ color: white;
110
+ }
111
+
112
+ .footer {
113
+ text-align: center;
114
+ padding: 10px;
115
+ color: #555;
116
+ }
117
+ """
118
 
119
+ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
120
+ # Header Section
121
  with gr.Row():
122
+ gr.HTML(f"""
123
+ <div class="header">
124
+ <h1>US Government Contract Data Analyzer</h1>
125
+ <p>Convert natural language queries into SQL and explore contract data effortlessly.</p>
126
+ </div>
127
+ """)
128
+
129
+ # Main Content
130
+ with gr.Row():
131
+ with gr.Column(scale=1, min_width=300):
132
+ # Instructions
133
+ gr.Markdown("""
134
+ ## How to Use
135
 
136
+ 1. **Describe your query**: Enter a natural language description of the data you need.
137
+ 2. **Select an example**: Choose from predefined example queries for inspiration.
138
+ 3. **Generate SQL**: Click the button to convert your description into an SQL query.
139
+ 4. **Execute**: Run the SQL query to view the results.
140
+
141
+ ### Example Queries
142
+ """)
143
+
144
+ # Example Queries Dropdown
145
+ example_queries = [
146
+ "Show awards over 1M in CA",
147
+ "Retrieve the top 15 records from contract_data where basetype is Award Notice, awardee has at least 12 characters, and popcity has more than 5 characters. Exclude the fields sub_tier, popzip, awardnumber, basetype, popstate, active, popcountry, type, countrycode, and popstreetaddress",
148
+ "Show top 10 departments by award amount",
149
+ "SELECT department_ind_agency, CONCAT('$', ROUND(SUM(award), 0)) AS sum_award FROM contract_data GROUP BY department_ind_agency ORDER BY SUM(award) DESC LIMIT 25",
150
+ "SELECT awardnumber, awarddate, award, office, department_ind_agency, awardee FROM contract_data WHERE awardee IS NOT NULL AND award IS NOT NULL AND popcity IS NOT NULL AND award > 100000000 LIMIT 10;",
151
+ "SELECT awardee, CONCAT('$', ROUND(SUM(award), 0)) AS sum_award FROM contract_data GROUP BY awardee ORDER BY SUM(award) DESC LIMIT 25"
152
+ ]
153
+
154
+ example_dropdown = gr.Dropdown(
155
+ label="Select an Example Query",
156
+ choices=example_queries,
157
+ value=example_queries[0],
158
+ interactive=True
159
+ )
160
 
161
+ # Copy Button for Example Queries
162
+ with gr.Row():
163
+ btn_load_example = gr.Button("Load Example", variant="primary")
164
+ btn_copy_example = gr.Button("Copy Query", variant="secondary")
165
+
166
+ # User Input
167
  query_input = gr.Textbox(
168
  label="Your Query",
169
  placeholder='e.g., "What are the total awards over 1M in California?"',
170
+ lines=2
171
  )
172
 
173
+ # Generate and Execute Buttons
174
+ with gr.Row():
175
+ btn_generate_sql = gr.Button("Generate SQL Query", variant="primary")
176
+ btn_execute_query = gr.Button("Execute Query", variant="secondary")
177
+
178
+ # SQL Query Output with Copy Button
179
+ with gr.Row():
180
+ sql_query_out = gr.Code(label="Generated SQL Query", language="sql", interactive=False)
181
+ btn_copy_sql = gr.Button("Copy SQL", variant="secondary")
182
+
183
+ # Error Output
184
+ error_out = gr.Markdown("", visible=False, elem_id="error-output")
185
+
186
+ # Copy Button for Results
187
+ with gr.Row():
188
+ btn_copy_results = gr.Button("Copy Results", variant="secondary")
189
+
190
  with gr.Column(scale=2):
191
+ # Results Dataframe
192
+ results_out = gr.Dataframe(label="Query Results", interactive=False, height=400)
193
 
194
+ # Dataset Schema Tab
195
  with gr.Tab("Dataset Schema"):
196
+ with gr.Accordion("View Schema Details", open=True):
197
+ schema_display = gr.JSON(label="Schema", value=get_schema(), interactive=False)
198
+
199
+ # Footer
200
+ gr.HTML(f"""
201
+ <div class="footer">
202
+ <p>&copy; 2024 Your Company Name. All rights reserved.</p>
203
+ </div>
204
+ """)
205
 
206
  # =========================
207
  # Event Functions
208
  # =========================
209
 
210
  def generate_sql(nl_query):
211
+ if not nl_query.strip():
212
+ return "", "Please enter a valid query.", None
213
  sql_query, error = parse_query(nl_query)
214
+ if error:
215
+ return "", error, None
216
+ return sql_query, "", None
217
 
218
  def execute_query(sql_query):
219
+ if not sql_query.strip():
220
+ return None, "No SQL query to execute."
221
  result_df, error = execute_sql_query(sql_query)
222
+ if error:
223
+ return None, error
224
+ return result_df, ""
225
 
226
+ def load_example(example_query):
227
  if example_query.strip().upper().startswith("SELECT"):
228
  sql_query = example_query
229
  result_df, error = execute_sql_query(sql_query)
230
+ if error:
231
+ return "", error, None
232
+ return sql_query, "", result_df
233
  else:
234
  sql_query, error = parse_query(example_query)
235
  if error:
236
+ return "", error, None
237
  result_df, exec_error = execute_sql_query(sql_query)
238
+ if exec_error:
239
+ return sql_query, exec_error, None
240
+ return sql_query, "", result_df
241
+
242
+ def copy_text(text):
243
+ return text # Gradio handles the copy functionality internally
244
 
245
  # =========================
246
  # Button Click Event Handlers
247
  # =========================
248
 
249
+ # Load Example Query
250
+ btn_load_example.click(
251
+ fn=load_example,
252
+ inputs=example_dropdown,
253
+ outputs=[sql_query_out, error_out, results_out],
254
+ show_progress=True
255
+ )
256
+
257
+ # Copy Example Query to Input
258
+ btn_copy_example.click(
259
+ fn=lambda x: x,
260
+ inputs=example_dropdown,
261
+ outputs=query_input
262
+ )
263
+
264
+ # Generate SQL Query
265
  btn_generate_sql.click(
266
  fn=generate_sql,
267
  inputs=query_input,
268
+ outputs=[sql_query_out, error_out, results_out],
269
+ show_progress=True
270
  )
271
 
272
+ # Execute SQL Query
273
  btn_execute_query.click(
274
  fn=execute_query,
275
  inputs=sql_query_out,
276
+ outputs=[results_out, error_out],
277
+ show_progress=True
278
  )
279
 
280
+ # Copy SQL Query
281
+ btn_copy_sql.click(
282
+ fn=copy_text,
283
+ inputs=sql_query_out,
284
+ outputs=None,
285
+ _js="(text) => { navigator.clipboard.writeText(text); }"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  )
287
 
288
+ # Copy Results
289
+ btn_copy_results.click(
290
+ fn=lambda df: df.to_csv(index=False),
291
+ inputs=results_out,
292
+ outputs=None,
293
+ _js="""
294
+ (csv) => {
295
+ navigator.clipboard.writeText(csv).then(function() {
296
+ alert('Results copied to clipboard!');
297
+ }, function(err) {
298
+ alert('Could not copy results: ', err);
299
+ });
300
+ }
301
+ """
302
+ )
303
 
304
+ # Launch the Gradio App with a larger server timeout and allow queueing
305
+ demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)