tanhm07 commited on
Commit
8992627
·
verified ·
1 Parent(s): bc25884

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -237
app.py CHANGED
@@ -1,304 +1,124 @@
1
- # ============================================================
2
- # Personal Finance Helper
3
- # ============================================================
4
- # This app:
5
- # 1. Collects some simple financial information from the user
6
- # 2. Calculates a few basic financial indicators using Python
7
- # 3. Sends the information to Gemini
8
- # 4. Displays Gemini's response in a simple web app
9
- # ============================================================
10
-
11
-
12
- # -----------------------------
13
- # 1. Import the libraries we need
14
- # -----------------------------
15
-
16
  import os
17
  import gradio as gr
18
  import spaces
19
  from google import genai
20
 
 
 
 
 
21
 
22
- # -----------------------------
23
- # 2. Connect to Gemini
24
- # -----------------------------
25
- # The API key should NOT be written directly in this file.
26
- #
27
- # Instead, add it in Hugging Face:
28
- #
29
- # Settings -> Secrets
30
- #
31
- # Name the secret:
32
- # GEMINI_API_KEY
33
- #
34
- # Hugging Face will then make it available securely to this app.
35
-
36
- api_key = os.getenv("GEMINI_API_KEY")
37
-
38
- if not api_key:
39
- raise ValueError(
40
- "GEMINI_API_KEY was not found. "
41
- "Please add it under your Hugging Face Space Settings -> Secrets."
42
- )
43
-
44
- client = genai.Client(api_key=api_key)
45
-
46
-
47
- # -----------------------------
48
- # 3. ZeroGPU placeholder
49
- # -----------------------------
50
- # Free Hugging Face accounts may use ZeroGPU.
51
- #
52
- # Hugging Face expects a ZeroGPU Space to contain at least one
53
- # function marked with @spaces.GPU.
54
- #
55
- # Our finance app does NOT actually need a GPU because Gemini
56
- # runs on Google's servers.
57
- #
58
- # This small placeholder function simply allows the Space to start.
59
-
60
  @spaces.GPU(duration=5)
61
  def gpu_placeholder():
62
  return "ready"
63
 
64
 
65
- # -----------------------------
66
- # 4. Main function of the app
67
- # -----------------------------
68
- # This function runs whenever the user presses Submit.
69
- #
70
- # Gradio sends the values from the input boxes into this function.
71
- # The function then returns the AI response back to Gradio.
72
-
73
- def finance_helper(
74
- income,
75
- expenses,
76
- cash,
77
- investments,
78
- debt,
79
- goal
80
- ):
81
 
82
  try:
83
-
84
- # -----------------------------
85
- # Clean up the user's inputs
86
- # -----------------------------
87
- # If a user leaves a number blank, we treat it as zero.
88
-
89
  income = float(income or 0)
90
  expenses = float(expenses or 0)
91
  cash = float(cash or 0)
92
  investments = float(investments or 0)
93
  debt = float(debt or 0)
94
 
95
-
96
- # -----------------------------
97
- # Do some calculations ourselves
98
- # -----------------------------
99
- # We do NOT need an LLM to calculate simple mathematics.
100
- #
101
- # This is an important idea when building AI applications:
102
- #
103
- # Use normal code for things that are predictable.
104
- # Use the LLM for interpretation, reasoning, and communication.
105
-
106
- monthly_surplus = income - expenses
107
-
108
- if income > 0:
109
- savings_rate = monthly_surplus / income * 100
110
- else:
111
- savings_rate = 0
112
-
113
- if expenses > 0:
114
- emergency_fund_months = cash / expenses
115
- else:
116
- emergency_fund_months = 0
117
-
118
-
119
- # -----------------------------
120
- # Create the prompt for Gemini
121
- # -----------------------------
122
- # This is where much of the "intelligence" of the app comes from.
123
- #
124
- # Students can customise this section to create completely
125
- # different applications.
126
 
