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|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utility functions for the Attendance Analyzer application
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
from datetime import datetime, date
|
| 8 |
+
import os
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
# Setup logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
def setup_logging():
|
| 16 |
+
"""Setup logging configuration"""
|
| 17 |
+
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 18 |
+
logging.basicConfig(
|
| 19 |
+
level=logging.INFO,
|
| 20 |
+
format=log_format,
|
| 21 |
+
handlers=[
|
| 22 |
+
logging.FileHandler('attendance_analyzer.log'),
|
| 23 |
+
logging.StreamHandler()
|
| 24 |
+
]
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def validate_image(image):
|
| 28 |
+
"""Validate uploaded image"""
|
| 29 |
+
if image is None:
|
| 30 |
+
return False, "No image provided"
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
if isinstance(image, np.ndarray):
|
| 34 |
+
if len(image.shape) != 3:
|
| 35 |
+
return False, "Invalid image format"
|
| 36 |
+
return True, "Valid image"
|
| 37 |
+
else:
|
| 38 |
+
return True, "Valid image"
|
| 39 |
+
except Exception as e:
|
| 40 |
+
return False, f"Image validation error: {str(e)}"
|
| 41 |
+
|
| 42 |
+
def resize_image(image, max_size=(800, 600)):
|
| 43 |
+
"""Resize image while maintaining aspect ratio"""
|
| 44 |
+
try:
|
| 45 |
+
height, width = image.shape[:2]
|
| 46 |
+
max_width, max_height = max_size
|
| 47 |
+
|
| 48 |
+
if width <= max_width and height <= max_height:
|
| 49 |
+
return image
|
| 50 |
+
|
| 51 |
+
# Calculate scaling factor
|
| 52 |
+
scale = min(max_width / width, max_height / height)
|
| 53 |
+
new_width = int(width * scale)
|
| 54 |
+
new_height = int(height * scale)
|
| 55 |
+
|
| 56 |
+
resized = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)
|
| 57 |
+
return resized
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"Error resizing image: {e}")
|
| 60 |
+
return image
|
| 61 |
+
|
| 62 |
+
def format_datetime(dt=None):
|
| 63 |
+
"""Format datetime for database storage"""
|
| 64 |
+
if dt is None:
|
| 65 |
+
dt = datetime.now()
|
| 66 |
+
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
| 67 |
+
|
| 68 |
+
def format_date(d=None):
|
| 69 |
+
"""Format date for database storage"""
|
| 70 |
+
if d is None:
|
| 71 |
+
d = date.today()
|
| 72 |
+
return d.strftime("%Y-%m-%d")
|
| 73 |
+
|
| 74 |
+
def create_directory_if_not_exists(directory_path):
|
| 75 |
+
"""Create directory if it doesn't exist"""
|
| 76 |
+
try:
|
| 77 |
+
if not os.path.exists(directory_path):
|
| 78 |
+
os.makedirs(directory_path)
|
| 79 |
+
logger.info(f"Created directory: {directory_path}")
|
| 80 |
+
return True
|
| 81 |
+
except Exception as e:
|
| 82 |
+
logger.error(f"Error creating directory {directory_path}: {e}")
|
| 83 |
+
return False
|
| 84 |
+
|
| 85 |
+
def cleanup_old_files(directory, days_old=30):
|
| 86 |
+
"""Clean up old files from specified directory"""
|
| 87 |
+
try:
|
| 88 |
+
current_time = datetime.now()
|
| 89 |
+
for filename in os.listdir(directory):
|
| 90 |
+
file_path = os.path.join(directory, filename)
|
| 91 |
+
if os.path.isfile(file_path):
|
| 92 |
+
file_time = datetime.fromtimestamp(os.path.getctime(file_path))
|
| 93 |
+
if (current_time - file_time).days > days_old:
|
| 94 |
+
os.remove(file_path)
|
| 95 |
+
logger.info(f"Removed old file: {filename}")
|
| 96 |
+
except Exception as e:
|
| 97 |
+
logger.error(f"Error cleaning up old files: {e}")
|
| 98 |
+
|
| 99 |
+
def validate_name(name):
|
| 100 |
+
"""Validate person name"""
|
| 101 |
+
if not name or not name.strip():
|
| 102 |
+
return False, "Name cannot be empty"
|
| 103 |
+
|
| 104 |
+
if len(name.strip()) < 2:
|
| 105 |
+
return False, "Name must be at least 2 characters long"
|
| 106 |
+
|
| 107 |
+
if len(name.strip()) > 50:
|
| 108 |
+
return False, "Name cannot exceed 50 characters"
|
| 109 |
+
|
| 110 |
+
# Check for valid characters (letters, spaces, hyphens, apostrophes)
|
| 111 |
+
import re
|
| 112 |
+
if not re.match(r"^[a-zA-Z\s\-'\.]+$", name.strip()):
|
| 113 |
+
return False, "Name contains invalid characters"
|
| 114 |
+
|
| 115 |
+
return True, "Valid name"
|
| 116 |
+
|
| 117 |
+
def validate_email(email):
|
| 118 |
+
"""Validate email address"""
|
| 119 |
+
if not email:
|
| 120 |
+
return True, "Email is optional"
|
| 121 |
+
|
| 122 |
+
import re
|
| 123 |
+
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
| 124 |
+
if re.match(email_pattern, email):
|
| 125 |
+
return True, "Valid email"
|
| 126 |
+
else:
|
| 127 |
+
return False, "Invalid email format"
|
| 128 |
+
|
| 129 |
+
def get_system_info():
|
| 130 |
+
"""Get system information for debugging"""
|
| 131 |
+
import platform
|
| 132 |
+
import psutil
|
| 133 |
+
|
| 134 |
+
info = {
|
| 135 |
+
"platform": platform.platform(),
|
| 136 |
+
"python_version": platform.python_version(),
|
| 137 |
+
"cpu_count": psutil.cpu_count(),
|
| 138 |
+
"memory_total": f"{psutil.virtual_memory().total / (1024**3):.2f} GB",
|
| 139 |
+
"memory_available": f"{psutil.virtual_memory().available / (1024**3):.2f} GB",
|
| 140 |
+
}
|
| 141 |
+
return info
|
| 142 |
+
|
| 143 |
+
def benchmark_face_detection(image, iterations=5):
|
| 144 |
+
"""Benchmark face detection performance"""
|
| 145 |
+
import time
|
| 146 |
+
import face_recognition
|
| 147 |
+
|
| 148 |
+
times = []
|
| 149 |
+
for _ in range(iterations):
|
| 150 |
+
start_time = time.time()
|
| 151 |
+
face_locations = face_recognition.face_locations(image)
|
| 152 |
+
end_time = time.time()
|
| 153 |
+
times.append(end_time - start_time)
|
| 154 |
+
|
| 155 |
+
avg_time = sum(times) / len(times)
|
| 156 |
+
return {
|
| 157 |
+
"average_time": avg_time,
|
| 158 |
+
"min_time": min(times),
|
| 159 |
+
"max_time": max(times),
|
| 160 |
+
"iterations": iterations
|
| 161 |
+
}
|