Files changed (1) hide show
  1. gradio_app.py +128 -375
gradio_app.py CHANGED
@@ -1,408 +1,161 @@
1
- """Gradio frontend for Unified Financial & Demand Forecast API."""
 
 
 
2
 
3
  import gradio as gr
4
  import requests
5
  import os
6
- import re
7
- from typing import List, Tuple
8
 
9
- # Get API base URL from environment variable or use default
10
- API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:8000")
11
 
12
 
13
- def get_api_base_url() -> str:
14
- """Return the API base URL used by the frontend (for display)."""
15
- return API_BASE_URL
16
-
17
-
18
- def check_backend_health() -> Tuple[str, str]:
19
- """Call backend /health endpoint and return a simple result pair (text, error)."""
20
  try:
21
- resp = requests.get(f"{API_BASE_URL}/health", timeout=10)
22
- if resp.status_code == 200:
23
- j = resp.json()
24
- return f"OK: {j.get('status')} (v={j.get('version')})", ""
25
- return "HTTP {}".format(resp.status_code), resp.text
26
  except Exception as e:
27
- return "Error", str(e)
28
-
29
 
30
- def parse_history_input(history_str: str) -> List[float]:
31
- """Parse demand history from flexible user input."""
32
- tokens = [token for token in re.split(r"[\s,]+", history_str.strip()) if token]
33
- if len(tokens) < 2:
34
- raise ValueError("Please provide at least 2 historical values.")
35
- return [float(token) for token in tokens]
36
 
 
 
 
 
37
 
38
- def call_ewa_forecast(history_str: str, horizon: int, alpha: float = None,
39
- beta: float = None, confidence: float = 0.95) -> Tuple[str, str]:
40
- """Call EWA forecast API."""
41
  try:
42
- history = parse_history_input(history_str)
43
-
44
- payload = {
45
- "history": history,
46
- "horizon": horizon,
47
- "confidence_level": confidence,
48
- }
49
- if alpha is not None and alpha > 0:
50
- payload["alpha"] = alpha
51
- if beta is not None and beta > 0:
52
- payload["beta"] = beta
53
-
54
- response = requests.post(
55
- f"{API_BASE_URL}/predict",
56
- json=payload,
57
- timeout=30
58
- )
59
-
60
- if response.status_code == 200:
61
- result = response.json()
62
- ci_lines = '\n'.join([f" - Period {i+1}: [{ci['lower']:.2f}, {ci['upper']:.2f}]" for i, ci in enumerate(result.get('confidence_intervals', []))])
63
- forecast_text = f"""
64
- ### Forecast summary
65
 
66
- The model used the historical values you entered and generated the forecast below.
67
 
68
- **Forecast Values:** {result.get('forecast', [])}
69
 
70
- **Model Type:** {result.get('model_type', 'Unknown')}
 
 
 
71
 
72
- **Alpha (smoothing):** {result.get('alpha', 'N/A')}
 
 
 
 
 
 
 
73
 
74
- **Beta (trend):** {result.get('beta', 'N/A')}
75
 
76
- **RMSE:** {result.get('rmse', 'N/A'):.4f}
77
 
78
- **Confidence Intervals (95%):**
79
- {ci_lines}
80
- """
81
- return forecast_text, ""
82
- else:
83
- error_text = f"API Error {response.status_code}: {response.text}"
84
- return "", error_text
85
-
86
  except Exception as e:
87
- return "", f"Error: {str(e)}"
88
-
89
 
90
- def call_distress_prediction(user_id: str, total_spend: float, txn_count: float,
91
- total_spend_30d: float, max_daily_spend_30d: float,
92
- txn_count_30d: float, ewa_usage: float = 0,
93
- ewa_total: float = 0, ewa_avg: float = 0,
94
- ewa_max: float = 0) -> Tuple[str, str]:
95
- """Call Financial Distress Prediction API."""
96
  try:
