Shreyass334 commited on
Commit
e8a8438
Β·
verified Β·
1 Parent(s): 8d19c16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -128
app.py CHANGED
@@ -6,71 +6,10 @@ 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():
@@ -85,22 +24,16 @@ def query_database(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
 
@@ -108,8 +41,6 @@ def query_database(question):
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
@@ -130,26 +61,27 @@ def query_database(question):
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()
@@ -160,7 +92,7 @@ def query_database(question):
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}")
@@ -168,13 +100,13 @@ def query_database(question):
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)}"
@@ -204,11 +136,64 @@ theme = gr.themes.Default(
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>
@@ -226,36 +211,27 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant") as demo:
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"):
@@ -282,26 +258,27 @@ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant") as demo:
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
  # Launch
 
6
  import json
7
  import time
8
  import traceback
9
+ from PIL import Image
10
 
11
+ # πŸ”§ CONFIGURE: Replace with your Django server URL
12
+ DJANGO_API_URL = "http://your-django-server.com/api/openai-prompt/"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def query_database(question):
15
  if not question.strip():
 
24
  print("="*50)
25
 
26
  # Prepare the request
27
+ payload = {"prompt": question}
 
 
 
 
28
 
29
+ print(f"Request URL: {DJANGO_API_URL}")
 
30
  print(f"Request payload: {payload}")
31
 
32
  # Make the request
33
  print("Sending request...")
34
  response = requests.post(
35
+ DJANGO_API_URL,
36
+ json=payload,
 
37
  timeout=300
38
  )
39
 
 
41
  print(f"\n=== RESPONSE RECEIVED ===")
42
  print(f"Response time: {elapsed_time:.2f} seconds")
43
  print(f"Response status: {response.status_code}")
 
 
44
  print(f"Response text: {response.text}")
45
 
46
  # Check if response is empty
 
61
 
62
  # Check HTTP status
63
  if response.status_code != 200:
64
+ error_msg = result.get("message", 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
  # Check for application error
69
+ if "status" in result and result["status"] == "error":
70
+ error_msg = result.get("message", "Unknown error")
71
  print(f"ERROR: Application error: {error_msg}")
72
  return "", None, None, f"❌ {error_msg}", f"Request time: {elapsed_time:.2f}s", "Application error"
73
 
74
  # Extract data
75
+ conversational_response = result.get("response", "")
76
+ sql = result.get("sql", "")
77
  rows = result.get("result", [])
78
  chart_data = result.get("chart")
79
+ row_count = result.get("row_count", len(rows))
80
 
81
  print(f"\n=== EXTRACTED DATA ===")
82
  print(f"SQL: {sql[:100] if sql else 'None'}...")
83
+ print(f"Rows count: {row_count}")
84
  print(f"Chart data received: {'Yes' if chart_data else 'No'}")
 
85
 
86
  # Create DataFrame
87
  df = pd.DataFrame(rows) if rows else pd.DataFrame()
 
92
  if chart_data:
93
  try:
94
  image_bytes = base64.b64decode(chart_data)
95
+ chart_image = Image.open(BytesIO(image_bytes))
96
  print("Chart decoded successfully")
97
  except Exception as e:
98
  print(f"Error decoding chart: {e}")
 
100
  # Prepare details
101
  details = f"Request time: {elapsed_time:.2f}s\n"
102
  details += f"Status code: {response.status_code}\n"
103
+ details += f"Rows returned: {row_count}\n"
104
  details += f"Chart generated: {'Yes' if chart_data else 'No'}\n"
105
  details += f"Response size: {len(response.text)} bytes"
106
 
107
  print(f"=== REQUEST COMPLETED SUCCESSFULLY ===")
108
 
109
+ return sql, df, chart_image, conversational_response, details, "Success"
110
 
111
  except requests.exceptions.ConnectionError as e:
112
  error_msg = f"Connection failed: {str(e)}"
 
136
  font=["Inter", "sans-serif"]
137
  ).set(
138
  body_background_fill="*neutral_950",
139
+ background_fill_secondary="*neutral_900",
140
+ button_primary_background_fill="*primary_600",
141
+ button_primary_background_fill_hover="*primary_700",
142
+ button_secondary_background_fill="*neutral_800",
143
+ button_secondary_background_fill_hover="*neutral_700",
144
+ block_title_text_color="*primary_400",
145
+ block_label_text_color="*neutral_300",
146
+ input_background_fill="*neutral_800",
147
+ input_border_color="*neutral_700",
148
+ input_border_width="1px",
149
+ input_text_color="*neutral_100",
150
  )
151
 
152
  # πŸš€ UI Layout
153
+ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant", css="""
154
+ .example-btn {
155
+ background-color: #1e40af;
156
+ color: white;
157
+ border-radius: 8px;
158
+ padding: 8px 12px;
159
+ margin: 4px;
160
+ font-size: 0.9em;
161
+ border: none;
162
+ cursor: pointer;
163
+ transition: all 0.2s;
164
+ }
165
+ .example-btn:hover {
166
+ background-color: #1d4ed8;
167
+ transform: translateY(-1px);
168
+ }
169
+ .chatbot-container {
170
+ border: 1px solid #334155;
171
+ border-radius: 8px;
172
+ padding: 15px;
173
+ background-color: #1e293b;
174
+ min-height: 200px;
175
+ max-height: 400px;
176
+ overflow-y: auto;
177
+ }
178
+ .status-success {
179
+ color: #10b981;
180
+ font-weight: bold;
181
+ }
182
+ .status-error {
183
+ color: #ef4444;
184
+ font-weight: bold;
185
+ }
186
+ .status-warning {
187
+ color: #f59e0b;
188
+ font-weight: bold;
189
+ }
190
+ .chart-container {
191
+ border: 1px solid #334155;
192
+ border-radius: 8px;
193
+ padding: 10px;
194
+ background-color: #1e293b;
195
+ }
196
+ """) as demo:
197
  gr.HTML("""
198
  <div style="text-align: center; padding: 20px;">
199
  <h1 style="color: #3B82F6; margin-bottom: 5px;">πŸ“Š Enterprise SQL Assistant</h1>
 
211
  label="Natural Language Query",
212
  lines=3
213
  )
