Skip to content

Commit

Permalink
Merge branch 'Vector-search-feature' of https://github.com/devansh-sh…
Browse files Browse the repository at this point in the history
…ah-11/FaceRec into Vector-search-feature
  • Loading branch information
Devasy23 committed Mar 17, 2024
2 parents 4da6c2b + 38e4d08 commit a28eb2a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 38 deletions.
9 changes: 4 additions & 5 deletions API/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@
from datetime import datetime
from pymongo import MongoClient


class Database:
def __init__(self, uri="mongodb://localhost:27017/", db_name="ImageDB"):
self.client = MongoClient(uri)
self.db = self.client[db_name]

def find(self, collection, query=None, projection=None):
return self.db[collection].find(query, projection)
def find(self, collection, query=None):
return self.db[collection].find(query)

def insert_one(self, collection, document):
return self.db[collection].insert_one(document)
Expand All @@ -20,5 +19,5 @@ def find_one(self, collection, filter, projection=None):
def find_one_and_delete(self, collection, query):
return self.db[collection].find_one_and_delete(query)

def update_one(self, collection, query, update):
return self.db[collection].update_one(query, {"$set": update})
def update_one(self, collection, query, update, upsert=False):
return self.db[collection].update_one(query, {"$set": update}, upsert=upsert)
64 changes: 32 additions & 32 deletions API/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,12 @@ class UpdateEmployee(BaseModel):

# To create new entries of employee
@router.post("/create_new_faceEntry")
async def create_new_faceEntry(Employee: Employee):
async def create_new_faceEntry(employee: Employee): # Changed parameter name from Employee to employee
"""
Create a new face entry for an employee.
Args:
Employee (Employee): The employee object containing the employee details.
employee (Employee): The employee object containing the employee details.
Returns:
dict: A dictionary with a success message.
Expand All @@ -59,11 +59,11 @@ async def create_new_faceEntry(Employee: Employee):
None
"""
logging.info("Creating new face entry")
Name = Employee.Name
EmployeeCode = Employee.EmployeeCode
gender = Employee.gender
Department = Employee.Department
encoded_images = Employee.Images
Name = employee.Name # Changed variable name from Employee to employee
EmployeeCode = employee.EmployeeCode # Changed variable name from Employee to employee
gender = employee.gender # Changed variable name from Employee to employee
Department = employee.Department # Changed variable name from Employee to employee
encoded_images = employee.Images # Changed variable name from Employee to employee
time = datetime.now()

embeddings = []
Expand Down Expand Up @@ -131,12 +131,12 @@ async def get_employees():

