ZakyF commited on
Commit
26afa72
·
1 Parent(s): c6bf683

feat: implement deterministic explanation and conditional Gemini advice, refactor risk scoring, and update UI elements and labels

Browse files
Files changed (1) hide show
  1. app.py +75 -53
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
- client = genai.Client(api_key=GOOGLE_API_KEY)
 
12
 
13
- # --- PALETTE WARNA & CSS CUSTOM ---
14
- # Primary: #0514DE, Secondary: #82C3EB, Pale: #E0EDF4, Accent: #F7BD87, White: #FFFFFF
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-style { background: #E0EDF4; border-radius: 12px; padding: 20px; border: 1px solid #82C3EB; box-shadow: 2px 4px 10px rgba(5, 20, 222, 0.05); }
20
- .status-badge { display: inline-block; padding: 5px 15px; border-radius: 20px; font-weight: bold; color: white; }
21
- .advice-box { background: white; border-left: 5px solid #F7BD87; padding: 20px; border-radius: 10px; font-size: 1.05em; line-height: 1.6; }
 
22
  """
23
 
24
  class ArchonNagariEngine:
@@ -28,115 +30,135 @@ class ArchonNagariEngine:
28
  except: self.classifier = None
29
 
30
  def load_data(self):
31
- # Fix C0014: fillna memastikan data siap olah
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 (WEIGHTED) ---
47
  income_txn = u_txn[u_txn['transaction_type'] == 'credit']['amount'].sum()
48
- base_income = max(income_txn, u_info['monthly_income'])
 
49
  expense = u_txn[u_txn['transaction_type'] == 'debit']['amount'].sum()
50
- er = expense / base_income
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
- score = (0.3 * er_s) + (0.2 * bt_s) + (0.2 * od_s) + (0.2 * mp_s) + 0.1
58
- risk_lv = "HIGH" if score >= 0.7 else ("MEDIUM" if score >= 0.4 else "LOW")
 
59
 
60
- return risk_lv, score, er, u_bal, u_txn, base_income, expense
61
 
62
- def get_adaptive_advice(self, risk_lv, er, score, u_txn, base_income, expense):
63
- # FASE 5 & 6: ADAPTIVE GEN-AI EXPLANATION
64
- recent_txn = u_txn.tail(3)['raw_description'].tolist()
65
- # Prompt yang lebih teknis dan mendalam agar Gemini tidak template
66
- prompt = f"""
67
- Identitas: Anda adalah Senior Financial Advisor Archon di Bank Nagari.
68
- Analisis Data Nasabah:
69
- - Status Risiko: {risk_lv} (Skor: {score:.2f}/1.00)
70
- - Rasio Pengeluaran: {er:.2%} (Pengeluaran: Rp{expense:,.0f} dari Pendapatan: Rp{base_income:,.0f})
71
- - Riwayat Belanja Terakhir: {', '.join(recent_txn)}
 
 
 
 
 
 
 
72
 
73
- Tugas:
74
- 1. Jelaskan arti skor {score:.2f} dan level {risk_lv} secara singkat dan logis.
75
- 2. Berikan saran personal yang dihubungkan dengan pengeluaran {er:.2%} dan riwayat belanja tersebut.
76
- 3. Gunakan sapaan Bapak/Ibu, bahasa Indonesia yang hangat namun profesional.
77
- 4. Jangan gunakan pembukaan template, langsung ke inti analisis.
 
 
 
 
 
 
78
  """
79
  try:
80
- resp = client.models.generate_content(model="gemini-1.5-flash", contents=prompt)
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 create_plots(self, u_bal, u_txn):
86
- # Plot 1: Cashflow (Nagari Colors)
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="Arus Kas Bulanan", barmode='group', template='plotly_white')
93
 
94
- # Plot 2: Balance History
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="Tren Saldo", template='plotly_white')
98
  return fig1, fig2
99
 
100
  # --- UI LOGIC ---
101
  engine = ArchonNagariEngine()
102
 
103
- def process(cust_id):
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
- advice = engine.get_adaptive_advice(risk_lv, er, score, u_txn, inc, exp)
 
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-style'>
115
  <h2 style='color: #0514DE; margin:0;'>Hasil Analisis AI</h2>
116
- <p style='margin:10px 0;'>Level Risiko: <span class='status-badge' style='background:{color}'>{risk_lv}</span></p>
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, advice, f1, f2
122
 
123
  with gr.Blocks(css=custom_css) as demo:
124
- gr.HTML("<div class='nagari-header'><h1>🛡️ ARCHON-AI: FINANCIAL ADVISOR</h1><p>Inteligensi Manajemen Risiko & Resiliensi Perbankan</p></div>")
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("RUN ANALYSIS", variant="primary")
130
  out_status = gr.HTML()
131
  gr.Markdown("---")
132
- gr.Markdown("**Interpretasi Metrik:**\n* **Risk Score**: Evaluasi gabungan saldo, cicilan, dan belanja.\n* **Expense Ratio**: Persentase gaji yang terpakai bulan ini.")
133
 
134
  with gr.Column(scale=2):
135
  with gr.Tabs():
136
- with gr.TabItem("Inflow vs Outflow"): plot_1 = gr.Plot()
137
  with gr.TabItem("Tren Pertumbuhan Saldo"): plot_2 = gr.Plot()
138
- out_advice = gr.Markdown(elem_classes="advice-box")
139
 
140
- btn.click(fn=process, inputs=id_in, outputs=[out_status, out_advice, plot_1, plot_2])
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()