File size: 12,900 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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
"""
Flask Web Application for InklyAI Signature Verification UI
"""
from flask import Flask, render_template, request, jsonify, send_from_directory
import os
import uuid
from datetime import datetime
import logging
from werkzeug.utils import secure_filename
from agentai_integration import AgentAISignatureManager, AgentAISignatureAPI
from src.models.siamese_network import SignatureVerifier
from src.data.preprocessing import SignaturePreprocessor
# Initialize Flask app
app = Flask(__name__)
app.config['SECRET_KEY'] = 'inklyai-secret-key-2024'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize signature manager
signature_manager = AgentAISignatureManager(
threshold=0.75,
device='auto'
)
# Initialize API wrapper
api = AgentAISignatureAPI(signature_manager)
# Create upload directories
UPLOAD_FOLDER = 'uploads'
REFERENCE_FOLDER = 'uploads/reference'
VERIFICATION_FOLDER = 'uploads/verification'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(REFERENCE_FOLDER, exist_ok=True)
os.makedirs(VERIFICATION_FOLDER, exist_ok=True)
# Allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff'}
def allowed_file(filename):
"""Check if file extension is allowed."""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def save_uploaded_file(file, folder):
"""Save uploaded file and return the path."""
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
# Add timestamp to avoid conflicts
name, ext = os.path.splitext(filename)
filename = f"{name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}{ext}"
filepath = os.path.join(folder, filename)
file.save(filepath)
return filepath
return None
@app.route('/')
def index():
"""Main page with signature verification UI."""
return render_template('index.html')
@app.route('/agents')
def agents():
"""Agent management page."""
return render_template('agents.html')
@app.route('/api/agents', methods=['GET'])
def get_agents():
"""Get list of registered agents."""
try:
agents = []
for agent_id, agent_signature in signature_manager.agent_signatures.items():
agents.append({
'agent_id': agent_id,
'created_at': agent_signature.created_at.isoformat(),
'last_verified': agent_signature.last_verified.isoformat() if agent_signature.last_verified else None,
'verification_count': agent_signature.verification_count,
'is_active': agent_signature.is_active
})
return jsonify({
'success': True,
'agents': agents,
'total_agents': len(agents)
})
except Exception as e:
logger.error(f"Error getting agents: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/register-agent', methods=['POST'])
def register_agent():
"""Register a new agent with signature template."""
try:
if 'signature_template' not in request.files:
return jsonify({
'success': False,
'error': 'No signature template file provided'
}), 400
file = request.files['signature_template']
agent_id = request.form.get('agent_id')
if not agent_id:
return jsonify({
'success': False,
'error': 'Agent ID is required'
}), 400
# Save the signature template
filepath = save_uploaded_file(file, REFERENCE_FOLDER)
if not filepath:
return jsonify({
'success': False,
'error': 'Invalid file type. Please upload an image file.'
}), 400
# Register the agent
success = signature_manager.register_agent_signature(agent_id, filepath)
if success:
return jsonify({
'success': True,
'agent_id': agent_id,
'message': 'Agent registered successfully'
})
else:
return jsonify({
'success': False,
'error': 'Failed to register agent'
}), 400
except Exception as e:
logger.error(f"Error registering agent: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/verify', methods=['POST'])
def verify_signatures():
"""Verify two signatures."""
try:
if 'signature1' not in request.files or 'signature2' not in request.files:
return jsonify({
'success': False,
'error': 'Both signature files are required'
}), 400
agent_id = request.form.get('agent_id')
if not agent_id:
return jsonify({
'success': False,
'error': 'Agent ID is required'
}), 400
# Save uploaded files
file1 = request.files['signature1']
file2 = request.files['signature2']
file1_path = save_uploaded_file(file1, VERIFICATION_FOLDER)
file2_path = save_uploaded_file(file2, VERIFICATION_FOLDER)
if not file1_path or not file2_path:
return jsonify({
'success': False,
'error': 'Invalid file types. Please upload image files.'
}), 400
# Verify signatures
similarity, is_genuine = signature_manager.verifier.verify_signatures(
file1_path, file2_path, threshold=signature_manager.threshold
)
# Calculate confidence
confidence = similarity # Simple confidence calculation
# Create verification result
verification_id = str(uuid.uuid4())[:12]
result = {
'success': True,
'is_verified': is_genuine,
'similarity_score': float(similarity),
'confidence': float(confidence),
'verification_id': verification_id,
'timestamp': datetime.now().isoformat(),
'agent_id': agent_id
}
# Log verification
logger.info(f"Verification completed: {result}")
return jsonify(result)
except Exception as e:
logger.error(f"Error verifying signatures: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/verify-agent', methods=['POST'])
def verify_agent_signature():
"""Verify signature against registered agent template."""
try:
if 'signature_image' not in request.files:
return jsonify({
'success': False,
'error': 'Signature image file is required'
}), 400
agent_id = request.form.get('agent_id')
if not agent_id:
return jsonify({
'success': False,
'error': 'Agent ID is required'
}), 400
# Check if agent exists
if agent_id not in signature_manager.agent_signatures:
return jsonify({
'success': False,
'error': 'Agent not found'
}), 404
# Save uploaded file
file = request.files['signature_image']
file_path = save_uploaded_file(file, VERIFICATION_FOLDER)
if not file_path:
return jsonify({
'success': False,
'error': 'Invalid file type. Please upload an image file.'
}), 400
# Verify against agent template
result = signature_manager.verify_agent_signature(agent_id, file_path)
return jsonify({
'success': True,
'is_verified': result.is_verified,
'similarity_score': result.similarity_score,
'confidence': result.confidence,
'verification_id': result.verification_id,
'timestamp': result.timestamp.isoformat(),
'agent_id': agent_id
})
except Exception as e:
logger.error(f"Error verifying agent signature: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/stats', methods=['GET'])
def get_stats():
"""Get verification statistics."""
try:
stats = {}
for agent_id in signature_manager.agent_signatures.keys():
agent_stats = signature_manager.get_agent_verification_stats(agent_id)
stats[agent_id] = agent_stats
return jsonify({
'success': True,
'stats': stats
})
except Exception as e:
logger.error(f"Error getting stats: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/agent-stats/<agent_id>', methods=['GET'])
def get_agent_stats(agent_id):
"""Get statistics for a specific agent."""
try:
stats = signature_manager.get_agent_verification_stats(agent_id)
return jsonify({
'success': True,
'agent_id': agent_id,
'stats': stats
})
except Exception as e:
logger.error(f"Error getting agent stats: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/deactivate-agent/<agent_id>', methods=['POST'])
def deactivate_agent(agent_id):
"""Deactivate an agent."""
try:
success = signature_manager.deactivate_agent(agent_id)
return jsonify({
'success': success,
'agent_id': agent_id,
'action': 'deactivated'
})
except Exception as e:
logger.error(f"Error deactivating agent: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/reactivate-agent/<agent_id>', methods=['POST'])
def reactivate_agent(agent_id):
"""Reactivate an agent."""
try:
success = signature_manager.reactivate_agent(agent_id)
return jsonify({
'success': success,
'agent_id': agent_id,
'action': 'reactivated'
})
except Exception as e:
logger.error(f"Error reactivating agent: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/health', methods=['GET'])
def health_check():
"""Health check endpoint."""
return jsonify({
'status': 'healthy',
'timestamp': datetime.now().isoformat(),
'service': 'InklyAI Web Application',
'agents_registered': len(signature_manager.agent_signatures)
})
@app.errorhandler(413)
def too_large(e):
"""Handle file too large error."""
return jsonify({
'success': False,
'error': 'File too large. Maximum size is 16MB.'
}), 413
@app.errorhandler(404)
def not_found(e):
"""Handle 404 errors."""
return jsonify({
'success': False,
'error': 'Endpoint not found'
}), 404
@app.errorhandler(500)
def internal_error(e):
"""Handle 500 errors."""
return jsonify({
'success': False,
'error': 'Internal server error'
}), 500
def initialize_demo_agents():
"""Initialize demo agents if sample data exists."""
try:
# Register demo agents if sample data exists
demo_agents = [
('Agent_01', 'data/samples/john_doe_1.png'),
('Agent_02', 'data/samples/jane_smith_1.png'),
('Agent_03', 'data/samples/bob_wilson_1.png'),
('Agent_04', 'data/samples/alice_brown_1.png')
]
for agent_id, signature_template in demo_agents:
if os.path.exists(signature_template):
signature_manager.register_agent_signature(agent_id, signature_template)
logger.info(f"Registered agent: {agent_id}")
logger.info("Demo agents initialized successfully")
except Exception as e:
logger.warning(f"Could not initialize demo agents: {e}")
if __name__ == '__main__':
# Initialize demo agents
initialize_demo_agents()
# Start the web application
port = int(os.environ.get('PORT', 8080)) # Use port 8080 instead of 5000
debug = os.environ.get('DEBUG', 'False').lower() == 'true'
logger.info(f"Starting InklyAI Web Application on port {port}")
logger.info(f"Access the application at: http://localhost:{port}")
app.run(host='0.0.0.0', port=port, debug=debug)
|