Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -25,13 +25,17 @@ def query_database(question, dashboard_mode=False, chart_type=None):
|
|
| 25 |
print(f"Chart type: {chart_type}")
|
| 26 |
print("="*50)
|
| 27 |
|
| 28 |
-
# Prepare the request
|
| 29 |
payload = {
|
| 30 |
"question": question,
|
| 31 |
-
"visualize": True
|
| 32 |
}
|
| 33 |
|
| 34 |
-
# Add
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
if chart_type and chart_type != "auto":
|
| 36 |
payload["viz_type"] = chart_type
|
| 37 |
|
|
@@ -50,7 +54,7 @@ def query_database(question, dashboard_mode=False, chart_type=None):
|
|
| 50 |
print(f"\n=== RESPONSE RECEIVED ===")
|
| 51 |
print(f"Response time: {elapsed_time:.2f} seconds")
|
| 52 |
print(f"Response status: {response.status_code}")
|
| 53 |
-
print(f"Response
|
| 54 |
|
| 55 |
# Check if response is empty
|
| 56 |
if not response.text:
|
|
@@ -65,13 +69,20 @@ def query_database(question, dashboard_mode=False, chart_type=None):
|
|
| 65 |
except json.JSONDecodeError as e:
|
| 66 |
error_msg = f"Invalid JSON response: {str(e)}"
|
| 67 |
print(f"ERROR: {error_msg}")
|
| 68 |
-
print(f"Response text (first
|
| 69 |
return "", None, None, f"β {error_msg}", f"Request time: {elapsed_time:.2f}s", "JSON parse error", "", "", ""
|
| 70 |
|
| 71 |
# Check HTTP status
|
| 72 |
if response.status_code != 200:
|
| 73 |
error_msg = result.get("error", f"HTTP {response.status_code}")
|
| 74 |
print(f"ERROR: HTTP status {response.status_code}: {error_msg}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
return "", None, None, f"β Server error: {error_msg}", f"Request time: {elapsed_time:.2f}s", "HTTP error", "", "", ""
|
| 76 |
|
| 77 |
# Extract data
|
|
@@ -89,7 +100,7 @@ def query_database(question, dashboard_mode=False, chart_type=None):
|
|
| 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 = ""
|
|
@@ -103,15 +114,19 @@ def query_database(question, dashboard_mode=False, chart_type=None):
|
|
| 103 |
chart_error = visualization["error"]
|
| 104 |
print(f"Chart error: {chart_error}")
|
| 105 |
else:
|
| 106 |
-
# Extract the base64 image string
|
| 107 |
chart_image_b64 = visualization.get("image")
|
| 108 |
if chart_image_b64:
|
| 109 |
-
#
|
| 110 |
if chart_image_b64.startswith("data:image/"):
|
| 111 |
chart_image_b64 = chart_image_b64.split(",")[1]
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
# Extract chart metadata
|
| 117 |
chart_title = visualization.get("title", "")
|
|
@@ -121,7 +136,7 @@ def query_database(question, dashboard_mode=False, chart_type=None):
|
|
| 121 |
elif isinstance(visualization, str):
|
| 122 |
# Fallback for backward compatibility
|
| 123 |
try:
|
| 124 |
-
#
|
| 125 |
if visualization.startswith("data:image/"):
|
| 126 |
visualization = visualization.split(",")[1]
|
| 127 |
image_bytes = base64.b64decode(visualization)
|
|
@@ -129,6 +144,7 @@ def query_database(question, dashboard_mode=False, chart_type=None):
|
|
| 129 |
print("Chart decoded successfully (fallback)")
|
| 130 |
except Exception as e:
|
| 131 |
print(f"Error decoding chart (fallback): {e}")
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
print(f"Error processing visualization: {e}")
|
| 134 |
chart_error = f"Visualization processing error: {str(e)}"
|
|
@@ -175,26 +191,38 @@ def check_health():
|
|
| 175 |
print("Checking API health...")
|
| 176 |
response = requests.get(f"{FLASK_API_URL}/health", timeout=10)
|
| 177 |
|
|
|
|
|
|
|
|
|
|
| 178 |
if response.status_code == 200:
|
| 179 |
health_data = response.json()
|
| 180 |
status = health_data.get('status', 'unknown')
|
| 181 |
-
tables = health_data.get('tables', [])
|
|
|
|
|
|
|
| 182 |
|
| 183 |
health_msg = f"β
API Status: {status.upper()}\n"
|
|
|
|
| 184 |
health_msg += f"π Tables: {', '.join(tables) if tables else 'None'}\n"
|
|
|
|
| 185 |
|
| 186 |
return health_msg, "success"
|
| 187 |
else:
|
| 188 |
-
return f"β API returned status {response.status_code}", "error"
|
| 189 |
except Exception as e:
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
def get_schema():
|
| 193 |
try:
|
| 194 |
print("Fetching database schema...")
|
| 195 |
-
# FIXED: Use correct endpoint
|
| 196 |
response = requests.get(f"{FLASK_API_URL}/tables", timeout=10)
|
| 197 |
|
|
|
|
|
|
|
|
|
|
| 198 |
if response.status_code == 200:
|
| 199 |
tables_data = response.json()
|
| 200 |
tables = tables_data.get("tables", [])
|
|
@@ -209,9 +237,12 @@ def get_schema():
|
|
| 209 |
|
| 210 |
return schema_text, "success"
|
| 211 |
else:
|
| 212 |
-
return f"β API returned status {response.status_code}", "error"
|
| 213 |
except Exception as e:
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
# π¨ Theme: Enterprise Dark Blue
|
| 217 |
theme = gr.themes.Default(
|
|
@@ -331,7 +362,7 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
|
|
| 331 |
label="Chart Type (Optional)",
|
| 332 |
choices=[
|
| 333 |
"auto", "bar", "line", "scatter", "pie", "histogram",
|
| 334 |
-
"time_series", "correlation"
|
| 335 |
],
|
| 336 |
value="auto",
|
| 337 |
info="Force a specific chart type"
|
|
|
|
| 25 |
print(f"Chart type: {chart_type}")
|
| 26 |
print("="*50)
|
| 27 |
|
| 28 |
+
# Prepare the request
|
| 29 |
payload = {
|
| 30 |
"question": question,
|
| 31 |
+
"visualize": True
|
| 32 |
}
|
| 33 |
|
| 34 |
+
# Add dashboard_mode if specified
|
| 35 |
+
if dashboard_mode:
|
| 36 |
+
payload["dashboard_mode"] = dashboard_mode
|
| 37 |
+
|
| 38 |
+
# Add chart_type if specified
|
| 39 |
if chart_type and chart_type != "auto":
|
| 40 |
payload["viz_type"] = chart_type
|
| 41 |
|
|
|
|
| 54 |
print(f"\n=== RESPONSE RECEIVED ===")
|
| 55 |
print(f"Response time: {elapsed_time:.2f} seconds")
|
| 56 |
print(f"Response status: {response.status_code}")
|
| 57 |
+
print(f"Response headers: {dict(response.headers)}")
|
| 58 |
|
| 59 |
# Check if response is empty
|
| 60 |
if not response.text:
|
|
|
|
| 69 |
except json.JSONDecodeError as e:
|
| 70 |
error_msg = f"Invalid JSON response: {str(e)}"
|
| 71 |
print(f"ERROR: {error_msg}")
|
| 72 |
+
print(f"Response text (first 1000 chars): {response.text[:1000]}")
|
| 73 |
return "", None, None, f"β {error_msg}", f"Request time: {elapsed_time:.2f}s", "JSON parse error", "", "", ""
|
| 74 |
|
| 75 |
# Check HTTP status
|
| 76 |
if response.status_code != 200:
|
| 77 |
error_msg = result.get("error", f"HTTP {response.status_code}")
|
| 78 |
print(f"ERROR: HTTP status {response.status_code}: {error_msg}")
|
| 79 |
+
|
| 80 |
+
# For 500 errors, show more details
|
| 81 |
+
if response.status_code == 500:
|
| 82 |
+
error_details = f"Server Error (500): {error_msg}\n"
|
| 83 |
+
error_details += f"Response: {json.dumps(result, indent=2)}"
|
| 84 |
+
return "", None, None, f"β Server error: {error_msg}", f"Request time: {elapsed_time:.2f}s", error_details, "", "", ""
|
| 85 |
+
|
| 86 |
return "", None, None, f"β Server error: {error_msg}", f"Request time: {elapsed_time:.2f}s", "HTTP error", "", "", ""
|
| 87 |
|
| 88 |
# Extract data
|
|
|
|
| 100 |
df = pd.DataFrame(rows) if rows else pd.DataFrame()
|
| 101 |
print(f"DataFrame shape: {df.shape}")
|
| 102 |
|
| 103 |
+
# Process visualization
|
| 104 |
chart_image = None
|
| 105 |
chart_title = ""
|
| 106 |
chart_type_result = ""
|
|
|
|
| 114 |
chart_error = visualization["error"]
|
| 115 |
print(f"Chart error: {chart_error}")
|
| 116 |
else:
|
| 117 |
+
# Extract the base64 image string
|
| 118 |
chart_image_b64 = visualization.get("image")
|
| 119 |
if chart_image_b64:
|
| 120 |
+
# Handle base64 prefix
|
| 121 |
if chart_image_b64.startswith("data:image/"):
|
| 122 |
chart_image_b64 = chart_image_b64.split(",")[1]
|
| 123 |
+
try:
|
| 124 |
+
image_bytes = base64.b64decode(chart_image_b64)
|
| 125 |
+
chart_image = Image.open(BytesIO(image_bytes))
|
| 126 |
+
print("Chart decoded successfully")
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Error decoding chart: {e}")
|
| 129 |
+
chart_error = f"Chart decoding error: {str(e)}"
|
| 130 |
|
| 131 |
# Extract chart metadata
|
| 132 |
chart_title = visualization.get("title", "")
|
|
|
|
| 136 |
elif isinstance(visualization, str):
|
| 137 |
# Fallback for backward compatibility
|
| 138 |
try:
|
| 139 |
+
# Handle base64 prefix
|
| 140 |
if visualization.startswith("data:image/"):
|
| 141 |
visualization = visualization.split(",")[1]
|
| 142 |
image_bytes = base64.b64decode(visualization)
|
|
|
|
| 144 |
print("Chart decoded successfully (fallback)")
|
| 145 |
except Exception as e:
|
| 146 |
print(f"Error decoding chart (fallback): {e}")
|
| 147 |
+
chart_error = f"Chart decoding error: {str(e)}"
|
| 148 |
except Exception as e:
|
| 149 |
print(f"Error processing visualization: {e}")
|
| 150 |
chart_error = f"Visualization processing error: {str(e)}"
|
|
|
|
| 191 |
print("Checking API health...")
|
| 192 |
response = requests.get(f"{FLASK_API_URL}/health", timeout=10)
|
| 193 |
|
| 194 |
+
print(f"Health check response status: {response.status_code}")
|
| 195 |
+
print(f"Health check response: {response.text}")
|
| 196 |
+
|
| 197 |
if response.status_code == 200:
|
| 198 |
health_data = response.json()
|
| 199 |
status = health_data.get('status', 'unknown')
|
| 200 |
+
tables = health_data.get('tables', [])
|
| 201 |
+
model = health_data.get('model', 'unknown')
|
| 202 |
+
data_rows = health_data.get('data_rows', 0)
|
| 203 |
|
| 204 |
health_msg = f"β
API Status: {status.upper()}\n"
|
| 205 |
+
health_msg += f"π€ Model: {model}\n"
|
| 206 |
health_msg += f"π Tables: {', '.join(tables) if tables else 'None'}\n"
|
| 207 |
+
health_msg += f"π Data Rows: {data_rows:,}"
|
| 208 |
|
| 209 |
return health_msg, "success"
|
| 210 |
else:
|
| 211 |
+
return f"β API returned status {response.status_code}\nResponse: {response.text}", "error"
|
| 212 |
except Exception as e:
|
| 213 |
+
error_msg = f"Health check failed: {str(e)}"
|
| 214 |
+
print(f"HEALTH CHECK ERROR: {error_msg}")
|
| 215 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 216 |
+
return f"β {error_msg}", "error"
|
| 217 |
|
| 218 |
def get_schema():
|
| 219 |
try:
|
| 220 |
print("Fetching database schema...")
|
|
|
|
| 221 |
response = requests.get(f"{FLASK_API_URL}/tables", timeout=10)
|
| 222 |
|
| 223 |
+
print(f"Schema response status: {response.status_code}")
|
| 224 |
+
print(f"Schema response: {response.text}")
|
| 225 |
+
|
| 226 |
if response.status_code == 200:
|
| 227 |
tables_data = response.json()
|
| 228 |
tables = tables_data.get("tables", [])
|
|
|
|
| 237 |
|
| 238 |
return schema_text, "success"
|
| 239 |
else:
|
| 240 |
+
return f"β API returned status {response.status_code}\nResponse: {response.text}", "error"
|
| 241 |
except Exception as e:
|
| 242 |
+
error_msg = f"Failed to fetch schema: {str(e)}"
|
| 243 |
+
print(f"SCHEMA FETCH ERROR: {error_msg}")
|
| 244 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 245 |
+
return f"β {error_msg}", "error"
|
| 246 |
|
| 247 |
# π¨ Theme: Enterprise Dark Blue
|
| 248 |
theme = gr.themes.Default(
|
|
|
|
| 362 |
label="Chart Type (Optional)",
|
| 363 |
choices=[
|
| 364 |
"auto", "bar", "line", "scatter", "pie", "histogram",
|
| 365 |
+
"time_series", "correlation"
|
| 366 |
],
|
| 367 |
value="auto",
|
| 368 |
info="Force a specific chart type"
|