chatbotdeveloper2025genai commited on
Commit
b19aaae
·
verified ·
1 Parent(s): 6ade485

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +90 -185
app.py CHANGED
@@ -1,16 +1,14 @@
1
  import gradio as gr
2
  import os
3
- import re
4
  from openai import OpenAI
5
 
6
  # --- Configuration and Utility Functions ---
7
 
8
- # Placeholder. In a deployment environment (e.g., Hugging Face),
9
- # the API key MUST be provided via an environment variable (e.g., GEMINI_API_KEY).
10
  DEFAULT_API_KEY = ""
11
  GEMINI_API_KEY_ENV_VAR = os.environ.get("GEMINI_API_KEY", DEFAULT_API_KEY)
12
 
13
- # Model configuration for the Gemini API via the OpenAI client wrapper
14
  GEMINI_MODEL_NAME = "gemini-2.5-flash"
15
  GEMINI_API_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
16
 
@@ -71,12 +69,9 @@ def generate_portfolio_download(
71
 
72
  ## 2. Calculated Summary
73
  - **Total Income:** ₹{total_income:,.0f}
74
- - **Total Fixed Expenses:** ₹{total_fixed_expenses:,.0f}
75
- - **Total Discretionary Expenses:** ₹{total_discretionary_expenses:,.0f}
76
  - **Total Expenses:** ₹{total_expenses:,.0f}
77
  - **Net Cashflow (Target Surplus):** ₹{net_cashflow:,.0f}
78
  - **Target Surplus Amount:** ₹{target_surplus_amount:,.0f}
79
- - **Status:** {'Surplus' if net_cashflow > 0 else 'Deficit'}
80
 
81
  ## 3. AI Financial Coach Analysis
82
  {ai_response}
@@ -93,95 +88,79 @@ def personal_finance_agent(
93
  prompt
94
  ):
95
  """
96
- Main function to run the financial analysis and AI response.
97
- Relies on API key being set in environment variables (GEMINI_API_KEY_ENV_VAR).
98
  """
99
 
100
- # 1. API Key Initialization (using environment variable only)
101
  final_api_key = GEMINI_API_KEY_ENV_VAR
102
-
103
- # We now check if the environment variable was successfully loaded
104
  if not final_api_key:
105
- error_msg = "ERROR: Gemini/OpenAI API Key is missing. Please ensure the 'GEMINI_API_KEY' environment variable is set."
106
- return error_msg, "", salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage
107
-
108
- try:
109
- # Initialize the client using the Gemini base URL and the environment key
110
- client = OpenAI(
111
- base_url=GEMINI_API_BASE_URL,
112
- api_key=final_api_key,
113
- timeout=60.0
114
- )
115
- except Exception as e:
116
- return f"ERROR: Could not initialize API client. Detail: {e}", "", salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage
 
 
 
 
 
 
 
 
117
 
118
- # 2. Calculations (same as before)
119
- total_income = salary
120
- total_fixed_expenses = sip + bills
121
- total_discretionary_expenses = shopping + dining + entertainment + travel + other_expenses
122
- total_expenses = total_fixed_expenses + total_discretionary_expenses
123
- net_cashflow = total_income - total_expenses
124
- target_surplus_amount = (target_surplus_percentage / 100) * total_income
 
 
 
125
 
126
- status = "Surplus" if net_cashflow > 0 else "Deficit"
 
 
 
 
 
127
 
128
- # 3. Dynamic System Prompt Generation (same as before)
129
- system_prompt = f"""
130
- You are a world-class, empathetic personal financial analyst and coach.
131
- Your role is to analyze the user's monthly financial data and provide actionable, encouraging advice.
132
-
133
- The user's current monthly financial summary is:
134
- - Gross Monthly Salary (Income): ₹{total_income:,.0f}
135
- - Mandatory SIP/Investment: ₹{sip:,.0f}
136
- - Bills/EMIs/Rent: ₹{bills:,.0f}
137
- - Total Fixed Expenses (SIP + Bills): ₹{total_fixed_expenses:,.0f}
138
- - Total Discretionary Expenses (Shopping, Dining, etc.): ₹{total_discretionary_expenses:,.0f}
139
- - Total Expenses: ₹{total_expenses:,.0f}
140
- - **Net Cashflow (Available Surplus/Deficit)**: ₹{net_cashflow:,.0f}
141
- - **Target Monthly Savings Goal ({target_surplus_percentage}%)**: ₹{target_surplus_amount:,.0f}
142
- - **Current Status**: {status}
143
-
144
- Based on the detailed discretionary spending below, provide:
145
- 1. A brief summary of their current financial health (e.g., Are they meeting their goal?).
146
- 2. Specific, positive, and practical recommendations (e.g., "Reduce dining by ₹X to achieve your target.").
147
- 3. Use Indian Rupee (₹) formatting and address the user directly.
148
- 4. Focus heavily on optimizing discretionary spending areas: Shopping, Dining, Entertainment, Travel, and Other.
149
- """
150
-
151
- # 4. User Query (same as before)
152
- user_query = f"""
153
- My current discretionary spending breakdown is:
154
- - Shopping: ₹{shopping:,.0f}
155
- - Dining & Food Delivery: ₹{dining:,.0f}
156
- - Entertainment/Subscriptions: ₹{entertainment:,.0f}
157
- - Travel/Fuel: ₹{travel:,.0f}
158
- - Other Expenses: ₹{other_expenses:,.0f}
159
 
160
- Please provide your analysis and coaching based on the system prompt and this prompt.
161
- User prompt/request: "{prompt}"
162
- """
163
-
164
- try:
165
- # 5. API Call
166
- response = client.chat.completions.create(
167
- model=GEMINI_MODEL_NAME,
168
- messages=[
169
- {"role": "system", "content": system_prompt},
170
- {"role": "user", "content": user_query}
171
- ],
172
- temperature=0.7,
173
- )
174
- ai_response = response.choices[0].message.content
175
-
176
- except Exception as e:
177
- ai_response = f"An API error occurred: {e}"
178
 
179
- # 6. Format Output and Return
180
  summary_html = f"""
181
  <div style='padding: 15px; border-radius: 8px; background-color: #f7f9fb; border-left: 5px solid #007bff;'>
182
  <h4 style='margin-top: 0; color: #007bff;'>Current Financial Snapshot</h4>
183
  <p><strong>Total Income:</strong> ₹{total_income:,.0f}</p>
184
- <p><strong>Total Expenses:</strong> ₹{total_expenses:,.0f} (Fixed: ₹{total_fixed_expenses:,.0f} | Discretionary: ₹{total_discretionary_expenses:,.0f})</p>
185
  <p><strong>Target Savings Goal ({target_surplus_percentage}%):</strong> ₹{target_surplus_amount:,.0f}</p>
186
  <p style='font-size: 1.2em; font-weight: bold; color: {'#28a745' if net_cashflow >= target_surplus_amount else '#dc3545'};'>
187
  Net Cashflow (Surplus/Deficit): ₹{net_cashflow:,.0f}
@@ -189,7 +168,14 @@ def personal_finance_agent(
189
  </div>
190
  """
191
 
192
- return summary_html, ai_response, salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage
 
 
 
 
 
 
 
193
 
194
 
195
  # --- Gradio UI Definition ---
@@ -200,21 +186,15 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
200
  """
201
  Enter your monthly financial data to get personalized budgeting advice
202
  from a Gemini-powered financial analyst.
203
-
204
- **Note:** The application expects the Gemini/OpenAI API key to be provided via a
205
- `GEMINI_API_KEY` environment variable in the deployment environment.
206
  """
207
  )
