Spaces:
Runtime error

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

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +28 -37
app.py CHANGED
@@ -5,9 +5,10 @@ from openai import OpenAI
5
 
6
  # --- Configuration and Utility Functions ---
7
 
8
- # Placeholder for the API Key. In a deployed environment,
9
- # this could be handled by environment variables.
10
  DEFAULT_API_KEY = ""
 
11
 
12
  # Model configuration for the Gemini API via the OpenAI client wrapper
13
  GEMINI_MODEL_NAME = "gemini-2.5-flash"
@@ -29,13 +30,12 @@ GENERIC_FINANCIAL_DATA = {
29
  def submit_feedback(feedback_text):
30
  """
31
  Handles user suggestions/feedback. Prints to the console and provides UI confirmation.
32
- In a real-world app, this would be saved to a database (like Firestore).
33
  """
34
  if feedback_text:
35
  # Print to application logs (simulating saving to a common file/log)
36
  print(f"--- USER FEEDBACK RECEIVED ---\n{feedback_text}\n------------------------------")
37
  gr.Info("Thank you! Your suggestion has been logged.")
38
- return "" # Clear the feedback box
39
 
40
  def generate_portfolio_download(
41
  salary, sip, bills, shopping, dining, entertainment, travel, other_expenses,
@@ -88,33 +88,34 @@ Generated by the AI Personal Finance Agent.
88
 
89
 
90
  def personal_finance_agent(
91
- api_key,
92
  salary, sip, bills, shopping, dining, entertainment, travel, other_expenses,
93
  target_surplus_percentage,
94
  prompt
95
  ):
96
  """
97
  Main function to run the financial analysis and AI response.
 
98
  """
99
 
100
- # 1. API Key Initialization
101
- final_api_key = api_key if api_key else os.environ.get("GEMINI_API_KEY", DEFAULT_API_KEY)
102
 
 
103
  if not final_api_key:
104
- # We only return the inputs for consistency, though they won't change here
105
- return "ERROR: Gemini/OpenAI API Key is missing. Please enter your key in the 'API Key' field above.", "", salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage
106
 
107
  try:
108
- # Initialize the client using the Gemini base URL
109
  client = OpenAI(
110
  base_url=GEMINI_API_BASE_URL,
111
  api_key=final_api_key,
112
- timeout=60.0 # Set a reasonable timeout
113
  )
114
  except Exception as e:
115
- return f"ERROR: Could not initialize API client. Check your key. Detail: {e}", "", salary, sip, bills, shopping, dining, entertainment, travel, other_expenses, target_surplus_percentage
116
 
117
- # 2. Calculations
118
  total_income = salary
119
  total_fixed_expenses = sip + bills
120
  total_discretionary_expenses = shopping + dining + entertainment + travel + other_expenses
@@ -124,7 +125,7 @@ def personal_finance_agent(
124
 
125
  status = "Surplus" if net_cashflow > 0 else "Deficit"
126
 
127
- # 3. Dynamic System Prompt Generation
128
  system_prompt = f"""
129
  You are a world-class, empathetic personal financial analyst and coach.
130
  Your role is to analyze the user's monthly financial data and provide actionable, encouraging advice.
@@ -147,7 +148,7 @@ def personal_finance_agent(
147
  4. Focus heavily on optimizing discretionary spending areas: Shopping, Dining, Entertainment, Travel, and Other.
148
  """
149
 
150
- # 4. User Query
151
  user_query = f"""
152
  My current discretionary spending breakdown is:
153
  - Shopping: ₹{shopping:,.0f}
@@ -176,8 +177,6 @@ def personal_finance_agent(
176
  ai_response = f"An API error occurred: {e}"
177
 
178
  # 6. Format Output and Return
179
-
180
- # Detailed financial summary to display on the UI
181
  summary_html = f"""
182
  <div style='padding: 15px; border-radius: 8px; background-color: #f7f9fb; border-left: 5px solid #007bff;'>
183
  <h4 style='margin-top: 0; color: #007bff;'>Current Financial Snapshot</h4>
@@ -201,6 +200,9 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
201
  """
202
  Enter your monthly financial data to get personalized budgeting advice
203
  from a Gemini-powered financial analyst.
 
 
 
204
  """
205
  )
206
 
@@ -208,19 +210,9 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
208
  last_ai_response = gr.State("")
209
 
210
  with gr.Row():
211
- # Configuration Column (API Key & Feedback)
212
  with gr.Column(scale=1):
213
- gr.Markdown("## ⚙️ Configuration")
214
-
215
- # API Key Input
216
- api_key_input = gr.Textbox(
217
- label="Gemini/OpenAI API Key (Required)",
218
- type="password",
219
- value="",
220
- placeholder="Enter your API Key here...",
221
- interactive=True
222
- )
223
- gr.Markdown("<small>_Your key is not stored and is only used for this session._</small>")
224
 
225
  # Download Button
226
  download_btn = gr.DownloadButton(
@@ -239,6 +231,7 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
239
  )
240
  feedback_button = gr.Button("Submit Feedback")
241
 
 
242
  feedback_button.click(
243
  fn=submit_feedback,
244
  inputs=[feedback_input],
@@ -365,14 +358,14 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
365
 
366
  # --- Event Handlers ---
367
 
368
- # List of all input components for the main function
369
  inputs = [
370
- api_key_input, salary_input, sip_input, bills_input, shopping_input, dining_input,
371
  entertainment_input, travel_input, other_expenses_input, target_surplus_input,
372
  prompt_input
373
  ]
374
 
375
- # List of output components (we return updated input values for consistency)
376
  outputs = [
377
  financial_summary_output, ai_response_output,
378
  salary_input, sip_input, bills_input, shopping_input, dining_input,
@@ -387,15 +380,13 @@ with gr.Blocks(title="AI Personal Finance Coach") as demo:
387
  queue=False,
388
  ).then(
389
  # Second chain: Update the state and download button content after analysis
390
- # The lambda retrieves the AI response (args[-1]) and the 9 numeric inputs (args[1:10])
391
- fn=lambda *args: (args[-1], generate_portfolio_download(*args[1:10], args[-1])),
392
  inputs=[
393
- api_key_input, salary_input, sip_input, bills_input, shopping_input, dining_input,
394
  entertainment_input, travel_input, other_expenses_input, target_surplus_input,
395
  ai_response_output # This component's value is passed as the last argument
396
  ],
397
  outputs=[last_ai_response, download_btn],
398
  queue=False,
399
  )
400
-
401
- # demo.launch() # Uncomment this line if running locally
 
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"
 
30
  def submit_feedback(feedback_text):
31
  """
32
  Handles user suggestions/feedback. Prints to the console and provides UI confirmation.
 
33
  """
34
  if feedback_text:
35
  # Print to application logs (simulating saving to a common file/log)
36
  print(f"--- USER FEEDBACK RECEIVED ---\n{feedback_text}\n------------------------------")
37
  gr.Info("Thank you! Your suggestion has been logged.")
38
+ return "" # Clear the input box
39
 
40
  def generate_portfolio_download(
41
  salary, sip, bills, shopping, dining, entertainment, travel, other_expenses,
 
88
 
89
 
90
  def personal_finance_agent(
 
91
  salary, sip, bills, shopping, dining, entertainment, travel, other_expenses,
92
  target_surplus_percentage,
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
 
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.
 
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}
 
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>
 
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
 
 
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(
 
231
  )
232
  feedback_button = gr.Button("Submit Feedback")
233
 
234
+ # Feedback action
235
  feedback_button.click(
236
  fn=submit_feedback,
237
  inputs=[feedback_input],
 
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,
 
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
  )