dwancin commited on
Commit
0b59336
1 Parent(s): a5661ba

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +37 -66
  2. requirements.txt +2 -5
app.py CHANGED
@@ -1,84 +1,55 @@
1
  import os
2
- import numpy as np
3
- import pandas as pd
4
- from PIL import Image
5
- from huggingface_hub import HfFileSystem, hf_hub_download
6
- import face_recognition
7
  import gradio as gr
8
- from sklearn.metrics import euclidean_distances
 
9
 
10
  # Environment Variables
11
  HF_TOKEN = os.getenv("HF_TOKEN")
12
  HF_DATASET = os.getenv('HF_DATASET')
 
13
 
14
- # Hugging Face File System for authentication
15
- fs = HfFileSystem()
16
-
17
- # Load and prepare dataset
18
- def load_dataset():
19
- """Load dataset metadata and embeddings, converting embeddings to numpy arrays."""
20
- with fs.open(f'datasets/{HF_DATASET}/metadata.csv', revision='main', token=True) as f:
21
- df = pd.read_csv(f)
22
- df['embeddings'] = df['embeddings'].apply(lambda x: np.fromstring(x.strip('[]'), sep=','))
23
- return df
24
-
25
- df = load_dataset()
26
-
27
- # Function to fetch images with authentication
28
  def get_image_with_auth(file_name):
29
  """Retrieve an image using Hugging Face's hub with authentication."""
30
  image_path = hf_hub_download(repo_id=HF_DATASET, repo_type="dataset", filename=file_name, token=HF_TOKEN)
31
  return Image.open(image_path)
32
 
33
- # Utility function to load and process image
34
- def get_embedding(image):
35
- """Generate facial embeddings from an image using the face_recognition library."""
36
- encodings = face_recognition.face_encodings(np.array(image))
37
- return encodings[0] if encodings else None
 
 
38
 
39
- # Matching face using sklearn
40
- def find_matching_face(embedding, df):
41
- """Find the most similar face in the dataset using Euclidean distance."""
42
- embeddings_matrix = np.stack(df['embeddings'].values)
43
- distances = euclidean_distances([embedding], embeddings_matrix)[0]
44
- min_index = np.argmin(distances)
45
- return df.iloc[min_index], distances[min_index]
46
 
47
- # Determine the quality of the match
48
- def categorize_similarity(distance):
49
- """Categorize the similarity based on the Euclidean distance."""
50
- if distance < 0.3:
51
- return "Very High Match"
52
- elif distance < 0.5:
53
- return "High Match"
54
- elif distance < 0.7:
55
- return "Moderate Match"
56
- elif distance < 1.0:
57
- return "Low Match"
58
- else:
59
- return "Very Low Match"
60
 
61
- # Main function to process the face matching
62
- def recognize_face(input_image_path):
63
- """Process an uploaded image to find the most similar face in the dataset."""
64
- input_image = Image.open(input_image_path).convert('RGB')
65
- embedding = get_embedding(input_image)
66
- if embedding is None:
67
- return None, "No face detected."
68
- most_similar_face, distance = find_matching_face(embedding, df)
69
- match_quality = categorize_similarity(distance)
70
- similar_face_image_path = get_image_with_auth(most_similar_face['file_name'])
71
- info_message = f'''```yaml
72
- input:
73
- - image: "{input_image_path}"
74
- output:
75
- - name: "{most_similar_face['text']}"
76
- - quality: "{match_quality}"
77
- - distance: {100 * (1 - distance)}
78
- ```
79
- '''
80
- print(info_message)
81
- return similar_face_image_path, info_message
82
 
83
  def update(output_info):
84
  return gr.update(visible=True)
 
1
  import os
2
+ import sys
3
+ import json
4
+ import requests
 
 
5
  import gradio as gr
6
+ from huggingface_hub import HfFileSystem, hf_hub_download
7
+ from PIL import Image
8
 
9
  # Environment Variables
10
  HF_TOKEN = os.getenv("HF_TOKEN")
11
  HF_DATASET = os.getenv('HF_DATASET')
12
+ SPACE_SUBDOMAIN = os.environ['SPACE_SUBDOMAIN']
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def get_image_with_auth(file_name):
15
  """Retrieve an image using Hugging Face's hub with authentication."""
16
  image_path = hf_hub_download(repo_id=HF_DATASET, repo_type="dataset", filename=file_name, token=HF_TOKEN)
17
  return Image.open(image_path)
18
 
19
+ def recognize_face(image):
20
+ """
21
+ Function to send either an image URL to the FastAPI backend and receive results.
22
+ """
23
+
24
+ # Set the URL to your FastAPI endpoint
25
+ url = 'https://dwancin-face-match-api.hf.space/recognize/'
26
 
27
+ # Prepare the payload with the image data and specify the type
28
+ payload = {
29
+ "image": f"https://{SPACE_SUBDOMAIN}.hf.space/file={image}",
30
+ "type": "url"
31
+ }
 
 
32
 
33
+ print(payload)
34
+
35
+
36
+ # Send POST request to FastAPI server with the image data and type
37
+ response = requests.post(url, json=payload)
 
 
 
 
 
 
 
 
38
 
39
+ print(response)
40
+
41
+ # Process response
42
+ if response.status_code == 200:
43
+ response_data = response.json()
44
+ image_path = response_data.get('image')
45
+ if image_path:
46
+ image_file = get_image_with_auth(image_path)
47
+ formatted_json = json.dumps(response_data, indent=4)
48
+ return image_file, f"```json\n{formatted_json}\n```"
49
+ else:
50
+ return None, "No image path found in response."
51
+ else:
52
+ return None, f"Error: {response.status_code} - {response.text}"
 
 
 
 
 
 
 
53
 
54
  def update(output_info):
55
  return gr.update(visible=True)
requirements.txt CHANGED
@@ -1,6 +1,3 @@
1
  gradio
2
- face_recognition
3
- numpy
4
- pillow
5
- pandas
6
- scikit-learn
 
1
  gradio
2
+ huggingface_hub
3
+ pillow