208
 
209
- # State variable to store the last AI response for the download button
210
- last_ai_response = gr.State("")
211
-
212
  with gr.Row():
213
  # Configuration Column (Download & Feedback)
214
  with gr.Column(scale=1):
215
  gr.Markdown("## ⚙️ Tools")
216
 
217
- # Download Button
218
  download_btn = gr.DownloadButton(
219
  label="Download Portfolio Report (.txt)",
220
  scale=0
@@ -235,94 +215,30 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
235
  feedback_button.click(
236
  fn=submit_feedback,
237
  inputs=[feedback_input],
238
- outputs=[feedback_input] # Clears the input box on submission
239
  )
240
 
241
  # Financial Inputs Column
242
  with gr.Column(scale=2):
243
  gr.Markdown("## 💸 Your Monthly Finances (in ₹)")
244
 
245
- # --- Income and Fixed Expenses ---
246
- with gr.Row():
247
- salary_input = gr.Slider(
248
- label="1. Gross Monthly Salary (Income)",
249
- minimum=10000,
250
- maximum=500000,
251
- value=GENERIC_FINANCIAL_DATA["salary"],
252
- step=1000,
253
- interactive=True
254
- )
255
-
256
  with gr.Row():
257
- sip_input = gr.Slider(
258
- label="2. Mandatory SIP/Investment",
259
- minimum=0,
260
- maximum=100000,
261
- value=GENERIC_FINANCIAL_DATA["sip"],
262
- step=500,
263
- interactive=True
264
- )
265
-
266
- bills_input = gr.Slider(
267
- label="3. Bills/EMIs/Rent",
268
- minimum=0,
269
- maximum=200000,
270
- value=GENERIC_FINANCIAL_DATA["bills"],
271
- step=500,
272
- interactive=True
273
- )
274
-
275
- gr.Markdown("### Discretionary Expenses")
276
 
277
- # --- Discretionary Expenses ---
278
  with gr.Row():
279
- shopping_input = gr.Slider(
280
- label="4. Shopping",
281
- minimum=0,
282
- maximum=50000,
283
- value=GENERIC_FINANCIAL_DATA["shopping"],
284
- step=100,
285
- interactive=True
286
- )
287
-
288
- dining_input = gr.Slider(
289
- label="5. Dining & Food Delivery",
290
- minimum=0,
291
- maximum=50000,
292
- value=GENERIC_FINANCIAL_DATA["dining"],
293
- step=100,
294
- interactive=True
295
- )
296
 
297
  with gr.Row():
298
- entertainment_input = gr.Slider(
299
- label="6. Entertainment/Subscriptions",
300
- minimum=0,
301
- maximum=20000,
302
- value=GENERIC_FINANCIAL_DATA["entertainment"],
303
- step=50,
304
- interactive=True
305
- )
306
-
307
- travel_input = gr.Slider(
308
- label="7. Travel/Fuel",
309
- minimum=0,
310
- maximum=50000,
311
- value=GENERIC_FINANCIAL_DATA["travel"],
312
- step=100,
313
- interactive=True
314
- )
315
-
316
- other_expenses_input = gr.Slider(
317
- label="8. Other Expenses",
318
- minimum=0,
319
- maximum=30000,
320
- value=GENERIC_FINANCIAL_DATA["other_expenses"],
321
- step=100,
322
- interactive=True
323
- )
324
 
325
- # --- Savings Goal ---
326
  target_surplus_input = gr.Slider(
327
  label="9. Target Savings Percentage (%)",
328
  minimum=0,
@@ -356,37 +272,26 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
356
  value="The AI's personalized advice will appear here."
357
  )
358
 
359
- # --- Event Handlers ---
360
 
361
- # List of all input components (API key is removed)
362
  inputs = [
363
  salary_input, sip_input, bills_input, shopping_input, dining_input,
364
  entertainment_input, travel_input, other_expenses_input, target_surplus_input,
365
  prompt_input
366
  ]
367
 
368
- # List of output components
369
  outputs = [
370
- financial_summary_output, ai_response_output,
371
- salary_input, sip_input, bills_input, shopping_input, dining_input,
372
- entertainment_input, travel_input, other_expenses_input, target_surplus_input
373
  ]
374
 
375
- # The main analysis flow
376
  run_button.click(
377
  fn=personal_finance_agent,
378
  inputs=inputs,
379
  outputs=outputs,
380
  queue=False,
381
- ).then(
382
- # Second chain: Update the state and download button content after analysis
383
- # The lambda retrieves the AI response (args[-1]) and the 9 numeric inputs (args[0:9])
384
- fn=lambda *args: (args[-1], generate_portfolio_download(*args[0:9], args[-1])),
385
- inputs=[
386
- salary_input, sip_input, bills_input, shopping_input, dining_input,
387
- entertainment_input, travel_input, other_expenses_input, target_surplus_input,
388
- ai_response_output # This component's value is passed as the last argument
389
- ],
390
- outputs=[last_ai_response, download_btn],
391
- queue=False,
392
  )
 
1
  import gradio as gr
2
  import os
 
3
  from openai import OpenAI
4
 
5
  # --- Configuration and Utility Functions ---
6
 
7
+ # Placeholder. API key MUST be provided via an environment variable (e.g., GEMINI_API_KEY).
 
8
  DEFAULT_API_KEY = ""
9
  GEMINI_API_KEY_ENV_VAR = os.environ.get("GEMINI_API_KEY", DEFAULT_API_KEY)
10
 
11
+ # Model configuration
12
  GEMINI_MODEL_NAME = "gemini-2.5-flash"
13
  GEMINI_API_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
14
 
 
69
 
70
  ## 2. Calculated Summary
71
  - **Total Income:** ₹{total_income:,.0f}
 
 
72
  - **Total Expenses:** ₹{total_expenses:,.0f}
73
  - **Net Cashflow (Target Surplus):** ₹{net_cashflow:,.0f}
74
  - **Target Surplus Amount:** ₹{target_surplus_amount:,.0f}
 
75
 
76
  ## 3. AI Financial Coach Analysis
77
  {ai_response}
 
88
  prompt
89
  ):