127
  prompt = f"""
128
  You are a friendly personal finance education assistant.
129
 
130
- Your role is to help the user understand their financial situation
131
- and think about sensible financial priorities.
132
-
133
  Provide general educational guidance only.
 
134
 
135
- Do not recommend specific stocks, securities, investment products,
136
- insurance products, or financial institutions.
137
-
138
- Here is the user's financial information:
139
 
140
  Monthly income: ${income:,.0f}
141
-
142
  Monthly expenses: ${expenses:,.0f}
143
-
144
- Monthly surplus: ${monthly_surplus:,.0f}
145
-
146
  Savings rate: {savings_rate:.1f}%
147
-
148
  Cash savings: ${cash:,.0f}
149
-
150
- Emergency fund:
151
- {emergency_fund_months:.1f} months of current expenses
152
-
153
  Investments: ${investments:,.0f}
154
-
155
  Debt: ${debt:,.0f}
156
 
157
- The user's main financial goal is:
158
-
159
  {goal}
160
 
161
-
162
- Please provide a concise and useful response using the following format:
163
 
164
  ## Financial Snapshot
165
-
166
- Summarise the user's current financial position in simple language.
167
-
168
-
169
  ## What Looks Good
170
-
171
- Identify two positive aspects of the user's financial position.
172
-
173
-
174
  ## Three Priorities
175
-
176
- Recommend three general priorities the user could consider.
177
-
178
-
179
  ## One Thing to Watch
180
-
181
- Identify one potential financial concern or area that deserves attention.
182
-
183
-
184
  ## Questions to Think About
185
 
186
- Provide three useful questions that could help the user think more carefully
187
- about their financial goals.
188
-
189
-
190
- Keep the response practical, easy to understand, and relatively concise.
191
  """
192
 
193
-
194
- # -----------------------------
195
- # 5. Send the prompt to Gemini
196
- # -----------------------------
197
-
198
  response = client.models.generate_content(
199
  model="gemini-3.6-flash",
200
  contents=prompt
201
  )
202
 
203
-
204
- # -----------------------------
205
- # 6. Return Gemini's answer
206
- # -----------------------------
207
- # Whatever we return here will appear in the Gradio output box.
208
-
209
  return response.text
210
 
211
-
212
  except Exception as e:
 
213
 
214
- # -----------------------------
215
- # Show errors in the app
216
- # -----------------------------
217
- # This is useful for learning and debugging.
218
- #
219
- # Instead of the app appearing to do nothing,
220
- # the user will see the actual error message.
221
-
222
- return f"""
223
- ## Something went wrong
224
 
225
- **Error type:** {type(e).__name__}
 
226
 
227
- **Error message:** {str(e)}
228
-
229
- Please check your API key and try again.
230
- """
231
 
 
232
 
233
- # -----------------------------
234
- # 7. Build the user interface
235
- # -----------------------------
236
- # Gradio creates the web page for us.
237
- #
238
- # "inputs" defines what users can enter.
239
- # "outputs" defines where the result will appear.
240
-
241
- demo = gr.Interface(
242
-
243
- fn=finance_helper,
244
-
245
- inputs=[
246
-
247
- gr.Number(
248
- label="Monthly Income",
249
- value=10000
250
- ),
251
-
252
- gr.Number(
253
- label="Monthly Expenses",
254
- value=6000
255
- ),
256
-
257
- gr.Number(
258
- label="Cash Savings",
259
- value=30000
260
- ),
261
-
262
- gr.Number(
263
- label="Investments",
264
- value=50000
265
- ),
266
-
267
- gr.Number(
268
- label="Debt",
269
- value=10000
270
- ),
271
-
272
- gr.Textbox(
273
- label="What is your main financial goal?",
274
- placeholder="For example: Buy a home in five years"
275
- )
276
- ],
277
 
278
- outputs=gr.Markdown(
279
- label="Your AI Financial Review"
280
- ),
281
 
282
- title="💰 Personal Finance Helper",
 
 
 
283
 
284
- description="""
285
- Enter a few details about your finances.
 
 
286
 
287
- The app will calculate some basic financial indicators and use AI
288
- to provide a simple financial health check.
 
 
289
 
290
- This tool is for educational purposes only and is not financial advice.
291
- """
292
- )
293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
- # -----------------------------
296
- # 8. Start the app
297
- # -----------------------------
298
- # Hugging Face automatically publishes the Gradio interface.
299
- #
300
- # We turn off SSR because it can sometimes create unnecessary
301
- # server issues in this simple Space.
302
 