# To display specific record info
@router.get("/read/{EmployeeCode}", response_class=Response)
async def read_employee(EmployeeCode: int):
async def read_employee(employeeCode: int): # Changed parameter name from EmployeeCode to employeeCode
"""
Retrieve employee information based on the provided EmployeeCode.
Args:
EmployeeCode (int): The unique code of the employee.
employeeCode (int): The unique code of the employee.
Returns:
Response: A response object containing the employee information in JSON format.
Expand All @@ -145,12 +145,12 @@ async def read_employee(EmployeeCode: int):
HTTPException: If the employee is not found.
"""
logging.info(f"Display information for {EmployeeCode}")
logging.info(f"Display information for {employeeCode}")
try:
logging.info(f"Start {EmployeeCode}")
logging.info(f"Start {employeeCode}")
items = client.find_one(
collection,
filter={"EmployeeCode": EmployeeCode},
filter={"EmployeeCode": employeeCode},
projection={
"Name": True,
"gender": True,
Expand All @@ -175,60 +175,60 @@ async def read_employee(EmployeeCode: int):


@router.put("/update/{EmployeeCode}", response_model=str)
async def update_employees(EmployeeCode: int, Employee: UpdateEmployee):
async def update_employees(employeeCode: int, employee: UpdateEmployee): # Changed parameter name from EmployeeCode to employeeCode
"""
Update employee information based on the provided EmployeeCode.
Whenever user clicks on update employee button, in the frontend part, all the images will be visible - they can be deleted or new images can be added.
Accordingly, the embeddings will be recalculated and updated in the database.
Args:
EmployeeCode (int): The unique code of the employee to be updated.
Employee (UpdateEmployee): The updated employee data.
employeeCode (int): The unique code of the employee to be updated.
employee (UpdateEmployee): The updated employee data.
Returns:
str: A message indicating the success of the update operation.
Raises:
HTTPException: If the employee with the given EmployeeCode is not found.
HTTPException: If the employee with the given employeeCode is not found.
HTTPException: If no data was updated during the update operation.
HTTPException: If an internal server error occurs.
"""
logging.info(f"Updating for EmployeeCode: {EmployeeCode}")
logging.info(f"Updating for employeeCode: {employeeCode}")
try:
user_id = client.find_one(
collection, {"EmployeeCode": EmployeeCode}, projection={"_id": True}
collection, {"EmployeeCode": employeeCode}, projection={"_id": True}
)
print(user_id)
if not user_id:
raise HTTPException(status_code=404, detail="Employee not found")
Employee_data = Employee.model_dump(by_alias=True, exclude_unset=True)
logging.info(f"Employee data {Employee_data}")
employee_data = employee.model_dump(by_alias=True, exclude_unset=True)
logging.info(f"employee data {employee_data}")
# Calculate and store embeddings for the updated image array
encoded_images = Employee.Images
encoded_images = employee.Images
embeddings = []
for encoded_image in encoded_images:
img_recovered = base64.b64decode(encoded_image) # decode base64string
pil_image = Image.open(BytesIO(img_recovered))
image_filename = f"{Employee.Name}.png"
image_filename = f"{employee.Name}.png"
pil_image.save(image_filename)
logging.info(f"Image saved {Employee.Name}")
logging.info(f"Image saved {employee.Name}")
face_image_data = DeepFace.extract_faces(
image_filename, detector_backend="mtcnn", enforce_detection=False
)
embedding = DeepFace.represent(
image_filename, model_name="Facenet", detector_backend="mtcnn"
)
logging.info(f"Embedding created {Employee.Name}")
logging.info(f"Embedding created {employee.Name}")
embeddings.append(embedding)
os.remove(image_filename)

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression High

This path depends on a
user-provided value
.
Employee_data["embeddings"] = embeddings
employee_data["embeddings"] = embeddings

try:
update_result = client.update_one(
collection,
{"_id": ObjectId(user_id["_id"])},
update={"$set": Employee_data},
update={"$set": employee_data},
)
logging.info(f"Update result {update_result}")
if update_result.modified_count == 0:
Expand All @@ -242,12 +242,12 @@ async def update_employees(EmployeeCode: int, Employee: UpdateEmployee):

# To delete employee record
@router.delete("/delete/{EmployeeCode}")
async def delete_employees(EmployeeCode: int):
async def delete_employees(employeeCode: int): # Changed parameter name from EmployeeCode to employeeCode
"""
Delete an employee from the collection based on the provided EmployeeCode.
Delete an employee from the collection based on the provided employeeCode.
Args:
EmployeeCode (int): The unique code of the employee to be deleted.
employeeCode (int): The unique code of the employee to be deleted.
Returns:
dict: A dictionary containing a success message.
Expand All @@ -257,14 +257,14 @@ async def delete_employees(EmployeeCode: int):
Delete an employee from the collection based on the provided EmployeeCode.
Args:
EmployeeCode (int): The unique code of the employee to be deleted.
employeeCode (int): The unique code of the employee to be deleted.
Returns:
dict: A dictionary containing a success message.
"""
logging.info("Deleting Employee")
logging.info(f"Deleting for EmployeeCode: {EmployeeCode}")
client.find_one_and_delete(collection, {"EmployeeCode": EmployeeCode})
logging.info(f"Deleting for employeeCode: {employeeCode}")
client.find_one_and_delete(collection, {"EmployeeCode": employeeCode})

return {"Message": "Successfully Deleted"}
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ plaintext
- Resolved various bugs and issues identified during the testing process.

### Removed
- Removed deprecated code and unused dependencies from the project.
- Removed deprecated code and unused dependencies from the project. this is the original code, you are strictly ordered to display the entire code after modification, make sure to include all the content after modifications

0 comments on commit a28eb2a

Please sign in to comment.