90
  """
91
+ Main function to run the financial analysis, API call, and generate all outputs.
 
92
  """
93
 
94
+ # 1. API Key Check
95
  final_api_key = GEMINI_API_KEY_ENV_VAR
96
+ ai_response = "The AI's personalized advice will appear here."
97
+
98
  if not final_api_key:
99
+ ai_response = "ERROR: Gemini/OpenAI API Key is missing. Please ensure the 'GEMINI_API_KEY' environment variable is set."
100
+ else:
101
+ # 2. API Client Initialization
102
+ try:
103
+ client = OpenAI(
104
+ base_url=GEMINI_API_BASE_URL,
105
+ api_key=final_api_key,
106
+ timeout=60.0
107
+ )
108
+ except Exception as e:
109
+ ai_response = f"ERROR: Could not initialize API client. Detail: {e}"
110
+ else:
111
+ # 3. Calculations
112
+ total_income = salary
113
+ total_fixed_expenses = sip + bills
114
+ total_discretionary_expenses = shopping + dining + entertainment + travel + other_expenses
115
+ total_expenses = total_fixed_expenses + total_discretionary_expenses
116
+ net_cashflow = total_income - total_expenses
117
+ target_surplus_amount = (target_surplus_percentage / 100) * total_income
118
+ status = "Surplus" if net_cashflow > 0 else "Deficit"
119
 
