Shreyass334 commited on
Commit
e4d6847
Β·
verified Β·
1 Parent(s): 42e0d37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -48
app.py CHANGED
@@ -7,13 +7,12 @@ import json
7
  import time
8
  import traceback
9
  from PIL import Image
10
-
11
  # πŸ”§ CONFIGURE: Your Flask API URL (Public URL)
12
- FLASK_API_URL = "http://18.219.185.9:5000"
13
 
14
- def query_database(question):
15
  if not question.strip():
16
- return "", None, None, "⚠️ Please enter a question.", "", "", "", ""
17
 
18
  try:
19
  start_time = time.time()
@@ -21,10 +20,19 @@ def query_database(question):
21
  print("=== NEW QUERY REQUEST ===")
22
  print(f"Time: {time.strftime('%Y-%m-%d %H:%M:%S')}")
23
  print(f"Question: {question}")
 
 
24
  print("="*50)
25
 
26
  # Prepare the request
27
- payload = {"question": question}
 
 
 
 
 
 
 
28
 
29
  print(f"Request URL: {FLASK_API_URL}/ask")
30
  print(f"Request payload: {payload}")
@@ -47,7 +55,7 @@ def query_database(question):
47
  if not response.text:
48
  error_msg = "Empty response from server"
49
  print(f"ERROR: {error_msg}")
50
- return "", None, None, f"❌ {error_msg}", f"Request time: {elapsed_time:.2f}s", "Empty response", "", ""
51
 
52
  # Try to parse JSON response
53
  try:
@@ -57,24 +65,26 @@ def query_database(question):
57
  error_msg = f"Invalid JSON response: {str(e)}"
58
  print(f"ERROR: {error_msg}")
59
  print(f"Response text (first 500 chars): {response.text[:500]}")
60
- return "", None, None, f"❌ {error_msg}", f"Request time: {elapsed_time:.2f}s", "JSON parse error", "", ""
61
 
62
  # Check HTTP status
63
  if response.status_code != 200:
64
  error_msg = result.get("error", f"HTTP {response.status_code}")
65
  print(f"ERROR: HTTP status {response.status_code}: {error_msg}")
66
- return "", None, None, f"❌ Server error: {error_msg}", f"Request time: {elapsed_time:.2f}s", "HTTP error", "", ""
67
 
68
  # Extract data
69
  sql = result.get("sql", "")
70
  rows = result.get("result", [])
71
  chart_data = result.get("chart")
72
  row_count = result.get("row_count", len(rows))
 
73
 
74
  print(f"\n=== EXTRACTED DATA ===")
75
  print(f"SQL: {sql[:100] if sql else 'None'}...")
76
  print(f"Rows count: {row_count}")
77
  print(f"Chart data received: {'Yes' if chart_data else 'No'}")
 
78
 
79
  # Create DataFrame
80
  df = pd.DataFrame(rows) if rows else pd.DataFrame()
@@ -83,67 +93,77 @@ def query_database(question):
83
  # Process chart - UPDATED TO HANDLE NEW STRUCTURED FORMAT
84
  chart_image = None
85
  chart_title = ""
86
- chart_type = ""
 
87
 
88
- if chart_data and isinstance(chart_data, dict):
89
- try:
90
- # Extract the base64 image string from the structured chart data
91
- chart_image_b64 = chart_data.get("image")
92
- if chart_image_b64:
93
- image_bytes = base64.b64decode(chart_image_b64)
94
- chart_image = Image.open(BytesIO(image_bytes))
95
- print("Chart decoded successfully")
96
-
97
- # Extract chart metadata
98
- chart_title = chart_data.get("title", "")
99
- chart_type = chart_data.get("type", "")
100
- print(f"Chart type: {chart_type}")
101
- print(f"Chart title: {chart_title}")
102
- except Exception as e:
103
- print(f"Error decoding chart: {e}")
104
- elif chart_data and isinstance(chart_data, str):
105
- # Fallback for backward compatibility
106
  try:
