File size: 9,880 Bytes
8eab354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""
Test script for InklyAI AgentAI integration.
"""

import requests
import json
import time
import os
from typing import Dict, Any


class AgentAIClient:
    """Client for testing AgentAI integration."""
    
    def __init__(self, base_url: str = "http://localhost:5000"):
        """
        Initialize the client.
        
        Args:
            base_url: Base URL of the API server
        """
        self.base_url = base_url
        self.session = requests.Session()
    
    def health_check(self) -> Dict[str, Any]:
        """Check API health."""
        response = self.session.get(f"{self.base_url}/health")
        return response.json()
    
    def register_agent(self, agent_id: str, signature_template: str) -> Dict[str, Any]:
        """Register an agent."""
        data = {
            "agent_id": agent_id,
            "signature_template": signature_template
        }
        response = self.session.post(f"{self.base_url}/register-agent", json=data)
        return response.json()
    
    def verify_signature(self, agent_id: str, signature_image: str, context: Dict[str, Any] = None) -> Dict[str, Any]:
        """Verify agent signature."""
        data = {
            "agent_id": agent_id,
            "signature_image": signature_image
        }
        if context:
            data["context"] = context
        
        response = self.session.post(f"{self.base_url}/verify-signature", json=data)
        return response.json()
    
    def get_agent_stats(self, agent_id: str) -> Dict[str, Any]:
        """Get agent statistics."""
        response = self.session.get(f"{self.base_url}/agent-stats/{agent_id}")
        return response.json()
    
    def list_agents(self) -> Dict[str, Any]:
        """List all agents."""
        response = self.session.get(f"{self.base_url}/list-agents")
        return response.json()
    
    def deactivate_agent(self, agent_id: str) -> Dict[str, Any]:
        """Deactivate an agent."""
        response = self.session.post(f"{self.base_url}/deactivate-agent/{agent_id}")
        return response.json()
    
    def reactivate_agent(self, agent_id: str) -> Dict[str, Any]:
        """Reactivate an agent."""
        response = self.session.post(f"{self.base_url}/reactivate-agent/{agent_id}")
        return response.json()


def test_agentai_integration():
    """Test the AgentAI integration."""
    print("πŸ§ͺ Testing InklyAI AgentAI Integration")
    print("=" * 50)
    
    # Initialize client
    client = AgentAIClient()
    
    # Test 1: Health check
    print("\n1. Testing health check...")
    health = client.health_check()
    print(f"   Health status: {health}")
    assert health['status'] == 'healthy', "Health check failed"
    print("   βœ… Health check passed")
    
    # Test 2: Register agents
    print("\n2. Testing agent registration...")
    
    # Check if sample data exists
    if not os.path.exists('data/samples/john_doe_1.png'):
        print("   ⚠️  Sample data not found. Run demo.py first to create sample signatures.")
        return
    
    # Register test agents
    agents = [
        ("test_agent_001", "data/samples/john_doe_1.png"),
        ("test_agent_002", "data/samples/jane_smith_1.png"),
        ("test_agent_003", "data/samples/bob_wilson_1.png")
    ]
    
    for agent_id, signature_template in agents:
        result = client.register_agent(agent_id, signature_template)
        if result['success']:
            print(f"   βœ… Registered {agent_id}")
        else:
            print(f"   ❌ Failed to register {agent_id}: {result.get('error', 'Unknown error')}")
    
    # Test 3: List agents
    print("\n3. Testing agent listing...")
    agents_list = client.list_agents()
    print(f"   Total agents: {agents_list.get('total_agents', 0)}")
    for agent in agents_list.get('agents', []):
        print(f"   - {agent['agent_id']} (active: {agent['is_active']})")
    print("   βœ… Agent listing passed")
    
    # Test 4: Signature verification
    print("\n4. Testing signature verification...")
    
    # Test genuine signatures
    test_cases = [
        ("test_agent_001", "data/samples/john_doe_2.png", "Genuine signature"),
        ("test_agent_002", "data/samples/jane_smith_2.png", "Genuine signature"),
        ("test_agent_001", "data/samples/jane_smith_1.png", "Forged signature"),
        ("test_agent_002", "data/samples/bob_wilson_1.png", "Forged signature")
    ]
    
    for agent_id, signature_image, expected in test_cases:
        result = client.verify_signature(agent_id, signature_image)
        if result['success']:
            is_verified = result['is_verified']
            similarity = result['similarity_score']
            confidence = result['confidence']
            print(f"   {agent_id} vs {signature_image.split('/')[-1]}: "
                  f"Verified={is_verified}, Similarity={similarity:.3f}, Confidence={confidence:.3f}")
        else:
            print(f"   ❌ Verification failed for {agent_id}: {result.get('error', 'Unknown error')}")
    
    print("   βœ… Signature verification passed")
    
    # Test 5: Agent statistics
    print("\n5. Testing agent statistics...")
    for agent_id, _ in agents:
        stats = client.get_agent_stats(agent_id)
        if stats['success']:
            agent_stats = stats['stats']
            print(f"   {agent_id}: {agent_stats['total_verifications']} verifications, "
                  f"success rate: {agent_stats['success_rate']:.2%}")
        else:
            print(f"   ❌ Failed to get stats for {agent_id}")
    
    print("   βœ… Agent statistics passed")
    
    # Test 6: Agent deactivation/reactivation
    print("\n6. Testing agent deactivation/reactivation...")
    
    # Deactivate an agent
    deactivate_result = client.deactivate_agent("test_agent_001")
    if deactivate_result['success']:
        print("   βœ… Deactivated test_agent_001")
    else:
        print(f"   ❌ Failed to deactivate test_agent_001: {deactivate_result.get('error')}")
    
    # Try to verify with deactivated agent
    deactivated_result = client.verify_signature("test_agent_001", "data/samples/john_doe_2.png")
    if not deactivated_result['is_verified']:
        print("   βœ… Deactivated agent correctly rejected verification")
    else:
        print("   ⚠️  Deactivated agent still accepted verification")
    
    # Reactivate the agent
    reactivate_result = client.reactivate_agent("test_agent_001")
    if reactivate_result['success']:
        print("   βœ… Reactivated test_agent_001")
    else:
        print(f"   ❌ Failed to reactivate test_agent_001: {reactivate_result.get('error')}")
    
    print("   βœ… Agent deactivation/reactivation passed")
    
    # Test 7: Batch verification
    print("\n7. Testing batch verification...")
    
    batch_requests = [
        {
            "agent_id": "test_agent_001",
            "signature_image": "data/samples/john_doe_2.png",
            "context": {"test": True}
        },
        {
            "agent_id": "test_agent_002", 
            "signature_image": "data/samples/jane_smith_2.png",
            "context": {"test": True}
        }
    ]
    
    batch_data = {"verification_requests": batch_requests}
    response = client.session.post(f"{client.base_url}/batch-verify", json=batch_data)
    batch_result = response.json()
    
    if batch_result['success']:
        print(f"   βœ… Batch verification processed {batch_result['total_processed']} requests")
        for result in batch_result['results']:
            print(f"   - {result['agent_id']}: Verified={result['is_verified']}, "
                  f"Similarity={result['similarity_score']:.3f}")
    else:
        print(f"   ❌ Batch verification failed: {batch_result.get('error')}")
    
    print("\nπŸŽ‰ All tests completed successfully!")
    print("\nAgentAI Integration Features Demonstrated:")
    print("βœ… Health monitoring")
    print("βœ… Agent registration and management")
    print("βœ… Signature verification")
    print("βœ… Agent statistics and monitoring")
    print("βœ… Agent activation/deactivation")
    print("βœ… Batch processing")
    print("βœ… Error handling and logging")


def test_api_endpoints():
    """Test individual API endpoints."""
    print("\nπŸ” Testing Individual API Endpoints")
    print("=" * 40)
    
    client = AgentAIClient()
    
    # Test configuration
    config_response = client.session.get(f"{client.base_url}/config")
    config = config_response.json()
    print(f"Current configuration: {json.dumps(config, indent=2)}")
    
    # Test error handling
    print("\nTesting error handling...")
    
    # Test with invalid agent ID
    invalid_result = client.verify_signature("invalid_agent", "data/samples/john_doe_1.png")
    print(f"Invalid agent test: {invalid_result}")
    
    # Test with missing fields
    response = client.session.post(f"{client.base_url}/verify-signature", json={})
    error_result = response.json()
    print(f"Missing fields test: {error_result}")


if __name__ == "__main__":
    print("InklyAI AgentAI Integration Test Suite")
    print("=" * 50)
    
    # Check if API server is running
    try:
        client = AgentAIClient()
        health = client.health_check()
        print(f"βœ… API server is running: {health['status']}")
    except requests.exceptions.ConnectionError:
        print("❌ API server is not running. Please start it with:")
        print("   python flask_api.py")
        print("\nThen run this test script again.")
        exit(1)
    
    # Run tests
    test_agentai_integration()
    test_api_endpoints()
    
    print("\n" + "=" * 50)
    print("Test suite completed!")
    print("\nTo start the API server manually:")
    print("   python flask_api.py")
    print("\nAPI will be available at: http://localhost:5000")
    print("API documentation: http://localhost:5000/health")