Shreyass334 commited on
Commit
2bbb157
Β·
verified Β·
1 Parent(s): d645da5

Update App.py

Browse files
Files changed (1) hide show
  1. App.py +307 -0
App.py CHANGED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import pandas as pd
4
+ import base64
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:
162
+ image_bytes = base64.b64decode(chart_data)
163
+ chart_image = BytesIO(image_bytes)
164
+ print("Chart decoded successfully")
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(
201
+ primary_hue="blue",
202
+ secondary_hue="gray",
203
+ neutral_hue="slate",
204
+ font=["Inter", "sans-serif"]
205
+ ).set(
206
+ body_background_fill="*neutral_950",
207
+ background_fill_secondary="*neutral_900"
208
+ )
209
+
210
+ # πŸš€ UI Layout
211
+ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant") as demo:
212
+ gr.HTML("""
213
+ <div style="text-align: center; padding: 20px;">
214
+ <h1 style="color: #3B82F6; margin-bottom: 5px;">πŸ“Š Enterprise SQL Assistant</h1>
215
+ <p style="color: #9CA3AF; font-size: 1.1em; margin-top: 0;">
216
+ Ask questions about your data. Get SQL, results, and insights.
217
+ </p>
218
+ </div>
219
+ """)
220
+
221
+ with gr.Row():
222
+ with gr.Column(scale=1):
223
+ gr.Markdown("### πŸ” Ask a Question")
224
+ question_input = gr.Textbox(
225
+ placeholder="E.g., How many members are there?",
226
+ label="Natural Language Query",
227
+ lines=3
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.Markdown("""
244
+ Try these example queries:
245
+
246
+ - How many members are there?
247
+ - What is the total transaction amount?
248
+ - Show members with their account balances
249
+ - Which member has the highest balance?
250
+ - Show transaction trends over time
251
+ - Count of members by status
252
+ - Show me the first 10 rows
253
+ - What is the average age of members?
254
+ """)
255
+
256
+ with gr.Column(scale=2):
257
+ gr.Markdown("### πŸ“„ Results")
258
+ status = gr.Textbox(label="Status", interactive=False)
259
+
260
+ with gr.Tabs():
261
+ with gr.Tab("SQL Query"):
262
+ sql_output = gr.Code(label="", language="sql")
263
+
264
+ with gr.Tab("Data Results"):
265
+ results_output = gr.Dataframe(
266
+ label="Query Results",
267
+ interactive=False,
268
+ wrap=True
269
+ )
270
+
271
+ with gr.Tab("Visual Insights"):
272
+ chart_output = gr.Image(
273
+ label="Chart",
274
+ type="pil",
275
+ height=400,
276
+ elem_classes="chart-container"
277
+ )
278
+
279
+ gr.Markdown("### πŸ“Š Request Details")
280
+ request_details = gr.Textbox(label="Request Details", interactive=False, lines=6)
281
+
282
+ gr.Markdown("### πŸ” Error Details")
283
+ error_details = gr.Textbox(label="Error Details", interactive=False, lines=4)
284
+
285
+ # Events
286
+ test_btn.click(
287
+ fn=test_connection,
288
+ outputs=[connection_status]
289
+ )
290
+
291
+ simple_test_btn.click(
292
+ fn=test_simple_endpoint,
293
+ outputs=[simple_test_status]
294
+ )
295
+
296
+ debug_test_btn.click(
297
+ fn=test_debug_endpoint,
298
+ outputs=[debug_test_status]
299
+ )
300
+
301
+ submit_btn.click(
302
+ fn=query_database,
303
+ inputs=question_input,
304
+ outputs=[sql_output, results_output, chart_output, status, request_details, error_details]
305
+ )
306
+
307
+ #