97
- payload = {
98
- "user_id": user_id if user_id else "unknown",
99
- "total_spend": total_spend,
100
- "txn_count": txn_count,
101
- "total_spend_30d": total_spend_30d,
102
- "max_daily_spend_30d": max_daily_spend_30d,
103
- "txn_count_30d": txn_count_30d,
104
- "ewa_usage_count": ewa_usage,
105
- "ewa_total_amount": ewa_total,
106
- "ewa_avg_amount": ewa_avg,
107
- "ewa_max_amount": ewa_max,
108
- }
109
-
110
- response = requests.post(
111
- f"{API_BASE_URL}/distress/predict",
112
- json=payload,
113
- timeout=30
114
- )
115
-
116
- if response.status_code == 200:
117
- result = response.json()
118
- risk_score = result.get('risk_score', 0)
119
-
120
- # Color code based on risk level
121
- if risk_score < 0.33:
122
- risk_level = "Low risk"
123
- elif risk_score < 0.67:
124
- risk_level = "Medium risk"
125
- else:
126
- risk_level = "High risk"
127
-
128
- result_text = f"""
129
- ### Risk summary
130
-
131
- This is an estimated risk score based on the spending and transaction features you provided.
132
-
133
- **User ID:** {result.get('user_id', 'Unknown')}
134
-
135
- **Risk Score:** {risk_score:.2%}
136
-
137
- **Risk Level:** {risk_level}
138
-
139
- **Model Type:** {result.get('model_type', 'Unknown')}
140
-
141
- **Timestamp:** {result.get('timestamp', 'N/A')}
142
-
143
- ---
144
- *Score interpretation: 0 = No risk, 1 = Highest risk of financial distress*
145
- """
146
- return result_text, ""
147
  else:
148
- error_text = f"API Error {response.status_code}: {response.text}"
149
- return "", error_text
150
-
151
  except Exception as e:
152
- return "", f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- # Build Gradio interface with tabs
156
- with gr.Blocks(title="Financial & Demand Forecast API") as demo:
157
  gr.Markdown("""
158
- # Financial & Demand Forecast API
 
 
159
 
160
- Forecast demand or estimate financial distress risk from one place.
161
- """)
162
- # Display configured backend URL and provide health check
163
  with gr.Row():
