Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,81 +5,157 @@ import base64
|
|
| 5 |
from io import BytesIO
|
| 6 |
import json
|
| 7 |
import time
|
|
|
|
| 8 |
|
| 9 |
# π§ CONFIGURE: Replace with your EC2 public IP
|
| 10 |
-
API_URL = "http://
|
| 11 |
-
HEALTH_URL = "http://
|
|
|
|
|
|
|
| 12 |
|
| 13 |
def test_connection():
|
| 14 |
try:
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
if response.status_code == 200:
|
| 17 |
return f"β
Connection successful! Status: {response.status_code}\nResponse: {response.text}"
|
| 18 |
else:
|
| 19 |
return f"β οΈ Connection returned status: {response.status_code}\nResponse: {response.text}"
|
| 20 |
-
except requests.exceptions.ConnectionError:
|
| 21 |
-
return "β Connection failed. The server might be down or not accessible from Hugging Face."
|
| 22 |
-
except requests.exceptions.Timeout:
|
| 23 |
-
return "β±οΈ Connection timed out after 30 seconds."
|
| 24 |
except Exception as e:
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
def
|
| 28 |
try:
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
if response.status_code == 200:
|
| 31 |
result = response.json()
|
| 32 |
-
|
| 33 |
-
image_bytes = base64.b64decode(result['chart'])
|
| 34 |
-
chart_image = BytesIO(image_bytes)
|
| 35 |
-
return "β
Test chart generated successfully!", chart_image
|
| 36 |
-
else:
|
| 37 |
-
return f"β Error: {result.get('message', 'Unknown error')}", None
|
| 38 |
else:
|
| 39 |
-
return f"β
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
except Exception as e:
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
def query_database(question):
|
| 44 |
if not question.strip():
|
| 45 |
-
return "", None, None, "β οΈ Please enter a question.", ""
|
| 46 |
|
| 47 |
try:
|
| 48 |
start_time = time.time()
|
| 49 |
-
print(
|
|
|
|
|
|
|
| 50 |
print(f"Question: {question}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
response = requests.post(
|
| 53 |
API_URL,
|
| 54 |
-
json=
|
| 55 |
-
|
|
|
|
| 56 |
)
|
| 57 |
|
| 58 |
elapsed_time = time.time() - start_time
|
| 59 |
-
print(f"
|
| 60 |
print(f"Response time: {elapsed_time:.2f} seconds")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
| 62 |
try:
|
| 63 |
result = response.json()
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
|
|
|
| 67 |
if response.status_code != 200:
|
| 68 |
error_msg = result.get("error", f"HTTP {response.status_code}")
|
| 69 |
-
|
|
|
|
| 70 |
|
|
|
|
| 71 |
if "error" in result:
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
|
|
|
|
| 74 |
sql = result.get("sql", "N/A")
|
| 75 |
rows = result.get("result", [])
|
| 76 |
chart_data = result.get("chart")
|
| 77 |
|
|
|
|
|
|
|
|
|
|
| 78 |
print(f"Chart data received: {'Yes' if chart_data else 'No'}")
|
| 79 |
print(f"Chart data length: {len(chart_data) if chart_data else 0}")
|
| 80 |
|
|
|
|
| 81 |
df = pd.DataFrame(rows) if rows else pd.DataFrame()
|
|
|
|
| 82 |
|
|
|
|
| 83 |
chart_image = None
|
| 84 |
if chart_data:
|
| 85 |
try:
|
|
@@ -89,18 +165,36 @@ def query_database(question):
|
|
| 89 |
except Exception as e:
|
| 90 |
print(f"Error decoding chart: {e}")
|
| 91 |
|
|
|
|
| 92 |
details = f"Request time: {elapsed_time:.2f}s\n"
|
|
|
|
| 93 |
details += f"Rows returned: {len(rows)}\n"
|
| 94 |
-
details += f"Chart generated: {'Yes' if chart_data else 'No'}"
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
return sql, df, chart_image, "β
Query completed successfully!", details
|
| 97 |
|
| 98 |
except requests.exceptions.ConnectionError as e:
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
| 100 |
except requests.exceptions.Timeout:
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
except Exception as e:
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
# π¨ Theme: Enterprise Dark Blue
|
| 106 |
theme = gr.themes.Default(
|
|
@@ -134,14 +228,16 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant") as demo:
|
|
| 134 |
)
|
| 135 |
submit_btn = gr.Button("π Generate SQL & Results", variant="primary")
|
| 136 |
|
| 137 |
-
gr.Markdown("### π§ Connection
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
| 145 |
|
| 146 |
gr.Markdown("### π‘ Example Queries")
|
| 147 |
gr.Examples(
|
|
@@ -183,7 +279,10 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant") as demo:
|
|
| 183 |
)
|
| 184 |
|
| 185 |
gr.Markdown("### π Request Details")
|
| 186 |
-
request_details = gr.Textbox(label="Request Details", interactive=False, lines=
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
# Events
|
| 189 |
test_btn.click(
|
|
@@ -191,15 +290,20 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant") as demo:
|
|
| 191 |
outputs=[connection_status]
|
| 192 |
)
|
| 193 |
|
| 194 |
-
|
| 195 |
-
fn=
|
| 196 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
)
|
| 198 |
|
| 199 |
submit_btn.click(
|
| 200 |
fn=query_database,
|
| 201 |
inputs=question_input,
|
| 202 |
-
outputs=[sql_output, results_output, chart_output, status, request_details]
|
| 203 |
)
|
| 204 |
|
| 205 |
# Launch
|
|
|
|
| 5 |
from io import BytesIO
|
| 6 |
import json
|
| 7 |
import time
|
| 8 |
+
import traceback
|
| 9 |
|
| 10 |
# π§ CONFIGURE: Replace with your EC2 public IP
|
| 11 |
+
API_URL = "http://3.14.153.135:5000/ask"
|
| 12 |
+
HEALTH_URL = "http://3.14.153.135:5000/health"
|
| 13 |
+
SIMPLE_TEST_URL = "http://3.14.153.135:5000/simple-test"
|
| 14 |
+
DEBUG_URL = "http://3.14.153.135:5000/debug"
|
| 15 |
|
| 16 |
def test_connection():
|
| 17 |
try:
|
| 18 |
+
print("=== TESTING CONNECTION ===")
|
| 19 |
+
response = requests.get(HEALTH_URL, timeout=30)
|
| 20 |
+
print(f"Connection test status: {response.status_code}")
|
| 21 |
+
print(f"Connection test response: {response.text}")
|
| 22 |
+
|
| 23 |
if response.status_code == 200:
|
| 24 |
return f"β
Connection successful! Status: {response.status_code}\nResponse: {response.text}"
|
| 25 |
else:
|
| 26 |
return f"β οΈ Connection returned status: {response.status_code}\nResponse: {response.text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
except Exception as e:
|
| 28 |
+
error_msg = f"Connection error: {str(e)}"
|
| 29 |
+
print(f"Connection error: {error_msg}")
|
| 30 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 31 |
+
return f"β {error_msg}"
|
| 32 |
|
| 33 |
+
def test_simple_endpoint():
|
| 34 |
try:
|
| 35 |
+
print("=== TESTING SIMPLE ENDPOINT ===")
|
| 36 |
+
response = requests.post(
|
| 37 |
+
SIMPLE_TEST_URL,
|
| 38 |
+
json={"question": "test question"},
|
| 39 |
+
timeout=30
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
print(f"Simple test status: {response.status_code}")
|
| 43 |
+
print(f"Simple test response: {response.text}")
|
| 44 |
+
|
| 45 |
if response.status_code == 200:
|
| 46 |
result = response.json()
|
| 47 |
+
return f"β
Simple test successful! SQL: {result.get('sql', 'N/A')}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
else:
|
| 49 |
+
return f"β Simple test failed: {response.status_code} - {response.text}", None
|
| 50 |
+
except Exception as e:
|
| 51 |
+
error_msg = f"Simple test error: {str(e)}"
|
| 52 |
+
print(f"Simple test error: {error_msg}")
|
| 53 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 54 |
+
return f"β {error_msg}", None
|
| 55 |
+
|
| 56 |
+
def test_debug_endpoint():
|
| 57 |
+
try:
|
| 58 |
+
print("=== TESTING DEBUG ENDPOINT ===")
|
| 59 |
+
response = requests.post(
|
| 60 |
+
DEBUG_URL,
|
| 61 |
+
json={"test": "data"},
|
| 62 |
+
timeout=30
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
print(f"Debug test status: {response.status_code}")
|
| 66 |
+
print(f"Debug test response: {response.text}")
|
| 67 |
+
|
| 68 |
+
return f"Debug response: {response.text}", None
|
| 69 |
except Exception as e:
|
| 70 |
+
error_msg = f"Debug test error: {str(e)}"
|
| 71 |
+
print(f"Debug test error: {error_msg}")
|
| 72 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 73 |
+
return f"β {error_msg}", None
|
| 74 |
|
| 75 |
def query_database(question):
|
| 76 |
if not question.strip():
|
| 77 |
+
return "", None, None, "β οΈ Please enter a question.", "", ""
|
| 78 |
|
| 79 |
try:
|
| 80 |
start_time = time.time()
|
| 81 |
+
print("\n" + "="*50)
|
| 82 |
+
print("=== NEW QUERY REQUEST ===")
|
| 83 |
+
print(f"Time: {time.strftime('%Y-%m-%d %H:%M:%S')}")
|
| 84 |
print(f"Question: {question}")
|
| 85 |
+
print("="*50)
|
| 86 |
+
|
| 87 |
+
# Prepare the request
|
| 88 |
+
headers = {
|
| 89 |
+
'Content-Type': 'application/json',
|
| 90 |
+
'User-Agent': 'HuggingFace-Space/1.0'
|
| 91 |
+
}
|
| 92 |
+
payload = {"question": question}
|
| 93 |
|
| 94 |
+
print(f"Request URL: {API_URL}")
|
| 95 |
+
print(f"Request headers: {headers}")
|
| 96 |
+
print(f"Request payload: {payload}")
|
| 97 |
+
|
| 98 |
+
# Make the request
|
| 99 |
+
print("Sending request...")
|
| 100 |
response = requests.post(
|
| 101 |
API_URL,
|
| 102 |
+
json=payload,
|
| 103 |
+
headers=headers,
|
| 104 |
+
timeout=300
|
| 105 |
)
|
| 106 |
|
| 107 |
elapsed_time = time.time() - start_time
|
| 108 |
+
print(f"\n=== RESPONSE RECEIVED ===")
|
| 109 |
print(f"Response time: {elapsed_time:.2f} seconds")
|
| 110 |
+
print(f"Response status: {response.status_code}")
|
| 111 |
+
print(f"Response headers: {dict(response.headers)}")
|
| 112 |
+
print(f"Response text length: {len(response.text)} characters")
|
| 113 |
+
print(f"Response text: {response.text}")
|
| 114 |
+
|
| 115 |
+
# Check if response is empty
|
| 116 |
+
if not response.text:
|
| 117 |
+
error_msg = "Empty response from server"
|
| 118 |
+
print(f"ERROR: {error_msg}")
|
| 119 |
+
return "", None, None, f"β {error_msg}", f"Request time: {elapsed_time:.2f}s", "Empty response"
|
| 120 |
|
| 121 |
+
# Try to parse JSON response
|
| 122 |
try:
|
| 123 |
result = response.json()
|
| 124 |
+
print(f"Parsed JSON successfully: {type(result)}")
|
| 125 |
+
except json.JSONDecodeError as e:
|
| 126 |
+
error_msg = f"Invalid JSON response: {str(e)}"
|
| 127 |
+
print(f"ERROR: {error_msg}")
|
| 128 |
+
print(f"Response text (first 500 chars): {response.text[:500]}")
|
| 129 |
+
return "", None, None, f"β {error_msg}", f"Request time: {elapsed_time:.2f}s", "JSON parse error"
|
| 130 |
|
| 131 |
+
# Check HTTP status
|
| 132 |
if response.status_code != 200:
|
| 133 |
error_msg = result.get("error", f"HTTP {response.status_code}")
|
| 134 |
+
print(f"ERROR: HTTP status {response.status_code}: {error_msg}")
|
| 135 |
+
return "", None, None, f"β Server error: {error_msg}", f"Request time: {elapsed_time:.2f}s", "HTTP error"
|
| 136 |
|
| 137 |
+
# Check for application error
|
| 138 |
if "error" in result:
|
| 139 |
+
error_msg = result['error']
|
| 140 |
+
print(f"ERROR: Application error: {error_msg}")
|
| 141 |
+
return "", None, None, f"β {error_msg}", f"Request time: {elapsed_time:.2f}s", "Application error"
|
| 142 |
|
| 143 |
+
# Extract data
|
| 144 |
sql = result.get("sql", "N/A")
|
| 145 |
rows = result.get("result", [])
|
| 146 |
chart_data = result.get("chart")
|
| 147 |
|
| 148 |
+
print(f"\n=== EXTRACTED DATA ===")
|
| 149 |
+
print(f"SQL: {sql[:100] if sql else 'None'}...")
|
| 150 |
+
print(f"Rows count: {len(rows)}")
|
| 151 |
print(f"Chart data received: {'Yes' if chart_data else 'No'}")
|
| 152 |
print(f"Chart data length: {len(chart_data) if chart_data else 0}")
|
| 153 |
|
| 154 |
+
# Create DataFrame
|
| 155 |
df = pd.DataFrame(rows) if rows else pd.DataFrame()
|
| 156 |
+
print(f"DataFrame shape: {df.shape}")
|
| 157 |
|
| 158 |
+
# Process chart
|
| 159 |
chart_image = None
|
| 160 |
if chart_data:
|
| 161 |
try:
|
|
|
|
| 165 |
except Exception as e:
|
| 166 |
print(f"Error decoding chart: {e}")
|
| 167 |
|
| 168 |
+
# Prepare details
|
| 169 |
details = f"Request time: {elapsed_time:.2f}s\n"
|
| 170 |
+
details += f"Status code: {response.status_code}\n"
|
| 171 |
details += f"Rows returned: {len(rows)}\n"
|
| 172 |
+
details += f"Chart generated: {'Yes' if chart_data else 'No'}\n"
|
| 173 |
+
details += f"Response size: {len(response.text)} bytes"
|
| 174 |
+
|
| 175 |
+
print(f"=== REQUEST COMPLETED SUCCESSFULLY ===")
|
| 176 |
|
| 177 |
+
return sql, df, chart_image, "β
Query completed successfully!", details, "Success"
|
| 178 |
|
| 179 |
except requests.exceptions.ConnectionError as e:
|
| 180 |
+
error_msg = f"Connection failed: {str(e)}"
|
| 181 |
+
print(f"CONNECTION ERROR: {error_msg}")
|
| 182 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 183 |
+
return "", None, None, f"β {error_msg}", "Connection error", "Connection error"
|
| 184 |
except requests.exceptions.Timeout:
|
| 185 |
+
error_msg = "Request timed out after 300 seconds"
|
| 186 |
+
print(f"TIMEOUT ERROR: {error_msg}")
|
| 187 |
+
return "", None, None, f"β±οΈ {error_msg}", "Timeout error", "Timeout error"
|
| 188 |
+
except requests.exceptions.RequestException as e:
|
| 189 |
+
error_msg = f"Request exception: {str(e)}"
|
| 190 |
+
print(f"REQUEST ERROR: {error_msg}")
|
| 191 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 192 |
+
return "", None, None, f"β {error_msg}", "Request error", "Request error"
|
| 193 |
except Exception as e:
|
| 194 |
+
error_msg = f"Unexpected error: {str(e)}"
|
| 195 |
+
print(f"UNEXPECTED ERROR: {error_msg}")
|
| 196 |
+
print(f"Traceback: {traceback.format_exc()}")
|
| 197 |
+
return "", None, None, f"π¨ {error_msg}", f"Error: {str(e)}", "Unexpected error"
|
| 198 |
|
| 199 |
# π¨ Theme: Enterprise Dark Blue
|
| 200 |
theme = gr.themes.Default(
|
|
|
|
| 228 |
)
|
| 229 |
submit_btn = gr.Button("π Generate SQL & Results", variant="primary")
|
| 230 |
|
| 231 |
+
gr.Markdown("### π§ Connection Tests")
|
| 232 |
+
with gr.Accordion("Connection Tests", open=True):
|
| 233 |
+
test_btn = gr.Button("Test Connection to EC2")
|
| 234 |
+
connection_status = gr.Textbox(label="Connection Status", interactive=False)
|
| 235 |
+
|
| 236 |
+
simple_test_btn = gr.Button("Test Simple Endpoint")
|
| 237 |
+
simple_test_status = gr.Textbox(label="Simple Test Status", interactive=False)
|
| 238 |
+
|
| 239 |
+
debug_test_btn = gr.Button("Test Debug Endpoint")
|
| 240 |
+
debug_test_status = gr.Textbox(label="Debug Test Status", interactive=False)
|
| 241 |
|
| 242 |
gr.Markdown("### π‘ Example Queries")
|
| 243 |
gr.Examples(
|
|
|
|
| 279 |
)
|
| 280 |
|
| 281 |
gr.Markdown("### π Request Details")
|
| 282 |
+
request_details = gr.Textbox(label="Request Details", interactive=False, lines=6)
|
| 283 |
+
|
| 284 |
+
gr.Markdown("### π Error Details")
|
| 285 |
+
error_details = gr.Textbox(label="Error Details", interactive=False, lines=4)
|
| 286 |
|
| 287 |
# Events
|
| 288 |
test_btn.click(
|
|
|
|
| 290 |
outputs=[connection_status]
|
| 291 |
)
|
| 292 |
|
| 293 |
+
simple_test_btn.click(
|
| 294 |
+
fn=test_simple_endpoint,
|
| 295 |
+
outputs=[simple_test_status]
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
debug_test_btn.click(
|
| 299 |
+
fn=test_debug_endpoint,
|
| 300 |
+
outputs=[debug_test_status]
|
| 301 |
)
|
| 302 |
|
| 303 |
submit_btn.click(
|
| 304 |
fn=query_database,
|
| 305 |
inputs=question_input,
|
| 306 |
+
outputs=[sql_output, results_output, chart_output, status, request_details, error_details]
|
| 307 |
)
|
| 308 |
|
| 309 |
# Launch
|