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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -26
app.py CHANGED
@@ -8,12 +8,12 @@ import time
8
  import traceback
9
  from PIL import Image
10
 
11
- # πŸ”§ CONFIGURE: Your Flask API 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()
@@ -47,7 +47,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,13 +57,13 @@ 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", "")
@@ -80,46 +80,70 @@ def query_database(question):
80
  df = pd.DataFrame(rows) if rows else pd.DataFrame()
81
  print(f"DataFrame shape: {df.shape}")
82
 
83
- # Process chart
84
  chart_image = None
85
- if chart_data:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  try:
87
  image_bytes = base64.b64decode(chart_data)
88
  chart_image = Image.open(BytesIO(image_bytes))
89
- print("Chart decoded successfully")
90
  except Exception as e:
91
- print(f"Error decoding chart: {e}")
92
 
93
  # Prepare details
94
  details = f"Request time: {elapsed_time:.2f}s\n"
95
  details += f"Status code: {response.status_code}\n"
96
  details += f"Rows returned: {row_count}\n"
97
  details += f"Chart generated: {'Yes' if chart_data else 'No'}\n"
 
 
 
 
98
  details += f"Response size: {len(response.text)} bytes"
99
 
100
  print(f"=== REQUEST COMPLETED SUCCESSFULLY ===")
101
 
102
- return sql, df, chart_image, f"βœ… Query completed successfully", details, "Success"
103
 
104
  except requests.exceptions.ConnectionError as e:
105
  error_msg = f"Connection failed: {str(e)}"
106
  print(f"CONNECTION ERROR: {error_msg}")
107
  print(f"Traceback: {traceback.format_exc()}")
108
- return "", None, None, f"❌ {error_msg}", "Connection error", "Connection error"
109
  except requests.exceptions.Timeout:
110
  error_msg = "Request timed out after 300 seconds"
111
  print(f"TIMEOUT ERROR: {error_msg}")
112
- return "", None, None, f"⏱️ {error_msg}", "Timeout error", "Timeout error"
113
  except requests.exceptions.RequestException as e:
114
  error_msg = f"Request exception: {str(e)}"
115
  print(f"REQUEST ERROR: {error_msg}")
116
  print(f"Traceback: {traceback.format_exc()}")
117
- return "", None, None, f"❌ {error_msg}", "Request error", "Request error"
118
  except Exception as e:
119
  error_msg = f"Unexpected error: {str(e)}"
120
  print(f"UNEXPECTED ERROR: {error_msg}")
121
  print(f"Traceback: {traceback.format_exc()}")
122
- return "", None, None, f"🚨 {error_msg}", f"Error: {str(e)}", "Unexpected error"
123
 
124
  def check_health():
125
  try:
@@ -207,6 +231,13 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
207
  padding: 10px;
208
  background-color: #1e293b;
209
  }
 
 
 
 
 
 
 
210
  /* Fix input text color */
211
  .gradio-container input[type="text"],
212
  .gradio-container textarea {
@@ -245,10 +276,10 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
245
  example3 = gr.Button("Show members with their account balances", elem_classes=["example-btn"])
246
  example4 = gr.Button("Which member has the highest balance?", elem_classes=["example-btn"])
247
  with gr.Column():
248
- example5 = gr.Button("Show transaction trends over time", elem_classes=["example-btn"])
249
- example6 = gr.Button("Count of members by status", elem_classes=["example-btn"])
250
- example7 = gr.Button("Show me the first 10 rows", elem_classes=["example-btn"])
251
- example8 = gr.Button("What is the average age of members?", elem_classes=["example-btn"])
252
 
253
  gr.Markdown("### 🩺 API Health Check")
254
  health_btn = gr.Button("Check API Health", variant="secondary")
@@ -273,12 +304,18 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
273
  )
274
 
275
  with gr.Tab("Visual Insights"):
276
- chart_output = gr.Image(
277
- label="Chart",
278
- type="pil",
279
- height=400,
280
- elem_classes="chart-container"
281
- )
 
 
 
 
 
 
282
 
283
  gr.Markdown("### πŸ“Š Request Details")
284
  request_details = gr.Textbox(label="Request Details", interactive=False, lines=6)
@@ -307,13 +344,13 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
307
  ).then(
308
  fn=query_database,
309
  inputs=question_input,
310
- outputs=[sql_output, results_output, chart_output, chatbot_output, request_details, error_details]
311
  )
312
 
313
  submit_btn.click(
314
  fn=query_database,
315
  inputs=question_input,
316
- outputs=[sql_output, results_output, chart_output, chatbot_output, request_details, error_details]
317
  )
318
 
319
  # Launch
 
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()
 
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
  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", "")
 
80
  df = pd.DataFrame(rows) if rows else pd.DataFrame()
81
  print(f"DataFrame shape: {df.shape}")
82
 
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:
 
231
  padding: 10px;
232
  background-color: #1e293b;
233
  }
234
+ .chart-metadata {
235
+ background-color: #1e293b;
236
+ border: 1px solid #334155;
237
+ border-radius: 8px;
238
+ padding: 10px;
239
+ margin-bottom: 10px;
240
+ }
241
  /* Fix input text color */
242
  .gradio-container input[type="text"],
243
  .gradio-container textarea {
 
276
  example3 = gr.Button("Show members with their account balances", elem_classes=["example-btn"])
277
  example4 = gr.Button("Which member has the highest balance?", elem_classes=["example-btn"])
278
  with gr.Column():
279
+ example5 = gr.Button("Show transaction trends over time", elem_classes=["example-btn"]) # Time series
280
+ example6 = gr.Button("Count of members by status", elem_classes=["example-btn"]) # Bar chart
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")
 
304
  )
305
 
306
  with gr.Tab("Visual Insights"):
307
+ with gr.Row():
308
+ with gr.Column(scale=3):
309
+ chart_output = gr.Image(
310
+ label="Chart",
311
+ type="pil",
312
+ height=400,
313
+ elem_classes="chart-container"
314
+ )
315
+ with gr.Column(scale=1):
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)
 
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