107
- image_bytes = base64.b64decode(chart_data)
108
- chart_image = Image.open(BytesIO(image_bytes))
109
- print("Chart decoded successfully (fallback)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  except Exception as e:
111
- print(f"Error decoding chart (fallback): {e}")
 
112
 
113
  # Prepare details
114
- details = f"Request time: {elapsed_time:.2f}s\n"
115
  details += f"Status code: {response.status_code}\n"
116
  details += f"Rows returned: {row_count}\n"
117
  details += f"Chart generated: {'Yes' if chart_data else 'No'}\n"
118
- if chart_type:
119
- details += f"Chart type: {chart_type}\n"
120
  if chart_title:
121
  details += f"Chart title: {chart_title}\n"
 
 
122
  details += f"Response size: {len(response.text)} bytes"
123
 
124
  print(f"=== REQUEST COMPLETED SUCCESSFULLY ===")
125
 
126
- return sql, df, chart_image, f"βœ… Query completed successfully", details, "Success", chart_type, chart_title
127
 
128
  except requests.exceptions.ConnectionError as e:
129
  error_msg = f"Connection failed: {str(e)}"
130
  print(f"CONNECTION ERROR: {error_msg}")
131
  print(f"Traceback: {traceback.format_exc()}")
132
- return "", None, None, f"❌ {error_msg}", "Connection error", "Connection error", "", ""
133
  except requests.exceptions.Timeout:
134
  error_msg = "Request timed out after 300 seconds"
135
  print(f"TIMEOUT ERROR: {error_msg}")
136
- return "", None, None, f"⏱️ {error_msg}", "Timeout error", "Timeout error", "", ""
137
  except requests.exceptions.RequestException as e:
138
  error_msg = f"Request exception: {str(e)}"
139
  print(f"REQUEST ERROR: {error_msg}")
140
  print(f"Traceback: {traceback.format_exc()}")
141
- return "", None, None, f"❌ {error_msg}", "Request error", "Request error", "", ""
142
  except Exception as e:
143
  error_msg = f"Unexpected error: {str(e)}"
144
  print(f"UNEXPECTED ERROR: {error_msg}")
145
  print(f"Traceback: {traceback.format_exc()}")
146
- return "", None, None, f"🚨 {error_msg}", f"Error: {str(e)}", "Unexpected error", "", ""
147
 
148
  def check_health():
149
  try:
@@ -168,6 +188,32 @@ def check_health():
168
  except Exception as e:
169
  return f"❌ Health check failed: {str(e)}", "error"
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  # 🎨 Theme: Enterprise Dark Blue
172
  theme = gr.themes.Default(
173
  primary_hue="blue",
@@ -238,6 +284,14 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
238
  padding: 10px;
239
  margin-bottom: 10px;
240
  }
 
 
 
 
 
 
 
 
241
  /* Fix input text color */
242
  .gradio-container input[type="text"],
243
  .gradio-container textarea {
@@ -266,6 +320,24 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
266
  label="Natural Language Query",
267
  lines=3
268
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  submit_btn = gr.Button("πŸš€ Generate SQL & Results", variant="primary", size="lg")
270
 
271
  gr.Markdown("### πŸ’‘ Example Queries")
@@ -281,9 +353,14 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
281
  example7 = gr.Button("Show distribution of transaction amounts", elem_classes=["example-btn"]) # Histogram
282
  example8 = gr.Button("Show correlations between numeric fields", elem_classes=["example-btn"]) # Heatmap
283
 
284
- gr.Markdown("### 🩺 API Health Check")
285
- health_btn = gr.Button("Check API Health", variant="secondary")
286
- health_output = gr.Markdown(label="API Status")
 
 
 
 
 
287
 
288
  with gr.Column(scale=2):
289
  gr.Markdown("### πŸ€– AI Assistant Response")
@@ -316,6 +393,7 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
316
  gr.Markdown("### πŸ“Š Chart Information")
317
  chart_type_output = gr.Markdown(label="Chart Type", elem_classes="chart-metadata")
318
  chart_title_output = gr.Markdown(label="Chart Title", elem_classes="chart-metadata")
 
319
 
320
  gr.Markdown("### πŸ“Š Request Details")
321
  request_details = gr.Textbox(label="Request Details", interactive=False, lines=6)
@@ -335,22 +413,26 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
335
  outputs=[health_output, error_details]
336
  )
337
 
 
 
 
 
 
 
 
338
  # Example query buttons
339
  for example_btn in [example1, example2, example3, example4, example5, example6, example7, example8]:
340
  example_btn.click(
341
  fn=set_example_query,
342
  inputs=[example_btn],
343
  outputs=[question_input]
344
- ).then(
345
- fn=query_database,
346
- inputs=question_input,
347
- outputs=[sql_output, results_output, chart_output, chatbot_output, request_details, error_details, chart_type_output, chart_title_output]
348
  )
349
 
 
350
  submit_btn.click(
351
  fn=query_database,
352
- inputs=question_input,
353
- outputs=[sql_output, results_output, chart_output, chatbot_output, request_details, error_details, chart_type_output, chart_title_output]
354
  )
355
 
356
  # Launch
 
7
  import time
8
  import traceback
9
  from PIL import Image
 
10
  # πŸ”§ CONFIGURE: Your Flask API URL (Public URL)
11
+ FLASK_API_URL = "http://52.15.175.95:5000"
12
 
13
+ def query_database(question, dashboard_mode=False, chart_type=None):
14
  if not question.strip():
15
+ return "", None, None, "⚠️ Please enter a question.", "", "", "", "", ""
16
 
17
  try:
18
  start_time = time.time()
 
20
  print("=== NEW QUERY REQUEST ===")
21
  print(f"Time: {time.strftime('%Y-%m-%d %H:%M:%S')}")
22
  print(f"Question: {question}")
23
+ print(f"Dashboard mode: {dashboard_mode}")
24
+ print(f"Chart type: {chart_type}")
25
  print("="*50)
26
 
27
  # Prepare the request
28
+ payload = {
29
+ "question": question,
30
+ "dashboard": dashboard_mode
31
+ }
32
+
33
+ # Add chart_type if specified
34
+ if chart_type:
35
+ payload["chart_type"] = chart_type
36
 
37
  print(f"Request URL: {FLASK_API_URL}/ask")
38
  print(f"Request payload: {payload}")
 
55
  if not response.text:
56
  error_msg = "Empty response from server"
57
  print(f"ERROR: {error_msg}")
58
+ return "", None, None, f"❌ {error_msg}", f"Request time: {elapsed_time:.2f}s", "Empty response", "", "", ""
59
 
60
  # Try to parse JSON response
61
  try:
 
65
  error_msg = f"Invalid JSON response: {str(e)}"
66
  print(f"ERROR: {error_msg}")
67
  print(f"Response text (first 500 chars): {response.text[:500]}")
68
+ return "", None, None, f"❌ {error_msg}", f"Request time: {elapsed_time:.2f}s", "JSON parse error", "", "", ""
69
 
70
  # Check HTTP status
71
  if response.status_code != 200:
72
  error_msg = result.get("error", f"HTTP {response.status_code}")
73
  print(f"ERROR: HTTP status {response.status_code}: {error_msg}")
74
+ return "", None, None, f"❌ Server error: {error_msg}", f"Request time: {elapsed_time:.2f}s", "HTTP error", "", "", ""
75
 
76
  # Extract data
77
  sql = result.get("sql", "")
78
  rows = result.get("result", [])
79
  chart_data = result.get("chart")
80
  row_count = result.get("row_count", len(rows))
81
+ elapsed_seconds = result.get("elapsed_seconds", elapsed_time)
82
 
83
  print(f"\n=== EXTRACTED DATA ===")
84
  print(f"SQL: {sql[:100] if sql else 'None'}...")
85
  print(f"Rows count: {row_count}")
86
  print(f"Chart data received: {'Yes' if chart_data else 'No'}")
87
+ print(f"Elapsed seconds: {elapsed_seconds}")
88
 
89
  # Create DataFrame
90
  df = pd.DataFrame(rows) if rows else pd.DataFrame()
 
93
  # Process chart - UPDATED TO HANDLE NEW STRUCTURED FORMAT
94
  chart_image = None
95
  chart_title = ""
96
+ chart_type_result = ""
97
+ chart_error = None
98
 
99
+ if chart_data:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  try:
101
+ if isinstance(chart_data, dict):
102
+ # Check if it's an error response
103
+ if "error" in chart_data:
104
+ chart_error = chart_data["error"]
105
+ print(f"Chart error: {chart_error}")
106
+ else:
107
+ # Extract the base64 image string from the structured chart data
108
+ chart_image_b64 = chart_data.get("image")
109
+ if chart_image_b64:
110
+ image_bytes = base64.b64decode(chart_image_b64)
111
+ chart_image = Image.open(BytesIO(image_bytes))
112
+ print("Chart decoded successfully")
113
+
114
+ # Extract chart metadata
115
+ chart_title = chart_data.get("title", "")
116
+ chart_type_result = chart_data.get("type", "")
117
+ print(f"Chart type: {chart_type_result}")
118
+ print(f"Chart title: {chart_title}")
119
+ elif isinstance(chart_data, str):
120
+ # Fallback for backward compatibility
121
+ try:
122
+ image_bytes = base64.b64decode(chart_data)
123
+ chart_image = Image.open(BytesIO(image_bytes))
124
+ print("Chart decoded successfully (fallback)")
125
+ except Exception as e:
126
+ print(f"Error decoding chart (fallback): {e}")
127
  except Exception as e:
128
+ print(f"Error processing chart: {e}")
129
+ chart_error = f"Chart processing error: {str(e)}"
130
 
131
  # Prepare details
132
+ details = f"Request time: {elapsed_seconds:.2f}s\n"
133
  details += f"Status code: {response.status_code}\n"
134
  details += f"Rows returned: {row_count}\n"
135
  details += f"Chart generated: {'Yes' if chart_data else 'No'}\n"
136
+ if chart_type_result:
137
+ details += f"Chart type: {chart_type_result}\n"
138
  if chart_title:
139
  details += f"Chart title: {chart_title}\n"
140
+ if dashboard_mode:
141
+ details += f"Dashboard mode: Enabled\n"
142
  details += f"Response size: {len(response.text)} bytes"
143
 
144
  print(f"=== REQUEST COMPLETED SUCCESSFULLY ===")
145
 
146
+ return sql, df, chart_image, f"βœ… Query completed successfully", details, "Success", chart_type_result, chart_title, chart_error
147
 
148
  except requests.exceptions.ConnectionError as e:
149
  error_msg = f"Connection failed: {str(e)}"
150
  print(f"CONNECTION ERROR: {error_msg}")
151
  print(f"Traceback: {traceback.format_exc()}")
152
+ return "", None, None, f"❌ {error_msg}", "Connection error", "Connection error", "", "", ""
153
  except requests.exceptions.Timeout:
154
  error_msg = "Request timed out after 300 seconds"
155
  print(f"TIMEOUT ERROR: {error_msg}")
156
+ return "", None, None, f"⏱️ {error_msg}", "Timeout error", "Timeout error", "", "", ""
157
  except requests.exceptions.RequestException as e:
158
  error_msg = f"Request exception: {str(e)}"
159
  print(f"REQUEST ERROR: {error_msg}")
160
  print(f"Traceback: {traceback.format_exc()}")
161
+ return "", None, None, f"❌ {error_msg}", "Request error", "Request error", "", "", ""
162
  except Exception as e:
163
  error_msg = f"Unexpected error: {str(e)}"
164
  print(f"UNEXPECTED ERROR: {error_msg}")
165
  print(f"Traceback: {traceback.format_exc()}")
166
+ return "", None, None, f"🚨 {error_msg}", f"Error: {str(e)}", "Unexpected error", "", "", ""
167
 
168
  def check_health():
169
  try:
 
188
  except Exception as e:
189
  return f"❌ Health check failed: {str(e)}", "error"
190
 
191
+ def get_schema():
192
+ try:
193
+ print("Fetching database schema...")
194
+ response = requests.get(f"{FLASK_API_URL}/schema", timeout=10)
195
+
196
+ if response.status_code == 200:
197
+ schema_data = response.json()
198
+ schema = schema_data.get("schema", {})
199
+ tables = schema_data.get("tables", [])
200
+
201
+ schema_text = "## Database Schema\n\n"
202
+ for table in tables:
203
+ schema_text += f"### {table}\n"
204
+ if table in schema:
205
+ columns = schema[table]
206
+ schema_text += "| Column | Type |\n|--------|------|\n"
207
+ for col in columns:
208
+ schema_text += f"| {col['name']} | {col['type']} |\n"
209
+ schema_text += "\n"
210
+
211
+ return schema_text, "success"
212
+ else:
213
+ return f"❌ API returned status {response.status_code}", "error"
214
+ except Exception as e:
215
+ return f"❌ Failed to fetch schema: {str(e)}", "error"
216
+
217
  # 🎨 Theme: Enterprise Dark Blue
218
  theme = gr.themes.Default(
219
  primary_hue="blue",
 
284
  padding: 10px;
285
  margin-bottom: 10px;
286
  }
287
+ .schema-container {
288
+ background-color: #1e293b;
289
+ border: 1px solid #334155;
290
+ border-radius: 8px;
291
+ padding: 15px;
292
+ max-height: 400px;
293
+ overflow-y: auto;
294
+ }
295
  /* Fix input text color */
296
  .gradio-container input[type="text"],
297
  .gradio-container textarea {
 
320
  label="Natural Language Query",
321
  lines=3
322
  )
323
+
324
+ with gr.Row():
325
+ dashboard_checkbox = gr.Checkbox(
326
+ label="Dashboard Mode",
327
+ value=False,
328
+ info="Generate multiple charts (only primary will be shown)"
329
+ )
330
+
331
+ chart_type_dropdown = gr.Dropdown(
332
+ label="Chart Type (Optional)",
333
+ choices=[
334
+ "auto", "time_series", "correlation", "histogram",
335
+ "bar", "scatter", "pie", "table"
336
+ ],
337
+ value="auto",
338
+ info="Force a specific chart type"
339
+ )
340
+
341
  submit_btn = gr.Button("πŸš€ Generate SQL & Results", variant="primary", size="lg")
342
 
343
  gr.Markdown("### πŸ’‘ Example Queries")
 
353
  example7 = gr.Button("Show distribution of transaction amounts", elem_classes=["example-btn"]) # Histogram
354
  example8 = gr.Button("Show correlations between numeric fields", elem_classes=["example-btn"]) # Heatmap
355
 
356
+ with gr.Accordion("Advanced Options", open=False):
357
+ gr.Markdown("### 🩺 System Information")
358
+ with gr.Row():
359
+ health_btn = gr.Button("Check API Health", variant="secondary", size="sm")
360
+ schema_btn = gr.Button("Get Database Schema", variant="secondary", size="sm")
361
+
362
+ health_output = gr.Markdown(label="API Status")
363
+ schema_output = gr.Markdown(label="Database Schema", elem_classes="schema-container")
364
 
365
  with gr.Column(scale=2):
366
  gr.Markdown("### πŸ€– AI Assistant Response")
 
393
  gr.Markdown("### πŸ“Š Chart Information")
394
  chart_type_output = gr.Markdown(label="Chart Type", elem_classes="chart-metadata")
395
  chart_title_output = gr.Markdown(label="Chart Title", elem_classes="chart-metadata")
396
+ chart_error_output = gr.Markdown(label="Chart Error", elem_classes="chart-metadata")
397
 
398
  gr.Markdown("### πŸ“Š Request Details")
399
  request_details = gr.Textbox(label="Request Details", interactive=False, lines=6)
 
413
  outputs=[health_output, error_details]
414
  )
415
 
416
+ # Schema button
417
+ schema_btn.click(
418
+ fn=get_schema,
419
+ inputs=[],
420
+ outputs=[schema_output, error_details]
421
+ )
422
+
423
  # Example query buttons
424
  for example_btn in [example1, example2, example3, example4, example5, example6, example7, example8]:
425
  example_btn.click(
426
  fn=set_example_query,
427
  inputs=[example_btn],
428
  outputs=[question_input]
 
 
 
 
429
  )
430
 
431
+ # Submit button
432
  submit_btn.click(
433
  fn=query_database,
434
+ inputs=[question_input, dashboard_checkbox, chart_type_dropdown],
435
+ outputs=[sql_output, results_output, chart_output, chatbot_output, request_details, error_details, chart_type_output, chart_title_output, chart_error_output]
436
  )
437
 
438
  # Launch