File size: 7,404 Bytes
18afae5
 
 
 
 
 
 
 
 
 
05ed0ff
18afae5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
Test script for Hugging Face deployed API
Creates sample expenses and tests recommendations
"""

import requests
import json
from datetime import datetime, timedelta

BASE_URL = "https://logicgoinfotechspaces-smart-budget-recommendation.hf.space"
USER_ID = "688c80ca990b63f0e945ecd9"

def test_health():
    """Test health endpoint"""
    print("=" * 60)
    print("1. Testing Health Endpoint")
    print("=" * 60)
    try:
        response = requests.get(f"{BASE_URL}/health")
        print(f"Status: {response.status_code}")
        print(f"Response: {json.dumps(response.json(), indent=2)}")
        return response.status_code == 200
    except Exception as e:
        print(f"Error: {e}")
        return False

def create_sample_expenses():
    """Create multiple sample expenses across different months"""
    print("\n" + "=" * 60)
    print("2. Creating Sample Expenses")
    print("=" * 60)
    
    # Create expenses for the past 4 months
    base_date = datetime(2024, 9, 15)  # Start from September 2024
    expenses = []
    
    # Groceries - 4 months
    for i in range(4):
        date = base_date + timedelta(days=30 * i)
        expenses.append({
            "user_id": USER_ID,
            "amount": 3500 + (i * 100),  # Varying amounts: 3500, 3600, 3700, 3800
            "category": "Groceries",
            "description": f"Monthly groceries - {date.strftime('%B %Y')}",
            "date": date.isoformat(),
            "type": "expense"
        })
    
    # Transport - 3 months
    for i in range(3):
        date = base_date + timedelta(days=30 * i)
        expenses.append({
            "user_id": USER_ID,
            "amount": 2000 + (i * 50),  # 2000, 2050, 2100
            "category": "Transport",
            "description": f"Monthly transport - {date.strftime('%B %Y')}",
            "date": date.isoformat(),
            "type": "expense"
        })
    
    # Utilities - 2 months
    for i in range(2):
        date = base_date + timedelta(days=30 * i)
        expenses.append({
            "user_id": USER_ID,
            "amount": 1500 + (i * 100),  # 1500, 1600
            "category": "Utilities",
            "description": f"Monthly utilities - {date.strftime('%B %Y')}",
            "date": date.isoformat(),
            "type": "expense"
        })
    
    created_count = 0
    for expense in expenses:
        try:
            response = requests.post(
                f"{BASE_URL}/expenses",
                json=expense,
                headers={"Content-Type": "application/json"}
            )
            if response.status_code == 200:
                print(f"[OK] Created: {expense['category']} - Rs.{expense['amount']} ({expense['date'][:10]})")
                created_count += 1
            else:
                print(f"[FAIL] Failed: {expense['category']} - {response.text}")
        except Exception as e:
            print(f"[ERROR] Error creating expense: {e}")
    
    print(f"\nTotal expenses created: {created_count}/{len(expenses)}")
    return created_count > 0

def get_expenses():
    """Get all expenses for the user"""
    print("\n" + "=" * 60)
    print("3. Getting All Expenses")
    print("=" * 60)
    try:
        response = requests.get(
            f"{BASE_URL}/expenses",
            params={"user_id": USER_ID, "limit": 100}
        )
        if response.status_code == 200:
            expenses = response.json()
            print(f"Found {len(expenses)} expenses:\n")
            for exp in expenses:
                print(f"  - {exp['category']}: Rs.{exp['amount']} ({exp['date'][:10]})")
            return True
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_recommendations():
    """Test getting budget recommendations"""
    print("\n" + "=" * 60)
    print("4. Testing Smart Budget Recommendations")
    print("=" * 60)
    try:
        # Get recommendations for next month
        next_month = datetime.now().month + 1
        next_year = datetime.now().year
        if next_month > 12:
            next_month = 1
            next_year += 1
        
        response = requests.get(
            f"{BASE_URL}/recommendations/{USER_ID}",
            params={"month": next_month, "year": next_year}
        )
        
        if response.status_code == 200:
            recommendations = response.json()
            print(f"\nFound {len(recommendations)} recommendations:\n")
            
            if len(recommendations) == 0:
                print("[WARNING] No recommendations yet. Need more expense data (at least 2-3 months).")
            else:
                for rec in recommendations:
                    print(f"Category: {rec['category']}")
                    print(f"  Average Expense: Rs.{rec['average_expense']:,.0f}")
                    print(f"  Recommended Budget: Rs.{rec['recommended_budget']:,.0f}")
                    print(f"  Confidence: {rec['confidence']*100:.0f}%")
                    print(f"  Reason: {rec['reason']}")
                    print()
            return True
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_category_expenses():
    """Test getting category expense averages"""
    print("\n" + "=" * 60)
    print("5. Testing Category Expense Averages")
    print("=" * 60)
    try:
        response = requests.get(
            f"{BASE_URL}/category-expenses/{USER_ID}",
            params={"months": 6}
        )
        
        if response.status_code == 200:
            categories = response.json()
            print(f"\nFound {len(categories)} categories:\n")
            
            for cat in categories:
                print(f"{cat['category']}:")
                print(f"  Average Monthly: Rs.{cat['average_monthly_expense']:,.0f}")
                print(f"  Total Transactions: {cat['total_expenses']}")
                print(f"  Months Analyzed: {cat['months_analyzed']}")
                print()
            return True
        else:
            print(f"Error: {response.status_code} - {response.text}")
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False

if __name__ == "__main__":
    print("\n" + "=" * 60)
    print("Smart Budget Recommendation API - Hugging Face Test")
    print("=" * 60)
    print(f"\nBase URL: {BASE_URL}")
    print(f"User ID: {USER_ID}\n")
    
    results = []
    
    # Run tests
    results.append(("Health Check", test_health()))
    results.append(("Create Expenses", create_sample_expenses()))
    results.append(("Get Expenses", get_expenses()))
    results.append(("Get Recommendations", test_recommendations()))
    results.append(("Category Averages", test_category_expenses()))
    
    # Summary
    print("\n" + "=" * 60)
    print("Test Summary")
    print("=" * 60)
    for test_name, passed in results:
        status = "[PASS]" if passed else "[FAIL]"
        print(f"{status} - {test_name}")
    
    passed_count = sum(1 for _, passed in results if passed)
    print(f"\nTotal: {passed_count}/{len(results)} tests passed")
    
    print("\n" + "=" * 60)
    print("API Documentation:")
    print(f"  Swagger UI: {BASE_URL}/docs")
    print("=" * 60)