H4_New / app /Hackathon_setup /test_api_with_faces.py
PavaniYerra's picture
Face Recognition
2ca4976
"""
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")