VectorV17 commited on
Commit
e48035a
·
verified ·
1 Parent(s): 04e0b57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -82
app.py CHANGED
@@ -16,7 +16,7 @@ from imblearn.over_sampling import SMOTE
16
  from imblearn.pipeline import Pipeline as ImbPipeline
17
 
18
  # =====================================================================
19
- # 1. CORE PIPELINE TRAINING (Fast Optimization Layout)
20
  # =====================================================================
21
  print("Initializing and training the Stacking Pipeline...")
22
 
@@ -26,8 +26,9 @@ df = pd.read_csv('loan_dataset.csv')
26
  X = df.drop('BAD', axis=1)
27
  y = df['BAD']
28
 
 
29
  num_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
30
- cat_cols = X.select_dtypes(include=['object']).columns.tolist()
31
 
32
  # Fast Outlier Rectification via IQR Capping
33
  def cap_outliers_iqr(data, columns):
@@ -45,7 +46,7 @@ def cap_outliers_iqr(data, columns):
45
 
46
  X_cleaned = cap_outliers_iqr(X, num_cols)
47
 
48
- # Transformers
49
  num_pipeline = Pipeline([
50
  ('imputer', KNNImputer(n_neighbors=5)),
51
  ('scaler', StandardScaler())
@@ -61,7 +62,7 @@ preprocessor = ColumnTransformer([
61
  ('cat', cat_pipeline, cat_cols)
62
  ])
63
 
64
- # Streamlined High-Speed Base Learners
65
  rf_base = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42, n_jobs=-1)
66
  xgb_base = XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=5, eval_metric='logloss', random_state=42, n_jobs=-1)
67
 
