BinduRP commited on
Commit
bbc05df
·
verified ·
1 Parent(s): 72783b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -68
app.py CHANGED
@@ -15,88 +15,62 @@ from google import genai
15
  from google.genai import types
16
  from google.api_core import exceptions
17
 
18
- # 1. Access the API Key from Hugging Face Secrets
19
- api_key = os.environ.get('GOOGLE_API_KEY')
 
20
 
21
- # Initialize the Client
22
- # Note: Using v1 for stable API version
23
- client = genai.Client(
24
- api_key=api_key,
25
- http_options=types.HttpOptions(api_version='v1')
26
- )
27
-
28
- # Use gemini-1.5-flash for the best free-tier stability
29
- FREE_STABLE_MODEL = "gemini-1.5-flash"
30
-
31
- # --- Data Preparation (Internal Systems) ---
32
- df_credit = pd.DataFrame({
33
- 'ID': [1111, 2222, 3333, 4444, 5555],
34
- 'Credit_Score': [455, 685, 825, 840, 350]
35
- })
36
 
 
 
37
  df_account = pd.DataFrame({
38
  'ID': [1111, 2222, 3333, 4444, 5555],
39
  'Name': ['Loren', 'Matt', 'Hilda', 'Andy', 'Kit'],
40
  'Status': ['good-standing', 'closed', 'delinquent', 'good-standing', 'delinquent'],
41
  'Nationality': ['Singaporean', 'NonSingaporean', 'Singaporean', 'NonSingaporean', 'Singaporean']
42
  })
43
-
44
  df_gov = pd.DataFrame({'ID': [2222, 4444], 'PR_Status': [True, False]})
45
  df_merged = df_account.merge(df_credit, on="ID").merge(df_gov, on="ID", how="left").fillna(False)
46
 
47
- # --- Upload Policies to Files API ---
48
- # In Spaces, these files must be in the same folder as app.py
49
- risk_policy_file = client.files.upload(file="Bank Loan Overall Risk Policy.pdf")
50
- interest_policy_file = client.files.upload(file="Bank Loan Interest Rate Policy.pdf")
51
-
52
- # --- Assessment Logic ---
53
- def process_loan_request(applicant_id, customer_name_optional, max_retries=3):
54
- for attempt in range(max_retries):
55
- try:
56
- row = df_merged[df_merged['ID'] == int(applicant_id)]
57
- if row.empty: return "Error: Applicant ID not found in system."
58
- applicant = row.iloc[0]
59
-
60
- prompt = f"""
61
- You are a Senior Loan Officer. Assess this application using the provided PDF policies.
62
-
63
- APPLICANT DATA:
64
- Name: {applicant['Name']} (ID: {applicant_id})
65
- Credit Score: {applicant['Credit_Score']}
66
- Account Status: {applicant['Status']}
67
- Nationality: {applicant['Nationality']}
68
- PR Status: {applicant['PR_Status']}
69
-
70
- REQUIRED STEPS:
71
- Step 1. Retrieve Information: State the name, score, status, and nationality.
72
- Step 2. PR Status Check: Mandatory for Non-Singaporeans.
73
- Step 3. Check Overall Risk: Use the 'Bank Loan Overall Risk Policy' table.
74
- Step 4. Check Interest Rate: Use the 'Bank Loan Interest Rate Policy' table.
75
- Step 5. Report: Recommend only if Singaporean OR (Non-Singaporean AND PR Status is True).
76
- """
77
-
78
- response = client.models.generate_content(
79
- model=FREE_STABLE_MODEL,
80
- contents=[risk_policy_file, interest_policy_file, prompt]
81
- )
82
- return response.text
83
-
84
- except exceptions.ResourceExhausted:
85
- wait_time = (2 ** attempt) + 5
86
- time.sleep(wait_time)
87
-
88
- return "Error: System currently at max capacity. Please retry in 1 minute."
89
 
90
  # --- Gradio Interface ---
91
  demo = gr.Interface(
92
- fn=process_loan_request,
93
- inputs=[
94
- gr.Textbox(label="Enter Applicant ID"),
95
- gr.Textbox(label="Enter Customer Name (Optional)")
96
- ],
97
- outputs=gr.Markdown(label="Underwriter Assessment Report"),
98
- title="🏦 Enterprise AI Loan Underwriter",
99
- description="Automated risk assessment via multi-system data integration and PDF policy compliance."
100
  )
101
 
102
  if __name__ == "__main__":
 
15
  from google.genai import types
16
  from google.api_core import exceptions
17
 
18
+ # 1. Initialize Client WITHOUT api_version
19
+ # This specifically fixes the 'INVALID_ARGUMENT' error you received
20
+ client = genai.Client(api_key=os.environ.get("GOOGLE_API_KEY"))
21
 
22
+ # Use the direct model ID
23
+ STABLE_MODEL = "gemini-1.5-flash"
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # --- Data Preparation ---
26
+ df_credit = pd.DataFrame({'ID': [1111, 2222, 3333, 4444, 5555], 'Credit_Score': [455, 685, 825, 840, 350]})
27
  df_account = pd.DataFrame({
28
  'ID': [1111, 2222, 3333, 4444, 5555],
29
  'Name': ['Loren', 'Matt', 'Hilda', 'Andy', 'Kit'],
30
  'Status': ['good-standing', 'closed', 'delinquent', 'good-standing', 'delinquent'],
31
  'Nationality': ['Singaporean', 'NonSingaporean', 'Singaporean', 'NonSingaporean', 'Singaporean']
32
  })
 
33
  df_gov = pd.DataFrame({'ID': [2222, 4444], 'PR_Status': [True, False]})
34
  df_merged = df_account.merge(df_credit, on="ID").merge(df_gov, on="ID", how="left").fillna(False)
35
 
36
+ # --- Upload Policies once on startup ---
37
+ # These files MUST be in the same folder as app.py in Hugging Face
38
+ risk_policy = client.files.upload(file="Bank Loan Overall Risk Policy.pdf")
39
+ rate_policy = client.files.upload(file="Bank Loan Interest Rate Policy.pdf")
40
+
41
+ def process_loan(applicant_id, optional_name):
42
+ try:
43
+ row = df_merged[df_merged['ID'] == int(applicant_id)]
44
+ if row.empty: return "ID not found."
45
+ applicant = row.iloc[0]
46
+
47
+ prompt = f"""
48
+ Assess this loan application using the provided PDF policies:
49
+ Name: {applicant['Name']} (ID: {applicant_id}), Score: {applicant['Credit_Score']}, Status: {applicant['Status']}
50
+ Nationality: {applicant['Nationality']}, PR Status: {applicant['PR_Status']}
51
+
52
+ Follow the multi-step report format:
53
+ 1. Info retrieval 2. PR check 3. Risk Assessment 4. Interest Rate 5. Recommendation
54
+ """
55
+
56
+ # Using direct file objects in the contents list
57
+ response = client.models.generate_content(
58
+ model=STABLE_MODEL,
59
+ contents=[risk_policy, rate_policy, prompt]
60
+ )
61
+ return response.text
62
+
63
+ except exceptions.ResourceExhausted:
64
+ return "Free tier limit reached. Please wait 60 seconds."
65
+ except Exception as e:
66
+ return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  # --- Gradio Interface ---
69
  demo = gr.Interface(
70
+ fn=process_loan,
71
+ inputs=[gr.Textbox(label="Applicant ID"), gr.Textbox(label="Name (Optional)")],
72
+ outputs=gr.Markdown(),
73
+ title="🏦 Enterprise Loan Underwriter"
 
 
 
 
74
  )
75
 
76
  if __name__ == "__main__":