164
- api_url_md = gr.Markdown(f"**Backend API (API_BASE_URL):** {get_api_base_url()}")
165
- health_btn = gr.Button("Check Backend Health")
166
- health_out = gr.Textbox(label="Health Check Result", interactive=False)
167
-
168
- with gr.Tabs():
169
- # Tab 1: EWA Demand Forecast
170
- with gr.Tab("EWA Demand Forecast"):
171
- gr.Markdown("""
172
- ### EWA (Exponential Weighted Average) Forecasting
173
-
174
- Input your historical demand data and get forecasts with confidence intervals.
175
-
176
- **How to use:**
177
- 1. Enter historical demand values on separate lines or as comma/space-separated numbers (feature: `history`)
178
- 2. Set forecast horizon (feature: `horizon`)
179
- 3. Optionally set alpha and beta smoothing parameters (features: `alpha`, `beta`)
180
- """)
181
-
182
- with gr.Row():
183
- with gr.Column():
184
- history_input = gr.TextArea(
185
- label="Historical Demand Values [feature: history]",
186
- placeholder="10\n12\n15\n14\n16\n\nYou can also paste: 10, 12, 15, 14, 16",
187
- lines=6
188
- )
189
- horizon_input = gr.Slider(
190
- label="Forecast Horizon [feature: horizon]",
191
- minimum=1,
192
- maximum=20,
193
- value=5,
194
- step=1
195
- )
196
- alpha_input = gr.Slider(
197
- label="Alpha (level smoothing) [feature: alpha]",
198
- minimum=0,
199
- maximum=1,
200
- value=0,
201
- step=0.01
202
- )
203
- beta_input = gr.Slider(
204
- label="Beta (trend smoothing) [feature: beta]",
205
- minimum=0,
206
- maximum=1,
207
- value=0,
208
- step=0.01
209
- )
210
- confidence_input = gr.Slider(
211
- label="Confidence Level [feature: confidence_level]",
212
- minimum=0.8,
213
- maximum=0.99,
214
- value=0.95,
215
- step=0.01
216
- )
217
- forecast_btn = gr.Button("Generate Forecast")
218
-
219
- with gr.Column():
220
- forecast_output = gr.Markdown(label="Results")
221
- forecast_error = gr.Textbox(label="Error", visible=False, interactive=False)
222
-
223
- forecast_btn.click(
224
- call_ewa_forecast,
225
- inputs=[history_input, horizon_input, alpha_input, beta_input, confidence_input],
226
- outputs=[forecast_output, forecast_error]
227
- )
228
-
229
- gr.Markdown("##### Quick examples")
230
- gr.Examples(
231
- examples=[
232
- ["10\n12\n15\n14\n16", 5, 0.0, 0.0, 0.95],
233
- ["120\n135\n148\n160\n155\n172", 6, 0.3, 0.1, 0.95],
234
- ],
235
- inputs=[history_input, horizon_input, alpha_input, beta_input, confidence_input],
236
- label="Click an example to fill the form",
237
- )
238
-
239
- # hook up health check button
240
- def _health_click():
241
- text, err = check_backend_health()
242
- if err:
243
- return f"Error: {err}"
244
- return text
245
-
246
- health_btn.click(_health_click, inputs=None, outputs=[health_out])
247
-
248
- # Tab 2: Financial Distress Prediction
249
- with gr.Tab("Financial Distress Risk"):
250
- gr.Markdown("""
251
- ### Financial Distress Prediction
252
-
253
- Enter a few spending and transaction values to estimate risk.
254
-
255
- **Input Features:**
256
- - **Total Spending** [feature: `total_spend`]: Total amount spent
257
- - **Transaction Count** [feature: `txn_count`]: Total number of transactions
258
- - **30-Day Spending** [feature: `total_spend_30d`]: Spending in last 30 days
259
- - **Max Daily Spend** [feature: `max_daily_spend_30d`]: Maximum daily spending in last 30 days
260
- - **30-Day Transaction Count** [feature: `txn_count_30d`]: Transactions in last 30 days
261
- - **EWA Usage** [feature: `ewa_usage_count`, `ewa_total_amount`, `ewa_avg_amount`, `ewa_max_amount`]: Integration with EWA demand forecast (optional)
262
-
263
- **Output:** Risk score from 0 (no risk) to 1 (highest risk)
264
- """)
265
-
266
- with gr.Row():
267
- with gr.Column():
268
- user_id_input = gr.Textbox(
269
- label="User ID (optional)",
270
- placeholder="e.g., user_12345"
271
- )
272
-
273
- gr.Markdown("##### Core spending features")
274
-
275
- total_spend_input = gr.Number(
276
- label="Total Spending [feature: total_spend]",
277
- value=5000
278
- )
279
- txn_count_input = gr.Number(
280
- label="Total Transaction Count [feature: txn_count]",
281
- value=50
282
- )
283
-
284
- total_spend_30d_input = gr.Number(
285
- label="Total Spending (30 days) [feature: total_spend_30d]",
286
- value=1500
287
- )
288
- max_daily_spend_input = gr.Number(
289
- label="Max Daily Spending (30 days) [feature: max_daily_spend_30d]",
290
- value=300
291
- )
292
- txn_count_30d_input = gr.Number(
293
- label="Transaction Count (30 days) [feature: txn_count_30d]",
294
- value=15
295
- )
296
-
297
- with gr.Accordion("Optional EWA usage features", open=False):
298
- gr.Markdown("These fields are optional. Leave them at 0 if you do not have EWA usage data.")
299
- ewa_usage_input = gr.Number(
300
- label="EWA Usage Count [feature: ewa_usage_count]",
301
- value=0
302
- )
303
- ewa_total_input = gr.Number(
304
- label="EWA Total Amount [feature: ewa_total_amount]",
305
- value=0
306
- )
307
- ewa_avg_input = gr.Number(
308
- label="EWA Average Amount [feature: ewa_avg_amount]",
309
- value=0
310
- )
311
- ewa_max_input = gr.Number(
312
- label="EWA Max Amount [feature: ewa_max_amount]",
313
- value=0
314
- )
315
-
316
- distress_btn = gr.Button("Analyze Risk")
317
-
318
- with gr.Column():
319
- distress_output = gr.Markdown(label="Results")
320
- distress_error = gr.Textbox(label="Error", visible=False, interactive=False)
321
-
322
- distress_btn.click(
323
- call_distress_prediction,
324
- inputs=[
325
- user_id_input, total_spend_input, txn_count_input,
326
- total_spend_30d_input, max_daily_spend_input, txn_count_30d_input,
327
- ewa_usage_input, ewa_total_input, ewa_avg_input, ewa_max_input
328
- ],
329
- outputs=[distress_output, distress_error]
330
- )
331
-
332
- gr.Markdown("##### Quick examples")
333
- gr.Examples(
334
- examples=[
335
- ["user_12345", 5000, 50, 1500, 300, 15, 0, 0, 0, 0],
336
- ["user_67890", 12000, 120, 4200, 800, 40, 6, 900, 150, 250],
337
- ],
338
- inputs=[
339
- user_id_input, total_spend_input, txn_count_input,
340
- total_spend_30d_input, max_daily_spend_input, txn_count_30d_input,
341
- ewa_usage_input, ewa_total_input, ewa_avg_input, ewa_max_input,
342
- ],
343
- label="Click an example to fill the risk form",
344
- )
345
-
346
- # Tab 3: Help
347
- with gr.Tab("Help"):
348
- gr.Markdown(f"""
349
- ### What this app does
350
-
351
- This app is for end users who want to forecast demand or estimate financial distress risk.
352
-
353
- #### Forecasting
354
-
355
- - **EWA Demand Forecast**: paste historical values, choose a horizon, and get a forecast.
356
- - **Financial Distress Risk**: enter spending and transaction fields to estimate risk.
357
- - **Health check**: confirms the backend is reachable.
358
-
359
- **Base URL:** `{API_BASE_URL}`
360
-
361
- #### How to use
362
-
363
- 1. Enter values in the form fields.
364
- 2. Click the action button.
365
- 3. Read the result shown below the form.
366
-
367
- #### Feature mapping
368
-
369
- | Field | Model feature |
370
- |---|---|
371
- | Historical demand values | `history` |
372
- | Forecast horizon | `horizon` |
373
- | Alpha | `alpha` |
374
- | Beta | `beta` |
375
- | Confidence level | `confidence_level` |
376
- | Total Spending | `total_spend` |
377
- | Transaction Count | `txn_count` |
378
- | 30-Day Spending | `total_spend_30d` |
379
- | Max Daily Spend | `max_daily_spend_30d` |
380
- | 30-Day Transaction Count | `txn_count_30d` |
381
- | EWA Usage Count | `ewa_usage_count` |
382
- | EWA Total Amount | `ewa_total_amount` |
383
- | EWA Average Amount | `ewa_avg_amount` |
384
- | EWA Max Amount | `ewa_max_amount` |
385
-
386
- #### Behind the scenes
387
-
388
- - `POST /predict`
389
- - `POST /predict/batch`
390
- - `POST /distress/predict`
391
- - `GET /health`
392
- - `GET /model-info`
393
- - `GET /docs`
394
-
395
- #### Notes
396
-
397
- - EWA forecast uses the values you enter to generate a future range.
398
- - Distress risk is estimated from the spending and transaction features above.
399
- - If the backend is unavailable, the health check will show an error.
400
- """)
401
 
 
402
 