@@ -109,99 +110,118 @@ def evaluate_loan_risk(loan, mortdue, value, reason, job, yoj, derog, delinq, cl
109
  prediction_proba = production_pipeline.predict_proba(input_data)[0]
110
  risk_of_default = prediction_proba[1]
111
 
112
- # Generate clean output cards
113
  if risk_of_default > 0.40:
114
- decision = "❌ RISK ASSESSMENT: LOAN APPLICATION REJECTED"
115
- explanation = "The risk metrics calculated by the Stacking Ensemble cross-validation profile indicate an elevated default probability threshold. Application does not meet current fiscal safety rules."
 
 
116
  else:
117
- decision = "✅ RISK ASSESSMENT: LOAN APPLICATION APPROVED"
118
- explanation = "The client profile demonstrates an established pattern of capital control, manageable debt-to-income limits, and minimal adverse filings. Proceed with standard capitalization."
 
 
119
 
120
  metrics_html = f"""
121
- <div style="background-color: #1a202c; color: #ffffff; padding: 20px; border-radius: 12px; border: 1px solid #2d3748;">
122
- <h3 style="margin-top: 0; color: #38bdf8; font-size: 1.3rem; font-weight: 700;">{decision}</h3>
123
- <p style="color: #cbd5e1; font-size: 0.95rem; line-height: 1.5; margin-bottom: 15px;">{explanation}</p>
124
- <hr style="border-color: #2d3748; margin-bottom: 15px;">
125
- <div style="display: flex; justify-content: space-between; font-family: monospace; font-size: 1rem;">
126
- <div><span style="color: #94a3b8;">DEFAULT PROBABILITY:</span> <strong style="color: {'#ef4444' if risk_of_default > 0.40 else '#22c55e'}">{risk_of_default * 100:.2f}%</strong></div>
127
- <div><span style="color: #94a3b8;">PIPELINE CONFIDENCE:</span> <strong style="color: #38bdf8;">{max(prediction_proba) * 100:.2f}%</strong></div>
 
 
 
 
 
128
  </div>
129
  </div>
130
  """
131
  return metrics_html
132
 
133
  # =====================================================================
134
- # 3. ELEGANT GRAPHIC LAYOUT AND STYLING (Gradio Blocks)
135
  # =====================================================================
136
  custom_css = """
137
- #main_container { background-color: #f8fafc; padding: 20px; font-family: 'Inter', sans-serif; }
138
- .block_header { text-align: center; margin-bottom: 25px; border-bottom: 2px solid #e2e8f0; padding-bottom: 15px; }
139
- .section_box { border: 1px solid #e2e8f0; background: #ffffff; padding: 18px; border-radius: 10px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
140
- .section_title { color: #1e293b; font-size: 1.1rem; font-weight: 600; margin-bottom: 12px; display: flex; align-items: center; gap: 8px; }
 
141
  """
142
 
143
- with io.Blocks(css=custom_css, title="AI Loan Underwriting Portal") as app:
 
144
 
145
- with io.Div(elem_id="main_container"):
146
- # Header Graphic Title
147
- with io.Div(elem_classes="block_header"):
148
- io.Markdown("# 🏦 Automated FinTech Loan Underwriting Interface")
149
- io.Markdown("Production underwriting dashboard fueled by an advanced **92.18% accurate Stacking Ensemble Network**.")
150
-
151
- # Main Workspace Split
152
- with io.Row():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- # Left Panel: User Parameter Inputs grouped cleanly into rows/columns
155
- with io.Column(scale=2):
156
-
157
- with io.Group(elem_classes="section_box"):
158
- io.Markdown("### 📊 Block A: Loan Request & Purpose")
159
- with io.Row():
160
- loan = io.Number(label="Loan Amount ($) [LOAN]", value=15000)
161
- reason = io.Dropdown(choices=["DebtCon", "HomeImp"], label="Purpose [REASON]", value="DebtCon")
162
-
163
- io.Spacer()
164
-
165
- with io.Group(elem_classes="section_box"):
166
- io.Markdown("### 🏠 Block B: Financial Standing & Assets")
167
- with io.Row():
168
- mortdue = io.Number(label="Mortgage Owed ($) [MORTDUE]", value=50000)
169
- value = io.Number(label="Property Asset Value ($) [VALUE]", value=85000)
170
- with io.Row():
171
- job = io.Dropdown(choices=["Other", "Mgr", "Office", "ProfExe", "Sales", "Self"], label="Job Category [JOB]", value="Other")
172
- yoj = io.Number(label="Years at Present Job [YOJ]", value=5)
173
-
174
- io.Spacer()
175
-
176
- with io.Group(elem_classes="section_box"):
177
- io.Markdown("### 💳 Block C: Internal Credit Risk Metrics")
178
- with io.Row():
179
- debtinc = io.Number(label="Debt-to-Income Ratio (%) [DEBTINC]", value=32.5)
180
- clage = io.Number(label="Oldest Credit Account (Months) [CLAGE]", value=180)
181
- with io.Row():
182
- delinq = io.Number(label="Delinquent Credit Lines [DELINQ]", value=0)
183
- derog = io.Number(label="Derogatory Reports [DEROG]", value=0)
184
- with io.Row():
185
- ninq = io.Number(label="Recent Credit Inquiries [NINQ]", value=1)
186
- clno = io.Number(label="Total Existing Credit Lines [CLNO]", value=20)
187
-
188
- submit_btn = io.Button("⚡ Generate Automated Underwriting Decision", variant="primary")
189
-
190
- # Right Panel: Results & Analytical Metrics Card
191
- with io.Column(scale=1):
192
- with io.Group(elem_classes="section_box"):
193
- io.Markdown("### 🏁 Underwriting Output Terminal")
194
- output_html = io.HTML(
195
- label="Assessment Outcome Dashboard",
196
- value="<div style='color: #64748b; font-style: italic; text-align: center; padding: 40px 10px;'>Adjust inputs on the left panels and click the generate button to update underwriting logs.</div>"
197
- )
198
-
199
- # Wire Button Click trigger link to prediction interface execution logic
200
- submit_btn.click(
201
- fn=evaluate_loan_risk,
202
- inputs=[loan, mortdue, value, reason, job, yoj, derog, delinq, clage, ninq, clno, debtinc],
203
- outputs=output_html
204
- )
205
 
206
  if __name__ == "__main__":
207
- app.launch(share=True)
 
 
16
  from imblearn.pipeline import Pipeline as ImbPipeline
17
 
18
  # =====================================================================
19
+ # 1. CORE PIPELINE TRAINING (High-Speed Layout Framework)
20
  # =====================================================================
21
  print("Initializing and training the Stacking Pipeline...")
22
 
 
26
  X = df.drop('BAD', axis=1)
27
  y = df['BAD']
28
 
29
+ # Updated column selectors to prevent Deprecated Pandas4Warnings
30
  num_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
31
+ cat_cols = X.select_dtypes(include=['object', 'string']).columns.tolist()
32
 
33
  # Fast Outlier Rectification via IQR Capping
34
  def cap_outliers_iqr(data, columns):
 
46
 
47
  X_cleaned = cap_outliers_iqr(X, num_cols)
48
 
49
+ # Build Transformation Layouts
50
  num_pipeline = Pipeline([
51
  ('imputer', KNNImputer(n_neighbors=5)),
52
  ('scaler', StandardScaler())
 
62
  ('cat', cat_pipeline, cat_cols)
63
  ])
64
 
65
+ # Fast High-Speed Base Learners
66
  rf_base = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42, n_jobs=-1)
