Spaces:
Running
Running
| import requests | |
| import base64 | |
| from PIL import Image | |
| import io | |
| import json | |
| import sys | |
| def test_local_server(image_path=None): | |
| """ | |
| Test the local MCP server by sending a request to embed an image | |
| Args: | |
| image_path: Path to the image file. If None, a test URL will be used. | |
| """ | |
| # Local server URL (default Gradio port) | |
| server_url = "http://localhost:7860/mcp" | |
| if image_path: | |
| # Load the image | |
| try: | |
| with open(image_path, "rb") as f: | |
| image_data = f.read() | |
| # Encode the image as base64 | |
| image_base64 = base64.b64encode(image_data).decode("utf-8") | |
| # Prepare the MCP request with image data | |
| mcp_request = { | |
| "jsonrpc": "2.0", | |
| "method": "callTool", | |
| "params": { | |
| "name": "embed_image", | |
| "arguments": { | |
| "image_data": image_base64 | |
| } | |
| }, | |
| "id": 1 | |
| } | |
| except Exception as e: | |
| print(f"Error loading image: {str(e)}") | |
| return | |
| else: | |
| # Use a test image URL | |
| test_image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/bert-architects.png" | |
| print(f"Using test image URL: {test_image_url}") | |
| # Prepare the MCP request with image URL | |
| mcp_request = { | |
| "jsonrpc": "2.0", | |
| "method": "callTool", | |
| "params": { | |
| "name": "embed_image", | |
| "arguments": { | |
| "image_url": test_image_url | |
| } | |
| }, | |
| "id": 1 | |
| } | |
| print("Sending request to local MCP server...") | |
| try: | |
| # Send the request to the MCP server | |
| response = requests.post(server_url, json=mcp_request) | |
| # Check if the request was successful | |
| if response.status_code == 200: | |
| # Parse the response | |
| result = response.json() | |
| if "error" in result: | |
| print(f"Error from server: {result['error']['message']}") | |
| else: | |
| # Extract the embedding from the response | |
| content = result["result"]["content"][0]["text"] | |
| embedding_data = json.loads(content) | |
| print("β Test successful!") | |
| print(f"Embedding dimension: {embedding_data['dimension']}") | |
| print(f"First 10 values of embedding: {embedding_data['embedding'][:10]}...") | |
| else: | |
| print(f"β Error: HTTP {response.status_code}") | |
| print(response.text) | |
| except Exception as e: | |
| print(f"β Error connecting to server: {str(e)}") | |
| print("Make sure the server is running with 'python app.py'") | |
| if __name__ == "__main__": | |
| # Check if an image path was provided | |
| if len(sys.argv) > 1: | |
| image_path = sys.argv[1] | |
| print(f"Testing with image: {image_path}") | |
| test_local_server(image_path) | |
| else: | |
| print("No image path provided, using test URL") | |
| test_local_server() |