403
- if __name__ == "__main__":
404
- demo.launch(
405
- server_name="0.0.0.0",
406
- server_port=7860,
407
- share=False,
 
 
 
 
 
 
 
 
408
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Payactiv Risk Prediction Dashboard
3
+ Gradio frontend connected to the Payactiv Railway API.
4
+ """
5
 
6
  import gradio as gr
7
  import requests
8
  import os
 
 
9
 
10
+ API_BASE_URL = os.getenv("API_BASE_URL", "https://web-production-00c9c.up.railway.app")
 
11
 
12
 
13
+ def check_health():
 
 
 
 
 
 
14
  try:
15
+ r = requests.get(f"{API_BASE_URL}/health", timeout=10)
16
+ if r.status_code == 200:
17
+ return "Connected"
18
+ return f"Error: {r.status_code}"
 
19
  except Exception as e:
20
+ return f"Unreachable: {str(e)}"
 
21
 
 
 
 
 
 
 
22
 
23
+ def lookup_user(user_id: str):
24
+ user_id = user_id.strip()
25
+ if not user_id:
26
+ return "Please enter a User ID.", "", "", ""
27
 
 
 
 
28
  try:
29
+ ewa_r = requests.get(f"{API_BASE_URL}/user_risk/{user_id}", timeout=30)
30
+ if ewa_r.status_code == 404:
31
+ return f"User '{user_id}' not found. Please check the ID and try again.", "", "", ""
32
+ ewa = ewa_r.json()
33
+ ewa_result = f"""
34
+ ## EWA Demand Prediction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ **Predicted Withdrawals:** {ewa['predicted_ewa_count']}
37
 
38
+ **Demand Tier:** {ewa['demand_tier']}
39
 
40
+ **Risk Score:** {ewa['predicted_score']}
41
+ """
42
+ except Exception as e:
43
+ ewa_result = f"EWA model error: {str(e)}"
44
 
45
+ try:
46
+ fd_r = requests.get(f"{API_BASE_URL}/distress_risk/{user_id}", timeout=30)
47
+ if fd_r.status_code == 404:
48
+ fd_result = "User not found in Financial Distress model."
49
+ else:
50
+ fd = fd_r.json()
51
+ fd_result = f"""
52
+ ## Financial Distress Prediction
53
 
54
+ **Distress Probability:** {fd['distress_probability']:.1%}
55
 
56
+ **Financially Distressed:** {fd['financially_distressed']}
57
 
58
+ **Risk Level:** {fd['risk_level']}
59
+ """
 
 
 
 
 
 
60
  except Exception as e:
61
+ fd_result = f"Distress model error: {str(e)}"
 
62
 
 
 
 
 
 
 
63
  try:
64
+ feat_r = requests.get(f"{API_BASE_URL}/top_features/{user_id}", timeout=30)
65
+ if feat_r.status_code == 200:
66
+ drivers = feat_r.json().get("top_drivers", [])
67
+ lines = "\n".join([
68
+ f"{d['rank']}. **{d['feature']}** = {d['value']} → {d['direction']}"
69
+ for d in drivers
70
+ ])
71
+ drivers_result = f"## Top EWA Demand Drivers\n\n{lines}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  else:
73
+ drivers_result = ""
 
 
74
  except Exception as e:
75
+ drivers_result = f"Driver error: {str(e)}"
76
+
77
+ try:
78
+ ewa_tier = ewa_r.json().get("demand_tier", "Unknown")
79
+ fd_level = fd_r.json().get("risk_level", "Unknown")
80
+
81
+ if ewa_tier == "High" and fd_level == "High":
82
+ action = "Urgent — reserve liquidity and initiate outreach immediately."
83
+ elif ewa_tier == "High" and fd_level != "High":
84
+ action = "Reserve higher liquidity. User is a heavy EWA user but financially stable."
85
+ elif ewa_tier != "High" and fd_level == "High":
86
+ action = "Financial wellness outreach recommended. User is struggling but not using EWA heavily."
87
+ else:
88
+ action = "No immediate action needed. Monitor regularly."
89
+
90
+ summary = f"""
91
+ ## Summary for {user_id}
92
 
93
+ | | Result |
94
+ |---|---|
95
+ | EWA Demand | {ewa_tier} |
96
+ | Financial Distress | {fd_level} |
97
+ | Recommended Action | {action} |
98
+ """
99
+ except:
100
+ summary = ""
101
+
102
+ return summary, ewa_result, fd_result, drivers_result
103
+
104
+
105
+ with gr.Blocks(title="Payactiv Risk Prediction Dashboard") as demo:
106
 
 
 
107
  gr.Markdown("""
108
+ # Payactiv Risk Prediction Dashboard
109
+ Predict EWA withdrawal demand and financial distress risk for any user.
110
+ """)
111
 
 
 
 
112
  with gr.Row():
113
+ api_status = gr.Markdown(f"**Backend:** {API_BASE_URL}")
114
+ health_btn = gr.Button("Check Connection", scale=0)
115
+ health_out = gr.Textbox(label="Status", interactive=False, scale=0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ gr.Markdown("---")
118
 
119
+ with gr.Row():
120
+ user_id_input = gr.Textbox(
121
+ label="User ID",
122
+ placeholder="e.g. Mymo1002027",
123
+ scale=3
124
+ )
125
+ search_btn = gr.Button("Get Prediction", variant="primary", scale=1)
126
+
127
+ gr.Markdown("##### Quick examples")
128
+ gr.Examples(
129
+ examples=[["Mymo1002027"], ["Mymo1002233"], ["Mymo1002952"]],
130
+ inputs=[user_id_input],
131
+ label="Click to load a sample user"
132
  )
133
+
134
+ gr.Markdown("---")
135
+
136
+ summary_out = gr.Markdown()
137
+
138
+ with gr.Row():
139
+ ewa_out = gr.Markdown()
140
+ fd_out = gr.Markdown()
141
+
142
+ drivers_out = gr.Markdown()
143
+
144
+ search_btn.click(
145
+ lookup_user,
146
+ inputs=[user_id_input],
147
+ outputs=[summary_out, ewa_out, fd_out, drivers_out]
148
+ )
149
+ user_id_input.submit(
150
+ lookup_user,
151
+ inputs=[user_id_input],
152
+ outputs=[summary_out, ewa_out, fd_out, drivers_out]
153
+ )
154
+ health_btn.click(check_health, outputs=[health_out])
155
+
156
+
157
+ if __name__ == "__main__":
158
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
159
+
160
+
161
+