Spaces:
Runtime error
Runtime error
Download app.py from alwafi/faceproject: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/spaces/alwafi/faceproject/resolve/main/app.py
- Command line
-
hf download hf://spaces/alwafi/faceproject/app.py
-
curl -L -o app.py https://huggingface.co/spaces/alwafi/faceproject/resolve/main/app.py
2.45 kB
| from transformers import pipeline | |
| from PIL import Image, ImageDraw | |
| from sentence_transformers import SentenceTransformer, util | |
| import requests | |
| from io import BytesIO | |
| import gradio as gr | |
| # Inisialisasi model deteksi dan pengkodean | |
| checkpoint = "google/owlvit-base-patch32" | |
| detector = pipeline(model=checkpoint, task="zero-shot-object-detection") | |
| model = SentenceTransformer('clip-ViT-L-14') | |
| def load_image(url): | |
| response = requests.get(url) | |
| image = Image.open(BytesIO(response.content)).convert("RGB") | |
| return image | |
| def get_face_image(url): | |
| image = load_image(url) | |
| predictions = detector( | |
| image, | |
| candidate_labels=["human face"], | |
| ) | |
| max_score = 0 | |
| box_area = None | |
| for prediction in predictions: | |
| box = prediction["box"] | |
| label = prediction["label"] | |
| score = prediction["score"] | |
| if score > max_score: | |
| xmin, ymin, xmax, ymax = box.values() | |
| box_area = (xmin, ymin, xmax, ymax) | |
| max_score = score | |
| else: | |
| continue | |
| if box_area: | |
| draw = ImageDraw.Draw(image) | |
| draw.rectangle(box_area, outline="red", width=2) | |
| crop_img = image.crop(box_area) | |
| newsize = (256, 256) | |
| face_img = crop_img.resize(newsize) | |
| return face_img | |
| def predict(url1, url2, inp_sim): | |
| face_image1 = get_face_image(url1) | |
| face_image2 = get_face_image(url2) | |
| if face_image1 is not None and face_image2 is not None: | |
| img_emb = model.encode([face_image1, face_image2]) | |
| sim = util.cos_sim(img_emb[0], img_emb[1]) | |
| if sim > inp_sim: | |
| return sim.item(), "SAME" | |
| else: | |
| return sim.item(), "DIFFERENT" | |
| else: | |
| return 0, "No face detected in one or both images" | |
| description = "An application that can recognize if two faces belong to the same person or not" | |
| title = "Facial Identity Recognition System" | |
| interface = gr.Interface(fn=predict, | |
| inputs=[gr.Textbox(label="Image URL 1"), | |
| gr.Textbox(label="Image URL 2"), | |
| gr.Slider(0, 1, value=0.8, label="Similarity Percentage", info="Choose between 0 and 1")], | |
| outputs=[gr.Number(label="Similarity"), | |
| gr.Textbox(label="Message")], | |
| description=description, | |
| title=title) | |
| interface.launch(debug=True) | |