sam-small / test_endpoint.py
Tony Neel
Add custom handler for SAM2
8ba5658
import requests
from pathlib import Path
from PIL import Image
import io
def get_stored_token():
"""Get the stored HuggingFace token"""
token_path = Path.home() / '.cache/huggingface/token'
if token_path.exists():
with open(token_path, 'r') as f:
return f.read().strip()
return None
# Update API URL to use the inference API endpoint
API_URL = "https://c3g262qlc7cizj5n.us-east4.gcp.endpoints.huggingface.cloud"
token = get_stored_token()
def query(image_path):
# Read image bytes directly
with open(image_path, "rb") as f:
image_bytes = f.read()
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "image/jpeg"
}
# Print some debug info
print(f"Sending file: {image_path}")
print(f"Content-Type: {headers['Content-Type']}")
print(f"Image size: {len(image_bytes)} bytes")
response = requests.post(
API_URL,
headers=headers,
data=image_bytes, # Send raw bytes
verify=True
)
# Add error handling
if response.status_code != 200:
print(f"Response headers: {response.headers}")
print(f"Request headers sent: {response.request.headers}")
return f"Error: {response.status_code}, {response.text}"
try:
return response.json()
except requests.exceptions.JSONDecodeError:
return f"Error decoding JSON. Raw response: {response.text}"
# Test with an image
if __name__ == "__main__":
# Option 1: Test with specific image
image_path = Path("images/20250121_gauge_0001.jpg")
# Option 2: Test with first image found in directory
# TRAIN_IMAGES_DIR = Path("images")
# image_path = next(TRAIN_IMAGES_DIR.glob('*.jpg'))
if not image_path.exists():
print(f"Error: Image not found at {image_path}")
exit(1)
print(f"Testing with image: {image_path}")
result = query(image_path)
print("\nAPI Response:")
print(result)