|
|
""" |
|
|
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 = "68a834c3f4694b11efedacd2" |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
base_date = datetime(2024, 9, 15) |
|
|
expenses = [] |
|
|
|
|
|
|
|
|
for i in range(4): |
|
|
date = base_date + timedelta(days=30 * i) |
|
|
expenses.append({ |
|
|
"user_id": USER_ID, |
|
|
"amount": 3500 + (i * 100), |
|
|
"category": "Groceries", |
|
|
"description": f"Monthly groceries - {date.strftime('%B %Y')}", |
|
|
"date": date.isoformat(), |
|
|
"type": "expense" |
|
|
}) |
|
|
|
|
|
|
|
|
for i in range(3): |
|
|
date = base_date + timedelta(days=30 * i) |
|
|
expenses.append({ |
|
|
"user_id": USER_ID, |
|
|
"amount": 2000 + (i * 50), |
|
|
"category": "Transport", |
|
|
"description": f"Monthly transport - {date.strftime('%B %Y')}", |
|
|
"date": date.isoformat(), |
|
|
"type": "expense" |
|
|
}) |
|
|
|
|
|
|
|
|
for i in range(2): |
|
|
date = base_date + timedelta(days=30 * i) |
|
|
expenses.append({ |
|
|
"user_id": USER_ID, |
|
|
"amount": 1500 + (i * 100), |
|
|
"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: |
|
|
|
|
|
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 = [] |
|
|
|
|
|
|
|
|
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())) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|