Valentin Peron commited on
Commit
7468932
·
1 Parent(s): 743fc77

feat(face_compare): Add face comparison functionality (NO FHE)

Browse files
__pycache__/face_compare.cpython-310.pyc ADDED
Binary file (1.32 kB). View file
 
face_compare.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from facenet_pytorch import MTCNN, InceptionResnetV1
2
+ import torchvision.transforms as transforms
3
+ from PIL import Image
4
+ import torch
5
+
6
+ mtcnn = MTCNN(keep_all=False, device='cpu')
7
+
8
+ model = InceptionResnetV1(pretrained='vggface2').eval()
9
+
10
+ def preprocess_face(base64_img):
11
+ img = Image.open(base64_img).convert('RGB')
12
+
13
+ preprocess = transforms.Compose([
14
+ transforms.Resize((160, 160)),
15
+ transforms.ToTensor(),
16
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
17
+ ])
18
+
19
+ # Detect face and get the bounding box
20
+ box, _ = mtcnn.detect(img)
21
+
22
+ if box is not None:
23
+ # Crop the image using the bounding box
24
+ img_cropped = img.crop(box[0]) # box[0] contains (x1, y1, x2, y2)
25
+
26
+ # Apply the rest of preprocessing (resize, tensor, normalize)
27
+ img_preprocessed = preprocess(img_cropped).unsqueeze(0)
28
+ return img_preprocessed
29
+ else:
30
+ print("No face detected")
31
+ return None
32
+
33
+ def compare_faces(base64_img1, base64_img2):
34
+ # Load and detect face, then crop the image
35
+
36
+ # Preprocess both images
37
+ img1 = preprocess_face(base64_img1) # Replace with your image path
38
+ img2 = preprocess_face(base64_img2) # Replace with your image path
39
+
40
+ # Check if faces were detected in both images
41
+ if img1 is not None and img2 is not None:
42
+ # Get the embeddings from the FaceNet model
43
+ with torch.no_grad():
44
+ emb1 = model(img1)
45
+ emb2 = model(img2)
46
+
47
+ # Calculate cosine similarity
48
+ cosine_similarity = torch.nn.functional.cosine_similarity(emb1, emb2)
49
+ return cosine_similarity.item()
50
+ else:
51
+ print("Face detection failed on one or both images.")
52
+ return None
main.py CHANGED
@@ -5,6 +5,15 @@ from fastapi.middleware.cors import CORSMiddleware
5
  import base64
6
  from pydantic import BaseModel
7
  import time
 
 
 
 
 
 
 
 
 
8
 
9
  app = FastAPI()
10
  router = APIRouter()
@@ -17,7 +26,7 @@ app.add_middleware(
17
  allow_headers=["*"],
18
  )
19
 
20
- pdf = 0
21
 
22
  class ImageData(BaseModel):
23
  image: str
@@ -37,16 +46,27 @@ async def verif() -> FileResponse:
37
  async def upload_pdf(data: ImageData):
38
  header, encoded = data.image.split(',', 1)
39
  binary_data = base64.b64decode(encoded)
40
- # Call
41
- pdf = binary_data;
42
- time.sleep(10)
43
  return {"message": "Image reçue et sauvegardée"}
44
 
45
  @router.post("/uploadids")
46
  async def upload_ids(data: ImagesData):
47
- # Call To The model
48
- return {"message": "Images reçues et sauvegardées"}
 
 
 
 
 
 
 
49
 
50
  app.include_router(router)
51
 
52
  app.mount("/", StaticFiles(directory="front/dist", html=True), name="static")
 
 
 
 
 
5
  import base64
6
  from pydantic import BaseModel
7
  import time
8
+ from facenet_pytorch import InceptionResnetV1, MTCNN
9
+ import warnings
10
+ import face_compare
11
+
12
+ warnings.filterwarnings('ignore', category=FutureWarning, module='facenet_pytorch')
13
+
14
+ mtcnn = MTCNN(keep_all=False, device='cpu')
15
+
16
+ model = InceptionResnetV1(pretrained='vggface2').eval()
17
 
18
  app = FastAPI()
19
  router = APIRouter()
 
26
  allow_headers=["*"],
27
  )
28
 
29
+ pdf = 0
30
 
31
  class ImageData(BaseModel):
32
  image: str
 
46
  async def upload_pdf(data: ImageData):
47
  header, encoded = data.image.split(',', 1)
48
  binary_data = base64.b64decode(encoded)
49
+
50
+ # Save the pdf
51
+ pdf = binary_data
52
  return {"message": "Image reçue et sauvegardée"}
53
 
54
  @router.post("/uploadids")
55
  async def upload_ids(data: ImagesData):
56
+ header, encoded1 = data.idCard.split(',', 1)
57
+ binary_data1 = base64.b64decode(encoded1)
58
+ header, encoded2 = data.profileImage.split(',', 1)
59
+ binary_data2 = base64.b64decode(encoded2)
60
+ output = face_compare.compare_faces(binary_data1, binary_data2)
61
+ if output > 0.6:
62
+ return {"message": "Les images correspondent"}
63
+ else:
64
+ return {"message": "Les images ne correspondent pas"}
65
 
66
  app.include_router(router)
67
 
68
  app.mount("/", StaticFiles(directory="front/dist", html=True), name="static")
69
+
70
+ if __name__ == "__main__":
71
+ import uvicorn
72
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt CHANGED
@@ -4,4 +4,4 @@ sentencepiece==0.1.*
4
  torch==1.11.*
5
  transformers==4.*
6
  uvicorn[standard]==0.17.*
7
- numpy<2.0
 
4
  torch==1.11.*
5
  transformers==4.*
6
  uvicorn[standard]==0.17.*
7
+ numpy<2.0