File size: 8,032 Bytes
382ea2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""
Test script for Payal Farmer Advisory Chatbot API
Run this script to test all API endpoints
"""

import requests
import json
from datetime import datetime

# Base URL - change if running on different host/port
BASE_URL = "http://localhost:8000"

# Test user ID and session (optional, for testing conversation history)
TEST_UID = "test_user_123"
TEST_SESSION_ID = ""  # Will be auto-generated

def print_response(title, response):
    """Pretty print API response"""
    print(f"\n{'='*60}")
    print(f"{title}")
    print(f"{'='*60}")
    print(f"Status Code: {response.status_code}")
    try:
        data = response.json()
        print(f"Response:")
        print(json.dumps(data, indent=2, ensure_ascii=False))
    except:
        print(f"Response: {response.text}")

def test_crop_advice_english():
    """Test crop advice endpoint in English"""
    url = f"{BASE_URL}/chat/crop"
    payload = {
        "query": "What crops should I grow in my area?",
        "lat": 28.6139,  # Delhi coordinates
        "lon": 77.2090,
        "soil": "Loamy",
        "local_info": "Moderate rainfall area",
        "uid": TEST_UID,
        "language": "en"
    }
    response = requests.post(url, json=payload)
    print_response("🌾 Crop Advice (English)", response)
    return response.json().get("session_id")

def test_crop_advice_hindi():
    """Test crop advice endpoint in Hindi"""
    url = f"{BASE_URL}/chat/crop"
    payload = {
        "query": "मेरे क्षेत्र में कौन सी फसलें उगानी चाहिए?",
        "lat": 17.3850,  # Hyderabad coordinates
        "lon": 78.4867,
        "soil": "दोमट मिट्टी",
        "local_info": "मध्यम वर्षा",
        "uid": TEST_UID,
        "language": "hi"
    }
    response = requests.post(url, json=payload)
    print_response("🌾 Crop Advice (Hindi)", response)
    return response.json().get("session_id")

def test_fertilizer_advice():
    """Test fertilizer advice endpoint"""
    url = f"{BASE_URL}/chat/fertilizer"
    payload = {
        "crop": "Wheat",
        "stage": "Vegetative",
        "soil_test": "Nitrogen: Low, Phosphorus: Medium",
        "uid": TEST_UID,
        "language": "en"
    }
    response = requests.post(url, json=payload)
    print_response("🌱 Fertilizer Advice", response)

def test_soil_health():
    """Test soil health advice endpoint"""
    url = f"{BASE_URL}/chat/soil"
    payload = {
        "soil_info": "pH level is 6.5, organic matter is low, clay soil",
        "uid": TEST_UID,
        "language": "hi"
    }
    response = requests.post(url, json=payload)
    print_response("🏞️ Soil Health Advice", response)

def test_weather_advice():
    """Test weather advice endpoint"""
    url = f"{BASE_URL}/chat/weather"
    payload = {
        "lat": 28.6139,
        "lon": 77.2090,
        "days": 3,
        "uid": TEST_UID,
        "language": "en"
    }
    response = requests.post(url, json=payload)
    print_response("🌧️ Weather Advice", response)

def test_mandi_price():
    """Test mandi price endpoint"""
    url = f"{BASE_URL}/chat/mandi"
    payload = {
        "district_name": "Delhi",
        "market_name": "Azadpur",
        "crop": "Tomato",
        "uid": TEST_UID,
        "language": "hi"
    }
    response = requests.post(url, json=payload)
    print_response("💰 Mandi Price", response)

def test_pest_detection():
    """Test pest detection endpoint"""
    url = f"{BASE_URL}/chat/pest"
    params = {
        "farmer_id": "farmer_001",
        "uid": TEST_UID,
        "language": "hi"
    }
    response = requests.get(url, params=params)
    print_response("🐛 Pest Detection", response)

def test_phishing_check():
    """Test phishing URL check endpoint"""
    url = f"{BASE_URL}/chat/phishing"
    payload = {
        "url": "https://www.google.com",
        "uid": TEST_UID,
        "language": "en"
    }
    response = requests.post(url, json=payload)
    print_response("🔒 Phishing URL Check", response)

def test_sentiment_analysis():
    """Test sentiment analysis endpoint"""
    url = f"{BASE_URL}/chat/sentiment"
    payload = {
        "query": "I am very happy with the crop yield this year!",
        "uid": TEST_UID,
        "language": "en"
    }
    response = requests.post(url, json=payload)
    print_response("📊 Sentiment Analysis", response)

def test_government_schemes():
    """Test government schemes endpoint"""
    url = f"{BASE_URL}/chat/schemes"
    payload = {
        "text": "I need information about farming subsidies and schemes",
        "uid": TEST_UID,
        "session_id": "",
        "language": "en"
    }
    response = requests.post(url, json=payload)
    print_response("🏛️ Government Schemes", response)
    
    # Test with Hindi
    payload_hindi = {
        "text": "कृषि ऋण और सब्सिडी योजनाओं के बारे में जानकारी चाहिए",
        "uid": TEST_UID,
        "session_id": "",
        "language": "hi"
    }
    response = requests.post(url, json=payload_hindi)
    print_response("🏛️ Government Schemes (Hindi)", response)

def test_conversation_history(session_id):
    """Test conversation history endpoint"""
    url = f"{BASE_URL}/chat/history"
    params = {
        "uid": TEST_UID,
        "session_id": session_id if session_id else ""
    }
    response = requests.get(url, params=params)
    print_response("📜 Conversation History", response)

def test_multilingual():
    """Test multilingual support"""
    languages = ["hi", "en", "te", "pa", "ta"]
    url = f"{BASE_URL}/chat/crop"
    
    print(f"\n{'='*60}")
    print("🌐 Testing Multilingual Support")
    print(f"{'='*60}")
    
    for lang in languages:
        payload = {
            "query": "Best crops to grow" if lang == "en" else "सबसे अच्छी फसलें",
            "lat": 28.6139,
            "lon": 77.2090,
            "uid": TEST_UID,
            "language": lang
        }
        response = requests.post(url, json=payload)
        data = response.json()
        print(f"\n{lang.upper()}: {data.get('language', 'unknown')}")
        print(f"Response: {data.get('response', '')[:100]}...")

def main():
    """Run all tests"""
    print("\n" + "="*60)
    print("🧪 PAYAL FARMER ADVISORY CHATBOT API - TEST SUITE")
    print("="*60)
    print(f"\nTesting API at: {BASE_URL}")
    print(f"Test User ID: {TEST_UID}")
    print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    try:
        # Test basic connectivity
        response = requests.get(f"{BASE_URL}/docs")
        if response.status_code != 200:
            print(f"\n❌ ERROR: Cannot connect to {BASE_URL}")
            print("Make sure the server is running: uvicorn main:app --reload")
            return
    except requests.exceptions.ConnectionError:
        print(f"\n❌ ERROR: Cannot connect to {BASE_URL}")
        print("Make sure the server is running: uvicorn main:app --reload")
        return
    
    print("\n✅ Server is running!")
    
    # Run tests
    try:
        session_id = test_crop_advice_english()
        test_crop_advice_hindi()
        test_fertilizer_advice()
        test_soil_health()
        test_weather_advice()
        test_mandi_price()
        test_pest_detection()
        test_phishing_check()
        test_sentiment_analysis()
        test_government_schemes()
        
        if session_id:
            test_conversation_history(session_id)
        
        test_multilingual()
        
        print("\n" + "="*60)
        print("✅ ALL TESTS COMPLETED")
        print("="*60)
        print("\n💡 Tip: Check the Swagger UI at http://localhost:8000/docs")
        print("   for interactive API testing and documentation")
        
    except Exception as e:
        print(f"\n❌ Error during testing: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()