ZakyF commited on
Commit
88eb790
Β·
1 Parent(s): cc1a9d9

refactor: rename engine and methods, enhance NBO logic with detailed steps, and overhaul report generation with new UI styling.

Browse files
Files changed (1) hide show
  1. app.py +90 -73
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
- # --- INITIALIZATION ---
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
  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
- .report-card { background: #FFFFFF; border-radius: 12px; padding: 25px; border: 1.5px solid #E0EDF4; box-shadow: 0 4px 15px rgba(5, 20, 222, 0.05); margin-bottom: 20px; }
20
- .section-header { color: #0514DE; border-bottom: 2px solid #F7BD87; padding-bottom: 5px; margin-bottom: 15px; font-weight: 700; }
21
- .status-pill { padding: 10px 20px; border-radius: 30px; color: white; font-weight: 800; display: inline-block; font-size: 1.1em; }
 
22
  """
23
 
24
- class ArchonNarrativeEngine:
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 run_full_pipeline(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 = self.df_cust[self.df_cust['customer_id'] == cid].iloc[0] if cid in self.df_cust['customer_id'].values else None
41
 
42
- if u_txn.empty or u_info is None: return None
 
43
 
44
- # --- FASE 2 & 3: INTELLIGENCE ---
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
- er_s = 1.0 if er > 0.8 else (0.5 if er > 0.5 else 0.0)
52
- 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
53
- od_s = 1.0 if (u_bal['min_balance'] <= 0).any() else 0.0
54
- mp_s = 1.0 if (u_rep['status'] == 'late').any() else 0.0
 
55
 
56
- score = (0.3 * er_s) + (0.2 * bt_s) + (0.2 * od_s) + (0.2 * mp_s) + 0.1
57
- risk_lv = "HIGH" if score >= 0.7 else ("MEDIUM" if score >= 0.4 else "LOW")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- # --- FASE 5: NBO ---
60
- if risk_lv == "HIGH": action, nbo_desc = "Restructuring Suggestion", "Fokus pada penyelamatan kredit."
61
- elif er > 0.6: action, nbo_desc = "Spending Control", "Batasi pengeluaran non-esensial."
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
- report += f"<h3 class='section-header'>πŸ” MENGAPA SKOR ANDA {score:.2f}?</h3>"
76
- report += f"<ul>"
77
- report += f"<li><b>Rasio Pengeluaran ({er:.1%})</b>: Artinya, dari setiap Rp1.000.000 yang Bapak/Ibu terima, sebanyak Rp{int(er*1000000):,} habis digunakan. {'Angka ini kritis karena melebihi batas aman 80%.' if er > 0.8 else 'Kondisi ini sehat karena di bawah batas aman.'}</li>"
78
 
79
- if len(u_bal) > 1:
80
- trend = "menurun" if u_bal.iloc[-1]['avg_balance'] < u_bal.iloc[-2]['avg_balance'] else "meningkat"
81
- report += f"<li><b>Tren Saldo</b>: Saldo rata-rata Anda terpantau <b>{trend}</b>. Tren ini digunakan bank untuk melihat kemampuan Bapak/Ibu dalam menghadapi kebutuhan mendadak di masa depan.</li>"
82
-
83
- report += f"</ul>"
 
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}, pengeluaran {er:.1%}. Terakhir belanja di {tx}. Beri saran hangat personal (Bapak/Ibu) maks 2 kalimat."
93
  resp = client_ai.models.generate_content(model="gemini-1.5-flash", contents=prompt)
94
- report += f"<div style='background:#f0f9ff; padding:15px; border-radius:10px; margin-top:10px; border:1px solid #bae6fd;'><b>πŸ’‘ Pesan Personal Advisor:</b><br>_{resp.text}_</div>"
95
  except: pass
96
-
97
- report += "</div>"
98
  return report
99
 
100
  # --- UI LOGIC ---
101
- engine = ArchonNarrativeEngine()
102
 
103
  def process(cust_id):
104
- res = engine.run_full_pipeline(cust_id)
105
- if not res: return "## ❌ ID Tidak Ditemukan", "Coba gunakan C0001 - C0120", None, None
106
 
107
- risk_lv, score, er, u_bal, u_txn, exp, inc, action, nbo_desc = res
108
- narrative = engine.build_narrative_report(risk_lv, score, er, u_bal, exp, inc, action, nbo_desc, cust_id, u_txn)
109
 
110
- # Graphs with Interpretation
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
- f2.add_trace(go.Bar(x=cf.index, y=cf.get('credit', 0), name='Pemasukan', marker_color='#82C3EB'))
120
- f2.add_trace(go.Bar(x=cf.index, y=cf.get('debit', 0), name='Pengeluaran', marker_color='#0514DE'))
121
- f2.update_layout(title="Laporan Arus Kas", barmode='group', template='plotly_white')
122
 
123
- status_color = "#ef4444" if risk_lv == "HIGH" else ("#f59e0b" if risk_lv == "MEDIUM" else "#10b981")
124
- status_html = f"""<div style='text-align:center;'><span class='status-pill' style='background:{status_color}'>{risk_lv} RISK</span><br><p style='margin-top:10px;'>Risk Score: <b>{score:.2f}</b></p></div>"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- return status_html, narrative, f1, f2
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("πŸ“‹ Executive Briefing"):
140
- out_report = gr.HTML()
141
- with gr.Tab("πŸ“ˆ Visual Analytics"):
142
- gr.Markdown("### Interpretasi Arus Kas\nBatang biru (Pengeluaran) tidak boleh sering melebihi batang muda (Pemasukan).")
143
  plot_cf = gr.Plot()
144
  gr.Markdown("---")
145
- gr.Markdown("### Tren Saldo\nGrafik yang naik menunjukkan nasabah memiliki daya tahan terhadap krisis ekonomi.")
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])