Devavrat28 commited on
Commit
8bbf3cf
Β·
verified Β·
1 Parent(s): b7e8018

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -25
app.py CHANGED
@@ -1,48 +1,147 @@
1
  #Gradio app
2
  # app.py
3
  # app.py - Original approach with profile object
 
4
  import gradio as gr
5
  import requests
 
6
 
7
- MODAL_URL = "https://devsam2898--personal-investment-strategist-9-web.modal.run/strategy"
8
 
9
  def get_investment_strategy(age_group, income, expenses, risk_profile, goal, timeframe):
10
- """Get investment strategy from Modal backend"""
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  payload = {
12
  "profile": {
13
  "age_group": age_group,
14
- "income": income,
15
- "expenses": expenses,
16
  "risk_profile": risk_profile,
17
  "goal": goal,
18
  "timeframe": timeframe
19
  }
20
  }
 
21
  try:
22
- response = requests.post(MODAL_URL, json=payload, timeout=60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  if response.status_code == 200:
24
- return response.json().get("strategy", "No strategy returned.")
 
 
25
  else:
26
- return f"❌ Error {response.status_code}: {response.text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  except Exception as e:
28
- return f"❌ Network error: {str(e)}"
 
 
 
 
29
 
30
- demo = gr.Interface(
31
- fn=get_investment_strategy,
32
- inputs=[
33
- gr.Dropdown(["20s", "30s", "40s", "50s+"], label="Age Group", value="30s"),
34
- gr.Textbox(label="Monthly Income ($)", value="6000"),
35
- gr.Textbox(label="Monthly Expenses ($)", value="4000"),
36
- gr.Radio(["Conservative", "Moderate", "Aggressive"], label="Risk Tolerance", value="Moderate"),
37
- gr.Textbox(label="Financial Goal (e.g., buy a house)", value="retirement planning"),
38
- gr.Textbox(label="Timeframe (e.g., 5 years)", value="10 years")
39
- ],
40
- outputs=gr.Markdown(label="Investment Strategy"),
41
- title="πŸ“ˆ Personal Finance Strategist",
42
- description="Powered by LlamaIndex + Nebius Qwen3 | Get personalized strategies based on life stage and goals.",
43
- theme="soft",
44
- allow_flagging="never"
45
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  if __name__ == "__main__":
48
- demo.launch()
 
 
 
 
 
1
  #Gradio app
2
  # app.py
3
  # app.py - Original approach with profile object
4
+ # app.py
5
  import gradio as gr
6
  import requests
7
+ import json
8
 
9
+ MODAL_URL = "https://devsam2898--personal-investment-strategist-10-web.modal.run/strategy"
10
 
11
  def get_investment_strategy(age_group, income, expenses, risk_profile, goal, timeframe):
12
+ """
13
+ Get investment strategy from Modal backend
14
+ """
15
+ # Input validation
16
+ if not all([age_group, income, expenses, risk_profile, goal, timeframe]):
17
+ return "❌ Please fill in all fields to get a personalized strategy."
18
+
19
+ # Convert income and expenses to numbers if they're strings
20
+ try:
21
+ income_val = float(income.replace('$', '').replace(',', '')) if isinstance(income, str) else float(income)
22
+ expenses_val = float(expenses.replace('$', '').replace(',', '')) if isinstance(expenses, str) else float(expenses)
23
+ except ValueError:
24
+ return "❌ Please enter valid numbers for income and expenses."
25
+
26
  payload = {
27
  "profile": {
28
  "age_group": age_group,
29
+ "income": income_val,
30
+ "expenses": expenses_val,
31
  "risk_profile": risk_profile,
32
  "goal": goal,
33
  "timeframe": timeframe
34
  }
35
  }
36
+
37
  try:
38
+ print(f"Sending request to: {MODAL_URL}")
39
+ print(f"Payload: {json.dumps(payload, indent=2)}")
40
+
41
+ response = requests.post(
42
+ MODAL_URL,
43
+ json=payload,
44
+ headers={
45
+ 'Content-Type': 'application/json',
46
+ 'Accept': 'application/json'
47
+ },
48
+ timeout=30 # Add timeout
49
+ )
50
+
51
+ print(f"Response status: {response.status_code}")
52
+ print(f"Response headers: {dict(response.headers)}")
53
+
54
  if response.status_code == 200:
55
+ result = response.json()
56
+ strategy = result.get("strategy", "No strategy returned.")
57
+ return f"## πŸ“Š Your Personalized Investment Strategy\n\n{strategy}"
58
  else:
59
+ error_msg = f"❌ **Error {response.status_code}**\n\n"
60
+ try:
61
+ error_detail = response.json()
62
+ error_msg += f"Details: {error_detail}"
63
+ except:
64
+ error_msg += f"Response: {response.text}"
65
+ return error_msg
66
+
67
+ except requests.exceptions.Timeout:
68
+ return "❌ **Request Timeout**: The service is taking too long to respond. Please try again."
69
+ except requests.exceptions.ConnectionError:
70
+ return "❌ **Connection Error**: Unable to connect to the backend service. Please check if the Modal service is running."
71
+ except requests.exceptions.RequestException as e:
72
+ return f"❌ **Network Error**: {str(e)}"
73
  except Exception as e:
74
+ return f"❌ **Unexpected Error**: {str(e)}"
75
+
76
+ # Test function to verify the function works
77
+ def test_function():
78
+ return "βœ… Function is working correctly!"
79
 
80
+ # Create the interface
81
+ with gr.Blocks(theme="soft", title="πŸ“ˆ Personal Finance Strategist") as interface:
82
+ gr.Markdown(
83
+ """
84
+ # πŸ“ˆ Personal Finance Strategist
85
+ **Powered by LlamaIndex + Nebius Qwen3**
86
+
87
+ Get personalized investment strategies based on your life stage and financial goals.
88
+ """
89
+ )
90
+
91
+ with gr.Row():
92
+ with gr.Column(scale=1):
93
+ age_group = gr.Dropdown(
94
+ choices=["20s", "30s", "40s", "50s+"],
95
+ label="Age Group",
96
+ value="30s"
97
+ )
98
+ income = gr.Textbox(
99
+ label="Monthly Income ($)",
100
+ value="6000",
101
+ placeholder="e.g., 6000"
102
+ )
103
+ expenses = gr.Textbox(
104
+ label="Monthly Expenses ($)",
105
+ value="4000",
106
+ placeholder="e.g., 4000"
107
+ )
108
+
109
+ with gr.Column(scale=1):
110
+ risk_profile = gr.Radio(
111
+ choices=["Conservative", "Moderate", "Aggressive"],
112
+ label="Risk Tolerance",
113
+ value="Moderate"
114
+ )
115
+ goal = gr.Textbox(
116
+ label="Financial Goal",
117
+ placeholder="e.g., buy a house, retirement, emergency fund"
118
+ )
119
+ timeframe = gr.Textbox(
120
+ label="Timeframe",
121
+ placeholder="e.g., 5 years, 10 years"
122
+ )
123
+
124
+ with gr.Row():
125
+ submit_btn = gr.Button("Get Investment Strategy", variant="primary")
126
+ test_btn = gr.Button("Test Connection", variant="secondary")
127
+
128
+ output = gr.Markdown(label="Investment Strategy")
129
+
130
+ # Event handlers
131
+ submit_btn.click(
132
+ fn=get_investment_strategy,
133
+ inputs=[age_group, income, expenses, risk_profile, goal, timeframe],
134
+ outputs=output
135
+ )
136
+
137
+ test_btn.click(
138
+ fn=test_function,
139
+ outputs=output
140
+ )
141
 
142
  if __name__ == "__main__":
143
+ interface.launch(
144
+ server_name="0.0.0.0",
145
+ server_port=7860,
146
+ share=False
147
+ )