File size: 5,003 Bytes
12cb1c8 bbc05df 12cb1c8 066e970 a9abf76 c9f040a 12cb1c8 303f724 bbc05df 12cb1c8 238f745 303f724 12cb1c8 303f724 bbc05df 32ae303 bbc05df 32ae303 bbc05df 32ae303 bbc05df 32ae303 bbc05df 32ae303 f0cecd4 32ae303 f0cecd4 32ae303 bbc05df 32ae303 bbc05df c9f040a 32ae303 bbc05df 32ae303 bbc05df 32ae303 12cb1c8 303f724 12cb1c8 303f724 bbc05df 39d8ecd 12cb1c8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
# -*- coding: utf-8 -*-
"""AI Loan Officer Assistant.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1Om043ogOg3FZB4mkhCZY2gcOapGFM-5q
"""
import os
import time
import pandas as pd
import gradio as gr
from google import genai
from google.genai import types
from google.api_core import exceptions
# 1. Initialize Client WITHOUT api_version
# This specifically fixes the 'INVALID_ARGUMENT' error you received
# Initialize the client with explicit API version 'v1'
import os
import time
import pandas as pd
import gradio as gr
from google import genai
from google.genai import types
from google.api_core import exceptions
# SECURE FIX: Use os.environ for Hugging Face Spaces
# The SDK will automatically use 'GOOGLE_API_KEY' if it exists in environment
client = genai.Client(api_key=os.environ.get('GOOGLE_API_KEY'))
# Use gemini-1.5-flash for the best free-tier stability
STABLE_MODEL = "gemini-flash-latest"
# 2. Data Preparation (Structured Systems)
df_credit = pd.DataFrame({'ID': [1111, 2222, 3333, 4444, 5555], 'Credit_Score': [455, 685, 825, 840, 350]})
df_account = pd.DataFrame({
'ID': [1111, 2222, 3333, 4444, 5555],
'Name': ['Loren', 'Matt', 'Hilda', 'Andy', 'Kit'],
'Email': ['loren@gmail.com', 'matt@yahoo.com', 'halida@gmail.com', 'andy@gmail.com', 'kit@yahho.com'],
'Status': ['Good-standing', 'Closed', 'Delinquent', 'Good-standing', 'Delinquent'],
'Nationality': ['Singaporean', 'NonSingaporean', 'Singaporean', 'NonSingaporean', 'Singaporean']
})
df_gov = pd.DataFrame({'ID': [2222, 4444], 'PR_Status': [True, False]})
df_merged = df_account.merge(df_credit, on="ID").merge(df_gov, on="ID", how="left").fillna(False)
# 3. Upload Policy Files once on startup
risk_policy_file = client.files.upload(file="Bank Loan Overall Risk Policy.pdf")
interest_policy_file = client.files.upload(file="Bank Loan Interest Rate Policy.pdf")
# 4. Standardized Assessment Logic
def process_loan_request(applicant_id, customer_name_optional):
try:
# Retrieve data from the structured systems
row = df_merged[df_merged['ID'] == int(applicant_id)]
if row.empty: return "Error: Applicant ID not found."
applicant = row.iloc[0]
# THE STANDARDIZED PROMPT: Ensuring strict adherence to provided tables
prompt = f"""
You are a Senior Loan Officer. Assess the application for the individual provided.
Stick strictly to the information and tables provided in the attached PDF policies.
APPLICANT DATA:
Name: {applicant['Name']}
ID: {applicant_id}
Email: {applicant['Email']}
Credit Score: {applicant['Credit_Score']}
Account Status: {applicant['Status']}
Nationality: {applicant['Nationality']}
PR Status: {applicant['PR_Status']}
REQUIRED OUTPUT PATTERN:
# Loan Assessment Report: {applicant['Name']} (ID: {applicant_id}, Email: {applicant['Email']})
### **1. Info Retrieval**
| Applicant Detail | Value |
| :--- | :--- |
| Name (ID) | {applicant['Name']} ({applicant_id}) |
| Credit Score | {applicant['Credit_Score']} |
| Account Status | {applicant['Status']} |
| Nationality | {applicant['Nationality']} |
| PR Status | {applicant['PR_Status']} |
### **2. PR Status Check**
- For Non-Singaporean applicants: State result as "PR Status -> [True/False]".
- For Singaporean applicants: State "Check not required for Singaporean".
### **3. Overall Risk Assessment**
- Reference 'Bank Loan Overall Risk Policy.pdf'.
- Calculation: Credit Score [{applicant['Credit_Score']}] + Account Status [{applicant['Status']}] -> Overall Risk: [Value from Table]
### **4. Interest Rate Determination**
- Reference 'Bank Loan Interest Rate Policy.pdf'.
- Calculation: Overall Risk [Value from Table] -> [Rate from Table]
- Apply conservative rule if risk falls between categories.
### **5. Final Report & Recommendation**
- Recommend the loan interest rate OR Not recommend.
- Rationale: Based on risk profile and compliance (PR false for Non-Singaporean leads to 'Not recommend').
"""
# Generate content using the multimodal input
response = client.models.generate_content(
model=STABLE_MODEL,
contents=[risk_policy_file, interest_policy_file, prompt]
)
return response.text
except exceptions.ResourceExhausted:
return "Error: Quota reached. Please wait 60 seconds."
except Exception as e:
return f"System Error: {str(e)}"
# 5. Launch Gradio Interface
demo = gr.Interface(
fn=process_loan_request,
inputs=[gr.Textbox(label="Applicant ID"), gr.Textbox(label="Name (Optional)")],
outputs=gr.Markdown(),
title="🏦 Enterprise AI Loan Risk Assessment Tool"
)
if __name__ == "__main__":
demo.launch() |