Shreyass334 commited on
Commit
7f3af20
ยท
verified ยท
1 Parent(s): e4d6847

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -42
app.py CHANGED
@@ -7,6 +7,7 @@ import json
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
 
@@ -27,12 +28,12 @@ def query_database(question, dashboard_mode=False, chart_type=None):
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}")
@@ -76,63 +77,61 @@ def query_database(question, dashboard_mode=False, chart_type=None):
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()
91
  print(f"DataFrame shape: {df.shape}")
92
 
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:
@@ -173,14 +172,10 @@ def check_health():
173
  if response.status_code == 200:
174
  health_data = response.json()
175
  status = health_data.get('status', 'unknown')
176
- model = health_data.get('model', 'unknown')
177
  tables = health_data.get('tables', [])
178
- data_rows = health_data.get('data_rows', 0)
179
 
180
  health_msg = f"โœ… API Status: {status.upper()}\n"
181
- health_msg += f"๐Ÿค– Model: {model}\n"
182
  health_msg += f"๐Ÿ“Š Tables: {', '.join(tables) if tables else 'None'}\n"
183
- health_msg += f"๐Ÿ“ˆ Data Rows: {data_rows:,}"
184
 
185
  return health_msg, "success"
186
  else:
@@ -191,21 +186,18 @@ def check_health():
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"
@@ -331,8 +323,7 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
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"
@@ -348,10 +339,10 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
348
  example3 = gr.Button("Show members with their account balances", elem_classes=["example-btn"])
349
  example4 = gr.Button("Which member has the highest balance?", elem_classes=["example-btn"])
350
  with gr.Column():
351
- example5 = gr.Button("Show transaction trends over time", elem_classes=["example-btn"]) # Time series
352
- example6 = gr.Button("Count of members by status", elem_classes=["example-btn"]) # Bar chart
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")
 
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://52.15.175.95:5000"
13
 
 
28
  # Prepare the request
29
  payload = {
30
  "question": question,
31
+ "visualize": True # Always request visualization
32
  }
33
 
34
  # Add chart_type if specified
35
+ if chart_type and chart_type != "auto":
36
+ payload["viz_type"] = chart_type
37
 
38
  print(f"Request URL: {FLASK_API_URL}/ask")
39
  print(f"Request payload: {payload}")
 
77
  # Extract data
78
  sql = result.get("sql", "")
79
  rows = result.get("result", [])
80
+ visualization = result.get("visualization", {})
81
  row_count = result.get("row_count", len(rows))
 
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"Visualization received: {'Yes' if visualization else 'No'}")
 
87
 
88
  # Create DataFrame
89
  df = pd.DataFrame(rows) if rows else pd.DataFrame()
90
  print(f"DataFrame shape: {df.shape}")
91
 
92
+ # Process visualization
93
  chart_image = None
94
  chart_title = ""
95
  chart_type_result = ""
96
  chart_error = None
97
 
98
+ if visualization:
99
  try:
100
+ if isinstance(visualization, dict):
101
  # Check if it's an error response
102
+ if "error" in visualization:
103
+ chart_error = visualization["error"]
104
  print(f"Chart error: {chart_error}")
105
  else:
106
+ # Extract the base64 image string from the structured visualization data
107
+ chart_image_b64 = visualization.get("image")
108
  if chart_image_b64:
109
  image_bytes = base64.b64decode(chart_image_b64)
110
  chart_image = Image.open(BytesIO(image_bytes))
111
  print("Chart decoded successfully")
112
 
113
  # Extract chart metadata
114
+ chart_title = visualization.get("title", "")
115
+ chart_type_result = visualization.get("type", "")
116
  print(f"Chart type: {chart_type_result}")
117
  print(f"Chart title: {chart_title}")
118
+ elif isinstance(visualization, str):
119
  # Fallback for backward compatibility
120
  try:
121
+ image_bytes = base64.b64decode(visualization)
122
  chart_image = Image.open(BytesIO(image_bytes))
123
  print("Chart decoded successfully (fallback)")
124
  except Exception as e:
125
  print(f"Error decoding chart (fallback): {e}")
126
  except Exception as e:
127
+ print(f"Error processing visualization: {e}")
128
+ chart_error = f"Visualization processing error: {str(e)}"
129
 
130
  # Prepare details
131
+ details = f"Request time: {elapsed_time:.2f}s\n"
132
  details += f"Status code: {response.status_code}\n"
133
  details += f"Rows returned: {row_count}\n"
134
+ details += f"Chart generated: {'Yes' if visualization else 'No'}\n"
135
  if chart_type_result:
136
  details += f"Chart type: {chart_type_result}\n"
137
  if chart_title:
 
172
  if response.status_code == 200:
173
  health_data = response.json()
174
  status = health_data.get('status', 'unknown')
 
175
  tables = health_data.get('tables', [])
 
176
 
177
  health_msg = f"โœ… API Status: {status.upper()}\n"
 
178
  health_msg += f"๐Ÿ“Š Tables: {', '.join(tables) if tables else 'None'}\n"
 
179
 
180
  return health_msg, "success"
181
  else:
 
186
  def get_schema():
187
  try:
188
  print("Fetching database schema...")
189
+ response = requests.get(f"{FLASK_API_URL}/tables", timeout=10)
190
 
191
  if response.status_code == 200:
192
+ tables_data = response.json()
193
+ tables = tables_data.get("tables", [])
 
194
 
195
  schema_text = "## Database Schema\n\n"
196
  for table in tables:
197
+ schema_text += f"### {table['name']}\n"
198
+ schema_text += "| Column |\n|--------|\n"
199
+ for col in table['columns']:
200
+ schema_text += f"| {col} |\n"
 
 
201
  schema_text += "\n"
202
 
203
  return schema_text, "success"
 
323
  chart_type_dropdown = gr.Dropdown(
324
  label="Chart Type (Optional)",
325
  choices=[
326
+ "auto", "bar", "line", "scatter", "pie", "histogram"
 
327
  ],
328
  value="auto",
329
  info="Force a specific chart type"
 
339
  example3 = gr.Button("Show members with their account balances", elem_classes=["example-btn"])
340
  example4 = gr.Button("Which member has the highest balance?", elem_classes=["example-btn"])
341
  with gr.Column():
342
+ example5 = gr.Button("Show transaction trends over time", elem_classes=["example-btn"])
343
+ example6 = gr.Button("Count of members by status", elem_classes=["example-btn"])
344
+ example7 = gr.Button("Show distribution of transaction amounts", elem_classes=["example-btn"])
345
+ example8 = gr.Button("Show correlations between numeric fields", elem_classes=["example-btn"])
346
 
347
  with gr.Accordion("Advanced Options", open=False):
348
  gr.Markdown("### ๐Ÿฉบ System Information")