update NBO decision logic, and enhance report narrative generation.
Browse files
app.py
CHANGED
|
@@ -10,23 +10,44 @@ from datetime import timedelta
|
|
| 10 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 11 |
client_ai = genai.Client(api_key=GOOGLE_API_KEY) if GOOGLE_API_KEY else None
|
| 12 |
|
| 13 |
-
# --- UI STYLE
|
|
|
|
| 14 |
custom_css = """
|
| 15 |
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
|
| 16 |
body, .gradio-container { font-family: 'Plus Jakarta Sans', sans-serif !important; background-color: #FFFFFF !important; }
|
| 17 |
-
|
| 18 |
-
.nagari-header
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
|
| 25 |
-
class
|
| 26 |
def __init__(self):
|
| 27 |
self.load_data()
|
| 28 |
|
| 29 |
def load_data(self):
|
|
|
|
| 30 |
self.df_txn = pd.read_csv('transactions.csv', parse_dates=['date']).sort_values('date')
|
| 31 |
self.df_cust = pd.read_csv('customers.csv')
|
| 32 |
self.df_bal = pd.read_csv('balances_revised.csv', parse_dates=['month']).sort_values('month')
|
|
@@ -42,107 +63,102 @@ class ArchonFinalEngine:
|
|
| 42 |
if u_txn.empty or u_info_list.empty: return None
|
| 43 |
u_info = u_info_list.iloc[0]
|
| 44 |
|
| 45 |
-
# --- FASE 2:
|
| 46 |
income_txn = u_txn[u_txn['transaction_type'] == 'credit']['amount'].sum()
|
| 47 |
ref_income = max(income_txn, u_info['monthly_income'])
|
| 48 |
expense = u_txn[u_txn['transaction_type'] == 'debit']['amount'].sum()
|
| 49 |
er = min(expense / ref_income, 1.0) if ref_income > 0 else 1.0
|
| 50 |
|
| 51 |
# --- FASE 4: RISK SCORING (30/20/20/20/10) ---
|
| 52 |
-
#
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
|
| 58 |
-
|
|
|
|
| 59 |
risk_lv = "HIGH" if final_score >= 0.7 else ("MEDIUM" if final_score >= 0.4 else "LOW")
|
| 60 |
|
| 61 |
-
# --- FASE 5: NBO ENGINE
|
| 62 |
-
if risk_lv == "HIGH" or
|
| 63 |
-
action,
|
| 64 |
-
steps = ["
|
| 65 |
elif er > 0.6:
|
| 66 |
-
action,
|
| 67 |
-
steps = ["
|
| 68 |
elif risk_lv == "LOW":
|
| 69 |
-
action,
|
| 70 |
-
steps = ["Penawaran Deposito
|
| 71 |
else:
|
| 72 |
-
action,
|
| 73 |
-
steps = ["
|
| 74 |
|
| 75 |
-
return risk_lv, final_score, er, u_bal, u_txn, expense, ref_income, action,
|
| 76 |
|
| 77 |
-
def
|
| 78 |
-
#
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
report += f"Berdasarkan audit mutasi, tingkat resiliensi Bapak/Ibu berada pada kategori **{risk_lv}** (Skor: {score:.2f}).\n\n"
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
|
| 87 |
if not u_bal.empty:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
|
|
|
|
| 98 |
if client_ai:
|
| 99 |
try:
|
| 100 |
tx = u_txn.tail(1)['raw_description'].iloc[0]
|
| 101 |
-
prompt = f"Advisor Bank Nagari: Nasabah {cid}
|
| 102 |
resp = client_ai.models.generate_content(model="gemini-1.5-flash", contents=prompt)
|
| 103 |
-
|
| 104 |
except: pass
|
| 105 |
-
return
|
| 106 |
|
| 107 |
-
# --- UI
|
| 108 |
-
engine =
|
| 109 |
|
| 110 |
-
def
|
| 111 |
res = engine.analyze(cust_id)
|
| 112 |
-
if not res: return "## ❌ ID Tidak
|
| 113 |
|
| 114 |
-
risk_lv, score, er, u_bal, u_txn, exp, inc, action,
|
| 115 |
-
report = engine.
|
| 116 |
|
| 117 |
-
# Graphs - CORRECTED
|
| 118 |
f1 = go.Figure()
|
| 119 |
u_txn['m'] = u_txn['date'].dt.to_period('M').dt.to_timestamp()
|
| 120 |
cf = u_txn.groupby(['m', 'transaction_type'])['amount'].sum().unstack().fillna(0)
|
| 121 |
f1.add_trace(go.Bar(x=cf.index, y=cf.get('credit', 0), name='Pemasukan (Inflow)', marker_color='#82C3EB'))
|
| 122 |
f1.add_trace(go.Bar(x=cf.index, y=cf.get('debit', 0), name='Pengeluaran (Outflow)', marker_color='#0514DE'))
|
| 123 |
-
f1.update_layout(title="
|
| 124 |
|
| 125 |
f2 = go.Figure()
|
| 126 |
f2.add_trace(go.Scatter(x=u_bal['month'], y=u_bal['avg_balance'], name='Saldo Rata-rata', line=dict(color='#F7BD87', width=4)))
|
| 127 |
f2.update_layout(title="Tren Pertumbuhan Saldo", template='plotly_white')
|
| 128 |
|
| 129 |
-
# Sidebar Badges (Brainstorming Result)
|
| 130 |
color = "#ef4444" if risk_lv == "HIGH" else ("#f59e0b" if risk_lv == "MEDIUM" else "#10b981")
|
| 131 |
-
|
| 132 |
<div class='card-left'>
|
| 133 |
<h2 style='color: #0514DE; margin:0;'>Dashboard Ringkasan</h2>
|
| 134 |
<div style='background:{color}; color:white; padding:10px 20px; border-radius:30px; font-weight:bold; display:inline-block; margin:15px 0;'>{risk_lv} RISK</div>
|
| 135 |
-
|
| 136 |
-
<div
|
| 137 |
-
<div
|
| 138 |
-
<div class='badge-item'><b>Overdraft:</b> {'❌ Pernah' if od_s == 1 else '✅ Tidak'}</div>
|
| 139 |
-
<div class='badge-item'><b>Credit Status:</b> {'❌ Late' if mp_s == 1 else '✅ On-Time'}</div>
|
| 140 |
-
|
| 141 |
-
<p style='margin-top:20px; font-size:0.85em; color:#666;'>*Parameter dihitung menggunakan bobot resmi perbankan Nagari (Fase 4).</p>
|
| 142 |
</div>
|
| 143 |
"""
|
| 144 |
-
|
| 145 |
-
return sidebar_html, report, f1, f2
|
| 146 |
|
| 147 |
with gr.Blocks(css=custom_css) as demo:
|
| 148 |
gr.HTML("<div class='nagari-header'><h1>ARCHON-AI</h1></div>")
|
|
@@ -150,18 +166,18 @@ with gr.Blocks(css=custom_css) as demo:
|
|
| 150 |
with gr.Column(scale=1):
|
| 151 |
id_in = gr.Textbox(label="Customer ID", placeholder="C0001")
|
| 152 |
btn = gr.Button("ANALYZE CUSTOMER", variant="primary")
|
| 153 |
-
|
| 154 |
with gr.Column(scale=2):
|
| 155 |
with gr.Tabs():
|
| 156 |
with gr.Tab("Audit Summary"):
|
| 157 |
out_report = gr.Markdown(elem_classes="report-card")
|
| 158 |
with gr.Tab("Visual Analytics"):
|
| 159 |
-
gr.Markdown("###
|
| 160 |
plot_cf = gr.Plot()
|
| 161 |
gr.Markdown("---")
|
| 162 |
-
gr.Markdown("### Tren Saldo\nMenunjukkan
|
| 163 |
plot_bal = gr.Plot()
|
| 164 |
|
| 165 |
-
btn.click(fn=
|
| 166 |
|
| 167 |
demo.launch()
|
|
|
|
| 10 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 11 |
client_ai = genai.Client(api_key=GOOGLE_API_KEY) if GOOGLE_API_KEY else None
|
| 12 |
|
| 13 |
+
# --- UI STYLE BANK NAGARI PREMIUM ---
|
| 14 |
+
# Palette: #0514DE (Blue), #82C3EB (Light Blue), #F7BD87 (Gold), #FFFFFF (White)
|
| 15 |
custom_css = """
|
| 16 |
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
|
| 17 |
body, .gradio-container { font-family: 'Plus Jakarta Sans', sans-serif !important; background-color: #FFFFFF !important; }
|
| 18 |
+
|
| 19 |
+
.nagari-header {
|
| 20 |
+
background: linear-gradient(135deg, #0514DE 0%, #82C3EB 100%);
|
| 21 |
+
padding: 35px; border-radius: 15px; border-bottom: 6px solid #F7BD87;
|
| 22 |
+
margin-bottom: 25px; text-align: center;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
.nagari-header h1 {
|
| 26 |
+
color: #FFFFFF !important; font-weight: 800 !important; margin: 0; font-size: 2.2em;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
.card-left {
|
| 30 |
+
background: #E0EDF4; border-radius: 15px; padding: 25px;
|
| 31 |
+
border: 1.5px solid #82C3EB; box-shadow: 0 4px 12px rgba(5, 20, 222, 0.08);
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
.report-card {
|
| 35 |
+
background: white; border-radius: 12px; padding: 30px;
|
| 36 |
+
border: 1px solid #E2E8F0; line-height: 1.8; color: #1e293b;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
.nbo-box {
|
| 40 |
+
background: #fffdf0; border: 2px solid #F7BD87; padding: 20px;
|
| 41 |
+
border-radius: 10px; margin-top: 20px;
|
| 42 |
+
}
|
| 43 |
"""
|
| 44 |
|
| 45 |
+
class ArchonMasterEngine:
|
| 46 |
def __init__(self):
|
| 47 |
self.load_data()
|
| 48 |
|
| 49 |
def load_data(self):
|
| 50 |
+
# Fase 1: Data Foundation
|
| 51 |
self.df_txn = pd.read_csv('transactions.csv', parse_dates=['date']).sort_values('date')
|
| 52 |
self.df_cust = pd.read_csv('customers.csv')
|
| 53 |
self.df_bal = pd.read_csv('balances_revised.csv', parse_dates=['month']).sort_values('month')
|
|
|
|
| 63 |
if u_txn.empty or u_info_list.empty: return None
|
| 64 |
u_info = u_info_list.iloc[0]
|
| 65 |
|
| 66 |
+
# --- FASE 2 & 3: AGGREGATION ---
|
| 67 |
income_txn = u_txn[u_txn['transaction_type'] == 'credit']['amount'].sum()
|
| 68 |
ref_income = max(income_txn, u_info['monthly_income'])
|
| 69 |
expense = u_txn[u_txn['transaction_type'] == 'debit']['amount'].sum()
|
| 70 |
er = min(expense / ref_income, 1.0) if ref_income > 0 else 1.0
|
| 71 |
|
| 72 |
# --- FASE 4: RISK SCORING (30/20/20/20/10) ---
|
| 73 |
+
# Menghitung skor tanpa walrus operator agar stabil
|
| 74 |
+
er_s = 1.0 if er > 0.8 else (0.5 if er > 0.5 else 0.0)
|
| 75 |
+
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
|
| 76 |
+
od_s = 1.0 if (u_bal['min_balance'] <= 0).any() else 0.0
|
| 77 |
+
mp_s = 1.0 if (u_rep['status'] == 'late').any() else 0.0
|
| 78 |
|
| 79 |
+
# Total Score: 0.1 adalah baseline volatility
|
| 80 |
+
final_score = (0.3 * er_s) + (0.2 * bt_s) + (0.2 * od_s) + (0.2 * mp_s) + 0.1
|
| 81 |
risk_lv = "HIGH" if final_score >= 0.7 else ("MEDIUM" if final_score >= 0.4 else "LOW")
|
| 82 |
|
| 83 |
+
# --- FASE 5: NBO DECISION ENGINE ---
|
| 84 |
+
if risk_lv == "HIGH" or mp_s == 1:
|
| 85 |
+
action, detail = "Restructuring Suggestion", "Prioritas penyelamatan kredit dan penjadwalan ulang cicilan."
|
| 86 |
+
steps = ["Peninjauan ulang suku bunga", "Perpanjangan tenor", "Konsolidasi kewajiban."]
|
| 87 |
elif er > 0.6:
|
| 88 |
+
action, detail = "Spending Control", "Pembatasan pengeluaran gaya hidup untuk menjaga likuiditas."
|
| 89 |
+
steps = ["Set limit QRIS harian", "Notifikasi saldo kritis", "Review pos belanja online."]
|
| 90 |
elif risk_lv == "LOW":
|
| 91 |
+
action, detail = "Promote Investment", "Optimalisasi dana mengendap melalui produk growth."
|
| 92 |
+
steps = ["Penawaran Deposito Nagari", "Reksa Dana", "Tabungan Berjangka."]
|
| 93 |
else:
|
| 94 |
+
action, detail = "Financial Education", "Edukasi pengelolaan arus kas harian agar resiliensi meningkat."
|
| 95 |
+
steps = ["Modul perencanaan budget", "Webinar literasi", "Saran RM Mingguan."]
|
| 96 |
|
| 97 |
+
return risk_lv, final_score, er, u_bal, u_txn, expense, ref_income, action, detail, steps, er_s, bt_s, od_s, mp_s
|
| 98 |
|
| 99 |
+
def get_narrative(self, risk_lv, score, er, u_bal, exp, inc, action, detail, steps, cid, u_txn):
|
| 100 |
+
# FASE 6: EXPLAINABLE SUMMARY (NARRATIVE)
|
| 101 |
+
msg = f"### 📊 LAPORAN EKSEKUTIF ARCHON-AI\n\n"
|
| 102 |
+
msg += f"Analisis resiliensi untuk nasabah **{cid}** menunjukkan profil risiko **{risk_lv}** (Skor: {score:.2f}).\n\n"
|
|
|
|
| 103 |
|
| 104 |
+
msg += f"**Mengapa Skor Ini Muncul?**\n"
|
| 105 |
+
msg += f"* **Rasio Belanja ({er:.1%})**: Anda menghabiskan Rp{exp:,.0f} dari daya beli Rp{inc:,.0f}. "
|
| 106 |
+
msg += "Ini menunjukkan defisit kas yang berisiko." if er > 0.8 else "Angka ini menunjukkan manajemen kas yang sehat."
|
| 107 |
|
| 108 |
if not u_bal.empty:
|
| 109 |
+
last_bal = u_bal.iloc[-1]['avg_balance']
|
| 110 |
+
msg += f"\n* **Tren Saldo**: Saldo saat ini Rp{last_bal:,.0f}. "
|
| 111 |
+
msg += "Terjadi penurunan saldo rata-rata, mengindikasikan tabungan mulai tergerus." if len(u_bal) > 1 and last_bal < u_bal.iloc[-2]['avg_balance'] else "Saldo tumbuh stabil."
|
| 112 |
+
|
| 113 |
+
msg += f"\n\n<div class='nbo-box'>**🎯 REKOMENDASI TINDAKAN (NBO): {action}**\n\n"
|
| 114 |
+
msg += f"**Definisi:** {detail}\n\n"
|
| 115 |
+
msg += f"**Langkah-langkah Strategis:**\n"
|
| 116 |
+
for i, s in enumerate(steps, 1): msg += f"{i}. {s}\n"
|
| 117 |
+
msg += f"</div>"
|
| 118 |
|
| 119 |
+
# GEN-AI BACKUP
|
| 120 |
if client_ai:
|
| 121 |
try:
|
| 122 |
tx = u_txn.tail(1)['raw_description'].iloc[0]
|
| 123 |
+
prompt = f"Advisor Bank Nagari: Nasabah {cid} ({risk_lv} risk). Saran hangat personal terkait {tx}, maks 2 kalimat."
|
| 124 |
resp = client_ai.models.generate_content(model="gemini-1.5-flash", contents=prompt)
|
| 125 |
+
msg += f"\n---\n**💡 SARAN VIRTUAL ADVISOR:**\n_{resp.text}_"
|
| 126 |
except: pass
|
| 127 |
+
return msg
|
| 128 |
|
| 129 |
+
# --- UI EXECUTION ---
|
| 130 |
+
engine = ArchonMasterEngine()
|
| 131 |
|
| 132 |
+
def run_app(cust_id):
|
| 133 |
res = engine.analyze(cust_id)
|
| 134 |
+
if not res: return "## ❌ ID Tidak Valid", "Gunakan C0001 - C0120", None, None
|
| 135 |
|
| 136 |
+
risk_lv, score, er, u_bal, u_txn, exp, inc, action, detail, steps, er_s, bt_s, od_s, mp_s = res
|
| 137 |
+
report = engine.get_narrative(risk_lv, score, er, u_bal, exp, inc, action, detail, steps, cust_id, u_txn)
|
| 138 |
|
| 139 |
+
# Graphs - CORRECTED
|
| 140 |
f1 = go.Figure()
|
| 141 |
u_txn['m'] = u_txn['date'].dt.to_period('M').dt.to_timestamp()
|
| 142 |
cf = u_txn.groupby(['m', 'transaction_type'])['amount'].sum().unstack().fillna(0)
|
| 143 |
f1.add_trace(go.Bar(x=cf.index, y=cf.get('credit', 0), name='Pemasukan (Inflow)', marker_color='#82C3EB'))
|
| 144 |
f1.add_trace(go.Bar(x=cf.index, y=cf.get('debit', 0), name='Pengeluaran (Outflow)', marker_color='#0514DE'))
|
| 145 |
+
f1.update_layout(title="Inflow vs Outflow Bulanan", barmode='group', template='plotly_white')
|
| 146 |
|
| 147 |
f2 = go.Figure()
|
| 148 |
f2.add_trace(go.Scatter(x=u_bal['month'], y=u_bal['avg_balance'], name='Saldo Rata-rata', line=dict(color='#F7BD87', width=4)))
|
| 149 |
f2.update_layout(title="Tren Pertumbuhan Saldo", template='plotly_white')
|
| 150 |
|
|
|
|
| 151 |
color = "#ef4444" if risk_lv == "HIGH" else ("#f59e0b" if risk_lv == "MEDIUM" else "#10b981")
|
| 152 |
+
sidebar = f"""
|
| 153 |
<div class='card-left'>
|
| 154 |
<h2 style='color: #0514DE; margin:0;'>Dashboard Ringkasan</h2>
|
| 155 |
<div style='background:{color}; color:white; padding:10px 20px; border-radius:30px; font-weight:bold; display:inline-block; margin:15px 0;'>{risk_lv} RISK</div>
|
| 156 |
+
<div style='background:white; padding:10px; border-radius:8px; margin-bottom:10px; border-left:4px solid #0514DE;'><b>Score:</b> {score:.2f}</div>
|
| 157 |
+
<div style='background:white; padding:10px; border-radius:8px; margin-bottom:10px; border-left:4px solid #0514DE;'><b>Ratio:</b> {er:.1%}</div>
|
| 158 |
+
<div style='background:white; padding:10px; border-radius:8px; border-left:4px solid #0514DE;'><b>Trend:</b> {'🔻 Turun' if bt_s == 1 else '🔼 Stabil'}</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
</div>
|
| 160 |
"""
|
| 161 |
+
return sidebar, report, f1, f2
|
|
|
|
| 162 |
|
| 163 |
with gr.Blocks(css=custom_css) as demo:
|
| 164 |
gr.HTML("<div class='nagari-header'><h1>ARCHON-AI</h1></div>")
|
|
|
|
| 166 |
with gr.Column(scale=1):
|
| 167 |
id_in = gr.Textbox(label="Customer ID", placeholder="C0001")
|
| 168 |
btn = gr.Button("ANALYZE CUSTOMER", variant="primary")
|
| 169 |
+
out_side = gr.HTML()
|
| 170 |
with gr.Column(scale=2):
|
| 171 |
with gr.Tabs():
|
| 172 |
with gr.Tab("Audit Summary"):
|
| 173 |
out_report = gr.Markdown(elem_classes="report-card")
|
| 174 |
with gr.Tab("Visual Analytics"):
|
| 175 |
+
gr.Markdown("### Analisis Arus Kas\n**Batang Muda (Light Blue)** = Uang Masuk. **Batang Tua (Deep Blue)** = Uang Keluar.")
|
| 176 |
plot_cf = gr.Plot()
|
| 177 |
gr.Markdown("---")
|
| 178 |
+
gr.Markdown("### Tren Pertumbuhan Saldo\nMenunjukkan konsistensi nasabah dalam membangun cadangan likuiditas.")
|
| 179 |
plot_bal = gr.Plot()
|
| 180 |
|
| 181 |
+
btn.click(fn=run_app, inputs=id_in, outputs=[out_side, out_report, plot_cf, plot_bal])
|
| 182 |
|
| 183 |
demo.launch()
|