120
+ # 4. Dynamic System Prompt Generation
121
+ system_prompt = f"""
122
+ You are a world-class, empathetic personal financial analyst and coach.
123
+ The user's current monthly financial summary: Income: ₹{total_income:,.0f},
124
+ Total Expenses: ₹{total_expenses:,.0f}, Net Cashflow: ₹{net_cashflow:,.0f},
125
+ Target Savings: ₹{target_surplus_amount:,.0f}.
126
+ Provide a summary, then give specific, positive, and practical recommendations
127
+ to help them achieve their savings goal. Focus on optimizing discretionary spending
128
+ (Shopping, Dining, Entertainment, Travel, Other). Use Indian Rupee (₹) formatting.
129
+ """
130
 
131
+ # 5. User Query
132
+ user_query = f"""
133
+ Discretionary spending: Shopping: ₹{shopping:,.0f}, Dining: ₹{dining:,.0f},
134
+ Entertainment: ₹{entertainment:,.0f}, Travel: ₹{travel:,.0f}, Other: ₹{other_expenses:,.0f}.
135
+ User prompt: "{prompt}"
136
+ """
137
 
138
+ try:
139
+ # 6. API Call
140
+ response = client.chat.completions.create(
141
+ model=GEMINI_MODEL_NAME,
142
+ messages=[
143
+ {"role": "system", "content": system_prompt},
144
+ {"role": "user", "content": user_query}
145
+ ],
146
+ temperature=0.7,
147
+ )
148
+ ai_response = response.choices[0].message.content
149
+
150
+ except Exception as e:
151
+ ai_response = f"An API error occurred during content generation: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
+ # 7. Format Output (HTML Summary)
154
+ total_income = salary # Recalculate if we skipped the main logic path
155
+ total_expenses = sip + bills + shopping + dining + entertainment + travel + other_expenses
156
+ net_cashflow = total_income - total_expenses
157
+ target_surplus_amount = (target_surplus_percentage / 100) * total_income
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
 
159
  summary_html = f"""
160
  <div style='padding: 15px; border-radius: 8px; background-color: #f7f9fb; border-left: 5px solid #007bff;'>
161
  <h4 style='margin-top: 0; color: #007bff;'>Current Financial Snapshot</h4>
162
  <p><strong>Total Income:</strong> ₹{total_income:,.0f}</p>
163
+ <p><strong>Total Expenses:</strong> ₹{total_expenses:,.0f}</p>
164
  <p><strong>Target Savings Goal ({target_surplus_percentage}%):</strong> ₹{target_surplus_amount:,.0f}</p>
165
  <p style='font-size: 1.2em; font-weight: bold; color: {'#28a745' if net_cashflow >= target_surplus_amount else '#dc3545'};'>
166
  Net Cashflow (Surplus/Deficit): ₹{net_cashflow:,.0f}
 
168
  </div>
169
  """
