Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
|
| 2 |
-
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import json
|
| 5 |
import plotly.graph_objects as go
|
|
@@ -520,4 +520,583 @@ if __name__ == "__main__":
|
|
| 520 |
server_name="0.0.0.0",
|
| 521 |
server_port=7860,
|
| 522 |
share=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
)
|
|
|
|
| 1 |
|
| 2 |
+
'''import gradio as gr
|
| 3 |
import requests
|
| 4 |
import json
|
| 5 |
import plotly.graph_objects as go
|
|
|
|
| 520 |
server_name="0.0.0.0",
|
| 521 |
server_port=7860,
|
| 522 |
share=True
|
| 523 |
+
)'''
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
import gradio as gr
|
| 527 |
+
import requests
|
| 528 |
+
import json
|
| 529 |
+
import plotly.graph_objects as go
|
| 530 |
+
import plotly.express as px
|
| 531 |
+
from fastapi import FastAPI
|
| 532 |
+
from typing import Dict, Any, Optional
|
| 533 |
+
import os
|
| 534 |
+
from datetime import datetime
|
| 535 |
+
from utils import (
|
| 536 |
+
validate_salary, validate_expenses, calculate_50_30_20_breakdown,
|
| 537 |
+
calculate_emergency_fund_target, calculate_sip_returns, get_tax_saving_instruments,
|
| 538 |
+
get_investment_allocation_by_age, calculate_goal_based_savings, get_expense_optimization_tips,
|
| 539 |
+
format_currency, get_financial_milestones_by_age, calculate_retirement_corpus
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
# Custom CSS for MoneyMate branding
|
| 543 |
+
CUSTOM_CSS = """
|
| 544 |
+
.gradio-container {
|
| 545 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 546 |
+
font-family: 'Inter', sans-serif;
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
.main-header {
|
| 550 |
+
text-align: center;
|
| 551 |
+
color: white;
|
| 552 |
+
margin-bottom: 2rem;
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
.money-card {
|
| 556 |
+
background: rgba(255, 255, 255, 0.95);
|
| 557 |
+
border-radius: 15px;
|
| 558 |
+
padding: 1.5rem;
|
| 559 |
+
margin: 1rem 0;
|
| 560 |
+
box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
|
| 561 |
+
backdrop-filter: blur(4px);
|
| 562 |
+
border: 1px solid rgba(255, 255, 255, 0.18);
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
.modal-branding {
|
| 566 |
+
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
|
| 567 |
+
-webkit-background-clip: text;
|
| 568 |
+
-webkit-text-fill-color: transparent;
|
| 569 |
+
font-weight: bold;
|
| 570 |
+
text-align: center;
|
| 571 |
+
margin-top: 1rem;
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
.advice-box {
|
| 575 |
+
background: #f8f9ff;
|
| 576 |
+
border-left: 4px solid #667eea;
|
| 577 |
+
padding: 1rem;
|
| 578 |
+
margin: 1rem 0;
|
| 579 |
+
border-radius: 8px;
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
.quick-action-btn {
|
| 583 |
+
background: linear-gradient(45deg, #667eea, #764ba2);
|
| 584 |
+
color: white;
|
| 585 |
+
border: none;
|
| 586 |
+
border-radius: 25px;
|
| 587 |
+
padding: 0.5rem 1rem;
|
| 588 |
+
margin: 0.25rem;
|
| 589 |
+
cursor: pointer;
|
| 590 |
+
transition: all 0.3s ease;
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
.quick-action-btn:hover {
|
| 594 |
+
transform: translateY(-2px);
|
| 595 |
+
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
|
| 596 |
+
}
|
| 597 |
+
"""
|
| 598 |
+
|
| 599 |
+
# Modal backend URL
|
| 600 |
+
MODAL_BACKEND_URL = os.getenv("MODAL_BACKEND_URL", "https://kaustubhme0--moneymate-backend-fastapi-app.modal.run")
|
| 601 |
+
|
| 602 |
+
def call_modal_financial_advice(user_input: str, context: Dict[str, Any] = None) -> str:
|
| 603 |
+
"""Call Modal backend for AI-powered financial advice"""
|
| 604 |
+
try:
|
| 605 |
+
payload = {
|
| 606 |
+
"user_input": user_input,
|
| 607 |
+
"context": context or {}
|
| 608 |
+
}
|
| 609 |
+
|
| 610 |
+
response = requests.post(
|
| 611 |
+
f"{MODAL_BACKEND_URL}/financial_advice",
|
| 612 |
+
json=payload,
|
| 613 |
+
timeout=60
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
if response.status_code == 200:
|
| 617 |
+
return response.json().get("advice", "Unable to get advice at the moment.")
|
| 618 |
+
else:
|
| 619 |
+
return "Sorry, I'm having trouble connecting to the financial advisor. Please try again."
|
| 620 |
+
|
| 621 |
+
except requests.exceptions.RequestException as e:
|
| 622 |
+
return f"Connection error: {str(e)}. Please check your internet connection."
|
| 623 |
+
|
| 624 |
+
def call_modal_analyze_expenses(expenses: Dict[str, float], salary: float) -> Dict[str, Any]:
|
| 625 |
+
"""Call Modal backend for expense analysis"""
|
| 626 |
+
try:
|
| 627 |
+
payload = {
|
| 628 |
+
"expenses": expenses,
|
| 629 |
+
"salary": salary
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
response = requests.post(
|
| 633 |
+
f"{MODAL_BACKEND_URL}/analyze_expenses",
|
| 634 |
+
json=payload,
|
| 635 |
+
timeout=30
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
if response.status_code == 200:
|
| 639 |
+
return response.json().get("analysis", {})
|
| 640 |
+
else:
|
| 641 |
+
# Fallback to local utils function
|
| 642 |
+
return {}
|
| 643 |
+
|
| 644 |
+
except requests.exceptions.RequestException:
|
| 645 |
+
# Fallback to local utils function
|
| 646 |
+
return {}
|
| 647 |
+
|
| 648 |
+
def call_modal_calculate_returns(monthly_investment: float, annual_return: float, years: int) -> Dict[str, Any]:
|
| 649 |
+
"""Call Modal backend for investment return calculations"""
|
| 650 |
+
try:
|
| 651 |
+
payload = {
|
| 652 |
+
"monthly_investment": monthly_investment,
|
| 653 |
+
"annual_return_rate": annual_return,
|
| 654 |
+
"years": years
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
response = requests.post(
|
| 658 |
+
f"{MODAL_BACKEND_URL}/calculate_returns",
|
| 659 |
+
json=payload,
|
| 660 |
+
timeout=30
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
if response.status_code == 200:
|
| 664 |
+
return response.json().get("returns", {})
|
| 665 |
+
else:
|
| 666 |
+
# Fallback to local utils function
|
| 667 |
+
return calculate_sip_returns(monthly_investment, annual_return, years)
|
| 668 |
+
|
| 669 |
+
except requests.exceptions.RequestException:
|
| 670 |
+
# Fallback to local utils function
|
| 671 |
+
return calculate_sip_returns(monthly_investment, annual_return, years)
|
| 672 |
+
|
| 673 |
+
def check_modal_health() -> Dict[str, Any]:
|
| 674 |
+
"""Check Modal backend health"""
|
| 675 |
+
try:
|
| 676 |
+
response = requests.get(f"{MODAL_BACKEND_URL}/health", timeout=10)
|
| 677 |
+
if response.status_code == 200:
|
| 678 |
+
return response.json()
|
| 679 |
+
else:
|
| 680 |
+
return {"status": "unhealthy", "message": "Backend not responding"}
|
| 681 |
+
except requests.exceptions.RequestException as e:
|
| 682 |
+
return {"status": "error", "message": str(e)}
|
| 683 |
+
|
| 684 |
+
def create_salary_breakdown_chart(salary: float, needs: float, wants: float, savings: float):
|
| 685 |
+
"""Create a pie chart for salary breakdown"""
|
| 686 |
+
labels = ['Needs (50%)', 'Wants (30%)', 'Savings (20%)']
|
| 687 |
+
values = [needs, wants, savings]
|
| 688 |
+
colors = ['#ff6b6b', '#4ecdc4', '#45b7d1']
|
| 689 |
+
|
| 690 |
+
fig = go.Figure(data=[go.Pie(
|
| 691 |
+
labels=labels,
|
| 692 |
+
values=values,
|
| 693 |
+
hole=0.4,
|
| 694 |
+
marker_colors=colors,
|
| 695 |
+
textinfo='label+percent',
|
| 696 |
+
textfont_size=12
|
| 697 |
+
)])
|
| 698 |
+
|
| 699 |
+
fig.update_layout(
|
| 700 |
+
title=f"Salary Breakdown for βΉ{salary:,.0f}",
|
| 701 |
+
font=dict(size=14),
|
| 702 |
+
showlegend=True,
|
| 703 |
+
height=400
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
return fig
|
| 707 |
+
|
| 708 |
+
def create_expense_analysis_chart(expenses: Dict[str, float]):
|
| 709 |
+
"""Create a bar chart for expense analysis"""
|
| 710 |
+
categories = list(expenses.keys())
|
| 711 |
+
amounts = list(expenses.values())
|
| 712 |
+
|
| 713 |
+
fig = go.Figure([go.Bar(
|
| 714 |
+
x=categories,
|
| 715 |
+
y=amounts,
|
| 716 |
+
marker_color='#667eea',
|
| 717 |
+
text=[f"βΉ{amount:,.0f}" for amount in amounts],
|
| 718 |
+
textposition='auto'
|
| 719 |
+
)])
|
| 720 |
+
|
| 721 |
+
fig.update_layout(
|
| 722 |
+
title="Monthly Expense Breakdown",
|
| 723 |
+
xaxis_title="Categories",
|
| 724 |
+
yaxis_title="Amount (βΉ)",
|
| 725 |
+
font=dict(size=12),
|
| 726 |
+
height=400
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
return fig
|
| 730 |
+
|
| 731 |
+
def create_investment_projection_chart(monthly_investment: float, years: int):
|
| 732 |
+
"""Create investment projection chart using Modal backend"""
|
| 733 |
+
returns_data = call_modal_calculate_returns(monthly_investment, 12.0, years)
|
| 734 |
+
|
| 735 |
+
if not returns_data:
|
| 736 |
+
return go.Figure()
|
| 737 |
+
|
| 738 |
+
# Create year-wise projection
|
| 739 |
+
years_list = list(range(1, years + 1))
|
| 740 |
+
investment_values = []
|
| 741 |
+
|
| 742 |
+
for year in years_list:
|
| 743 |
+
year_data = call_modal_calculate_returns(monthly_investment, 12.0, year)
|
| 744 |
+
investment_values.append(year_data.get('future_value', 0))
|
| 745 |
+
|
| 746 |
+
fig = go.Figure()
|
| 747 |
+
|
| 748 |
+
fig.add_trace(go.Scatter(
|
| 749 |
+
x=years_list,
|
| 750 |
+
y=investment_values,
|
| 751 |
+
mode='lines+markers',
|
| 752 |
+
name='Investment Growth',
|
| 753 |
+
line=dict(color='#667eea', width=3),
|
| 754 |
+
marker=dict(size=8)
|
| 755 |
+
))
|
| 756 |
+
|
| 757 |
+
fig.update_layout(
|
| 758 |
+
title=f"SIP Growth Projection (βΉ{monthly_investment:,.0f}/month @ 12% annual return)",
|
| 759 |
+
xaxis_title="Years",
|
| 760 |
+
yaxis_title="Amount (βΉ)",
|
| 761 |
+
font=dict(size=12),
|
| 762 |
+
height=400
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
return fig
|
| 766 |
+
|
| 767 |
+
def process_financial_query(
|
| 768 |
+
salary: float,
|
| 769 |
+
rent: float,
|
| 770 |
+
food: float,
|
| 771 |
+
transport: float,
|
| 772 |
+
utilities: float,
|
| 773 |
+
entertainment: float,
|
| 774 |
+
other: float,
|
| 775 |
+
savings_goal: str,
|
| 776 |
+
user_question: str
|
| 777 |
+
) -> tuple:
|
| 778 |
+
"""Process user's financial query with enhanced Modal integration"""
|
| 779 |
+
|
| 780 |
+
# Validate inputs using utils
|
| 781 |
+
salary_valid, salary_msg = validate_salary(salary)
|
| 782 |
+
if not salary_valid:
|
| 783 |
+
return None, None, f"β {salary_msg}", "Please fix the salary amount and try again."
|
| 784 |
+
|
| 785 |
+
# Calculate totals
|
| 786 |
+
total_expenses = rent + food + transport + utilities + entertainment + other
|
| 787 |
+
remaining_salary = salary - total_expenses
|
| 788 |
+
|
| 789 |
+
# Create expense dictionary
|
| 790 |
+
expenses = {
|
| 791 |
+
"rent": rent,
|
| 792 |
+
"food": food,
|
| 793 |
+
"transport": transport,
|
| 794 |
+
"utilities": utilities,
|
| 795 |
+
"entertainment": entertainment,
|
| 796 |
+
"other": other
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
# Validate expenses using utils
|
| 800 |
+
expenses_valid, expenses_msg, warnings = validate_expenses(expenses, salary)
|
| 801 |
+
if not expenses_valid:
|
| 802 |
+
return None, None, f"β {expenses_msg}", "Please adjust your expenses and try again."
|
| 803 |
+
|
| 804 |
+
# Get salary breakdown using utils
|
| 805 |
+
breakdown = calculate_50_30_20_breakdown(salary)
|
| 806 |
+
needs = breakdown["needs"]
|
| 807 |
+
wants = breakdown["wants"]
|
| 808 |
+
savings = breakdown["savings"]
|
| 809 |
+
|
| 810 |
+
# Get expense analysis from Modal backend
|
| 811 |
+
modal_analysis = call_modal_analyze_expenses(expenses, salary)
|
| 812 |
+
|
| 813 |
+
# Get optimization tips from utils
|
| 814 |
+
optimization_tips = get_expense_optimization_tips(expenses, salary)
|
| 815 |
+
|
| 816 |
+
# Create charts
|
| 817 |
+
salary_chart = create_salary_breakdown_chart(salary, needs, wants, savings)
|
| 818 |
+
expense_chart = create_expense_analysis_chart({k.title(): v for k, v in expenses.items()})
|
| 819 |
+
|
| 820 |
+
# Calculate emergency fund target using utils
|
| 821 |
+
emergency_fund = calculate_emergency_fund_target(total_expenses)
|
| 822 |
+
|
| 823 |
+
# Prepare context for Modal backend
|
| 824 |
+
context = {
|
| 825 |
+
"salary": salary,
|
| 826 |
+
"expenses": expenses,
|
| 827 |
+
"total_expenses": total_expenses,
|
| 828 |
+
"remaining_salary": remaining_salary,
|
| 829 |
+
"savings_goal": savings_goal,
|
| 830 |
+
"breakdown": breakdown,
|
| 831 |
+
"emergency_fund": emergency_fund,
|
| 832 |
+
"optimization_tips": optimization_tips[:3] # Top 3 tips
|
| 833 |
+
}
|
| 834 |
+
|
| 835 |
+
# Get AI advice from Modal
|
| 836 |
+
if user_question.strip():
|
| 837 |
+
advice = call_modal_financial_advice(user_question, context)
|
| 838 |
+
else:
|
| 839 |
+
advice = call_modal_financial_advice(f"Analyze my finances: Salary βΉ{salary}, Total expenses βΉ{total_expenses}", context)
|
| 840 |
+
|
| 841 |
+
# Create enhanced summary
|
| 842 |
+
summary = f"""
|
| 843 |
+
## π° Financial Summary
|
| 844 |
+
|
| 845 |
+
**Monthly Salary:** βΉ{salary:,.0f}
|
| 846 |
+
**Total Expenses:** βΉ{total_expenses:,.0f}
|
| 847 |
+
**Remaining Amount:** βΉ{remaining_salary:,.0f}
|
| 848 |
+
|
| 849 |
+
### π Recommended Allocation (50/30/20 Rule)
|
| 850 |
+
- **Needs (50%):** βΉ{needs:,.0f}
|
| 851 |
+
- **Wants (30%):** βΉ{wants:,.0f}
|
| 852 |
+
- **Savings (20%):** βΉ{savings:,.0f}
|
| 853 |
+
|
| 854 |
+
### π― Status
|
| 855 |
+
{'β
Good job! You have money left over.' if remaining_salary > 0 else 'β οΈ You are overspending. Consider reducing expenses.'}
|
| 856 |
+
|
| 857 |
+
### π¨ Emergency Fund Target
|
| 858 |
+
**Target Amount:** βΉ{emergency_fund['target_amount']:,.0f} ({emergency_fund['months_coverage']} months)
|
| 859 |
+
|
| 860 |
+
### π‘ Quick Optimization Tips
|
| 861 |
+
{chr(10).join(f"β’ {tip}" for tip in optimization_tips[:3])}
|
| 862 |
+
|
| 863 |
+
### β οΈ Warnings
|
| 864 |
+
{chr(10).join(f"β’ {warning}" for warning in warnings) if warnings else "No warnings - you're doing great!"}
|
| 865 |
+
"""
|
| 866 |
+
|
| 867 |
+
return salary_chart, expense_chart, summary, advice
|
| 868 |
+
|
| 869 |
+
def calculate_sip_projection(monthly_investment: float, annual_return: float, years: int) -> tuple:
|
| 870 |
+
"""Calculate and visualize SIP projections using Modal backend"""
|
| 871 |
+
|
| 872 |
+
if monthly_investment <= 0 or years <= 0:
|
| 873 |
+
return None, "Please enter valid investment amount and timeline."
|
| 874 |
+
|
| 875 |
+
# Get returns data from Modal backend
|
| 876 |
+
returns_data = call_modal_calculate_returns(monthly_investment, annual_return, years)
|
| 877 |
+
|
| 878 |
+
if not returns_data:
|
| 879 |
+
return None, "Unable to calculate returns. Please try again."
|
| 880 |
+
|
| 881 |
+
# Create projection chart
|
| 882 |
+
projection_chart = create_investment_projection_chart(monthly_investment, years)
|
| 883 |
+
|
| 884 |
+
# Create summary
|
| 885 |
+
summary = f"""
|
| 886 |
+
## π SIP Investment Projection
|
| 887 |
+
|
| 888 |
+
**Monthly Investment:** βΉ{monthly_investment:,.0f}
|
| 889 |
+
**Annual Return:** {annual_return}%
|
| 890 |
+
**Investment Period:** {years} years
|
| 891 |
+
|
| 892 |
+
### π° Projected Results
|
| 893 |
+
- **Total Invested:** βΉ{returns_data.get('total_invested', 0):,.0f}
|
| 894 |
+
- **Future Value:** βΉ{returns_data.get('future_value', 0):,.0f}
|
| 895 |
+
- **Returns Generated:** βΉ{returns_data.get('returns', 0):,.0f}
|
| 896 |
+
- **Return Percentage:** {returns_data.get('return_percentage', 0):.1f}%
|
| 897 |
+
|
| 898 |
+
### π― Wealth Creation
|
| 899 |
+
Your βΉ{monthly_investment:,.0f} monthly investment will grow to βΉ{returns_data.get('future_value', 0):,.0f} in {years} years!
|
| 900 |
+
"""
|
| 901 |
+
|
| 902 |
+
return projection_chart, summary
|
| 903 |
+
|
| 904 |
+
def handle_quick_question(question: str, salary: float = 50000) -> str:
|
| 905 |
+
"""Handle pre-defined quick questions"""
|
| 906 |
+
context = {"salary": salary}
|
| 907 |
+
return call_modal_financial_advice(question, context)
|
| 908 |
+
|
| 909 |
+
def show_health_status() -> str:
|
| 910 |
+
"""Show Modal backend health status"""
|
| 911 |
+
health = check_modal_health()
|
| 912 |
+
|
| 913 |
+
if health.get("status") == "healthy":
|
| 914 |
+
return "β
Backend is healthy and running!"
|
| 915 |
+
else:
|
| 916 |
+
return f"β Backend issue: {health.get('message', 'Unknown error')}"
|
| 917 |
+
|
| 918 |
+
# Create Gradio interface
|
| 919 |
+
def create_moneymate_app():
|
| 920 |
+
with gr.Blocks(css=CUSTOM_CSS, title="MoneyMate - Your Financial Assistant") as app:
|
| 921 |
+
|
| 922 |
+
# Header
|
| 923 |
+
gr.HTML("""
|
| 924 |
+
<div class="main-header">
|
| 925 |
+
<h1>π° MoneyMate</h1>
|
| 926 |
+
<p>Your Personal Financial Assistant for Smart Money Management</p>
|
| 927 |
+
<div class="modal-branding">β‘ Powered by Modal Labs</div>
|
| 928 |
+
</div>
|
| 929 |
+
""")
|
| 930 |
+
|
| 931 |
+
with gr.Tabs():
|
| 932 |
+
# Main Financial Analysis Tab
|
| 933 |
+
with gr.Tab("πΌ Financial Analysis"):
|
| 934 |
+
with gr.Row():
|
| 935 |
+
with gr.Column(scale=1):
|
| 936 |
+
gr.HTML('<div class="money-card">')
|
| 937 |
+
gr.Markdown("### πΌ Your Financial Details")
|
| 938 |
+
|
| 939 |
+
salary_input = gr.Number(
|
| 940 |
+
label="Monthly Salary (βΉ)",
|
| 941 |
+
value=50000,
|
| 942 |
+
minimum=0,
|
| 943 |
+
step=1000
|
| 944 |
+
)
|
| 945 |
+
|
| 946 |
+
gr.Markdown("#### Monthly Expenses")
|
| 947 |
+
rent_input = gr.Number(label="Rent (βΉ)", value=15000, minimum=0)
|
| 948 |
+
food_input = gr.Number(label="Food (βΉ)", value=8000, minimum=0)
|
| 949 |
+
transport_input = gr.Number(label="Transport (βΉ)", value=3000, minimum=0)
|
| 950 |
+
utilities_input = gr.Number(label="Utilities (βΉ)", value=2000, minimum=0)
|
| 951 |
+
entertainment_input = gr.Number(label="Entertainment (βΉ)", value=4000, minimum=0)
|
| 952 |
+
other_input = gr.Number(label="Other Expenses (βΉ)", value=3000, minimum=0)
|
| 953 |
+
|
| 954 |
+
savings_goal_input = gr.Textbox(
|
| 955 |
+
label="Savings Goal",
|
| 956 |
+
placeholder="e.g., Emergency fund, Vacation, House down payment",
|
| 957 |
+
value="Emergency fund"
|
| 958 |
+
)
|
| 959 |
+
|
| 960 |
+
user_question_input = gr.Textbox(
|
| 961 |
+
label="Ask MoneyMate",
|
| 962 |
+
placeholder="e.g., How should I invest my savings? What's the best way to save for a house?",
|
| 963 |
+
lines=3
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
analyze_btn = gr.Button("Analyze My Finances π", variant="primary", size="large")
|
| 967 |
+
health_btn = gr.Button("Check Backend Status π", variant="secondary", size="small")
|
| 968 |
+
health_status = gr.Textbox(label="Status", interactive=False)
|
| 969 |
+
|
| 970 |
+
gr.HTML('</div>')
|
| 971 |
+
|
| 972 |
+
# Quick action buttons
|
| 973 |
+
gr.HTML('<div class="money-card">')
|
| 974 |
+
gr.Markdown("### π Quick Questions")
|
| 975 |
+
|
| 976 |
+
with gr.Row():
|
| 977 |
+
quick_btn1 = gr.Button("π‘ Investment Tips", size="small")
|
| 978 |
+
quick_btn2 = gr.Button("π Save for House", size="small")
|
| 979 |
+
|
| 980 |
+
with gr.Row():
|
| 981 |
+
quick_btn3 = gr.Button("βοΈ Plan Vacation", size="small")
|
| 982 |
+
quick_btn4 = gr.Button("π Buy a Car", size="small")
|
| 983 |
+
|
| 984 |
+
gr.HTML('</div>')
|
| 985 |
+
|
| 986 |
+
with gr.Column(scale=2):
|
| 987 |
+
gr.HTML('<div class="money-card">')
|
| 988 |
+
|
| 989 |
+
# Output components
|
| 990 |
+
with gr.Tab("π Salary Breakdown"):
|
| 991 |
+
salary_chart_output = gr.Plot()
|
| 992 |
+
|
| 993 |
+
with gr.Tab("πΈ Expense Analysis"):
|
| 994 |
+
expense_chart_output = gr.Plot()
|
| 995 |
+
|
| 996 |
+
with gr.Tab("π Summary"):
|
| 997 |
+
summary_output = gr.Markdown()
|
| 998 |
+
|
| 999 |
+
with gr.Tab("π€ AI Advice"):
|
| 1000 |
+
advice_output = gr.Markdown(value="Click 'Analyze My Finances' to get personalized advice!")
|
| 1001 |
+
|
| 1002 |
+
gr.HTML('</div>')
|
| 1003 |
+
|
| 1004 |
+
# SIP Calculator Tab
|
| 1005 |
+
with gr.Tab("π SIP Calculator"):
|
| 1006 |
+
with gr.Row():
|
| 1007 |
+
with gr.Column(scale=1):
|
| 1008 |
+
gr.Markdown("### π SIP Investment Calculator")
|
| 1009 |
+
|
| 1010 |
+
monthly_investment_input = gr.Number(
|
| 1011 |
+
label="Monthly Investment (βΉ)",
|
| 1012 |
+
value=5000,
|
| 1013 |
+
minimum=500,
|
| 1014 |
+
step=500
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
annual_return_input = gr.Number(
|
| 1018 |
+
label="Expected Annual Return (%)",
|
| 1019 |
+
value=12.0,
|
| 1020 |
+
minimum=1.0,
|
| 1021 |
+
maximum=30.0,
|
| 1022 |
+
step=0.5
|
| 1023 |
+
)
|
| 1024 |
+
|
| 1025 |
+
years_input = gr.Number(
|
| 1026 |
+
label="Investment Period (Years)",
|
| 1027 |
+
value=10,
|
| 1028 |
+
minimum=1,
|
| 1029 |
+
maximum=50,
|
| 1030 |
+
step=1
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
calculate_sip_btn = gr.Button("Calculate SIP Returns π", variant="primary")
|
| 1034 |
+
|
| 1035 |
+
with gr.Column(scale=2):
|
| 1036 |
+
sip_chart_output = gr.Plot()
|
| 1037 |
+
sip_summary_output = gr.Markdown()
|
| 1038 |
+
|
| 1039 |
+
# Event handlers
|
| 1040 |
+
analyze_btn.click(
|
| 1041 |
+
fn=process_financial_query,
|
| 1042 |
+
inputs=[
|
| 1043 |
+
salary_input, rent_input, food_input, transport_input,
|
| 1044 |
+
utilities_input, entertainment_input, other_input,
|
| 1045 |
+
savings_goal_input, user_question_input
|
| 1046 |
+
],
|
| 1047 |
+
outputs=[salary_chart_output, expense_chart_output, summary_output, advice_output]
|
| 1048 |
+
)
|
| 1049 |
+
|
| 1050 |
+
calculate_sip_btn.click(
|
| 1051 |
+
fn=calculate_sip_projection,
|
| 1052 |
+
inputs=[monthly_investment_input, annual_return_input, years_input],
|
| 1053 |
+
outputs=[sip_chart_output, sip_summary_output]
|
| 1054 |
+
)
|
| 1055 |
+
|
| 1056 |
+
health_btn.click(
|
| 1057 |
+
fn=show_health_status,
|
| 1058 |
+
outputs=[health_status]
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
# Quick question handlers
|
| 1062 |
+
quick_btn1.click(
|
| 1063 |
+
fn=lambda s: handle_quick_question("What are the best investment options for a beginner in India?", s),
|
| 1064 |
+
inputs=[salary_input],
|
| 1065 |
+
outputs=[advice_output]
|
| 1066 |
+
)
|
| 1067 |
+
|
| 1068 |
+
quick_btn2.click(
|
| 1069 |
+
fn=lambda s: handle_quick_question("How should I save for buying a house in India?", s),
|
| 1070 |
+
inputs=[salary_input],
|
| 1071 |
+
outputs=[advice_output]
|
| 1072 |
+
)
|
| 1073 |
+
|
| 1074 |
+
quick_btn3.click(
|
| 1075 |
+
fn=lambda s: handle_quick_question("What's the best way to save for a vacation?", s),
|
| 1076 |
+
inputs=[salary_input],
|
| 1077 |
+
outputs=[advice_output]
|
| 1078 |
+
)
|
| 1079 |
+
|
| 1080 |
+
quick_btn4.click(
|
| 1081 |
+
fn=lambda s: handle_quick_question("How should I plan to buy a car with my salary?", s),
|
| 1082 |
+
inputs=[salary_input],
|
| 1083 |
+
outputs=[advice_output]
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
# Footer
|
| 1087 |
+
gr.HTML("""
|
| 1088 |
+
<div style="text-align: center; margin-top: 2rem; color: white;">
|
| 1089 |
+
<p>Made with β€οΈ for Agents & MCP Hackathon 2025</p>
|
| 1090 |
+
<p>π Track 1 β MCP Tool / Server</p>
|
| 1091 |
+
</div>
|
| 1092 |
+
""")
|
| 1093 |
+
|
| 1094 |
+
return app
|
| 1095 |
+
|
| 1096 |
+
if __name__ == "__main__":
|
| 1097 |
+
app = create_moneymate_app()
|
| 1098 |
+
app.launch(
|
| 1099 |
+
server_name="0.0.0.0",
|
| 1100 |
+
server_port=7860,
|
| 1101 |
+
share=True
|
| 1102 |
)
|