214
+ submit_btn = gr.Button("πŸš€ Generate SQL & Results", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
215
 
216
  gr.Markdown("### πŸ’‘ Example Queries")
217
+ with gr.Row():
218
+ with gr.Column():
219
+ example1 = gr.Button("How many members are there?", elem_classes=["example-btn"])
220
+ example2 = gr.Button("What is the total transaction amount?", elem_classes=["example-btn"])
221
+ example3 = gr.Button("Show members with their account balances", elem_classes=["example-btn"])
222
+ example4 = gr.Button("Which member has the highest balance?", elem_classes=["example-btn"])
223
+ with gr.Column():
224
+ example5 = gr.Button("Show transaction trends over time", elem_classes=["example-btn"])
225
+ example6 = gr.Button("Count of members by status", elem_classes=["example-btn"])
226
+ example7 = gr.Button("Show me the first 10 rows", elem_classes=["example-btn"])
227
+ example8 = gr.Button("What is the average age of members?", elem_classes=["example-btn"])
 
228
 
229
  with gr.Column(scale=2):
230
+ gr.Markdown("### πŸ€– AI Assistant Response")
231
+ chatbot_output = gr.Markdown(
232
+ label="AI Response",
233
+ elem_classes=["chatbot-container"]
234
+ )
235
 
236
  with gr.Tabs():
237
  with gr.Tab("SQL Query"):
 
258
  gr.Markdown("### πŸ” Error Details")
259
  error_details = gr.Textbox(label="Error Details", interactive=False, lines=4)
260
 
261
+ # Function to handle example query clicks
262
+ def set_example_query(example_text):
263
+ return example_text
 
 
 
 
 
 
 
264
 
265
+ # Events
266
+ # Example query buttons
267
+ for example_btn in [example1, example2, example3, example4, example5, example6, example7, example8]:
268
+ example_btn.click(
269
+ fn=set_example_query,
270
+ inputs=[example_btn],
271
+ outputs=[question_input]
272
+ ).then(
273
+ fn=query_database,
274
+ inputs=question_input,
275
+ outputs=[sql_output, results_output, chart_output, chatbot_output, request_details, error_details]
276
+ )
277
 
278
  submit_btn.click(
279
  fn=query_database,
280
  inputs=question_input,
281
+ outputs=[sql_output, results_output, chart_output, chatbot_output, request_details, error_details]
282
  )
283
 
284
  # Launch