refactor: rename engine and methods, enhance NBO logic with detailed steps, and overhaul report generation with new UI styling.
Browse files
app.py
CHANGED
|
@@ -6,143 +6,160 @@ import plotly.graph_objects as go
|
|
| 6 |
from google import genai
|
| 7 |
from datetime import timedelta
|
| 8 |
|
| 9 |
-
# ---
|
| 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
|
| 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 |
.nagari-header { background: linear-gradient(135deg, #0514DE 0%, #82C3EB 100%); padding: 35px; border-radius: 15px; border-bottom: 6px solid #F7BD87; text-align: center; margin-bottom: 25px; }
|
| 18 |
.nagari-header h1 { color: #FFFFFF !important; font-weight: 800 !important; margin: 0; font-size: 2.2em; }
|
| 19 |
-
.
|
| 20 |
-
.
|
| 21 |
-
.
|
|
|
|
| 22 |
"""
|
| 23 |
|
| 24 |
-
class
|
| 25 |
def __init__(self):
|
| 26 |
self.load_data()
|
| 27 |
|
| 28 |
def load_data(self):
|
| 29 |
-
# FASE 1: Foundation
|
| 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')
|
| 33 |
self.df_rep = pd.read_csv('repayments_revised.csv', parse_dates=['due_date']).fillna("on_time")
|
| 34 |
|
| 35 |
-
def
|
| 36 |
cid = str(customer_id).strip().upper()
|
| 37 |
u_txn = self.df_txn[self.df_txn['customer_id'] == cid].copy()
|
| 38 |
u_bal = self.df_bal[self.df_bal['customer_id'] == cid].sort_values('month')
|
| 39 |
u_rep = self.df_rep[self.df_rep['customer_id'] == cid]
|
| 40 |
-
|
| 41 |
|
| 42 |
-
if u_txn.empty or
|
|
|
|
| 43 |
|
| 44 |
-
# --- FASE 2
|
| 45 |
income_txn = u_txn[u_txn['transaction_type'] == 'credit']['amount'].sum()
|
| 46 |
ref_income = max(income_txn, u_info['monthly_income'])
|
| 47 |
expense = u_txn[u_txn['transaction_type'] == 'debit']['amount'].sum()
|
| 48 |
-
er = min(expense / ref_income, 1.0)
|
| 49 |
|
| 50 |
# --- FASE 4: RISK SCORING (30/20/20/20/10) ---
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
risk_lv = "HIGH" if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
else: action, nbo_desc = "Promote Saving/Investment", "Optimalkan surplus dana nasabah."
|
| 63 |
-
|
| 64 |
-
return risk_lv, score, er, u_bal, u_txn, expense, ref_income, action, nbo_desc
|
| 65 |
-
|
| 66 |
-
def build_narrative_report(self, risk_lv, score, er, u_bal, expense, income, action, nbo_desc, cid, u_txn):
|
| 67 |
-
# FASE 6: EXPLAINABLE SUMMARY & RINGKASAN AI
|
| 68 |
-
report = f"<div class='report-card'>"
|
| 69 |
-
report += f"<h3 class='section-header'>π EXECUTIVE SUMMARY (RINGKASAN AI)</h3>"
|
| 70 |
-
|
| 71 |
-
# Ringkasan Naratif Otomatis
|
| 72 |
-
report += f"<p>Berdasarkan analisis menyeluruh terhadap data mutasi dan profil Bapak/Ibu ({cid}), sistem Archon menetapkan tingkat resiliensi finansial Anda berada pada kategori <b>{risk_lv}</b>. "
|
| 73 |
-
report += f"Hal ini disebabkan oleh kombinasi antara rasio pengeluaran sebesar {er:.1%} dan stabilitas saldo yang memerlukan perhatian khusus.</p>"
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 84 |
|
| 85 |
-
report += f"<h3 class='section-header'>π― REKOMENDASI TINDAKAN (NBO)</h3>"
|
| 86 |
-
report += f"<p>Sistem merekomendasikan aksi: <b>{action}</b>. <br><i>Mengapa?</i> {nbo_desc}</p>"
|
| 87 |
-
|
| 88 |
-
# Gemini Section
|
| 89 |
if client_ai:
|
| 90 |
try:
|
| 91 |
tx = u_txn.tail(1)['raw_description'].iloc[0]
|
| 92 |
-
prompt = f"Advisor Bank Nagari: Nasabah {cid} risiko {risk_lv},
|
| 93 |
resp = client_ai.models.generate_content(model="gemini-1.5-flash", contents=prompt)
|
| 94 |
-
report += f"
|
| 95 |
except: pass
|
| 96 |
-
|
| 97 |
-
report += "</div>"
|
| 98 |
return report
|
| 99 |
|
| 100 |
# --- UI LOGIC ---
|
| 101 |
-
engine =
|
| 102 |
|
| 103 |
def process(cust_id):
|
| 104 |
-
res = engine.
|
| 105 |
-
if not res: return "## β ID Tidak Ditemukan", "
|
| 106 |
|
| 107 |
-
risk_lv, score, er, u_bal, u_txn, exp, inc, action,
|
| 108 |
-
|
| 109 |
|
| 110 |
-
# Graphs
|
| 111 |
-
color = "#0514DE"
|
| 112 |
f1 = go.Figure()
|
| 113 |
-
f1.add_trace(go.Scatter(x=u_bal['month'], y=u_bal['avg_balance'], name='Rata-rata Saldo', line=dict(color='#F7BD87', width=4)))
|
| 114 |
-
f1.update_layout(title="Kesehatan Pertumbuhan Saldo", template="plotly_white")
|
| 115 |
-
|
| 116 |
-
f2 = go.Figure()
|
| 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 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
return
|
| 127 |
|
| 128 |
with gr.Blocks(css=custom_css) as demo:
|
| 129 |
gr.HTML("<div class='nagari-header'><h1>ARCHON-AI</h1></div>")
|
| 130 |
-
|
| 131 |
with gr.Row():
|
| 132 |
with gr.Column(scale=1):
|
| 133 |
id_in = gr.Textbox(label="Customer ID", placeholder="C0001")
|
| 134 |
btn = gr.Button("ANALYZE CUSTOMER", variant="primary")
|
| 135 |
out_status = gr.HTML()
|
| 136 |
-
|
| 137 |
with gr.Column(scale=2):
|
| 138 |
with gr.Tabs():
|
| 139 |
-
with gr.Tab("
|
| 140 |
-
out_report = gr.
|
| 141 |
-
with gr.Tab("
|
| 142 |
-
gr.Markdown("### Interpretasi Arus Kas\
|
| 143 |
plot_cf = gr.Plot()
|
| 144 |
gr.Markdown("---")
|
| 145 |
-
gr.Markdown("### Tren Saldo\
|
| 146 |
plot_bal = gr.Plot()
|
| 147 |
|
| 148 |
btn.click(fn=process, inputs=id_in, outputs=[out_status, out_report, plot_cf, plot_bal])
|
|
|
|
| 6 |
from google import genai
|
| 7 |
from datetime import timedelta
|
| 8 |
|
| 9 |
+
# --- CONFIG AI ---
|
| 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 REFINED ---
|
| 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 |
.nagari-header { background: linear-gradient(135deg, #0514DE 0%, #82C3EB 100%); padding: 35px; border-radius: 15px; border-bottom: 6px solid #F7BD87; text-align: center; margin-bottom: 25px; }
|
| 18 |
.nagari-header h1 { color: #FFFFFF !important; font-weight: 800 !important; margin: 0; font-size: 2.2em; }
|
| 19 |
+
.card-left { background: #E0EDF4; border-radius: 15px; padding: 25px; border: 1.5px solid #82C3EB; box-shadow: 0 4px 12px rgba(5, 20, 222, 0.08); }
|
| 20 |
+
.badge-item { background: white; padding: 10px; border-radius: 8px; margin-bottom: 10px; border-left: 4px solid #0514DE; font-size: 0.9em; }
|
| 21 |
+
.report-card { background: white; border-radius: 12px; padding: 30px; border: 1px solid #E2E8F0; line-height: 1.8; color: #1e293b; }
|
| 22 |
+
.nbo-box { background: #fffdf0; border: 2px solid #F7BD87; padding: 20px; border-radius: 10px; margin-top: 20px; }
|
| 23 |
"""
|
| 24 |
|
| 25 |
+
class ArchonFinalEngine:
|
| 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')
|
| 33 |
self.df_rep = pd.read_csv('repayments_revised.csv', parse_dates=['due_date']).fillna("on_time")
|
| 34 |
|
| 35 |
+
def analyze(self, customer_id):
|
| 36 |
cid = str(customer_id).strip().upper()
|
| 37 |
u_txn = self.df_txn[self.df_txn['customer_id'] == cid].copy()
|
| 38 |
u_bal = self.df_bal[self.df_bal['customer_id'] == cid].sort_values('month')
|
| 39 |
u_rep = self.df_rep[self.df_rep['customer_id'] == cid]
|
| 40 |
+
u_info_list = self.df_cust[self.df_cust['customer_id'] == cid]
|
| 41 |
|
| 42 |
+
if u_txn.empty or u_info_list.empty: return None
|
| 43 |
+
u_info = u_info_list.iloc[0]
|
| 44 |
|
| 45 |
+
# --- FASE 2: INTELLIGENCE ---
|
| 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 |
+
# Normalisasi Skor 0 - 1
|
| 53 |
+
er_score_val = 1.0 if er > 0.8 else (0.5 if er > 0.5 else 0.0)
|
| 54 |
+
bt_val = 1.0 if len(u_bal) >= 2 and u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[-2]['avg_balance'] else 0.0
|
| 55 |
+
od_val = 1.0 if (u_bal['min_balance'] <= 0).any() else 0.0
|
| 56 |
+
mp_val = 1.0 if (u_rep['status'] == 'late').any() else 0.0
|
| 57 |
|
| 58 |
+
final_score = (0.3 * er_score_val) + (0.2 * bt_s := bt_val) + (0.2 * od_s := od_val) + (0.2 * mp_s := mp_val) + 0.1
|
| 59 |
+
risk_lv = "HIGH" if final_score >= 0.7 else ("MEDIUM" if final_score >= 0.4 else "LOW")
|
| 60 |
+
|
| 61 |
+
# --- FASE 5: NBO ENGINE (SPENDING CONTROL FOCUS) ---
|
| 62 |
+
if risk_lv == "HIGH" or mp_val == 1:
|
| 63 |
+
action, nbo_detail = "Restructuring Suggestion", "Prioritas penyelamatan kredit melalui penjadwalan ulang cicilan."
|
| 64 |
+
steps = ["Penurunan suku bunga sementara", "Perpanjangan tenor pinjaman", "Konsolidasi utang harian."]
|
| 65 |
+
elif er > 0.6:
|
| 66 |
+
action, nbo_detail = "Spending Control", "Pengendalian pengeluaran non-esensial untuk menjaga likuiditas harian."
|
| 67 |
+
steps = ["Aktivasi limit harian transaksi QRIS", "Notifikasi otomatis saat belanja > Rp500rb", "Edukasi pemisahan rekening operasional."]
|
| 68 |
+
elif risk_lv == "LOW":
|
| 69 |
+
action, nbo_detail = "Promote Investment", "Optimalisasi surplus dana melalui produk investasi Bank Nagari."
|
| 70 |
+
steps = ["Penawaran Deposito Gold", "Reksa Dana pasar uang", "Tabungan berjangka otomatis."]
|
| 71 |
+
else:
|
| 72 |
+
action, nbo_detail = "Financial Education", "Edukasi pengelolaan arus kas agar status risiko tetap stabil."
|
| 73 |
+
steps = ["Webinar literasi keuangan", "E-book perencanaan budget", "Review bulanan bersama RM."]
|
| 74 |
+
|
| 75 |
+
return risk_lv, final_score, er, u_bal, u_txn, expense, ref_income, action, nbo_detail, steps, er_score_val, bt_val, od_val, mp_val
|
| 76 |
+
|
| 77 |
+
def get_report_text(self, risk_lv, score, er, u_bal, expense, income, action, nbo_detail, steps, cid, u_txn):
|
| 78 |
+
# Fase 6: Explainable Summary
|
| 79 |
+
report = f"### π ANALISIS EKSEKUTIF ARCHON-AI\n\n"
|
| 80 |
+
report += f"**Identitas Nasabah:** {cid}\n"
|
| 81 |
+
report += f"Berdasarkan audit mutasi, tingkat resiliensi Bapak/Ibu berada pada kategori **{risk_lv}** (Skor: {score:.2f}).\n\n"
|
| 82 |
|
| 83 |
+
report += f"**1. Mengapa Skor Ini Muncul?**\n"
|
| 84 |
+
report += f"* **Efisiensi Dana**: Rasio belanja Anda {er:.1%}. Artinya dari pendapatan Rp{income:,.0f}, sebanyak Rp{expense:,.0f} terpakai. "
|
| 85 |
+
report += "Ini mengindikasikan tekanan likuiditas." if er > 0.8 else "Ini menunjukkan kondisi kas yang aman."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
if not u_bal.empty:
|
| 88 |
+
report += f"\n* **Analisis Saldo**: Saldo rata-rata terakhir Rp{u_bal.iloc[-1]['avg_balance']:,.0f}. "
|
| 89 |
+
report += "Tren menurun terpantau, yang berarti cadangan dana darurat mulai menipis." if len(u_bal) > 1 and u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[-2]['avg_balance'] else "Tren pertumbuhan saldo positif."
|
| 90 |
|
| 91 |
+
report += f"\n\n<div class='nbo-box'>**π― REKOMENDASI STRATEGIS (NBO): {action}**\n\n"
|
| 92 |
+
report += f"**Definisi:** {nbo_detail}\n\n"
|
| 93 |
+
report += f"**Langkah-Langkah Implementasi:**\n"
|
| 94 |
+
for i, step in enumerate(steps, 1):
|
| 95 |
+
report += f"{i}. {step}\n"
|
| 96 |
+
report += f"</div>"
|
| 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} risiko {risk_lv}, expense {er:.1%}. Terakhir belanja di {tx}. Beri 1 saran hangat personal (Bapak/Ibu) maks 2 kalimat."
|
| 102 |
resp = client_ai.models.generate_content(model="gemini-1.5-flash", contents=prompt)
|
| 103 |
+
report += f"\n---\n**π‘ SARAN VIRTUAL ADVISOR:**\n_{resp.text}_"
|
| 104 |
except: pass
|
|
|
|
|
|
|
| 105 |
return report
|
| 106 |
|
| 107 |
# --- UI LOGIC ---
|
| 108 |
+
engine = ArchonFinalEngine()
|
| 109 |
|
| 110 |
def process(cust_id):
|
| 111 |
+
res = engine.analyze(cust_id)
|
| 112 |
+
if not res: return "## β ID Tidak Ditemukan", "Gunakan C0001 - C0120", None, None
|
| 113 |
|
| 114 |
+
risk_lv, score, er, u_bal, u_txn, exp, inc, action, nbo_detail, steps, er_s, bt_s, od_s, mp_s = res
|
| 115 |
+
report = engine.get_report_text(risk_lv, score, er, u_bal, exp, inc, action, nbo_detail, steps, cust_id, u_txn)
|
| 116 |
|
| 117 |
+
# Graphs - CORRECTED LEGEND
|
|
|
|
| 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="Arus Kas Bulanan", barmode='group', template='plotly_white')
|
| 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 |
+
sidebar_html = f"""
|
| 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 class='badge-item'><b>Expense Ratio:</b> {er:.1%} {'β οΈ' if er > 0.8 else 'β
'}</div>
|
| 137 |
+
<div class='badge-item'><b>Balance Trend:</b> {'π» Menurun' if bt_s == 1 else 'πΌ Stabil'}</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>")
|
|
|
|
| 149 |
with gr.Row():
|
| 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 |
out_status = gr.HTML()
|
|
|
|
| 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("### Interpretasi Arus Kas\n**Batang Tua (Pengeluaran)** sebaiknya tidak lebih tinggi dari **Batang Muda (Pemasukan)**.")
|
| 160 |
plot_cf = gr.Plot()
|
| 161 |
gr.Markdown("---")
|
| 162 |
+
gr.Markdown("### Tren Saldo\nMenunjukkan daya tahan nasabah terhadap krisis.")
|
| 163 |
plot_bal = gr.Plot()
|
| 164 |
|
| 165 |
btn.click(fn=process, inputs=id_in, outputs=[out_status, out_report, plot_cf, plot_bal])
|