shukdevdattaEX commited on
Commit
84b21bc
·
verified ·
1 Parent(s): b7c4fee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -10
app.py CHANGED
@@ -2,6 +2,7 @@ from groq import Groq
2
  from pydantic import BaseModel
3
  import json
4
  import gradio as gr
 
5
 
6
  class ValidationStatus(BaseModel):
7
  is_valid: bool
@@ -19,14 +20,41 @@ class SQLQueryGeneration(BaseModel):
19
  execution_results: str
20
  optimization_notes: list[str]
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def generate_sql_query(api_key, user_query):
23
  """Generate SQL query from natural language using GROQ API"""
24
  try:
25
  if not api_key:
26
- return "Error: Please enter your GROQ API key", "", "", "", "", ""
27
 
28
  if not user_query:
29
- return "Error: Please enter a query description", "", "", "", "", ""
30
 
31
  client = Groq(api_key=api_key)
32
 
@@ -41,12 +69,24 @@ After generating the SQL query, you must:
41
  2. Populate the table with realistic sample data that demonstrates the query's functionality
42
  3. Execute the generated SQL query against the sample table
43
  4. Display the SQL table structure and data clearly
44
- 5. Show the query execution results
 
 
 
 
 
 
 
 
 
 
 
 
45
  Always present your response in this order:
46
  - Generated SQL query with syntax explanation
47
  - Table schema (CREATE TABLE statement)
48
  - Sample data (INSERT statements or table visualization)
49
- - Query execution results
50
  - Any relevant notes about assumptions made or query optimization suggestions""",
51
  },
52
  {
@@ -87,18 +127,21 @@ Execution Notes:
87
  Optimization Notes:
88
  {chr(10).join(f"- {note}" for note in sql_query_generation.optimization_notes)}"""
89
 
 
 
 
90
  return (
91
  sql_query_generation.query,
92
  metadata,
93
  sql_query_generation.table_schema,
94
  sql_query_generation.sample_data,
95
- sql_query_generation.execution_results,
96
  validation_text
97
  )
98
 
99
  except Exception as e:
100
  error_msg = f"Error: {str(e)}"
101
- return error_msg, "", "", "", "", ""
102
 
103
  # Create Gradio interface
104
  with gr.Blocks(title="SQL Query Generator", theme=gr.themes.Soft()) as demo:
@@ -173,9 +216,14 @@ with gr.Blocks(title="SQL Query Generator", theme=gr.themes.Soft()) as demo:
173
  )
174
 
175
  with gr.Row():
176
- execution_output = gr.Textbox(
177
- label="Execution Results",
178
- lines=10
 
 
 
 
 
179
  )
180
 
181
  generate_btn.click(
@@ -202,7 +250,7 @@ with gr.Blocks(title="SQL Query Generator", theme=gr.themes.Soft()) as demo:
202
  The app will provide:
203
  - A validated SQL query
204
  - Table schema and sample data
205
- - Execution results
206
  - Optimization suggestions
207
  """
208
  )
 
2
  from pydantic import BaseModel
3
  import json
4
  import gradio as gr
5
+ import pandas as pd
6
 
7
  class ValidationStatus(BaseModel):
8
  is_valid: bool
 
20
  execution_results: str
21
  optimization_notes: list[str]
22
 
23
+ def parse_execution_results_to_dataframe(execution_results):
24
+ """Convert text-based table results to pandas DataFrame"""
25
+ try:
26
+ lines = execution_results.strip().split('\n')
27
+ if len(lines) < 3:
28
+ return None
29
+
30
+ # Extract header
31
+ header_line = lines[0]
32
+ headers = [col.strip() for col in header_line.split('|')]
33
+
34
+ # Extract data rows (skip separator line)
35
+ data_rows = []
36
+ for line in lines[2:]:
37
+ if line.strip() and not line.strip().startswith('-'):
38
+ row = [cell.strip() for cell in line.split('|')]
39
+ if len(row) == len(headers):
40
+ data_rows.append(row)
41
+
42
+ if data_rows:
43
+ df = pd.DataFrame(data_rows, columns=headers)
44
+ return df
45
+ return None
46
+ except Exception as e:
47
+ print(f"Error parsing results: {e}")
48
+ return None
49
+
50
  def generate_sql_query(api_key, user_query):
51
  """Generate SQL query from natural language using GROQ API"""
52
  try:
53
  if not api_key:
54
+ return "Error: Please enter your GROQ API key", "", "", "", None, ""
55
 
56
  if not user_query:
57
+ return "Error: Please enter a query description", "", "", "", None, ""
58
 
59
  client = Groq(api_key=api_key)
60
 
 
69
  2. Populate the table with realistic sample data that demonstrates the query's functionality
70
  3. Execute the generated SQL query against the sample table
71
  4. Display the SQL table structure and data clearly
72
+ 5. Show the query execution results in a pipe-delimited table format
73
+
74
+ IMPORTANT: The execution_results field must contain a properly formatted table with:
75
+ - Header row with column names separated by pipes (|)
76
+ - A separator row with dashes
77
+ - Data rows with values separated by pipes (|)
78
+
79
+ Example format:
80
+ column1 | column2 | column3
81
+ --------|---------|--------
82
+ value1 | value2 | value3
83
+ value4 | value5 | value6
84
+
85
  Always present your response in this order:
86
  - Generated SQL query with syntax explanation
87
  - Table schema (CREATE TABLE statement)
88
  - Sample data (INSERT statements or table visualization)
89
+ - Query execution results (in pipe-delimited table format)
90
  - Any relevant notes about assumptions made or query optimization suggestions""",
91
  },
92
  {
 
127
  Optimization Notes:
128
  {chr(10).join(f"- {note}" for note in sql_query_generation.optimization_notes)}"""
129
 
130
+ # Convert execution results to DataFrame
131
+ results_df = parse_execution_results_to_dataframe(sql_query_generation.execution_results)
132
+
133
  return (
134
  sql_query_generation.query,
135
  metadata,
136
  sql_query_generation.table_schema,
137
  sql_query_generation.sample_data,
138
+ results_df,
139
  validation_text
140
  )
141
 
142
  except Exception as e:
143
  error_msg = f"Error: {str(e)}"
144
+ return error_msg, "", "", "", None, ""
145
 
146
  # Create Gradio interface
147
  with gr.Blocks(title="SQL Query Generator", theme=gr.themes.Soft()) as demo:
 
216
  )
217
 
218
  with gr.Row():
219
+ execution_output = gr.Dataframe(
220
+ label="📊 Execution Results",
221
+ headers=None,
222
+ datatype="str",
223
+ row_count=10,
224
+ col_count=None,
225
+ wrap=True,
226
+ interactive=False
227
  )
228
 
229
  generate_btn.click(
 
250
  The app will provide:
251
  - A validated SQL query
252
  - Table schema and sample data
253
+ - Execution results in Excel-style table format
254
  - Optimization suggestions
255
  """
256
  )