refactor: Rename main engine class, refine financial analysis logic and NBO recommendations with added steps, update narrative generation, and simplify visualizations.
Browse files
app.py
CHANGED
|
@@ -13,25 +13,15 @@ client_ai = genai.Client(api_key=GOOGLE_API_KEY) if GOOGLE_API_KEY else None
|
|
| 13 |
custom_css = """
|
| 14 |
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
|
| 15 |
body, .gradio-container { font-family: 'Plus Jakarta Sans', sans-serif !important; background-color: #FFFFFF !important; }
|
| 16 |
-
|
| 17 |
-
.nagari-header {
|
| 18 |
-
|
| 19 |
-
padding: 35px; border-radius: 15px; border-bottom: 6px solid #F7BD87;
|
| 20 |
-
margin-bottom: 25px; text-align: center;
|
| 21 |
-
}
|
| 22 |
-
.nagari-header h1 { color: #FFFFFF !important; font-weight: 800 !important; margin: 0; font-size: 2.2em; text-shadow: 2px 2px 4px rgba(0,0,0,0.2); }
|
| 23 |
-
|
| 24 |
-
.card-sidebar {
|
| 25 |
-
background: #E0EDF4; border-radius: 15px; padding: 25px;
|
| 26 |
-
border: 1.5px solid #82C3EB; box-shadow: 0 4px 12px rgba(5, 164, 222, 0.1);
|
| 27 |
-
}
|
| 28 |
.health-badge { background: white; padding: 12px; border-radius: 8px; margin-bottom: 12px; border-left: 5px solid #05A4DE; font-size: 0.95em; }
|
| 29 |
-
|
| 30 |
.report-card { background: white; border-radius: 12px; padding: 30px; border: 1px solid #E2E8F0; line-height: 1.8; color: #1e293b; }
|
| 31 |
.nbo-box { background: #fffdf0; border: 2px solid #F7BD87; padding: 20px; border-radius: 10px; margin-top: 20px; }
|
| 32 |
"""
|
| 33 |
|
| 34 |
-
class
|
| 35 |
def __init__(self):
|
| 36 |
self.load_data()
|
| 37 |
|
|
@@ -48,72 +38,79 @@ class ArchonMasterEngine:
|
|
| 48 |
u_txn = self.df_txn[self.df_txn['customer_id'] == cid].copy()
|
| 49 |
u_bal = self.df_bal[self.df_bal['customer_id'] == cid].sort_values('month')
|
| 50 |
u_rep = self.df_rep[self.df_rep['customer_id'] == cid]
|
| 51 |
-
|
| 52 |
|
| 53 |
-
if u_txn.empty or
|
| 54 |
-
u_info =
|
| 55 |
|
| 56 |
-
# --- FASE 2: INTELLIGENCE (
|
| 57 |
-
|
| 58 |
-
essential_keywords = ['indomaret', 'alfamart', 'pdam', 'listrik', 'cicilan', 'pinjaman', 'bill', 'gaji', 'atm', 'grocer', 'sekolah', 'rs ', 'obat']
|
| 59 |
-
|
| 60 |
def classify_exp(row):
|
| 61 |
desc = str(row.get('raw_description', '')).lower()
|
| 62 |
-
if any(k in desc for k in
|
| 63 |
-
return 'discretionary'
|
| 64 |
-
|
| 65 |
u_txn['expense_type'] = u_txn.apply(classify_exp, axis=1)
|
| 66 |
|
| 67 |
-
# --- FASE 3 & 4: RISK SCORING (STRICT
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
er =
|
| 72 |
|
|
|
|
| 73 |
er_s = 1.0 if er > 0.8 else (0.5 if er > 0.5 else 0.0)
|
| 74 |
-
bt_s = 1.0 if len(u_bal) >= 2 and u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[
|
| 75 |
od_s = 1.0 if (u_bal['min_balance'] <= 0).any() else 0.0
|
| 76 |
mp_s = 1.0 if (u_rep['status'] == 'late').any() else 0.0
|
| 77 |
|
| 78 |
score = (0.3 * er_s) + (0.2 * bt_s) + (0.2 * od_s) + (0.2 * mp_s) + 0.05
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
# --- FASE 5: NBO ENGINE (Customer Oriented) ---
|
| 82 |
if risk_lv == "HIGH" or mp_s == 1:
|
| 83 |
action = "Evaluasi Cicilan & Restrukturisasi"
|
| 84 |
nbo_msg = "Untuk membantu meringankan beban finansial, Bapak/Ibu dapat mengajukan perpanjangan tenor atau penyesuaian jadwal pembayaran cicilan."
|
|
|
|
| 85 |
elif er > 0.6:
|
| 86 |
action = "Pengaturan Limit Belanja (Spending Control)"
|
| 87 |
nbo_msg = "Kami mendeteksi pengeluaran bulanan yang cukup tinggi. Bapak/Ibu disarankan mengaktifkan fitur limit transaksi QRIS untuk menjaga tabungan."
|
|
|
|
| 88 |
elif risk_lv == "LOW":
|
| 89 |
action = "Pengembangan Aset (Saving/Investment)"
|
| 90 |
nbo_msg = "Kondisi keuangan Bapak/Ibu sangat prima. Ini waktu yang tepat untuk menanamkan dana mengendap ke Deposito atau Tabungan Berjangka."
|
|
|
|
| 91 |
else:
|
| 92 |
action = "Edukasi Pengelolaan Kas"
|
| 93 |
nbo_msg = "Mari optimalkan arus kas harian Bapak/Ibu dengan fitur budgeting di aplikasi mobile kami agar resiliensi tetap terjaga."
|
|
|
|
| 94 |
|
| 95 |
-
return risk_lv, score, er, u_bal, u_txn,
|
| 96 |
|
| 97 |
-
def
|
| 98 |
-
# FASE 6: EXPLAINABLE NARRATIVE
|
| 99 |
-
|
| 100 |
-
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
|
| 106 |
if not u_bal.empty:
|
| 107 |
-
|
| 108 |
-
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
| 114 |
|
| 115 |
def create_viz(self, u_bal, u_txn):
|
| 116 |
-
# 1.
|
| 117 |
u_txn['m'] = u_txn['date'].dt.to_period('M').dt.to_timestamp()
|
| 118 |
cf = u_txn.groupby(['m', 'transaction_type'])['amount'].sum().unstack().fillna(0)
|
| 119 |
f1 = go.Figure()
|
|
@@ -130,58 +127,51 @@ class ArchonMasterEngine:
|
|
| 130 |
)])
|
| 131 |
f2.update_layout(title="Komposisi Pengeluaran (Kebutuhan vs Gaya Hidup)")
|
| 132 |
|
| 133 |
-
|
| 134 |
-
f3 = go.Figure()
|
| 135 |
-
f3.add_trace(go.Scatter(x=u_bal['month'], y=u_bal['avg_balance'], name='Saldo Rata-rata', line=dict(color='#F7BD87', width=4)))
|
| 136 |
-
f3.update_layout(title="Tren Pertumbuhan Saldo", template='plotly_white')
|
| 137 |
-
|
| 138 |
-
return f1, f2, f3
|
| 139 |
|
| 140 |
# --- UI LOGIC ---
|
| 141 |
-
engine =
|
| 142 |
|
| 143 |
-
def
|
| 144 |
res = engine.analyze(cust_id)
|
| 145 |
-
if not res: return "ID Tidak Valid", "Gunakan C0001 - C0120", None, None
|
| 146 |
|
| 147 |
-
risk_lv, score, er, u_bal, u_txn, exp, inc, action, nbo_msg, er_s, bt_s, od_s, mp_s = res
|
| 148 |
-
report = engine.
|
| 149 |
-
p1, p2
|
| 150 |
|
| 151 |
color = "#ef4444" if risk_lv == "HIGH" else ("#f59e0b" if risk_lv == "MEDIUM" else "#10b981")
|
| 152 |
sidebar = f"""
|
| 153 |
<div class='card-sidebar'>
|
| 154 |
-
<h2 style='color: #05A4DE; margin:0;'>
|
| 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 class='health-badge'><b>Skor Risiko:</b> {score:.2f} / 1.00</div>
|
| 157 |
-
<div class='health-badge'><b>
|
| 158 |
-
<div class='health-badge'><b>
|
| 159 |
</div>
|
| 160 |
"""
|
| 161 |
-
return sidebar, report, p1, p2
|
| 162 |
|
| 163 |
with gr.Blocks(css=custom_css) as demo:
|
| 164 |
gr.HTML("<div class='nagari-header'><h1>ARCHON-AI</h1></div>")
|
| 165 |
with gr.Row():
|
| 166 |
with gr.Column(scale=1):
|
| 167 |
id_in = gr.Textbox(label="Customer ID", placeholder="C0001")
|
| 168 |
-
btn = gr.Button("
|
| 169 |
out_side = gr.HTML()
|
| 170 |
with gr.Column(scale=2):
|
| 171 |
with gr.Tabs():
|
| 172 |
-
with gr.Tab("Laporan
|
| 173 |
out_report = gr.Markdown(elem_classes="report-card")
|
| 174 |
-
with gr.Tab("
|
| 175 |
-
gr.Markdown("### 1.
|
| 176 |
plot_cf = gr.Plot()
|
|
|
|
| 177 |
gr.Markdown("---")
|
| 178 |
-
gr.Markdown("### 2.
|
| 179 |
plot_dist = gr.Plot()
|
| 180 |
-
gr.HTML("<div style='background:#f1f5f9; padding:15px; border-radius:8px;'><b>
|
| 181 |
-
gr.Markdown("---")
|
| 182 |
-
gr.Markdown("### 3. Tren Pertumbuhan Saldo")
|
| 183 |
-
plot_bal = gr.Plot()
|
| 184 |
|
| 185 |
-
btn.click(fn=
|
| 186 |
|
| 187 |
demo.launch()
|
|
|
|
| 13 |
custom_css = """
|
| 14 |
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap');
|
| 15 |
body, .gradio-container { font-family: 'Plus Jakarta Sans', sans-serif !important; background-color: #FFFFFF !important; }
|
| 16 |
+
.nagari-header { background: linear-gradient(135deg, #05A4DE 0%, #82C3EB 100%); padding: 35px; border-radius: 15px; border-bottom: 6px solid #F7BD87; text-align: center; margin-bottom: 25px; }
|
| 17 |
+
.nagari-header h1 { color: #FFFFFF !important; font-weight: 800 !important; margin: 0; font-size: 2.2em; }
|
| 18 |
+
.card-sidebar { background: #E0EDF4; border-radius: 15px; padding: 25px; border: 1.5px solid #82C3EB; box-shadow: 0 4px 12px rgba(5, 164, 222, 0.1); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
.health-badge { background: white; padding: 12px; border-radius: 8px; margin-bottom: 12px; border-left: 5px solid #05A4DE; font-size: 0.95em; }
|
|
|
|
| 20 |
.report-card { background: white; border-radius: 12px; padding: 30px; border: 1px solid #E2E8F0; line-height: 1.8; color: #1e293b; }
|
| 21 |
.nbo-box { background: #fffdf0; border: 2px solid #F7BD87; padding: 20px; border-radius: 10px; margin-top: 20px; }
|
| 22 |
"""
|
| 23 |
|
| 24 |
+
class ArchonFinalEngine:
|
| 25 |
def __init__(self):
|
| 26 |
self.load_data()
|
| 27 |
|
|
|
|
| 38 |
u_txn = self.df_txn[self.df_txn['customer_id'] == cid].copy()
|
| 39 |
u_bal = self.df_bal[self.df_bal['customer_id'] == cid].sort_values('month')
|
| 40 |
u_rep = self.df_rep[self.df_rep['customer_id'] == cid]
|
| 41 |
+
u_info_list = self.df_cust[self.df_cust['customer_id'] == cid]
|
| 42 |
|
| 43 |
+
if u_txn.empty or u_info_list.empty: return None
|
| 44 |
+
u_info = u_info_list.iloc[0]
|
| 45 |
|
| 46 |
+
# --- FASE 2: TRANSACTION INTELLIGENCE (Semantic) ---
|
| 47 |
+
essential_list = ['indomaret', 'alfamart', 'listrik', 'pdam', 'telkom', 'sekolah', 'rs ', 'obat', 'cicilan', 'pinjaman', 'gaji', 'asuransi']
|
|
|
|
|
|
|
| 48 |
def classify_exp(row):
|
| 49 |
desc = str(row.get('raw_description', '')).lower()
|
| 50 |
+
return 'essential' if any(k in desc for k in essential_list) else 'discretionary'
|
|
|
|
|
|
|
| 51 |
u_txn['expense_type'] = u_txn.apply(classify_exp, axis=1)
|
| 52 |
|
| 53 |
+
# --- FASE 3 & 4: RISK SCORING (STRICT COMPLIANCE) ---
|
| 54 |
+
income_txn = u_txn[u_txn['transaction_type'] == 'credit']['amount'].sum()
|
| 55 |
+
ref_income = max(income_txn, u_info['monthly_income'])
|
| 56 |
+
expense = u_txn[u_txn['transaction_type'] == 'debit']['amount'].sum()
|
| 57 |
+
er = expense / ref_income if ref_income > 0 else 1.0
|
| 58 |
|
| 59 |
+
# Scoring Rules
|
| 60 |
er_s = 1.0 if er > 0.8 else (0.5 if er > 0.5 else 0.0)
|
| 61 |
+
bt_s = 1.0 if len(u_bal) >= 2 and u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[0]['avg_balance'] else 0.0
|
| 62 |
od_s = 1.0 if (u_bal['min_balance'] <= 0).any() else 0.0
|
| 63 |
mp_s = 1.0 if (u_rep['status'] == 'late').any() else 0.0
|
| 64 |
|
| 65 |
score = (0.3 * er_s) + (0.2 * bt_s) + (0.2 * od_s) + (0.2 * mp_s) + 0.05
|
| 66 |
+
|
| 67 |
+
# Classification (Sesuai dokumen)
|
| 68 |
+
if score >= 0.7: risk_lv = "HIGH"
|
| 69 |
+
elif score >= 0.4: risk_lv = "MEDIUM"
|
| 70 |
+
else: risk_lv = "LOW"
|
| 71 |
|
| 72 |
# --- FASE 5: NBO ENGINE (Customer Oriented) ---
|
| 73 |
if risk_lv == "HIGH" or mp_s == 1:
|
| 74 |
action = "Evaluasi Cicilan & Restrukturisasi"
|
| 75 |
nbo_msg = "Untuk membantu meringankan beban finansial, Bapak/Ibu dapat mengajukan perpanjangan tenor atau penyesuaian jadwal pembayaran cicilan."
|
| 76 |
+
steps = ["Ajukan peninjauan tenor pinjaman", "Konsolidasi tagihan harian", "Manfaatkan konsultasi dana darurat."]
|
| 77 |
elif er > 0.6:
|
| 78 |
action = "Pengaturan Limit Belanja (Spending Control)"
|
| 79 |
nbo_msg = "Kami mendeteksi pengeluaran bulanan yang cukup tinggi. Bapak/Ibu disarankan mengaktifkan fitur limit transaksi QRIS untuk menjaga tabungan."
|
| 80 |
+
steps = ["Atur limit harian belanja", "Aktifkan notifikasi saldo minimum", "Prioritaskan kebutuhan pokok (Essential)."]
|
| 81 |
elif risk_lv == "LOW":
|
| 82 |
action = "Pengembangan Aset (Saving/Investment)"
|
| 83 |
nbo_msg = "Kondisi keuangan Bapak/Ibu sangat prima. Ini waktu yang tepat untuk menanamkan dana mengendap ke Deposito atau Tabungan Berjangka."
|
| 84 |
+
steps = ["Buka tabungan berjangka otomatis", "Pindahkan dana ke deposito bunga tinggi", "Eksplorasi produk reksa dana."]
|
| 85 |
else:
|
| 86 |
action = "Edukasi Pengelolaan Kas"
|
| 87 |
nbo_msg = "Mari optimalkan arus kas harian Bapak/Ibu dengan fitur budgeting di aplikasi mobile kami agar resiliensi tetap terjaga."
|
| 88 |
+
steps = ["Baca artikel cerdas belanja", "Gunakan fitur budgeting di aplikasi", "Review pengeluaran akhir bulan."]
|
| 89 |
|
| 90 |
+
return risk_lv, score, er, u_bal, u_txn, expense, ref_income, action, nbo_msg, steps, er_s, bt_s, od_s, mp_s
|
| 91 |
|
| 92 |
+
def build_narrative(self, risk_lv, score, er, u_bal, exp, inc, action, nbo_msg, steps, cid, u_txn):
|
| 93 |
+
# FASE 6: EXPLAINABLE SUMMARY (NARRATIVE)
|
| 94 |
+
msg = f"### ANALISIS RESILIENSI FINANSIAL ANDA\n\n"
|
| 95 |
+
msg += f"Halo Bapak/Ibu, berdasarkan tinjauan transaksi Anda ({cid}), sistem kami menetapkan tingkat kesehatan finansial Anda pada kategori **{risk_lv}** (Skor: {score:.2f}).\n\n"
|
| 96 |
|
| 97 |
+
msg += f"**1. Mengapa Skor Ini Muncul?**\n"
|
| 98 |
+
msg += f"* **Efisiensi Belanja ({er:.1%})**: Anda menghabiskan Rp{exp:,.0f} dari pendapatan Rp{inc:,.0f}. "
|
| 99 |
+
msg += "Artinya, Bapak/Ibu membelanjakan lebih banyak dari yang diterima. Ini mengindikasikan penggunaan dana tabungan untuk konsumsi harian." if er > 1 else "Manajemen belanja Anda terpantau sehat."
|
| 100 |
|
| 101 |
if not u_bal.empty:
|
| 102 |
+
msg += f"\n* **Analisis Saldo**: Saldo saat ini Rp{u_bal.iloc[-1]['avg_balance']:,.0f}. "
|
| 103 |
+
msg += "Terdeteksi tren penurunan saldo rata-rata, disarankan untuk mulai menabung kembali." if len(u_bal) > 1 and u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[0]['avg_balance'] else "Saldo Anda tumbuh dengan stabil dan aman."
|
| 104 |
|
| 105 |
+
msg += f"\n\n<div class='nbo-box'>REKOMENDASI UNTUK ANDA: {action}\n\n"
|
| 106 |
+
msg += f"**Tujuan:** {nbo_msg}\n\n"
|
| 107 |
+
msg += f"**Langkah Implementasi:**\n"
|
| 108 |
+
for i, step in enumerate(steps, 1): msg += f"{i}. {step}\n"
|
| 109 |
+
msg += f"</div>"
|
| 110 |
+
return msg
|
| 111 |
|
| 112 |
def create_viz(self, u_bal, u_txn):
|
| 113 |
+
# 1. Cashflow
|
| 114 |
u_txn['m'] = u_txn['date'].dt.to_period('M').dt.to_timestamp()
|
| 115 |
cf = u_txn.groupby(['m', 'transaction_type'])['amount'].sum().unstack().fillna(0)
|
| 116 |
f1 = go.Figure()
|
|
|
|
| 127 |
)])
|
| 128 |
f2.update_layout(title="Komposisi Pengeluaran (Kebutuhan vs Gaya Hidup)")
|
| 129 |
|
| 130 |
+
return f1, f2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
# --- UI LOGIC ---
|
| 133 |
+
engine = ArchonFinalEngine()
|
| 134 |
|
| 135 |
+
def run_app(cust_id):
|
| 136 |
res = engine.analyze(cust_id)
|
| 137 |
+
if not res: return "ID Tidak Valid", "Gunakan C0001 - C0120", None, None
|
| 138 |
|
| 139 |
+
risk_lv, score, er, u_bal, u_txn, exp, inc, action, nbo_msg, steps, er_s, bt_s, od_s, mp_s = res
|
| 140 |
+
report = engine.build_narrative(risk_lv, score, er, u_bal, exp, inc, action, nbo_msg, steps, cust_id, u_txn)
|
| 141 |
+
p1, p2 = engine.create_viz(u_bal, u_txn)
|
| 142 |
|
| 143 |
color = "#ef4444" if risk_lv == "HIGH" else ("#f59e0b" if risk_lv == "MEDIUM" else "#10b981")
|
| 144 |
sidebar = f"""
|
| 145 |
<div class='card-sidebar'>
|
| 146 |
+
<h2 style='color: #05A4DE; margin:0;'>Status Keuangan</h2>
|
| 147 |
+
<div style='background:{color}; color:white; padding:10px 20px; border-radius:30px; font-weight:bold; display:inline-block; margin:15px 0;'>{risk_lv} RISK LEVEL</div>
|
| 148 |
<div class='health-badge'><b>Skor Risiko:</b> {score:.2f} / 1.00</div>
|
| 149 |
+
<div class='health-badge'><b>Efisiensi Belanja:</b> {er:.1%} {'⚠️' if er > 0.8 else '✔️'}</div>
|
| 150 |
+
<div class='health-badge'><b>Kesehatan Saldo:</b> {'🔻 Menurun' if bt_s == 1 else '🔺 Stabil'}</div>
|
| 151 |
</div>
|
| 152 |
"""
|
| 153 |
+
return sidebar, report, p1, p2
|
| 154 |
|
| 155 |
with gr.Blocks(css=custom_css) as demo:
|
| 156 |
gr.HTML("<div class='nagari-header'><h1>ARCHON-AI</h1></div>")
|
| 157 |
with gr.Row():
|
| 158 |
with gr.Column(scale=1):
|
| 159 |
id_in = gr.Textbox(label="Customer ID", placeholder="C0001")
|
| 160 |
+
btn = gr.Button("ANALYISIS SEKARANG", variant="primary")
|
| 161 |
out_side = gr.HTML()
|
| 162 |
with gr.Column(scale=2):
|
| 163 |
with gr.Tabs():
|
| 164 |
+
with gr.Tab("Laporan Untuk Anda"):
|
| 165 |
out_report = gr.Markdown(elem_classes="report-card")
|
| 166 |
+
with gr.Tab("Visualisasi Keuangan"):
|
| 167 |
+
gr.Markdown("### 1. Uang Masuk vs Uang Keluar")
|
| 168 |
plot_cf = gr.Plot()
|
| 169 |
+
gr.HTML("<div style='background:#f1f5f9; padding:15px; border-radius:8px;'><b>Interpretasi:</b> Batang muda (Inflow) harus lebih tinggi dari batang tua (Outflow) untuk menjaga saldo tetap aman.</div>")
|
| 170 |
gr.Markdown("---")
|
| 171 |
+
gr.Markdown("### 2. Ke mana Uang Anda Pergi?")
|
| 172 |
plot_dist = gr.Plot()
|
| 173 |
+
gr.HTML("<div style='background:#f1f5f9; padding:15px; border-radius:8px;'><b>Warna:</b> Biru = Kebutuhan (Essential). Emas = Gaya Hidup (Discretionary).</div>")
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
btn.click(fn=run_app, inputs=id_in, outputs=[out_side, out_report, plot_cf, plot_dist])
|
| 176 |
|
| 177 |
demo.launch()
|