Spaces:
Sleeping
Sleeping
File size: 5,862 Bytes
2ca4976 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
"""
Simple API test script that extracts the numerical score
"""
import requests
import base64
import numpy as np
import cv2
from PIL import Image
import io
import re
def create_face_image():
"""Create a simple face-like image"""
img = np.zeros((100, 100), dtype=np.uint8)
# Face outline
cv2.ellipse(img, (50, 50), (40, 50), 0, 0, 360, 100, -1)
# Eyes
cv2.circle(img, (35, 40), 5, 200, -1)
cv2.circle(img, (65, 40), 5, 200, -1)
# Nose
cv2.line(img, (50, 45), (50, 60), 150, 2)
# Mouth
cv2.ellipse(img, (50, 70), (15, 8), 0, 0, 180, 150, 2)
# Convert to RGB
img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
return img_rgb
def test_api():
"""Test the API and extract the score"""
url = "https://pavaniyerra-hackthon4.hf.space/predict_similarity/"
print("Testing Face Similarity API")
print("=" * 40)
try:
# Create two test face images
face1 = create_face_image()
face2 = create_face_image()
# Convert to bytes
def img_to_bytes(img):
pil_img = Image.fromarray(img)
buffer = io.BytesIO()
pil_img.save(buffer, format='JPEG')
return buffer.getvalue()
face1_bytes = img_to_bytes(face1)
face2_bytes = img_to_bytes(face2)
# Prepare files for upload
files = {
'file1': ('face1.jpg', face1_bytes, 'image/jpeg'),
'file2': ('face2.jpg', face2_bytes, 'image/jpeg')
}
print("Sending request to API...")
response = requests.post(url, files=files, timeout=30)
print(f"Status Code: {response.status_code}")
if response.status_code == 200:
print("SUCCESS! API is working")
# Extract the dissimilarity score from HTML
html_content = response.text
# Look for the dissimilarity score in the HTML
# Pattern: "Dissimilarity: X.X"
pattern = r'Dissimilarity:</span>\s*<span[^>]*>\s*([0-9.]+)'
match = re.search(pattern, html_content)
if match:
score = float(match.group(1))
print(f"Dissimilarity Score: {score}")
# Convert dissimilarity to similarity (assuming 1.0 = completely different, 0.0 = identical)
similarity = 1.0 - score
print(f"Similarity Score: {similarity:.4f}")
# Interpret the result
if similarity > 0.8:
print("Result: Very High Similarity (likely same person)")
elif similarity > 0.6:
print("Result: High Similarity (possibly same person)")
elif similarity > 0.4:
print("Result: Moderate Similarity (uncertain)")
elif similarity > 0.2:
print("Result: Low Similarity (likely different persons)")
else:
print("Result: Very Low Similarity (definitely different persons)")
else:
print("WARNING: Could not extract score from HTML response")
print("HTML content preview:")
print(html_content[:500] + "..." if len(html_content) > 500 else html_content)
else:
print(f"ERROR: {response.status_code}")
print(f"Response: {response.text}")
except Exception as e:
print(f"ERROR: {e}")
def test_multiple_times():
"""Test the API multiple times to check consistency"""
print("\n" + "=" * 40)
print("Testing API Multiple Times")
print("=" * 40)
scores = []
for i in range(3):
print(f"\nTest {i+1}/3:")
try:
face1 = create_face_image()
face2 = create_face_image()
def img_to_bytes(img):
pil_img = Image.fromarray(img)
buffer = io.BytesIO()
pil_img.save(buffer, format='JPEG')
return buffer.getvalue()
files = {
'file1': ('face1.jpg', img_to_bytes(face1), 'image/jpeg'),
'file2': ('face2.jpg', img_to_bytes(face2), 'image/jpeg')
}
response = requests.post("https://pavaniyerra-hackthon4.hf.space/predict_similarity/",
files=files, timeout=30)
if response.status_code == 200:
# Extract score
pattern = r'Dissimilarity:</span>\s*<span[^>]*>\s*([0-9.]+)'
match = re.search(pattern, response.text)
if match:
score = float(match.group(1))
scores.append(score)
print(f" Score: {score}")
else:
print(" Could not extract score")
else:
print(f" Error: {response.status_code}")
except Exception as e:
print(f" Error: {e}")
if scores:
print(f"\nScore Statistics:")
print(f" Average: {sum(scores)/len(scores):.4f}")
print(f" Min: {min(scores):.4f}")
print(f" Max: {max(scores):.4f}")
print(f" Range: {max(scores) - min(scores):.4f}")
if __name__ == "__main__":
# Test the API
test_api()
# Test multiple times for consistency
test_multiple_times()
print("\n" + "=" * 50)
print("API Testing Complete!")
print("\nYour API is working correctly!")
print("The API expects:")
print("- Method: POST")
print("- Format: multipart/form-data")
print("- Parameters: file1, file2 (image files)")
print("- Response: HTML with dissimilarity score")
|