feat: implement deterministic explanation and conditional Gemini advice, refactor risk scoring, and update UI elements and labels
Browse files
app.py
CHANGED
|
@@ -6,19 +6,21 @@ import plotly.graph_objects as go
|
|
| 6 |
from google import genai
|
| 7 |
from transformers import pipeline
|
| 8 |
|
| 9 |
-
# --- KONFIGURASI AI ---
|
| 10 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 11 |
-
|
|
|
|
| 12 |
|
| 13 |
-
# ---
|
| 14 |
-
#
|
| 15 |
custom_css = """
|
| 16 |
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap');
|
| 17 |
.gradio-container { font-family: 'Plus Jakarta Sans', sans-serif !important; background-color: #FFFFFF !important; }
|
| 18 |
.nagari-header { background: linear-gradient(135deg, #0514DE 0%, #82C3EB 100%); color: white; padding: 30px; border-radius: 15px; border-bottom: 6px solid #F7BD87; margin-bottom: 25px; text-align: center; }
|
| 19 |
-
.card-
|
| 20 |
-
.status-badge { display: inline-block; padding: 5px 15px; border-radius: 20px; font-weight: bold; color: white; }
|
| 21 |
-
.
|
|
|
|
| 22 |
"""
|
| 23 |
|
| 24 |
class ArchonNagariEngine:
|
|
@@ -28,115 +30,135 @@ class ArchonNagariEngine:
|
|
| 28 |
except: self.classifier = None
|
| 29 |
|
| 30 |
def load_data(self):
|
| 31 |
-
#
|
| 32 |
self.df_txn = pd.read_csv('transactions.csv', parse_dates=['date']).fillna({"raw_description": "Transaksi Umum"})
|
| 33 |
self.df_cust = pd.read_csv('customers.csv')
|
| 34 |
self.df_bal = pd.read_csv('balances_revised.csv', parse_dates=['month']).fillna(0)
|
| 35 |
self.df_rep = pd.read_csv('repayments_revised.csv', parse_dates=['due_date']).fillna("on_time")
|
| 36 |
|
| 37 |
def analyze(self, customer_id):
|
| 38 |
-
# Filter Data
|
| 39 |
u_txn = self.df_txn[self.df_txn['customer_id'] == customer_id].copy()
|
| 40 |
u_bal = self.df_bal[self.df_bal['customer_id'] == customer_id].sort_values('month')
|
| 41 |
u_rep = self.df_rep[self.df_rep['customer_id'] == customer_id]
|
| 42 |
-
u_info = self.df_cust[self.df_cust['customer_id'] == customer_id].iloc[0]
|
| 43 |
|
| 44 |
if u_txn.empty or u_bal.empty: return None
|
| 45 |
|
| 46 |
-
# --- FASE 4: RISK SCORING (
|
| 47 |
income_txn = u_txn[u_txn['transaction_type'] == 'credit']['amount'].sum()
|
| 48 |
-
|
|
|
|
| 49 |
expense = u_txn[u_txn['transaction_type'] == 'debit']['amount'].sum()
|
| 50 |
-
er = expense /
|
| 51 |
|
| 52 |
er_s = 1.0 if er > 0.8 else (0.5 if er > 0.5 else 0.0)
|
| 53 |
bt_s = 1.0 if len(u_bal) >= 2 and u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[-2]['avg_balance'] else 0.0
|
| 54 |
od_s = 1.0 if (u_bal['min_balance'] <= 0).any() else 0.0
|
| 55 |
mp_s = 1.0 if (u_rep['status'] == 'late').any() else 0.0
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
|
|
|
| 59 |
|
| 60 |
-
return risk_lv,
|
| 61 |
|
| 62 |
-
def
|
| 63 |
-
#
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
"""
|
| 79 |
try:
|
| 80 |
-
resp =
|
| 81 |
return resp.text
|
| 82 |
-
except:
|
| 83 |
-
return "Mohon maaf, sistem advisor sedang melakukan pemeliharaan. Silakan merujuk pada metrik risiko di panel kiri."
|
| 84 |
|
| 85 |
-
def
|
| 86 |
-
# Plot 1: Cashflow (
|
| 87 |
u_txn['m'] = u_txn['date'].dt.to_period('M').dt.to_timestamp()
|
| 88 |
cf = u_txn.groupby(['m', 'transaction_type'])['amount'].sum().unstack().fillna(0)
|
| 89 |
fig1 = go.Figure()
|
| 90 |
fig1.add_trace(go.Bar(x=cf.index, y=cf.get('credit', 0), name='Pemasukan', marker_color='#82C3EB'))
|
| 91 |
fig1.add_trace(go.Bar(x=cf.index, y=cf.get('debit', 0), name='Pengeluaran', marker_color='#0514DE'))
|
| 92 |
-
fig1.update_layout(title="
|
| 93 |
|
| 94 |
-
# Plot 2: Balance
|
| 95 |
fig2 = go.Figure()
|
| 96 |
fig2.add_trace(go.Scatter(x=u_bal['month'], y=u_bal['avg_balance'], name='Saldo Rata-rata', line=dict(color='#F7BD87', width=4)))
|
| 97 |
-
fig2.update_layout(title="
|
| 98 |
return fig1, fig2
|
| 99 |
|
| 100 |
# --- UI LOGIC ---
|
| 101 |
engine = ArchonNagariEngine()
|
| 102 |
|
| 103 |
-
def
|
| 104 |
res = engine.analyze(cust_id)
|
| 105 |
if not res: return "## ❌ ID Tidak Valid", "Data tidak ditemukan.", None, None
|
| 106 |
|
| 107 |
risk_lv, score, er, u_bal, u_txn, inc, exp = res
|
| 108 |
-
|
|
|
|
| 109 |
f1, f2 = engine.create_plots(u_bal, u_txn)
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
color = "#ef4444" if risk_lv == "HIGH" else ("#f59e0b" if risk_lv == "MEDIUM" else "#10b981")
|
| 112 |
-
|
| 113 |
status_html = f"""
|
| 114 |
-
<div class='card-
|
| 115 |
<h2 style='color: #0514DE; margin:0;'>Hasil Analisis AI</h2>
|
| 116 |
-
<
|
| 117 |
-
<p><b>Risk Score:</b> {score:.2f} / 1.00</p>
|
| 118 |
<p><b>Expense Ratio:</b> {er:.1%}</p>
|
| 119 |
</div>
|
| 120 |
"""
|
| 121 |
-
return status_html,
|
| 122 |
|
| 123 |
with gr.Blocks(css=custom_css) as demo:
|
| 124 |
-
gr.HTML("<div class='nagari-header'><h1>🛡️ ARCHON-AI: FINANCIAL ADVISOR</h1><p>
|
| 125 |
|
| 126 |
with gr.Row():
|
| 127 |
with gr.Column(scale=1):
|
| 128 |
-
id_in = gr.Textbox(label="Customer ID", placeholder="C0001 - C0120")
|
| 129 |
-
btn = gr.Button("
|
| 130 |
out_status = gr.HTML()
|
| 131 |
gr.Markdown("---")
|
| 132 |
-
gr.Markdown("**
|
| 133 |
|
| 134 |
with gr.Column(scale=2):
|
| 135 |
with gr.Tabs():
|
| 136 |
-
with gr.TabItem("
|
| 137 |
with gr.TabItem("Tren Pertumbuhan Saldo"): plot_2 = gr.Plot()
|
| 138 |
-
|
| 139 |
|
| 140 |
-
btn.click(fn=
|
| 141 |
|
| 142 |
demo.launch()
|
|
|
|
| 6 |
from google import genai
|
| 7 |
from transformers import pipeline
|
| 8 |
|
| 9 |
+
# --- KONFIGURASI GENERATIVE AI ---
|
| 10 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 11 |
+
# Inisialisasi Client (SDK Terbaru 2026)
|
| 12 |
+
client_ai = genai.Client(api_key=GOOGLE_API_KEY) if GOOGLE_API_KEY else None
|
| 13 |
|
| 14 |
+
# --- PALET WARNA BANK NAGARI ---
|
| 15 |
+
# #0514DE (Deep Blue), #82C3EB (Light Blue), #E0EDF4 (Pale), #F7BD87 (Gold), #FFFFFF (White)
|
| 16 |
custom_css = """
|
| 17 |
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap');
|
| 18 |
.gradio-container { font-family: 'Plus Jakarta Sans', sans-serif !important; background-color: #FFFFFF !important; }
|
| 19 |
.nagari-header { background: linear-gradient(135deg, #0514DE 0%, #82C3EB 100%); color: white; padding: 30px; border-radius: 15px; border-bottom: 6px solid #F7BD87; margin-bottom: 25px; text-align: center; }
|
| 20 |
+
.card-nagari { background: #E0EDF4; border-radius: 12px; padding: 20px; border: 1px solid #82C3EB; box-shadow: 0 4px 10px rgba(5, 20, 122, 0.05); }
|
| 21 |
+
.status-badge { display: inline-block; padding: 5px 15px; border-radius: 20px; font-weight: bold; color: white; margin-top: 10px; }
|
| 22 |
+
.report-box { background: white; border-radius: 10px; padding: 20px; border-left: 6px solid #0514DE; line-height: 1.6; }
|
| 23 |
+
.advice-box { background: #fffdf0; border: 1px solid #F7BD87; padding: 20px; border-radius: 10px; }
|
| 24 |
"""
|
| 25 |
|
| 26 |
class ArchonNagariEngine:
|
|
|
|
| 30 |
except: self.classifier = None
|
| 31 |
|
| 32 |
def load_data(self):
|
| 33 |
+
# Fase 1: Foundation (Fix C0014 error handling)
|
| 34 |
self.df_txn = pd.read_csv('transactions.csv', parse_dates=['date']).fillna({"raw_description": "Transaksi Umum"})
|
| 35 |
self.df_cust = pd.read_csv('customers.csv')
|
| 36 |
self.df_bal = pd.read_csv('balances_revised.csv', parse_dates=['month']).fillna(0)
|
| 37 |
self.df_rep = pd.read_csv('repayments_revised.csv', parse_dates=['due_date']).fillna("on_time")
|
| 38 |
|
| 39 |
def analyze(self, customer_id):
|
| 40 |
+
# 1. Filter Data & Validation
|
| 41 |
u_txn = self.df_txn[self.df_txn['customer_id'] == customer_id].copy()
|
| 42 |
u_bal = self.df_bal[self.df_bal['customer_id'] == customer_id].sort_values('month')
|
| 43 |
u_rep = self.df_rep[self.df_rep['customer_id'] == customer_id]
|
|
|
|
| 44 |
|
| 45 |
if u_txn.empty or u_bal.empty: return None
|
| 46 |
|
| 47 |
+
# --- FASE 4: RISK SCORING (DETERMINISTIC AI) ---
|
| 48 |
income_txn = u_txn[u_txn['transaction_type'] == 'credit']['amount'].sum()
|
| 49 |
+
cust_profile = self.df_cust[self.df_cust['customer_id'] == customer_id].iloc[0]
|
| 50 |
+
base_inc = max(income_txn, cust_profile['monthly_income'])
|
| 51 |
expense = u_txn[u_txn['transaction_type'] == 'debit']['amount'].sum()
|
| 52 |
+
er = expense / base_inc
|
| 53 |
|
| 54 |
er_s = 1.0 if er > 0.8 else (0.5 if er > 0.5 else 0.0)
|
| 55 |
bt_s = 1.0 if len(u_bal) >= 2 and u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[-2]['avg_balance'] else 0.0
|
| 56 |
od_s = 1.0 if (u_bal['min_balance'] <= 0).any() else 0.0
|
| 57 |
mp_s = 1.0 if (u_rep['status'] == 'late').any() else 0.0
|
| 58 |
|
| 59 |
+
# Risk Score 0.0 - 1.0 (Bobot 30/20/20/20/10)
|
| 60 |
+
final_score = (0.3 * er_s) + (0.2 * bt_s) + (0.2 * od_s) + (0.2 * mp_s) + 0.1
|
| 61 |
+
risk_lv = "HIGH" if final_score >= 0.7 else ("MEDIUM" if final_score >= 0.4 else "LOW")
|
| 62 |
|
| 63 |
+
return risk_lv, final_score, er, u_bal, u_txn, base_inc, expense
|
| 64 |
|
| 65 |
+
def get_deterministic_explanation(self, risk_lv, score, er, u_bal):
|
| 66 |
+
# Penjelasan adaptif berdasarkan output riil (Backup jika LLM gagal)
|
| 67 |
+
exp = f"### 📖 Interpretasi Analisis Archon\n"
|
| 68 |
+
if risk_lv == "HIGH":
|
| 69 |
+
exp += f"⚠️ **Level Risiko Tinggi ({score:.2f})**: Perilaku keuangan Anda memerlukan restrukturisasi segera. "
|
| 70 |
+
elif risk_lv == "MEDIUM":
|
| 71 |
+
exp += f"🔔 **Level Risiko Menengah ({score:.2f})**: Anda berada dalam zona peringatan dini (Early Warning). "
|
| 72 |
+
else:
|
| 73 |
+
exp += f"✅ **Level Risiko Rendah ({score:.2f})**: Resiliensi finansial Anda terpantau sangat sehat. "
|
| 74 |
+
|
| 75 |
+
exp += f"\n\n**Rincian Metrik:**\n"
|
| 76 |
+
exp += f"- **Expense Ratio ({er:.1%})**: Anda menggunakan {er:.1%} pendapatan untuk belanja. "
|
| 77 |
+
exp += f"{'Sangat boros (>80%), kurangi pengeluaran lifestyle.' if er > 0.8 else 'Cukup aman, namun tetap waspada.'}\n"
|
| 78 |
+
|
| 79 |
+
latest_bal = u_bal.iloc[-1]['avg_balance']
|
| 80 |
+
exp += f"- **Tren Saldo**: Saldo rata-rata Anda Rp{latest_bal:,.0f}. "
|
| 81 |
+
exp += f"{'Tren menurun dibanding bulan lalu.' if len(u_bal) > 1 and latest_bal < u_bal.iloc[-2]['avg_balance'] else 'Saldo terpantau stabil/naik.'}"
|
| 82 |
|
| 83 |
+
return exp
|
| 84 |
+
|
| 85 |
+
def get_gemini_advice(self, risk_lv, er, cust_id, u_txn):
|
| 86 |
+
# FASE 5: NBO GENERATIVE
|
| 87 |
+
if not client_ai: return None
|
| 88 |
+
merchants = u_txn.tail(3)['raw_description'].tolist()
|
| 89 |
+
prompt = f"""
|
| 90 |
+
Identitas: Senior Wealth Manager Bank Nagari.
|
| 91 |
+
Analisis Nasabah {cust_id}: Risiko {risk_lv}, Rasio Pengeluaran {er:.1%}.
|
| 92 |
+
Riwayat Belanja: {', '.join(merchants)}.
|
| 93 |
+
Tugas: Berikan saran finansial spesifik & empati untuk Bapak/Ibu. Hubungkan dengan pengeluaran di {merchants[0]}. Maks 3 kalimat.
|
| 94 |
"""
|
| 95 |
try:
|
| 96 |
+
resp = client_ai.models.generate_content(model="gemini-1.5-flash", contents=prompt)
|
| 97 |
return resp.text
|
| 98 |
+
except: return None
|
|
|
|
| 99 |
|
| 100 |
+
def create_viz(self, u_bal, u_txn):
|
| 101 |
+
# Plot 1: Cashflow (Fase 6)
|
| 102 |
u_txn['m'] = u_txn['date'].dt.to_period('M').dt.to_timestamp()
|
| 103 |
cf = u_txn.groupby(['m', 'transaction_type'])['amount'].sum().unstack().fillna(0)
|
| 104 |
fig1 = go.Figure()
|
| 105 |
fig1.add_trace(go.Bar(x=cf.index, y=cf.get('credit', 0), name='Pemasukan', marker_color='#82C3EB'))
|
| 106 |
fig1.add_trace(go.Bar(x=cf.index, y=cf.get('debit', 0), name='Pengeluaran', marker_color='#0514DE'))
|
| 107 |
+
fig1.update_layout(title="Inflow vs Outflow Bulanan", barmode='group', template='plotly_white')
|
| 108 |
|
| 109 |
+
# Plot 2: Balance Trend
|
| 110 |
fig2 = go.Figure()
|
| 111 |
fig2.add_trace(go.Scatter(x=u_bal['month'], y=u_bal['avg_balance'], name='Saldo Rata-rata', line=dict(color='#F7BD87', width=4)))
|
| 112 |
+
fig2.update_layout(title="Kesehatan Saldo (Fase 6)", template='plotly_white')
|
| 113 |
return fig1, fig2
|
| 114 |
|
| 115 |
# --- UI LOGIC ---
|
| 116 |
engine = ArchonNagariEngine()
|
| 117 |
|
| 118 |
+
def run_archon(cust_id):
|
| 119 |
res = engine.analyze(cust_id)
|
| 120 |
if not res: return "## ❌ ID Tidak Valid", "Data tidak ditemukan.", None, None
|
| 121 |
|
| 122 |
risk_lv, score, er, u_bal, u_txn, inc, exp = res
|
| 123 |
+
det_exp = engine.get_deterministic_explanation(risk_lv, score, er, u_bal)
|
| 124 |
+
gen_advice = engine.get_gemini_advice(risk_lv, er, cust_id, u_txn)
|
| 125 |
f1, f2 = engine.create_plots(u_bal, u_txn)
|
| 126 |
|
| 127 |
+
# Gabungkan penjelasan Deterministik dengan Gemini (Jika Gemini ok)
|
| 128 |
+
final_report = det_exp
|
| 129 |
+
if gen_advice:
|
| 130 |
+
final_report += f"\n\n---\n**💡 Rekomendasi Virtual Advisor:**\n{gen_advice}"
|
| 131 |
+
else:
|
| 132 |
+
final_report += f"\n\n---\n*Saran Virtual Advisor sedang dalam sinkronisasi sistem.*"
|
| 133 |
+
|
| 134 |
color = "#ef4444" if risk_lv == "HIGH" else ("#f59e0b" if risk_lv == "MEDIUM" else "#10b981")
|
|
|
|
| 135 |
status_html = f"""
|
| 136 |
+
<div class='card-nagari'>
|
| 137 |
<h2 style='color: #0514DE; margin:0;'>Hasil Analisis AI</h2>
|
| 138 |
+
<span class='status-badge' style='background:{color}'>{risk_lv} RISK</span>
|
| 139 |
+
<p style='margin-top:15px;'><b>Risk Score:</b> {score:.2f} / 1.00</p>
|
| 140 |
<p><b>Expense Ratio:</b> {er:.1%}</p>
|
| 141 |
</div>
|
| 142 |
"""
|
| 143 |
+
return status_html, final_report, f1, f2
|
| 144 |
|
| 145 |
with gr.Blocks(css=custom_css) as demo:
|
| 146 |
+
gr.HTML("<div class='nagari-header'><h1>🛡️ ARCHON-AI: FINANCIAL ADVISOR</h1><p>Sistem Intelijen Resiliensi Finansial & Manajemen Risiko</p></div>")
|
| 147 |
|
| 148 |
with gr.Row():
|
| 149 |
with gr.Column(scale=1):
|
| 150 |
+
id_in = gr.Textbox(label="Customer ID", placeholder="Masukkan ID (C0001 - C0120)")
|
| 151 |
+
btn = gr.Button("PROSES DATA", variant="primary")
|
| 152 |
out_status = gr.HTML()
|
| 153 |
gr.Markdown("---")
|
| 154 |
+
gr.Markdown("ℹ️ **Info Metrik**: Skor risiko didasarkan pada perpaduan saldo, rasio belanja, dan kedisiplinan cicilan nasabah.")
|
| 155 |
|
| 156 |
with gr.Column(scale=2):
|
| 157 |
with gr.Tabs():
|
| 158 |
+
with gr.TabItem("Analisis Cashflow"): plot_1 = gr.Plot()
|
| 159 |
with gr.TabItem("Tren Pertumbuhan Saldo"): plot_2 = gr.Plot()
|
| 160 |
+
out_report = gr.Markdown(elem_classes="report-box")
|
| 161 |
|
| 162 |
+
btn.click(fn=run_archon, inputs=id_in, outputs=[out_status, out_report, plot_1, plot_2])
|
| 163 |
|
| 164 |
demo.launch()
|