generativeai's picture
Update app.py
e38bafd
raw
history blame
2.35 kB
import os
import gradio as gr
from services.aws_service import AwsService
from dotenv import load_dotenv
import cv2
import face_recognition
import numpy as np
load_dotenv()
def find_face_encodings(image):
face_enc = face_recognition.face_encodings(image)
return face_enc[0]
def face_similarity(img1, img2, compare_image_folder=""):
image_1 = find_face_encodings(img1)
image_2 = find_face_encodings(img2)
# checking both images are same
is_same = face_recognition.compare_faces([image_1], image_2)[0]
accuracy = 0
if is_same:
# finding the distance level between images
distance = face_recognition.face_distance([image_1], image_2)
distance = round(distance[0] * 100)
# calcuating accuracy level between images
accuracy = 100 - round(distance)
return {"is_same": "true" if is_same else "false", "accuracy": accuracy, "error": "false", "compare_image": compare_image_folder}
def convert_pil_to_open_cv(pil_image):
open_cv_image = np.array(pil_image)
open_cv_image = open_cv_image[:, :, ::-1].copy()
return open_cv_image
def check_image_similarity(main_image_folder, compare_image_folder):
main_image = AwsService.get_image_from_s3(os.environ.get('AWS_S3_BUCKET'), main_image_folder)
compare_image = AwsService.get_image_from_s3(os.environ.get('AWS_S3_BUCKET'), compare_image_folder)
result = False
try:
result = face_similarity(convert_pil_to_open_cv(main_image["pil"]), convert_pil_to_open_cv(compare_image["pil"]), compare_image_folder)
except Exception as e:
print("Error on execution: ", e)
finally:
if not result:
result = {"is_same": "false", "accuracy": 0, "error": "true", "compare_image": compare_image_folder}
return result
def compare_photoshoot_crops(photo_shoot_id, main_image_folder):
folder = "PhotoShoots/" + str(photo_shoot_id) + "/Croppeds"
files = AwsService.get_files_from_s3(os.environ.get('AWS_S3_BUCKET'), folder)
results = []
for file in files:
if main_image_folder != file['Key']:
result = check_image_similarity(main_image_folder, file['Key'])
results.append(result)
return results
iface = gr.Interface(
fn=compare_photoshoot_crops,
inputs=[
gr.Textbox(lines=1, placeholder="Photo Shoot ID"),
gr.Textbox(lines=1, placeholder="Main Image Key")
],
outputs="text"
)
iface.launch()