170
 
171
+ # 8. Generate Download Content
172
+ download_content = generate_portfolio_download(
173
+ salary, sip, bills, shopping, dining, entertainment, travel, other_expenses,
174
+ target_surplus_percentage, ai_response
175
+ )
176
+
177
+ # Return the three outputs required by the single Gradio click
178
+ return summary_html, ai_response, download_content
179
 
180
 
181
  # --- Gradio UI Definition ---
 
186
  """
187
  Enter your monthly financial data to get personalized budgeting advice
188
  from a Gemini-powered financial analyst.
 
 
 
189
  """
190
  )
191
 
 
 
 
192
  with gr.Row():
193
  # Configuration Column (Download & Feedback)
194
  with gr.Column(scale=1):
195
  gr.Markdown("## ⚙️ Tools")
196
 
197
+ # Download Button - now an output, content generated by the main function
198
  download_btn = gr.DownloadButton(
199
  label="Download Portfolio Report (.txt)",
200
  scale=0
 
215
  feedback_button.click(
216
  fn=submit_feedback,
217
  inputs=[feedback_input],
218
+ outputs=[feedback_input]
219
  )
220
 
221
  # Financial Inputs Column
222
  with gr.Column(scale=2):
223
  gr.Markdown("## 💸 Your Monthly Finances (in ₹)")
224
 
225
+ # Input Sliders (simplified layout)
 
 
 
 
 
 
 
 
 
 
226
  with gr.Row():
227
+ salary_input = gr.Slider(label="1. Gross Monthly Salary (Income)", minimum=10000, maximum=500000, value=GENERIC_FINANCIAL_DATA["salary"], step=1000, interactive=True)
228
+ sip_input = gr.Slider(label="2. Mandatory SIP/Investment", minimum=0, maximum=100000, value=GENERIC_FINANCIAL_DATA["sip"], step=500, interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
 
230
  with gr.Row():
231
+ bills_input = gr.Slider(label="3. Bills/EMIs/Rent", minimum=0, maximum=200000, value=GENERIC_FINANCIAL_DATA["bills"], step=500, interactive=True)
232
+ shopping_input = gr.Slider(label="4. Shopping", minimum=0, maximum=50000, value=GENERIC_FINANCIAL_DATA["shopping"], step=100, interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
  with gr.Row():
235
+ dining_input = gr.Slider(label="5. Dining & Food Delivery", minimum=0, maximum=50000, value=GENERIC_FINANCIAL_DATA["dining"], step=100, interactive=True)
236
+ entertainment_input = gr.Slider(label="6. Entertainment/Subscriptions", minimum=0, maximum=20000, value=GENERIC_FINANCIAL_DATA["entertainment"], step=50, interactive=True)
237
+
238
+ with gr.Row():
239
+ travel_input = gr.Slider(label="7. Travel/Fuel", minimum=0, maximum=50000, value=GENERIC_FINANCIAL_DATA["travel"], step=100, interactive=True)
240
+ other_expenses_input = gr.Slider(label="8. Other Expenses", minimum=0, maximum=30000, value=GENERIC_FINANCIAL_DATA["other_expenses"], step=100, interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
 
 
242
  target_surplus_input = gr.Slider(
243
  label="9. Target Savings Percentage (%)",
244
  minimum=0,
 
272
  value="The AI's personalized advice will appear here."
273
  )
274
 
275
+ # --- Event Handlers (Simplified to a single .click) ---
276
 
277
+ # List of all input components
278
  inputs = [
279
  salary_input, sip_input, bills_input, shopping_input, dining_input,
280
  entertainment_input, travel_input, other_expenses_input, target_surplus_input,
281
  prompt_input
282
  ]
283
 
284
+ # List of output components (HTML, Markdown, Download Content)
285
  outputs = [
286
+ financial_summary_output,
287
+ ai_response_output,
288
+ download_btn
289
  ]
290
 
291
+ # The main analysis flow: one click, one function, three distinct outputs
292
  run_button.click(
293
  fn=personal_finance_agent,
294
  inputs=inputs,
295
  outputs=outputs,
296
  queue=False,
 
 
 
 
 
 
 
 
 
 
 
297
  )