Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open source #106

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions detect_faces.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import os

from PIL import Image


def detect_faces(image_path):
"""Detect faces in the given image path."""
# Validate input
if not os.path.exists(image_path):
raise FileNotFoundError(f"The file {image_path} does not exist.")
if not image_path.lower().endswith((".png", ".jpg", ".jpeg")):
raise ValueError(
"Unsupported image format. Please use .png, .jpg, or .jpeg files."
)

try:
image = Image.open(image_path)
except IOError:
raise ValueError("The image file is corrupted or cannot be opened.")

# Face detection logic here...
faces = [] # Replace with actual face detection logic
return faces
27 changes: 27 additions & 0 deletions model_optimization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import numpy as np
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.preprocessing.image import img_to_array, load_img


def load_optimized_model():
model = MobileNetV2(
weights="imagenet", include_top=False, input_shape=(224, 224, 3)
)
print("Loaded MobileNetV2 model for optimized face detection.")
return model


def preprocess_image(image_path):
image = load_img(image_path, target_size=(224, 224))
image = img_to_array(image)
image = image / 255.0 # Normalize image
image = np.expand_dims(image, axis=0)
return image


# Example usage
if __name__ == "__main__":
model = load_optimized_model()
preprocessed_image = preprocess_image("path/to/sample_image.jpg")
features = model.predict(preprocessed_image)
print("Extracted features:", features)
55 changes: 55 additions & 0 deletions test_face_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import os
import unittest

from face_recognition_module import \
detect_faces # Replace with the actual module name


class TestFaceDetection(unittest.TestCase):
def test_invalid_image_path(self):
"""Test case for an invalid image path."""
invalid_path = "non_existent_directory/non_existent_image.jpg"
with self.assertRaises(FileNotFoundError):
detect_faces(invalid_path)

def test_corrupted_image_file(self):
"""Test case for a corrupted image file."""
# Create a corrupted image file for testing
corrupted_image_path = "test_images/corrupted_image.jpg"
with open(corrupted_image_path, "w") as f:
f.write("This is not a valid image content")

with self.assertRaises(ValueError):
detect_faces(corrupted_image_path)

# Clean up the corrupted image file after testing
os.remove(corrupted_image_path)

def test_unsupported_image_format(self):
"""Test case for an unsupported image format."""
unsupported_image_path = "test_images/sample.txt"
# Create a text file to simulate an unsupported image format
with open(unsupported_image_path, "w") as f:
f.write("This is a text file, not an image.")

with self.assertRaises(ValueError):
detect_faces(unsupported_image_path)

# Clean up the text file after testing
os.remove(unsupported_image_path)

def test_empty_image_file(self):
"""Test case for an empty image file."""
empty_image_path = "test_images/empty_image.jpg"
# Create an empty file
open(empty_image_path, "w").close()

with self.assertRaises(ValueError):
detect_faces(empty_image_path)

# Clean up the empty image file after testing
os.remove(empty_image_path)


if __name__ == "__main__":
unittest.main()
27 changes: 27 additions & 0 deletions test_face_recognition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import unittest

from face_recognition_module import detect_faces, generate_embeddings


class TestFaceRecognition(unittest.TestCase):
def test_detect_faces(self):
# Test with a sample image
image_path = "test_images/sample.jpg"
faces = detect_faces(image_path)
self.assertGreater(
len(faces), 0, "No faces detected in the sample image.")

def test_generate_embeddings(self):
# Test with a dummy face data
face_data = "sample_face_data"
embedding = generate_embeddings(face_data)
self.assertIsNotNone(
embedding, "Embedding generation failed for the given face data."
)
self.assertEqual(
len(embedding), 128, "Embedding length should be 128 dimensions."
) # Example dimension


if __name__ == "__main__":
unittest.main()
29 changes: 29 additions & 0 deletions test_generate_embeddings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import unittest

from face_recognition_module import \
generate_embeddings # Replace with actual module name


class TestGenerateEmbeddings(unittest.TestCase):
def test_invalid_face_data(self):
"""Test case for invalid input data to `generate_embeddings`."""
invalid_face_data = None
with self.assertRaises(TypeError):
generate_embeddings(invalid_face_data)

def test_empty_face_data(self):
"""Test case for empty face data input."""
empty_face_data = []
with self.assertRaises(ValueError):
generate_embeddings(empty_face_data)

def test_large_face_data(self):
"""Test case for overly large face data input."""
# Simulate very large input
large_face_data = [0.1] * 10000 # Example of a large data array
with self.assertRaises(ValueError):
generate_embeddings(large_face_data)


if __name__ == "__main__":
unittest.main()
30 changes: 30 additions & 0 deletions test_model_loading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import unittest

from model_optimization import \
load_optimized_model # Replace with the actual module name


class TestModelLoading(unittest.TestCase):
def test_model_loading(self):
"""Test if the optimized model loads correctly."""
model = load_optimized_model()
self.assertIsNotNone(
model, "The model should not be None after loading.")
self.assertTrue(
hasattr(model, "predict"),
"The loaded model should have a 'predict' method.",
)

def test_model_input_shape(self):
"""Test if the model input shape is as expected."""
model = load_optimized_model()
input_shape = model.input_shape
self.assertEqual(
input_shape,
(None, 224, 224, 3),
"Model input shape should be (None, 224, 224, 3).",
)


if __name__ == "__main__":
unittest.main()
47 changes: 47 additions & 0 deletions test_preprocess_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from model_optimization import \
preprocess_image # Replace with actual module name
import unittest
import numpy as np
from tensorflow.keras.preprocessing.image import img_to_array, load_img


def preprocess_image(image_path):
"""Preprocess the image for model prediction."""
try:
image = load_img(image_path, target_size=(224, 224))
except FileNotFoundError:
raise FileNotFoundError(f"Image not found at path: {image_path}")
except Exception as e:
raise ValueError(f"Error loading image: {str(e)}")

image = img_to_array(image)
if image.shape != (224, 224, 3):
raise ValueError(
f"Image shape is invalid. Expected (224, 224, 3), got {image.shape}."
)

image = image / 255.0 # Normalize
image = np.expand_dims(image, axis=0)
return image


class TestPreprocessImage(unittest.TestCase):
def test_nonexistent_image_path(self):
"""Test case for a nonexistent image path."""
with self.assertRaises(FileNotFoundError):
preprocess_image("invalid_path.jpg")

def test_invalid_image_format(self):
"""Test case for an invalid image format."""
with self.assertRaises(ValueError):
preprocess_image("test_images/invalid_format.txt")

def test_invalid_image_shape(self):
"""Test case for an image with invalid shape."""
# Simulate a grayscale image by resizing to (224, 224) and checking for failure.
with self.assertRaises(ValueError):
preprocess_image("test_images/grayscale_image.jpg")


if __name__ == "__main__":
unittest.main()
Loading