67
  xgb_base = XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=5, eval_metric='logloss', random_state=42, n_jobs=-1)
68
 
 
110
  prediction_proba = production_pipeline.predict_proba(input_data)[0]
111
  risk_of_default = prediction_proba[1]
112
 
113
+ # Generate high-contrast sleek outcome templates dynamically
114
  if risk_of_default > 0.40:
115
+ bg_gradient = "linear-gradient(135deg, #451a1a 0%, #1f0d0d 100%)"
116
+ accent_color = "#f87171"
117
+ status_text = "❌ RISK ASSESSMENT: APPLICATION REJECTED"
118
+ description = "The calculated default risk probability exceeds fiscal baseline limits. Cross-validation patterns indicate an elevated risk of variance failure."
119
  else:
120
+ bg_gradient = "linear-gradient(135deg, #14321a 0%, #0a1c10 100%)"
121
+ accent_color = "#4ade80"
122
+ status_text = "✅ RISK ASSESSMENT: APPLICATION APPROVED"
123
+ description = "This profile displays clear financial asset coverage, balanced debt metrics, and strong structural repayment probabilities."
124
 
125
  metrics_html = f"""
126
+ <div style="background: {bg_gradient}; color: #ffffff; padding: 24px; border-radius: 12px; border: 1px solid #334155; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.3);">
127
+ <h3 style="margin-top: 0; color: {accent_color}; font-size: 1.25rem; font-weight: 700; letter-spacing: 0.5px;">{status_text}</h3>
128
+ <p style="color: #e2e8f0; font-size: 0.95rem; line-height: 1.6; margin-bottom: 20px;">{description}</p>
129
+ <div style="border-top: 1px solid #334155; padding-top: 15px; display: flex; flex-direction: column; gap: 8px; font-family: monospace; font-size: 1rem;">
130
+ <div style="display: flex; justify-content: space-between;">
131
+ <span style="color: #94a3b8;">DEFAULT RISK INDEX:</span>
132
+ <strong style="color: {accent_color};">{risk_of_default * 100:.2f}%</strong>
133
+ </div>
134
+ <div style="display: flex; justify-content: space-between;">
135
+ <span style="color: #94a3b8;">MODEL ACCURACY SPEC:</span>
136
+ <strong style="color: #38bdf8;">92.18%</strong>
137
+ </div>
138
  </div>
139
  </div>
140
  """
141
  return metrics_html
142
 
143
  # =====================================================================
144
+ # 3. HIGH-END GRAPHIC INTERFACE DESIGN (Gradio 6.0+ Compliant)
145
  # =====================================================================
146
  custom_css = """
147
+ .gradio-container { background-color: #0f172a !important; color: #f8fafc !important; }
148
+ .section_panel { background-color: #1e293b !important; padding: 20px !important; border-radius: 12px !important; border: 1px solid #334155 !important; }
149
+ label { color: #cbd5e1 !important; font-weight: 600 !important; }
150
+ input, select { background-color: #0f172a !important; color: white !important; border: 1px solid #475569 !important; }
151
+ button.primary { background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%) !important; border: none !important; font-weight: bold !important; }
152
  """
153
 