303
  demo.launch(
304
  ssr_mode=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import spaces
4
  from google import genai
5
 
6
+ # Connect to Gemini
7
+ client = genai.Client(
8
+ api_key=os.getenv("GEMINI_API_KEY")
9
+ )
10
 
11
+ # Required for ZeroGPU Spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  @spaces.GPU(duration=5)
13
  def gpu_placeholder():
14
  return "ready"
15
 
16
 
17
+ def finance_helper(income, expenses, cash, investments, debt, goal):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  try:
 
 
 
 
 
 
20
  income = float(income or 0)
21
  expenses = float(expenses or 0)
22
  cash = float(cash or 0)
23
  investments = float(investments or 0)
24
  debt = float(debt or 0)
25
 
26
+ surplus = income - expenses
27
+ savings_rate = surplus / income * 100 if income > 0 else 0
28
+ emergency_months = cash / expenses if expenses > 0 else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  prompt = f"""
31
  You are a friendly personal finance education assistant.
32
 
 
 
 
33
  Provide general educational guidance only.
34
+ Do not recommend specific financial products or investments.
35
 
36
+ Financial information:
 
 
 
37
 
38
  Monthly income: ${income:,.0f}
 
39
  Monthly expenses: ${expenses:,.0f}
40
+ Monthly surplus: ${surplus:,.0f}
 
 
41
  Savings rate: {savings_rate:.1f}%
 
42
  Cash savings: ${cash:,.0f}
43
+ Emergency fund: {emergency_months:.1f} months
 
 
 
44
  Investments: ${investments:,.0f}
 
45
  Debt: ${debt:,.0f}
46
 
47
+ Main financial goal:
 
48
  {goal}
49
 
50
+ Please provide:
 
51
 
52
  ## Financial Snapshot
 
 
 
 
53
  ## What Looks Good
 
 
 
 
54
  ## Three Priorities
 
 
 
 
55
  ## One Thing to Watch
 
 
 
 
56
  ## Questions to Think About
57
 
58
+ Keep the response practical and concise.
 
 
 
 
59
  """
60
 
 
 
 
 
 
61
  response = client.models.generate_content(
62
  model="gemini-3.6-flash",
63
  contents=prompt
64
  )
65
 
 
 
 
 
 
 
66
  return response.text
67
 
 
68
  except Exception as e:
69
+ return f"## Error\n\n{str(e)}"
70
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ # Build the app
73
+ with gr.Blocks(title="Personal Finance Helper") as demo:
74
 
75
+ gr.Markdown(
76
+ """
77
+ # 💰 Personal Finance Helper
 
78
 
79
+ Enter a few details below to receive an AI generated financial health check.
80
 
81
+ *For educational purposes only. This is not financial advice.*
82
+ """
83
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ with gr.Row():
86
+ income = gr.Number(label="Monthly Income")
87
+ expenses = gr.Number(label="Monthly Expenses")
88
 
89
+ with gr.Row():
90
+ cash = gr.Number(label="Cash Savings")
91
+ investments = gr.Number(label="Investments")
92
+ debt = gr.Number(label="Debt")
93
 
94
+ goal = gr.Textbox(
95
+ label="Main Financial Goal",
96
+ placeholder="For example: Buy a home in five years"
97
+ )
98
 
99
+ submit = gr.Button(
100
+ "Analyse My Finances",
101
+ variant="primary"
102
+ )
103
 
104
+ output = gr.Markdown(
105
+ label="AI Financial Review"
106
+ )
107
 
108
+ submit.click(
109
+ fn=finance_helper,
110
+ inputs=[
111
+ income,
112
+ expenses,
113
+ cash,
114
+ investments,
115
+ debt,
116
+ goal
117
+ ],
118
+ outputs=output,
119
+ show_progress="full"
120
+ )
121
 
 
 
 
 
 
 
 
122
 
123
  demo.launch(
124
  ssr_mode=False