Spaces:
Sleeping
Sleeping
File size: 8,329 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | """
Test script for the Hugging Face API using face images
"""
import requests
import base64
import numpy as np
import cv2
from PIL import Image
import io
import os
def create_face_like_image():
"""Create a more realistic face-like image for testing"""
# Create a grayscale image that looks more like a face
img = np.zeros((100, 100), dtype=np.uint8)
# Add some face-like features
# Face outline (oval)
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 3-channel for consistency
img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
return img_rgb
def load_real_face_image(image_path):
"""Load a real face image if available"""
if os.path.exists(image_path):
try:
img = cv2.imread(image_path)
if img is not None:
# Resize to 100x100
img = cv2.resize(img, (100, 100))
return img
except Exception as e:
print(f"Error loading image {image_path}: {e}")
return None
def image_to_base64(img):
"""Convert image to base64 string"""
if len(img.shape) == 2: # Grayscale
pil_img = Image.fromarray(img, mode='L')
else: # RGB
pil_img = Image.fromarray(img)
buffer = io.BytesIO()
pil_img.save(buffer, format='JPEG')
img_str = base64.b64encode(buffer.getvalue()).decode()
return img_str
def test_api_with_face_images():
"""Test the API with face-like images"""
url = "https://pavaniyerra-hackthon4.hf.space/predict_similarity/"
print("Testing API with face-like images...")
print("=" * 50)
try:
# Create two face-like images
face1 = create_face_like_image()
face2 = create_face_like_image()
# Convert to base64
face1_b64 = image_to_base64(face1)
face2_b64 = image_to_base64(face2)
print("Created face-like test images")
print(f"Image 1 shape: {face1.shape}")
print(f"Image 2 shape: {face2.shape}")
# Try different request formats
test_formats = [
# Format 1: JSON with file1, file2
{"file1": face1_b64, "file2": face2_b64},
# Format 2: JSON with img1, img2
{"img1": face1_b64, "img2": face2_b64},
# Format 3: JSON with image1, image2
{"image1": face1_b64, "image2": face2_b64},
# Format 4: JSON with faces array
{"faces": [face1_b64, face2_b64]},
# Format 5: JSON with data wrapper
{"data": {"file1": face1_b64, "file2": face2_b64}}
]
for i, data in enumerate(test_formats, 1):
print(f"\n--- Testing Format {i}: {list(data.keys())} ---")
try:
response = requests.post(url, json=data, timeout=30)
print(f"Status Code: {response.status_code}")
if response.status_code == 200:
try:
result = response.json()
print("SUCCESS! API Response:")
print(f"Similarity Score: {result}")
# Interpret the result
if isinstance(result, (int, float)):
if result > 0.8:
print("Result: Very High Similarity (likely same person)")
elif result > 0.6:
print("Result: High Similarity (possibly same person)")
elif result > 0.4:
print("Result: Moderate Similarity (uncertain)")
elif result > 0.2:
print("Result: Low Similarity (likely different persons)")
else:
print("Result: Very Low Similarity (definitely different persons)")
else:
print(f"Response format: {type(result)} - {result}")
return True # Success, no need to try other formats
except Exception as e:
print(f"Error parsing JSON response: {e}")
print(f"Raw response: {response.text}")
else:
print(f"Error: {response.text[:200]}...")
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")
except Exception as e:
print(f"Error: {e}")
print("\nAll JSON formats failed. Trying form data...")
# Try form data approach
try:
face1_bytes = base64.b64decode(face1_b64)
face2_bytes = base64.b64decode(face2_b64)
files = {
'file1': ('face1.jpg', face1_bytes, 'image/jpeg'),
'file2': ('face2.jpg', face2_bytes, 'image/jpeg')
}
response = requests.post(url, files=files, timeout=30)
print(f"Form data Status: {response.status_code}")
print(f"Form data Response: {response.text}")
except Exception as e:
print(f"Form data error: {e}")
except Exception as e:
print(f"General error: {e}")
return False
def test_with_real_images():
"""Test with real face images if available"""
print("\nTesting with real face images...")
print("=" * 40)
# Look for common face image files
possible_files = [
"face1.jpg", "face2.jpg", "person1.jpg", "person2.jpg",
"test_face1.jpg", "test_face2.jpg", "sample1.jpg", "sample2.jpg"
]
found_images = []
for filename in possible_files:
if os.path.exists(filename):
found_images.append(filename)
print(f"Found: {filename}")
if len(found_images) >= 2:
try:
# Load the first two images
img1 = load_real_face_image(found_images[0])
img2 = load_real_face_image(found_images[1])
if img1 is not None and img2 is not None:
print(f"Loaded real images: {found_images[0]}, {found_images[1]}")
# Convert to base64
img1_b64 = image_to_base64(img1)
img2_b64 = image_to_base64(img2)
# Test with real images
url = "https://pavaniyerra-hackthon4.hf.space/predict_similarity/"
data = {"file1": img1_b64, "file2": img2_b64}
response = requests.post(url, json=data, timeout=30)
print(f"Real images test - Status: {response.status_code}")
if response.status_code == 200:
result = response.json()
print(f"SUCCESS with real images! Similarity: {result}")
else:
print(f"Error with real images: {response.text}")
else:
print("Could not load real images properly")
except Exception as e:
print(f"Error testing with real images: {e}")
else:
print("No real face images found for testing")
print("Place some face images in the current directory to test with real data")
if __name__ == "__main__":
print("Hugging Face API Test - Face Images")
print("=" * 60)
print(f"API URL: https://pavaniyerra-hackthon4.hf.space/predict_similarity/")
print()
# Test with face-like images
success = test_api_with_face_images()
# Test with real images if available
test_with_real_images()
print("\n" + "=" * 60)
print("Face API Testing Complete!")
print("\nTo test with real face images:")
print("1. Place face images in the current directory")
print("2. Name them face1.jpg, face2.jpg, etc.")
print("3. Run this script again")
|