Actionsync / test_hf_space.py
barathvasan-dev
Fix: Parse HF Space detection response format correctly - handle single detection object not array
f9c9a7c
Raw
History Blame Contribute Delete
2.51 kB
#!/usr/bin/env python
"""Test HuggingFace Space API directly"""
import sys
import json
import tempfile
from PIL import Image
try:
from gradio_client import Client, handle_file
except ImportError:
print("❌ gradio_client not installed")
sys.exit(1)
try:
# Test image path
test_image_path = r"C:\Users\barat\OneDrive\Desktop\test_image.jpg"
print(f"Loading test image: {test_image_path}")
image = Image.open(test_image_path)
print(f"βœ… Image loaded: {image.size}")
# Connect to HF Space
HF_SPACE_ID = "BARATH0070/plate-detector"
print(f"\nπŸ”Œ Connecting to HF Space: {HF_SPACE_ID}")
client = Client(HF_SPACE_ID)
print("βœ… Connected to HF Space")
# View the API
print("\nπŸ“‹ Checking available endpoints...")
try:
info = client.view_api()
print("Available API endpoints:")
print(json.dumps(info, indent=2, default=str))
except Exception as e:
print(f"⚠️ Could not view API: {e}")
# Save image to temp file
print("\nπŸ“Έ Saving image to temp file...")
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
image.save(tmp.name)
tmp_path = tmp.name
print(f"βœ… Temp file: {tmp_path}")
# Try to call the API
print("\nπŸš€ Calling HF Space API...")
image_input = handle_file(tmp_path)
print(f"βœ… Image input prepared: {image_input}")
# Try different endpoint names
endpoints = [
"/detect_and_save",
"/predict_0",
"/predict",
"/run",
]
for endpoint in endpoints:
try:
print(f"\n Trying endpoint: {endpoint}")
result = client.predict(image_input, api_name=endpoint)
print(f" βœ… Success! Result type: {type(result)}")
print(f" Result: {result}")
# Try to parse as JSON if it's a string
if isinstance(result, (list, tuple)):
print(f" Result length: {len(result)}")
for i, item in enumerate(result):
print(f" [{i}] type={type(item).__name__}, value={item}")
break
except Exception as e:
print(f" ⚠️ Failed: {e}")
# Cleanup
import os
if os.path.exists(tmp_path):
os.remove(tmp_path)
print(f"\nβœ… Cleaned up temp file")
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()