154
+ # FIX: Extracted css and title from here to be compliant with Gradio 6.0+
155
+ with io.Blocks() as app:
156
 
157
+ # Clean Header Section using direct Markdown
158
+ io.Markdown(
159
+ """
160
+ <div style='text-align: center; margin-bottom: 30px; padding: 10px; border-bottom: 1px solid #334155;'>
161
+ <h1 style='color: #38bdf8; font-size: 2.2rem; font-weight: 800; margin-bottom: 5px;'>🏦 AI-Driven Loan Underwriting Framework</h1>
162
+ <p style='color: #94a3b8; font-size: 1.1rem;'>Strategic Credit Risk Analysis powered by a <b>92.18% Accurate Stacking Ensemble</b></p>
163
+ </div>
164
+ """
165
+ )
166
+
167
+ # Master Layout Split
168
+ with io.Row():
169
+
170
+ # Left Workspace Column: 12 Input Features Grouped Neatly
171
+ with io.Column(scale=2):
172
+
173
+ with io.Column(elem_classes="section_panel"):
174
+ io.Markdown("### 💵 Segment 1: Requested Loan Terms")
175
+ with io.Row():
176
+ loan = io.Number(label="Loan Capital ($) [LOAN]", value=15000)
177
+ reason = io.Dropdown(choices=["DebtCon", "HomeImp"], label="Purpose [REASON]", value="DebtCon")
178
+
179
+ io.Spacer()
180
+
181
+ with io.Column(elem_classes="section_panel"):
182
+ io.Markdown("### 🏠 Segment 2: Assets & Occupation")
183
+ with io.Row():
184
+ mortdue = io.Number(label="Mortgage Amount Due ($) [MORTDUE]", value=50000)
185
+ value = io.Number(label="Property Market Value ($) [VALUE]", value=85000)
186
+ with io.Row():
187
+ job = io.Dropdown(choices=["Other", "Mgr", "Office", "ProfExe", "Sales", "Self"], label="Job Category [JOB]", value="Other")
188
+ yoj = io.Number(label="Years at Current Job [YOJ]", value=5)
189
+
190
+ io.Spacer()
191
 
192
+ with io.Column(elem_classes="section_panel"):
193
+ io.Markdown("### 💳 Segment 3: Historic Credit Performance")
194
+ with io.Row():
195
+ debtinc = io.Number(label="Debt-to-Income Ratio (%) [DEBTINC]", value=32.5)
196
+ clage = io.Number(label="Oldest Line Account (Months) [CLAGE]", value=180)
197
+ with io.Row():
198
+ delinq = io.Number(label="Delinquent Lines Tally [DELINQ]", value=0)
199
+ derog = io.Number(label="Derogatory Reports Tally [DEROG]", value=0)
200
+ with io.Row():
201
+ ninq = io.Number(label="Recent Credit Inquiries [NINQ]", value=1)
202
+ clno = io.Number(label="Total Active Lines [CLNO]", value=20)
203
+
204
+ submit_btn = io.Button("⚡ Run Stacking Underwriting Evaluation", variant="primary")
205
+
206
+ # Right Workspace Column: Colorful Output Display Output Card
207
+ with io.Column(scale=1):
208
+ with io.Column(elem_classes="section_panel"):
209
+ io.Markdown("### 🏁 Terminal Output Feed")
210
+ output_html = io.HTML(
211
+ value="""
212
+ <div style='color: #64748b; background-color: #0f172a; border-radius: 8px; border: 1px dashed #334155; padding: 40px 15px; text-align: center; font-style: italic;'>
213
+ Awaiting assessment execution thread. Configure customer attributes on the left and click evaluate to initialize the stacking network.
214
+ </div>
215
+ """
216
+ )
217
+
218
+ # Attach event execution triggers
219
+ submit_btn.click(
220
+ fn=evaluate_loan_risk,
221
+ inputs=[loan, mortdue, value, reason, job, yoj, derog, delinq, clage, ninq, clno, debtinc],
222
+ outputs=output_html
223
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  if __name__ == "__main__":
226
+ # FIX: CSS styling rules and app title parameters passed down here inside .launch()
227
+ app.launch(css=custom_css, title="AI Loan Underwriting Portal", share=True)