# -*- coding: utf-8 -*-
"""face_cluster.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1M10T304NmhDr8LL602Fbep8_BHMVSOJb

%%<br>
-*- coding: utf-8 -*-

FaceCluster.ipynb<br>
Automatically generated by Colaboratory.<br>
Original file is located at<br>
    https://colab.research.google.com/drive/1jkfqDottCatOFnu-TXHD06fWDKWMqJJc<br>
"""

# from google.colab import drive
# drive.mount('/content/drive')
#
# !ls '/content/drive/MyDrive/faceCluster_5'
#
# pip install face_recognition opencv-python imutils scikit-learn matplotlib

from imutils import build_montages, paths
import numpy as np
import face_recognition
import cv2
import os
import matplotlib.pyplot as plt
import json

# from google.colab import files

image_folder_path = input("Enter the path for loading the images ")  # /content/drive/MyDrive/faceCluster_5
number_of_clusters = image_folder_path[-1]
number_of_clusters = int(number_of_clusters)
print('number_of_clusters', number_of_clusters)
imagePaths = list(paths.list_images(image_folder_path))
print(len(imagePaths))
cluster_data = []
data = []

for (i, path) in enumerate(imagePaths):
    print(path)
    image = cv2.imread(path)
    rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    boxes = face_recognition.face_locations(rgb, model="cnn")
    encodings = face_recognition.face_encodings(rgb, boxes)
    cluster_data.append(encodings)

    d = [{"imagePath": path, "loc": box, "encoding": enc} for (box, enc) in zip(boxes, encodings)]
    data.extend(d)

cluster_data = np.array(cluster_data).reshape(len(imagePaths), 128)
cluster_data.shape

from sklearn.cluster import DBSCAN

cluster = DBSCAN(metric="euclidean", n_jobs=-1)
cluster.fit(cluster_data)

cluster.labels_

labelIDs = np.unique(cluster.labels_)
numUniqueFaces = len(np.where(labelIDs > -1)[0])

json_list = []

for labelID in labelIDs:
    idxs = np.where(cluster.labels_ == labelID)[0]
    idxs = np.random.choice(idxs, size=min(25, len(idxs)), replace=False)

    faces = []
    for i in idxs:
        image = cv2.imread(data[i]["imagePath"])
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        (top, right, bottom, left) = data[i]["loc"]
        face = image[top:bottom, left:right]
        face = cv2.resize(face, (96, 96))
        faces.append(face)
        montage = build_montages(faces, (96, 96), (5, 5))[0]

    # show the output montage
    if labelID == -1:
        title = "Unknown Fcaes"
    else:
        title = "Face ID #{}".format(labelID)
    plt.title(title)
    plt.imshow(montage)
    plt.show()

for i in range(0, number_of_clusters):
    id = []
    for j in range(0, len(cluster.labels_)):
        if i == cluster.labels_[j]:
            id.append(imagePaths[j][len(image_folder_path) + 1:])
            element = {"cluster_no": int(i), "elements": id}
    json_list.append(element)

print(json_list)
output_json = "clusters.json"
with open(output_json, 'w') as f:
    json.dump(json_list, f)
